]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions-install.php
Allow custom table creation on install
[Github/YOURLS.git] / includes / functions-install.php
1 <?php
2
3 /**
4  * Check if server has MySQL 5.0+
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( '5.0', $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 > 5.2
44  *
45  */
46 function yourls_check_php_version() {
47         return ( version_compare( '5.2', 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  * @since 1.3
187  * @return array  An array like array( 'success' => array of success strings, 'errors' => array of error strings )
188  */
189 function yourls_create_sql_tables() {
190     // Allow plugins (most likely a custom db.php layer in user dir) to short-circuit the whole function
191     $pre = yourls_apply_filter( 'shunt_yourls_create_sql_tables', null );
192     // your filter function should return an array of ( 'success' => $success_msg, 'error' => $error_msg ), see below
193     if ( null !== $pre ) {
194         return $pre;
195     }
196
197         global $ydb;
198         
199         $error_msg = array();
200         $success_msg = array();
201
202         // Create Table Query
203         $create_tables = array();
204         $create_tables[YOURLS_DB_TABLE_URL] =
205                 'CREATE TABLE IF NOT EXISTS `'.YOURLS_DB_TABLE_URL.'` ('.
206                 '`keyword` varchar(200) BINARY NOT NULL,'.
207                 '`url` text BINARY NOT NULL,'.
208                 '`title` text CHARACTER SET utf8,'.
209                 '`timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,'.
210                 '`ip` VARCHAR(41) NOT NULL,'.
211                 '`clicks` INT(10) UNSIGNED NOT NULL,'.
212                 ' PRIMARY KEY  (`keyword`),'.
213                 ' KEY `timestamp` (`timestamp`),'.
214                 ' KEY `ip` (`ip`)'.
215                 ');';
216
217         $create_tables[YOURLS_DB_TABLE_OPTIONS] = 
218                 'CREATE TABLE IF NOT EXISTS `'.YOURLS_DB_TABLE_OPTIONS.'` ('.
219                 '`option_id` bigint(20) unsigned NOT NULL auto_increment,'.
220                 '`option_name` varchar(64) NOT NULL default "",'.
221                 '`option_value` longtext NOT NULL,'.
222                 'PRIMARY KEY  (`option_id`,`option_name`),'.
223                 'KEY `option_name` (`option_name`)'.
224                 ') AUTO_INCREMENT=1 ;';
225                 
226         $create_tables[YOURLS_DB_TABLE_LOG] = 
227                 'CREATE TABLE IF NOT EXISTS `'.YOURLS_DB_TABLE_LOG.'` ('.
228                 '`click_id` int(11) NOT NULL auto_increment,'.
229                 '`click_time` datetime NOT NULL,'.
230                 '`shorturl` varchar(200) BINARY NOT NULL,'.
231                 '`referrer` varchar(200) NOT NULL,'.
232                 '`user_agent` varchar(255) NOT NULL,'.
233                 '`ip_address` varchar(41) NOT NULL,'.
234                 '`country_code` char(2) NOT NULL,'.
235                 'PRIMARY KEY  (`click_id`),'.
236                 'KEY `shorturl` (`shorturl`)'.
237                 ') AUTO_INCREMENT=1 ;';
238
239
240         $create_table_count = 0;
241         
242         $ydb->show_errors = true;
243         
244         // Create tables
245         foreach ( $create_tables as $table_name => $table_query ) {
246                 $ydb->query( $table_query );
247                 $create_success = $ydb->query( "SHOW TABLES LIKE '$table_name'" );
248                 if( $create_success ) {
249                         $create_table_count++;
250                         $success_msg[] = yourls_s( "Table '%s' created.", $table_name ); 
251                 } else {
252                         $error_msg[] = yourls_s( "Error creating table '%s'.", $table_name ); 
253                 }
254         }
255                 
256         // Initializes the option table
257         if( !yourls_initialize_options() )
258                 $error_msg[] = yourls__( 'Could not initialize options' );
259         
260         // Insert sample links
261         if( !yourls_insert_sample_links() )
262                 $error_msg[] = yourls__( 'Could not insert sample short URLs' );
263         
264         // Check results of operations
265         if ( sizeof( $create_tables ) == $create_table_count ) {
266                 $success_msg[] = yourls__( 'YOURLS tables successfully created.' );
267         } else {
268                 $error_msg[] = yourls__( 'Error creating YOURLS tables.' ); 
269         }
270
271         return array( 'success' => $success_msg, 'error' => $error_msg );
272 }
273
274 /**
275  * Initializes the option table
276  *
277  * Each yourls_update_option() returns either true on success (option updated) or false on failure (new value == old value, or 
278  * for some reason it could not save to DB).
279  * Since true & true & true = 1, we cast it to boolean type to return true (or false)
280  *
281  * @since 1.7
282  * @return bool
283  */
284 function yourls_initialize_options() {
285         return ( bool ) (
286                   yourls_update_option( 'version', YOURLS_VERSION )
287                 & yourls_update_option( 'db_version', YOURLS_DB_VERSION )
288                 & yourls_update_option( 'next_id', 1 )
289         );
290 }
291
292 /**
293  * Populates the URL table with a few sample links
294  *
295  * @since 1.7
296  * @return bool
297  */
298 function yourls_insert_sample_links() {
299         $link1 = yourls_add_new_link( 'http://blog.yourls.org/', 'yourlsblog', 'YOURLS\' Blog' );
300         $link2 = yourls_add_new_link( 'http://yourls.org/',      'yourls',     'YOURLS: Your Own URL Shortener' );
301         $link3 = yourls_add_new_link( 'http://ozh.org/',         'ozh',        'ozh.org' );
302         return ( bool ) ( 
303                   $link1['status'] == 'success'
304                 & $link2['status'] == 'success'
305                 & $link3['status'] == 'success'
306         );
307 }
308
309
310 /**
311  * Toggle maintenance mode. Inspired from WP. Returns true for success, false otherwise
312  *
313  */
314 function yourls_maintenance_mode( $maintenance = true ) {
315
316         $file = YOURLS_ABSPATH . '/.maintenance' ;
317
318         // Turn maintenance mode on : create .maintenance file
319         if ( (bool)$maintenance ) {
320                 if ( ! ( $fp = @fopen( $file, 'w' ) ) )
321                         return false;
322                 
323                 $maintenance_string = '<?php $maintenance_start = ' . time() . '; ?>';
324                 @fwrite( $fp, $maintenance_string );
325                 @fclose( $fp );
326                 @chmod( $file, 0644 ); // Read and write for owner, read for everybody else
327
328                 // Not sure why the fwrite would fail if the fopen worked... Just in case
329                 return( is_readable( $file ) );
330                 
331         // Turn maintenance mode off : delete the .maintenance file
332         } else {
333                 return @unlink($file);
334         }
335 }