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