]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Avatar.php
Did the OpportunisticQM fixes in the wrong order
[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             foreach ($avatars as $avatar) {
68                 if ($avatar->original && !$original) {
69                     continue;
70                 }
71                 $avatar->delete();
72             }
73         } catch (NoAvatarException $e) {
74             // There are no avatars to delete, a sort of success.
75         }
76
77         return true;
78     }
79
80     static protected $_avatars = array();
81
82     /*
83      * Get an avatar by profile. Currently can't call newSize with $height
84      */
85     public static function byProfile(Profile $target, $width=null, $height=null)
86     {
87         $width  = intval($width);
88         $height = !is_null($height) ? intval($height) : null;
89         if (is_null($height)) {
90             $height = $width;
91         }
92
93         $size = "{$width}x{$height}";
94         if (!isset(self::$_avatars[$target->id])) {
95             self::$_avatars[$target->id] = array();
96         } elseif (isset(self::$_avatars[$target->id][$size])){
97             return self::$_avatars[$target->id][$size];
98         }
99
100         $avatar = null;
101         if (Event::handle('StartProfileGetAvatar', array($target, $width, &$avatar))) {
102             $avatar = self::pkeyGet(
103                 array(
104                     'profile_id' => $target->id,
105                     'width'      => $width,
106                     'height'     => $height,
107                 )
108             );
109             Event::handle('EndProfileGetAvatar', array($target, $width, &$avatar));
110         }
111
112         if (is_null($avatar)) {
113             // Obviously we can't find an avatar, so let's resize the original!
114             $avatar = Avatar::newSize($target, $width);
115         } elseif (!($avatar instanceof Avatar)) {
116             throw new NoAvatarException($target, $avatar);
117         }
118
119         self::$_avatars[$target->id]["{$avatar->width}x{$avatar->height}"] = $avatar;
120         return $avatar;
121     }
122
123     public static function getUploaded(Profile $target)
124     {
125         $avatar = new Avatar();
126         $avatar->profile_id = $target->id;
127         $avatar->original = true;
128         if (!$avatar->find(true)) {
129             throw new NoAvatarException($target, $avatar);
130         }
131         if (!file_exists(Avatar::path($avatar->filename))) {
132             // The delete call may be odd for, say, unmounted filesystems
133             // that cause a file to currently not exist, but actually it does...
134             $avatar->delete();
135             throw new NoAvatarException($target, $avatar);
136         }
137         return $avatar;
138     }
139
140     public static function getProfileAvatars(Profile $target) {
141         $avatar = new Avatar();
142         $avatar->profile_id = $target->id;
143         if (!$avatar->find()) {
144             throw new NoAvatarException($target, $avatar);
145         }
146         return $avatar->fetchAll();
147     }
148
149     /**
150      * Where should the avatar go for this user?
151      */
152     static function filename($id, $extension, $size=null, $extra=null)
153     {
154         if ($size) {
155             return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
156         } else {
157             return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
158         }
159     }
160
161     static function path($filename)
162     {
163         $dir = common_config('avatar', 'dir');
164
165         if ($dir[strlen($dir)-1] != '/') {
166             $dir .= '/';
167         }
168
169         return $dir . $filename;
170     }
171
172     static function url($filename)
173     {
174         $path = common_config('avatar', 'path');
175
176         if ($path[strlen($path)-1] != '/') {
177             $path .= '/';
178         }
179
180         if ($path[0] != '/') {
181             $path = '/'.$path;
182         }
183
184         $server = common_config('avatar', 'server');
185
186         if (empty($server)) {
187             $server = common_config('site', 'server');
188         }
189
190         $ssl = common_config('avatar', 'ssl');
191
192         if (is_null($ssl)) { // null -> guess
193             if (common_config('site', 'ssl') == 'always' &&
194                 !common_config('avatar', 'server')) {
195                 $ssl = true;
196             } else {
197                 $ssl = false;
198             }
199         }
200
201         $protocol = ($ssl) ? 'https' : 'http';
202
203         return $protocol.'://'.$server.$path.$filename;
204     }
205
206     function displayUrl()
207     {
208         return Avatar::url($this->filename);
209     }
210
211     static function urlByProfile(Profile $target, $width=null, $height=null) {
212         try {
213             return self::byProfile($target,  $width, $height)->displayUrl();
214         } catch (Exception $e) {
215             return self::defaultImage($width);
216         }
217     }
218
219     static function defaultImage($size)
220     {
221         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
222                                   AVATAR_STREAM_SIZE => 'stream',
223                                   AVATAR_MINI_SIZE => 'mini');
224         return Theme::path('default-avatar-'.$sizenames[$size].'.png');
225     }
226
227     static function newSize(Profile $target, $width) {
228         $width = intval($width);
229         if ($width < 1 || $width > common_config('avatar', 'maxsize')) {
230             // TRANS: An error message when avatar size is unreasonable
231             throw new Exception(_m('Avatar size too large'));
232         }
233         // So far we only have square avatars and I don't have time to
234         // rewrite support for non-square ones right now ;)
235         $height = $width;
236
237         $original = Avatar::getUploaded($target);
238
239         $imagefile = new ImageFile(null, Avatar::path($original->filename));
240         $filename = Avatar::filename($target->getID(), image_type_to_extension($imagefile->preferredType()),
241                                      $width, common_timestamp());
242         $imagefile->resizeTo(Avatar::path($filename), array('width'=>$width, 'height'=>$height));
243
244         $scaled = clone($original);
245         $scaled->original = false;
246         $scaled->width = $width;
247         $scaled->height = $height;
248         $scaled->filename = $filename;
249         $scaled->created = common_sql_now();
250
251         if (!$scaled->insert()) {
252             // TRANS: An error message when unable to insert avatar data into the db
253             throw new Exception(_m('Could not insert new avatar data to database'));
254         }
255
256         // Return the new avatar object
257         return $scaled;
258     }
259 }