3
* PHPDevShell is a RAD Framework aimed at developing administrative applications.
6
* @link http://www.phpdevshell.org
7
* @copyright Copyright (C) 2007 Jason Schoeman, All rights reserved.
8
* @license GNU/LGPL, see readme/licensed_under_lgpl or http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
9
* @author Jason Schoeman, Contact: titan [at] phpdevshell [dot] org.
11
* Copyright notice: See readme/notice
12
* By using PHPDevShell you agree to notice and license, if you dont agree to this notice/license you are not allowed to use PHPDevShell.
15
* This class handles file uploads in its simplest form.
21
* Should file uploads be logged to the database.
22
* Default will load settings from database.
26
public $log_uploads = 'default';
28
* The default upload relative path for files.
29
* Default will load settings from database.
34
public $default_upload_directory = 'default';
36
* Set permission for newly uploaded files.
37
* Default will load settings from database.
42
public $cmod = 'default';
44
* The maximum allowed file upload size.
45
* Default will load settings from database.
46
* Example : 1000 (1kb)
50
public $max_filesize = 'default';
52
* The maximum allowed image upload size.
53
* Default will load settings from database.
54
* Example : 1000 (1kb)
58
public $max_imagesize = 'default';
60
* The allowed extentions for uploads.
61
* Default will load settings from database.
62
* Example : jpg,png,gif
66
public $allowed_ext = 'default';
68
* Should thumbnails be created on image uploads.
69
* Default will load settings from database.
73
public $do_create_thumb = 'default';
75
* Image quality of converted images.
76
* Default will load settings from database.
81
public $image_quality = 'default';
83
* Typical resize type for thumbnails.
84
* Default will load settings from database.
85
* Options : resize | resizepercent | cropfromcenter | crop | adaptive
89
public $thumbnail_type = 'default';
91
* Adaptive adjust resizing.
92
* Default will load settings from database.
93
* [Max Width, Max Height] example (resize image to no wider than 250 pixels wide and 250 pixels high thumbnails to be uniformly sized) : 250,250
97
public $resize_adaptive_dimension = 'default';
100
* Default will load settings from database.
101
* [Max Width, Max Height] example (resize image to no wider than 250 pixels wide and 250 pixels high) : 250,250
105
public $resize_thumb_dimension = 'default';
107
* Resize by percentage.
108
* Default will load settings from database.
109
* [Percentage] example (reduce the image by 50%) : 50
113
public $resize_thumb_percent = 'default';
116
* Default will load settings from database.
117
* [Crop Size] example (create a 100x100 pixel crop from the center of an image) : 100
121
public $crop_thumb_fromcenter = 'default';
124
* Default will load settings from database.
125
* [startX, startY, width, height] example (create a 100x50 pixel crop from the top left corner of an image) : 0,0,100,50
129
public $crop_thumb_dimension = 'default';
131
* Add thumb reflections.
132
* Default will load settings from database.
136
public $do_thumb_reflect = 'default';
138
* Reflection options.
139
* Default will load settings from database.
140
* Data fields expected are [[Percentage of image], [Reflection percentage], [Transparency of reflection], [Set Border], [Border Color]. Example : 40,40,80,true,#a4a4a4
144
public $thumb_reflect_settings = 'default';
146
* This option will shrink a large image to a smaller then original viewable image. This should be larger then a thumbnail in most cases as this is the image the user can see when clicking on a thumbnail.
147
* Default will load settings from database.
151
public $do_create_resize_image = 'default';
153
* [Max Width, Max Height] example (resize image to no wider than 500 pixels wide and 500 pixels high) : 500,500
154
* Default will load settings from database.
158
public $resize_image_dimension = 'default';
160
* An alias to group the images with in a certain application.
161
* Will use active plugin name if left empty.
167
* Groups file upload by menu id.
168
* Will use active menu id if left empty.
174
* Groups file uploads to a specific document.
175
* Will use active menu id if left empty.
181
* The group a file batch belongs to.
182
* Will use uploaders primary group id if left empty.
188
* Convert pdf to image using convert in Linux.
189
* Please note imagemagick needs to be installed on Linux server.
193
public $convert_pdf = false;
195
* Choose the density image will be converted to from pdf.
199
public $convert_density = '300';
202
* Supports gd, imagick
206
public $graphics_engine = 'gd';
208
* When converting to pdf with multiple pages, image copies will be stored here.
212
public $image_copies = array();
214
* Holds a record of recently uploaded files.
218
public $upload_history = array();
221
* This method simply renames the file to unix standards.
223
* @param string $filename
224
* @param string $replace Replace odd characters with what?
226
public function safe_file_name ($filename, $replace = '_')
229
return $core->safe_name($filename, $replace);
233
* Get a files extension.
235
* @param string $filename
238
public function get_file_extension ($filename)
240
return end(explode('.', $filename));
244
* Get filename without extension.
246
* @param string $filename
249
public function get_file_base ($filename)
251
$filename_ = explode('.', $filename);
252
return $filename_[0];
256
* Takes a filename and checks what icon needs to go with it.
258
* @param string $extension_lookup
260
public function icon_type ($extension_lookup)
262
global $configuration;
263
if (empty($extension_lookup)) return false;
264
switch ($extension_lookup) {
266
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/archive.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
269
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/archive.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
272
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/archive.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
275
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/archive.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
278
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/archive.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
281
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/archive.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
284
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/archive.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
287
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/archive.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
290
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/doc.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
293
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/xls.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
296
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/eps.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
299
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/exe.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
302
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/fla.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
305
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/gif.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
308
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/html.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
311
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/html.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
314
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/jpg.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
317
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/jpg.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
320
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/pdf.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
323
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/psd.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
326
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/sig.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
329
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/swf.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
332
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/video2.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
335
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/video2.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
338
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/video.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
341
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/bin.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
344
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/txt.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
347
$icon = "<img src=\"{$configuration['absolute_url']}/themes/{$configuration['template_folder']}/images/icons/unknown.gif\" border=\"0\" alt=\"$extension_lookup\" title=\"$extension_lookup\">";
354
* Deletes a filename.
356
* @param string $filename
358
public function delete_filename ($filename = false)
360
if (! empty($filename)) {
361
if (file_exists($filename)) {
362
if (unlink($filename)) {
374
* Creates directory according to month and year.
376
* @param string $directory Writable directory where new directories will be created and files stored.
377
* @param integer $cmod
379
public function create_date_directory ($directory = false, $cmod = false)
383
// Create directory strings.
384
$year_directory = str_ireplace('//', '/', $directory . '/' . $year . '/');
385
$full_directory = str_ireplace('//', '/', $directory . '/' . $year . '/' . $month . '/');
386
$thumb_directory = str_ireplace('//', '/', $directory . '/' . $year . '/' . $month . '/thumbs/');
387
$resize_directory = str_ireplace('//', '/', $directory . '/' . $year . '/' . $month . '/resize/');
388
// Check if year exists.
389
if (! file_exists($year_directory)) {
390
mkdir($year_directory);
391
chmod($year_directory, $cmod);
392
touch($year_directory . 'index.html');
394
// Check if full folder exists.
395
if (! file_exists($full_directory)) {
396
mkdir($full_directory);
397
chmod($full_directory, $cmod);
398
touch($full_directory . 'index.html');
400
// Check if thumbs folder exists.
401
if (! file_exists($thumb_directory)) {
402
mkdir($thumb_directory);
403
chmod($thumb_directory, $cmod);
404
touch($thumb_directory . 'index.html');
406
// Check if thumbs folder exists.
407
if (! file_exists($resize_directory)) {
408
mkdir($resize_directory);
409
chmod($resize_directory, $cmod);
410
touch($resize_directory . 'index.html');
413
return $full_directory;
417
* Move file from temp directory to specified directory.
419
* @param string $uploaded_filename
420
* @param string $directory
421
* @param string $new_filename
423
public function upload_file ($uploaded_filename, $directory, $new_filename)
425
if (move_uploaded_file($uploaded_filename, $directory . basename($new_filename))) {
433
* Creates unique and safe filename.
436
public function rename_unique_filename ($filename, $extension = false)
438
if (empty($filename)) {
441
if ($extension == false) {
444
$extension_ = '.' . $extension;
446
$random = rand(0, 999999999);
447
$uniq = $this->safe_file_name($this->get_file_base($filename)) . '_' . uniqid($random) . $extension_;
453
* Simplifies the whole process of uploading files with type=file.
455
* @param string $input_name The name of the <form type="file" name="???" />
456
* @param string $file_overwrite_id The id of the log that needs to be overwritten.
457
* @param string $file_description a Simple file description for uploaded item.
459
* @return string Will return the complete uploaded directory with its filename.
461
public function auto_upload ($input_name, $file_overwrite_id = false, $file_description = false)
463
// Set global variables.
464
global $template, $lang, $db, $configuration, $core;
465
// Start Exception handling.
467
// Get database settings.
468
if (empty($this->setting)) {
469
$this->setting = $db->get_settings(array('log_uploads' , 'default_upload_directory' , 'cmod' , 'max_filesize' , 'max_imagesize' , 'allowed_ext' , 'do_create_thumb' , 'do_create_resize_image' , 'image_quality' , 'thumbnail_type' , 'resize_thumb_dimension' , 'resize_image_dimension' , 'resize_thumb_percent' , 'crop_thumb_fromcenter' , 'crop_thumb_dimension' , 'do_thumb_reflect' , 'thumb_reflect_settings', 'graphics_engine', 'resize_adaptive_dimension'), 'PHPDevShell');
471
// Do we have files uploaded?
472
if (! empty($_FILES[$input_name]['tmp_name']) && ! empty($_FILES[$input_name]['name'])) {
474
$tmp_name = $_FILES[$input_name]['tmp_name'];
475
$original_name = $_FILES[$input_name]['name'];
476
$uploaded_size = $_FILES[$input_name]['size'];
477
$mime_type = $_FILES[$input_name]['type'];
478
$extention_type = $this->get_file_extension($original_name);
479
// Determine standard file association variables.
480
(empty($this->sub_id)) ? $sub_id = $configuration['m'] : $sub_id = $this->sub_id;
481
(empty($this->menu_id)) ? $menu_id = $configuration['m'] : $menu_id = $this->menu_id;
482
(empty($this->alias)) ? $alias = $core->active_plugin() : $alias = $this->alias;
483
(empty($file_description)) ? $file_description = $original_name : false;
484
(empty($this->group_id)) ? $group_id = $configuration['user_group'] : $group_id = $this->group_id;
485
// Determine correct file upload options.
487
$graphics_engine = $this->setting($this->graphics_engine, $this->setting['graphics_engine'], 'gd');
488
define('DEFAULT_THUMBLIB_IMPLEMENTATION', $graphics_engine);
490
$log_uploads = $this->setting($this->log_uploads, $this->setting['log_uploads'], true, true);
491
// default_upload_directory
492
$default_upload_directory = $this->setting($this->default_upload_directory, $this->setting['default_upload_directory'], 'upload');
494
$cmod = $this->setting($this->cmod, octdec($this->setting['cmod']), 0644);
496
$max_filesize = $this->setting($this->max_filesize, $this->setting['max_filesize'], false);
498
$max_imagesize = $this->setting($this->max_imagesize, $this->setting['max_imagesize'], false);
500
$allowed_ext = $this->setting($this->allowed_ext, $this->setting['allowed_ext'], false);
502
$do_create_thumb = $this->setting($this->do_create_thumb, $this->setting['do_create_thumb'], true, true);
503
// do_create_resize_image
504
$do_create_resize_image = $this->setting($this->do_create_resize_image, $this->setting['do_create_resize_image'], true, true);
505
// resize_image_dimension
506
$resize_image_dimension = $this->setting($this->resize_image_dimension, $this->setting['resize_image_dimension'], '640,480');
507
$resize_image_dimension_ = explode(',', $resize_image_dimension);
509
$image_quality = $this->setting($this->image_quality, $this->setting['image_quality'], 80);
511
if (stripos($mime_type, 'image') !== false) {
512
$mime_upload = 'image';
513
$check_size = $max_imagesize;
515
$mime_upload = 'file';
516
$check_size = $max_filesize;
518
// Setup thumbnail settings.
519
$set_thumb = array('jpegQuality' => $image_quality);
520
//////////////////////////////////////////////////////////////
522
if (! empty($check_size) && ($uploaded_size > $check_size)) {
523
throw new Exception(sprintf(___('File %s is larger (%s) then the allowed size %s.'), $original_name, $this->display_filesize($uploaded_size), $this->display_filesize($check_size)));
526
// Check extentions allowed.
527
if (! empty($allowed_ext)) {
528
// Check if we have the required extention.
529
$extention_find = stripos($allowed_ext, $extention_type);
530
// Check if extention is allowed.
531
if ($extention_find === false) {
532
throw new Exception(sprintf(___('Extention type %s not allowed, allowed extention/s : %s'), $extention_type, $allowed_ext));
536
//////////////////////////////////////////////////////////////
539
// Create date directory.
540
$final_upload_path = $this->create_date_directory($default_upload_directory, $cmod);
541
// Create unique filename.
542
$unique_filename = $this->rename_unique_filename($original_name, $extention_type);
543
// Move files to correct folder.
544
if ($this->upload_file($tmp_name, $final_upload_path, $unique_filename)) {
545
// Check if we have a pdf and if we need to convert it.
546
if ($this->convert_pdf == true && $extention_type == 'pdf') {
547
$mime_upload = 'image';
548
$pdf_path = $final_upload_path . $unique_filename;
549
$jpg_file = str_replace(".pdf", ".jpg", "$unique_filename");
550
$jpg_path = $final_upload_path . $jpg_file;
551
exec("convert -density {$this->convert_density} -resize $resize_image_dimension_[0] -quality $image_quality $pdf_path $jpg_path");
552
$mime_type = 'image/jpg';
553
$extention_type = 'jpg';
554
// Check if system renamed it.
555
if (file_exists($jpg_path)) {
556
$unique_filename = $jpg_file;
558
$unique_filename = str_replace(".jpg", "-0.jpg", "$jpg_file");
560
// Finally delete old pdf.
561
$this->delete_filename($pdf_path);
563
// Initiate thumbnail.
564
if ($mime_upload == 'image') {
566
$thumbnail_path = $final_upload_path . 'thumbs/' . $unique_filename;
567
// Initiate thumb class.
568
$thumbnail = thumbnail::create($final_upload_path . $unique_filename, $set_thumb);
569
if (! empty($do_create_thumb)) {
571
$thumbnail_path = $final_upload_path . 'thumbs/' . $unique_filename;
572
// Initiate thumb class.
573
$resizeimg = thumbnail::create($final_upload_path . $unique_filename, $set_thumb);
575
$thumbnail_type = $this->setting($this->thumbnail_type, $this->setting['thumbnail_type'], 'resize');
576
// Set preferred settings.
577
switch ($thumbnail_type) {
579
// resize_thumb_dimension
580
$resize_thumb_dimension = $this->setting($this->resize_thumb_dimension, $this->setting['resize_thumb_dimension'], '150,150');
581
$resize_thumb_dimension_ = explode(',', $resize_thumb_dimension);
582
$thumbnail->resize($resize_thumb_dimension_[0], $resize_thumb_dimension_[1]);
584
case 'resizepercent':
585
// resize_thumb_percent
586
$resize_thumb_percent = $this->setting($this->resize_thumb_percent, $this->setting['resize_thumb_percent'], '40');
587
$thumbnail->resizePercent($resize_thumb_percent);
589
case 'cropfromcenter':
590
// crop_thumb_fromcenter
591
$crop_thumb_fromcenter = $this->setting($this->crop_thumb_fromcenter, $this->setting['crop_thumb_fromcenter'], '150');
592
$thumbnail->cropFromCenter($crop_thumb_fromcenter);
595
// crop_thumb_dimension
596
$crop_thumb_dimension = $this->setting($this->crop_thumb_dimension, $this->setting['crop_thumb_dimension'], '0,0,100,50');
597
$crop_thumb_dimension_ = explode(',', $crop_thumb_dimension);
598
$thumbnail->crop($crop_thumb_dimension_[0], $crop_thumb_dimension_[1], $crop_thumb_dimension_[2], $crop_thumb_dimension_[3]);
601
// crop_thumb_dimension
602
$resize_adaptive_dimension = $this->setting($this->resize_adaptive_dimension, $this->setting['resize_adaptive_dimension'], '250,250');
603
$resize_adaptive_dimension_ = explode(',', $resize_adaptive_dimension);
604
$thumbnail->adaptiveResize($resize_adaptive_dimension_[0], $resize_adaptive_dimension_[1]);
607
// resize_thumb_dimension
608
$resize_thumb_dimension = $this->setting($this->resize_thumb_dimension, $this->setting['resize_thumb_dimension'], '150,150');
609
$resize_thumb_dimension_ = explode(',', $resize_thumb_dimension);
610
$thumbnail->resize($resize_thumb_dimension_[0], $resize_thumb_dimension_[1]);
614
$do_thumb_reflect = $this->setting($this->do_thumb_reflect, $this->setting['do_thumb_reflect'], false, true);
615
// thumb_reflect_settings
616
if (! empty($do_thumb_reflect)) {
617
// thumb_reflect_settings
618
$thumb_reflect_settings = $this->setting($this->thumb_reflect_settings, $this->setting['thumb_reflect_settings'], '40,40,80,false,#fff');
619
$thumb_reflect_settings_ = explode(',', $thumb_reflect_settings);
620
$thumbnail->createReflection($thumb_reflect_settings_[0], $thumb_reflect_settings_[1], $thumb_reflect_settings_[2], $thumb_reflect_settings_[3], $thumb_reflect_settings_[4]);
622
//////////////////////////////////////////////
623
// Continue saving thumb image well. /////////
624
//////////////////////////////////////////////
625
// Finaly save thumbnail!
626
$thumbnail->save($thumbnail_path);
627
// Set needed permissions.
628
chmod($thumbnail_path, $cmod);
630
//////////////////////////////////////////////
631
// Continue saving a resized image as well. //
632
//////////////////////////////////////////////
633
if (! empty($do_create_resize_image)) {
635
$resized_view_path = $final_upload_path . 'resize/' . $unique_filename;
636
// Initiate thumb class.
637
$resizeimg = thumbnail::create($final_upload_path . $unique_filename, $set_thumb);
638
// Resize view image if we need it.
639
$dimension = $resizeimg->getCurrentDimensions();
640
if ($dimension['width'] > $resize_image_dimension_[0] || $dimension['height'] > $resize_image_dimension_[1]) $resizeimg->resize($resize_image_dimension_[0], $resize_image_dimension_[1]);
641
// Save resized image!
642
$resizeimg->save($resized_view_path);
643
// Set needed permissions.
644
chmod($resized_view_path, $cmod);
647
// We dont have an image so we wont have thumbs and resized images.
648
$thumbnail_path = false;
649
$resized_view_path = false;
651
// Should it be logged?
652
if (! empty($log_uploads)) {
653
// Now that all is good, lets log this entry to the database.
656
_db_core_upload_logs (file_id, sub_id, menu_id, alias, original_filename, new_filename, relative_path, thumbnail, resized, extention, mime_type, file_desc, group_id, user_id, date_stored, file_size)
658
('$file_overwrite_id', '$sub_id', '$menu_id', '$alias', '$original_name', '$unique_filename', '$final_upload_path', '$thumbnail_path', '$resized_view_path', '$extention_type', '$mime_type', '$file_description', '$group_id', '{$configuration['user_id']}', '{$configuration['time']}', '$uploaded_size')
661
// Set needed permissions.
662
chmod($final_upload_path . $unique_filename, $cmod);
663
// Return filename and relative path.
664
return $final_upload_path . $unique_filename;
674
} catch (Exception $e) {
675
throw new Exception($e->getMessage());
680
* Convert numeric into file size.
682
* @param numeric $filesize
684
* @author info@levaravel.com
686
public function display_filesize ($filesize)
690
if (is_numeric($filesize)) {
693
$prefix = array(___('Bytes'), ___('Kb'), ___('Mb'), ___('Gb'), ___('Tb'), ___('Pb'));
694
while (($filesize / $decr) > 0.9) {
695
$filesize = $filesize / $decr;
698
return round($filesize, 2) . ' ' . $prefix[$step];
705
* Internal check to see what thumbnail what settings to return.
707
* @param mixed $preferred_setting First passed through settings.
708
* @param mixed $database_setting Database called settings.
709
* @param mixed $fail_setting If all else fail use this setting.
710
* @param boolean $boolean Is setting a boolean value?
713
private function setting ($preferred_setting, $database_setting, $fail_setting, $boolean = false)
715
if (empty($boolean)) {
716
if ($preferred_setting == 'default' && ! empty($database_setting)) {
717
return $database_setting;
718
} else if (! empty($preferred_setting)) {
719
return $preferred_setting;
721
return $fail_setting;
724
if ($preferred_setting == 'default' && isset($database_setting)) {
725
return $database_setting;
726
} else if (isset($preferred_setting)) {
727
return $preferred_setting;
729
return $fail_setting;
735
* Build query for extracting stored files.
737
* @param integer $file_id Get only a single file with a file_id.
738
* @param string $alias Load only files by this alias.
739
* @param integer $sub_id Load only files by this sub_id.
740
* @param integer $menu_id Load only files by this menu_id.
743
private function build_file_query ($file_id = false, $alias = false, $sub_id = false, $menu_id = false)
746
$query_grouped = false;
747
// Check if we need a single file.
748
if (! empty($file_id)) {
749
$query_grouped = " WHERE file_id = '$file_id' ";
751
// Group WHERE queries first level.
752
if (! empty($alias)) {
753
$query_grouped .= " WHERE alias = '$alias' ";
754
} else if (! empty($sub_id)) {
755
$query_grouped .= " WHERE sub_id = '$sub_id' ";
757
} else if (! empty($menu_id)) {
758
$query_grouped .= " WHERE menu_id = '$menu_id' ";
761
// Group AND queries second level.
762
if (! empty($query_grouped)) {
763
if (! empty($sub_id) && empty($sub_id_set)) {
764
$query_grouped .= " AND sub_id = '$sub_id' ";
766
if (! empty($menu_id) && empty($menu_id_set)) {
767
$query_grouped .= " AND menu_id = '$menu_id' ";
770
// We need no queries here.
771
$query_grouped = false;
775
return $query_grouped;
779
* Delete file logs from database.
781
* @param integer $file_id Get only a single file with a file_id.
782
* @param string $alias Load only files by this alias.
783
* @param integer $sub_id Load only files by this sub_id.
784
* @param integer $menu_id Load only files by this menu_id.
785
* @return boolean Will return true if deleted.
787
public function delete_files ($file_id = false, $alias = false, $sub_id = false, $menu_id = false)
790
// Load deleted item.
791
$files = $this->load_files($file_id, $alias, $sub_id, $menu_id);
793
$query_grouped = $this->build_file_query($file_id, $alias, $sub_id, $menu_id);
801
foreach ($files as $fa) {
802
// Check if multiple images exists of a pdf conversion left over.
803
if (strstr($fa['download_file'], '-0.jpg')) {
804
$this->return_image_copies($fa['download_file']);
805
// Loop multiple images and list them.
806
if (!empty($this->image_copies)) {
807
foreach ($this->image_copies as $multiple_images_) {
808
$this->delete_filename($multiple_images_);
813
if (! empty($fa['download_file'])) $this->delete_filename($fa['download_file']);
815
if (! empty($fa['resized'])) $this->delete_filename($fa['resized']);
817
if (! empty($fa['thumbnail'])) $this->delete_filename($fa['thumbnail']);
827
* Load uploaded files from the log database.
829
* @param integer $file_id Get only a single file with a file_id.
830
* @param string $alias Load only files by this alias.
831
* @param integer $sub_id Load only files by this sub_id.
832
* @param integer $menu_id Load only files by this menu_id.
833
* @param string $order What the query should be ordered by. allows you to order by any of these column values : file_id, sub_id, menu_id, alias, original_filename, new_filename, relative_path, thumbnail, resized, extention, mime_type, file_desc, group_id, user_id, date_stored
834
* @param string $limit how many files should be returned in the array.
837
public function load_files ($file_id = false, $alias = false, $sub_id = false, $menu_id = false, $order = 'file_id DESC', $limit = '0,5')
841
$query_grouped = $this->build_file_query($file_id, $alias, $sub_id, $menu_id);
843
if (empty($file_id)) {
844
// Create order and limit query.
845
$order_by = " ORDER BY $order LIMIT $limit";
849
// Load files from database.
850
$load_files_db = $db->new_query("
873
// Loop and gather results.
874
while ($files_array = mysql_fetch_array($load_files_db)) {
875
// Create download filename.
876
$files_array['download_file'] = $files_array['relative_path'] . $files_array['new_filename'];
877
// Create human readable file size.
878
$files_array['format_file_size'] = $this->display_filesize($files_array['file_size']);
879
// Create extention image.
880
$files_array['extention_img'] = $this->icon_type($files_array['extention']);
882
$final_files_return[$files_array['file_id']] = $files_array;
886
if (! empty($final_files_return)) {
888
return $final_files_return;
890
// No results to return.
895
* Check if multiple images exists converted from a pdf with multiple pages.
897
* @param string $file
898
* @param int $nr The current file number in the loop.
900
public function return_image_copies ($file, $nr=0)
902
// Multiple files should exist, recall and check.
903
if (file_exists($file)) {
904
$this->image_copies[$nr] = $file;
906
$file_next = str_replace("-$nr.jpg", "-$nr_next.jpg", "$file");
907
$this->return_image_copies($file_next, $nr_next);
912
* Enables the caller to download a file to a local writable directory.
914
* @param $url The url to download from
915
* @param $copy_to The location to copy to add the name to the file too, example: /var/www/test.zip
918
public function download_file($url, $copy_to)
921
// Check if function exists.
922
if (!function_exists('curl_init')) {
923
throw new Exception(___('Oops cURL is not installed on your server, I cannot continue.'));
927
$out = fopen($copy_to, 'wb');
929
throw new Exception(sprintf(___('File %s could not be written to %s, please check permission, directories and if file exists.'), $url, $copy_to));
933
curl_setopt($ch, CURLOPT_FILE, $out);
934
curl_setopt($ch, CURLOPT_HEADER, 0);
935
curl_setopt($ch, CURLOPT_URL, $url);
937
if (curl_error($ch)) {
938
throw new Exception(sprintf(___('There was a cURL error : %s when I tried to copy to : %s'), curl_error($ch), $copy_to));
946
* Extracts a ZIP archive to the specified extract path
948
* @param string $file The ZIP archive to extract (including the path)
949
* @param string $extractPath The path to extract the ZIP archive to
951
* @return boolean TURE if the ZIP archive is successfully extracted, FALSE if there was an errror
954
public function zip_extract($file, $extractPath)
956
$zip = new ZipArchive();
957
$res = $zip->open($file);
959
$zip->extractTo($extractPath);
969
* Copy file or folder from source to destination, it can do
970
* recursive copy as well and is very smart
971
* It recursively creates the dest file or directory path if there weren't exists
973
* - Src:/home/test/file.txt ,Dst:/home/test/b ,Result:/home/test/b -> If source was file copy file.txt name with b as name to destination
974
* - Src:/home/test/file.txt ,Dst:/home/test/b/ ,Result:/home/test/b/file.txt -> If source was file Creates b directory if does not exsits and copy file.txt into it
975
* - Src:/home/test ,Dst:/home/ ,Result:/home/test/** -> If source was directory copy test directory and all of its content into dest
976
* - Src:/home/test/ ,Dst:/home/ ,Result:/home/**-> if source was direcotry copy its content to dest
977
* - Src:/home/test ,Dst:/home/test2 ,Result:/home/test2/** -> if source was directoy copy it and its content to dest with test2 as name
978
* - Src:/home/test/ ,Dst:/home/test2 ,Result:->/home/test2/** if source was directoy copy it and its content to dest with test2 as name
980
* - Should have rollback technique so it can undo the copy when it wasn't successful
981
* - Auto destination technique should be possible to turn off
982
* - Supporting callback function
983
* - May prevent some issues on shared enviroments : http://us3.php.net/umask
984
* @param $source //file or folder
985
* @param $dest ///file or folder
986
* @param $options //folderPermission,filePermission
989
public function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0644))
993
if (is_file($source)) {
994
if ($dest[strlen($dest)-1]=='/') {
995
if (!file_exists($dest)) {
996
cmfcDirectory::makeAll($dest,$options['folderPermission'],true);
998
$__dest=$dest."/".basename($source);
1002
$result=copy($source, $__dest);
1003
chmod($__dest,$options['filePermission']);
1005
} elseif(is_dir($source)) {
1006
if ($dest[strlen($dest)-1]=='/') {
1007
if ($source[strlen($source)-1]=='/') {
1008
//Copy only contents
1010
//Change parent itself and its contents
1011
$dest=$dest.basename($source);
1013
chmod($dest,$options['filePermission']);
1016
if ($source[strlen($source)-1]=='/') {
1017
//Copy parent directory with new name and all its content
1018
@mkdir($dest,$options['folderPermission']);
1019
chmod($dest,$options['filePermission']);
1021
//Copy parent directory with new name and all its content
1022
@mkdir($dest,$options['folderPermission']);
1023
chmod($dest,$options['filePermission']);
1027
$dirHandle=opendir($source);
1028
while($file=readdir($dirHandle))
1030
if($file!="." && $file!="..")
1032
if(!is_dir($source."/".$file)) {
1033
$__dest=$dest."/".$file;
1035
$__dest=$dest."/".$file;
1037
//echo "$source/$file ||| $__dest<br />";
1038
$result = $this->smartCopy($source."/".$file, $__dest, $options);
1041
closedir($dirHandle);
1050
* Will delete a whole directory recursively (directory muste be writable).
1052
* @param $dirname Directory to delete.
1055
public function delete_dir($dirname) {
1056
if (is_dir($dirname))
1057
$dir_handle = opendir($dirname);
1060
while($file = readdir($dir_handle)) {
1061
if ($file != "." && $file != "..") {
1062
if (!is_dir($dirname."/".$file))
1063
unlink($dirname."/".$file);
1065
$this->delete_dir($dirname.'/'.$file);
1068
closedir($dir_handle);
1075
* Connects to a normal ftp or secure server.
1076
* If values left empty system will use PHPDevShell configuration values.
1085
* @return resource connection id.
1087
public function establish_ftp ($username='config', $password='config', $host='config', $port='config', $ssl='config', $timeout='config', $chdir='config')
1089
global $db, $template;
1091
// Load database settings.
1092
$conf = $db->get_settings(array('ftp_enable', 'ftp_username', 'ftp_password', 'ftp_host', 'ftp_port', 'ftp_ssl', 'ftp_timeout', 'ftp_root'));
1095
if (!empty($conf['ftp_enable'])) {
1096
if ($username == 'config') $username = $conf['ftp_username'];
1097
if ($password == 'config') $password = $conf['ftp_password'];
1098
if ($host == 'config') $host = $conf['ftp_host'];
1099
if ($port == 'config') $port = $conf['ftp_port'];
1100
if ($ssl == 'config') $ssl = $conf['ftp_ssl'];
1101
if ($timeout == 'config') $timeout = $conf['ftp_timeout'];
1102
if ($chdir == 'config' && ! empty($conf['ftp_root'])) $chdir = $conf['ftp_root'];
1104
// Establish connection.
1105
if ($ssl == false) {
1106
if (!$resource = ftp_connect($host, $port, $timeout)) {
1107
throw new Exception(sprintf(___('I could not connect to local ftp server %s, user %s.'), $host, $username));
1111
if (!$resource = ftp_ssl_connect($host, $port, $timeout)) {
1112
throw new Exception(sprintf(___('I could not connect using SSL to local ftp server %s, user %s.'), $host, $username));
1116
// Log in to server.
1117
if (ftp_login($resource, $username, $password)) {
1118
// Should we change the directory path.
1119
if (! empty($chdir) && $chdir != 'config') {
1120
ftp_chdir($resource, $chdir);
1125
throw new Exception(sprintf(___('Incorrect login for local ftp server %s, user %s.'), $host, $username));
1131
* The following is a fully tested function (based on a previous note) that recursively puts files from a source directory to a destination directory. See http://rufy.com/tech/archives/000026.html for more information.
1133
* NOTE: Use full path name for the destination directory and the destination directory must already exist
1135
* @param resource $conn_id
1136
* @param string $src_dir
1137
* @param string $dst_dir
1140
public function ftp_rcopy($conn_id, $src_dir, $dst_dir)
1143
if ($dir = dir($src_dir)) {
1144
while($file = $dir->read()) { // do this for each file in the directory
1145
if ($file != '.' && $file != '..') { // to prevent an infinite loop
1146
if (is_dir($src_dir . '/' . $file)) { // do the following if it is a directory
1147
if (!@ftp_nlist($conn_id, $dst_dir . '/' . $file)) {
1148
ftp_mkdir($conn_id, $dst_dir . '/' . $file); // create directories that do not yet exist
1149
ftp_chmod($conn_id, 0755, $dst_dir . '/' . $file);
1151
$this->ftp_rcopy($conn_id, $src_dir . '/' . $file, $dst_dir . '/' . $file); // recursive part
1152
$this->upload_history[] = array('from' => $src_dir . '/' . $file, 'to' => $dst_dir . '/' . $file);
1154
if (!ftp_put($conn_id, $dst_dir . '/' . $file, $src_dir . '/' . $file, FTP_BINARY)) { // put the files
1155
throw new Exception(sprintf(___('There was a problem copying file %s'), $dst_dir . '/' . $file));
1157
$this->upload_history[] = array('from' => $src_dir . '/' . $file, 'to' => $dst_dir . '/' . $file);
1158
ftp_chmod($conn_id, 0644, $dst_dir . '/' . $file);
1164
if (!empty($this->upload_history)) {
b'\\ No newline at end of file'