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