From d577f790c8cbcf4f8dce74f9991e4bd62e21f949 Mon Sep 17 00:00:00 2001
From: Tobias Ramforth <tobias@ramforth.com>
Date: Fri, 8 Feb 2013 00:00:51 +0100
Subject: [PATCH] Added MS SQL Server support

---
 core/js/setup.js                |   7 ++
 core/setup.php                  |   2 +
 core/templates/installation.php |  20 +++-
 lib/db.php                      | 180 +++++++++++++++++++++++++++++++-
 lib/setup.php                   | 148 +++++++++++++++++++++++++-
 5 files changed, 346 insertions(+), 11 deletions(-)

diff --git a/core/js/setup.js b/core/js/setup.js
index 9aded6591ca..fb6e7c5097c 100644
--- a/core/js/setup.js
+++ b/core/js/setup.js
@@ -5,6 +5,7 @@ $(document).ready(function() {
 		mysql:!!$('#hasMySQL').val(),
 		postgresql:!!$('#hasPostgreSQL').val(),
 		oracle:!!$('#hasOracle').val(),
+        mssql:!!$('#hasMSSQL').val()
 	};
 	
 	$('#selectDbType').buttonset();
@@ -41,6 +42,12 @@ $(document).ready(function() {
 		$('#dbhost').show(250);
 		$('#dbhostlabel').show(250);
 	});
+    
+    $('#mssql').click(function() {
+		$('#use_other_db').slideDown(250);
+		$('#dbhost').show(250);
+		$('#dbhostlabel').show(250);
+	});
 
 	$('input[checked]').trigger('click');
 
diff --git a/core/setup.php b/core/setup.php
index 66b8cf378bd..0da9b35a35a 100644
--- a/core/setup.php
+++ b/core/setup.php
@@ -16,6 +16,7 @@ $hasSQLite = class_exists('SQLite3');
 $hasMySQL = is_callable('mysql_connect');
 $hasPostgreSQL = is_callable('pg_connect');
 $hasOracle = is_callable('oci_connect');
+$hasMSSQL = is_callable('sqlsrv_connect');
 $datadir = OC_Config::getValue('datadirectory', OC::$SERVERROOT.'/data');
 
 // Protect data directory here, so we can test if the protection is working
@@ -26,6 +27,7 @@ $opts = array(
 	'hasMySQL' => $hasMySQL,
 	'hasPostgreSQL' => $hasPostgreSQL,
 	'hasOracle' => $hasOracle,
+    'hasMSSQLServer' => $hasMSSQL,
 	'directory' => $datadir,
 	'secureRNG' => OC_Util::secureRNG_available(),
 	'htaccessWorking' => OC_Util::ishtaccessworking(),
diff --git a/core/templates/installation.php b/core/templates/installation.php
index 03c580c9b0b..6a6370785d3 100644
--- a/core/templates/installation.php
+++ b/core/templates/installation.php
@@ -2,6 +2,7 @@
 <input type='hidden' id='hasSQLite' value='<?php echo $_['hasSQLite'] ?>'>
 <input type='hidden' id='hasPostgreSQL' value='<?php echo $_['hasPostgreSQL'] ?>'>
 <input type='hidden' id='hasOracle' value='<?php echo $_['hasOracle'] ?>'>
+<input type='hidden' id='hasMSSQL' value='<?php echo $_['hasMSSQL'] ?>'>
 <form action="index.php" method="post">
 <input type="hidden" name="install" value="true" />
 	<?php if(count($_['errors']) > 0): ?>
@@ -55,7 +56,7 @@
 	</fieldset>
 
 	<fieldset id='databaseField'>
-		<?php if($_['hasMySQL'] or $_['hasPostgreSQL'] or $_['hasOracle']) $hasOtherDB = true; else $hasOtherDB =false; //other than SQLite ?>
+		<?php if($_['hasMySQL'] or $_['hasPostgreSQL'] or $_['hasOracle'] or $_['hasMSSQL']) $hasOtherDB = true; else $hasOtherDB =false; //other than SQLite ?>
 		<legend><?php echo $l->t( 'Configure the database' ); ?></legend>
 		<div id="selectDbType">
 		<?php if($_['hasSQLite']): ?>
@@ -71,7 +72,7 @@
 
 		<?php if($_['hasMySQL']): ?>
 		<input type='hidden' id='hasMySQL' value='true'/>
-		<?php if(!$_['hasSQLite'] and !$_['hasPostgreSQL'] and !$_['hasOracle']): ?>
+		<?php if(!$_['hasSQLite'] and !$_['hasPostgreSQL'] and !$_['hasOracle'] and !$_['hasMSSQL']): ?>
 		<p>MySQL <?php echo $l->t( 'will be used' ); ?>.</p>
 		<input type="hidden" id="dbtype" name="dbtype" value="mysql" />
 		<?php else: ?>
@@ -81,7 +82,7 @@
 		<?php endif; ?>
 
 		<?php if($_['hasPostgreSQL']): ?>
-		<?php if(!$_['hasSQLite'] and !$_['hasMySQL'] and !$_['hasOracle']): ?>
+		<?php if(!$_['hasSQLite'] and !$_['hasMySQL'] and !$_['hasOracle'] and !$_['hasMSSQL']): ?>
 		<p>PostgreSQL <?php echo $l->t( 'will be used' ); ?>.</p>
 		<input type="hidden" id="dbtype" name="dbtype" value="pgsql" />
 		<?php else: ?>
@@ -91,7 +92,7 @@
 		<?php endif; ?>
 
 		<?php if($_['hasOracle']): ?>
-		<?php if(!$_['hasSQLite'] and !$_['hasMySQL'] and !$_['hasPostgreSQL']): ?>
+		<?php if(!$_['hasSQLite'] and !$_['hasMySQL'] and !$_['hasPostgreSQL'] and !$_['hasMSSQL']): ?>
 		<p>Oracle <?php echo $l->t( 'will be used' ); ?>.</p>
 		<input type="hidden" id="dbtype" name="dbtype" value="oci" />
 		<?php else: ?>
@@ -99,6 +100,17 @@
 		<input type="radio" name="dbtype" value='oci' id="oci" <?php OC_Helper::init_radio('dbtype', 'oci', 'sqlite'); ?>/>
 		<?php endif; ?>
 		<?php endif; ?>
+        
+		<?php if($_['hasMSSQL']): ?>
+		<input type='hidden' id='hasMSSQL' value='true'/>
+		<?php if(!$_['hasSQLite'] and !$_['hasMySQL'] and !$_['hasPostgreSQL'] and !$_['hasOracle']): ?>
+		<p>MS SQL <?php echo $l->t( 'will be used' ); ?>.</p>
+		<input type="hidden" id="dbtype" name="dbtype" value="mssql" />
+		<?php else: ?>
+        <label class="mssql" for="mssql">MS SQL</label>
+		<input type="radio" name="dbtype" value='mssql' id="mssql" <?php OC_Helper::init_radio('dbtype', 'mssql', 'sqlite'); ?>/>
+		<?php endif; ?>
+		<?php endif; ?>        
 		</div>
 
 		<?php if($hasOtherDB): ?>
diff --git a/lib/db.php b/lib/db.php
index 51f7c7679d4..58f46c1171f 100644
--- a/lib/db.php
+++ b/lib/db.php
@@ -178,6 +178,13 @@ class OC_DB {
 							$dsn = 'oci:dbname=//' . $host . '/' . $name;
 					}
 					break;
+                case 'mssql':
+					if ($port) {
+							$dsn='sqlsrv:Server='.$host.','.$port.';Database='.$name;
+					} else {
+							$dsn='sqlsrv:Server='.$host.';Database='.$name;
+					}
+					break;                    
 				default:
 					return false;
 			}
@@ -277,6 +284,15 @@ class OC_DB {
 						$dsn['database'] = $user;
 					}
 					break;
+                case 'mssql':
+					$dsn = array(
+						'phptype' => 'sqlsrv',
+						'username' => $user,
+						'password' => $pass,
+						'hostspec' => $host,
+						'database' => $name
+					);                    
+                    break;
 				default:
 					return false;
 			}
@@ -540,7 +556,7 @@ class OC_DB {
 		 * http://www.sqlite.org/lang_createtable.html
 		 * http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions037.htm
 		 */
-		if( $CONFIG_DBTYPE == 'pgsql' ) { //mysql support it too but sqlite doesn't
+		if( $CONFIG_DBTYPE == 'pgsql' || 'mssql') { //mysql support it too but sqlite doesn't
 			$content = str_replace( '<default>0000-00-00 00:00:00</default>', '<default>CURRENT_TIMESTAMP</default>', $content );
 		}
 		file_put_contents( $file2, $content );
@@ -624,7 +640,7 @@ class OC_DB {
 			} else {
 				return true;
 			}
-		} elseif( $type == 'pgsql' || $type == 'oci' || $type == 'mysql') {
+		} elseif( $type == 'pgsql' || $type == 'oci' || $type == 'mysql' || $type == 'mssql') {
 			$query = 'INSERT INTO `' .$table . '` ('
 				. implode(',', array_keys($input)) . ') SELECT \''
 				. implode('\',\'', array_values($input)) . '\' FROM ' . $table . ' WHERE ';
@@ -683,7 +699,15 @@ class OC_DB {
 		}elseif( $type == 'oci'  ) {
 			$query = str_replace( '`', '"', $query );
 			$query = str_ireplace( 'NOW()', 'CURRENT_TIMESTAMP', $query );
-		}
+		}elseif( $type == 'mssql' ) {
+			$query = preg_replace( "/\`(.*?)`/", "[$1]", $query );
+			$query = str_replace( 'NOW()', 'CURRENT_TIMESTAMP', $query );
+			$query = str_replace( 'now()', 'CURRENT_TIMESTAMP', $query );
+			$query = str_replace( 'LENGTH(', 'LEN(', $query );
+			$query = str_replace( 'SUBSTR(', 'SUBSTRING(', $query );
+            
+            $query = self::fixLimitClauseForMSSQL($query);
+        }
 
 		// replace table name prefix
 		$query = str_replace( '*PREFIX*', $prefix, $query );
@@ -691,6 +715,60 @@ class OC_DB {
 		return $query;
 	}
 
+    private static function fixLimitClauseForMSSQL($query) {
+        $limitLocation = stripos ($query, "LIMIT");
+        
+        if ( $limitLocation === false ) {
+            return $query;
+        } 
+        
+        // total == 0 means all results - not zero results
+        //
+        // First number is either total or offset, locate it by first space
+        //
+        $offset = substr ($query, $limitLocation + 5);
+        $offset = substr ($offset, 0, stripos ($offset, ' '));
+        $offset = trim ($offset);
+
+        // check for another parameter
+        if (stripos ($offset, ',') === false) {
+            // no more parameters
+            $offset = 0;
+            $total = intval ($offset);
+        } else {
+            // found another parameter
+            $offset = intval ($offset);
+
+            $total = substr ($query, $limitLocation + 5);
+            $total = substr ($total, stripos ($total, ','));
+
+            $total = substr ($total, 0, stripos ($total, ' '));
+            $total = intval ($total);
+        }
+
+        $query = trim (substr ($query, 0, $limitLocation));
+
+        if ($offset == 0 && $total !== 0) {
+            if (strpos($query, "SELECT") === false) {
+                $query = "TOP {$total} " . $query;
+            } else {
+                $query = preg_replace('/SELECT(\s*DISTINCT)?/Dsi', 'SELECT$1 TOP '.$total, $query);
+            }
+        } else if ($offset > 0) {
+            $query = preg_replace('/SELECT(\s*DISTINCT)?/Dsi', 'SELECT$1 TOP(10000000) ', $query);
+            $query = 'SELECT *
+                    FROM (SELECT sub2.*, ROW_NUMBER() OVER(ORDER BY sub2.line2) AS line3
+                    FROM (SELECT 1 AS line2, sub1.* FROM (' . $query . ') AS sub1) as sub2) AS sub3';
+
+            if ($total > 0) {
+                $query .= ' WHERE line3 BETWEEN ' . ($offset + 1) . ' AND ' . ($offset + $total);
+            } else {
+                $query .= ' WHERE line3 > ' . $offset;
+            }
+        }
+        return $query;
+    }
+    
 	/**
 	 * @brief drop a table
 	 * @param string $tableName the table to drop
@@ -844,6 +922,14 @@ class PDOStatementWrapper{
 	public function execute($input=array()) {
 		$this->lastArguments=$input;
 		if(count($input)>0) {
+            if (!isset($type)) {
+                $type = OC_Config::getValue( "dbtype", "sqlite" );
+            }
+            
+            if ($type == 'mssql') {
+                $this->tryFixSubstringLastArgumentDataForMSSQL($input);
+            }
+            
 			$result=$this->statement->execute($input);
 		}else{
 			$result=$this->statement->execute();
@@ -855,6 +941,94 @@ class PDOStatementWrapper{
 		}
 	}
 
+    private function tryFixSubstringLastArgumentDataForMSSQL(&$input) {
+        $query = $this->statement->queryString;
+        $pos = stripos ($query, 'SUBSTRING');
+                
+        if ( $pos === false) {
+            return;
+        }
+        
+        try {
+            $newQuery = '';
+
+            $cArg = 0;
+
+            $inSubstring = false;
+
+            // Create new query
+            for ($i = 0; $i < strlen ($query); $i++) {
+                if ($inSubstring == false) {
+                    // Defines when we should start inserting values
+                    if (substr ($query, $i, 9) == 'SUBSTRING') {
+                        $inSubstring = true;
+                    }
+                } else {
+                    // Defines when we should stop inserting values
+                    if (substr ($query, $i, 1) == ')') {
+                        $inSubstring = false;
+                    }
+                }
+
+                if (substr ($query, $i, 1) == '?') {
+                    // We found a question mark
+                    if ($inSubstring) {
+                        $newQuery .= $input[$cArg];
+
+                        //
+                        // Remove from input array
+                        //
+                        array_splice ($input, $cArg, 1);
+                    } else {
+                        $newQuery .= substr ($query, $i, 1);
+                        $cArg++;
+                    }
+                } else {
+                    $newQuery .= substr ($query, $i, 1);
+                }
+            }
+
+            // The global data we need
+            $name = OC_Config::getValue( "dbname", "owncloud" );
+            $host = OC_Config::getValue( "dbhost", "" );
+            $user = OC_Config::getValue( "dbuser", "" );
+            $pass = OC_Config::getValue( "dbpassword", "" );
+            if (strpos($host,':')) {
+                list($host, $port) = explode(':', $host, 2);
+            } else {
+                $port = false;
+            }
+            $opts = array();
+
+            if ($port) {
+                $dsn = 'sqlsrv:Server='.$host.','.$port.';Database='.$name;
+            } else {
+                $dsn = 'sqlsrv:Server='.$host.';Database='.$name;
+            }
+
+            $PDO = new PDO($dsn, $user, $pass, $opts);
+            $PDO->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
+            $PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
+
+            $this->statement = $PDO->prepare($newQuery);
+
+            $this->lastArguments = $input;
+        } catch (PDOException $e){
+			$entry = 'PDO DB Error: "'.$e->getMessage().'"<br />';
+			$entry .= 'Offending command was: '.$this->statement->queryString .'<br />';
+			$entry .= 'Input parameters: ' .print_r($input, true).'<br />';
+			$entry .= 'Stack trace: ' .$e->getTraceAsString().'<br />';
+			OC_Log::write('core', $entry, OC_Log::FATAL);
+    		OC_User::setUserId(null);
+
+            // send http status 503
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
+            header('Status: 503 Service Temporarily Unavailable');
+            OC_Template::printErrorPage('Failed to connect to database');
+            die ($entry);
+		}
+    }
+    
 	/**
 	 * provide numRows
 	 */
diff --git a/lib/setup.php b/lib/setup.php
index 4dd190b99fb..d4ea26354ef 100644
--- a/lib/setup.php
+++ b/lib/setup.php
@@ -33,12 +33,14 @@ class OC_Setup {
 			$error[] = 'Specify a data folder.';
 		}
 
-		if($dbtype=='mysql' or $dbtype == 'pgsql' or $dbtype == 'oci') { //mysql and postgresql needs more config options
-			if($dbtype=='mysql')
+		if($dbtype == 'mysql' or $dbtype == 'pgsql' or $dbtype == 'oci' or $dbtype == 'mssql') { //mysql and postgresql needs more config options
+			if($dbtype == 'mysql')
 				$dbprettyname = 'MySQL';
-			else if($dbtype=='pgsql')
+			else if($dbtype == 'pgsql')
 				$dbprettyname = 'PostgreSQL';
-			else
+			else if ($dbtype == 'mssql')
+                $dbprettyname = 'MS SQL Server';
+            else
 				$dbprettyname = 'Oracle';
 
 
@@ -145,6 +147,29 @@ class OC_Setup {
 					return $error;
 				}
 			}
+            elseif ($dbtype == 'mssql') {
+				$dbuser = $options['dbuser'];
+				$dbpass = $options['dbpass'];
+				$dbname = $options['dbname'];
+				$dbhost = $options['dbhost'];
+				$dbtableprefix = isset($options['dbtableprefix']) ? $options['dbtableprefix'] : 'oc_';
+				
+				OC_Config::setValue('dbname', $dbname);
+				OC_Config::setValue('dbhost', $dbhost);
+				OC_Config::setValue('dbuser', $dbuser);
+				OC_Config::setValue('dbpassword', $dbpass);
+				OC_Config::setValue('dbtableprefix', $dbtableprefix);
+
+				try {
+					self::setupMSSQLDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix);
+				} catch (Exception $e) {
+					$error[] = array(
+						'error' => 'MS SQL username and/or password not valid',
+						'hint' => 'You need to enter either an existing account or the administrator.'
+					);
+					return $error;
+				}
+            }
 			else {
 				//delete the old sqlite database first, might cause infinte loops otherwise
 				if(file_exists("$datadir/owncloud.db")) {
@@ -563,6 +588,121 @@ class OC_Setup {
 		}
 	}
 
+	private static function setupMSSQLDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix) {
+		//check if the database user has admin right
+		$masterConnectionInfo = array( "Database" => "master", "UID" => $dbuser, "PWD" => $dbpass);
+		
+		$masterConnection = @sqlsrv_connect($dbhost, $masterConnectionInfo);
+		if(!$masterConnection) {
+                        $entry = null;
+                        if( ($errors = sqlsrv_errors() ) != null) {
+                            $entry='DB Error: "'.print_r(sqlsrv_errors()).'"<br />';
+                        } else {
+                            $entry = '';
+                        }
+			throw new Exception('MS SQL username and/or password not valid: '.$entry);
+		}
+
+		OC_Config::setValue('dbuser', $dbuser);
+		OC_Config::setValue('dbpassword', $dbpass);
+
+		self::mssql_createDBLogin($dbuser, $dbpass, $masterConnection);
+		
+		self::mssql_createDatabase($dbname, $masterConnection);
+		
+		self::mssql_createDBUser($dbuser, $dbpass, $masterConnection);
+
+		sqlsrv_close($masterConnection);
+
+		$connectionInfo = array( "Database" => $dbname, "UID" => $dbuser, "PWD" => $dbpass);
+
+        $connection = @sqlsrv_connect($dbhost, $connectionInfo);
+
+		//fill the database if needed
+		$query="SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{$dbname}' AND TABLE_NAME = '{$dbtableprefix}users'";
+		$result = sqlsrv_query($connection, $query);
+		if($result) {
+			$row=sqlsrv_fetch_array($result);
+		}
+		
+		if(!$result or $row[0] == 0) {
+			OC_DB::createDbFromStructure('db_structure.xml');
+		}
+		
+		sqlsrv_close($connection);
+	}    
+
+    private static function mssql_createDBLogin($name, $password, $connection) {
+		$query = "SELECT * FROM master.sys.server_principals WHERE name = '".$name."';";
+		$result = sqlsrv_query($connection, $query);
+		if ($result) {
+			$row = sqlsrv_fetch_array($result);
+		}
+		
+		if (!$result or $row[0] == 0) {
+			$query = "CREATE LOGIN [".$name."] WITH PASSWORD = '".$password."';";
+			$result = sqlsrv_query($connection, $query);
+			if (!$result or $result === false) {
+			    if ( ($errors = sqlsrv_errors() ) != null) {
+                    $entry='DB Error: "'.print_r(sqlsrv_errors()).'"<br />';
+			    } else {
+			    	$entry = '';
+			    }
+		    	$entry.='Offending command was: '.$query.'<br />';
+			    echo($entry);
+			}			
+		}
+	}
+
+	private static function mssql_createDBUser($name, $dbname, $connection) {
+		$query = "SELECT * FROM [".$dbname."].sys.database_principals WHERE name = '".$name."';";
+		$result = sqlsrv_query($connection, $query);
+		if($result) {
+			$row=sqlsrv_fetch_array($result);
+		}		
+		
+		if (!$result or $row[0] == 0) {
+			$query = "USE [".$dbname."]; CREATE USER [".$name."] FOR LOGIN [".$name."];";
+			$result = sqlsrv_query($connection, $query);
+			if (!$result or $result === false) {
+			    if ( ($errors = sqlsrv_errors() ) != null) {
+                    $entry='DB Error: "'.print_r(sqlsrv_errors()).'"<br />';
+			    } else {
+			    	$entry = '';
+			    }
+		    	$entry.='Offending command was: '.$query.'<br />';
+			    echo($entry);
+			}			
+		}
+		
+		$query = "USE [".$dbname."]; EXEC sp_addrolemember 'db_owner', '".$name."';";
+		$result = sqlsrv_query($connection, $query);
+		if (!$result or $result === false) {
+		    if ( ($errors = sqlsrv_errors() ) != null) {
+                $entry='DB Error: "'.print_r(sqlsrv_errors()).'"<br />';
+		    } else {
+		    	$entry = '';
+		    }
+	    	$entry.='Offending command was: '.$query.'<br />';
+		    echo($entry);
+		}
+	}
+	
+	private static function mssql_createDatabase($dbname, $connection) {
+		$query = "CREATE DATABASE [".$dbname."];";
+		$result = sqlsrv_query($connection, $query);
+		if (!$result or $result === false) {
+		    if ( ($errors = sqlsrv_errors() ) != null) {
+                $entry='DB Error: "'.print_r(sqlsrv_errors()).'"<br />';
+		    } else {
+		    	$entry = '';
+		    }
+	    	$entry.='Offending command was: '.$query.'<br />';
+		    echo($entry);
+		}
+	}    
+    
+    
 	/**
 	 * create .htaccess files for apache hosts
 	 */
-- 
GitLab