Mount a FTP connection in your file system on Ubuntu

I was just looking for an easy and strict way to process files and directories via FTP (in a shell script) and stumbled over the CurlFtpFS, which allows you to mount an FTP connection as part of your file system. Extremely nice and elaborated solution these guys implemented. You can either mount it using sudo e.g. in /mnt/ftp/hostname or simply in your home directory, e.g. “~/ftp”. As Bob Ross used to say: “And it’s really that simple”.

Installation

sudo aptitude install curlftpfs

Mount

# Create a directory to have a mount point
mkdir ~/ftp

# To directly connect with username and password in the command line:
sudo curlftpfs username:password@host.or.domain ~/ftp

# If you want to type the password in the shell:
sudo curlftpfs -o user="username" host.or.domain ~/ftp

# To check if's mounted
mount
# You get a list that should include the line like:
#   curlftpfs#.... on ..../ftp type fuse (rw,nosuid,nodev,user=....)

Unnount

sudo umount ~/ftp

Annotation: I added sudo because you very likely cannot unmount the drive without root permissions, even not in your home folder.

Posted in Uncategorized | Tagged , , , , | Leave a comment

Boot camp with Windows 7 and a SSD

As not all programs are available on MacOS 10.7, you may want to install Windows 7 either on a virtual machine or, to get the whole performance of your machine, on a Boot Camp partition. As described in the last article, I switched to a Vertex 2 SSD, which is much faster then the HDD before, but provides with 240GB only half of the space compared to the replaced hard disk. As a very result, I didn’t want to waste space on a second partition that needs already more than 20GB for the operating system (we can forgive Steve Jobs that Lion has a similar disk usage, but for any reason we can’t forgive Steve Ballmer). So, 50GB was my choice for the Boot Camp partition, and the Windows 7 space had to be trimmed somehow. The major issue was to prevent that the disk usage grows too much after the installation (due to indexing, backups, shadow images, memory dumps etc). The updates will increase the required space enough anyway. Furthermore, SSDs and convendtional HDDs require different handling, e.g. SSD do not need to be defragmented. Here are the steps that helped me keeping the system clean and speedy. I hope it helps you, too. Note: Every change has its side effects, so checkout if you need a feature or not.

Cleanup and removing the disk shadow copy

A simple way of freeing space is to use the normal disk cleanup. This package also contains the functionality to remove a disk shadow copy.

  1. Go to START > Computer
  2. Right click on drive C:, select “Properties”
  3. Switch to tab “General” and click the “Disk Cleanup” button
  4. If the button “Cleanup system files” is shown, click it
  5. The tab “More options” should be visible, switch to it
  6. Under “System Restore and Shadow Copy”, click “Cleanup” and confirm the deletion

Disable Hybernation

Hybernation is principally a good thing. However, it has the side effect that a file is created, which contains the RAM state during hybernation. Depending on the RAM size, this preserves gigabytes of disk space (in my case a 1/6 of the disk space!), and the file is not deleted after hybernation. Disabling it is easy (the file will be automatically removed). Side effect: The system can only switch to sleep mode, which still requires battery. If latter is empty Windows would normally hybernate, but can’t. So it will either force a shutdown or just go off.

  1. Click START, search “cmd.exe”, and run it as admin (don’t hit RETURN, but right click on the found item “cmd.exe”)
  2. Enter “powercfg -h off” in the shell window

Disabling Indexing service

The indexing service is the Windows-Spotlight background task and uses disk space as well. Side effects: Finding programs and files still works, but more detailled searches, such as words in mails or PDFs does not work.

  1. Go START:, search for “services.msc”
  2. Locate “Windows Search Service”, right click: Properties
  3. Select “disabled” in the dropdown “Startup type”

Trimming page file size

The page file is the virtual memory and similar to the scratch partition. It can grow quite a lot. Side effects: You could run out out of memory. This never happend to me up to now, but if you use Software, which needs huge amount of RAM … well – could happen that the program crashes or throws an allocation error.

  1. Go START
  2. Right click on “Computer”, select “Properties” from menu
  3. Select “Advanced System Settings” on the left side menu
  4. Under “Performance”, click on the “settings” button
  5. Click the “Advanced tab”
  6. In section “Virtual memory” click on “Change”
  7. Uncheck “Automatically manage paging file size [...]“
  8. Click option “Custom size” enter “500″ under Initial size and what you want (e.g. 1000 for 1GB) for maximum size.

Disable System Restore

The System Restore Points are principally a good Idea, but they need space. Here how to disable this feature. Side effects: You don’t have a direct undo operation for your system setup (I use incremental network backups to get around this problem).

  1. Go START, search for “gpedit.msc” and hit return
  2. Browse to the folder “Local Computer Policy”/”Administrative Templates”/”Windows Components”/”Backup”/”Client”
  3. Double click “Turn off the ability to back up data files” and select the “enabled” option. (Yes, it is ENABLED), click OK
  4. Double click “Turn off restore functionality” and select the “enabled” option. Click OK
  5. Double click “Turn off the ability to create a system image” and select the “enabled” option. Click OK

Disable Defrag schedule

SSDs don’t need to be defragmented, indeed it is a waste of resources and decreases the life time unnecessarily.

  1. Go to START/All Programs/Accessories/System Tools/Disk Defragmenter
  2. Click the “Configure Schedule” button
  3. Untick the checkbox “Run on a schedule (recommended)”

Disable MacOS X partition visibility

If you don’t want that windows programs can access your Mac partition, you can unassign its drive letter. This is not a “really secure security feature”, but it should help a bit, because admin permissions are required to reassign a drive letter.

  1. Click START, search for “Administrative Tools”
  2. Doubleclick on “Computer Management”
  3. Click in the side bar on “Disk Management” (in folder “Storage”)
  4. Right click on the partition, which file system is HFS and select from the context menu “Change drive letter and paths”
  5. Remove the drive letter by clicking the “Remove” button and ignore the warning that programs may rely on this drive.

References

Posted in Uncategorized | Tagged , , , , , , , , , , , , , | Leave a comment

Migrate Mac OS 10.7 Lion on a OCZ Vertex SSD in a unibody MacBook Pro

To speed up my unibody MacBook Pro (6,2) I decided to replace the internal hard disk with a SSD (OCZ-Vertex 2, 240GB, SATA2/3Gbps, Rev. 1.33). After browsing loads of tutorials I found another really easy way to put Lion on the blank disk. I have no confirmation if this is really the “master way” and that complications or side effects are impossible, but it works without 3rd party software, without shell commands, but only with Apple software and the tools you use anyway.

I assume you have already have …

  • an installed and functioning system in on your internal hard disk. If this is a MacOS 10.6 Snow Leopard installation, you must upgrade to Lion, because the Recovery Disk Assistant will be used, which is not available under 10.6 yet.
  • a Time Machine disk
  • a “scrap” USB stick or old USB hard disk. The Apple guys say it must have at least 1GB space.

Installation sequence

  1. Make Time Machine backup
  2. Remove large files (videos, music, photos, etc) from your internal hard disk until the used disk space is less than the disk size of the SSD. (I simply removed almost all media files and had 90GB disk usage after this cleanup. No applications or settings in the Library deleted.) A software which helped me quite well finding the space wastes was WhatSize. Probably you could use some cleanup programs as well to reduce the used disk space first (I didn’t). I would definitely propose to remove more rather than less. You can get the stuff back from the backup anyway.
  3. Make a Time Machine backup again. This backup will be the one to migrate later on.
  4. Download the Lion Recovery Disk Assistant. Additional information about this Apple software can be found in the article OS X Lion: About Lion Recovery Disk Assistant.
  5. Connect the USB disk and format it with a HFS+ filesystem using the the Disk Utility. Then run downloaded Recovery Disk Assistant, which will detect the USB disk (“follow the instructions :-)”. In my case it was a 8GB USB stick (one of the d**ned Cuiser sticks), I repartitioned it with one partition, Journaled HFS+, partition name: “LionRecovery”).
  6. Replace the internal HDD with the SSD. A good Tutorial by mefouryou how to do this can be found at YouTube: How to Install an SSD Into a Unibody MacBook Pro.
  7. Switch on your notebook, press the option-key until the boot menu shows up, and boot from your Lion Recovery disk.
  8. Plug in the Time Machine backup disk and choose the “Restore From Time Machine Backup” option. In my case the process took about 1 hour. After finishing the restore procedure, the notebook restarted and I could log in as usual.

Conclusion and annotations

After restoring on the SSD, the system worked out of the box. All settings I checked, such as saved passwords in Safari, Bookmarks, and the like were unchanged. Mail asked to import already existing emails and did this without any side effects. However, some Adobe programs had trouble with the licensing, so I had to uninstall (inclusively removing the settings in ~/Library) and reinstall them. Word 2011 wanted the CD key again (probably because the Hardware ID changed). The processor load was quite high after the installation due to the Spotlight indexing process. The next Time Machine backup, which I did directly after the migration, had a size of 75GB.

Some SSD related settings

As they are some differences between SSDs and HDDs, here some further things you may want to do:

  1. Disable sudden motion sensor, which protects the disk mechanics if you drop your notebook. As SSDs have no mechanical parts, disable it in the terminal: sudo pmset -a sms 0
  2. Enable TRIM support. Lion enables TRIM for Apple SSDs, but not for Vertex 2. I don’t like to present a solution on this site because this issue and its solution is a quite dynamic and not long time tested affaire at the moment. One of the referred discussions is http://notebooksnews.com/apple/enable-trim-mac-os-x-lion/. I have no idea if this will work for future versions, so search the internet for the actual solutions!
  3. Disable hard drive sleep: It’s no advantage to put SSDs into sleep mode. You can switch this off in the System preferences section “Energy Saver” by unticking the “Put hard disks into sleep when possible” checkbox for both Battery and Power tabs.
  4. You can free some disk space by disabling the hibernation mode. (This is not directly related to the handling of the SSDs, but general disk usage). Setting the sleep mode settings from 3 to 0 does this: sudo pmset -a hibernatemode 0. You can then remove the sleep image: sudo rm /var/vm/sleepimage.



Summa Summarum: After determining what to do, the whole migration took effectively about 2.5 hours of my lifetime – which is less than fixing the last compilation issue with MacPorts …

Posted in Uncategorized | Tagged , , , , , , , | Leave a comment

Mantis installation script for Ubuntu 10.04

The MantisBT is a PHP/MySQL based issue tracking system, licensed under the GPL and quite popular in the open source community to deal with software bugs. There are different ways to install MantisBT on your Ubuntu 10.04 server (e.g. aptitude), but if you want a one-shot preconfigured system in your /var/www/ folder, take a look at this small blog article.

Sequence:

  • If not yet installed, install GIT using sudo aptitude install git (GIT is good anyway :) ). This is needed because the script gets the latest repository snapshot with all the nice bug fixed.
  • Download and extract the ZIP archive in your server home directory or /tmp/”,
  • Run in the shell ./mantis-setup/setup install <mysql root password> <database name> <database user> <database password> (I used myself database name=”mantisbt”, database user=mantisbt). Well, please don’t choose a user name or database name that already exists, I did not check what happens then. It’s anyway better to have all database stuff this separated.

What happens then?

  • The script downloads MantisBT with the plugins source-integration and meta using GIT,
  • modifies the config_inc.php file of the MantisBT,
  • adapts the file/directory permissions for Apache2 (www-data, if you have another user/group, then modify the script file header, ou can’t miss it)
  • generates the database and the database user (the database contents are copied from the SQL file “copytables.sql”),
  • generates an individual SALT value for your BT system encryption
  • moves the whole folder structure to /var/www/mantisbt.

Result

  • You can access the bugtracker using http://yourserver.wtf/mantisbt
  • Login: “administrator”, password: “root”. Don’t forget to change it directly.
  • Installed plugins: “meta” and “source-integration”

Installation script source code

#!/bin/bash

#########################################################################################
## Settings
#########################################################################################

APTITUDE='/usr/bin/aptitude'
WWW_ROOT="/var/www"
APACHE_USER="www-data"
APACHE_GROUP="www-data"
TEMP_DIR="/tmp/mantis-setup"
GIT="/usr/bin/git"
MANTIS_GITHUB_URL="https://github.com/mantisbt/mantisbt.git"
MANTIS_GIT_PLUGIN_SOURCE_URL="git://git.mantisforge.org/source-integration.git"
MANTIS_GIT_PLUGIN_META_URL="git://git.mantisforge.org/meta.git"
WWW_MANTIS_DIRNAME='mantis'
DB_MYSQL_ROOT_PASS="$2"
DB_NAME="$3"
DB_USER="$4"
DB_PASS="$5"
DB_HOST='localhost'
CRYPTO_SALT="$(cat /dev/urandom | head -c 64 | base64 -w 1000)"

pushd . > /dev/null
cd "$(dirname $0)"
SCRIPT_DIR="$(pwd)"
popd > /dev/null

#########################################################################################
## Program starts here
#########################################################################################

# functions
function echo_error()  { echo -e "\033[0;31m[FAILED] $@\033[0m"; }
function echo_ok()     { echo -e "\033[0;32m[OK] $@\033[0m"; }
function echo_info()   { echo -e "\033[0;33m$@\033[0m"; }

function set_php_var() {
	sudo grep -Fq "${1}" "${3}";
	if [ $? -eq 0 ]; then
		sudo sed -i "s,${1}.*,${1} = ${2};," "${3}";
	else
		sudo sed -i "\$a\\${1} = ${2};" "${3}";
	fi;
}

function print_usage() {
	echo "Usage:"
	echo ""
	echo " To install:"
	echo "   $SCRIPT_DIR install <mysql root password> <database name> <database user> <database password>"
	echo ""
	echo " To uninstall:"
	echo "   $SCRIPT_DIR uninstall --really"
	echo ""
	exit
}

function chmod_chown_wwwdata() {
	echo_info "Changing file modes/owner/group to make them suitable for Apache"
	sudo chown -R $APACHE_USER:$APACHE_GROUP $TEMP_DIR/mantisbt
	sudo find . -type d -exec chmod 550 {} \;
	sudo find . -type f -exec chmod 440 {} \;
}

# uninstall process
if [ "$1" = "uninstall" ]; then
	if [ "$2" != "--really" ]; then
		echo_error 'You must say "setup uninstall --really"'
		exit
	fi
	echo_error "TODO: IMPLEMENT UNINSTALLER"
	sudo echo ""
	echo_info "----------------------------------------------------------------------"
	echo_info "UNINSTALL"
	echo_info "----------------------------------------------------------------------"
	echo_info "remove mantis ..."

	if [ ! -d $WWW_ROOT ]; then
		echo_error "Web root directory not there ($WWW_ROOT)"
		exit
	elif [ ! -d $WWW_ROOT/$WWW_MANTIS_DIRNAME ]; then
		echo_error "Mantis is not installed in $WWW_ROOT/$WWW_MANTIS_DIRNAME"
		exit
	fi

	sudo rm -rf $WWW_ROOT/$WWW_MANTIS_DIRNAME

	echo_info "NOTE: DATABASE WILL NOT BE DELETED"
	echo_ok "uninstalled"
	exit
elif [ "$1" = "install" ]; then
	# mark sudo
	sudo echo ""

	if [ ! -d $WWW_ROOT ]; then
		echo_error "Web root directory not there ($WWW_ROOT)"
		exit
	elif [ "$4" = "" ]; then
		print_usage
	elif [ -d $WWW_ROOT/$WWW_MANTIS_DIRNAME ]; then
		echo_error "Mantis is already installed in $WWW_ROOT/$WWW_MANTIS_DIRNAME"
		exit
	fi

	if [ "$DB_NAME" = "" -o "$DB_USER" = "" -o "$DB_PASS" = "" ]; then
		echo_error "You must set database name, user and password."
	fi

	echo_info "Preparing temporary direcory"
	pushd . &> /dev/null
	mkdir $TEMP_DIR
	cd $TEMP_DIR

	echo_info "Cloning mantis from github"
	if [ ! -d "$TEMP_DIR/mantisbt" ]; then
		# get mantis
		$GIT clone $MANTIS_GITHUB_URL
		echo_info "(To ensure compatibility when generating the database structure,"
		echo_info " we checkout release-1.2.6, can be updated later ...)"
		cd $TEMP_DIR/mantisbt
		$GIT checkout release-1.2.6
		rm -rf .git

		# get source-integration
		cd $TEMP_DIR/mantisbt/plugins
		$GIT clone "$MANTIS_GIT_PLUGIN_SOURCE_URL"
		if [ ! -d "$TEMP_DIR/mantisbt/plugins/source-integration" ]; then
			echo_error "Failed to get source-integration plugin from $MANTIS_GIT_PLUGIN_META_URL"
		else
			mv $TEMP_DIR/mantisbt/plugins/source-integration/Source* $TEMP_DIR/mantisbt/plugins
			rm -rf $TEMP_DIR/mantisbt/plugins/source-integration
		fi

		# get meta
		cd $TEMP_DIR/mantisbt/plugins
		$GIT clone "$MANTIS_GIT_PLUGIN_META_URL"
		if [ ! -d "$TEMP_DIR/mantisbt/plugins/meta" ]; then
			echo_error "Failed to get meta plugin from $MANTIS_GIT_PLUGIN_META_URL"
		else
			mv $TEMP_DIR/mantisbt/plugins/meta/Meta $TEMP_DIR/mantisbt/plugins/
			rm -rf $TEMP_DIR/mantisbt/plugins/meta
		fi

		# finish git clone stuff
		cd $TEMP_DIR/mantisbt
	fi

	if [ ! -d "$TEMP_DIR/mantisbt" ]; then
		echo_error "Mantis was not cloned from git"
	fi

	echo_info "Processing $TEMP_DIR/mantisbt/config_inc.php"
	sudo chown -R $USER:$USER $TEMP_DIR/mantisbt
	sudo rm $TEMP_DIR/mantisbt/config_inc.php &> /dev/null
	sudo cp -f $TEMP_DIR/mantisbt/config_inc.php.sample $TEMP_DIR/mantisbt/config_inc.php
	set_php_var '$g_hostname' '"'"$DB_HOST"'"' $TEMP_DIR/mantisbt/config_inc.php
	set_php_var '$g_db_username' '"'"$DB_USER"'"'  $TEMP_DIR/mantisbt/config_inc.php
	set_php_var '$g_db_password' '"'"$DB_PASS"'"'  $TEMP_DIR/mantisbt/config_inc.php
	set_php_var '$g_database_name' '"'"$DB_NAME"'"'  $TEMP_DIR/mantisbt/config_inc.php
	set_php_var '$g_allow_signup' 'false'  $TEMP_DIR/mantisbt/config_inc.php
	set_php_var '$g_allow_anonymous_login' 'false'  $TEMP_DIR/mantisbt/config_inc.php
	set_php_var '$g_crypto_master_salt' '"'"$CRYPTO_SALT"'"'  $TEMP_DIR/mantisbt/config_inc.php
	#sudo cat $TEMP_DIR/mantisbt/config_inc.php

	echo_info "Changing file modes/owner/group to make them suitable for Apache"
	sudo chown -R $APACHE_USER:$APACHE_GROUP $TEMP_DIR/mantisbt
	sudo find . -type d -exec chmod 550 {} \;
	sudo find . -type f -exec chmod 440 {} \;

	echo_info "Generating database"
	sudo cp "$SCRIPT_DIR/dbcreate.sql" "$TEMP_DIR/dbcreate.sql"
	sudo chmod 666 "$TEMP_DIR/dbcreate.sql"
	sudo sed -i "s/@@@mantisbt_db/$DB_NAME/" "$TEMP_DIR/dbcreate.sql"
	sudo sed -i "s/@@@mantisbt_user/$DB_USER/" "$TEMP_DIR/dbcreate.sql"
	sudo sed -i "s/@@@mantisbt_pass/$DB_PASS/" "$TEMP_DIR/dbcreate.sql"
	sudo cat "$SCRIPT_DIR/copytables.sql" >> "$TEMP_DIR/dbcreate.sql"
	sudo cat "$SCRIPT_DIR/dbcreate-finish.sql" >> "$TEMP_DIR/dbcreate.sql"

	echo_info "Running mysql, you must enter the mysql root password now"
	#cat "$TEMP_DIR/dbcreate.sql"
	if [ "$DB_MYSQL_ROOT_PASS" = "" ]; then
		mysql --user="root" -p < "$TEMP_DIR/dbcreate.sql"
	else
		mysql --user="root" --password="$DB_MYSQL_ROOT_PASS" < "$TEMP_DIR/dbcreate.sql"
	fi
	sudo rm "$TEMP_DIR/dbcreate.sql"

	# Finish install
	echo_info "Moving to www root"
	sudo mv $TEMP_DIR/mantisbt $WWW_ROOT/$WWW_MANTIS_DIRNAME
	echo_info "Renaming mantis admin path ($WWW_ROOT/$WWW_MANTIS_DIRNAME/admin)"
	sudo mv $WWW_ROOT/$WWW_MANTIS_DIRNAME/admin $WWW_ROOT/$WWW_MANTIS_DIRNAME/.admin
	popd &> /dev/null
	echo_info "Removing temp directory"
	sudo rm -rf $TEMP_DIR &> /dev/null

	echo_info "NOTE: You can now login as administrator under /$WWW_MANTIS_DIRNAME/index.php"
	echo_info "      login name: administrator"
	echo_info "      login pass: root"
	echo_info "      AND YOU SHOULD CHANGE THIS PASSWORD IMMEDIATELY"

	echo_ok "Installed"
else
	echo 'You mus say "install" or "uninstall"'
	exit
fi

Output

The script output should look similar to this (just in color):

foo@host:~/ubuntu-setup-scripts/mantis$ ./setup install "*******************" mantisbt mantisbt "****************"

Preparing temporary direcory
Cloning mantis from github
Initialized empty Git repository in /tmp/mantis-setup/mantisbt/.git/
remote: Counting objects: 64350, done.
remote: Compressing objects: 100% (11204/11204), done.
remote: Total 64350 (delta 52967), reused 63836 (delta 52508)
Receiving objects: 100% (64350/64350), 22.87 MiB | 1.10 MiB/s, done.
Resolving deltas: 100% (52967/52967), done.
(To ensure compatibility when generating the database structure,
 we checkout release-1.2.6, can be updated later ...)
Note: checking out 'release-1.2.6'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name

HEAD is now at 89738d5... Bump
Initialized empty Git repository in /tmp/mantis-setup/mantisbt/plugins/source-integration/.git/
remote: Counting objects: 2442, done.
remote: Compressing objects: 100% (651/651), done.
remote: Total 2442 (delta 1693), reused 2442 (delta 1693)
Receiving objects: 100% (2442/2442), 369.03 KiB, done.
Resolving deltas: 100% (1693/1693), done.
Initialized empty Git repository in /tmp/mantis-setup/mantisbt/plugins/meta/.git/
remote: Counting objects: 9, done.
remote: Compressing objects: 100% (7/7), done.
remote: Total 9 (delta 0), reused 9 (delta 0)
Receiving objects: 100% (9/9), 12.59 KiB, done.
Processing /tmp/mantis-setup/mantisbt/config_inc.php
Changing file modes/owner/group to make them suitable for Apache
Generating database
Running mysql, you must enter the mysql root password now
Moving to www root
Renaming mantis admin path (/var/www/mantis/admin)
Removing temp directory
NOTE: You can now login as administrator under /mantis/index.php
      login name: administrator
      login pass: root
      AND YOU SHOULD CHANGE THIS PASSWORD IMMEDIATELY
[OK] Installed
Posted in Programming | Tagged , , , , , | Leave a comment

Connect Drupal 7 to SabreDAV

One of the best Apache2 compatible WebDAV server implementations is the object oriented PHP implementation SabreDAV. If you use a Drupal for your content management and like to add a WebDAV file storage, you can connect SabreDAV to the Drupal user database. You can to this by using the Drupal module DP UserConnector (http://drupal.org/sandbox/stfwi/1201872, the project is currently reviewed in the sandbox) and implement the Sabre_DAV_Auth_IBackend interface, as shown in this source code:

SabreDAV BasicAuth implementation and server run

<?php
require_once 'Sabre/autoload.php';

/**
 * DP connected user authentification
 */
class Sabre_DAV_Auth_Backend_Basic_DrupalConnected implements Sabre_DAV_Auth_IBackend {

    /**
     * @var DrupalUserAuth
     */
    public $dpu = null;

    /**
     * Returns information about the currently logged in username.
     * If nobody is currently logged in, this method should return null.
     * @return string|null
     */
    public function getCurrentUser() {
        return !$this->dpu ? null : $this->dpu->name;
    }

    /**
     * Authenticates the user based on the current request.
     * If authentication is succesful, true must be returned.
     * If authentication fails, an exception must be thrown.
     * @throws Sabre_DAV_Exception_NotAuthenticated
     * @return bool
     */
    public function authenticate(Sabre_DAV_Server $server,$realm) {

        // Assuming we only accept https for basic auth
        if(!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on') {
            throw new Sabre_DAV_Exception_NotAuthenticated('HTTPS only');
        }

        // Prepare SabreDav auth instances, get user & password pair
        $auth = new Sabre_HTTP_BasicAuth();
        $auth->setHTTPRequest($server->httpRequest);
        $auth->setHTTPResponse($server->httpResponse);
        $auth->setRealm($realm);
        $userpass = $auth->getUserPass();

        // Pre check
        if(!$userpass) {
            $auth->requireLogin();
            throw new Sabre_DAV_Exception_NotAuthenticated('No basic authentication headers were found');
        }

        // Assuming DRUPAL ROOT = $_SERVER['DOCUMENT_ROOT']
        require_once($_SERVER['DOCUMENT_ROOT'] . '/modules/dpuser_connector/client/DrupalUserAuth.class.inc');

        // The token used to connect to DP
        DrupalUserBase::setToken("---my---token---here---");

        // Authentification request
        $dpu = new DrupalUserAuth();
        $dpu->request(
            $userpass[0],    // user name
            $userpass[1],     // pass
            null,            // email
            true,            // active users only
            null            // no profile fields to fetch
        );

        // Validation
        if (!$dpu->valid) {
            $auth->requireLogin();
            throw new Sabre_DAV_Exception_NotAuthenticated('Username or password does not match');
        } else {
            $this->dpu = $dpu;
            return true;
        }
    }
}

// Directory structure of this sample code:
//
// drwx  - document root (www-data)
// dr-x     - webdav
// -r--        - index.php
// drwx        - davfiles
//                 (DAV FILES ARE IN HERE)
// drw-        - data
// -rw-           - locks
// dr-x        - Sabre
//
$rootDirectory = new Sabre_DAV_FS_Directory('davfiles');
$server = new Sabre_DAV_Server($rootDirectory);
$server->setBaseUri('/webdav/');
// The lock manager is reponsible for making sure users don't overwrite each others changes.
// Change 'data' to a different directory, if you're storing your data somewhere else.
$lockBackend = new Sabre_DAV_Locks_Backend_File('data/locks');
$lockPlugin = new Sabre_DAV_Locks_Plugin($lockBackend);
$server->addPlugin($lockPlugin);
$authBackend = new Sabre_DAV_Auth_Backend_Basic_DrupalConnected();
$authPlugin = new Sabre_DAV_Auth_Plugin($authBackend,'WebDAV area');
$server->addPlugin($authPlugin);
$server->exec(); // All we need to do now, is to fire up the server
Posted in PHP, Programming | Leave a comment