]> scripts.mit.edu Git - wizard.git/blob - wizard/app/mediawiki.py
4ab86287f5baa6a1a03678e8fe6f2118a4caf296
[wizard.git] / wizard / app / mediawiki.py
1 import re
2 import distutils.version
3 import os
4 import lxml.cssselect
5 import lxml.etree
6 import StringIO
7 import logging
8
9 from wizard import app, install, resolve, shell, sql, util
10 from wizard.app import php
11
12 # Note: Maintenance script exit codes
13 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
14 # MediaWiki has notoriously spotty support for exit codes.  It has
15 # gotten better, but there are still always cases that slip through,
16 # such as <https://bugzilla.wikimedia.org/show_bug.cgi?id=29588>.
17 # As a result, we check both for exit codes AND for the "success"
18 # message in stdout.
19
20 def make_filename_regex(var):
21     """See :ref:`versioning config <seed>` for more information."""
22     return 'LocalSettings.php', php.re_var(var)
23
24 seed = util.dictmap(make_filename_regex, {
25         'WIZARD_IP': 'IP', # obsolete, remove after we're done
26         'WIZARD_SITENAME': 'wgSitename',
27         'WIZARD_META_NAMESPACE': 'wgMetaNamespace',
28         'WIZARD_SCRIPTPATH': 'wgScriptPath',
29         'WIZARD_SERVER': 'wgServer',
30         'WIZARD_EMERGENCYCONTACT': ('wgEmergencyContact', 'wgPasswordSender'),
31         'WIZARD_DBSERVER': 'wgDBserver',
32         'WIZARD_DBNAME': 'wgDBname',
33         'WIZARD_DBUSER': 'wgDBuser',
34         'WIZARD_DBPASSWORD': 'wgDBpassword',
35         'WIZARD_SECRETKEY': ('wgSecretKey', 'wgProxyKey'),
36         'WIZARD_UPGRADEKEY': 'wgUpgradeKey',
37         })
38
39 class Application(app.Application):
40     fullname = "MediaWiki"
41     database = "mysql"
42     parametrized_files = ['LocalSettings.php'] + php.parametrized_files
43     deprecated_keys = set(['WIZARD_IP']) | php.deprecated_keys
44     extractors = app.make_extractors(seed)
45     extractors.update(php.extractors)
46     substitutions = app.make_substitutions(seed)
47     substitutions.update(php.substitutions)
48     install_schema = install.ArgSchema("db", "admin", "email", "title")
49     random_keys = set(['WIZARD_SECRETKEY', 'WIZARD_UPGRADEKEY'])
50     def download(self, version):
51         series = ".".join(str(version).split(".")[:2])
52         return "http://download.wikimedia.org/mediawiki/%s/mediawiki-%s.tar.gz" % (series, version)
53     def checkConfig(self, deployment):
54         return os.path.isfile("LocalSettings.php")
55     def detectVersion(self, deployment):
56         return self.detectVersionFromFile("includes/DefaultSettings.php", php.re_var("wgVersion"))
57     def checkWeb(self, deployment):
58         return self.checkWebPage(deployment, "/index.php?title=Main_Page", outputs=["<!-- Served"])
59     def install(self, version, options):
60         php.ini_replace_vars()
61         if version >= distutils.version.LooseVersion("1.17.0"):
62             self.install_1_17_0(options)
63         else:
64             self.install_old(options)
65     def install_1_17_0(self, options):
66         util.soft_unlink("LocalSettings.php")
67         if os.path.exists("math"):
68             with util.ChangeDirectory("math"):
69                 shell.call("make")
70         try:
71             dbpass_fd, out_fd = os.pipe()
72             os.write(out_fd, options.dsn.password)
73             os.close(out_fd)
74             pass_fd, out_fd = os.pipe()
75             os.write(out_fd, options.admin_password)
76             os.close(out_fd)
77
78             result = shell.eval(
79                     "php", "-c", ".", "maintenance/install.php",
80                     "--dbname", options.dsn.database,
81                     "--dbpassfile", "php://fd/%d" % (dbpass_fd,),
82                     "--dbserver", options.dsn.host,
83                     "--dbuser", options.dsn.username,
84                     "--email", options.email,
85                     "--passfile", "php://fd/%d" % (pass_fd,),
86                     "--server", "https://" + options.web_host,
87                     "--scriptpath", options.web_path,
88                     options.title, options.admin_name,
89                     log=True,
90                     close_fds=False,
91             )
92         except shell.CallError as e:
93             raise app.RecoverableInstallFailure(["Install script returned non-zero exit code\nSTDOUT: %s\nSTDERR: %s" % (e.stdout, e.stderr)])
94         logging.debug("Install script output:\n\n" + result)
95         # See [Note: Maintenance script exit codes]
96         results = result.rstrip().split()
97         if not results or not results[-1] == "done":
98             raise app.RecoverableInstallFailure([result])
99
100     def install_old(self, options):
101         util.soft_unlink("LocalSettings.php")
102         os.chmod("config", 0777) # XXX: vaguely sketchy
103
104         postdata = {
105             'Sitename': options.title,
106             'EmergencyContact': options.email,
107             'LanguageCode': 'en',
108             'DBserver': options.dsn.host,
109             'DBname': options.dsn.database,
110             'DBuser': options.dsn.username,
111             'DBpassword': options.dsn.password,
112             'DBpassword2': options.dsn.password,
113             'defaultEmail': options.email,
114             'SysopName': options.admin_name,
115             'SysopPass': options.admin_password,
116             'SysopPass2': options.admin_password,
117             }
118         result = install.fetch(options, '/config/index.php', post=postdata)
119         result_etree = lxml.etree.parse(StringIO.StringIO(result), lxml.etree.HTMLParser())
120         selector = lxml.cssselect.CSSSelector(".error")
121         error_messages = [e.text for e in selector(result_etree)]
122         logging.debug("Installation output:\n\n" + result)
123         if result.find("Installation successful") == -1:
124             if not error_messages:
125                 raise app.InstallFailure()
126             else:
127                 raise app.RecoverableInstallFailure(error_messages)
128         os.rename('config/LocalSettings.php', 'LocalSettings.php')
129
130     def upgrade(self, d, version, options):
131         if not os.path.isfile("AdminSettings.php"):
132             shell.call("git", "checkout", "-q", "mediawiki-" + str(version), "--", "AdminSettings.php")
133         if os.path.exists("math"):
134             with util.ChangeDirectory("math"):
135                 shell.call("make")
136         try:
137             result = shell.eval("php", "maintenance/update.php", "--quick", log=True)
138         except shell.CallError as e:
139             raise app.UpgradeFailure("Update script returned non-zero exit code\nSTDOUT: %s\nSTDERR: %s" % (e.stdout, e.stderr))
140         logging.debug("Upgrade script output:\n\n" + result)
141         # See [Note: Maintenance script exit codes]
142         results = result.rstrip().split()
143         if not results or not results[-1] == "Done.":
144             raise app.UpgradeFailure(result)
145     @app.throws_database_errors
146     def backup(self, deployment, backup_dir, options):
147         sql.backup(backup_dir, deployment)
148     @app.throws_database_errors
149     def restore(self, deployment, backup_dir, options):
150         sql.restore(backup_dir, deployment)
151     @app.throws_database_errors
152     def remove(self, deployment, options):
153         sql.drop(deployment.dsn)
154     def researchFilter(self, filename, added, deleted):
155         if filename == "LocalSettings.php":
156             return added == deleted == 10 or added == deleted == 9
157         elif filename == "AdminSettings.php":
158             return added == 0 and deleted == 20
159         elif filename == "config/index.php" or filename == "config/index.php5":
160             return added == 0
161         return False
162
163 Application.resolutions = {
164 'LocalSettings.php': [
165     ("""
166 <<<<<<<
167 ***1***
168 =======
169 ## The URL base path to the directory containing the wiki;
170 ## defaults for all runtime URL paths are based off of this.
171 ## For more information on customizing the URLs please see:
172 ## http://www.mediawiki.org/wiki/Manual:Short_URL
173 ***2***
174 $wgScriptExtension  = ".php";
175
176 ## UPO means: this is also a user preference option
177 >>>>>>>
178 """, [-1]),
179     ("""
180 <<<<<<<
181 ***1***
182 =======
183
184 # MySQL specific settings
185 $wgDBprefix         = "";
186 >>>>>>>
187 """, ["\n# MySQL specific settings", 1]),
188     ("""
189 <<<<<<<
190 ## is writable, then uncomment this:
191 ***1***
192 =======
193 ## is writable, then set this to true:
194 $wgEnableUploads       = false;
195 >>>>>>>
196 """, [-1]),
197     ("""
198 <<<<<<<
199 ***1***
200 $wgMathPath         = "{$wgUploadPath}/math";
201 $wgMathDirectory    = "{$wgUploadDirectory}/math";
202 $wgTmpDirectory     = "{$wgUploadDirectory}/tmp";
203 =======
204 $wgUseTeX           = false;
205 >>>>>>>
206 """, [1]),
207     # order of these rules is important
208     ("""
209 <<<<<<<
210 $configdate = gmdate( 'YmdHis', @filemtime( __FILE__ ) );
211 $wgCacheEpoch = max( $wgCacheEpoch, $configdate );
212 ***1***
213 ?>
214 =======
215 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', @filemtime( __FILE__ ) ) );
216 >>>>>>>
217 """, [0, 1]),
218     ("""
219 <<<<<<<
220 $configdate = gmdate( 'YmdHis', @filemtime( __FILE__ ) );
221 $wgCacheEpoch = max( $wgCacheEpoch, $configdate );
222 ***1***
223 =======
224 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', @filemtime( __FILE__ ) ) );
225 >>>>>>>
226 """, [0, 1]),
227     ("""
228 <<<<<<<
229 ?>
230 =======
231 # When you make changes to this configuration file, this will make
232 # sure that cached pages are cleared.
233 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', @filemtime( __FILE__ ) ) );
234 >>>>>>>
235 """, [0]),
236     ("""
237 <<<<<<<
238 ***1***
239 ?>
240 =======
241 # When you make changes to this configuration file, this will make
242 # sure that cached pages are cleared.
243 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', @filemtime( __FILE__ ) ) );
244 >>>>>>>
245 """, [1, 0]),
246     ("""
247 <<<<<<<
248 ***1***
249 =======
250 # When you make changes to this configuration file, this will make
251 # sure that cached pages are cleared.
252 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', @filemtime( __FILE__ ) ) );
253 >>>>>>>
254 """, [1, 0]),
255     ]
256 }
257