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