]> scripts.mit.edu Git - wizard.git/blob - wizard/app/mediawiki.py
Update MediaWiki config regexes
[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             result = shell.eval(
72                     "php", "-c", ".", "maintenance/install.php",
73                     "--dbname", options.dsn.database,
74                     "--dbpass", options.dsn.password,
75                     "--dbserver", options.dsn.host,
76                     "--dbuser", options.dsn.username,
77                     "--email", options.email,
78                     "--pass", options.admin_password,
79                     "--server", "https://" + options.web_host,
80                     "--scriptpath", options.web_path,
81                     options.title, options.admin_name,
82                     log=True)
83         except shell.CallError as e:
84             raise app.RecoverableInstallFailure(["Install script returned non-zero exit code\nSTDOUT: %s\nSTDERR: %s" % (e.stdout, e.stderr)])
85         logging.debug("Install script output:\n\n" + result)
86         # See [Note: Maintenance script exit codes]
87         results = result.rstrip().split()
88         if not results or not results[-1] == "done":
89             raise app.RecoverableInstallFailure([result])
90
91     def install_old(self, options):
92         util.soft_unlink("LocalSettings.php")
93         os.chmod("config", 0777) # XXX: vaguely sketchy
94
95         postdata = {
96             'Sitename': options.title,
97             'EmergencyContact': options.email,
98             'LanguageCode': 'en',
99             'DBserver': options.dsn.host,
100             'DBname': options.dsn.database,
101             'DBuser': options.dsn.username,
102             'DBpassword': options.dsn.password,
103             'DBpassword2': options.dsn.password,
104             'defaultEmail': options.email,
105             'SysopName': options.admin_name,
106             'SysopPass': options.admin_password,
107             'SysopPass2': options.admin_password,
108             }
109         result = install.fetch(options, '/config/index.php', post=postdata)
110         result_etree = lxml.etree.parse(StringIO.StringIO(result), lxml.etree.HTMLParser())
111         selector = lxml.cssselect.CSSSelector(".error")
112         error_messages = [e.text for e in selector(result_etree)]
113         logging.debug("Installation output:\n\n" + result)
114         if result.find("Installation successful") == -1:
115             if not error_messages:
116                 raise app.InstallFailure()
117             else:
118                 raise app.RecoverableInstallFailure(error_messages)
119         os.rename('config/LocalSettings.php', 'LocalSettings.php')
120
121     def upgrade(self, d, version, options):
122         if not os.path.isfile("AdminSettings.php"):
123             shell.call("git", "checkout", "-q", "mediawiki-" + str(version), "--", "AdminSettings.php")
124         if os.path.exists("math"):
125             with util.ChangeDirectory("math"):
126                 shell.call("make")
127         try:
128             result = shell.eval("php", "maintenance/update.php", "--quick", log=True)
129         except shell.CallError as e:
130             raise app.UpgradeFailure("Update script returned non-zero exit code\nSTDOUT: %s\nSTDERR: %s" % (e.stdout, e.stderr))
131         logging.debug("Upgrade script output:\n\n" + result)
132         # See [Note: Maintenance script exit codes]
133         results = result.rstrip().split()
134         if not results or not results[-1] == "Done.":
135             raise app.UpgradeFailure(result)
136     @app.throws_database_errors
137     def backup(self, deployment, backup_dir, options):
138         sql.backup(backup_dir, deployment)
139     @app.throws_database_errors
140     def restore(self, deployment, backup_dir, options):
141         sql.restore(backup_dir, deployment)
142     @app.throws_database_errors
143     def remove(self, deployment, options):
144         sql.drop(deployment.dsn)
145     def researchFilter(self, filename, added, deleted):
146         if filename == "LocalSettings.php":
147             return added == deleted == 10 or added == deleted == 9
148         elif filename == "AdminSettings.php":
149             return added == 0 and deleted == 20
150         elif filename == "config/index.php" or filename == "config/index.php5":
151             return added == 0
152         return False
153
154 Application.resolutions = {
155 'LocalSettings.php': [
156     ("""
157 <<<<<<<
158 ***1***
159 =======
160 ## The URL base path to the directory containing the wiki;
161 ## defaults for all runtime URL paths are based off of this.
162 ## For more information on customizing the URLs please see:
163 ## http://www.mediawiki.org/wiki/Manual:Short_URL
164 ***2***
165 $wgScriptExtension  = ".php";
166
167 ## UPO means: this is also a user preference option
168 >>>>>>>
169 """, [-1]),
170     ("""
171 <<<<<<<
172 ***1***
173 =======
174
175 # MySQL specific settings
176 $wgDBprefix         = "";
177 >>>>>>>
178 """, ["\n# MySQL specific settings", 1]),
179     ("""
180 <<<<<<<
181 ## is writable, then uncomment this:
182 ***1***
183 =======
184 ## is writable, then set this to true:
185 $wgEnableUploads       = false;
186 >>>>>>>
187 """, [-1]),
188     ("""
189 <<<<<<<
190 ***1***
191 $wgMathPath         = "{$wgUploadPath}/math";
192 $wgMathDirectory    = "{$wgUploadDirectory}/math";
193 $wgTmpDirectory     = "{$wgUploadDirectory}/tmp";
194 =======
195 $wgUseTeX           = false;
196 >>>>>>>
197 """, [1]),
198     # order of these rules is important
199     ("""
200 <<<<<<<
201 $configdate = gmdate( 'YmdHis', @filemtime( __FILE__ ) );
202 $wgCacheEpoch = max( $wgCacheEpoch, $configdate );
203 ***1***
204 ?>
205 =======
206 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', @filemtime( __FILE__ ) ) );
207 >>>>>>>
208 """, [0, 1]),
209     ("""
210 <<<<<<<
211 $configdate = gmdate( 'YmdHis', @filemtime( __FILE__ ) );
212 $wgCacheEpoch = max( $wgCacheEpoch, $configdate );
213 ***1***
214 =======
215 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', @filemtime( __FILE__ ) ) );
216 >>>>>>>
217 """, [0, 1]),
218     ("""
219 <<<<<<<
220 ?>
221 =======
222 # When you make changes to this configuration file, this will make
223 # sure that cached pages are cleared.
224 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', @filemtime( __FILE__ ) ) );
225 >>>>>>>
226 """, [0]),
227     ("""
228 <<<<<<<
229 ***1***
230 ?>
231 =======
232 # When you make changes to this configuration file, this will make
233 # sure that cached pages are cleared.
234 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', @filemtime( __FILE__ ) ) );
235 >>>>>>>
236 """, [1, 0]),
237     ("""
238 <<<<<<<
239 ***1***
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