[ Index ]

PHP Cross Reference of YOURLS

title

Body

[close]

/includes/ -> functions-install.php (source)

   1  <?php
   2  
   3  /**
   4   * Check if we have PDO installed, returns bool
   5   *
   6   * @since 1.7.3
   7   * @return bool
   8   */
   9  function yourls_check_PDO() {
  10      return extension_loaded('pdo');
  11  }
  12  
  13  /**
  14   * Check if server has MySQL 5.0+
  15   *
  16   * @return bool
  17   */
  18  function yourls_check_database_version() {
  19      return ( version_compare( '5.0', yourls_get_database_version() ) <= 0 );
  20  }
  21  
  22  /**
  23   * Get DB version
  24   *
  25   * @since 1.7
  26   * @return string sanitized DB version
  27   */
  28  function yourls_get_database_version() {
  29      // Allow plugins to short-circuit the whole function
  30      $pre = yourls_apply_filter( 'shunt_get_database_version', false );
  31      if ( false !== $pre ) {
  32          return $pre;
  33      }
  34  
  35      return yourls_sanitize_version(yourls_get_db()->mysql_version());
  36  }
  37  
  38  /**
  39   * Check if PHP > 7.2
  40   *
  41   * As of 1.8 we advertise YOURLS as being 7.4+ but it should work on 7.2 (although untested)
  42   * so we don't want to strictly enforce a limitation that may not be necessary.
  43   *
  44   * @return bool
  45   */
  46  function yourls_check_php_version() {
  47      return version_compare( PHP_VERSION, '7.2.0', '>=' );
  48  }
  49  
  50  /**
  51   * Check if server is an Apache
  52   *
  53   * @return bool
  54   */
  55  function yourls_is_apache() {
  56      if( !array_key_exists( 'SERVER_SOFTWARE', $_SERVER ) )
  57          return false;
  58      return (
  59         strpos( $_SERVER['SERVER_SOFTWARE'], 'Apache' ) !== false
  60      || strpos( $_SERVER['SERVER_SOFTWARE'], 'LiteSpeed' ) !== false
  61      );
  62  }
  63  
  64  /**
  65   * Check if server is running IIS
  66   *
  67   * @return bool
  68   */
  69  function yourls_is_iis() {
  70      return ( array_key_exists( 'SERVER_SOFTWARE', $_SERVER ) ? ( strpos( $_SERVER['SERVER_SOFTWARE'], 'IIS' ) !== false ) : false );
  71  }
  72  
  73  
  74  /**
  75   * Create .htaccess or web.config. Returns boolean
  76   *
  77   * @return bool
  78   */
  79  function yourls_create_htaccess() {
  80      $host = parse_url( yourls_get_yourls_site() );
  81      $path = ( isset( $host['path'] ) ? $host['path'] : '' );
  82  
  83      if ( yourls_is_iis() ) {
  84          // Prepare content for a web.config file
  85          $content = array(
  86              '<?'.'xml version="1.0" encoding="UTF-8"?>',
  87              '<configuration>',
  88              '    <system.webServer>',
  89              '        <security>',
  90              '            <requestFiltering allowDoubleEscaping="true" />',
  91              '        </security>',
  92              '        <rewrite>',
  93              '            <rules>',
  94              '                <rule name="YOURLS" stopProcessing="true">',
  95              '                    <match url="^(.*)$" ignoreCase="false" />',
  96              '                    <conditions>',
  97              '                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />',
  98              '                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />',
  99              '                    </conditions>',
 100              '                    <action type="Rewrite" url="'.$path.'/yourls-loader.php" appendQueryString="true" />',
 101              '                </rule>',
 102              '            </rules>',
 103              '        </rewrite>',
 104              '    </system.webServer>',
 105              '</configuration>',
 106          );
 107  
 108          $filename = YOURLS_ABSPATH.'/web.config';
 109          $marker = 'none';
 110  
 111      } else {
 112          // Prepare content for a .htaccess file
 113          $content = array(
 114              '<IfModule mod_rewrite.c>',
 115              'RewriteEngine On',
 116              'RewriteBase '.$path.'/',
 117              'RewriteCond %{REQUEST_FILENAME} !-f',
 118              'RewriteCond %{REQUEST_FILENAME} !-d',
 119              'RewriteRule ^.*$ '.$path.'/yourls-loader.php [L]',
 120              '</IfModule>',
 121          );
 122  
 123          $filename = YOURLS_ABSPATH.'/.htaccess';
 124          $marker = 'YOURLS';
 125  
 126      }
 127  
 128      return ( yourls_insert_with_markers( $filename, $marker, $content ) );
 129  }
 130  
 131  /**
 132   * Insert text into a file between BEGIN/END markers, return bool. Stolen from WP
 133   *
 134   * Inserts an array of strings into a file (eg .htaccess ), placing it between
 135   * BEGIN and END markers. Replaces existing marked info. Retains surrounding
 136   * data. Creates file if none exists.
 137   *
 138   * @since 1.3
 139   *
 140   * @param string $filename
 141   * @param string $marker
 142   * @param array  $insertion
 143   * @return bool True on write success, false on failure.
 144   */
 145  function yourls_insert_with_markers( $filename, $marker, $insertion ) {
 146      if ( !file_exists( $filename ) || is_writeable( $filename ) ) {
 147          if ( !file_exists( $filename ) ) {
 148              $markerdata = '';
 149          } else {
 150              $markerdata = explode( "\n", implode( '', file( $filename ) ) );
 151          }
 152  
 153          if ( !$f = @fopen( $filename, 'w' ) )
 154              return false;
 155  
 156          $foundit = false;
 157          if ( $markerdata ) {
 158              $state = true;
 159              foreach ( $markerdata as $n => $markerline ) {
 160                  if ( strpos( $markerline, '# BEGIN ' . $marker ) !== false )
 161                      $state = false;
 162                  if ( $state ) {
 163                      if ( $n + 1 < count( $markerdata ) )
 164                          fwrite( $f, "{$markerline}\n" );
 165                      else
 166                          fwrite( $f, "{$markerline}" );
 167                  }
 168                  if ( strpos( $markerline, '# END ' . $marker ) !== false ) {
 169                      if ( $marker != 'none' )
 170                          fwrite( $f, "# BEGIN {$marker}\n" );
 171                      if ( is_array( $insertion ) )
 172                          foreach ( $insertion as $insertline )
 173                              fwrite( $f, "{$insertline}\n" );
 174                      if ( $marker != 'none' )
 175                          fwrite( $f, "# END {$marker}\n" );
 176                      $state = true;
 177                      $foundit = true;
 178                  }
 179              }
 180          }
 181          if ( !$foundit ) {
 182              if ( $marker != 'none' )
 183                  fwrite( $f, "\n\n# BEGIN {$marker}\n" );
 184              foreach ( $insertion as $insertline )
 185                  fwrite( $f, "{$insertline}\n" );
 186              if ( $marker != 'none' )
 187                  fwrite( $f, "# END {$marker}\n\n" );
 188          }
 189          fclose( $f );
 190          return true;
 191      } else {
 192          return false;
 193      }
 194  }
 195  
 196  /**
 197   * Create MySQL tables. Return array( 'success' => array of success strings, 'errors' => array of error strings )
 198   *
 199   * @since 1.3
 200   * @return array  An array like array( 'success' => array of success strings, 'errors' => array of error strings )
 201   */
 202  function yourls_create_sql_tables() {
 203      // Allow plugins (most likely a custom db.php layer in user dir) to short-circuit the whole function
 204      $pre = yourls_apply_filter( 'shunt_yourls_create_sql_tables', null );
 205      // your filter function should return an array of ( 'success' => $success_msg, 'error' => $error_msg ), see below
 206      if ( null !== $pre ) {
 207          return $pre;
 208      }
 209  
 210      $ydb = yourls_get_db();
 211  
 212      $error_msg = array();
 213      $success_msg = array();
 214  
 215      // Create Table Query
 216      $create_tables = array();
 217      $create_tables[YOURLS_DB_TABLE_URL] =
 218          'CREATE TABLE IF NOT EXISTS `'.YOURLS_DB_TABLE_URL.'` ('.
 219           '`keyword` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT "",'.
 220           '`url` text CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,'.
 221           '`title` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,'.
 222           '`timestamp` timestamp NOT NULL DEFAULT current_timestamp(),'.
 223           '`ip` varchar(41) COLLATE utf8mb4_unicode_ci NOT NULL,'.
 224           '`clicks` int(10) unsigned NOT NULL,'.
 225           'PRIMARY KEY (`keyword`),'.
 226           'KEY `ip` (`ip`),'.
 227           'KEY `timestamp` (`timestamp`)'.
 228          ') DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;';
 229  
 230      $create_tables[YOURLS_DB_TABLE_OPTIONS] =
 231          'CREATE TABLE IF NOT EXISTS `'.YOURLS_DB_TABLE_OPTIONS.'` ('.
 232          '`option_id` bigint(20) unsigned NOT NULL auto_increment,'.
 233          '`option_name` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL default "",'.
 234          '`option_value` longtext COLLATE utf8mb4_unicode_ci NOT NULL,'.
 235          'PRIMARY KEY  (`option_id`,`option_name`),'.
 236          'KEY `option_name` (`option_name`)'.
 237          ') AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;';
 238  
 239      $create_tables[YOURLS_DB_TABLE_LOG] =
 240          'CREATE TABLE IF NOT EXISTS `'.YOURLS_DB_TABLE_LOG.'` ('.
 241          '`click_id` int(11) NOT NULL auto_increment,'.
 242          '`click_time` datetime NOT NULL,'.
 243          '`shorturl` varchar(100) BINARY NOT NULL,'.
 244          '`referrer` varchar(200) NOT NULL,'.
 245          '`user_agent` varchar(255) NOT NULL,'.
 246          '`ip_address` varchar(41) NOT NULL,'.
 247          '`country_code` char(2) NOT NULL,'.
 248          'PRIMARY KEY  (`click_id`),'.
 249          'KEY `shorturl` (`shorturl`)'.
 250          ') AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;';
 251  
 252  
 253      $create_table_count = 0;
 254  
 255      yourls_debug_mode(true);
 256  
 257      // Create tables
 258      foreach ( $create_tables as $table_name => $table_query ) {
 259          $ydb->perform( $table_query );
 260          $create_success = $ydb->fetchAffected( "SHOW TABLES LIKE '$table_name'" );
 261          if( $create_success ) {
 262              $create_table_count++;
 263              $success_msg[] = yourls_s( "Table '%s' created.", $table_name );
 264          } else {
 265              $error_msg[] = yourls_s( "Error creating table '%s'.", $table_name );
 266          }
 267      }
 268  
 269      // Initializes the option table
 270      if( !yourls_initialize_options() )
 271          $error_msg[] = yourls__( 'Could not initialize options' );
 272  
 273      // Insert sample links
 274      if( !yourls_insert_sample_links() )
 275          $error_msg[] = yourls__( 'Could not insert sample short URLs' );
 276  
 277      // Check results of operations
 278      if ( sizeof( $create_tables ) == $create_table_count ) {
 279          $success_msg[] = yourls__( 'YOURLS tables successfully created.' );
 280      } else {
 281          $error_msg[] = yourls__( 'Error creating YOURLS tables.' );
 282      }
 283  
 284      return array( 'success' => $success_msg, 'error' => $error_msg );
 285  }
 286  
 287  /**
 288   * Initializes the option table
 289   *
 290   * Each yourls_update_option() returns either true on success (option updated) or false on failure (new value == old value, or
 291   * for some reason it could not save to DB).
 292   * Since true & true & true = 1, we cast it to boolean type to return true (or false)
 293   *
 294   * @since 1.7
 295   * @return bool
 296   */
 297  function yourls_initialize_options() {
 298      return ( bool ) (
 299            yourls_update_option( 'version', YOURLS_VERSION )
 300          & yourls_update_option( 'db_version', YOURLS_DB_VERSION )
 301          & yourls_update_option( 'next_id', 1 )
 302          & yourls_update_option( 'active_plugins', array() )
 303      );
 304  }
 305  
 306  /**
 307   * Populates the URL table with a few sample links
 308   *
 309   * @since 1.7
 310   * @return bool
 311   */
 312  function yourls_insert_sample_links() {
 313      $link1 = yourls_add_new_link( 'https://blog.yourls.org/', 'yourlsblog', 'YOURLS\' Blog' );
 314      $link2 = yourls_add_new_link( 'https://yourls.org/',      'yourls',     'YOURLS: Your Own URL Shortener' );
 315      $link3 = yourls_add_new_link( 'https://ozh.org/',         'ozh',        'ozh.org' );
 316      return ( bool ) (
 317            $link1['status'] == 'success'
 318          & $link2['status'] == 'success'
 319          & $link3['status'] == 'success'
 320      );
 321  }
 322  
 323  
 324  /**
 325   * Toggle maintenance mode. Inspired from WP. Returns true for success, false otherwise
 326   *
 327   * @param bool $maintenance  True to enable, false to disable
 328   * @return bool              True on success, false on failure
 329   */
 330  function yourls_maintenance_mode( $maintenance = true ) {
 331  
 332      $file = YOURLS_ABSPATH . '/.maintenance' ;
 333  
 334      // Turn maintenance mode on : create .maintenance file
 335      if ( (bool)$maintenance ) {
 336          if ( ! ( $fp = @fopen( $file, 'w' ) ) )
 337              return false;
 338  
 339          $maintenance_string = '<?php $maintenance_start = ' . time() . '; ?>';
 340          @fwrite( $fp, $maintenance_string );
 341          @fclose( $fp );
 342          @chmod( $file, 0644 ); // Read and write for owner, read for everybody else
 343  
 344          // Not sure why the fwrite would fail if the fopen worked... Just in case
 345          return( is_readable( $file ) );
 346  
 347      // Turn maintenance mode off : delete the .maintenance file
 348      } else {
 349          return @unlink($file);
 350      }
 351  }


Generated: Wed Sep 18 05:10:18 2024 Cross-referenced by PHPXref 0.7.1