Avatar.php 8.8 KB
Newer Older
Evan Prodromou's avatar
Evan Prodromou committed
1
<?php
2 3 4

if (!defined('GNUSOCIAL')) { exit(1); }

Evan Prodromou's avatar
Evan Prodromou committed
5 6 7 8
/**
 * Table Definition for avatar
 */

9
class Avatar extends Managed_DataObject
Evan Prodromou's avatar
Evan Prodromou committed
10 11 12
{
    public $__table = 'avatar';                          // table name
    public $profile_id;                      // int(4)  primary_key not_null
13
    public $original;                        // tinyint(1)
Evan Prodromou's avatar
Evan Prodromou committed
14 15 16
    public $width;                           // int(4)  primary_key not_null
    public $height;                          // int(4)  primary_key not_null
    public $mediatype;                       // varchar(32)   not_null
17
    public $filename;                        // varchar(191)   not 255 because utf8mb4 takes more space
Evan Prodromou's avatar
Evan Prodromou committed
18 19
    public $created;                         // datetime()   not_null
    public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
20
	
21 22 23 24 25 26 27 28 29
    public static function schemaDef()
    {
        return array(
            'fields' => array(
                'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'foreign key to profile table'),
                'original' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'uploaded by user or generated?'),
                'width' => array('type' => 'int', 'not null' => true, 'description' => 'image width'),
                'height' => array('type' => 'int', 'not null' => true, 'description' => 'image height'),
                '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 32 33 34 35
                'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
                'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
            ),
            'primary key' => array('profile_id', 'width', 'height'),
            'unique keys' => array(
36
//                'avatar_filename_key' => array('filename'),
37 38 39 40 41 42 43 44 45
            ),
            'foreign keys' => array(
                'avatar_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
            ),
            'indexes' => array(
                'avatar_profile_id_idx' => array('profile_id'),
            ),
        );
    }
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 60 61 62 63 64 65 66 67 68 69 70 71 72
    /*
     * Deletes all avatars (but may spare the original) from a profile.
     * 
     * @param   Profile $target     The profile we're deleting avatars of.
     * @param   boolean $original   Whether original should be removed or not.
     */
    public static function deleteFromProfile(Profile $target, $original=true) {
        try {
            $avatars = self::getProfileAvatars($target);
            foreach ($avatars as $avatar) {
                if ($avatar->original && !$original) {
                    continue;
                }
                $avatar->delete();
            }
73
        } catch (NoAvatarException $e) {
74
            // There are no avatars to delete, a sort of success.
75
        }
76 77

        return true;
78 79
    }

80 81 82 83 84 85 86
    static protected $_avatars = array();

    /*
     * Get an avatar by profile. Currently can't call newSize with $height
     */
    public static function byProfile(Profile $target, $width=null, $height=null)
    {
87 88
        $width  = intval($width);
        $height = !is_null($height) ? intval($height) : null;
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
        if (is_null($height)) {
            $height = $width;
        }

        $size = "{$width}x{$height}";
        if (!isset(self::$_avatars[$target->id])) {
            self::$_avatars[$target->id] = array();
        } elseif (isset(self::$_avatars[$target->id][$size])){
            return self::$_avatars[$target->id][$size];
        }

        $avatar = null;
        if (Event::handle('StartProfileGetAvatar', array($target, $width, &$avatar))) {
            $avatar = self::pkeyGet(
                array(
                    'profile_id' => $target->id,
                    'width'      => $width,
                    'height'     => $height,
                )
            );
            Event::handle('EndProfileGetAvatar', array($target, $width, &$avatar));
        }

        if (is_null($avatar)) {
            // Obviously we can't find an avatar, so let's resize the original!
            $avatar = Avatar::newSize($target, $width);
        } elseif (!($avatar instanceof Avatar)) {
            throw new NoAvatarException($target, $avatar);
        }

        self::$_avatars[$target->id]["{$avatar->width}x{$avatar->height}"] = $avatar;
        return $avatar;
    }

123
    public static function getUploaded(Profile $target)
124 125 126 127 128
    {
        $avatar = new Avatar();
        $avatar->profile_id = $target->id;
        $avatar->original = true;
        if (!$avatar->find(true)) {
129
            throw new NoAvatarException($target, $avatar);
130
        }
131 132 133 134
        if (!file_exists(Avatar::path($avatar->filename))) {
            // The delete call may be odd for, say, unmounted filesystems
            // that cause a file to currently not exist, but actually it does...
            $avatar->delete();
135
            throw new NoAvatarException($target, $avatar);
136
        }
137
        return $avatar;
138 139
    }

140 141 142
    public static function getProfileAvatars(Profile $target) {
        $avatar = new Avatar();
        $avatar->profile_id = $target->id;
143
        if (!$avatar->find()) {
144
            throw new NoAvatarException($target, $avatar);
145
        }
146 147 148
        return $avatar->fetchAll();
    }

149 150 151
    /**
     * Where should the avatar go for this user?
     */
152 153 154 155 156 157 158 159 160 161 162
    static function filename($id, $extension, $size=null, $extra=null)
    {
        if ($size) {
            return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
        } else {
            return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
        }
    }

    static function path($filename)
    {
163 164 165 166 167 168 169
        $dir = common_config('avatar', 'dir');

        if ($dir[strlen($dir)-1] != '/') {
            $dir .= '/';
        }

        return $dir . $filename;
170 171 172 173
    }

    static function url($filename)
    {
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
        $path = common_config('avatar', 'path');

        if ($path[strlen($path)-1] != '/') {
            $path .= '/';
        }

        if ($path[0] != '/') {
            $path = '/'.$path;
        }

        $server = common_config('avatar', 'server');

        if (empty($server)) {
            $server = common_config('site', 'server');
        }
Zach Copley's avatar
Zach Copley committed
189

mmn's avatar
mmn committed
190
        $ssl = (common_config('avatar', 'ssl') || GNUsocial::useHTTPS());
191 192

        $protocol = ($ssl) ? 'https' : 'http';
193

194
        return $protocol.'://'.$server.$path.$filename;
195 196 197 198
    }

    function displayUrl()
    {
199
        return Avatar::url($this->filename);
200 201
    }

202 203 204 205 206 207 208 209
    static function urlByProfile(Profile $target, $width=null, $height=null) {
        try {
            return self::byProfile($target,  $width, $height)->displayUrl();
        } catch (Exception $e) {
            return self::defaultImage($width);
        }
    }

210
    static function defaultImage($size)
211 212 213 214
    {
        static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
                                  AVATAR_STREAM_SIZE => 'stream',
                                  AVATAR_MINI_SIZE => 'mini');
215
        return Theme::path('default-avatar-'.$sizenames[$size].'.png');
216
    }
217

218
    static function newSize(Profile $target, $width) {
219
        $width = intval($width);
220
        if ($width < 1 || $width > common_config('avatar', 'maxsize')) {
221
            // TRANS: An error message when avatar size is unreasonable
222
            throw new Exception(_m('Avatar size too large'));
223
        }
224 225 226
        // So far we only have square avatars and I don't have time to
        // rewrite support for non-square ones right now ;)
        $height = $width;
227

228
        $original = Avatar::getUploaded($target);
229

230
        $imagefile = new ImageFile(null, Avatar::path($original->filename));
231 232 233
        $filename = Avatar::filename($target->getID(), image_type_to_extension($imagefile->preferredType()),
                                     $width, common_timestamp());
        $imagefile->resizeTo(Avatar::path($filename), array('width'=>$width, 'height'=>$height));
234 235 236

        $scaled = clone($original);
        $scaled->original = false;
237
        $scaled->width = $width;
238
        $scaled->height = $height;
239 240
        $scaled->filename = $filename;
        $scaled->created = common_sql_now();
241 242 243 244 245 246 247 248 249

        if (!$scaled->insert()) {
            // TRANS: An error message when unable to insert avatar data into the db
            throw new Exception(_m('Could not insert new avatar data to database'));
        }

        // Return the new avatar object
        return $scaled;
    }
Evan Prodromou's avatar
Evan Prodromou committed
250
}