<?php
/**************************************************************************
* This file is part of the WebIssues Server program
* Copyright (C) 2006 Michał Męciński
* Copyright (C) 2007-2009 WebIssues Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
**************************************************************************/

switch ( $config[ 'mail_engine' ] ) {
    case 'standard':
        require_once( 'mail-standard.inc.php' );
        break;
    case 'smtp':
        require_once( 'mail-smtp.inc.php' );
        break;
}

function wi_mail( $to, $subject, $body, $content_type = 'text/plain' )
{
    global $config;

    return wi_mail_send( $config[ 'mail_from' ], $to, $subject, $body, $content_type );
}

function wi_parse_headers( $headers )
{
    $parsed = array();
    foreach ( explode( "\n", $headers ) as $header ) {
        $temp = explode( ":", $header, 2 );
        if ( count( $temp ) == 2 ) {
            $key = trim( $temp[ 0 ] );
            $value = trim( $temp[ 1 ] );
            $parsed[ $key ] = $value;
        }
    }
    return $parsed;
}

function wi_format_headers( $headers )
{
    $mime_headers = array();
    foreach ( $headers as $name => $value )
        $mime_headers[] = $name . ': ' . wi_mime_header_encode( $value );
    return join( "\n", $mime_headers );
}

function wi_header( $headers, $key, $default = '' )
{
    if ( isset( $headers[ $key ] ) )
        return $headers[ $key ];
    return $default;
}

function wi_mime_header_encode( $string )
{
    if ( preg_match( '/[^\x20-\x7E]/', $string ) ) {
        $chunk_size = 47;
        $len = strlen( $string );
        $output = '';
        while ( $len > 0 ) {
            $chunk = wi_truncate_bytes( $string, $chunk_size );
            $output .= ' =?UTF-8?B?' . base64_encode( $chunk ) . "?=\n";
            $c = strlen( $chunk );
            $string = substr( $string, $c );
            $len -= $c;
        }
        return trim( $output );
    }
    return $string;
}

function wi_truncate_bytes( $string, $len )
{
    if ( strlen( $string ) <= $len )
        return $string;
    if ( ( ord( $string[ $len ] ) < 0x80 ) || ( ord( $string[ $len ] ) >= 0xC0 ) )
        return substr( $string, 0, $len );
    while ( --$len >= 0 && ord( $string[ $len ] ) >= 0x80 && ord( $string[ $len ] ) < 0xC0 )
        ;
    return substr( $string, 0, $len );
}
