Advertisement
Guest User

Makaja

a guest
Aug 21st, 2014
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 26.46 KB | None | 0 0
  1. <?php
  2.  
  3. /* --------------------------------------------------------------------
  4.  
  5.   Chevereto
  6.   http://chevereto.com/
  7.  
  8.   @author   Rodolfo Berrios A. <http://rodolfoberrios.com/>
  9.             <inbox@rodolfoberrios.com>
  10.  
  11.   Copyright (C) Rodolfo Berrios A. All rights reserved.
  12.  
  13.   BY USING THIS SOFTWARE YOU DECLARE TO ACCEPT THE CHEVERETO EULA
  14.   http://chevereto.com/license
  15.  
  16.   --------------------------------------------------------------------- */
  17.  
  18. namespace CHV;
  19. use G, Exception;
  20.  
  21. class Image {
  22.    
  23.     static $table_chv_image = [
  24.                 'name',
  25.                 'extension',
  26.                 'album_id',
  27.                 'size',
  28.                 'width',
  29.                 'height',
  30.                 'date',
  31.                 'date_gmt',
  32.                 'nsfw',
  33.                 'user_id',
  34.                 'uploader_ip',
  35.                 'storage',
  36.                 'storage_id',
  37.                 'md5',
  38.                 'original_filename',
  39.                 'original_exifdata',
  40.                 'category_id',
  41.                 'description'
  42.             ];
  43.    
  44.     public static function getSingle($id, $sumview=false, $pretty=true) {
  45.        
  46.         $tables = DB::getTables();
  47.         $query = 'SELECT * FROM '.$tables['images']."\n";
  48.        
  49.         $joins = array(
  50.             'LEFT JOIN '.$tables['users'].' ON '.$tables['images'].'.image_user_id = '.$tables['users'].'.user_id',
  51.             'LEFT JOIN '.$tables['albums'].' ON '.$tables['images'].'.image_album_id = '.$tables['albums'].'.album_id'
  52.         );
  53.  
  54.         $query .=  implode("\n", $joins) . "\n";
  55.         $query .= 'WHERE image_id=:image_id;'."\n";
  56.        
  57.         if($sumview === true) {
  58.             $query .= 'UPDATE '.$tables['images'].' SET image_views = image_views + 1 WHERE image_id=:image_id';
  59.         }
  60.        
  61.         try {
  62.             $db = DB::getInstance();
  63.             $db->query($query);
  64.             $db->bind(':image_id', $id);
  65.             $image_db = $db->fetchSingle();
  66.             if($image_db) {
  67.                 if($sumview === true and $image_db['image_views'] == 0) {
  68.                     $image_db['image_views'] = 1;
  69.                 }
  70.                 $return = array_merge($image_db, self::getSrcTargetSingle($image_db, true));               
  71.                 return $pretty ? self::formatArray($return) : $return;
  72.             } else {
  73.                 return $image_db;
  74.             }
  75.         } catch(Exception $e) {
  76.             throw new ImageException($e->getMessage(), 400);
  77.         }
  78.        
  79.     }
  80.    
  81.     public static function getMultiple($ids, $pretty=false) {
  82.        
  83.         if(!is_array($ids)) {
  84.             $ids = func_get_args();
  85.             $aux = array();
  86.             foreach($ids as $k => $v) {
  87.                 $aux[] = $v;
  88.             }
  89.             $ids = $aux;
  90.         }
  91.        
  92.         if(count($ids) == 0) {
  93.             throw new ImageException('Null ids provided in Image::get_multiple', 100);
  94.         }
  95.        
  96.         $tables = DB::getTables();
  97.         $query = 'SELECT * FROM '.$tables['images']."\n";
  98.        
  99.         $joins = array(
  100.             'LEFT JOIN '.$tables['users'].' ON '.$tables['images'].'.image_user_id = '.$tables['users'].'.user_id',
  101.             'LEFT JOIN '.$tables['albums'].' ON '.$tables['images'].'.image_album_id = '.$tables['albums'].'.album_id'
  102.         );
  103.  
  104.         $query .=  implode("\n", $joins) . "\n";
  105.         $query .= 'WHERE image_id IN ('. join(',', $ids). ')' . "\n";
  106.        
  107.         try {
  108.             $db = DB::getInstance();
  109.             $db->query($query);
  110.             $images_db = $db->fetchAll();
  111.             if($images_db) {
  112.                 foreach($images_db as $k => $v) {
  113.                     $images_db[$k] = array_merge($v, self::getSrcTargetSingle($v, true));
  114.                 }
  115.             }
  116.             if($pretty) {
  117.                 $return = [];
  118.                 foreach($images_db as $k => $v) {
  119.                     $return[] = self::formatArray($v);
  120.                 }
  121.                 return $return;
  122.             }
  123.             return $images_db;
  124.         } catch(Exception $e) {
  125.             throw new ImageException($e->getMessage(), 400);
  126.         }
  127.     }
  128.    
  129.     public static function getAlbumSlice($image_id, $album_id=NULL, $padding=2) {
  130.        
  131.         $tables = DB::getTables();
  132.        
  133.         if($image_id == NULL) {
  134.             throw new ImageException("Image id can't be NULL", 100);
  135.         }
  136.        
  137.         if($album_id == NULL) {
  138.             try {
  139.                 $db = DB::getInstance();
  140.                 $db->query('SELECT image_album_id FROM '.$tables['images'].' WHERE image_id=:image_id');
  141.                 $db->bind(':image_id', $image_id);
  142.                 $image_album_db = $db->fetchSingle();
  143.                 $album_id = $image_album_db['image_album_id'];
  144.             } catch(Excepton $e) {
  145.                 throw new ImageException($e->getMessage(), 400);
  146.             }
  147.            
  148.             if($album_id == NULL) {
  149.                 return;
  150.             }
  151.         }
  152.        
  153.         if(!is_numeric($padding)) {
  154.             $padding = 2;
  155.         }
  156.  
  157.         //$where_album = $album_id !== NULL ? "image_album_id=:image_album_id" : "image_album_id IS NULL";
  158.        
  159.         try {
  160.             $db = DB::getInstance();
  161.             $db->query('SELECT * FROM (
  162.                     (SELECT * FROM '.$tables['images'].' WHERE image_album_id=:image_album_id AND image_id <= :image_id ORDER BY image_id DESC LIMIT 0,'.($padding*2 + 1).')
  163.                     UNION
  164.                     (SELECT * FROM '.$tables['images'].' WHERE image_album_id=:image_album_id AND image_id > :image_id ORDER BY image_id ASC LIMIT 0,'.($padding*2).')
  165.                 ) images ORDER BY images.image_id ASC');
  166.  
  167.             $db->bind(':image_album_id', $album_id);
  168.             $db->bind(':image_id', $image_id);
  169.            
  170.             $image_album_slice_db = $db->fetchAll();
  171.            
  172.             $album_offset = array('top' => 0, 'bottom' => 0);
  173.             foreach($image_album_slice_db as $v) {
  174.                 if($image_id > $v['image_id']) {
  175.                     $album_offset['top']++;
  176.                 }
  177.                 if($image_id < $v['image_id']) {
  178.                     $album_offset['bottom']++;
  179.                 }
  180.             }
  181.            
  182.             $album_chop_count = count($image_album_slice_db);
  183.             $album_iteration_times = $album_chop_count - ($padding*2 + 1);
  184.            
  185.             if($album_chop_count > ($padding*2 + 1)) {
  186.                                    
  187.                 if($album_offset['top'] > $padding && $album_offset['bottom'] > $padding) {
  188.                     // Cut on top
  189.                     for($i=0; $i<$album_offset['top']-$padding; $i++) {
  190.                         unset($image_album_slice_db[$i]);
  191.                     }
  192.                     // Cut on bottom
  193.                     for($i=1; $i<=$album_offset['bottom']-$padding; $i++) {
  194.                         unset($image_album_slice_db[$album_chop_count - $i]);
  195.                     }
  196.                 } else if($album_offset['top'] <= $padding) {
  197.                     // Cut bottom
  198.                     for($i=0; $i<$album_iteration_times; $i++) {
  199.                         unset($image_album_slice_db[$album_chop_count - 1 - $i]);
  200.                     }
  201.                 } else if($album_offset['bottom'] <= $padding) {
  202.                     // Cut top
  203.                     for($i=0; $i<$album_iteration_times; $i++) {
  204.                         unset($image_album_slice_db[$i]);
  205.                     }
  206.                 }
  207.                
  208.                 // Some cleaning after the unsets
  209.                 $image_album_slice_db = array_values($image_album_slice_db);
  210.             }
  211.  
  212.             $album_cursor = '';
  213.             foreach($image_album_slice_db as $k => $v) {
  214.                 if($v['image_id'] == $image_id) {
  215.                     $album_cursor = $k;
  216.                     break;
  217.                 }
  218.             }
  219.            
  220.             $image_album_slice['images'] = array();
  221.            
  222.             foreach($image_album_slice_db as $k => $v) {
  223.                 $image_album_slice['images'][$k] = self::formatArray($v);
  224.             }
  225.            
  226.             if($image_album_slice['images'][$album_cursor-1]) {
  227.                 $image_album_slice['prev'] =  $image_album_slice['images'][$album_cursor-1];
  228.             }
  229.            
  230.             if($image_album_slice['images'][$album_cursor+1]) {
  231.                 $image_album_slice['next'] = $image_album_slice['images'][$album_cursor+1];
  232.             }
  233.            
  234.             return array(
  235.                 'db'        => $image_album_slice_db,
  236.                 'formatted' => $image_album_slice
  237.             );
  238.  
  239.         } catch(Exception $e) {
  240.             throw new ImageException($e->getMessage(), 400);
  241.         }
  242.     }
  243.     public static function getCategorySlice($image_id, $cat_id=NULL, $padding=2) {
  244.        
  245.         $tables = DB::getTables();
  246.        
  247.         if($image_id == NULL) {
  248.             throw new ImageException("Image id can't be NULL", 100);
  249.         }
  250.        
  251.         if($cat_id == NULL) {
  252.             try {
  253.                 $db = DB::getInstance();
  254.                 $db->query('SELECT image_category_id FROM '.$tables['images'].' WHERE image_id=:image_id');
  255.                 $db->bind(':image_id', $image_id);
  256.                 $image_album_db = $db->fetchSingle();
  257.                 $cat_id = $image_album_db['image_category_id'];
  258.             } catch(Excepton $e) {
  259.                 throw new ImageException($e->getMessage(), 400);
  260.             }
  261.            
  262.             if($cat_id == NULL) {
  263.                 return;
  264.             }
  265.         }
  266.        
  267.         if(!is_numeric($padding)) {
  268.             $padding = 2;
  269.         }
  270.  
  271.         //$where_album = $album_id !== NULL ? "image_album_id=:image_album_id" : "image_album_id IS NULL";
  272.        
  273.         try {
  274.             $db = DB::getInstance();
  275.             $db->query('SELECT * FROM (
  276.                     (SELECT * FROM '.$tables['images'].' WHERE image_category_id=:image_category_id AND image_id <= :image_id ORDER BY image_id DESC LIMIT 0,'.($padding*2 + 1).')
  277.                     UNION
  278.                     (SELECT * FROM '.$tables['images'].' WHERE image_category_id=:image_category_id AND image_id > :image_id ORDER BY image_id ASC LIMIT 0,'.($padding*2).')
  279.                 ) images ORDER BY images.image_id ASC');
  280.  
  281.             $db->bind(':image_category_id', $cat_id);
  282.             $db->bind(':image_id', $image_id);
  283.            
  284.             $image_album_slice_db = $db->fetchAll();
  285.            
  286.             $album_offset = array('top' => 0, 'bottom' => 0);
  287.             foreach($image_album_slice_db as $v) {
  288.                 if($image_id > $v['image_id']) {
  289.                     $album_offset['top']++;
  290.                 }
  291.                 if($image_id < $v['image_id']) {
  292.                     $album_offset['bottom']++;
  293.                 }
  294.             }
  295.            
  296.             $album_chop_count = count($image_album_slice_db);
  297.             $album_iteration_times = $album_chop_count - ($padding*2 + 1);
  298.            
  299.             if($album_chop_count > ($padding*2 + 1)) {
  300.                                    
  301.                 if($album_offset['top'] > $padding && $album_offset['bottom'] > $padding) {
  302.                     // Cut on top
  303.                     for($i=0; $i<$album_offset['top']-$padding; $i++) {
  304.                         unset($image_album_slice_db[$i]);
  305.                     }
  306.                     // Cut on bottom
  307.                     for($i=1; $i<=$album_offset['bottom']-$padding; $i++) {
  308.                         unset($image_album_slice_db[$album_chop_count - $i]);
  309.                     }
  310.                 } else if($album_offset['top'] <= $padding) {
  311.                     // Cut bottom
  312.                     for($i=0; $i<$album_iteration_times; $i++) {
  313.                         unset($image_album_slice_db[$album_chop_count - 1 - $i]);
  314.                     }
  315.                 } else if($album_offset['bottom'] <= $padding) {
  316.                     // Cut top
  317.                     for($i=0; $i<$album_iteration_times; $i++) {
  318.                         unset($image_album_slice_db[$i]);
  319.                     }
  320.                 }
  321.                
  322.                 // Some cleaning after the unsets
  323.                 $image_album_slice_db = array_values($image_album_slice_db);
  324.             }
  325.  
  326.             $album_cursor = '';
  327.             foreach($image_album_slice_db as $k => $v) {
  328.                 if($v['image_id'] == $image_id) {
  329.                     $album_cursor = $k;
  330.                     break;
  331.                 }
  332.             }
  333.            
  334.             $image_album_slice['images'] = array();
  335.            
  336.             foreach($image_album_slice_db as $k => $v) {
  337.                 $image_album_slice['images'][$k] = self::formatArray($v);
  338.             }
  339.            
  340.             if($image_album_slice['images'][$album_cursor-1]) {
  341.                 $image_album_slice['prev'] =  $image_album_slice['images'][$album_cursor-1];
  342.             }
  343.            
  344.             if($image_album_slice['images'][$album_cursor+1]) {
  345.                 $image_album_slice['next'] = $image_album_slice['images'][$album_cursor+1];
  346.             }
  347.            
  348.             return array(
  349.                 'db'        => $image_album_slice_db,
  350.                 'formatted' => $image_album_slice
  351.             );
  352.  
  353.         } catch(Exception $e) {
  354.             throw new ImageException($e->getMessage(), 400);
  355.         }
  356.     }
  357.     public static function getSrcTargetSingle($filearray, $prefix=true) {
  358.        
  359.         $prefix = $prefix ? 'image_' : '';
  360.         $folder = CHV_PATH_IMAGES;
  361.        
  362.         switch($filearray[$prefix.'storage']) {
  363.             case 'datefolder':
  364.                 $folder .= date('Y/m/d/', strtotime($filearray[$prefix.'date'])); // sqlite no strtotime!
  365.             break;
  366.             case 'old':
  367.                 $folder .= 'old/';
  368.             break;
  369.             case 'direct':
  370.                 // use direct $folder
  371.             break;
  372.         }
  373.        
  374.         $targets = array(
  375.             $prefix.'path' => $folder.$filearray[$prefix.'name'] . '.' . $filearray[$prefix.'extension'],
  376.             $prefix.'path_thumb' => $folder.$filearray[$prefix.'name'].'.th.'.$filearray[$prefix.'extension'],
  377.             $prefix.'path_medium' => $folder.$filearray[$prefix.'name'].'.md.'.$filearray[$prefix.'extension'],
  378.             $prefix.'path_large' => $folder.$filearray[$prefix.'name'].'.la.'.$filearray[$prefix.'extension']
  379.         );
  380.        
  381.         $return = array();
  382.         foreach($targets as $k => $v) {
  383.             if(!file_exists($v)) continue;
  384.             $return[$k] = $v;
  385.         }
  386.        
  387.         return $return;
  388.     }
  389.    
  390.     public static function getUrlViewer($id_encoded) {
  391.         return G\get_base_url('image/'.$id_encoded);
  392.     }
  393.    
  394.     public static function upload($source, $destination, $filename='', $options=array()) {
  395.        
  396.         $default_options = array(
  397.             'max_size'      => G\get_bytes('2 MB'),
  398.             'filenaming'    => 'original'
  399.         );
  400.        
  401.         foreach($options as $k => $v) {
  402.             $upload_options[$k] = $v;
  403.         }
  404.  
  405.         if($filename !== '' and !$upload_options['filenaming']) {
  406.             $upload_options['filenaming'] = 'original';
  407.         }
  408.        
  409.         try {
  410.             $upload = new Upload;
  411.             $upload->setSource($source);
  412.             $upload->setDestination($destination);
  413.             $upload->setOptions($upload_options);
  414.             if($filename !== '') {
  415.                 $upload->setFilename($filename);
  416.             }
  417.             $upload->exec();
  418.            
  419.             // Watermark
  420.             if($options['watermark']) {
  421.                
  422.                 $watermark_postion = explode(' ', get_chv_setting('watermark_position'));
  423.                 $watermark_file = CHV_PATH_CONTENT_IMAGES_SYSTEM . get_chv_setting('watermark_image');
  424.                
  425.                 if(!is_readable($watermark_file)) {
  426.                     throw new Exception("Can't read watermark file", 100);
  427.                 }
  428.                
  429.                 switch($upload->uploaded['fileinfo']['extension']) {
  430.                     case 'gif':
  431.                         $src = imagecreatefromgif($upload->uploaded['file']);
  432.                     break;
  433.                     case 'png':
  434.                         $src = imagecreatefrompng($upload->uploaded['file']);
  435.                     break;
  436.                     case 'jpg':
  437.                         $src = imagecreatefromjpeg($upload->uploaded['file']);
  438.                     break;
  439.                 }
  440.                 $src_width = imagesx($src);
  441.                 $src_height = imagesy($src);
  442.                
  443.                 $watermark_src = imagecreatefrompng($watermark_file);
  444.                 $watermark_width = imagesx($watermark_src);
  445.                 $watermark_height = imagesy($watermark_src);
  446.  
  447.                 // Calculate the position
  448.                 switch($watermark_postion[0]) {
  449.                     case 'left':
  450.                         $watermark_x = get_chv_setting('watermark_margin');
  451.                         break;
  452.                     case 'center':
  453.                         $watermark_x = $src_width/2 - $watermark_width/2;
  454.                         break;
  455.                     case 'right':
  456.                         $watermark_x = $src_width - $watermark_width - get_chv_setting('watermark_margin');
  457.                         break;
  458.                 }
  459.                 switch($watermark_postion[1]) {
  460.                     case 'top':
  461.                         $watermark_y = get_chv_setting('watermark_margin');
  462.                         break;
  463.                     case 'center':
  464.                         $watermark_y = $src_height/2 - $watermark_height/2;
  465.                         break;
  466.                     case 'bottom':
  467.                         $watermark_y = $src_height - $watermark_height - get_chv_setting('watermark_margin');
  468.                         break;
  469.                 }
  470.                
  471.                 // Watermark has the same or greater size of the image ?
  472.                 // --> Center the watermark
  473.                 if($watermark_width == $src_width && $watermark_height == $src_height) {
  474.                     $watermark_x = $src_width/2 - $watermark_width/2;
  475.                     $watermark_y = $src_height/2 - $watermark_height/2;
  476.                 }
  477.                
  478.                 // Watermark is too big ?
  479.                 // --> Fit the watermark on the image
  480.                 if($watermark_width > $src_width || $watermark_height > $src_height) {
  481.                     // Watermark is wider than the image
  482.                     if($watermark_width > $src_width) {
  483.                         $watermark_new_width  = $src_width;
  484.                         $watermark_new_height = $src_width * $watermark_height / $watermark_width;
  485.                         if($watermark_new_height > $src_height) {
  486.                             $watermark_new_width  = $src_height * $watermark_width / $watermark_height;
  487.                             $watermark_new_height = $src_height;
  488.                         }
  489.                     } else {
  490.                         $watermark_new_width  = $src_height * $watermark_width / $watermark_height;
  491.                         $watermark_new_height = $src_height;
  492.                     }
  493.                     try {
  494.                         $watermark_temp = @tempnam(sys_get_temp_dir(), 'chvtemp');
  495.                         self::resize($watermark_file, $watermark_temp, ['width' => $watermark_new_width]);
  496.                         $watermark_width = $watermark_new_width;
  497.                         $watermark_height = $watermark_new_height;
  498.                         $watermark_src = imagecreatefrompng($watermark_temp);
  499.                         $watermark_x = $src_width/2 - $watermark_width/2;
  500.                         $watermark_y = $src_height/2 - $watermark_height/2;
  501.                     } catch(Exception $e) {} // Silence
  502.                 }
  503.                                    
  504.                 // Apply and save the watermark
  505.                 G\imagecopymerge_alpha($src, $watermark_src, $watermark_x, $watermark_y, 0, 0, $watermark_width, $watermark_height, get_chv_setting('watermark_opacity'), $upload->uploaded['fileinfo']['extension']);
  506.                
  507.                 switch($upload->uploaded['fileinfo']['extension']) {
  508.                     case 'gif':
  509.                         imagegif($src, $upload->uploaded['file']);
  510.                     break;
  511.                     case 'png':
  512.                         imagepng($src, $upload->uploaded['file']);
  513.                     break;
  514.                     case 'jpg':
  515.                         imagejpeg($src, $upload->uploaded['file'], 90);
  516.                     break;
  517.                 }
  518.                 imagedestroy($src);
  519.                 @unlink($watermark_temp);
  520.                
  521.                 // Remake the fileinfo array
  522.                 $upload->uploaded['fileinfo'] = get_image_fileinfo($upload->uploaded['file']);
  523.                
  524.             }
  525.             return array(
  526.                 'uploaded'  => $upload->uploaded,
  527.                 'source'    => $upload->source
  528.             );
  529.         } catch(Exception $e) {
  530.             throw new ImageException($e->getMessage(), $e->getCode());
  531.         }
  532.        
  533.     }
  534.    
  535.     public static function uploadToWebsite($source, $user, $params=[]) {
  536.        
  537.         try {
  538.             $storage = get_chv_setting('upload_storage_mode');
  539.             switch($storage) {
  540.                 case "direct":
  541.                     $upload_path = CHV_PATH_IMAGES;
  542.                 break;
  543.                 case "datefolder":
  544.                     $upload_path = CHV_PATH_IMAGES . date("Y/m/d/");
  545.                 break;
  546.             }
  547.            
  548.             $upload_options = array(
  549.                 'max_size'      => G\get_bytes(get_chv_setting('upload_max_filesize_mb') . ' MB'),
  550.                 'filenaming'    => in_array($params['privacy'], ['private', 'private_but_link']) ? 'random' : get_chv_setting('upload_filenaming'),
  551.                 'watermark'     => get_chv_setting('watermark_enable')
  552.             );
  553.            
  554.             $image_upload = self::upload($source, $upload_path, NULL, $upload_options);
  555.            
  556.             // Try to generate the thumb
  557.             $image_thumb_options = array(
  558.                 'width'     => get_chv_setting('upload_thumb_width'),
  559.                 'height'    => get_chv_setting('upload_thumb_height')
  560.             );
  561.            
  562.             $image_thumb = self::resize($image_upload['uploaded']['file'], $upload_path, $image_upload['uploaded']['name'] . '.th', $image_thumb_options);
  563.            
  564.             // Try to generate the medium
  565.             $medium_size = get_chv_setting('upload_medium_width');
  566.  
  567.             $is_animated_image = $image_upload['uploaded']['fileinfo']['extension'] == 'gif' and G\is_animated_image($image_upload['uploaded']['file']);
  568.  
  569.             if($image_upload['uploaded']['fileinfo']['width'] > $medium_size or $image_upload['uploaded']['fileinfo']['height'] > $medium_size or $is_animated_image) {
  570.                
  571.                 $image_medium_options = [];
  572.                
  573.                 /*
  574.                 if($image_upload['uploaded']['fileinfo']['ratio'] > 1) {
  575.                     $image_medium_options['width'] = $medium_size;
  576.                 } else {
  577.                     $image_medium_options['height'] = $medium_size;
  578.                 }
  579.                 */
  580.                 $image_medium_options['width'] = $medium_size;
  581.                
  582.                 if($is_animated_image) {
  583.                     $image_medium_options['forced'] = true;
  584.                 }
  585.  
  586.                 $image_large_options = array(
  587.                     'width'     => 2048,
  588.                     'forced'    => true
  589.                 );
  590.                 $image_medium = self::resize($image_upload['uploaded']['file'], $upload_path, $image_upload['uploaded']['name'] . '.md', $image_medium_options);
  591.             }
  592.  
  593.             if($image_upload['uploaded']['fileinfo']['width'] > 2048 or $image_upload['uploaded']['fileinfo']['height'] > 2048 or $is_animated_image) {
  594.                
  595.                 $image_large_options = array(
  596.                     'width'     => 2048,
  597.                     'forced'    => true
  598.                 );
  599.                 $image_large = self::resize($image_upload['uploaded']['file'], $upload_path, $image_upload['uploaded']['name'] . '.la', $image_large_options);
  600.             }
  601.            
  602.             $image_insert_values = array(
  603.                 'storage'       => $storage,
  604.                 'storage_id'    => NULL,
  605.                 'user_id'       => $user['id'],
  606.                 'album_id'      => NULL,
  607.                 'nsfw'          => $params['nsfw'],
  608.                 'category_id'   => $params['category_id']
  609.             );
  610.            
  611.             $uploaded_id = self::insert($image_upload, $image_insert_values);
  612.             $user_updated_counts = [
  613.                 'image_count' => $user['image_count'] + 1
  614.             ];
  615.            
  616.             // Private upload? Create a private album then
  617.             if(in_array($params['privacy'], ['private', 'private_but_link'])) {
  618.                 $upload_timestamp = $params['timestamp'];  
  619.                 if(!$_SESSION['upload_'.$upload_timestamp]) {
  620.                     $inserted_album = Album::insert(_s('Private upload').' '.G\datetime('Y-m-d'), $user['id'], $params['privacy']);
  621.                     $_SESSION['upload_'.$upload_timestamp] = encodeID($inserted_album);
  622.                 }
  623.                 Album::addImage(decodeID($_SESSION['upload_'.$upload_timestamp]), $uploaded_id);
  624.             }
  625.            
  626.             // Update user (if any)
  627.             if($user) {
  628.                 User::update($user['id'], $user_updated_counts);
  629.             }
  630.            
  631.             return $uploaded_id;
  632.            
  633.         } catch(Exception $e) {
  634.             //@unlink($image_upload['uploaded']['file'], $image_medium['file'], $image_thumb['file']);
  635.             //@unlink($image_upload['uploaded']['file'], $image_large['file'], $image_thumb['file']);
  636.             throw new ImageException($e->getMessage(), $e->getCode());
  637.         }
  638.        
  639.     }
  640.    
  641.     public static function resize($source, $destination, $filename='', $options=array()) {
  642.         try {  
  643.             $resize = new Imageresize;
  644.             $resize->setSource($source);
  645.             $resize->setDestination($destination);
  646.             if($filename) {
  647.                 $resize->setFilename($filename);
  648.             }
  649.             $resize->setOptions($options);
  650.             if($options['width']) {
  651.                 $resize->set_width($options['width']);
  652.             }
  653.             if($options['height']) {
  654.                 $resize->set_height($options['height']);
  655.             }
  656.             if($options['width'] == $options['height']) {
  657.                 $resize->set_fixed();
  658.             }
  659.             if($options['forced']) {
  660.                 $resize->setOption('forced', true);
  661.             }
  662.             $resize->exec();
  663.             return $resize->resized;
  664.         } catch(Exception $e) {
  665.             throw new ImageException($e->getMessage(), $e->getCode());
  666.         }
  667.     }
  668.    
  669.     public static function insert($image_upload, $values=[]) {
  670.         try {
  671.             $table_chv_image = self::$table_chv_image;
  672.             foreach($table_chv_image as $k => $v) {
  673.                 $table_chv_image[$k] = 'image_' . $v;
  674.             }
  675.            
  676.             $values = array(
  677.                 'album_id'          => $values['album_id'],
  678.                 'date'              => G\datetime(),
  679.                 'date_gmt'          => G\datetimegmt(),
  680.                 'nsfw'              => isset($values['nsfw']) ? $values['nsfw'] : 0,
  681.                 'user_id'           => $values['user_id'],
  682.                 'uploader_ip'       => G\get_client_ip(),
  683.                 'storage'           => $values['storage'],
  684.                 'storage_id'        => $values['storage_id'],
  685.                 'md5'               => md5_file($image_upload['uploaded']['file']),
  686.                 'original_filename' => $image_upload['source']['filename'],
  687.                 'original_exifdata' => (G\check_value($image_upload['source']['image_exif']) ? json_encode($image_upload['source']['image_exif']) : null),
  688.                 'category_id'       => $values['category_id'],
  689.                 'description'       => $values['description']
  690.             );
  691.            
  692.             // Populate the info from fileinfo
  693.             $values = array_merge($image_upload['uploaded']['fileinfo'], $values);
  694.            
  695.             foreach(['description', 'category_id'] as $v) {
  696.                 G\nullify_string($values[$v]);
  697.             }
  698.            
  699.             // Now use only the values accepted by the table
  700.             foreach($values as $k => $v) {
  701.                 if(!in_array('image_' . $k, $table_chv_image)) {
  702.                     unset($values[$k]);
  703.                 }
  704.             }
  705.            
  706.             $insert = DB::insert('images', $values);
  707.            
  708.             if(!is_null($values['album_id']) and $insert) {
  709.                 Album::updateImageCount($values['album_id'], 1);
  710.             }
  711.            
  712.             return $insert;
  713.  
  714.         } catch(Exception $e) {
  715.             throw new ImageException($e->getMessage(), 400);
  716.         }
  717.     }
  718.    
  719.     public static function update($id, $values) {
  720.         try {
  721.            
  722.             $values = G\array_filter_array($values, self::$table_chv_image, 'exclusion');
  723.            
  724.             foreach(['description', 'category_id'] as $v) {
  725.                 G\nullify_string($values[$v]);
  726.             }
  727.            
  728.             if(isset($values['album_id'])) {
  729.                 $image_db = self::getSingle($id, false, false);
  730.                 $old_album = $image_db['image_album_id'];
  731.                 $new_album = $values['album_id'];
  732.                 $update = DB::update('images', $values, ['id' => $id]);
  733.                 if($update and $old_album !== $new_album) {
  734.                     if(!is_null($old_album)) { // Update the old album
  735.                         Album::updateImageCount($old_album, 1, '-');
  736.                     }
  737.                     if(!is_null($new_album)) { // Update the new album
  738.                         Album::updateImageCount($new_album, 1);
  739.                     }
  740.                 }
  741.                 return $update;
  742.             } else {
  743.                 return DB::update('images', $values, ['id' => $id]);
  744.             }
  745.         } catch(Excepton $e) {
  746.             throw new ImageException($e->getMessage(), 400);
  747.         }
  748.     }
  749.    
  750.     public static function delete($id, $update_user=true) {
  751.         try {
  752.             if($update_user) {
  753.                 // Get the user id
  754.                 $user_id = DB::get('images', ['id' => $id])[0]['image_user_id'];
  755.             }
  756.             $image_db = self::getSingle($id, false, false);
  757.             $file_deletes = array('image_path', 'image_path_thumb', 'image_path_medium', 'image_path_large');
  758.             foreach($file_deletes as $file_delete) {
  759.                 $target = $image_db[$file_delete];
  760.                 if(file_exists($target) and !unlink($target)) {
  761.                     throw new ImageException("Can't delete file", 200);
  762.                 }
  763.             }
  764.             if($update_user and $user_id) {
  765.                 $user = User::getSingle($user_id, 'id');
  766.                 User::update($user_id, ['image_count' => $user['image_count'] - 1]);
  767.             }
  768.            
  769.             // Update album count
  770.             if($image_db['image_album_id'] > 0) {
  771.                 Album::updateImageCount($image_db['image_album_id'], 1, '-');
  772.             }
  773.            
  774.             return DB::delete('images', ['id' => $id]);
  775.         } catch(Exception $e) {
  776.             throw new ImageException($e->getMessage(), 400);
  777.         }
  778.     }
  779.    
  780.     public static function deleteMultiple($ids) {
  781.         if(!is_array($ids)) {
  782.             throw new ImageException('Expecting array argument, '.gettype($ids).' given in '. __METHOD__, 100);
  783.         }
  784.         try {
  785.             foreach($ids as $id) {
  786.                 self::delete($id);
  787.             }
  788.             return true;
  789.         } catch(Excepton $e) {
  790.             throw new ImageException($e->getMessage(), 400);
  791.         }
  792.     }
  793.    
  794.     public static function fill(&$image) {
  795.  
  796.         $image['id_encoded'] = encodeID($image['id']);
  797.        
  798.         $targets = self::getSrcTargetSingle($image, false);
  799.        
  800.         if(count($targets) > 0) {
  801.             $image = array_merge($image, (array) get_image_fileinfo($targets['path'])); // Never do an array merge over an empty thing!
  802.         }
  803.        
  804.         $image['file_resource'] = $targets ? [
  805.             'type'  => 'path',
  806.             'image' => $targets['path'],
  807.             'thumb' => $targets['path_thumb'],
  808.             'medium'=> $targets['path_medium'],
  809.             'large'=> $targets['path_large']
  810.         ] : false;
  811.        
  812.         $image['url_viewer'] = self::getUrlViewer($image['id_encoded']);
  813.        
  814.         $image['thumb'] = file_exists($targets['path_thumb']) ? get_image_fileinfo($targets['path_thumb']) : null;
  815.         $image['medium'] = file_exists($targets['path_medium']) ? get_image_fileinfo($targets['path_medium']) : null;
  816.         $image['large'] = file_exists($targets['path_large']) ? get_image_fileinfo($targets['path_large']) : null;
  817.        
  818.         $image['views_label'] = _n('view', 'views', $image['views']);
  819.         $image['display_url'] = $image['medium'] == null ? $image['url'] : $image['medium']['url'];
  820.         $image['how_long_ago'] = time_elapsed_string($image['date_gmt']);
  821.        
  822.     }
  823.    
  824.     public static function formatArray($dbrow, $safe=false) {
  825.        
  826.         try {
  827.             $output = DB::formatRow($dbrow);
  828.         } catch(Excepton $e) {
  829.             throw new ImageException($e->getMessage(), 400);
  830.         }
  831.        
  832.         if(!is_null($output['user']['id'])) {
  833.             User::fill($output['user']);
  834.         } else {
  835.             unset($output['user']);
  836.         }
  837.  
  838.         if(!is_null($output['album']['id']) or !is_null($output['user']['id'])) {
  839.             Album::fill($output['album'], $output['user']);
  840.         } else {
  841.             unset($output['album']);
  842.         }
  843.        
  844.         self::fill($output);
  845.        
  846.         if($safe === true) {
  847.             unset($output['id'], $output['path'], $output['uploader_ip']);
  848.             unset($output['album']['id'], $output['album']['privacy_extra']);
  849.             unset($output['user']['id']);
  850.             unset($output['path'], $output['path_thumb'], $output['path_medium']);
  851.             if($output['file_resource']['type'] == 'path') {
  852.                 unset($output['file_resource']);
  853.             }
  854.         }
  855.        
  856.         return $output;
  857.     }
  858.    
  859. }
  860.  
  861. class ImageException extends Exception {}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement