joomla-2.5 /media/zoo/elements/download/download.php

Language PHP Lines 428
MD5 Hash bb49124a2816e3c83e0733f1100ef803 Estimated Cost $5,064 (why?)
Repository https://bitbucket.org/organicdevelopment/joomla-2.5.git View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
<?php
/**
* @package   com_zoo
* @author    YOOtheme http://www.yootheme.com
* @copyright Copyright (C) YOOtheme GmbH
* @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
*/

// register ElementFile class
App::getInstance('zoo')->loader->register('ElementFile', 'elements:file/file.php');

/*
	Class: ElementDownload
		The file download element class
*/
class ElementDownload extends ElementFile implements iSubmittable {

	/*
	   Function: Constructor
	*/
	public function __construct() {

		// call parent constructor
		parent::__construct();

		// set defaults
		$this->config->set('secret', $this->app->system->config->getValue('config.secret'));

		// set callbacks
		$this->registerCallback('download');

		if ($this->app->system->application->isAdmin()) {
			$this->registerCallback('reset');
			$this->registerCallback('files');
		}
	}

	/*
		Function: getSize
			Gets the download file size.

		Returns:
			String - Download file with KB/MB suffix
	*/
	public function getSize() {
		return $this->app->filesystem->formatFilesize($this->get('size', 0));
	}

	/*
		Function: getSize
			Gets the download file size.

		Returns:
			String - Download file with KB/MB suffix
	*/
	public function isDownloadLimitReached() {
		return ($limit = $this->get('download_limit')) && $this->get('hits', 0) >= $limit;
	}

	/*
		Function: getLink
			Gets the link to the download.

		Returns:
			String - link
	*/
	public function getLink() {

		// init vars
		$download_mode = $this->config->get('download_mode');

		// create download link
		$query = array('task' => 'callelement', 'format' => 'raw', 'item_id' => $this->_item->id, 'element' => $this->identifier, 'method' => 'download');

		if ($download_mode == 1) {
			return $this->app->link($query);
		} else if ($download_mode == 2) {
			$query['args[0]'] = $this->filecheck();
			return $this->app->link($query);
		} else {
			return $this->get('file');
		}

	}

	/*
		Function: render
			Renders the element.

	   Parameters:
   			$params - render parameter

		Returns:
			String - html
	*/
	public function render($params = array()) {

		// init vars
		$params = $this->app->data->create($params);
		$file = $this->get('file');
		$filename = basename($file);

		// render layout
		if ($layout = $this->getLayout()) {
			return $this->renderLayout($layout,
				array(
					'file' => $file,
					'filename' => $filename,
					'size' => $this->getSize(),
					'hits' => (int) $this->get('hits', 0),
					'download_name' => $this->app->string->str_ireplace('{filename}', $filename, $params->get('download_name', '')),
					'download_link' => $this->getLink(),
					'filetype' => $this->getExtension(),
					'display' => $params->get('display', null),
					'limit_reached' => $this->isDownloadLimitReached(),
					'download_limit' => $this->get('download_limit')
				)
			);
		}
	}

	/*
		Function: download
			Download the file.

		Returns:
			Binary - File data
	*/
	public function download($check = '') {

		// init vars
		$filepath = $this->app->path->path('root:'.$this->get('file'));
		$download_mode = $this->config->get('download_mode');

		// check access
		if (!$this->canAccess()) {
			header('Content-Type: text/html');
			echo JText::_('Unable to access download!');
			return;
		}

		// check limit
		if ($this->isDownloadLimitReached()) {
			header('Content-Type: text/html');
			echo JText::_('Download limit reached!');
			return;
		}

		// trigger on download event
		$canDownload = true;
		$this->app->event->dispatcher->notify($this->app->event->create($this, 'element:download', array('check' => $check, 'canDownload' => &$canDownload)));

		if ($canDownload) {

			// output file
			if ($download_mode == 1 && is_readable($filepath) && is_file($filepath)) {
				$this->set('hits', $this->get('hits', 0) + 1);
				$this->app->filesystem->output($filepath);
			} else if ($download_mode == 2 && $this->filecheck() == $check && is_readable($filepath) && is_file($filepath)) {
				$this->set('hits', $this->get('hits', 0) + 1);
				$this->app->filesystem->output($filepath);
			} else {
				header('Content-Type: text/html');
				echo JText::_('Invalid file!');
			}

			// save item
			$this->app->table->item->save($this->getItem());

		}

	}

	/*
	   Function: filecheck
	       Get the file check string.

	   Returns:
	       String - md5(file + secret + date)
	*/
	public function filecheck() {
		return md5($this->get('file').$this->config->get('secret').date('Y-m-d'));
	}

	/*
	   Function: edit
	       Renders the edit form field.

	   Returns:
	       String - html
	*/
	public function edit(){

		// create info
		$info[] = JText::_('Size').': '.$this->getSize();
		$info[] = JText::_('Hits').': '.(int) $this->get('hits', 0);
		$info   = ' ('.implode(', ', $info).')';

        if ($layout = $this->getLayout('edit.php')) {
            return $this->renderLayout($layout,
                array(
					'info' => $info,
                    'hits' => $this->get('hits', 0)
                )
            );
        }

	}

	/*
		Function: loadAssets
			Load elements css/js assets.

		Returns:
			Void
	*/
	public function loadAssets() {
		parent::loadAssets();
		$this->app->document->addScript('elements:download/assets/js/download.js');
	}

	public function reset() {

		$this->set('hits', 0);

		//save item
		$this->app->table->item->save($this->getItem());

		return $this->edit();
	}

	/*
		Function: bindData
			Set data through data array.

		Parameters:
			$data - array

		Returns:
			Void
	*/
	public function bindData($data = array()) {
		parent::bindData($data);

		// add size to data
		$filepath = $this->app->path->path('root:'.$this->get('file'));
		if (is_readable($filepath) && is_file($filepath)) {
			$this->set('size', sprintf('%u', filesize($filepath)));
		} else {
			$this->set('size', 0);
		}
	}

	/*
		Function: renderSubmission
			Renders the element in submission.

	   Parameters:
            $params - AppData submission parameters

		Returns:
			String - html
	*/
	public function renderSubmission($params = array()) {

        // get params
        $trusted_mode = $params->get('trusted_mode');

        // init vars
        $upload = $this->get('file');

        if (empty($upload) && $trusted_mode) {
            $upload = $this->get('upload');
        }

        // is uploaded file
        $upload = is_array($upload) ? '' : $upload;

        // build upload select
        $lists = array();
        if ($trusted_mode) {
            $options = array($this->app->html->_('select.option', '', '- '.JText::_('Select File').' -'));
            if (!empty($upload) && !$this->_inUploadPath($upload)) {
                $options[] = $this->app->html->_('select.option', $upload, '- '.JText::_('No Change').' -');
            }
			foreach ($this->app->path->files('root:'.$this->_getUploadPath()) as $file) {
                $options[] = $this->app->html->_('select.option', $this->_getUploadPath().'/'.$file, basename($file));
            }
            $lists['upload_select'] = $this->app->html->_('select.genericlist', $options, $this->getControlName('upload'), 'class="upload"', 'value', 'text', $upload);
        }

        if (!empty($upload)) {
            $upload = basename($upload);
        }

        if ($layout = $this->getLayout('submission.php')) {
            return $this->renderLayout($layout,
                compact('lists', 'upload', 'trusted_mode')
            );
        }

	}

	/*
		Function: validateSubmission
			Validates the submitted element

	   Parameters:
            $value  - AppData value
            $params - AppData submission parameters

		Returns:
			Array - cleaned value
	*/
	public function validateSubmission($value, $params) {

        // init vars
        $trusted_mode = $params->get('trusted_mode');

        // get old file value
		$old_file = $this->get('file');

        $file = '';
        // get file from select list
        if ($trusted_mode && $file = $value->get('upload')) {

            if (!$this->_inUploadPath($file) && $file != $old_file) {
                throw new AppValidatorException(sprintf('This file is not located in the upload directory.'));
            }

            if (!JFile::exists($file)) {
                throw new AppValidatorException(sprintf('This file does not exist.'));
            }

        // get file from upload
        } else {

            try {

                // get the uploaded file information
                $userfile = $value->get('userfile', null);

				// get legal extensions
				$extensions = array_map(create_function('$ext', 'return strtolower(trim($ext));'), explode(',', $this->config->get('upload_extensions', 'png,jpg,doc,mp3,mov,avi,mpg,zip,rar,gz')));

				//get legal mime types
				$legal_mime_types = $this->app->data->create(array_intersect_key($this->app->filesystem->getMimeMapping(), array_flip($extensions)))->flattenRecursive();

				// get max upload size
				$max_upload_size = $this->config->get('max_upload_size', '512') * 1024;
				$max_upload_size = empty($max_upload_size) ? null : $max_upload_size;

				// validate
                $file = $this->app->validator
						->create('file', array('mime_types' => $legal_mime_types, 'max_size' => $max_upload_size))
						->addMessage('mime_types', 'Uploaded file is not of a permitted type.')
						->clean($userfile);

            } catch (AppValidatorException $e) {

                if ($e->getCode() != UPLOAD_ERR_NO_FILE) {
                    throw $e;
                }

                if (!$trusted_mode && $old_file && $value->get('upload')) {
                    $file = $old_file;
                }

            }

        }

        if ($params->get('required') && empty($file)) {
            throw new AppValidatorException('Please select a file to upload.');
        }

        $download_limit = (string) $this->app->validator
				->create('integer', array('required' => false), array('number' => 'The Download Limit needs to be a number.'))
				->clean($value->get('download_limit'));

		// connect to submission beforesave event
		$this->app->event->dispatcher->connect('submission:beforesave', array($this, 'submissionBeforeSave'));

		return compact('file', 'download_limit');
	}

	/*
		Function: submissionBeforeSave
			Callback before item submission is saved

		Returns:
			void
	*/
    public function submissionBeforeSave() {

        // get the uploaded file information
        if (($userfile = $this->get('file')) && is_array($userfile)) {
            // get file name
            $ext = $this->app->filesystem->getExtension($userfile['name']);
            $base_path = JPATH_ROOT . '/' . $this->_getUploadPath() . '/';
            $file = $base_path . $userfile['name'];
            $filename = basename($file, '.'.$ext);

            $i = 1;
            while (JFile::exists($file)) {
                $file = $base_path . $filename . '-' . $i++ . '.' . $ext;
            }

            if (!JFile::upload($userfile['tmp_name'], $file)) {
                throw new AppException('Unable to upload file.');
            }

			$this->app->zoo->putIndexFile(dirname($file));

            $this->set('file', $this->app->path->relative($file));

        }
    }

    protected function _inUploadPath($image) {
        return $this->_getUploadPath() == dirname($image);
    }

    protected function _getUploadPath() {
        return trim(trim($this->config->get('upload_directory', 'images/zoo/uploads/')), '\/');
    }

}
Back to Top