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