]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Avatar.php
Merge remote-tracking branch 'upstream/master'
[quix0rs-gnu-social.git] / classes / Avatar.php
1 <?php
2
3 if (!defined('GNUSOCIAL')) { exit(1); }
4
5 /**
6  * Table Definition for avatar
7  */
8
9 class Avatar extends Managed_DataObject
10 {
11     public $__table = 'avatar';                          // table name
12     public $profile_id;                      // int(4)  primary_key not_null
13     public $original;                        // tinyint(1)
14     public $width;                           // int(4)  primary_key not_null
15     public $height;                          // int(4)  primary_key not_null
16     public $mediatype;                       // varchar(32)   not_null
17     public $filename;                        // varchar(191)   not 255 because utf8mb4 takes more space
18     public $created;                         // datetime()   not_null
19     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
20         
21     public static function schemaDef()
22     {
23         return array(
24             'fields' => array(
25                 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'foreign key to profile table'),
26                 'original' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'uploaded by user or generated?'),
27                 'width' => array('type' => 'int', 'not null' => true, 'description' => 'image width'),
28                 'height' => array('type' => 'int', 'not null' => true, 'description' => 'image height'),
29                 'mediatype' => array('type' => 'varchar', 'length' => 32, 'not null' => true, 'description' => 'file type'),
30                 'filename' => array('type' => 'varchar', 'length' => 191, 'description' => 'local filename, if local'),
31                 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
32                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
33             ),
34             'primary key' => array('profile_id', 'width', 'height'),
35             'unique keys' => array(
36 //                'avatar_filename_key' => array('filename'),
37             ),
38             'foreign keys' => array(
39                 'avatar_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
40             ),
41             'indexes' => array(
42                 'avatar_profile_id_idx' => array('profile_id'),
43             ),
44         );
45     }
46
47     // We clean up the file, too
48     function delete($useWhere=false)
49     {
50         $filename = $this->filename;
51         if (file_exists(Avatar::path($filename))) {
52             @unlink(Avatar::path($filename));
53         }
54
55         return parent::delete($useWhere);
56     }
57
58     /*
59      * Deletes all avatars (but may spare the original) from a profile.
60      * 
61      * @param   Profile $target     The profile we're deleting avatars of.
62      * @param   boolean $original   Whether original should be removed or not.
63      */
64     public static function deleteFromProfile(Profile $target, $original=true) {
65         try {
66             $avatars = self::getProfileAvatars($target);
67
68             foreach ($avatars as $avatar) {
69                 assert($avatar instanceof Avatar);
70
71                 if ($avatar->original && !$original) {
72                     continue;
73                 }
74
75                 $avatar->delete();
76             }
77         } catch (NoAvatarException $e) {
78             // There are no avatars to delete, a sort of success.
79         }
80
81         return true;
82     }
83
84     static protected $_avatars = array();
85
86     /*
87      * Get an avatar by profile. Currently can't call newSize with $height
88      */
89     public static function byProfile(Profile $target, $width=null, $height=null)
90     {
91         $width  = intval($width);
92         $height = !is_null($height) ? intval($height) : null;
93         if (is_null($height)) {
94             $height = $width;
95         }
96
97         $size = "{$width}x{$height}";
98
99         if (!isset(self::$_avatars[$target->id])) {
100             self::$_avatars[$target->id] = array();
101         } elseif (isset(self::$_avatars[$target->id][$size])){
102             return self::$_avatars[$target->id][$size];
103         }
104
105         $avatar = null;
106
107         if (Event::handle('StartProfileGetAvatar', array($target, $width, &$avatar))) {
108             $avatar = self::pkeyGet(
109                 array(
110                     'profile_id' => $target->id,
111                     'width'      => $width,
112                     'height'     => $height,
113                 )
114             );
115
116             Event::handle('EndProfileGetAvatar', array($target, $width, &$avatar));
117         }
118
119         if (is_null($avatar)) {
120             // Obviously we can't find an avatar, so let's resize the original!
121             $avatar = Avatar::newSize($target, $width);
122         } elseif (!($avatar instanceof Avatar)) {
123             throw new NoAvatarException($target, $avatar);
124         }
125
126         self::$_avatars[$target->id]["{$avatar->width}x{$avatar->height}"] = $avatar;
127         return $avatar;
128     }
129
130     public static function getUploaded(Profile $target)
131     {
132         $avatar = new Avatar();
133         $avatar->profile_id = $target->id;
134         $avatar->original = true;
135         if (!$avatar->find(true)) {
136             throw new NoAvatarException($target, $avatar);
137         }
138         if (!file_exists(Avatar::path($avatar->filename))) {
139             // The delete call may be odd for, say, unmounted filesystems
140             // that cause a file to currently not exist, but actually it does...
141             $avatar->delete();
142             throw new NoAvatarException($target, $avatar);
143         }
144         return $avatar;
145     }
146
147     public static function getProfileAvatars(Profile $target) {
148         $avatar = new Avatar();
149         $avatar->profile_id = $target->id;
150         if (!$avatar->find()) {
151             throw new NoAvatarException($target, $avatar);
152         }
153         return $avatar->fetchAll();
154     }
155
156     /**
157      * Where should the avatar go for this user?
158      */
159     static function filename($id, $extension, $size=null, $extra=null)
160     {
161         if ($size) {
162             return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
163         } else {
164             return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
165         }
166     }
167
168     static function path($filename)
169     {
170         $dir = common_config('avatar', 'dir');
171
172         if ($dir[strlen($dir)-1] != '/') {
173             $dir .= '/';
174         }
175
176         return $dir . $filename;
177     }
178
179     static function url($filename)
180     {
181         $path = common_config('avatar', 'path');
182
183         if ($path[strlen($path)-1] != '/') {
184             $path .= '/';
185         }
186
187         if ($path[0] != '/') {
188             $path = '/' . $path;
189         }
190
191         $server = common_config('avatar', 'server');
192
193         if (empty($server)) {
194             $server = common_config('site', 'server');
195         }
196
197         $ssl = common_config('avatar', 'ssl');
198
199         if (is_null($ssl)) { // null -> guess
200             if (common_config('site', 'ssl') == 'always' &&
201                 !common_config('avatar', 'server')) {
202                 $ssl = true;
203             } else {
204                 $ssl = false;
205             }
206         }
207
208         $protocol = ($ssl) ? 'https' : 'http';
209
210         return $protocol.'://'.$server.$path.$filename;
211     }
212
213     function displayUrl()
214     {
215         return Avatar::url($this->filename);
216     }
217
218     static function urlByProfile(Profile $target, $width=null, $height=null) {
219         try {
220             return self::byProfile($target,  $width, $height)->displayUrl();
221         } catch (Exception $e) {
222             common_debug(sprintf('target=>id=%s,width=%s,height=%s,message=%s',
223                 $target->id,
224                 $width,
225                 $height,
226                 $e->getMessage()
227             ));
228             return self::defaultImage($width);
229         }
230     }
231
232     static function defaultImage($size)
233     {
234         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
235                                   AVATAR_STREAM_SIZE => 'stream',
236                                   AVATAR_MINI_SIZE => 'mini');
237         return Theme::path('default-avatar-' . $sizenames[$size] . '.png');
238     }
239
240     static function newSize(Profile $target, $width) {
241         $width = intval($width);
242         if ($width < 1 || $width > common_config('avatar', 'maxsize')) {
243             // TRANS: An error message when avatar size is unreasonable
244             throw new Exception(_m('Avatar size too large'));
245         }
246         // So far we only have square avatars and I don't have time to
247         // rewrite support for non-square ones right now ;)
248         $height = $width;
249
250         $original = Avatar::getUploaded($target);
251
252         $imagefile = new ImageFile(null, Avatar::path($original->filename));
253         $filename = Avatar::filename($target->getID(), image_type_to_extension($imagefile->preferredType()),
254                                      $width, common_timestamp());
255         $imagefile->resizeTo(Avatar::path($filename), array('width'=>$width, 'height'=>$height));
256
257         $scaled = clone($original);
258         $scaled->original = false;
259         $scaled->width = $width;
260         $scaled->height = $height;
261         $scaled->filename = $filename;
262         $scaled->created = common_sql_now();
263
264         if (!$scaled->insert()) {
265             // TRANS: An error message when unable to insert avatar data into the db
266             throw new Exception(_m('Could not insert new avatar data to database'));
267         }
268
269         // Return the new avatar object
270         return $scaled;
271     }
272 }