]> git.mxchange.org Git - friendica.git/blob - addon/js_upload/js_upload.php
Merge branch 'friendika-master'
[friendica.git] / addon / js_upload / js_upload.php
1 <?php
2
3
4 function js_upload_install() {
5         register_hooks('photo_post_init', 'addon/js_upload/js_upload.php', 'js_upload_post_init');
6         register_hooks('photo_post_file', 'addon/js_upload/js_upload.php', 'js_upload_post_file');
7         register_hooks('photo_post_end',  'addon/js_upload/js_upload.php', 'js_upload_post_end');
8 }
9
10
11 function js_upload_uninstall() {
12         register_hooks('photo_post_init', 'addon/js_upload/js_upload.php', 'js_upload_post_init');
13         register_hooks('photo_post_file', 'addon/js_upload/js_upload.php', 'js_upload_post_file');
14         register_hooks('photo_post_end',  'addon/js_upload/js_upload.php', 'js_upload_post_end');
15 }
16
17
18 function js_upload_post_init(&$a,&$b) {
19
20         // list of valid extensions, ex. array("jpeg", "xml", "bmp")
21
22         $allowedExtensions = array("jpeg","gif","png","jpg");
23
24         // max file size in bytes
25
26         $sizeLimit = 6 * 1024 * 1024;
27
28         $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
29         $result = $uploader->handleUpload('uploads/');
30
31         // to pass data through iframe you will need to encode all html tags
32         $a->data['upload_jsonresponse'] =  htmlspecialchars(json_encode($result), ENT_NOQUOTES);
33
34         if(isset($result['error'])) {
35                 logger('mod/photos.php: photos_post(): error uploading photo: ' . $result['error'] , 'LOGGER_DEBUG');
36                 killme();
37         }
38
39
40 }
41
42 function js_upload_photo_post_file(&$a,&$b) {
43
44         $b['src']               = 'uploads/'.$result['filename'];
45         $b['filename']  = $result['filename'];
46         $b['filesize']  = filesize($src);
47 }
48
49
50 function js_upload_photo_post_end(&$a,&$b) {
51
52         if(x($a->data,'upload_jsonresponse')) {
53                 echo $a->data['upload_jsonresponse'];
54                 @unlink($src);
55                 killme();
56         }
57
58 }
59
60
61 /**
62  * Handle file uploads via XMLHttpRequest
63  */
64 class qqUploadedFileXhr {
65     /**
66      * Save the file to the specified path
67      * @return boolean TRUE on success
68      */
69     function save($path) {    
70         $input = fopen("php://input", "r");
71         $temp = tmpfile();
72         $realSize = stream_copy_to_stream($input, $temp);
73         fclose($input);
74         
75         if ($realSize != $this->getSize()){            
76             return false;
77         }
78         
79         $target = fopen($path, "w");        
80         fseek($temp, 0, SEEK_SET);
81         stream_copy_to_stream($temp, $target);
82         fclose($target);
83         
84         return true;
85     }
86     function getName() {
87         return $_GET['qqfile'];
88     }
89     function getSize() {
90         if (isset($_SERVER["CONTENT_LENGTH"])){
91             return (int)$_SERVER["CONTENT_LENGTH"];            
92         } else {
93             throw new Exception('Getting content length is not supported.');
94         }      
95     }   
96 }
97
98 /**
99  * Handle file uploads via regular form post (uses the $_FILES array)
100  */
101 class qqUploadedFileForm {  
102     /**
103      * Save the file to the specified path
104      * @return boolean TRUE on success
105      */
106     function save($path) {
107         if(!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)){
108             return false;
109         }
110         return true;
111     }
112     function getName() {
113         return $_FILES['qqfile']['name'];
114     }
115     function getSize() {
116         return $_FILES['qqfile']['size'];
117     }
118 }
119 class qqFileUploader {
120     private $allowedExtensions = array();
121     private $sizeLimit = 10485760;
122     private $file;
123
124     function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760){        
125         $allowedExtensions = array_map("strtolower", $allowedExtensions);
126             
127         $this->allowedExtensions = $allowedExtensions;        
128         $this->sizeLimit = $sizeLimit;
129         
130         $this->checkServerSettings();       
131
132         if (isset($_GET['qqfile'])) {
133             $this->file = new qqUploadedFileXhr();
134         } elseif (isset($_FILES['qqfile'])) {
135             $this->file = new qqUploadedFileForm();
136         } else {
137             $this->file = false; 
138         }
139     }
140     
141     private function checkServerSettings(){        
142         $postSize = $this->toBytes(ini_get('post_max_size'));
143         $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));        
144                 logger('mod/photos.php: qqFileUploader(): upload_max_filesize=' . $uploadSize , 'LOGGER_DEBUG');
145         if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit){
146             $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';             
147             die("{'error':'increase post_max_size and upload_max_filesize to $size'}");    
148         }        
149     }
150     
151     private function toBytes($str){
152         $val = trim($str);
153         $last = strtolower($str[strlen($str)-1]);
154         switch($last) {
155             case 'g': $val *= 1024;
156             case 'm': $val *= 1024;
157             case 'k': $val *= 1024;        
158         }
159         return $val;
160     }
161     
162     /**
163      * Returns array('success'=>true) or array('error'=>'error message')
164      */
165     function handleUpload($uploadDirectory, $replaceOldFile = FALSE){
166         if (!is_writable($uploadDirectory)){
167             return array('error' => t('Server error. Upload directory isn't writable.'));
168         }
169         
170         if (!$this->file){
171             return array('error' => t('No files were uploaded.'));
172         }
173         
174         $size = $this->file->getSize();
175         
176         if ($size == 0) {
177             return array('error' => t('Uploaded file is empty'));
178         }
179         
180         if ($size > $this->sizeLimit) {
181
182             return array('error' => t('Uploaded file is too large'));
183         }
184         
185
186                 $maximagesize = get_config('system','maximagesize');
187
188                 if(($maximagesize) && ($size > $maximagesize)) {
189                         return array('error' => t('Image exceeds size limit of ') . $maximagesize );
190
191                 }
192
193         $pathinfo = pathinfo($this->file->getName());
194         $filename = $pathinfo['filename'];
195         //$filename = md5(uniqid());
196         $ext = $pathinfo['extension'];
197
198         if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){
199             $these = implode(', ', $this->allowedExtensions);
200             return array('error' => t('File has an invalid extension, it should be one of ') . $these . '.');
201         }
202         
203         if(!$replaceOldFile){
204             /// don't overwrite previous files that were uploaded
205             while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
206                 $filename .= rand(10, 99);
207             }
208         }
209         
210         if ($this->file->save($uploadDirectory . $filename . '.' . $ext)){
211             return array('success'=>true,'filename' => $filename . '.' . $ext);
212         } else {
213             return array('error'=> t('Could not save uploaded file.') .
214                 t('The upload was cancelled, or server error encountered'),'filename' => $filename . '.' . $ext);
215         }
216         
217     }    
218 }