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