├── .editorconfig ├── .github └── workflows │ └── ci.yml ├── .phpcs.xml ├── CONTRIBUTORS.md ├── Command └── SshCommand.php ├── Controller └── AuthController.php ├── DependencyInjection ├── Configuration.php └── ToolforgeExtension.php ├── LICENSE.txt ├── Logger └── WebRequestProcessor.php ├── README.md ├── Resources ├── assets │ ├── jquery.i18n.min.js │ ├── toolforge.js │ └── wikimedia-base.less ├── config │ ├── routes.yaml │ └── services.yaml ├── i18n │ ├── de.json │ ├── en.json │ └── qqq.json ├── phpcs │ └── ruleset.xml └── templates │ └── i18n.html.twig ├── Service ├── Intuition.php ├── NativeSessionStorage.php ├── ReplicasClient.php └── Util.php ├── Tests ├── Service │ └── ReplicasClientTest.php └── Twig │ └── ExtensionTest.php ├── ToolforgeBundle.php ├── Twig └── Extension.php └── bin └── deploy.sh /.editorconfig: -------------------------------------------------------------------------------- 1 | # https://EditorConfig.org 2 | 3 | # Unix-style newlines with a newline ending every file 4 | [*] 5 | end_of_line = lf 6 | insert_final_newline = true 7 | trim_trailing_whitespace = true 8 | 9 | # tab indentation 10 | [*.{php,js,less,twig}] 11 | indent_style = space 12 | indent_size = 4 13 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - '**' 10 | 11 | jobs: 12 | build: 13 | 14 | strategy: 15 | matrix: 16 | php: [ '8.0', '8.1', '8.2', '8.3' ] 17 | 18 | runs-on: ubuntu-latest 19 | 20 | steps: 21 | - name: Checkout 22 | uses: actions/checkout@v4 23 | 24 | - name: ShellCheck 25 | uses: ludeeus/action-shellcheck@master 26 | with: 27 | scandir: './bin' 28 | 29 | - name: Set up PHP 30 | uses: shivammathur/setup-php@v2 31 | with: 32 | php-version: ${{matrix.php}} 33 | 34 | - name: Test 35 | run: | 36 | composer install 37 | composer test 38 | -------------------------------------------------------------------------------- /.phpcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | . 5 | vendor/ 6 | node_modules/ 7 | *.min.js 8 | 9 | -------------------------------------------------------------------------------- /CONTRIBUTORS.md: -------------------------------------------------------------------------------- 1 | Contributors 2 | ============ 3 | 4 | This file contains information for people wanting to contribute to the Toolforge Bundle. 5 | For general usage documentation, see the [README](README.md). 6 | 7 | ## Project setup 8 | 9 | For most development, you need to work on the bundle within an actual Symfony application; here we call this the 'host' application. 10 | This can be set up with a command such as `symfony new ProjectName`, which will install the host application to the `ProjectName/` directory. 11 | We suggest cloning ToolforgeBundle to an adjacent location to this (`git clone https://github.com/wikimedia/ToolforgeBundle.git`). 12 | 13 | Then you need to set up the host application's Composer file to include the ToolforgeBundle. 14 | Do this by first adding the following to its `composer.json` (replacing the path to `ToolforgeBundle/` to match what is correct for your setup): 15 | 16 | "repositories": [{ 17 | "type": "path", 18 | "url": "../ToolforgeBundle/", 19 | "options": { 20 | "symlink": true 21 | } 22 | }], 23 | 24 | Then run `composer require wikimedia/toolforge-bundle @dev`, 25 | which will create a symlink in the host application's `vendor/wikimedia/` directory. 26 | 27 | It is now possible to work on the files in the bundle and use them in the host application. 28 | -------------------------------------------------------------------------------- /Command/SshCommand.php: -------------------------------------------------------------------------------- 1 | client = $client; 38 | parent::__construct('toolforge:ssh'); 39 | } 40 | 41 | /** 42 | * Configuration for the SshCommand. 43 | */ 44 | protected function configure(): void 45 | { 46 | $this->setDescription('Create an SSH tunnel to the Toolforge replicas.'); 47 | $this->setHelp('Note you must already have added your SSH key to the ssh-agent before running this.'); 48 | $this->addArgument( 49 | 'username', 50 | InputArgument::OPTIONAL, 51 | 'Your Toolforge UNIX shell username, if different than your local username.' 52 | ); 53 | $this->addOption( 54 | 'service', 55 | null, 56 | InputOption::VALUE_OPTIONAL, 57 | "Service to use. Either 'web' (default) or 'analytics'", 58 | 'web' 59 | ); 60 | $this->addOption( 61 | 'bind-address', 62 | 'b', 63 | InputOption::VALUE_REQUIRED, 64 | "Sets the binding address of the SSH tunnel. For Docker installations you may need to set this to 0.0.0.0" 65 | ); 66 | $this->addOption( 67 | 'toolsdb', 68 | null, 69 | InputOption::VALUE_NONE, 70 | 'Sets up an SSH tunnel to tools.db.svc.wikimedia.cloud' 71 | ); 72 | $this->addOption( 73 | 'trove', 74 | null, 75 | InputOption::VALUE_REQUIRED, 76 | 'Sets up an SSH tunnel to a Trove database. Provide the hostname of the Trove database to connect to.' 77 | ); 78 | } 79 | 80 | /** 81 | * Create the SSH tunnel and wait until the process is manually killed. 82 | * @param InputInterface $input 83 | * @param OutputInterface $output 84 | * @returns int 85 | */ 86 | protected function execute(InputInterface $input, OutputInterface $output): int 87 | { 88 | $username = $input->getArgument('username'); 89 | $service = $input->getOption('service'); 90 | $bindAddress = $input->getOption('bind-address'); 91 | $toolsDb = $input->getOption('toolsdb'); 92 | $trove = $input->getOption('trove'); 93 | $host = "$service".self::HOST_SUFFIX; 94 | $login = $username ? $username.'@'.self::LOGIN_URL : self::LOGIN_URL; 95 | 96 | $toolsDbStr = $toolsDb ? ' and tools'.self::HOST_SUFFIX : ''; 97 | $output->writeln("Connecting to *.$host$toolsDbStr via $login... use ^C to cancel or terminate connection."); 98 | 99 | $slices = array_unique(array_values($this->client->getDbList())); 100 | $processArgs = ['ssh', '-N']; 101 | 102 | if ($output->isVerbose()) { 103 | $processArgs[] = '-v'; 104 | } elseif ($output->isVeryVerbose()) { 105 | $processArgs[] = '-vv'; 106 | } elseif ($output->isDebug()) { 107 | $processArgs[] = '-vvv'; 108 | } 109 | 110 | foreach ($slices as $slice) { 111 | $processArgs[] = '-L'; 112 | $arg = $this->client->getPortForSlice($slice).":$slice.$host:3306"; 113 | if ($bindAddress) { 114 | $arg = $bindAddress.':'.$arg; 115 | } 116 | $processArgs[] = $arg; 117 | } 118 | if ($toolsDb) { 119 | $processArgs[] = '-L'; 120 | $port = $this->client->getPortForSlice('toolsdb'); 121 | $arg = $port.':tools'.self::HOST_SUFFIX.':3306'; 122 | if ($bindAddress) { 123 | $arg = $bindAddress.':'.$arg; 124 | } 125 | $processArgs[] = $arg; 126 | } 127 | if ($trove) { 128 | $processArgs[] = '-L'; 129 | $port = $this->client->getPortForSlice('trove'); 130 | $arg = "$port:$trove:3306"; 131 | if ($bindAddress) { 132 | $arg = $bindAddress.':'.$arg; 133 | } 134 | $processArgs[] = $arg; 135 | } 136 | $processArgs[] = $login; 137 | 138 | $process = Process::fromShellCommandline(implode(' ', $processArgs)); 139 | $process->setTimeout(null); // Never time out 140 | $process->start(); 141 | 142 | $process->wait(function ($type, $buffer) use ($output): void { 143 | if (Process::ERR === $type) { 144 | $output->writeln(''.trim($buffer).''); 145 | } else { 146 | $output->writeln($buffer); 147 | } 148 | }); 149 | 150 | return Command::SUCCESS; 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /Controller/AuthController.php: -------------------------------------------------------------------------------- 1 | getParameter('toolforge.oauth.logged_in_user'); 27 | if ($loggedInUser) { 28 | $this->get('session')->set('logged_in_user', (object)[ 29 | 'username' => $loggedInUser, 30 | ]); 31 | return $this->redirectToRoute('home'); 32 | } 33 | 34 | // Set the callback URL if given and if it matches the required prefix. If there's no 35 | // prefix registered with the consumer then we can't supply our own callback. 36 | // The prefixed callback is used to redirect back to target page after logging in. 37 | $callback = $request->query->get('callback', ''); 38 | $callbackPrefix = $this->generateUrl('toolforge_oauth_callback', [], UrlGeneratorInterface::ABSOLUTE_URL); 39 | $isPrefix = substr($callback, 0, strlen($callbackPrefix)) === $callbackPrefix; 40 | if ($callback && $isPrefix) { 41 | $oauthClient->setCallback($request->query->get('callback')); 42 | } 43 | 44 | // Continue with OAuth authentication. 45 | [$next, $token] = $oauthClient->initiate(); 46 | 47 | // Save the request token to the session. 48 | $session->set('oauth.request_token', $token); 49 | 50 | // Send the user to Meta Wiki. 51 | return new RedirectResponse($next); 52 | } 53 | 54 | /** 55 | * Receive authentication credentials back from the OAuth wiki. 56 | * @param Request $request The HTTP request. 57 | * @return RedirectResponse 58 | */ 59 | #[Route("/oauth_callback", name:"toolforge_oauth_callback")] 60 | public function oauthCallbackAction(Request $request, Session $session, Client $client): RedirectResponse 61 | { 62 | // Give up if the required GET params or stored request token don't exist. 63 | if (!$request->get('oauth_verifier')) { 64 | throw $this->createNotFoundException('No OAuth verifier given.'); 65 | } 66 | if (!$session->has('oauth.request_token')) { 67 | throw $this->createNotFoundException('No request token found. Please try logging in again.'); 68 | } 69 | 70 | // Complete authentication. 71 | $token = $session->get('oauth.request_token'); 72 | $verifier = $request->get('oauth_verifier'); 73 | $accessToken = $client->complete($token, $verifier); 74 | 75 | // Store access token, and remove request token. 76 | $session->set('oauth.access_token', $accessToken); 77 | $session->remove('oauth.request_token'); 78 | 79 | // Regenerate session ID. 80 | $session->migrate(); 81 | 82 | // Store user identity. 83 | $ident = $client->identify($accessToken); 84 | $session->set('logged_in_user', $ident); 85 | 86 | // Redirect to callback, if given. 87 | if ($request->query->get('redirect')) { 88 | return $this->redirect($request->query->get('redirect')); 89 | } 90 | 91 | // Otherwise send to homepage. 92 | return $this->redirectToRoute('home'); 93 | } 94 | 95 | /** 96 | * Log out the user and return to the homepage. 97 | * @return RedirectResponse 98 | */ 99 | #[Route("/logout", name:"toolforge_logout")] 100 | public function logoutAction(Session $session): RedirectResponse 101 | { 102 | $session->invalidate(); 103 | return $this->redirectToRoute('home'); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /DependencyInjection/Configuration.php: -------------------------------------------------------------------------------- 1 | getRootNode() 20 | ->children() 21 | ->arrayNode('oauth') 22 | ->addDefaultsIfNotSet() 23 | ->children() 24 | ->scalarNode('url') 25 | ->defaultValue('https://meta.wikimedia.org/w/index.php?title=Special:OAuth') 26 | ->end() 27 | ->scalarNode('consumer_key')->defaultValue('')->end() 28 | ->scalarNode('consumer_secret')->defaultValue('')->end() 29 | ->scalarNode('logged_in_user')->defaultValue('')->end() 30 | ->scalarNode('redirect_to')->defaultValue('/')->end() 31 | ->end() 32 | ->end() 33 | ->arrayNode('intuition') 34 | ->addDefaultsIfNotSet() 35 | ->children() 36 | ->scalarNode('domain')->defaultValue('')->end() 37 | ->end() 38 | ->end() 39 | ->end(); 40 | return $builder; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /DependencyInjection/ToolforgeExtension.php: -------------------------------------------------------------------------------- 1 | processConfiguration($configuration, $configs); 25 | $container->setParameter('toolforge.oauth.url', $config['oauth']['url']); 26 | $container->setParameter('toolforge.oauth.consumer_key', $config['oauth']['consumer_key']); 27 | $container->setParameter('toolforge.oauth.consumer_secret', $config['oauth']['consumer_secret']); 28 | $container->setParameter('toolforge.oauth.logged_in_user', $config['oauth']['logged_in_user']); 29 | $container->setParameter('toolforge.intuition.domain', $config['intuition']['domain']); 30 | 31 | // Load services. 32 | $configDir = dirname(__DIR__).'/Resources/config'; 33 | $loader = new YamlFileLoader($container, new FileLocator($configDir)); 34 | $loader->load('services.yaml'); 35 | } 36 | 37 | /** 38 | * Allow an extension to prepend the extension configurations. 39 | * @param ContainerBuilder $container 40 | */ 41 | public function prepend(ContainerBuilder $container): void 42 | { 43 | // Add the bundle's templates directory to Twig. 44 | $container->prependExtensionConfig('twig', [ 45 | 'paths' => [ 46 | dirname(__DIR__).'/Resources/templates' => 'toolforge', 47 | ], 48 | ]); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Logger/WebRequestProcessor.php: -------------------------------------------------------------------------------- 1 | requestStack = $requestStack; 21 | } 22 | 23 | /** 24 | * Adds extra information to the log entry. 25 | * @see https://symfony.com/doc/current/logging/processors.html 26 | * @param mixed[]|LogRecord $record 27 | * @return mixed[]|LogRecord 28 | */ 29 | public function __invoke(mixed $record): mixed 30 | { 31 | $request = $this->requestStack->getCurrentRequest(); 32 | 33 | if ($request) { 34 | if ($record instanceof LogRecord) { 35 | $record->offsetSet('extra', [ 36 | 'host' => $request->getHost(), 37 | 'uri' => $request->getUri(), 38 | ]); 39 | } else { 40 | $record['extra']['host'] = $request->getHost(); 41 | $record['extra']['uri'] = $request->getUri(); 42 | } 43 | } 44 | 45 | return $record; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Toolforge Bundle 2 | ================ 3 | 4 | A Symfony 5/6/7 bundle that provides some common parts of web-based tools in Wikimedia Toolforge. 5 | 6 | Features: 7 | 8 | * OAuth user authentication against [Meta Wiki](https://meta.wikimedia.org/). 9 | * Internationalization with the [Intuition](https://intuition.toolforge.org/) and jQuery.i18n libraries. 10 | * Interface to connect and query the [replica databases](https://wikitech.wikimedia.org/wiki/Wiki_replicas) 11 | * PHP Code Sniffer ruleset 12 | * Base Wikimedia UI stylesheet (LESS) 13 | 14 | Still to come: 15 | 16 | * Universal Language Selector (ULS) 17 | * Localizable routes 18 | * OOUI 19 | * CSSJanus 20 | * Addwiki 21 | * Critical error reporting to tool maintainers' email 22 | 23 | [![Packagist](https://img.shields.io/packagist/v/wikimedia/toolforge-bundle.svg)](https://packagist.org/packages/wikimedia/toolforge-bundle) 24 | [![License](https://img.shields.io/github/license/wikimedia/ToolforgeBundle.svg)](https://www.gnu.org/licenses/gpl-3.0) 25 | [![GitHub issues](https://img.shields.io/github/issues/wikimedia/ToolforgeBundle.svg)](https://github.com/wikimedia/ToolforgeBundle/issues) 26 | [![Build Status](https://github.com/wikimedia/ToolforgeBundle/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/wikimedia/ToolforgeBundle/actions/workflows/ci.yml?query=branch%3Amaster) 27 | 28 | Please report all issues either on [Github](https://github.com/wikimedia/ToolforgeBundle/issues) 29 | or on [Phabricator](https://phabricator.wikimedia.org/tag/community-tech) (tagged with `community-tech`). 30 | 31 | ## Table of Contents 32 | 33 | * [Installation](#installation) 34 | * [Configuration](#configuration) 35 | * [OAuth](#oauth) 36 | * [Internationalization (Intuition and jQuery.i18n)](#internationalization-intuition-and-jqueryi18n) 37 | * [Replicas connection manager](#replicas-connection-manager) 38 | * [PHP Code Sniffer](#php-code-sniffer) 39 | * [Wikimedia UI styles](#wikimedia-ui-styles) 40 | * [Deployment script](#deployment-script) 41 | * [Sessions](#sessions) 42 | * [Examples](#examples) 43 | * [License](#license) 44 | 45 | ## Installation 46 | 47 | ### New project 48 | 49 | To get a new project up and running quickly 50 | first make sure you've got [Composer](https://getcomposer.org) and the [Symfony CLI](https://symfony.com/download) installed 51 | and then use the [Toolforge Skeleton](https://packagist.org/packages/wikimedia/toolforge-skeleton): 52 | 53 | composer create-project wikimedia/toolforge-skeleton ./my-cool-tool 54 | cd my-cool-tool 55 | symfony server:start -d 56 | 57 | Navigate to http://localhost:8000 and you should see your new tool up and running. 58 | 59 | ### Existing project 60 | 61 | Install the code in an existing Symfony project: 62 | 63 | composer require wikimedia/toolforge-bundle 64 | 65 | Register the bundle in your `AppKernel`: 66 | 67 | class AppKernel extends Kernel { 68 | public function registerBundles() { 69 | $bundles = [ 70 | new Wikimedia\ToolforgeBundle\ToolforgeBundle(), 71 | ]; 72 | return $bundles; 73 | } 74 | } 75 | 76 | Or `config/bundles.php` 77 | 78 | Wikimedia\ToolforgeBundle\ToolforgeBundle::class => ['dev' => true], 79 | 80 | ## Configuration 81 | 82 | ### OAuth 83 | 84 | The bundle creates three new routes `/login`, `/oauth_callback`, and `/logout`. 85 | Your application should have a route called `home`. 86 | You need to register these with your application 87 | by adding the following to your `config/routes.yaml` file (or equivalent): 88 | 89 | toolforge: 90 | resource: '@ToolforgeBundle/Resources/config/routes.yaml' 91 | 92 | To configure OAuth, first 93 | [apply for an OAuth consumer](https://meta.wikimedia.org/wiki/Special:OAuthConsumerRegistration/propose) 94 | on Meta Wiki with a callback URL of `/oauth_callback` 95 | and add the consumer key and secret to your `.env` file. 96 | Then connect these to your application's config with the following in `config/packages/toolforge.yaml`: 97 | 98 | toolforge: 99 | oauth: 100 | consumer_key: '%env(OAUTH_KEY)%' 101 | consumer_secret: '%env(OAUTH_SECRET)%' 102 | 103 | If you need to authenticate to a different wiki, 104 | you can also set the `toolforge.oauth.url` parameter 105 | to the full URL to `Special:OAuth`. 106 | 107 | Add a login link to the relevant Twig template (often `base.html.twig`), e.g.: 108 | 109 | {% if logged_in_user() %} 110 | {{ msg( 'toolforge-logged-in-as', [ logged_in_user().username ] ) }} 111 | {{ msg('toolforge-logout') }} 112 | {% else %} 113 | {{ msg('toolforge-login') }} 114 | {% endif %} 115 | 116 | The internationalization parts of this are explained below. 117 | The OAuth-specific part is the `logged_in_user()`, 118 | which is a bungle-provided Twig function 119 | that gives you access to the currently logged-in user. 120 | 121 | While in development, it can be useful to not have to log your user in all the time. 122 | To force login of a particular user (but note that you still have to click the 'login' link), 123 | add a `logged_in_user` key to your `config/packages/toolforge.yml` file, e.g.: 124 | 125 | toolforge: 126 | oauth: 127 | logged_in_user: '%env(LOGGED_IN_USER)%' 128 | 129 | In controllers, you can test whether the user is logged in by checking: 130 | 131 | $this->get('session')->get('logged_in_user') 132 | 133 | #### Redirecting after login 134 | 135 | After the user logs in, you may want to redirect them back to the page they originally tried to 136 | view, instead of the `home` route. To do this, first make sure you registered your OAuth consumer 137 | to accept a callback URL using the "Allow consumer to specify a callback..." option. The value for 138 | the callback would for example be `https://my-tool.toolforge.org/oauth_callback`. 139 | 140 | The implementation in your views is best explained by example. Let's assume the current page 141 | the user sees shows a login link, and you want to redirect them back to the same page after 142 | they authenticate. The code in your Twig template should look something like: 143 | 144 | Login 145 | 146 | Here `app.request.uri` evaluates to the current URL the user is viewing. It is provided as the 147 | `redirect` for the `oauth_callback` route, which is provided as the `callback` for the `login` route. 148 | The URL for the login link ends up being something like: 149 | 150 | https://my-tool.toolforge.org/login?callback=https%3A//my-tool.toolforge.org/oauth_callback%3Fredirect%3Dhttps%253A//my-tool.toolforge.org/my-page%253Ffoo%253Dbar 151 | 152 | Note the double-encoding of the URL used for the value of `redirect`. In this example the user will 153 | ultimately be redirected back to `https://my-tool.toolforge.org/my-page?foo=bar`. 154 | 155 | ### Internationalization (Intuition and jQuery.i18n) 156 | 157 | Internationalization is handled similarly to how it is done in MediaWiki, 158 | with translated strings being stored in `i18n/` directories. 159 | The bundle comes with some strings of its own, all prefixed with `toolforge_`; 160 | it is recommended that these are used where possible because it reduces the work for translators. 161 | 162 | #### 1. PHP 163 | 164 | In PHP, set your application's i18n 'domain' with the following in `config/packages/toolforge.yaml`: 165 | 166 | toolforge: 167 | intuition: 168 | domain: 'app-name-here' 169 | 170 | You can inject (the bundle's subclass of) Intuition into your controllers via type hinting, e.g.: 171 | 172 | public function indexAction( Request $request, \Wikimedia\ToolforgeBundle\Service\Intuition $intuition ) { /*...*/ } 173 | 174 | The following Twig functions and filters are available: 175 | 176 | * `msg( msg, params )` *string* Get a single message. 177 | * `bdi( text )` *string* Wrap a string with tags for bidirectional isolation 178 | * `msg_exists( msg )` *bool* Check to see if a given message exists. 179 | * `msg_if_exists( msg, params )` *string* Get a message if it exists, or else return the provided string. 180 | * `lang( lang )` *string* The code of the current or given language. 181 | * `lang_name( lang )` *string* The name of the current or given language. 182 | * `all_langs()` *string[]* List of all languages defined in JSON files in the `i18n/` directory (code => name). 183 | * `is_rtl()` *bool* Whether the current language is right-to-left. 184 | * `git_tag()` *string* The current Git tag, or the short hash if there are no tags. 185 | * `git_branch()` *string* The current Git branch. 186 | * `git_hash()` *string* The current Git hash. 187 | * `git_hash_short()` *string* The short version of the current Git hash. 188 | * `|num_format` *int|float* Format a number according to the current Locale. 189 | * `|list_format` *string[]* Format an array of strings as a separated inline-list. In English this is comma-separate with 'and' before the last item. 190 | 191 | #### 2. Javascript 192 | 193 | In Javascript, you need to do three things to enable internationalisation: 194 | 195 | 1. Add the following to your main JS file (e.g. `app.js`) or `webpack.config.js`: 196 | 197 | require('../vendor/wikimedia/toolforge-bundle/Resources/assets/toolforge.js'); 198 | 199 | 2. This to your HTML template (before your `app.js`): 200 | 201 | 202 | {% include '@toolforge/i18n.html.twig' %} 203 | 204 | (The jQuery can be left out if you're already loading that through other means.) 205 | 206 | 3. And symlink your `i18n/` directory from `public/i18n/`, 207 | so that the language files can be loaded by from Javascript. 208 | 209 | Then you can get i18n messages anywhere with: `$.i18n( 'msg-name', paramOne, paramTwo )` 210 | 211 | ### Replicas connection manager 212 | 213 | If your tool connects to multiple databases on the 214 | [Toolforge replicas](https://wikitech.wikimedia.org/wiki/Help:Toolforge/Database), 215 | you can take advantage of ToolforgeBundle's `ReplicasClient` service to ensure your application 216 | opens no more connections than it needs to. 217 | 218 | For this to work, you first need to add the following to your `config/packages/doctrine.yaml`: 219 | 220 |
221 | doctrine.yaml 222 | 223 | ``` 224 | doctrine: 225 | dbal: 226 | connections: 227 | toolforge_s1: 228 | host: '%env(REPLICAS_HOST_S1)%' 229 | port: '%env(REPLICAS_PORT_S1)%' 230 | user: '%env(REPLICAS_USERNAME)%' 231 | password: '%env(REPLICAS_PASSWORD)%' 232 | toolforge_s2: 233 | host: '%env(REPLICAS_HOST_S2)%' 234 | port: '%env(REPLICAS_PORT_S2)%' 235 | user: '%env(REPLICAS_USERNAME)%' 236 | password: '%env(REPLICAS_PASSWORD)%' 237 | toolforge_s3: 238 | host: '%env(REPLICAS_HOST_S3)%' 239 | port: '%env(REPLICAS_PORT_S3)%' 240 | user: '%env(REPLICAS_USERNAME)%' 241 | password: '%env(REPLICAS_PASSWORD)%' 242 | toolforge_s4: 243 | host: '%env(REPLICAS_HOST_S4)%' 244 | port: '%env(REPLICAS_PORT_S4)%' 245 | user: '%env(REPLICAS_USERNAME)%' 246 | password: '%env(REPLICAS_PASSWORD)%' 247 | toolforge_s5: 248 | host: '%env(REPLICAS_HOST_S5)%' 249 | port: '%env(REPLICAS_PORT_S5)%' 250 | user: '%env(REPLICAS_USERNAME)%' 251 | password: '%env(REPLICAS_PASSWORD)%' 252 | toolforge_s6: 253 | host: '%env(REPLICAS_HOST_S6)%' 254 | port: '%env(REPLICAS_PORT_S6)%' 255 | user: '%env(REPLICAS_USERNAME)%' 256 | password: '%env(REPLICAS_PASSWORD)%' 257 | toolforge_s7: 258 | host: '%env(REPLICAS_HOST_S7)%' 259 | port: '%env(REPLICAS_PORT_S7)%' 260 | user: '%env(REPLICAS_USERNAME)%' 261 | password: '%env(REPLICAS_PASSWORD)%' 262 | toolforge_s8: 263 | host: '%env(REPLICAS_HOST_S8)%' 264 | port: '%env(REPLICAS_PORT_S8)%' 265 | user: '%env(REPLICAS_USERNAME)%' 266 | password: '%env(REPLICAS_PASSWORD)%' 267 | # If you need to work with toolsdb 268 | toolforge_toolsdb: 269 | host: '%env(TOOLSDB_HOST)%' 270 | port: '%env(TOOLSDB_PORT)%' 271 | user: '%env(TOOLSDB_USERNAME)%' 272 | password: '%env(TOOLSDB_PASSWORD)%' 273 | # If you need to work with a Trove database 274 | toolforge_trove: 275 | host: '%env(TROVE_HOST)%' 276 | port: '%env(TROVE_PORT)%' 277 | user: '%env(TROVE_USERNAME)%' 278 | password: '%env(TROVE_PASSWORD)%' 279 | ``` 280 | 281 |
282 | 283 | Also adding the `REPLICAS_HOST_`, `REPLICAS_USERNAME`, `REPLICAS_PASSWORD` and each 284 | `REPLICAS_PORT_` to .env as necessary. If new sections are added (which is rare), you will 285 | need to update these accordingly. 286 | 287 | In **production**, the `REPLICAS_HOST_S1` variables should be `s1.web.db.svc.wikimedia.cloud` 288 | (or `analytics` instead of `web`), and similarly for each section. The `REPLICAS_PORT_` vars 289 | should be `3306` in production. For **local environments**, use `127.0.0.1` for the host vars 290 | and any safe range of ports (such as 4711 for `s1`, 4712 for `s2`, and so on). 291 | 292 | Next, establish an SSH tunnel to the replicas (only necessary on local environments): 293 | 294 | php bin/console toolforge:ssh 295 | 296 | Use the `--bind-address` flag to change the binding address, if needed. This may be necessary 297 | for Docker installations. 298 | 299 | If you need to work against [tools-db](https://wikitech.wikimedia.org/wiki/Help:Toolforge/Database#User_databases), 300 | pass the `--toolsdb` flag and make sure the `TOOLSBD_` env variables are set correctly. 301 | Unless you have a private database, you should be able to use the same username and password 302 | as `REPLICAS_USERNAME` and `REPLICAS_PASSWORD`. 303 | 304 | If you need to work against a [Trove database](https://wikitech.wikimedia.org/wiki/Help:Trove_database_user_guide), 305 | pass the `--trove` flag, supplying the hostname, and make sure the `TROVE_` env variables are set correctly. 306 | The credentials for this are separate from the replicas and toolsdb. 307 | 308 | If your Toolforge UNIX shell username is different than your local, you'll need to specify it with `--username`. 309 | 310 | To query the replicas, inject the `ReplicasClient` service then call the `getConnection()` 311 | method, passing in a valid database, and you should get a `Doctrine\DBAL\Connection` object. 312 | For example: 313 | 314 | # src/Controller/MyController.php 315 | public function myMethod(ReplicasClient $client) { 316 | $frConnection = $client->getConnection('frwiki'); 317 | $frUserId = $frConnection->executeQuery("SELECT user_id FROM user LIMIT 1")->fetch(); 318 | $ruConnection = $client->getConnection('ruwiki'); 319 | $ruUserId = $ruConnection->executeQuery("SELECT user_id FROM user LIMIT 1")->fetch(); 320 | # ... 321 | } 322 | 323 | In this example, `$frConnection` and `$ruConnection` actually point to the same `Connection` 324 | instance, since (at the time of writing) both `frwiki` and `ruwiki` live on the 325 | [same section](https://noc.wikimedia.org/conf/highlight.php?file=dblists/s6.dblist). 326 | `ReplicasClient` knows to do this because it queries (and caches) the dblists at 327 | https://noc.wikimedia.org. 328 | 329 | ### PHP Code Sniffer 330 | 331 | You can use the bundle's phpcs rules by adding the following 332 | to the `require-dev` section of your project's `composer.json`: 333 | 334 | "slevomat/coding-standard": "^4.8" 335 | 336 | And then referencing the bundle's ruleset with the following in your project's `.phpcs.xml`: 337 | 338 | 339 | 340 | ### Wikimedia UI styles 341 | 342 | You may want your tool to conform to the 343 | [Wikimedia Design Style Guide](https://design.wikimedia.org/style-guide/). 344 | A basic [LESS](http://lesscss.org/) stylesheet that applies some of these design elements 345 | is available in the bundle. To use it, first install the required packages: 346 | 347 | npm install wikimedia-ui-base less less-loader 348 | 349 | And then import both it and the bundle's CSS file for it 350 | (e.g. at the top of your `assets/app.less` file): 351 | 352 | @import '../node_modules/wikimedia-ui-base/wikimedia-ui-base.less'; 353 | @import '../vendor/wikimedia/toolforge-bundle/Resources/assets/wikimedia-base.less'; 354 | 355 | ### Deployment script 356 | 357 | The bundle comes with a deployment script for use on Toolforge 358 | where an application is run on the Kubernetes cluster. 359 | 360 | It should be added to your tool's crontab to run e.g. every ten minutes: 361 | 362 | */10 * * * * /usr/bin/jsub -once -quiet /data/project///vendor/wikimedia/toolforge-bundle/bin/deploy.sh prod /data/project/// 363 | 364 | * The first argument is either `prod` or `dev`, 365 | depending on whether you want to run the highest tagged version, 366 | or the latest master branch. 367 | * The second is the path to the tool's top-level directory, 368 | which is usually either the tool's home directory or a directory within it 369 | (e.g. `/data/project//app`). 370 | 371 | ### Sessions 372 | 373 | By default Symfony uses `/` for sessions' cookie path, but this isn't secure on Toolforge 374 | because it means that different tools can access each other's cookies. Additionally, Toolforge 375 | may by default use the fallback to the session expiry defined in php.ini, which is only 376 | 24 minutes. To fix this, set the following in your `framework.yaml`: 377 | 378 | framework: 379 | session: 380 | storage_id: Wikimedia\ToolforgeBundle\Service\NativeSessionStorage 381 | handler_id: 'session.handler.native_file' 382 | save_path: '%kernel.project_dir%/var/sessions/%kernel.environment%' 383 | cookie_lifetime: 604800 # one week 384 | 385 | ## Examples 386 | 387 | This bundle is currently in use on the following projects: 388 | 389 | 1. [Event Metrics](https://meta.wikimedia.org/wiki/Special:MyLanguage/Event_Metrics) 390 | 2. [SVG Translate](https://commons.wikimedia.org/wiki/Special:MyLanguage/Commons:SVG_Translate_tool) 391 | 3. [Global Search](https://global-search.toolforge.org) 392 | 4. [Flickr Dashboard](https://flickrdash.toolforge.org) 393 | 5. [Wikisource Export](https://wsexport.wmcloud.org) 394 | 6. [Wikimedia OCR](https://ocr.wmcloud.org) 395 | 7. [CopyPatrol](https://copypatrol.toolforge.org) 396 | 8. [Wikisource Contests](https://wscontest.toolforge.org) 397 | 398 | ## License 399 | 400 | GPL 3.0 or later. 401 | -------------------------------------------------------------------------------- /Resources/assets/jquery.i18n.min.js: -------------------------------------------------------------------------------- 1 | (function($){"use strict";var nav,I18N,slice=Array.prototype.slice;I18N=function(options){this.options=$.extend({},I18N.defaults,options);this.parser=this.options.parser;this.locale=this.options.locale;this.messageStore=this.options.messageStore;this.languages={};this.init()};I18N.prototype={init:function(){var i18n=this;String.locale=i18n.locale;String.prototype.toLocaleString=function(){var localeParts,localePartIndex,value,locale,fallbackIndex,tryingLocale,message;value=this.valueOf();locale=i18n.locale;fallbackIndex=0;while(locale){localeParts=locale.split("-");localePartIndex=localeParts.length;do{tryingLocale=localeParts.slice(0,localePartIndex).join("-");message=i18n.messageStore.get(tryingLocale,value);if(message){return message}localePartIndex--}while(localePartIndex);if(locale==="en"){break}locale=$.i18n.fallbacks[i18n.locale]&&$.i18n.fallbacks[i18n.locale][fallbackIndex]||i18n.options.fallbackLocale;$.i18n.log("Trying fallback locale for "+i18n.locale+": "+locale);fallbackIndex++}return""}},destroy:function(){$.removeData(document,"i18n")},load:function(source,locale){var fallbackLocales,locIndex,fallbackLocale,sourceMap={};if(!source&&!locale){source="i18n/"+$.i18n().locale+".json";locale=$.i18n().locale}if(typeof source==="string"&&source.split(".").pop()!=="json"){sourceMap[locale]=source+"/"+locale+".json";fallbackLocales=($.i18n.fallbacks[locale]||[]).concat(this.options.fallbackLocale);for(locIndex in fallbackLocales){fallbackLocale=fallbackLocales[locIndex];sourceMap[fallbackLocale]=source+"/"+fallbackLocale+".json"}return this.load(sourceMap)}else{return this.messageStore.load(source,locale)}},parse:function(key,parameters){var message=key.toLocaleString();this.parser.language=$.i18n.languages[$.i18n().locale]||$.i18n.languages["default"];if(message===""){message=key}return this.parser.parse(message,parameters)}};$.i18n=function(key,param1){var parameters,i18n=$.data(document,"i18n"),options=typeof key==="object"&&key;if(options&&options.locale&&i18n&&i18n.locale!==options.locale){String.locale=i18n.locale=options.locale}if(!i18n){i18n=new I18N(options);$.data(document,"i18n",i18n)}if(typeof key==="string"){if(param1!==undefined){parameters=slice.call(arguments,1)}else{parameters=[]}return i18n.parse(key,parameters)}else{return i18n}};$.fn.i18n=function(){var i18n=$.data(document,"i18n");if(!i18n){i18n=new I18N;$.data(document,"i18n",i18n)}String.locale=i18n.locale;return this.each(function(){var $this=$(this),messageKey=$this.data("i18n"),lBracket,rBracket,type,key;if(messageKey){lBracket=messageKey.indexOf("[");rBracket=messageKey.indexOf("]");if(lBracket!==-1&&rBracket!==-1&&lBracket1?["CONCAT"].concat(expr):expr[0]}function templateWithReplacement(){var result=sequence([templateName,colon,replacement]);return result===null?null:[result[0],result[2]]}function templateWithOutReplacement(){var result=sequence([templateName,colon,paramExpression]);return result===null?null:[result[0],result[2]]}templateContents=choice([function(){var res=sequence([choice([templateWithReplacement,templateWithOutReplacement]),nOrMore(0,templateParam)]);return res===null?null:res[0].concat(res[1])},function(){var res=sequence([templateName,nOrMore(0,templateParam)]);if(res===null){return null}return[res[0]].concat(res[1])}]);openTemplate=makeStringParser("{{");closeTemplate=makeStringParser("}}");function template(){var result=sequence([openTemplate,templateContents,closeTemplate]);return result===null?null:result[1]}expression=choice([template,replacement,literal]);paramExpression=choice([template,replacement,literalWithoutBar]);function start(){var result=nOrMore(0,expression)();if(result===null){return null}return["CONCAT"].concat(result)}result=start();if(result===null||pos!==message.length){throw new Error("Parse error at position "+pos.toString()+" in input: "+message)}return result}};$.extend($.i18n.parser,new MessageParser)})(jQuery);(function($){"use strict";var MessageParserEmitter=function(){this.language=$.i18n.languages[String.locale]||$.i18n.languages["default"]};MessageParserEmitter.prototype={constructor:MessageParserEmitter,emit:function(node,replacements){var ret,subnodes,operation,messageParserEmitter=this;switch(typeof node){case"string":case"number":ret=node;break;case"object":subnodes=$.map(node.slice(1),function(n){return messageParserEmitter.emit(n,replacements)});operation=node[0].toLowerCase();if(typeof messageParserEmitter[operation]==="function"){ret=messageParserEmitter[operation](subnodes,replacements)}else{throw new Error('unknown operation "'+operation+'"')}break;case"undefined":ret="";break;default:throw new Error("unexpected type in AST: "+typeof node)}return ret},concat:function(nodes){var result="";$.each(nodes,function(i,node){result+=node});return result},replace:function(nodes,replacements){var index=parseInt(nodes[0],10);if(index=parseInt(range_list[0],10)&&result[0] 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | ToolforgeBundle.php 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /Resources/templates/i18n.html.twig: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /Service/Intuition.php: -------------------------------------------------------------------------------- 1 | getCurrentRequest()) { 29 | $currentRequest = $requestStack->getCurrentRequest(); 30 | // Use lang from the 'lang' query parameter or the 'lang' session variable. 31 | $queryLang = false; 32 | if ($currentRequest->query->has('uselang')) { 33 | $queryLang = $currentRequest->query->get('uselang'); 34 | if (!empty($queryLang)) { 35 | $useLang = $queryLang; 36 | } 37 | } 38 | $sessionLang = false; 39 | if ($currentRequest->hasSession()) { 40 | $session = $currentRequest->getSession(); 41 | $sessionLang = $session->get('lang'); 42 | if (!$queryLang && !empty($sessionLang)) { 43 | $useLang = $sessionLang; 44 | } 45 | // Save the language to the session. 46 | if ($session->get('lang') !== $useLang) { 47 | $session->set('lang', $useLang); 48 | } 49 | } 50 | } 51 | 52 | // Set up Intuition, using the selected language. 53 | $intuition = new static(['domain' => $domain, 'param' => false]); 54 | $intuition->registerDomain($domain, $projectDir.'/i18n'); 55 | $intuition->registerDomain('toolforge', dirname(__DIR__).'/Resources/i18n'); 56 | $intuition->setLang(strtolower($useLang)); 57 | 58 | // Also add US English, so we can access the locale information (e.g. for date formatting). 59 | $intuition->addAvailableLang('en-us', 'US English'); 60 | 61 | return $intuition; 62 | } 63 | 64 | /** 65 | * Get names of all registered domains. 66 | * 67 | * @return string[] 68 | */ 69 | public function getDomains(): array 70 | { 71 | return array_keys($this->domainInfos); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /Service/NativeSessionStorage.php: -------------------------------------------------------------------------------- 1 | getMasterRequest(); 29 | if ($masterRequest) { 30 | // If we're in a request, use the base URL as the cookie path. 31 | $options['cookie_path'] = $masterRequest->getBaseUrl().'/'; 32 | } 33 | parent::__construct($options, $handler, $metaBag); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Service/ReplicasClient.php: -------------------------------------------------------------------------------- 1 | httpClient = $httpClient; 44 | $this->cache = $cache; 45 | $this->driver = $driver; 46 | } 47 | 48 | /** 49 | * Fetch and concatenate all the dblists into one array. 50 | * @return string[] Keys are the db name (i.e. 'enwiki'), values are the slice (i.e. 's1') 51 | */ 52 | public function getDbList(): array 53 | { 54 | return $this->cache->get('toolforge.dblists', function (ItemInterface $item) { 55 | $item->expiresAfter(self::DBLIST_CACHE_DURATION); 56 | 57 | $dbList = []; 58 | $exists = true; 59 | $i = 0; 60 | 61 | while ($exists) { 62 | $i += 1; 63 | $response = $this->httpClient->request('GET', self::DBLISTS_URL."s$i.dblist"); 64 | $exists = in_array( 65 | $response->getStatusCode(), 66 | [Response::HTTP_OK, Response::HTTP_NOT_MODIFIED] 67 | ) && $i < 50; // Safeguard 68 | 69 | if (!$exists) { 70 | break; 71 | } 72 | 73 | $lines = explode("\n", $response->getContent()); 74 | foreach ($lines as $line) { 75 | $line = trim($line); 76 | if (1 !== preg_match('/^#/', $line) && '' !== $line) { 77 | // Skip comments and blank lines. 78 | $dbList[$line] = "s$i"; 79 | } 80 | } 81 | } 82 | 83 | return $dbList; 84 | }); 85 | } 86 | 87 | /** 88 | * Get a Doctrine Connection instance for the given database. 89 | * Any databases that live on the same shard will share the same Connection instance. 90 | * @param string $db The desired database to connect to, with or without the _p suffix. 91 | * @param bool $useDb Whether to set the connection to USE the given $db. This usually costs 92 | * about 20-50ms, so for cross-wiki tools it is best practice to prefix the table name 93 | * with the database in your SQL, and call this method with $useDb set to false. 94 | * @return Connection 95 | */ 96 | public function getConnection(string $db, bool $useDb = true): Connection 97 | { 98 | // Remove _p if given. 99 | $db = str_replace('_p', '', $db); 100 | $slice = $this->getDbList()[$db]; 101 | 102 | /** @var Connection $conn */ 103 | $conn = $this->driver->getConnection('toolforge_'.$slice); 104 | 105 | if ($useDb) { 106 | $conn->executeQuery('USE '.$db.'_p'); 107 | } 108 | 109 | return $conn; 110 | } 111 | 112 | /** 113 | * Get the port number that should be used for the given slice. 114 | * @param string $slice Such as 's1', 's2', etc. 115 | * @return int 116 | */ 117 | public function getPortForSlice(string $slice): int 118 | { 119 | $conn = $this->driver->getConnection('toolforge_'.$slice); 120 | return (int)$conn->getParams()['port']; 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /Service/Util.php: -------------------------------------------------------------------------------- 1 | client = new ReplicasClient( 24 | HttpClient::create(), 25 | new FilesystemAdapter(), 26 | new Registry(new Container(), [], [], '', '') 27 | ); 28 | } 29 | 30 | /** 31 | * @covers ReplicasRepository::fetchDbLists() 32 | */ 33 | public function testGetDbList(): void 34 | { 35 | $dbList = $this->client->getDbList(); 36 | 37 | $this->assertArrayHasKey('enwiki', $dbList); 38 | 39 | // This should be future-proof. 40 | $this->assertEquals($dbList['enwiki'], 's1'); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Tests/Twig/ExtensionTest.php: -------------------------------------------------------------------------------- 1 | setSession(new Session(new MockArraySessionStorage())); 28 | $requestStack->push($request); 29 | $domain = 'toolforge'; 30 | $rootDir = dirname(__DIR__, 2); 31 | $intuition = Intuition::serviceFactory($requestStack, $rootDir, $domain); 32 | $cache = new NullAdapter(); 33 | $this->extension = new Extension($intuition, $cache, $requestStack, $domain); 34 | } 35 | 36 | public function testBasics(): void 37 | { 38 | static::assertEquals('en', $this->extension->getLang()); 39 | static::assertEquals('English', $this->extension->getLangName()); 40 | 41 | $allLangs = $this->extension->getAllLangs(); 42 | 43 | // There should be a bunch. 44 | static::assertGreaterThan(0, count($allLangs)); 45 | 46 | // Keys should be the language codes, with name as the values. 47 | static::assertArrayHasKey('en', $allLangs); 48 | static::assertSame('English', $allLangs['en']); 49 | static::assertArrayHasKey('de', $allLangs); 50 | static::assertSame('Deutsch', $allLangs['de']); 51 | 52 | // Testing if the language is RTL. 53 | static::assertFalse($this->extension->isRtl('en')); 54 | static::assertTrue($this->extension->isRtl('ar')); 55 | } 56 | 57 | public function testBdi(): void 58 | { 59 | static::assertEquals('Foo', $this->extension->bdi('Foo')); 60 | static::assertEquals('', $this->extension->bdi('')); 61 | } 62 | 63 | /** 64 | * Format a number. 65 | */ 66 | public function testNumberFormat(): void 67 | { 68 | static::assertEquals('1,234', $this->extension->numberFormat(1234)); 69 | static::assertEquals('1,234.32', $this->extension->numberFormat(1234.316, 2)); 70 | static::assertEquals('50', $this->extension->numberFormat(50.0000, 4)); 71 | } 72 | 73 | /** 74 | * Methods that fetch data about the git repository. 75 | */ 76 | public function testGitMethods(): void 77 | { 78 | static::assertEquals(7, strlen($this->extension->gitHashShort())); 79 | static::assertEquals(40, strlen($this->extension->gitHash())); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /ToolforgeBundle.php: -------------------------------------------------------------------------------- 1 | intuition = $intuition; 44 | $this->cache = $cache; 45 | if ($requestStack->getCurrentRequest() && $requestStack->getCurrentRequest()->hasSession()) { 46 | $this->session = $requestStack->getCurrentRequest()->getSession(); 47 | } 48 | $this->domain = $domain; 49 | } 50 | 51 | /** 52 | * Get all functions that this extension provides. 53 | * @return TwigFunction[] 54 | */ 55 | public function getFunctions(): array 56 | { 57 | $rawHtml = ['is_safe' => ['html']]; 58 | return [ 59 | new TwigFunction('logged_in_user', [$this, 'getLoggedInUser']), 60 | new TwigFunction('msg', [$this, 'msg'], $rawHtml), 61 | new TwigFunction('bdi', [$this, 'bdi'], $rawHtml), 62 | new TwigFunction('msg_exists', [$this, 'msgExists'], $rawHtml), 63 | new TwigFunction('msg_if_exists', [$this, 'msgIfExists'], $rawHtml), 64 | new TwigFunction('lang', [$this, 'getLang']), 65 | new TwigFunction('lang_name', [$this, 'getLangName']), 66 | new TwigFunction('all_langs', [$this, 'getAllLangs']), 67 | new TwigFunction('is_rtl', [$this, 'isRtl']), 68 | new TwigFunction('git_tag', [$this, 'gitTag']), 69 | new TwigFunction('git_branch', [$this, 'gitBranch']), 70 | new TwigFunction('git_hash', [$this, 'gitHash']), 71 | new TwigFunction('git_hash_short', [$this, 'gitHashShort']), 72 | ]; 73 | } 74 | 75 | /** 76 | * Get the currently logged in user's details, as returned by \MediaWiki\OAuthClient\Client::identify() when the 77 | * user logged in. 78 | * @return string[]|bool 79 | */ 80 | public function getLoggedInUser() 81 | { 82 | if (!$this->session) { 83 | return false; 84 | } 85 | return $this->session->get('logged_in_user'); 86 | } 87 | 88 | /** 89 | * Get an i18n message if the key exists, otherwise treat as plain text. 90 | * @param string $message 91 | * @param string[] $vars 92 | * @return mixed|null|string 93 | */ 94 | public function msgIfExists(string $message = '', array $vars = []) 95 | { 96 | $exists = $this->msgExists($message, $vars); 97 | if ($exists) { 98 | return $this->msg($message, $vars); 99 | } 100 | return $message; 101 | } 102 | 103 | /** 104 | * See if a given i18n message exists. 105 | * If this returns false it means msg() would return "[message-key]" 106 | * 107 | * @param string $message The message. 108 | * @param string[] $vars 109 | * @return bool 110 | */ 111 | public function msgExists(string $message = '', array $vars = []): bool 112 | { 113 | foreach ($this->intuition->getDomains() as $domain) { 114 | $exists = $this->intuition->msgExists($message, [ 115 | 'domain' => $domain, 116 | 'variables' => is_array($vars) ? $vars : [], 117 | ]); 118 | if ($exists) { 119 | return true; 120 | } 121 | } 122 | return false; 123 | } 124 | 125 | /** 126 | * Get an i18n message, searching all registered domains. 127 | * @param string $message 128 | * @param string[] $vars 129 | * @return mixed|null|string 130 | */ 131 | public function msg(string $message = '', array $vars = []) 132 | { 133 | // Check all domains for this message. 134 | foreach ($this->intuition->getDomains() as $domain) { 135 | if ($this->intuition->msgExists($message, ['domain' => $domain])) { 136 | return $this->intuition->msg($message, [ 137 | 'domain' => $domain, 138 | 'variables' => $vars, 139 | ]); 140 | } 141 | } 142 | return $this->intuition->bracketMsg($message); 143 | } 144 | 145 | /** 146 | * Wrap text with bdi tags for bidirectional isolation 147 | * @param string $text Text to be wrapped 148 | * @return string Text wrapped with bdi tags, or empty string 149 | * if an empty string was originally given 150 | */ 151 | public function bdi(string $text = ''): string 152 | { 153 | if (!empty($text)) { 154 | return ''.$text.''; 155 | } 156 | return ''; 157 | } 158 | 159 | /** 160 | * Get the current language code. 161 | * @return string 162 | */ 163 | public function getLang(): string 164 | { 165 | return $this->intuition->getLang(); 166 | } 167 | 168 | /** 169 | * Get the current language name (defaults to 'English'). 170 | * @return string 171 | */ 172 | public function getLangName(?string $lang = null): string 173 | { 174 | if ($lang) { 175 | return $this->intuition->getLangName($lang); 176 | } 177 | return $this->intuition->getLangName($this->intuition->getLang()); 178 | } 179 | 180 | /** 181 | * Get all available languages in the i18n directory. 182 | * @return string[] Associative array of langKey => langName 183 | */ 184 | public function getAllLangs(): array 185 | { 186 | $domainInfo = $this->intuition->getDomainInfo($this->domain); 187 | $messageFiles = glob($domainInfo['dir'].'/*.json'); 188 | $languages = array_values(array_unique(array_map( 189 | function ($filename) { 190 | return basename($filename, '.json'); 191 | }, 192 | $messageFiles 193 | ))); 194 | $availableLanguages = []; 195 | foreach ($languages as $lang) { 196 | $availableLanguages[$lang] = $this->intuition->getLangName($lang); 197 | } 198 | ksort($availableLanguages); 199 | return $availableLanguages; 200 | } 201 | 202 | /** 203 | * Whether the current (or specified) language is right-to-left. 204 | * @param string|bool $lang Language code (if false, will use current language). 205 | * @return bool 206 | * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint 207 | */ 208 | public function isRtl($lang = false): bool 209 | { 210 | if ($lang) { 211 | return $this->intuition->isRtl($lang); 212 | } 213 | return $this->intuition->isRtl($this->intuition->getLang()); 214 | } 215 | 216 | /** 217 | * Get the current Git tag, or the short hash if there's no tags. 218 | * @return string 219 | */ 220 | public function gitTag(): string 221 | { 222 | return $this->cache->get('toolforgebundle-git-tag', function (CacheItemInterface $cacheItem) { 223 | $cacheItem->expiresAfter(new DateInterval('PT10M')); 224 | $process = new Process(['git', 'describe', '--tags', '--always']); 225 | $process->run(); 226 | if (!$process->isSuccessful()) { 227 | return $this->gitHashShort(); 228 | } 229 | return trim($process->getOutput()); 230 | }); 231 | } 232 | 233 | /** 234 | * Get the currently checked-out Git branch. 235 | * @return string 236 | */ 237 | public function gitBranch(): string 238 | { 239 | return $this->gitCommand('git-branch', ['git', 'rev-parse', '--symbolic-full-name', '--abbrev-ref', 'HEAD']); 240 | } 241 | 242 | /** 243 | * Get the full hash of the currently checked-out Git commit. 244 | * @return string 245 | */ 246 | public function gitHash(): string 247 | { 248 | return $this->gitCommand('git-hash', ['git', 'rev-parse', 'HEAD']); 249 | } 250 | 251 | /** 252 | * Get the short hash of the currently checked-out Git commit. 253 | * @return string 254 | */ 255 | public function gitHashShort(): string 256 | { 257 | return $this->gitCommand('git-hash-short', ['git', 'rev-parse', '--short', 'HEAD']); 258 | } 259 | 260 | /** 261 | * @param string[] $command Command parts. 262 | */ 263 | private function gitCommand(string $cacheKey, array $command): string 264 | { 265 | $key = 'toolforge-bundle-'.$cacheKey; 266 | return $this->cache->get($key, function (CacheItemInterface $cacheItem) use ($command) { 267 | $cacheItem->expiresAfter(new DateInterval('PT10M')); 268 | $process = new Process($command); 269 | $process->run(); 270 | return trim($process->getOutput()); 271 | }); 272 | } 273 | 274 | /** 275 | * Get all filters that this extension provides. 276 | * @return TwigFilter[] 277 | */ 278 | public function getFilters(): array 279 | { 280 | return [ 281 | new TwigFilter('num_format', [$this, 'numberFormat']), 282 | new TwigFilter('list_format', [$this, 'listFormat']), 283 | ]; 284 | } 285 | 286 | /** 287 | * Format a number based on language settings. 288 | * @param int|float $number 289 | * @param int $decimals Number of decimals to format to. 290 | * @return string 291 | * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint 292 | */ 293 | public function numberFormat($number, int $decimals = 0): string 294 | { 295 | if (!isset($this->numberFormatter)) { 296 | $this->numberFormatter = new NumberFormatter($this->intuition->getLang(), NumberFormatter::DECIMAL); 297 | } 298 | $this->numberFormatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimals); 299 | return $this->numberFormatter->format($number); 300 | } 301 | 302 | /** 303 | * Format a list of values. In English this is a comma-separated list with the last item separated with 'and'. 304 | * @param string[] $list The list items. 305 | * @return string 306 | */ 307 | public function listFormat(array $list): string 308 | { 309 | return $this->intuition->listToText($list); 310 | } 311 | } 312 | -------------------------------------------------------------------------------- /bin/deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [[ "$#" -gt 5 || "$#" -lt 2 ]]; then 4 | echo "USAGE: $0 [--branch git-branch] [--build-assets]" 5 | exit 1 6 | fi 7 | 8 | ## Get CLI parameters. 9 | MODE=$1 10 | if [ ! -d "$2" ]; then 11 | echo "Directory doesn't exist: $2" 12 | exit 1 13 | fi 14 | APP_DIR=$(cd "$2" && pwd) 15 | shift 2 16 | 17 | cd "$APP_DIR" || exit 18 | 19 | BRANCH="master" 20 | BUILD_ASSETS=0 21 | 22 | # Our little param parser. 23 | while test $# -gt 0; do 24 | case "$1" in 25 | -b|--branch) 26 | shift 27 | if [[ -z $(git ls-remote origin "$1") ]]; then 28 | echo "$1 branch does not exist. Not deploying." 29 | exit 0 30 | else 31 | BRANCH="$1" 32 | fi 33 | shift 34 | ;; 35 | -a|--build-assets) 36 | BUILD_ASSETS=1 37 | shift 1 38 | ;; 39 | *) 40 | break; 41 | ;; 42 | esac 43 | done 44 | 45 | ## Update the repo. 46 | git fetch --quiet origin 2>&1 47 | 48 | ## Get some information about git. 49 | HIGHEST_TAG=$(git tag --list "*.*.*" | sort --version-sort | tail --lines 1) 50 | CURRENT_TAG=$(git describe --tags --always) 51 | CURRENT_BRANCH=$(git symbolic-ref --short -q HEAD) 52 | DIFF_TO_BRANCH=$(git diff origin/"$BRANCH") 53 | 54 | ## Prod site: do nothing if we're already at the highest tag. 55 | if [[ $MODE == "prod" && "$CURRENT_TAG" == "$HIGHEST_TAG" ]]; then 56 | exit 0 57 | fi 58 | 59 | ## Dev site: do nothing if not on specified branch. 60 | if [[ $MODE == "dev" && "$CURRENT_BRANCH" != "$BRANCH" ]]; then 61 | ## Tell the maintainers, so they don't forget they're in 62 | ## the middle of testing something. 63 | echo "Dev site not on specified branch. Not deploying." 64 | exit 0 65 | fi 66 | 67 | ## Dev site: do nothing if there's no difference to the specified branch. 68 | if [[ $MODE == "dev" && -z "$DIFF_TO_BRANCH" ]]; then 69 | exit 0 70 | fi 71 | 72 | ## Update the code. 73 | if [[ $MODE == "prod" ]]; then 74 | git checkout "$HIGHEST_TAG" 75 | ## Write to to the Server Admin Log on Wikitech if dologmsg is available. 76 | if [[ $(command -v dologmsg) ]]; then 77 | dologmsg "Updating to version $HIGHEST_TAG" 78 | fi 79 | fi 80 | if [[ $MODE == "dev" ]]; then 81 | git pull origin "$BRANCH" 82 | fi 83 | 84 | ## Prod and dev sites: install the application. 85 | composer install --no-dev --optimize-autoloader 86 | ./bin/console cache:clear 87 | 88 | ## Run migration command if migration folder exists. 89 | if [[ -d "migrations" ]]; then 90 | ./bin/console doctrine:migrations:migrate --no-interaction 91 | fi 92 | 93 | # Build assets if requested. 94 | if [[ $BUILD_ASSETS == 1 ]]; then 95 | npm install --production 96 | npm run build 97 | fi 98 | --------------------------------------------------------------------------------