]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions-install.php
Safer DB version number, and debug feedback if failure on install
[Github/YOURLS.git] / includes / functions-install.php
1 <?php
2
3 /**
4  * Check if server has MySQL 4.1+
5  *
6  */
7 function yourls_check_database_version() {
8         global $ydb;
9         
10         // Attempt to get MySQL server version, check result and if error count increased
11         $num_errors1 = count( $ydb->captured_errors );
12         $version     = yourls_get_database_version();
13         $num_errors2 = count( $ydb->captured_errors );
14         
15         if( $version == NULL || ( $num_errors2 > $num_errors1 ) ) {
16                 yourls_die( yourls__( 'Incorrect DB config, or could not connect to DB' ), yourls__( 'Fatal error' ), 503 );
17         }
18         
19         return ( version_compare( '4.1', $version ) <= 0 );
20 }
21
22 /**
23  * Get DB version
24  *
25  * The regex removes everything that's not a number at the start of the string, or remove anything that's not a number and what
26  * follows after that.
27  *   'omgmysql-5.5-ubuntu-4.20' => '5.5'
28  *   'mysql5.5-ubuntu-4.20'     => '5.5'
29  *   '5.5-ubuntu-4.20'          => '5.5'
30  *   '5.5-beta2'                => '5.5'
31  *   '5.5'                      => '5.5'
32  *
33  * @since 1.7
34  * @return string sanitized DB version
35  */
36 function yourls_get_database_version() {
37         global $ydb;
38         
39         return preg_replace( '/(^[^0-9]*)|[^0-9.].*/', '', $ydb->mysql_version() );
40 }
41
42 /**
43  * Check if PHP > 4.3
44  *
45  */
46 function yourls_check_php_version() {
47         return ( version_compare( '4.3', phpversion() ) <= 0 );
48 }
49
50 /**
51  * Check if server is an Apache
52  *
53  */
54 function yourls_is_apache() {
55         if( !array_key_exists( 'SERVER_SOFTWARE', $_SERVER ) )
56                 return false;
57         return (
58            strpos( $_SERVER['SERVER_SOFTWARE'], 'Apache' ) !== false
59         || strpos( $_SERVER['SERVER_SOFTWARE'], 'LiteSpeed' ) !== false
60         );
61 }
62
63 /**
64  * Check if server is running IIS
65  *
66  */
67 function yourls_is_iis() {
68         return ( array_key_exists( 'SERVER_SOFTWARE', $_SERVER ) ? ( strpos( $_SERVER['SERVER_SOFTWARE'], 'IIS' ) !== false ) : false );
69 }
70
71
72 /**
73  * Create .htaccess or web.config. Returns boolean
74  *
75  */
76 function yourls_create_htaccess() {
77         $host = parse_url( YOURLS_SITE );
78         $path = ( isset( $host['path'] ) ? $host['path'] : '' );
79
80         if ( yourls_is_iis() ) {
81                 // Prepare content for a web.config file
82                 $content = array(
83                         '<?'.'xml version="1.0" encoding="UTF-8"?>',
84                         '<configuration>', 
85                         '    <system.webServer>',
86                         '        <rewrite>',
87                         '            <rules>',
88                         '                <rule name="YOURLS" stopProcessing="true">',
89                         '                    <match url="^(.*)$" ignoreCase="false" />',
90                         '                    <conditions>',
91                         '                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />',
92                         '                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />',
93                         '                    </conditions>',
94                         '                    <action type="Rewrite" url="'.$path.'/yourls-loader.php" appendQueryString="true" />',
95                         '                </rule>',
96                         '            </rules>',
97                         '        </rewrite>',
98                         '    </system.webServer>',
99                         '</configuration>',
100                 );
101         
102                 $filename = YOURLS_ABSPATH.'/web.config';
103                 $marker = 'none';
104
105         } else {
106                 // Prepare content for a .htaccess file
107                 $content = array(
108                         '<IfModule mod_rewrite.c>',
109                         'RewriteEngine On',
110                         'RewriteBase '.$path.'/',
111                         'RewriteCond %{REQUEST_FILENAME} !-f',
112                         'RewriteCond %{REQUEST_FILENAME} !-d',
113                         'RewriteRule ^.*$ '.$path.'/yourls-loader.php [L]',
114                         '</IfModule>',
115                 );
116         
117                 $filename = YOURLS_ABSPATH.'/.htaccess';
118                 $marker = 'YOURLS';
119                 
120         }
121         
122         return ( yourls_insert_with_markers( $filename, $marker, $content ) );
123 }
124
125 /**
126  * Inserts $insertion (text in an array of lines) into $filename (.htaccess) between BEGIN/END $marker block. Returns bool. Stolen from WP
127  *
128  */
129 function yourls_insert_with_markers( $filename, $marker, $insertion ) {
130         if ( !file_exists( $filename ) || is_writeable( $filename ) ) {
131                 if ( !file_exists( $filename ) ) {
132                         $markerdata = '';
133                 } else {
134                         $markerdata = explode( "\n", implode( '', file( $filename ) ) );
135                 }
136
137                 if ( !$f = @fopen( $filename, 'w' ) )
138                         return false;
139
140                 $foundit = false;
141                 if ( $markerdata ) {
142                         $state = true;
143                         foreach ( $markerdata as $n => $markerline ) {
144                                 if ( strpos( $markerline, '# BEGIN ' . $marker ) !== false )
145                                         $state = false;
146                                 if ( $state ) {
147                                         if ( $n + 1 < count( $markerdata ) )
148                                                 fwrite( $f, "{$markerline}\n" );
149                                         else
150                                                 fwrite( $f, "{$markerline}" );
151                                 }
152                                 if ( strpos( $markerline, '# END ' . $marker ) !== false ) {
153                                         if ( $marker != 'none' )
154                                                 fwrite( $f, "# BEGIN {$marker}\n" );
155                                         if ( is_array( $insertion ) )
156                                                 foreach ( $insertion as $insertline )
157                                                         fwrite( $f, "{$insertline}\n" );
158                                         if ( $marker != 'none' )
159                                                 fwrite( $f, "# END {$marker}\n" );
160                                         $state = true;
161                                         $foundit = true;
162                                 }
163                         }
164                 }
165                 if ( !$foundit ) {
166                         if ( $marker != 'none' )
167                                 fwrite( $f, "\n\n# BEGIN {$marker}\n" );
168                         foreach ( $insertion as $insertline )
169                                 fwrite( $f, "{$insertline}\n" );
170                         if ( $marker != 'none' )
171                                 fwrite( $f, "# END {$marker}\n\n" );
172                 }
173                 fclose( $f );
174                 return true;
175         } else {
176                 return false;
177         }
178 }
179
180 /**
181  * Create MySQL tables. Return array( 'success' => array of success strings, 'errors' => array of error strings )
182  *
183  */
184 function yourls_create_sql_tables() {
185         global $ydb;
186         
187         $error_msg = array();
188         $success_msg = array();
189
190         // Create Table Query
191         $create_tables = array();
192         $create_tables[YOURLS_DB_TABLE_URL] =
193                 'CREATE TABLE IF NOT EXISTS `'.YOURLS_DB_TABLE_URL.'` ('.
194                 '`keyword` varchar(200) BINARY NOT NULL,'.
195                 '`url` text BINARY NOT NULL,'.
196                 '`title` text CHARACTER SET utf8,'.
197                 '`timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,'.
198                 '`ip` VARCHAR(41) NOT NULL,'.
199                 '`clicks` INT(10) UNSIGNED NOT NULL,'.
200                 ' PRIMARY KEY  (`keyword`),'.
201                 ' KEY `timestamp` (`timestamp`),'.
202                 ' KEY `ip` (`ip`)'.
203                 ');';
204
205         $create_tables[YOURLS_DB_TABLE_OPTIONS] = 
206                 'CREATE TABLE IF NOT EXISTS `'.YOURLS_DB_TABLE_OPTIONS.'` ('.
207                 '`option_id` bigint(20) unsigned NOT NULL auto_increment,'.
208                 '`option_name` varchar(64) NOT NULL default "",'.
209                 '`option_value` longtext NOT NULL,'.
210                 'PRIMARY KEY  (`option_id`,`option_name`),'.
211                 'KEY `option_name` (`option_name`)'.
212                 ') AUTO_INCREMENT=1 ;';
213                 
214         $create_tables[YOURLS_DB_TABLE_LOG] = 
215                 'CREATE TABLE IF NOT EXISTS `'.YOURLS_DB_TABLE_LOG.'` ('.
216                 '`click_id` int(11) NOT NULL auto_increment,'.
217                 '`click_time` datetime NOT NULL,'.
218                 '`shorturl` varchar(200) BINARY NOT NULL,'.
219                 '`referrer` varchar(200) NOT NULL,'.
220                 '`user_agent` varchar(255) NOT NULL,'.
221                 '`ip_address` varchar(41) NOT NULL,'.
222                 '`country_code` char(2) NOT NULL,'.
223                 'PRIMARY KEY  (`click_id`),'.
224                 'KEY `shorturl` (`shorturl`)'.
225                 ') AUTO_INCREMENT=1 ;';
226
227
228         $create_table_count = 0;
229         
230         $ydb->show_errors = true;
231         
232         // Create tables
233         foreach ( $create_tables as $table_name => $table_query ) {
234                 $ydb->query( $table_query );
235                 $create_success = $ydb->query( "SHOW TABLES LIKE '$table_name'" );
236                 if( $create_success ) {
237                         $create_table_count++;
238                         $success_msg[] = yourls_s( "Table '%s' created.", $table_name ); 
239                 } else {
240                         $error_msg[] = yourls_s( "Error creating table '%s'.", $table_name ); 
241                 }
242         }
243                 
244         // Insert data into tables
245         yourls_update_option( 'version', YOURLS_VERSION );
246         yourls_update_option( 'db_version', YOURLS_DB_VERSION );
247         yourls_update_option( 'next_id', 1 );
248         
249         // Insert sample links
250         yourls_insert_link_in_db( 'http://planetozh.com/blog/', 'ozhblog', 'planetOzh: Ozh\' blog' );
251         yourls_insert_link_in_db( 'http://ozh.org/', 'ozh', 'ozh.org' );
252         yourls_insert_link_in_db( 'http://yourls.org/', 'yourls', 'YOURLS: Your Own URL Shortener' );
253                 
254         // Check results of operations
255         if ( sizeof( $create_tables ) == $create_table_count ) {
256                 $success_msg[] = yourls__( 'YOURLS tables successfully created.' );
257         } else {
258                 $error_msg[] = yourls__( 'Error creating YOURLS tables.' ); 
259         }
260
261         return array( 'success' => $success_msg, 'error' => $error_msg );
262 }
263
264
265 /**
266  * Toggle maintenance mode. Inspired from WP. Returns true for success, false otherwise
267  *
268  */
269 function yourls_maintenance_mode( $maintenance = true ) {
270
271         $file = YOURLS_ABSPATH . '/.maintenance' ;
272
273         // Turn maintenance mode on : create .maintenance file
274         if ( (bool)$maintenance ) {
275                 if ( ! ( $fp = @fopen( $file, 'w' ) ) )
276                         return false;
277                 
278                 $maintenance_string = '<?php $maintenance_start = ' . time() . '; ?>';
279                 @fwrite( $fp, $maintenance_string );
280                 @fclose( $fp );
281                 @chmod( $file, 0644 ); // Read and write for owner, read for everybody else
282
283                 // Not sure why the fwrite would fail if the fopen worked... Just in case
284                 return( is_readable( $file ) );
285                 
286         // Turn maintenance mode off : delete the .maintenance file
287         } else {
288                 return @unlink($file);
289         }
290 }