<?php

/**
 * OpenKM, Open Knowledge Management System S.L.  (http://www.openkm.com)
 * Copyright (c) 2006-2023
 *
 * No bytes were intentionally harmed during the development of this application.
 *
 * This program is commercial software; you can use it under the terms of the
 * EULA - OpenKM SDK End User License Agreement as published by OpenKM Knowledge Management System S.L.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * EULA - OpenKM SDK End User License Agreement for more details:
 * http://docs.openkm.com/kcenter/view/licenses/eula-openkm-sdk-end-user-license-agreement.html
 */

namespace openkm\impl;

use Httpful\Exception\ConnectionErrorException;
use Httpful\Mime;
use Httpful\Request;
use openkm\definition\BaseConversion;
use openkm\exception\AccessDeniedException;
use openkm\exception\ConversionException;
use openkm\exception\IOException;
use openkm\exception\NotImplementedException;
use openkm\exception\UnknowException;
use openkm\util\Status;
use openkm\util\TypeException;
use openkm\util\UriHelper;

/**
 * ConversionImpl
 *
 * @author sochoa
 */
class ConversionImpl extends ClientImpl implements BaseConversion {

    
    /**
     * Retrieve the uploaded document converted to PDF format
     * 
     * The openoffice service must be enabled in OpenKM server to get it running.
     * 
     * @param string $content Recommend using file_get_contents — Reads entire file into a string
     * @param string $fileName The document file name. Application uses this parameter to identify by document extension the document MIME TYPE.
     * @return string Retrieve the uploaded document converted to PDF format.
     * @throws ConnectionErrorException
     * @throws AccessDeniedException
     * @throws ConversionException
     * @throws NotImplementedException
     * @throws UnknowException
     */
    public function doc2pdf($content, $fileName) {
        try {
            $uri = UriHelper::getUri($this->host, UriHelper::CONVERT_DOC_TO_PDF);
            $body = [];

            $params = [];
            $body['params'] = $params;

            $files = [];
            $file['name'] = 'content';
            $file['body'] = $content;
            $file['fileName'] = $fileName;
            $files[] = $file;
            $body['files'] = $files;

            $client = Request::post($uri);
            $client->setCurlPostFile(true);
            $client->body($body, Mime::UPLOAD);
            $client->authenticateWith($this->user, $this->password);
            $client->expects(Mime::UPLOAD);
            $response = $client->send();
            if ($response->code == Status::OK) {
                return $response->body;
            } else {
                if ($response->code == Status::UNAUTHORIZED) {
                    throw new AccessDeniedException($response->body, $response->code);
                } else if ($response->code == Status::INTERNAL_SERVER_ERROR) {
                    $position = strpos($response->body, ':');
                    if ($position) {
                        $error = substr($response->body, 0, $position);
                        $msg = substr($response->body, $position + 1, strlen($response->body));
                        if ($error == TypeException::CONVERSION_EXCEPTION) {
                            throw new ConversionException($error . ': ' . $msg);
                        } else if ($error == TypeException::NOT_IMPLEMENTED_EXCEPTION) {
                            throw new NotImplementedException($error . ': ' . $msg);
                        } else {
                            throw new UnknowException($error . ': ' . $msg);
                        }
                    } else {
                        throw new UnknowException("HTTP error code " . $response->code . ": " . $response->body);
                    }
                } else {
                    throw new UnknowException("HTTP error code " . $response->code . ": " . $response->body);
                }
            }
        } catch (ConnectionErrorException $cee) {
            throw new ConnectionErrorException('ConnectionErrorException: ' . $cee->getMessage());
        }
    }

    /**
     * Retrieve the uploaded document converted to SWF format.
     * 
     * The pdf2swf tool must be enabled in OpenKM server to get it running.
     * 
     * @param string $content Recommend using file_get_contents — Reads entire file into a string
     * @param string $fileName The document file name. Application uses this parameter to identify by document extension the document MIME TYPE.
     * @return string Retrieve the uploaded document converted to SWF format.
     * @throws ConnectionErrorException
     * @throws AccessDeniedException
     * @throws ConversionException
     * @throws NotImplementedException
     * @throws UnknowException
     */
    public function pdf2swf($content, $fileName) {
        try {
            $uri = UriHelper::getUri($this->host, UriHelper::CONVERT_PDF_TO_SWF);
            $body = [];

            $params = [];
            $body['params'] = $params;

            $files = [];
            $file['name'] = 'content';
            $file['body'] = $content;
            $file['fileName'] = $fileName;
            $files[] = $file;
            $body['files'] = $files;

            $client = Request::post($uri);
            $client->setCurlPostFile(true);
            $client->body($body, Mime::UPLOAD);
            $client->authenticateWith($this->user, $this->password);
            $client->expects(Mime::UPLOAD);
            $response = $client->send();
            if ($response->code == Status::OK) {
                return $response->body;
            } else {
                if ($response->code == Status::UNAUTHORIZED) {
                    throw new AccessDeniedException($response->body, $response->code);
                } else if ($response->code == Status::INTERNAL_SERVER_ERROR) {
                    $position = strpos($response->body, ':');
                    if ($position) {
                        $error = substr($response->body, 0, $position);
                        $msg = substr($response->body, $position + 1, strlen($response->body));
                        if ($error == TypeException::CONVERSION_EXCEPTION) {
                            throw new ConversionException($error . ': ' . $msg);
                        } else if ($error == TypeException::NOT_IMPLEMENTED_EXCEPTION) {
                            throw new NotImplementedException($error . ': ' . $msg);
                        } else {
                            throw new UnknowException($error . ': ' . $msg);
                        }
                    } else {
                        throw new UnknowException("HTTP error code " . $response->code . ": " . $response->body);
                    }
                } else {
                    throw new UnknowException("HTTP error code " . $response->code . ": " . $response->body);
                }
            }
        } catch (ConnectionErrorException $cee) {
            throw new ConnectionErrorException('ConnectionErrorException: ' . $cee->getMessage());
        }
    }

    /**
     * Retrieve the uploaded image with transformation.
     * 
     * Using this method you are really executing on server side the ImageMagick convert tool.
     * You can set a lot of parameters - transformations - in params variable. Take a look at ImageMagick convert tool to get a complete list of them.
     * 
     * The image convert tool must be enabled in OpenKM server to get it running.
     * When params value is not empty always must contains ends with the chain "${fileIn} ${fileOut}".
     * Ensure there is only a white space as separator between two parameters.
     * When building your integrations, we suggest installing ImageMagic software locally, and check your image transformations first from your command line.
     * 
     * @param string $content Recommend using file_get_contents — Reads entire file into a string
     * @param string $fileName The document file name. Application uses this parameter to identify by document extension the document MIME TYPE.
     * @param string $params
     * @param string $dstMimeType The expected document MIME TYPE result.
     * @return string Retrieve the uploaded image with transformation.
     * @throws ConnectionErrorException
     * @throws AccessDeniedException
     * @throws IOException
     * @throws UnknowException
     */
    public function imageConvert($content, $fileName, $params, $dstMimeType) {
        try {
            $uri = UriHelper::getUri($this->host, UriHelper::CONVERT_IMAGE_CONVERT);
            $body = [];

            $param = [];
            $param['params'] = $params;
            $param['dstMimeType'] = $dstMimeType;
            $body['params'] = $param;

            $files = [];
            $file['name'] = 'content';
            $file['body'] = $content;
            $file['fileName'] = $fileName;
            $files[] = $file;
            $body['files'] = $files;

            $client = Request::post($uri);
            $client->setCurlPostFile(true);
            $client->body($body, Mime::UPLOAD);
            $client->authenticateWith($this->user, $this->password);
            $client->expects(Mime::UPLOAD);
            $response = $client->send();
            if ($response->code == Status::OK) {
                return $response->body;
            } else {
                if ($response->code == Status::UNAUTHORIZED) {
                    throw new AccessDeniedException($response->body, $response->code);
                } else if ($response->code == Status::INTERNAL_SERVER_ERROR) {
                    $position = strpos($response->body, ':');
                    if ($position) {
                        $error = substr($response->body, 0, $position);
                        $msg = substr($response->body, $position + 1, strlen($response->body));
                        if ($error == TypeException::IO_EXCEPTION) {
                            throw new IOException($error . ': ' . $msg);
                        } else {
                            throw new UnknowException($error . ': ' . $msg);
                        }
                    } else {
                        throw new UnknowException("HTTP error code " . $response->code . ": " . $response->body);
                    }
                } else {
                    throw new UnknowException("HTTP error code " . $response->code . ": " . $response->body);
                }
            }
        } catch (ConnectionErrorException $cee) {
            throw new ConnectionErrorException('ConnectionErrorException: ' . $cee->getMessage());
        }
    }

    /**
     * Retrieve the PDF of an URL.
     * 
     * The HTML to PDF conversion tool must be enabled in OpenKM server to get it running.
     * 
     * @param string $url
     * @return string Retrieve the PDF of an URL.
     * @throws ConnectionErrorException
     * @throws AccessDeniedException
     * @throws ConversionException
     * @throws IOException
     * @throws UnknowException
     */
    public function html2pdf($url) {
        try {
            $uri = UriHelper::getUri($this->host, UriHelper::CONVERT_HTML_TO_PDF);
            $uri .= '?url=' . urlencode($url);
            $client = Request::get($uri);
            $response = $this->getClient($client);
            if ($response->code == Status::OK) {
                return $response->body;
            } else {
                if ($response->code == Status::UNAUTHORIZED) {
                    throw new AccessDeniedException($response->body, $response->code);
                } else if ($response->code == Status::INTERNAL_SERVER_ERROR) {
                    $position = strpos($response->body, ':');
                    if ($position) {
                        $error = substr($response->body, 0, $position);
                        $msg = substr($response->body, $position + 1, strlen($response->body));
                        if ($error == TypeException::CONVERSION_EXCEPTION) {
                            throw new ConversionException($error . ': ' . $msg);
                        } else if ($error == TypeException::IO_EXCEPTION) {
                            throw new IOException($error . ': ' . $msg);
                        } else {
                            throw new UnknowException($error . ': ' . $msg);
                        }
                    } else {
                        throw new UnknowException("HTTP error code " . $response->code . ": " . $response->body);
                    }
                } else {
                    throw new UnknowException("HTTP error code " . $response->code . ": " . $response->body);
                }
            }
        } catch (ConnectionErrorException $cee) {
            throw new ConnectionErrorException('ConnectionErrorException: ' . $cee->getMessage());
        }
    }

    /**
     * Extracts the text from the upload document.
     * 
     * Must be enabled a Text Extractor for the document MIME TYPE in OpenKM server to get it running.
     * 
     * @param string $content Recommend using file_get_contents — Reads entire file into a string
     * @param string $fileName The document file name. Application uses this parameter to identify by document extension the document MIME TYPE.
     * @return string Extracts the text from the upload document.
     * @throws ConnectionErrorException
     * @throws AccessDeniedException
     * @throws ConversionException
     * @throws NotImplementedException
     * @throws UnknowException
     */
    public function doc2txt($content, $fileName) {
        try {
            $uri = UriHelper::getUri($this->host, UriHelper::CONVERT_DOC_TO_TXT);
            $body = [];

            $params = [];
            $body['params'] = $params;

            $files = [];
            $file['name'] = 'content';
            $file['body'] = $content;
            $file['fileName'] = $fileName;
            $files[] = $file;
            $body['files'] = $files;

            $client = Request::post($uri);
            $client->setCurlPostFile(true);
            $client->body($body, Mime::UPLOAD);
            $client->authenticateWith($this->user, $this->password);
            $client->expects(Mime::UPLOAD);
            $response = $client->send();
            if ($response->code == Status::OK) {
                return $response->body;
            } else {
                if ($response->code == Status::UNAUTHORIZED) {
                    throw new AccessDeniedException($response->body, $response->code);
                } else if ($response->code == Status::INTERNAL_SERVER_ERROR) {
                    $position = strpos($response->body, ':');
                    if ($position) {
                        $error = substr($response->body, 0, $position);
                        $msg = substr($response->body, $position + 1, strlen($response->body));
                        if ($error == TypeException::CONVERSION_EXCEPTION) {
                            throw new ConversionException($error . ': ' . $msg);
                        } else if ($error == TypeException::NOT_IMPLEMENTED_EXCEPTION) {
                            throw new NotImplementedException($error . ': ' . $msg);
                        } else {
                            throw new UnknowException($error . ': ' . $msg);
                        }
                    } else {
                        throw new UnknowException("HTTP error code " . $response->code . ": " . $response->body);
                    }
                } else {
                    throw new UnknowException("HTTP error code " . $response->code . ": " . $response->body);
                }
            }
        } catch (ConnectionErrorException $cee) {
            throw new ConnectionErrorException('ConnectionErrorException: ' . $cee->getMessage());
        }
    }

    /**
     * Extracts the text from the uploaded image.
     * 
     * The OCR engine must be enabled in OpenKM server to get it running.
     * 
     * @param string $content Recommend using file_get_contents — Reads entire file into a string
     * @param string $fileName The document file name. Application uses this parameter to identify by document extension the document MIME TYPE.
     * @return string Extracts the text from the uploaded image.
     * @throws ConnectionErrorException
     * @throws AccessDeniedException
     * @throws ConversionException
     * @throws NotImplementedException
     * @throws UnknowException
     */
    public function img2txt($content, $fileName) {
        try {
            $uri = UriHelper::getUri($this->host, UriHelper::CONVERT_IMAGE_TO_TXT);
            $body = [];

            $params = [];
            $body['params'] = $params;

            $files = [];
            $file['name'] = 'content';
            $file['body'] = $content;
            $file['fileName'] = $fileName;
            $files[] = $file;
            $body['files'] = $files;

            $client = Request::post($uri);
            $client->setCurlPostFile(true);
            $client->body($body, Mime::UPLOAD);
            $client->authenticateWith($this->user, $this->password);
            $client->expects(Mime::UPLOAD);
            $response = $client->send();
            if ($response->code == Status::OK) {
                return $response->body;
            } else {
                if ($response->code == Status::UNAUTHORIZED) {
                    throw new AccessDeniedException($response->body, $response->code);
                } else if ($response->code == Status::INTERNAL_SERVER_ERROR) {
                    $position = strpos($response->body, ':');
                    if ($position) {
                        $error = substr($response->body, 0, $position);
                        $msg = substr($response->body, $position + 1, strlen($response->body));
                        if ($error == TypeException::CONVERSION_EXCEPTION) {
                            throw new ConversionException($error . ': ' . $msg);
                        } else if ($error == TypeException::NOT_IMPLEMENTED_EXCEPTION) {
                            throw new NotImplementedException($error . ': ' . $msg);
                        } else {
                            throw new UnknowException($error . ': ' . $msg);
                        }
                    } else {
                        throw new UnknowException("HTTP error code " . $response->code . ": " . $response->body);
                    }
                } else {
                    throw new UnknowException("HTTP error code " . $response->code . ": " . $response->body);
                }
            }
        } catch (ConnectionErrorException $cee) {
            throw new ConnectionErrorException('ConnectionErrorException: ' . $cee->getMessage());
        }
    }

    /**
     * Extracts the barcode text from the uploaded image.
     * 
     * The Bar Code tool must be enabled in OpenKM server to get it running.
     * 
     * @param string $content Recommend using file_get_contents — Reads entire file into a string
     * @param string $fileName The document file name. Application uses this parameter to identify by document extension the document MIME TYPE.
     * @return string Extracts the barcode text from the uploaded image.
     * @throws ConnectionErrorException
     * @throws AccessDeniedException
     * @throws ConversionException
     * @throws NotImplementedException
     * @throws UnknowException
     */
    public function barcode2txt($content, $fileName) {
        try {
            $uri = UriHelper::getUri($this->host, UriHelper::CONVERT_BARCODE_TO_TXT);
            $body = [];

            $params = [];
            $body['params'] = $params;

            $files = [];
            $file['name'] = 'content';
            $file['body'] = $content;
            $file['fileName'] = $fileName;
            $files[] = $file;
            $body['files'] = $files;

            $client = Request::post($uri);
            $client->setCurlPostFile(true);
            $client->body($body, Mime::UPLOAD);
            $client->authenticateWith($this->user, $this->password);
            $client->expects(Mime::UPLOAD);
            $response = $client->send();
            if ($response->code == Status::OK) {
                return $response->body;
            } else {
                if ($response->code == Status::UNAUTHORIZED) {
                    throw new AccessDeniedException($response->body, $response->code);
                } else if ($response->code == Status::INTERNAL_SERVER_ERROR) {
                    $position = strpos($response->body, ':');
                    if ($position) {
                        $error = substr($response->body, 0, $position);
                        $msg = substr($response->body, $position + 1, strlen($response->body));
                        if ($error == TypeException::CONVERSION_EXCEPTION) {
                            throw new ConversionException($error . ': ' . $msg);
                        } else if ($error == TypeException::NOT_IMPLEMENTED_EXCEPTION) {
                            throw new NotImplementedException($error . ': ' . $msg);
                        } else {
                            throw new UnknowException($error . ': ' . $msg);
                        }
                    } else {
                        throw new UnknowException("HTTP error code " . $response->code . ": " . $response->body);
                    }
                } else {
                    throw new UnknowException("HTTP error code " . $response->code . ": " . $response->body);
                }
            }
        } catch (ConnectionErrorException $cee) {
            throw new ConnectionErrorException('ConnectionErrorException: ' . $cee->getMessage());
        }
    }

}

?>
