[ 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 server 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('read-get_database_version')->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('write-create_sql_tables');
 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           'KEY `url_idx` (`url`(30))'.
 229          ') DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;';
 230  
 231      $create_tables[YOURLS_DB_TABLE_OPTIONS] =
 232          'CREATE TABLE IF NOT EXISTS `'.YOURLS_DB_TABLE_OPTIONS.'` ('.
 233          '`option_id` bigint(20) unsigned NOT NULL auto_increment,'.
 234          '`option_name` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL default \'\','.
 235          '`option_value` longtext COLLATE utf8mb4_unicode_ci NOT NULL,'.
 236          'PRIMARY KEY  (`option_id`,`option_name`),'.
 237          'KEY `option_name` (`option_name`)'.
 238          ') AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;';
 239  
 240      $create_tables[YOURLS_DB_TABLE_LOG] =
 241          'CREATE TABLE IF NOT EXISTS `'.YOURLS_DB_TABLE_LOG.'` ('.
 242          '`click_id` int(11) NOT NULL auto_increment,'.
 243          '`click_time` datetime NOT NULL,'.
 244          '`shorturl` varchar(100) BINARY NOT NULL,'.
 245          '`referrer` varchar(200) NOT NULL,'.
 246          '`user_agent` varchar(255) NOT NULL,'.
 247          '`ip_address` varchar(41) NOT NULL,'.
 248          '`country_code` char(2) NOT NULL,'.
 249          'PRIMARY KEY  (`click_id`),'.
 250          'KEY `shorturl` (`shorturl`)'.
 251          ') AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;';
 252  
 253  
 254      $create_table_count = 0;
 255  
 256      yourls_debug_mode(true);
 257  
 258      // Create tables
 259      foreach ( $create_tables as $table_name => $table_query ) {
 260          $ydb->perform( $table_query );
 261          $create_success = $ydb->fetchAffected( "SHOW TABLES LIKE '$table_name'" );
 262          if( $create_success ) {
 263              $create_table_count++;
 264              $success_msg[] = yourls_s( "Table '%s' created.", $table_name );
 265          } else {
 266              $error_msg[] = yourls_s( "Error creating table '%s'.", $table_name );
 267          }
 268      }
 269  
 270      // Initializes the option table
 271      if( !yourls_initialize_options() )
 272          $error_msg[] = yourls__( 'Could not initialize options' );
 273  
 274      // Insert sample links
 275      if( !yourls_insert_sample_links() )
 276          $error_msg[] = yourls__( 'Could not insert sample short URLs' );
 277  
 278      // Check results of operations
 279      if ( sizeof( $create_tables ) == $create_table_count ) {
 280          $success_msg[] = yourls__( 'YOURLS tables successfully created.' );
 281      } else {
 282          $error_msg[] = yourls__( 'Error creating YOURLS tables.' );
 283      }
 284  
 285      return array( 'success' => $success_msg, 'error' => $error_msg );
 286  }
 287  
 288  /**
 289   * Initializes the option table
 290   *
 291   * Each yourls_update_option() returns either true on success (option updated) or false on failure (new value == old value, or
 292   * for some reason it could not save to DB).
 293   * Since true & true & true = 1, we cast it to boolean type to return true (or false)
 294   *
 295   * @since 1.7
 296   * @return bool
 297   */
 298  function yourls_initialize_options() {
 299      return ( bool ) (
 300            yourls_update_option( 'version', YOURLS_VERSION )
 301          & yourls_update_option( 'db_version', YOURLS_DB_VERSION )
 302          & yourls_update_option( 'next_id', 1 )
 303          & yourls_update_option( 'active_plugins', array() )
 304      );
 305  }
 306  
 307  /**
 308   * Populates the URL table with a few sample links
 309   *
 310   * @since 1.7
 311   * @return bool
 312   */
 313  function yourls_insert_sample_links() {
 314      $link1 = yourls_add_new_link( 'https://blog.yourls.org/', 'yourlsblog', 'YOURLS\' Blog' );
 315      $link2 = yourls_add_new_link( 'https://yourls.org/',      'yourls',     'YOURLS: Your Own URL Shortener' );
 316      $link3 = yourls_add_new_link( 'https://ozh.org/',         'ozh',        'ozh.org' );
 317      return ( bool ) (
 318            $link1['status'] == 'success'
 319          & $link2['status'] == 'success'
 320          & $link3['status'] == 'success'
 321      );
 322  }
 323  
 324  
 325  /**
 326   * Toggle maintenance mode. Inspired from WP. Returns true for success, false otherwise
 327   *
 328   * @param bool $maintenance  True to enable, false to disable
 329   * @return bool              True on success, false on failure
 330   */
 331  function yourls_maintenance_mode( $maintenance = true ) {
 332  
 333      $file = YOURLS_ABSPATH . '/.maintenance' ;
 334  
 335      // Turn maintenance mode on : create .maintenance file
 336      if ( (bool)$maintenance ) {
 337          if ( ! ( $fp = @fopen( $file, 'w' ) ) )
 338              return false;
 339  
 340          $maintenance_string = '<?php $maintenance_start = ' . time() . '; ?>';
 341          @fwrite( $fp, $maintenance_string );
 342          @fclose( $fp );
 343          @chmod( $file, 0644 ); // Read and write for owner, read for everybody else
 344  
 345          // Not sure why the fwrite would fail if the fopen worked... Just in case
 346          return( is_readable( $file ) );
 347  
 348      // Turn maintenance mode off : delete the .maintenance file
 349      } else {
 350          return @unlink($file);
 351      }
 352  }


Generated: Sat Jan 10 05:10:40 2026 Cross-referenced by PHPXref 0.7.1