WebService Source

The document service source code consists of three main files, along with an optional PHP mailer implementation, all of which are available for download in the main site's download section.

It's essential for the site to have an SSL certificate to enable the use of the HTTPS protocol for access. This is necessary to prevent user names and passwords from being exposed to potential traffic sniffers that might monitor network traffic.

Note: Even though we provide PHP-compatible encryption and decryption functions in the plugin, the web service itself does not include any encryption or decryption features. When using the plugin to save documents to the service, the plugin handles document encryption before sending them to the service. Therefore, the SOAP service does not require any additional features for document encryption or decryption, as this process is already taken care of.

Source Code:

The source code is available for download and is functional as is. However, you have the flexibility to make adjustments or implement new features as needed.

index.php

<?php

ini_set('display_errors', 'On');

include "zx_config.php";

defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);

// Add SENDMAIL support to DocumentService
function XsendMail($fromName, $fromEml, $toName, $toEml, $subject, $body, $cc = "", $bcc = "", $attArray = array(), $in = 1)
{
    global $core_config;
    $thispath = __DIR__ . "/";
    require_once $thispath . '/PHPMailer/PHPMailerAutoload.php';
    
    $results_messages = array();
    
    $mail          = new PHPMailer(true);
    $mail->CharSet = 'utf-8';
    $error         = false;
    // Include the PHP mailer to enable mail sending through the document service, 
    // mail with doc as attachement. 
    if (!class_exists(phpmailerAppException)) {
        class phpmailerAppException extends phpmailerException
        {
        }
    }
    try {
        if (!PHPMailer::validateAddress($toEml)) {
            throw new phpmailerAppException("Email address " . $to . " is invalid -- aborting!");
        }
        // For SMTP sending - Uncomment
        /*$mail->isSMTP();                                      // Set mailer to use SMTP
        
        $mail->Host = 'mail host to use';  // Specify main and backup SMTP servers
        $mail->SMTPAuth = true;                               // Enable SMTP authentication
        $mail->Username = 'noreply';                 // SMTP username
        $mail->Password = 'password to mail service';                           // SMTP password
        $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
        $mail->Port = 587;    
        */
        
        // Send using sendmail. 
        $mail->isMail(); // if SMTP, uncomment this line. 
        $mail->addReplyTo($fromEml, $fromName);
        $mail->From     = $fromEml;
        $mail->Sender   = $fromEml;
        $mail->FromName = $fromName;
        $mail->addAddress($toEml, $toName);
        
        if ($bcc != '') {
            $bcc     = str_replace(",", ";", $bcc);
            $indiBCC = explode(";", $bcc);
            foreach ($indiBCC as $key => $value) {
                $mail->addBCC($value);
            }
        }
        if ($cc != '') {
            $cc     = str_replace(",", ";", $cc);
            $indiCC = explode(";", $cc);
            foreach ($indiCC as $key => $value) {
                $mail->addCC($value);
            }
        }
        
        $mail->Subject = $subject;
        
        $mail->WordWrap = 80;
        $mail->msgHTML($body, dirname(__FILE__), true); //Create message bodies and embed images
        foreach ($attArray as $attrow) {
            $mail->addAttachment($attrow['path'], $attrow['file']);
        }
        
        try {
            $mail->send();
            $results_messages[] = "Message has been sent using MAIL";
            //echo "Message has been sent using MAIL"; 
        }
        catch (phpmailerException $e) {
            $error = true;
            throw new phpmailerAppException('Unable to send to: ' . $toEml . ': ' . $e->getMessage());
        }
    }
    catch (phpmailerAppException $e) {
        $results_messages[] = $e->errorMessage();
        $error              = true;
        // echo $e->errorMessage();
    }
    if ($error) {
        //throw new Exception ($results_messages[0]) ;
        return $results_messages;
    }
    return true;
}


$xKey = "";
class SOAP_Service_Secure
{
    protected $class_name = '';
    protected $authenticated = false;
    protected $ServiceAvailable;
    protected $Key;
    
    
    // -----
    
    public function __construct($class_name, $sa = true)
    {
        $this->class_name       = $class_name;
        $this->ServiceAvailable = $sa;
        $this->Key              = "";
        $this->user_config      = array();
    }
    
    public function getUserConfig()
    {
        return $this->user_config;
    }
    
    public function Header($Header)
    {
        global $xKey, $core_config, $user_config;
        
        foreach ($core_config['AUTH'] as $conf) {
            if ($Header->UN == $conf['USER'] && $Header->PW == $conf['PASS']) {
                $this->authenticated = true;
                $user_config         = $conf;
                break;
            }
        }
        $this->Key = $Header->Key;
        $xKey      = $Header->Key;
    }
    
    public function __call($method_name, $arguments)
    {
        if ($core_config['SECURITY']['REQUIRESSL']) {
            $a = ($_SERVER['SERVER_PORT'] == "80");
            if ($a) {
                $result = array(
                    'Status' => "ERROR",
                    'Message' => "The use of HTTPS protocol is mandatory"
                );
                return $result;
            }
        }
        
        
        if (!$this->ServiceAvailable) {
            $result = array(
                'Status' => "ERROR",
                'Message' => "The service is temporarily unavailable"
            );
            
            return $result;
        }
        
        if (!method_exists($this->class_name, $method_name))
            throw new Exception('method not found: ' . $method_name);
        
        if ($this->checkAuth()) {
            
            return call_user_func_array(array(
                $this->class_name,
                $method_name
            ), $arguments);
        } else {
            if ($this->Key == "TEST") {
                $op = "TEST LOGIN";
            } else {
                $op = $method_name . "/" . $this->Key;
            }
            
            $result = array(
                'Status' => "ERROR",
                'Message' => "Autentication failure! - Operation:  " . $op
            );
            return $result;
        }
    }
    
    protected function checkAuth()
    {
        if (!$this->authenticated)
            return false;
        
        return true;
        
    }
}
function fb()
{
}

function fixUTF8Names($string)
{
    // Fixing UTF8 alternatives for å and Å that does not convert well to ISO-8859-1
    return str_replace(array(
        "\x61\xCC\x8A",
        "\x41\xCC\x8A"
    ), array(
        "\xC3\xA5",
        "\xC3\x85"
    ), $string);
}

function bel_($belValue)
{
    $x = str_replace(".", ",", $belValue);
    if (substr($x, 0, 1) == ",") {
        $x = "0" . $x;
    }
    return $x;
}

function soaputils_autoFindSoapRequest()
{
    global $HTTP_RAW_POST_DATA;
    
    if ($HTTP_RAW_POST_DATA)
        return $HTTP_RAW_POST_DATA;
    
    $f = file("php://input");
    return implode(" ", $f);
}

class DocumentService
{
    // -------------- G E T     D O C U M E N T ------------------
    public static function GetDocument($params)
    {
        global $xKey, $user_config;
        
        
        // Any special functions ? 
        switch (strtoupper($xKey)) {
            case 'TEST':
                return array(
                    'Status' => "OK",
                    'Message' => "Autenticated OK"
                );
                break;
            case 'TESTENCODING':
                $orig_encoding = mb_detect_encoding($params->FileName);
                if ($params->FileName == "File ÆØÅ æøå.txt") {
                    return array(
                        'Status' => "Encoding OK",
                        'Message' => "Encoding: " . $orig_encoding
                    );
                } elseif ($orig_encoding != "UTF-8") {
                    return array(
                        'Status' => "Wrong encoding",
                        'Message' => "Encoding: " . $orig_encoding
                    );
                } else {
                    return array(
                        'Status' => "Feil test-filnavn, benyttet encoding:" . $orig_encoding,
                        'Message' => "For test: bruk filnavn 'File ÆØÅ æøå.txt' Du benyttet: '" . $params->FileName . "'"
                    );
                }
                
        }
        
        // If the service is not yet active, we have pre-loaded the result....
        
        $result = array(
            'Status' => "ERROR",
            'Message' => "Autenticated and OK; but service not yet active"
        );
        
        try {
            
            
            
            $fnWin         = fixUTF8Names($params->FileName);
            $orig_encoding = mb_detect_encoding($fnWin);
            $fnWin         = mb_convert_encoding($fnWin, FILPATH_ENCODING, $orig_encoding);
            $filepath      = str_replace("/", DS, $user_config['PATH'] . $params->Path . $fnWin);
            if (strpos($filepath, "..") > 0) {
                $result['Message'] = "Path cannot contain .. ";
                return $result;
            }
            file_put_contents("ResultDoc.txt", $filepath . "\n" . $orig_encoding);
            $fn  = pathinfo($filepath, PATHINFO_BASENAME);
            $ext = pathinfo($filepath, PATHINFO_EXTENSION);
            
            $encrypted_suffix = "_encrypted";
            
            if (file_exists($filepath)) {
                $rFn = $params->FileName;
            } elseif (file_exists($filepath . $encrypted_suffix)) {
                $rFn = $params->FileName . $encrypted_suffix;
                $filepath .= $encrypted_suffix;
            } else {
                $result = array(
                    'Status' => "ERROR",
                    'Message' => "File does not exists"
                );
                return $result;
            }
            
            
            $result = array(
                'Status' => "OK",
                'Message' => mb_convert_encoding($filepath, "UTF-8", FILPATH_ENCODING),
                'Type' => $ext,
                'File' => @file_get_contents($filepath),
                'FileName' => $rFn
            );
            if ($result["File"] === FALSE) {
                $result["File"]    = "";
                $result["Status"]  = "ERROR";
                $result["Message"] = "Failed to read file";
            }
            
        }
        catch (Exception $e) {
            
            
            $result = array(
                'Status' => "ERROR",
                'Message' => $e->getCode() . " " . $e->getMessage(),
                'FileName' => $filepath
            );
            
        }
        
        
        return $result;
    }
    // -------------- S A V E     D O C U M E N T ------------------
    public static function SaveDocument($params)
    {
        global $xKey, $user_config;
        ;
        $result = array(
            'Status' => "ERROR",
            'Message' => "Autenticated and OK; but service not yet active"
        );
        
        if ($user_config['ACCESS'] == "R") {
            $result['Message'] = "No Write access to this service";
            return $result;
        }
        
        try {
            
            $re = '/.+?\|\|SENDMAIL\|\|data-.+?.txt/i';
            // 	$str = 'logo.gif||fromName||fromemail@doe.com||ToName||toEmail@doe.com||ccemail@doe.com||bccemail@doe.com||MessageSubject||MessageBody';
            
            $isMailSend = preg_match_all($re, $params->FileName, $matches, PREG_SET_ORDER, 0);
            
            // The option to send attachemnt by e-mail 
            // Encode the special encoded filename by using syntax like the above. 	   			
            
            
            if ($isMailSend) {
                $MailParams = explode("||", $params->FileName);
                $fnAtt      = $MailParams[0];
                $ckey       = $MailParams[1];
                $fndata     = $MailParams[2];
                $fnWin      = fixUTF8Names($fndata);
                $fnWin      = mb_convert_encoding($fnWin, FILPATH_ENCODING, mb_detect_encoding($fnWin));
                $filepath   = str_replace("/", DS, STARTPATH . $params->Path . $fnWin);
                $content    = @file_get_contents($filepath);
                
                $MailParams = explode("||", $content);
                
                
                $fromName  = $MailParams[1];
                $fromEmail = $MailParams[2];
                $ToName    = $MailParams[3];
                $email     = $MailParams[4];
                $cc        = $MailParams[5];
                $bcc       = $MailParams[6];
                $sub       = $MailParams[7];
                $body      = $MailParams[8];
                $body      = str_replace("\n", "<br/>\n", $body);
                $body      = str_replace("\r", "<br/>\n", $body);
                $fnWin     = fixUTF8Names($fnAtt);
            } else {
                $fnWin = fixUTF8Names($params->FileName);
            }
            
            
            
            $fnWin = mb_convert_encoding($fnWin, FILPATH_ENCODING, mb_detect_encoding($fnWin));
            
            $filepath = str_replace("/", DS, $user_config['PATH'] . $params->Path . $fnWin);
            
            if (strpos($filepath, "..") > 0) {
                $result['Message'] = "Path cannot contain .. ";
                return $result;
            }
            
            $ext      = pathinfo($filepath, PATHINFO_EXTENSION);
            $fn       = pathinfo($filepath, PATHINFO_BASENAME);
            $dir      = pathinfo($filepath, PATHINFO_DIRNAME);
            $fn_noext = pathinfo($filepath, PATHINFO_FILENAME);
            
            
            if (!file_exists($dir)) {
                if (!@mkdir($dir, 0777, true)) {
                    throw new Exception("Kunne ikke opprette directory: $dir");
                }
            }
            // create new name if allready exists. 
            if (strtoupper($xKey) != "UPDATE") {
                $regex = "/(.+)_([0-9]{0,2})\.([a-z0-9]{0,10})/";
                // group 1: filename
                // group 2: version number
                // group 3: extention. 
                ;
                if (preg_match($regex, $fn, $out)) {
                    $fn_noext = $out[1];
                    $i        = intval($out[2]);
                } else {
                    $i = 1;
                }
                $fileex = file_exists($filepath);
                while ($fileex) {
                    $i++;
                    
                    $fn       = $fn_noext . "_" . $i . "." . $ext;
                    $filepath = $dir . DS . $fn;
                    $fileex   = file_exists($filepath);
                }
            }
            
            file_put_contents($filepath, $params->File);
            
            if ($isMailSend) {
                $res = XsendMail($fromName, $fromEmail, $ToName, $email, $sub, $body, $cc, $bcc, array(
                    array(
                        'path' => $filepath,
                        'file' => $fn
                    )
                ));
                if ($res === true) {
                    $result = array(
                        'Status' => "OK",
                        'Message' => mb_convert_encoding($filepath, "UTF-8", FILPATH_ENCODING),
                        'FileName' => mb_convert_encoding($fn, "UTF-8", FILPATH_ENCODING)
                    );
                } else {
                    $result = array(
                        'Status' => "ERROR",
                        'Message' => $res[0],
                        'FileName' => mb_convert_encoding($fn, "UTF-8", FILPATH_ENCODING)
                    );
                }
                
            } else {
                $result = array(
                    'Status' => "OK",
                    'Message' => mb_convert_encoding($filepath, "UTF-8", FILPATH_ENCODING),
                    'FileName' => mb_convert_encoding($fn, "UTF-8", FILPATH_ENCODING)
                );
            }
            
            
            
            
        }
        catch (Exception $e) {
            
            $result = array(
                'Status' => "ERROR",
                'Message' => $e->getCode() . " " . $e->getMessage(),
                'FileName' => $filepath
            );
            
        }
        
        
        return $result;
    }
    
    private function obligatoryFieldCheck($Name, $value)
    {
        if ($value == "") {
            throw new Exception("Required XML tag missing or is empty, path:" . $Name, 10012);
        }
    }
    
    
}
try {
    
    $user_config = array();
    $Service     = new SOAP_Service_Secure('DocumentService', true);
    
    $opts                 = Array();
    $opts['compression']  = SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP;
    $opts['soap_version'] = SOAP_1_1;
    $opts['cache_wsdl']   = WSDL_CACHE_NONE; //WSDL_CACHE_BOTH
    
    $Server = new SoapServer('DocumentService.wsdl', $opts);
    $Server->setObject($Service);
    
    // $req = soaputils_autoFindSoapRequest(); 
    // file_put_contents("ResultDoc.txt", $req); 
    $Server->handle();
    
}
catch (Exception $e) {
    echo $e->getCode() . " " . $e->getMessage();
}

?>

Please make sure to access and download these files from the designated download section on the main site.