File indexing completed on 2024-06-16 05:27:01

0001 <?php
0002 
0003 /**
0004  *  ocs-webserver
0005  *
0006  *  Copyright 2016 by pling GmbH.
0007  *
0008  *    This file is part of ocs-webserver.
0009  *
0010  *    This program is free software: you can redistribute it and/or modify
0011  *    it under the terms of the GNU Affero General Public License as
0012  *    published by the Free Software Foundation, either version 3 of the
0013  *    License, or (at your option) any later version.
0014  *
0015  *    This program is distributed in the hope that it will be useful,
0016  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
0017  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
0018  *    GNU Affero General Public License for more details.
0019  *
0020  *    You should have received a copy of the GNU Affero General Public License
0021  *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
0022  **/
0023 class Default_Model_DbTable_Image extends Zend_Db_Table_Abstract
0024 {
0025     protected $_name = "image";
0026     protected $_fields = array(
0027         'id'          => null,
0028         'filename'    => null,
0029         'code'        => null,
0030         'name'        => null,
0031         'member_id'   => null,
0032         'model'       => null,
0033         'foreign_key' => null,
0034         'foreign_id'  => null,
0035         'created'     => null
0036     );
0037     protected $_allowed = array(
0038         'image/jpeg'          => '.jpg',
0039         'image/jpg'           => '.jpg',
0040         'image/png'           => '.png',
0041         'image/gif'           => '.gif',
0042         'application/x-empty' => '.png'
0043     );
0044     protected $_allowedFileExtension = array(
0045         'jpg',
0046         'jpeg',
0047         'png',
0048         'gif'
0049     );
0050     // protected $_maxsize = array(
0051     //     'width'  => 1024,
0052     //     'height' => 768
0053     // );
0054      protected $_maxsize = array(
0055         'width'  => 2000,
0056         'height' => 2000
0057     );
0058     protected $_errorMsg = null;
0059 
0060     public function getMemberImages($member_id)
0061     {
0062         $images = $this->select()->where('member_id = ?', $member_id)->query()->fetchAll();
0063 
0064         return $images;
0065     }
0066 
0067     public function storeExternalImage($url, $fileExtension = null)
0068     {
0069         Zend_Registry::get('logger')->debug(__METHOD__ . ' - ' . print_r(func_get_args(), true));
0070         $tmpFileName = $this->storeRemoteImage($url, $fileExtension);
0071 
0072         if (file_exists(IMAGES_UPLOAD_PATH . 'tmp/' . $tmpFileName)) {
0073             $content_type = mime_content_type(IMAGES_UPLOAD_PATH . 'tmp/' . $tmpFileName);
0074             $filePath = $this->saveImageOnMediaServer($tmpFileName);
0075             $filename = $filePath;
0076             $file_info['size'] = filesize(IMAGES_UPLOAD_PATH . '/' . $filename);
0077             $this->save(array('code' => $content_type, 'filename' => $filename));
0078         }
0079 
0080         return $filename;
0081     }
0082 
0083     public function storeRemoteImage($url, $fileExtention = null, &$file_info = null)
0084     {
0085         //$host = parse_url( $url, PHP_URL_HOST );
0086         //$path = parse_url($url, PHP_URL_PATH);
0087         //$query = parse_url($url, PHP_URL_QUERY);
0088 
0089         //$url = 'http://'.$host.$path.'?'.urlencode($query);
0090         $limit = 4194304; #4Mb
0091         $filename = md5($url);
0092         if ($fileExtention) {
0093             $filename .= '.' . $fileExtention;
0094         }
0095         $file_info = array();
0096         if (file_exists(IMAGES_UPLOAD_PATH . 'tmp/' . $filename)) {
0097             // Delete old file. Maybe an updated version is available.
0098             if (false == unlink(IMAGES_UPLOAD_PATH . 'tmp/' . $filename)) {
0099                 throw new Exception('Cannot delete file: ' . IMAGES_UPLOAD_PATH . 'tmp/' . $filename);
0100             }
0101         }
0102         try {
0103             #$file = file_get_contents($url, NULL, NULL, -1, $limit);
0104             $file = $this->file_get_contents_curl($url);
0105         } catch (Exception $e) {
0106             $file = null;
0107         }
0108         if (file_put_contents(IMAGES_UPLOAD_PATH . 'tmp/' . $filename, $file)) {
0109             $content_type = $this->_get_mime_content_type(IMAGES_UPLOAD_PATH . 'tmp/' . $filename);
0110             if (!in_array($content_type, array_keys($this->_allowed))) {
0111                 throw new Exception('Format not allowed ' . $content_type . ' for url ' . $url);
0112             }
0113             touch(IMAGES_UPLOAD_PATH . 'tmp/' . $filename);
0114         } else {
0115             throw new Exception('Error storing remote image');
0116         }
0117 
0118         $file_info['size'] = filesize(IMAGES_UPLOAD_PATH . 'tmp/' . $filename);
0119 
0120         return $filename;
0121     }
0122 
0123     public function file_get_contents_curl($url)
0124     {
0125         $ch = curl_init();
0126 
0127         curl_setopt($ch, CURLOPT_AUTOREFERER, true);
0128         curl_setopt($ch, CURLOPT_HEADER, 0);
0129         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
0130         curl_setopt($ch, CURLOPT_URL, $url);
0131         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
0132 
0133         $data = curl_exec($ch);
0134         curl_close($ch);
0135 
0136         return $data;
0137     }
0138 
0139     public function _get_mime_content_type($filename)
0140     {
0141 
0142         if (!function_exists('mime_content_type')) {
0143 
0144             $mime_types = array(
0145 
0146                 'txt'  => 'text/plain',
0147                 'htm'  => 'text/html',
0148                 'html' => 'text/html',
0149                 'php'  => 'text/html',
0150                 'css'  => 'text/css',
0151                 'js'   => 'application/javascript',
0152                 'json' => 'application/json',
0153                 'xml'  => 'application/xml',
0154                 'swf'  => 'application/x-shockwave-flash',
0155                 'flv'  => 'video/x-flv',
0156                 // images
0157                 'png'  => 'image/png',
0158                 'jpe'  => 'image/jpeg',
0159                 'jpeg' => 'image/jpeg',
0160                 'jpg'  => 'image/jpeg',
0161                 'gif'  => 'image/gif',
0162                 'bmp'  => 'image/bmp',
0163                 'ico'  => 'image/vnd.microsoft.icon',
0164                 'tiff' => 'image/tiff',
0165                 'tif'  => 'image/tiff',
0166                 'svg'  => 'image/svg+xml',
0167                 'svgz' => 'image/svg+xml',
0168                 // archives
0169                 'zip'  => 'application/zip',
0170                 'rar'  => 'application/x-rar-compressed',
0171                 'exe'  => 'application/x-msdownload',
0172                 'msi'  => 'application/x-msdownload',
0173                 'cab'  => 'application/vnd.ms-cab-compressed',
0174                 // audio/video
0175                 'mp3'  => 'audio/mpeg',
0176                 'qt'   => 'video/quicktime',
0177                 'mov'  => 'video/quicktime',
0178                 // adobe
0179                 'pdf'  => 'application/pdf',
0180                 'psd'  => 'image/vnd.adobe.photoshop',
0181                 'ai'   => 'application/postscript',
0182                 'eps'  => 'application/postscript',
0183                 'ps'   => 'application/postscript',
0184                 // ms office
0185                 'doc'  => 'application/msword',
0186                 'rtf'  => 'application/rtf',
0187                 'xls'  => 'application/vnd.ms-excel',
0188                 'ppt'  => 'application/vnd.ms-powerpoint',
0189                 // open office
0190                 'odt'  => 'application/vnd.oasis.opendocument.text',
0191                 'ods'  => 'application/vnd.oasis.opendocument.spreadsheet',
0192             );
0193 
0194             $ext = strtolower(array_pop(explode('.', $filename)));
0195             if (array_key_exists($ext, $mime_types)) {
0196                 return $mime_types[$ext];
0197             } else if (function_exists('finfo_open')) {
0198                 $finfo = finfo_open(FILEINFO_MIME);
0199                 $mimetype = finfo_file($finfo, $filename);
0200                 finfo_close($finfo);
0201 
0202                 return $mimetype;
0203             } else {
0204                 return 'application/octet-stream';
0205             }
0206         } else {
0207             return mime_content_type($filename);
0208         }
0209     }
0210 
0211     public function saveImageOnMediaServer($filePathName)
0212     {
0213         if (empty($filePathName)) {
0214             return null;
0215         }
0216 
0217         $content_type = mime_content_type($filePathName);
0218 
0219         if (!in_array($content_type, array_keys($this->_allowed))) {
0220             throw new Exception('Format not allowed: ' . $content_type . ' for img: ' . $filePathName);
0221         }
0222 
0223         // Generate filename
0224         $generatedFilename = $this->_generateFilename($filePathName);
0225         $destinationFile = IMAGES_UPLOAD_PATH . $generatedFilename . $this->_allowed[$content_type];
0226 
0227         if (copy($filePathName, $destinationFile)) {
0228             if (file_exists($filePathName)) {
0229                 if (false === unlink($filePathName)) {
0230                     Zend_Registry::get('logger')->warn(__METHOD__ . ' - can not delete temp file: ' . $filePathName);
0231                 }
0232             }
0233             Zend_Registry::get('logger')->debug(__METHOD__ . ' - Start upload picture - ' . print_r($destinationFile,
0234                     true))
0235             ;
0236             $srcPathOnMediaServer = $this->sendImageToMediaServer($destinationFile, $content_type);
0237             if (file_exists($destinationFile)) {
0238                 if (false === unlink($destinationFile)) {
0239                     Zend_Registry::get('logger')->warn(__METHOD__ . ' - can not delete file: ' . $destinationFile);
0240                 }
0241             }
0242             if (!$srcPathOnMediaServer) {
0243                 throw new Exception("Error in upload to CDN-Server. \n Server message:\n" . $this->_errorMsg);
0244             }
0245 
0246             Zend_Registry::get('logger')->debug(__METHOD__ . ' - End upload picture - ' . print_r(IMAGES_UPLOAD_PATH
0247                     . $srcPathOnMediaServer, true))
0248             ;
0249 
0250             return $srcPathOnMediaServer;
0251         }
0252     }
0253 
0254     private function _generateFilename($filePathName)
0255     {
0256         return sha1_file($filePathName);
0257     }
0258 
0259     /**
0260      * @param $fullFilePath
0261      * @param $mimeType
0262      *
0263      * @return string
0264      * @throws Zend_Exception
0265      * @throws Zend_Http_Client_Exception
0266      * @throws Zend_Uri_Exception
0267      */
0268     protected function sendImageToMediaServer($fullFilePath, $mimeType)
0269     {
0270         $config = Zend_Registry::get('config');
0271         $url = $config->images->media->upload;
0272 
0273         $client = new Zend_Http_Client($url);
0274         $client->setFileUpload($fullFilePath, basename($fullFilePath), null, $mimeType);
0275 
0276         $response = $client->request('POST');
0277 
0278         if ($response->getStatus() > 200) {
0279             throw new Default_Model_Exception_Image('Could not upload file to ' . $url . ' - server response: ' . $response->getBody());
0280         }
0281 
0282         return $response->getBody();
0283     }
0284 
0285     public function save($image)
0286     {
0287         foreach ($image as $key => $value) {
0288             if (!in_array($key, array_keys($this->_fields))) {
0289                 unset($image[$key]);
0290             }
0291         }
0292 
0293         if (isset($image['filename']) && !isset($image['code'])) {
0294             $image['code'] = $this->_trimExtension($image['filename']);
0295         }
0296 
0297         if (isset($image['id'])) {
0298             return $this->_update($image);
0299         } else {
0300             return $this->_add($image);
0301         }
0302     }
0303 
0304     private function _update($image)
0305     {
0306         if (!isset($image['id'])) {
0307             throw new Exception('Invalid update without an id');
0308         } else {
0309             $id = (int)$image['id'];
0310         }
0311 
0312         return $this->update($image, array('id = ?' => $id));
0313     }
0314 
0315     private function _add($image)
0316     {
0317         return $this->insert($image);
0318     }
0319 
0320     /**
0321      * @param Zend_Form_Element_File $formFileElement
0322      *
0323      * @return string
0324      * @throws Zend_Exception
0325      * @todo wrong place for this method
0326      */
0327     public function saveImage($formFileElement)
0328     {
0329         if (empty($formFileElement)) {
0330             Zend_Registry::get('logger')->err(__METHOD__ . ' - form file element empty');
0331             return null;
0332         }
0333 
0334         $filesInfo = $formFileElement->getFileInfo();
0335 
0336         if (1 < count($filesInfo)) {
0337             throw new Zend_Exception('Element contains more than one file elements');
0338         }
0339 
0340         foreach ($filesInfo as $file => $fileInfo) {
0341             if (null == $fileInfo['size']) {
0342                 return null;
0343             }
0344             $contentType = mime_content_type($fileInfo['tmp_name']);
0345             if (false === in_array($contentType, array_keys($this->_allowed))) {
0346                 throw new Zend_Exception('Format not allowed: ' . $contentType . ' for img: ' . $fileInfo['name']);
0347             }
0348             $generatedFilename = $this->_generateFilename($fileInfo['tmp_name']);
0349             $destinationFile = IMAGES_UPLOAD_PATH . $generatedFilename . $this->_allowed[$contentType];
0350             Zend_Registry::get('logger')->info(__METHOD__ . ' - destination file path: ' . $destinationFile);
0351 
0352             if (copy($fileInfo['tmp_name'], $destinationFile)) {
0353                 if (file_exists($fileInfo['tmp_name'])) {
0354                     if (false === unlink($fileInfo['tmp_name'])) {
0355                         Zend_Registry::get('logger')->warn(__METHOD__ . ' - can not delete temp file: '
0356                             . $fileInfo['tmp_name'])
0357                         ;
0358                     }
0359                 }
0360                 Zend_Registry::get('logger')->debug(__METHOD__ . ' - Start upload picture - '
0361                     . print_r($destinationFile, true))
0362                 ;
0363                 $srcPathOnMediaServer = $this->sendImageToMediaServer($destinationFile, $contentType);
0364                 if (file_exists($destinationFile)) {
0365                     if (false === unlink($destinationFile)) {
0366                         Zend_Registry::get('logger')->warn(__METHOD__ . ' - can not delete file: ' . $destinationFile);
0367                     }
0368                 }
0369                 if (!$srcPathOnMediaServer) {
0370                     throw new Zend_Exception("Error in upload to CDN-Server. \n Server message:\n" . $this->_errorMsg);
0371                 }
0372                 Zend_Registry::get('logger')->debug(__METHOD__ . ' - End upload a picture - '
0373                     . print_r(IMAGES_UPLOAD_PATH . $srcPathOnMediaServer, true))
0374                 ;
0375 
0376                 return $srcPathOnMediaServer;
0377             }
0378         }
0379     }
0380 
0381     /**
0382      * @param Zend_Form_Element_File $formFileElement
0383      *
0384      * @return array
0385      * @throws Zend_Exception
0386      */
0387     public function saveImages($formFileElement)
0388     {
0389         if (empty($formFileElement)) {
0390             return array();
0391         }
0392 
0393         $resultPath = array();
0394         $filesInfo = $formFileElement->getFileInfo();
0395 
0396         foreach ($filesInfo as $file => $fileInfo) {
0397             if (null == $fileInfo['size']) {
0398                 continue;
0399             }
0400             $contentType = mime_content_type($fileInfo['tmp_name']);
0401             if (!in_array($contentType, array_keys($this->_allowed))) {
0402                 throw new Zend_Exception('Format not allowed: ' . $contentType . ' for img: ' . $fileInfo['name']);
0403             }
0404             $generatedFilename = $this->_generateFilename($fileInfo['tmp_name']);
0405             $destinationFile = IMAGES_UPLOAD_PATH . $generatedFilename . $this->_allowed[$contentType];
0406 
0407             if (copy($fileInfo['tmp_name'], $destinationFile)) {
0408                 Zend_Registry::get('logger')->debug(__METHOD__ . ' - Start upload picture - '
0409                     . print_r($destinationFile, true))
0410                 ;
0411                 $srcPathOnMediaServer = $this->sendImageToMediaServer($destinationFile, $contentType);
0412                 if (!$srcPathOnMediaServer) {
0413                     throw new Zend_Exception("Error in upload to CDN-Server. \n Server message:\n" . $this->_errorMsg);
0414                 }
0415                 Zend_Registry::get('logger')->debug(__METHOD__ . ' - End upload a picture - '
0416                     . print_r(IMAGES_UPLOAD_PATH . $srcPathOnMediaServer, true))
0417                 ;
0418 
0419                 $resultPath[] = $srcPathOnMediaServer;
0420             }
0421         }
0422 
0423         return $resultPath;
0424     }
0425 
0426     public function getAllowedFileExtension()
0427     {
0428         return $this->_allowedFileExtension;
0429     }
0430 
0431     public function getAllowedMimeTypes()
0432     {
0433         return array_keys($this->getAllowed());
0434     }
0435 
0436     public function getAllowed()
0437     {
0438         return $this->_allowed;
0439     }
0440 
0441     public function setAllowed($allowed)
0442     {
0443         $this->_allowed = $allowed;
0444     }
0445 
0446     public function getMaxsize()
0447     {
0448         return $this->_maxsize;
0449     }
0450 
0451     public function setMaxsize($maxsize)
0452     {
0453         $this->_maxsize = $maxsize;
0454     }
0455 
0456 }