]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions-install.php
Merge
[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                         '        <security>',
87                         '            <requestFiltering allowDoubleEscaping="true" />',
88                         '        </security>',
89                         '        <rewrite>',
90                         '            <rules>',
91                         '                <rule name="YOURLS" stopProcessing="true">',
92                         '                    <match url="^(.*)$" ignoreCase="false" />',
93                         '                    <conditions>',
94                         '                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />',
95                         '                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />',
96                         '                    </conditions>',
97                         '                    <action type="Rewrite" url="'.$path.'/yourls-loader.php" appendQueryString="true" />',
98                         '                </rule>',
99                         '            </rules>',
100                         '        </rewrite>',
101                         '    </system.webServer>',
102                         '</configuration>',
103                 );
104         
105                 $filename = YOURLS_ABSPATH.'/web.config';
106                 $marker = 'none';
107
108         } else {
109                 // Prepare content for a .htaccess file
110                 $content = array(
111                         '<IfModule mod_rewrite.c>',
112                         'RewriteEngine On',
113                         'RewriteBase '.$path.'/',
114                         'RewriteCond %{REQUEST_FILENAME} !-f',
115                         'RewriteCond %{REQUEST_FILENAME} !-d',
116                         'RewriteRule ^.*$ '.$path.'/yourls-loader.php [L]',
117                         '</IfModule>',
118                 );
119         
120                 $filename = YOURLS_ABSPATH.'/.htaccess';
121                 $marker = 'YOURLS';
122                 
123         }
124         
125         return ( yourls_insert_with_markers( $filename, $marker, $content ) );
126 }
127
128 /**
129  * Inserts $insertion (text in an array of lines) into $filename (.htaccess) between BEGIN/END $marker block. Returns bool. Stolen from WP
130  *
131  */
132 function yourls_insert_with_markers( $filename, $marker, $insertion ) {
133         if ( !file_exists( $filename ) || is_writeable( $filename ) ) {
134                 if ( !file_exists( $filename ) ) {
135                         $markerdata = '';
136                 } else {
137                         $markerdata = explode( "\n", implode( '', file( $filename ) ) );
138                 }
139
140                 if ( !$f = @fopen( $filename, 'w' ) )
141                         return false;
142
143                 $foundit = false;
144                 if ( $markerdata ) {
145                         $state = true;
146                         foreach ( $markerdata as $n => $markerline ) {
147                                 if ( strpos( $markerline, '# BEGIN ' . $marker ) !== false )
148                                         $state = false;
149                                 if ( $state ) {
150                                         if ( $n + 1 < count( $markerdata ) )
151                                                 fwrite( $f, "{$markerline}\n" );
152                                         else
153                                                 fwrite( $f, "{$markerline}" );
154                                 }
155                                 if ( strpos( $markerline, '# END ' . $marker ) !== false ) {
156                                         if ( $marker != 'none' )
157                                                 fwrite( $f, "# BEGIN {$marker}\n" );
158                                         if ( is_array( $insertion ) )
159                                                 foreach ( $insertion as $insertline )
160                                                         fwrite( $f, "{$insertline}\n" );
161                                         if ( $marker != 'none' )
162                                                 fwrite( $f, "# END {$marker}\n" );
163                                         $state = true;
164                                         $foundit = true;
165                                 }
166                         }
167                 }
168                 if ( !$foundit ) {
169                         if ( $marker != 'none' )
170                                 fwrite( $f, "\n\n# BEGIN {$marker}\n" );
171                         foreach ( $insertion as $insertline )
172                                 fwrite( $f, "{$insertline}\n" );
173                         if ( $marker != 'none' )
174                                 fwrite( $f, "# END {$marker}\n\n" );
175                 }
176                 fclose( $f );
177                 return true;
178         } else {
179                 return false;
180         }
181 }
182
183 /**
184  * Create MySQL tables. Return array( 'success' => array of success strings, 'errors' => array of error strings )
185  *
186  */
187 function yourls_create_sql_tables() {
188         global $ydb;
189         
190         $error_msg = array();
191         $success_msg = array();
192
193         // Create Table Query
194         $create_tables = array();
195         $create_tables[YOURLS_DB_TABLE_URL] =
196                 'CREATE TABLE IF NOT EXISTS `'.YOURLS_DB_TABLE_URL.'` ('.
197                 '`keyword` varchar(200) BINARY NOT NULL,'.
198                 '`url` text BINARY NOT NULL,'.
199                 '`title` text CHARACTER SET utf8,'.
200                 '`timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,'.
201                 '`ip` VARCHAR(41) NOT NULL,'.
202                 '`clicks` INT(10) UNSIGNED NOT NULL,'.
203                 ' PRIMARY KEY  (`keyword`),'.
204                 ' KEY `timestamp` (`timestamp`),'.
205                 ' KEY `ip` (`ip`)'.
206                 ');';
207
208         $create_tables[YOURLS_DB_TABLE_OPTIONS] = 
209                 'CREATE TABLE IF NOT EXISTS `'.YOURLS_DB_TABLE_OPTIONS.'` ('.
210                 '`option_id` bigint(20) unsigned NOT NULL auto_increment,'.
211                 '`option_name` varchar(64) NOT NULL default "",'.
212                 '`option_value` longtext NOT NULL,'.
213                 'PRIMARY KEY  (`option_id`,`option_name`),'.
214                 'KEY `option_name` (`option_name`)'.
215                 ') AUTO_INCREMENT=1 ;';
216                 
217         $create_tables[YOURLS_DB_TABLE_LOG] = 
218                 'CREATE TABLE IF NOT EXISTS `'.YOURLS_DB_TABLE_LOG.'` ('.
219                 '`click_id` int(11) NOT NULL auto_increment,'.
220                 '`click_time` datetime NOT NULL,'.
221                 '`shorturl` varchar(200) BINARY NOT NULL,'.
222                 '`referrer` varchar(200) NOT NULL,'.
223                 '`user_agent` varchar(255) NOT NULL,'.
224                 '`ip_address` varchar(41) NOT NULL,'.
225                 '`country_code` char(2) NOT NULL,'.
226                 'PRIMARY KEY  (`click_id`),'.
227                 'KEY `shorturl` (`shorturl`)'.
228                 ') AUTO_INCREMENT=1 ;';
229
230
231         $create_table_count = 0;
232         
233         $ydb->show_errors = true;
234         
235         // Create tables
236         foreach ( $create_tables as $table_name => $table_query ) {
237                 $ydb->query( $table_query );
238                 $create_success = $ydb->query( "SHOW TABLES LIKE '$table_name'" );
239                 if( $create_success ) {
240                         $create_table_count++;
241                         $success_msg[] = yourls_s( "Table '%s' created.", $table_name ); 
242                 } else {
243                         $error_msg[] = yourls_s( "Error creating table '%s'.", $table_name ); 
244                 }
245         }
246                 
247         // Initializes the option table
248         if( !yourls_initialize_options() )
249                 $error_msg[] = yourls__( 'Could not initialize options' );
250         
251         // Insert sample links
252         if( !yourls_insert_sample_links() )
253                 $error_msg[] = yourls__( 'Could not insert sample short URLs' );
254         
255         // Check results of operations
256         if ( sizeof( $create_tables ) == $create_table_count ) {
257                 $success_msg[] = yourls__( 'YOURLS tables successfully created.' );
258         } else {
259                 $error_msg[] = yourls__( 'Error creating YOURLS tables.' ); 
260         }
261
262         return array( 'success' => $success_msg, 'error' => $error_msg );
263 }
264
265 /**
266  * Initializes the option table
267  *
268  * Each yourls_update_option() returns either true on success (option updated) or false on failure (new value == old value, or 
269  * for some reason it could not save to DB).
270  * Since true & true & true = 1, we cast it to boolean type to return true (or false)
271  *
272  * @since 1.7
273  * @return bool
274  */
275 function yourls_initialize_options() {
276         return ( bool ) (
277                   yourls_update_option( 'version', YOURLS_VERSION )
278                 & yourls_update_option( 'db_version', YOURLS_DB_VERSION )
279                 & yourls_update_option( 'next_id', 1 )
280         );
281 }
282
283 /**
284  * Populates the URL table with a few sample links
285  *
286  * @since 1.7
287  * @return bool
288  */
289 function yourls_insert_sample_links() {
290         $link1 = yourls_add_new_link( 'http://blog.yourls.org/', 'yourlsblog', 'YOURLS\' Blog' );
291         $link2 = yourls_add_new_link( 'http://yourls.org/',      'yourls',     'YOURLS: Your Own URL Shortener' );
292         $link3 = yourls_add_new_link( 'http://ozh.org/',         'ozh',        'ozh.org' );
293         return ( bool ) ( 
294                   $link1['status'] == 'success'
295                 & $link2['status'] == 'success'
296                 & $link3['status'] == 'success'
297         );
298 }
299
300
301 /**
302  * Toggle maintenance mode. Inspired from WP. Returns true for success, false otherwise
303  *
304  */
305 function yourls_maintenance_mode( $maintenance = true ) {
306
307         $file = YOURLS_ABSPATH . '/.maintenance' ;
308
309         // Turn maintenance mode on : create .maintenance file
310         if ( (bool)$maintenance ) {
311                 if ( ! ( $fp = @fopen( $file, 'w' ) ) )
312                         return false;
313                 
314                 $maintenance_string = '<?php $maintenance_start = ' . time() . '; ?>';
315                 @fwrite( $fp, $maintenance_string );
316                 @fclose( $fp );
317                 @chmod( $file, 0644 ); // Read and write for owner, read for everybody else
318
319                 // Not sure why the fwrite would fail if the fopen worked... Just in case
320                 return( is_readable( $file ) );
321                 
322         // Turn maintenance mode off : delete the .maintenance file
323         } else {
324                 return @unlink($file);
325         }
326 }