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