]> git.mxchange.org Git - friendica.git/blob - src/Model/Photo.php
old boot.php functions replaced in /src
[friendica.git] / src / Model / Photo.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Model;
23
24 use Friendica\Core\Cache\Enum\Duration;
25 use Friendica\Core\Logger;
26 use Friendica\Core\Session;
27 use Friendica\Core\System;
28 use Friendica\Database\DBA;
29 use Friendica\DI;
30 use Friendica\Core\Storage\Type\ExternalResource;
31 use Friendica\Core\Storage\Exception\InvalidClassStorageException;
32 use Friendica\Core\Storage\Exception\ReferenceStorageException;
33 use Friendica\Core\Storage\Exception\StorageException;
34 use Friendica\Core\Storage\Type\SystemResource;
35 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
36 use Friendica\Object\Image;
37 use Friendica\Util\DateTimeFormat;
38 use Friendica\Util\Images;
39 use Friendica\Security\Security;
40 use Friendica\Util\Proxy;
41 use Friendica\Util\Strings;
42
43 /**
44  * Class to handle photo dabatase table
45  */
46 class Photo
47 {
48         const CONTACT_PHOTOS = 'Contact Photos';
49         const PROFILE_PHOTOS = 'Profile Photos';
50         const BANNER_PHOTOS  = 'Banner Photos';
51
52         const DEFAULT        = 0;
53         const USER_AVATAR    = 10;
54         const USER_BANNER    = 11;
55         const CONTACT_AVATAR = 20;
56         const CONTACT_BANNER = 21;
57
58         /**
59          * Select rows from the photo table and returns them as array
60          *
61          * @param array $fields     Array of selected fields, empty for all
62          * @param array $conditions Array of fields for conditions
63          * @param array $params     Array of several parameters
64          *
65          * @return boolean|array
66          *
67          * @throws \Exception
68          * @see   \Friendica\Database\DBA::selectToArray
69          */
70         public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
71         {
72                 if (empty($fields)) {
73                         $fields = self::getFields();
74                 }
75
76                 return DBA::selectToArray('photo', $fields, $conditions, $params);
77         }
78
79         /**
80          * Retrieve a single record from the photo table
81          *
82          * @param array $fields     Array of selected fields, empty for all
83          * @param array $conditions Array of fields for conditions
84          * @param array $params     Array of several parameters
85          *
86          * @return bool|array
87          *
88          * @throws \Exception
89          * @see   \Friendica\Database\DBA::select
90          */
91         public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
92         {
93                 if (empty($fields)) {
94                         $fields = self::getFields();
95                 }
96
97                 return DBA::selectFirst('photo', $fields, $conditions, $params);
98         }
99
100         /**
101          * Get photos for user id
102          *
103          * @param integer $uid        User id
104          * @param string  $resourceid Rescource ID of the photo
105          * @param array   $conditions Array of fields for conditions
106          * @param array   $params     Array of several parameters
107          *
108          * @return bool|array
109          *
110          * @throws \Exception
111          * @see   \Friendica\Database\DBA::select
112          */
113         public static function getPhotosForUser(int $uid, string $resourceid, array $conditions = [], array $params = [])
114         {
115                 $conditions['resource-id'] = $resourceid;
116                 $conditions['uid'] = $uid;
117
118                 return self::selectToArray([], $conditions, $params);
119         }
120
121         /**
122          * Get a photo for user id
123          *
124          * @param integer $uid        User id
125          * @param string  $resourceid Rescource ID of the photo
126          * @param integer $scale      Scale of the photo. Defaults to 0
127          * @param array   $conditions Array of fields for conditions
128          * @param array   $params     Array of several parameters
129          *
130          * @return bool|array
131          *
132          * @throws \Exception
133          * @see   \Friendica\Database\DBA::select
134          */
135         public static function getPhotoForUser(int $uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
136         {
137                 $conditions['resource-id'] = $resourceid;
138                 $conditions['uid'] = $uid;
139                 $conditions['scale'] = $scale;
140
141                 return self::selectFirst([], $conditions, $params);
142         }
143
144         /**
145          * Get a single photo given resource id and scale
146          *
147          * This method checks for permissions. Returns associative array
148          * on success, "no sign" image info, if user has no permission,
149          * false if photo does not exists
150          *
151          * @param string  $resourceid Rescource ID of the photo
152          * @param integer $scale      Scale of the photo. Defaults to 0
153          *
154          * @return boolean|array
155          * @throws \Exception
156          */
157         public static function getPhoto(string $resourceid, int $scale = 0)
158         {
159                 $r = self::selectFirst(['uid'], ['resource-id' => $resourceid]);
160                 if (!DBA::isResult($r)) {
161                         return false;
162                 }
163
164                 $uid = $r['uid'];
165
166                 $accessible = $uid ? (bool)DI::pConfig()->get($uid, 'system', 'accessible-photos', false) : false;
167
168                 $sql_acl = Security::getPermissionsSQLByUserId($uid, $accessible);
169
170                 $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
171                 $params = ['order' => ['scale' => true]];
172                 $photo = self::selectFirst([], $conditions, $params);
173
174                 return $photo;
175         }
176
177         /**
178          * Check if photo with given conditions exists
179          *
180          * @param array $conditions Array of extra conditions
181          *
182          * @return boolean
183          * @throws \Exception
184          */
185         public static function exists(array $conditions): bool
186         {
187                 return DBA::exists('photo', $conditions);
188         }
189
190
191         /**
192          * Get Image data for given row id. null if row id does not exist
193          *
194          * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
195          *
196          * @return \Friendica\Object\Image|null Image object or null on error
197          */
198         public static function getImageDataForPhoto(array $photo)
199         {
200                 if (!empty($photo['data'])) {
201                         return $photo['data'];
202                 }
203
204                 try {
205                         $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
206                         /// @todo refactoring this returning, because the storage returns a "string" which is casted in different ways - a check "instanceof Image" will fail!
207                         return $backendClass->get($photo['backend-ref'] ?? '');
208                 } catch (InvalidClassStorageException $storageException) {
209                         try {
210                                 // legacy data storage in "data" column
211                                 $i = self::selectFirst(['data'], ['id' => $photo['id']]);
212                                 if ($i !== false) {
213                                         return $i['data'];
214                                 } else {
215                                         DI::logger()->info('Stored legacy data is empty', ['photo' => $photo]);
216                                 }
217                         } catch (\Exception $exception) {
218                                 DI::logger()->info('Unexpected database exception', ['photo' => $photo, 'exception' => $exception]);
219                         }
220                 } catch (ReferenceStorageException $referenceStorageException) {
221                         DI::logger()->debug('Invalid reference for photo', ['photo' => $photo, 'exception' => $referenceStorageException]);
222                 } catch (StorageException $storageException) {
223                         DI::logger()->info('Unexpected storage exception', ['photo' => $photo, 'exception' => $storageException]);
224                 } catch (\ImagickException $imagickException) {
225                         DI::logger()->info('Unexpected imagick exception', ['photo' => $photo, 'exception' => $imagickException]);
226                 }
227
228                 return null;
229         }
230
231         /**
232          * Get Image object for given row id. null if row id does not exist
233          *
234          * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
235          *
236          * @return \Friendica\Object\Image
237          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
238          * @throws \ImagickException
239          */
240         public static function getImageForPhoto(array $photo): Image
241         {
242                 return new Image(self::getImageDataForPhoto($photo), $photo['type']);
243         }
244
245         /**
246          * Return a list of fields that are associated with the photo table
247          *
248          * @return array field list
249          * @throws \Exception
250          */
251         private static function getFields(): array
252         {
253                 $allfields = DI::dbaDefinition()->getAll();
254                 $fields = array_keys($allfields['photo']['fields']);
255                 array_splice($fields, array_search('data', $fields), 1);
256                 return $fields;
257         }
258
259         /**
260          * Construct a photo array for a system resource image
261          *
262          * @param string $filename Image file name relative to code root
263          * @param string $mimetype Image mime type. Is guessed by file name when empty.
264          *
265          * @return array
266          * @throws \Exception
267          */
268         public static function createPhotoForSystemResource(string $filename, string $mimetype = ''): array
269         {
270                 if (empty($mimetype)) {
271                         $mimetype = Images::guessTypeByExtension($filename);
272                 }
273
274                 $fields = self::getFields();
275                 $values = array_fill(0, count($fields), '');
276
277                 $photo                  = array_combine($fields, $values);
278                 $photo['backend-class'] = SystemResource::NAME;
279                 $photo['backend-ref']   = $filename;
280                 $photo['type']          = $mimetype;
281                 $photo['cacheable']     = false;
282
283                 return $photo;
284         }
285
286         /**
287          * Construct a photo array for an external resource image
288          *
289          * @param string $url      Image URL
290          * @param int    $uid      User ID of the requesting person
291          * @param string $mimetype Image mime type. Is guessed by file name when empty.
292          *
293          * @return array
294          * @throws \Exception
295          */
296         public static function createPhotoForExternalResource(string $url, int $uid = 0, string $mimetype = ''): array
297         {
298                 if (empty($mimetype)) {
299                         $mimetype = Images::guessTypeByExtension($url);
300                 }
301
302                 $fields = self::getFields();
303                 $values = array_fill(0, count($fields), '');
304
305                 $photo                  = array_combine($fields, $values);
306                 $photo['backend-class'] = ExternalResource::NAME;
307                 $photo['backend-ref']   = json_encode(['url' => $url, 'uid' => $uid]);
308                 $photo['type']          = $mimetype;
309                 $photo['cacheable']     = true;
310
311                 return $photo;
312         }
313
314         /**
315          * store photo metadata in db and binary in default backend
316          *
317          * @param Image   $image     Image object with data
318          * @param integer $uid       User ID
319          * @param integer $cid       Contact ID
320          * @param string  $rid       Resource ID
321          * @param string  $filename  Filename
322          * @param string  $album     Album name
323          * @param integer $scale     Scale
324          * @param integer $type      Photo type, optional, default: Photo::DEFAULT
325          * @param string  $allow_cid Permissions, allowed contacts. optional, default = ""
326          * @param string  $allow_gid Permissions, allowed groups. optional, default = ""
327          * @param string  $deny_cid  Permissions, denied contacts.optional, default = ""
328          * @param string  $deny_gid  Permissions, denied greoup.optional, default = ""
329          * @param string  $desc      Photo caption. optional, default = ""
330          *
331          * @return boolean True on success
332          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
333          */
334         public static function store(Image $image, int $uid, int $cid, string $rid, string $filename, string $album, int $scale, int $type = self::DEFAULT, string $allow_cid = '', string $allow_gid = '', string $deny_cid = '', string $deny_gid = '', string $desc = ''): bool
335         {
336                 $photo = self::selectFirst(['guid'], ["`resource-id` = ? AND `guid` != ?", $rid, '']);
337                 if (DBA::isResult($photo)) {
338                         $guid = $photo['guid'];
339                 } else {
340                         $guid = System::createGUID();
341                 }
342
343                 $existing_photo = self::selectFirst(['id', 'created', 'backend-class', 'backend-ref'], ['resource-id' => $rid, 'uid' => $uid, 'contact-id' => $cid, 'scale' => $scale]);
344                 $created = DateTimeFormat::utcNow();
345                 if (DBA::isResult($existing_photo)) {
346                         $created = $existing_photo['created'];
347                 }
348
349                 // Get defined storage backend.
350                 // if no storage backend, we use old "data" column in photo table.
351                 // if is an existing photo, reuse same backend
352                 $data        = '';
353                 $backend_ref = '';
354                 $storage     = '';
355
356                 try {
357                         if (DBA::isResult($existing_photo)) {
358                                 $backend_ref = (string)$existing_photo['backend-ref'];
359                                 $storage     = DI::storageManager()->getWritableStorageByName($existing_photo['backend-class'] ?? '');
360                         } else {
361                                 $storage = DI::storage();
362                         }
363                         $backend_ref = $storage->put($image->asString(), $backend_ref);
364                 } catch (InvalidClassStorageException $storageException) {
365                         $data = $image->asString();
366                 }
367
368                 $fields = [
369                         'uid' => $uid,
370                         'contact-id' => $cid,
371                         'guid' => $guid,
372                         'resource-id' => $rid,
373                         'hash' => md5($image->asString()),
374                         'created' => $created,
375                         'edited' => DateTimeFormat::utcNow(),
376                         'filename' => basename($filename),
377                         'type' => $image->getType(),
378                         'album' => $album,
379                         'height' => $image->getHeight(),
380                         'width' => $image->getWidth(),
381                         'datasize' => strlen($image->asString()),
382                         'data' => $data,
383                         'scale' => $scale,
384                         'photo-type' => $type,
385                         'profile' => false,
386                         'allow_cid' => $allow_cid,
387                         'allow_gid' => $allow_gid,
388                         'deny_cid' => $deny_cid,
389                         'deny_gid' => $deny_gid,
390                         'desc' => $desc,
391                         'backend-class' => (string)$storage,
392                         'backend-ref' => $backend_ref
393                 ];
394
395                 if (DBA::isResult($existing_photo)) {
396                         $r = DBA::update('photo', $fields, ['id' => $existing_photo['id']]);
397                 } else {
398                         $r = DBA::insert('photo', $fields);
399                 }
400
401                 return $r;
402         }
403
404
405         /**
406          * Delete info from table and data from storage
407          *
408          * @param array $conditions Field condition(s)
409          * @param array $options    Options array, Optional
410          *
411          * @return boolean
412          *
413          * @throws \Exception
414          * @see   \Friendica\Database\DBA::delete
415          */
416         public static function delete(array $conditions, array $options = []): bool
417         {
418                 // get photo to delete data info
419                 $photos = DBA::select('photo', ['id', 'backend-class', 'backend-ref'], $conditions);
420
421                 while ($photo = DBA::fetch($photos)) {
422                         try {
423                                 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
424                                 $backend_class->delete($photo['backend-ref'] ?? '');
425                                 // Delete the photos after they had been deleted successfully
426                                 DBA::delete('photo', ['id' => $photo['id']]);
427                         } catch (InvalidClassStorageException $storageException) {
428                                 DI::logger()->debug('Storage class not found.', ['conditions' => $conditions, 'exception' => $storageException]);
429                         } catch (ReferenceStorageException $referenceStorageException) {
430                                 DI::logger()->debug('Photo doesn\'t exist.', ['conditions' => $conditions, 'exception' => $referenceStorageException]);
431                         }
432                 }
433
434                 DBA::close($photos);
435
436                 return DBA::delete('photo', $conditions, $options);
437         }
438
439         /**
440          * Update a photo
441          *
442          * @param array $fields     Contains the fields that are updated
443          * @param array $conditions Condition array with the key values
444          * @param Image $image      Image to update. Optional, default null.
445          * @param array $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
446          *
447          * @return boolean  Was the update successfull?
448          *
449          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
450          * @see   \Friendica\Database\DBA::update
451          */
452         public static function update(array $fields, array $conditions, Image $image = null, array $old_fields = []): bool
453         {
454                 if (!is_null($image)) {
455                         // get photo to update
456                         $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
457
458                         foreach($photos as $photo) {
459                                 try {
460                                         $backend_class         = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
461                                         $fields['backend-ref'] = $backend_class->put($image->asString(), $photo['backend-ref']);
462                                 } catch (InvalidClassStorageException $storageException) {
463                                         $fields['data'] = $image->asString();
464                                 }
465                         }
466                         $fields['updated'] = DateTimeFormat::utcNow();
467                 }
468
469                 $fields['edited'] = DateTimeFormat::utcNow();
470
471                 return DBA::update('photo', $fields, $conditions, $old_fields);
472         }
473
474         /**
475          * @param string  $image_url     Remote URL
476          * @param integer $uid           user id
477          * @param integer $cid           contact id
478          * @param boolean $quit_on_error optional, default false
479          * @return array|bool Array on success, false on error
480          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
481          * @throws \ImagickException
482          */
483         public static function importProfilePhoto(string $image_url, int $uid, int $cid, bool $quit_on_error = false)
484         {
485                 $thumb = '';
486                 $micro = '';
487
488                 $photo = DBA::selectFirst(
489                         'photo', ['resource-id'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'photo-type' => self::CONTACT_AVATAR]
490                 );
491                 if (!empty($photo['resource-id'])) {
492                         $resource_id = $photo['resource-id'];
493                 } else {
494                         $resource_id = self::newResource();
495                 }
496
497                 $photo_failure = false;
498
499                 $filename = basename($image_url);
500                 if (!empty($image_url)) {
501                         $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE);
502                         Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
503                         $img_str = $ret->getBody();
504                         $type = $ret->getContentType();
505                 } else {
506                         $img_str = '';
507                         $type = '';
508                 }
509
510                 if ($quit_on_error && ($img_str == '')) {
511                         return false;
512                 }
513
514                 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
515
516                 $image = new Image($img_str, $type);
517                 if ($image->isValid()) {
518                         $image->scaleToSquare(300);
519
520                         $filesize = strlen($image->asString());
521                         $maximagesize = DI::config()->get('system', 'maximagesize');
522                         if (!empty($maximagesize) && ($filesize > $maximagesize)) {
523                                 Logger::info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $image->getType()]);
524                                 if ($image->getType() == 'image/gif') {
525                                         $image->toStatic();
526                                         $image = new Image($image->asString(), 'image/png');
527
528                                         $filesize = strlen($image->asString());
529                                         Logger::info('Converted gif to a static png', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]);
530                                 }
531                                 if ($filesize > $maximagesize) {
532                                         foreach ([160, 80] as $pixels) {
533                                                 if ($filesize > $maximagesize) {
534                                                         Logger::info('Resize', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'max' => $maximagesize, 'pixels' => $pixels, 'type' => $image->getType()]);
535                                                         $image->scaleDown($pixels);
536                                                         $filesize = strlen($image->asString());
537                                                 }
538                                         }
539                                 }
540                                 Logger::info('Avatar is resized', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]);
541                         }
542
543                         $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4, self::CONTACT_AVATAR);
544
545                         if ($r === false) {
546                                 $photo_failure = true;
547                         }
548
549                         $image->scaleDown(80);
550
551                         $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 5, self::CONTACT_AVATAR);
552
553                         if ($r === false) {
554                                 $photo_failure = true;
555                         }
556
557                         $image->scaleDown(48);
558
559                         $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 6, self::CONTACT_AVATAR);
560
561                         if ($r === false) {
562                                 $photo_failure = true;
563                         }
564
565                         $suffix = '?ts=' . time();
566
567                         $image_url = DI::baseUrl() . '/photo/' . $resource_id . '-4.' . $image->getExt() . $suffix;
568                         $thumb = DI::baseUrl() . '/photo/' . $resource_id . '-5.' . $image->getExt() . $suffix;
569                         $micro = DI::baseUrl() . '/photo/' . $resource_id . '-6.' . $image->getExt() . $suffix;
570                 } else {
571                         $photo_failure = true;
572                 }
573
574                 if ($photo_failure && $quit_on_error) {
575                         return false;
576                 }
577
578                 if ($photo_failure) {
579                         $contact = Contact::getById($cid) ?: [];
580                         $image_url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
581                         $thumb = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
582                         $micro = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
583                 }
584
585                 return [$image_url, $thumb, $micro];
586         }
587
588         /**
589          * Returns a float that represents the GPS coordinate from EXIF data
590          *
591          * @param array $exifCoord coordinate
592          * @param string $hemi      hemi
593          * @return float
594          */
595         public static function getGps(array $exifCoord, string $hemi): float
596         {
597                 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
598                 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
599                 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
600
601                 $flip = ($hemi == 'W' || $hemi == 'S') ? -1 : 1;
602
603                 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
604         }
605
606         /**
607          * Change GPS to float number
608          *
609          * @param string $coordPart coordPart
610          * @return float
611          */
612         private static function gps2Num(string $coordPart): float
613         {
614                 $parts = explode('/', $coordPart);
615
616                 if (count($parts) <= 0) {
617                         return 0;
618                 }
619
620                 if (count($parts) == 1) {
621                         return (float)$parts[0];
622                 }
623
624                 return floatval($parts[0]) / floatval($parts[1]);
625         }
626
627         /**
628          * Fetch the photo albums that are available for a viewer
629          *
630          * The query in this function is cost intensive, so it is cached.
631          *
632          * @param int  $uid    User id of the photos
633          * @param bool $update Update the cache
634          *
635          * @return array Returns array of the photo albums
636          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
637          */
638         public static function getAlbums(int $uid, bool $update = false): array
639         {
640                 $sql_extra = Security::getPermissionsSQLByUserId($uid);
641
642                 $avatar_type = (Session::getLocalUser() && (Session::getLocalUser() == $uid)) ? self::USER_AVATAR : self::DEFAULT;
643                 $banner_type = (Session::getLocalUser() && (Session::getLocalUser() == $uid)) ? self::USER_BANNER : self::DEFAULT;
644
645                 $key = 'photo_albums:' . $uid . ':' . Session::getLocalUser() . ':' . Session::getRemoteUser();
646                 $albums = DI::cache()->get($key);
647
648                 if (is_null($albums) || $update) {
649                         if (!DI::config()->get('system', 'no_count', false)) {
650                                 /// @todo This query needs to be renewed. It is really slow
651                                 // At this time we just store the data in the cache
652                                 $albums = DBA::toArray(DBA::p("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
653                                         FROM `photo`
654                                         WHERE `uid` = ? AND `photo-type` IN (?, ?, ?) $sql_extra
655                                         GROUP BY `album` ORDER BY `created` DESC",
656                                         $uid,
657                                         self::DEFAULT,
658                                         $banner_type,
659                                         $avatar_type
660                                 ));
661                         } else {
662                                 // This query doesn't do the count and is much faster
663                                 $albums = DBA::toArray(DBA::p("SELECT DISTINCT(`album`), '' AS `total`
664                                         FROM `photo` USE INDEX (`uid_album_scale_created`)
665                                         WHERE `uid` = ? AND `photo-type` IN (?, ?, ?) $sql_extra",
666                                         $uid,
667                                         self::DEFAULT,
668                                         $banner_type,
669                                         $avatar_type
670                                 ));
671                         }
672                         DI::cache()->set($key, $albums, Duration::DAY);
673                 }
674                 return $albums;
675         }
676
677         /**
678          * @param int $uid User id of the photos
679          * @return void
680          * @throws \Exception
681          */
682         public static function clearAlbumCache(int $uid)
683         {
684                 $key = 'photo_albums:' . $uid . ':' . Session::getLocalUser() . ':' . Session::getRemoteUser();
685                 DI::cache()->set($key, null, Duration::DAY);
686         }
687
688         /**
689          * Generate a unique photo ID.
690          *
691          * @return string Resource GUID
692          * @throws \Exception
693          */
694         public static function newResource(): string
695         {
696                 return System::createGUID(32, false);
697         }
698
699         /**
700          * Extracts the rid from a local photo URI
701          *
702          * @param string $image_uri The URI of the photo
703          * @return string The rid of the photo, or an empty string if the URI is not local
704          */
705         public static function ridFromURI(string $image_uri): string
706         {
707                 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
708                         return '';
709                 }
710                 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
711                 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
712                 return trim($image_uri);
713         }
714
715         /**
716          * Checks if the given URL is a local photo.
717          * Since it is meant for time critical occasions, the check is done without any database requests.
718          *
719          * @param string $url
720          * @return boolean
721          */
722         public static function isPhotoURI(string $url): bool
723         {
724                 return !empty(self::ridFromURI($url));
725         }
726
727         /**
728          * Changes photo permissions that had been embedded in a post
729          *
730          * @todo This function currently does have some flaws:
731          * - Sharing a post with a forum will create a photo that only the forum can see.
732          * - Sharing a photo again that been shared non public before doesn't alter the permissions.
733          *
734          * @return string
735          * @throws \Exception
736          */
737         public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
738         {
739                 // Simplify image codes
740                 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
741                 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
742
743                 // Search for images
744                 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
745                         return false;
746                 }
747                 $images = $match[1];
748                 if (empty($images)) {
749                         return false;
750                 }
751
752                 foreach ($images as $image) {
753                         $image_rid = self::ridFromURI($image);
754                         if (empty($image_rid)) {
755                                 continue;
756                         }
757
758                         // Ensure to only modify photos that you own
759                         $srch = '<' . intval($original_contact_id) . '>';
760
761                         $condition = [
762                                 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
763                                 'resource-id' => $image_rid, 'uid' => $uid
764                         ];
765                         if (!self::exists($condition)) {
766                                 $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]);
767                                 if (!DBA::isResult($photo)) {
768                                         Logger::info('Image not found', ['resource-id' => $image_rid]);
769                                 } else {
770                                         Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]);
771                                 }
772                                 continue;
773                         }
774
775                         /**
776                          * @todo Existing permissions need to be mixed with the new ones.
777                          * Otherwise this creates problems with sharing the same picture multiple times
778                          * Also check if $str_contact_allow does contain a public forum.
779                          * Then set the permissions to public.
780                          */
781
782                         self::setPermissionForRessource($image_rid, $uid, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
783                 }
784
785                 return true;
786         }
787
788         /**
789          * Add permissions to photo ressource
790          * @todo mix with previous photo permissions
791          *
792          * @param string $image_rid
793          * @param integer $uid
794          * @param string $str_contact_allow
795          * @param string $str_group_allow
796          * @param string $str_contact_deny
797          * @param string $str_group_deny
798          * @return void
799          */
800         public static function setPermissionForRessource(string $image_rid, int $uid, string $str_contact_allow, string $str_group_allow, string $str_contact_deny, string $str_group_deny)
801         {
802                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
803                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny,
804                 'accessible' => DI::pConfig()->get($uid, 'system', 'accessible-photos', false)];
805
806                 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
807                 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
808                 self::update($fields, $condition);
809         }
810
811         /**
812          * Fetch the guid and scale from picture links
813          *
814          * @param string $name Picture link
815          * @return array
816          */
817         public static function getResourceData(string $name): array
818         {
819                 $base = DI::baseUrl()->get();
820
821                 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
822
823                 if (parse_url($guid, PHP_URL_SCHEME)) {
824                         return [];
825                 }
826
827                 $guid = pathinfo($guid, PATHINFO_FILENAME);
828                 if (substr($guid, -2, 1) != "-") {
829                         return [];
830                 }
831
832                 $scale = intval(substr($guid, -1, 1));
833                 if (!is_numeric($scale)) {
834                         return [];
835                 }
836
837                 $guid = substr($guid, 0, -2);
838                 return ['guid' => $guid, 'scale' => $scale];
839         }
840
841         /**
842          * Tests if the picture link points to a locally stored picture
843          *
844          * @param string $name Picture link
845          * @return boolean
846          * @throws \Exception
847          */
848         public static function isLocal(string $name): bool
849         {
850                 // @TODO Maybe a proper check here on true condition?
851                 return (bool)self::getIdForName($name);
852         }
853
854         /**
855          * Return the id of a local photo
856          *
857          * @param string $name Picture link
858          * @return int
859          */
860         public static function getIdForName(string $name): int
861         {
862                 $data = self::getResourceData($name);
863                 if (empty($data)) {
864                         return 0;
865                 }
866
867                 $photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $data['guid'], 'scale' => $data['scale']]);
868                 if (!empty($photo['id'])) {
869                         return $photo['id'];
870                 }
871                 return 0;
872         }
873
874         /**
875          * Tests if the link points to a locally stored picture page
876          *
877          * @param string $name Page link
878          * @return boolean
879          * @throws \Exception
880          */
881         public static function isLocalPage(string $name): bool
882         {
883                 $base = DI::baseUrl()->get();
884
885                 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
886                 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
887                 if (empty($guid)) {
888                         return false;
889                 }
890
891                 return DBA::exists('photo', ['resource-id' => $guid]);
892         }
893
894         /**
895          * Tries to resize image to wanted maximum size
896          *
897          * @param Image $image Image instance
898          * @return Image|null Image instance on success, null on error
899          */
900         private static function fitImageSize(Image $image)
901         {
902                 $max_length = DI::config()->get('system', 'max_image_length');
903                 if ($max_length > 0) {
904                         $image->scaleDown($max_length);
905                         Logger::info('File upload: Scaling picture to new size', ['max-length' => $max_length]);
906                 }
907
908                 $filesize = strlen($image->asString());
909                 $width    = $image->getWidth();
910                 $height   = $image->getHeight();
911
912                 $maximagesize = DI::config()->get('system', 'maximagesize');
913
914                 if (!empty($maximagesize) && ($filesize > $maximagesize)) {
915                         // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
916                         foreach ([5120, 2560, 1280, 640] as $pixels) {
917                                 if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
918                                         Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
919                                         $image->scaleDown($pixels);
920                                         $filesize = strlen($image->asString());
921                                         $width = $image->getWidth();
922                                         $height = $image->getHeight();
923                                 }
924                         }
925                         if ($filesize > $maximagesize) {
926                                 Logger::notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
927                                 return null;
928                         }
929                 }
930
931                 return $image;
932         }
933
934         /**
935          * Fetches image from URL and returns an array with instance and local file name
936          *
937          * @param string $image_url URL to image
938          * @return array With: 'image' and 'filename' fields or empty array on error
939          */
940         private static function loadImageFromURL(string $image_url): array
941         {
942                 $filename = basename($image_url);
943                 if (!empty($image_url)) {
944                         $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE);
945                         Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
946                         $img_str = $ret->getBody();
947                         $type = $ret->getContentType();
948                 } else {
949                         $img_str = '';
950                         $type = '';
951                 }
952
953                 if (empty($img_str)) {
954                         Logger::notice('Empty content');
955                         return [];
956                 }
957
958                 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
959
960                 $image = new Image($img_str, $type);
961
962                 $image = self::fitImageSize($image);
963                 if (empty($image)) {
964                         return [];
965                 }
966
967                 return ['image' => $image, 'filename' => $filename];
968         }
969
970         /**
971          * Inserts uploaded image into database and removes local temporary file
972          *
973          * @param array $files File array
974          * @return array With 'image' for Image instance and 'filename' for local file name or empty array on error
975          */
976         private static function uploadImage(array $files): array
977         {
978                 Logger::info('starting new upload');
979
980                 if (empty($files)) {
981                         Logger::notice('Empty upload file');
982                         return [];
983                 }
984
985                 if (!empty($files['tmp_name'])) {
986                         if (is_array($files['tmp_name'])) {
987                                 $src = $files['tmp_name'][0];
988                         } else {
989                                 $src = $files['tmp_name'];
990                         }
991                 } else {
992                         $src = '';
993                 }
994
995                 if (!empty($files['name'])) {
996                         if (is_array($files['name'])) {
997                                 $filename = basename($files['name'][0]);
998                         } else {
999                                 $filename = basename($files['name']);
1000                         }
1001                 } else {
1002                         $filename = '';
1003                 }
1004
1005                 if (!empty($files['size'])) {
1006                         if (is_array($files['size'])) {
1007                                 $filesize = intval($files['size'][0]);
1008                         } else {
1009                                 $filesize = intval($files['size']);
1010                         }
1011                 } else {
1012                         $filesize = 0;
1013                 }
1014
1015                 if (!empty($files['type'])) {
1016                         if (is_array($files['type'])) {
1017                                 $filetype = $files['type'][0];
1018                         } else {
1019                                 $filetype = $files['type'];
1020                         }
1021                 } else {
1022                         $filetype = '';
1023                 }
1024
1025                 if (empty($src)) {
1026                         Logger::notice('No source file name', ['files' => $files]);
1027                         return [];
1028                 }
1029
1030                 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
1031
1032                 Logger::info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]);
1033
1034                 $imagedata = @file_get_contents($src);
1035                 $image = new Image($imagedata, $filetype);
1036                 if (!$image->isValid()) {
1037                         Logger::notice('Image is unvalid', ['files' => $files]);
1038                         return [];
1039                 }
1040
1041                 $image->orient($src);
1042                 @unlink($src);
1043
1044                 $image = self::fitImageSize($image);
1045                 if (empty($image)) {
1046                         return [];
1047                 }
1048
1049                 return ['image' => $image, 'filename' => $filename];
1050         }
1051
1052         /**
1053          * Handles uploaded image and assigns it to given user id
1054          *
1055          * @param int         $uid   User ID
1056          * @param array       $files uploaded file array
1057          * @param string      $album Album name (optional)
1058          * @param string|null $allow_cid
1059          * @param string|null $allow_gid
1060          * @param string      $deny_cid
1061          * @param string      $deny_gid
1062          * @param string      $desc Description (optional)
1063          * @param string      $resource_id GUID (optional)
1064          * @return array photo record or empty array on error
1065          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1066          */
1067         public static function upload(int $uid, array $files, string $album = '', string $allow_cid = null, string $allow_gid = null, string $deny_cid = '', string $deny_gid = '', string $desc = '', string $resource_id = ''): array
1068         {
1069                 $user = User::getOwnerDataById($uid);
1070                 if (empty($user)) {
1071                         Logger::notice('User not found', ['uid' => $uid]);
1072                         return [];
1073                 }
1074
1075                 $data = self::uploadImage($files);
1076                 if (empty($data)) {
1077                         Logger::info('upload failed');
1078                         return [];
1079                 }
1080
1081                 $image    = $data['image'];
1082                 $filename = $data['filename'];
1083                 $width    = $image->getWidth();
1084                 $height   = $image->getHeight();
1085
1086                 $resource_id = $resource_id ?: self::newResource();
1087                 $album       = $album ?: DI::l10n()->t('Wall Photos');
1088
1089                 if (is_null($allow_cid) && is_null($allow_gid)) {
1090                         $allow_cid = '<' . $user['id'] . '>';
1091                         $allow_gid = '';
1092                 }
1093
1094                 $smallest = 0;
1095
1096                 $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 0, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1097                 if (!$r) {
1098                         Logger::warning('Photo could not be stored', ['uid' => $user['uid'], 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1099                         return [];
1100                 }
1101
1102                 if ($width > 640 || $height > 640) {
1103                         $image->scaleDown(640);
1104                         $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 1, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1105                         if ($r) {
1106                                 $smallest = 1;
1107                         }
1108                 }
1109
1110                 if ($width > 320 || $height > 320) {
1111                         $image->scaleDown(320);
1112                         $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 2, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1113                         if ($r && ($smallest == 0)) {
1114                                 $smallest = 2;
1115                         }
1116                 }
1117
1118                 $condition = ['resource-id' => $resource_id];
1119                 $photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]);
1120                 if (empty($photo)) {
1121                         Logger::notice('Photo not found', ['condition' => $condition]);
1122                         return [];
1123                 }
1124
1125                 $picture = [];
1126
1127                 $picture['id']          = $photo['id'];
1128                 $picture['resource_id'] = $resource_id;
1129                 $picture['size']        = $photo['datasize'];
1130                 $picture['width']       = $photo['width'];
1131                 $picture['height']      = $photo['height'];
1132                 $picture['type']        = $photo['type'];
1133                 $picture['albumpage']   = DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $resource_id;
1134                 $picture['picture']     = DI::baseUrl() . '/photo/{$resource_id}-0.' . $image->getExt();
1135                 $picture['preview']     = DI::baseUrl() . '/photo/{$resource_id}-{$smallest}.' . $image->getExt();
1136
1137                 Logger::info('upload done', ['picture' => $picture]);
1138                 return $picture;
1139         }
1140
1141         /**
1142          * Upload a user avatar
1143          *
1144          * @param int    $uid   User ID
1145          * @param array  $files uploaded file array
1146          * @param string $url   External image url
1147          * @return string avatar resource
1148          */
1149         public static function uploadAvatar(int $uid, array $files, string $url = ''): string
1150         {
1151                 if (!empty($files)) {
1152                         $data = self::uploadImage($files);
1153                         if (empty($data)) {
1154                                 Logger::info('upload failed');
1155                                 return '';
1156                         }
1157                 } elseif (!empty($url)) {
1158                         $data = self::loadImageFromURL($url);
1159                         if (empty($data)) {
1160                                 Logger::info('loading from external url failed');
1161                                 return '';
1162                         }
1163                 } else {
1164                         Logger::info('Neither files nor url provided');
1165                         return '';
1166                 }
1167
1168                 $image    = $data['image'];
1169                 $filename = $data['filename'];
1170                 $width    = $image->getWidth();
1171                 $height   = $image->getHeight();
1172
1173                 $resource_id = self::newResource();
1174                 $album       = DI::l10n()->t(self::PROFILE_PHOTOS);
1175
1176                 // upload profile image (scales 4, 5, 6)
1177                 logger::info('starting new profile image upload');
1178
1179                 if ($width > 300 || $height > 300) {
1180                         $image->scaleDown(300);
1181                 }
1182
1183                 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 4, self::USER_AVATAR);
1184                 if (!$r) {
1185                         logger::warning('profile image upload with scale 4 (300) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1186                 }
1187
1188                 if ($width > 80 || $height > 80) {
1189                         $image->scaleDown(80);
1190                 }
1191
1192                 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 5, self::USER_AVATAR);
1193                 if (!$r) {
1194                         logger::warning('profile image upload with scale 5 (80) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1195                 }
1196
1197                 if ($width > 48 || $height > 48) {
1198                         $image->scaleDown(48);
1199                 }
1200
1201                 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 6, self::USER_AVATAR);
1202                 if (!$r) {
1203                         logger::warning('profile image upload with scale 6 (48) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1204                 }
1205
1206                 logger::info('new profile image upload ended');
1207
1208                 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $resource_id, $uid];
1209                 self::update(['profile' => false, 'photo-type' => self::DEFAULT], $condition);
1210
1211                 Contact::updateSelfFromUserID($uid, true);
1212
1213                 // Update global directory in background
1214                 Profile::publishUpdate($uid);
1215
1216                 return $resource_id;
1217         }
1218
1219         /**
1220          * Upload a user banner
1221          *
1222          * @param int    $uid   User ID
1223          * @param array  $files uploaded file array
1224          * @param string $url   External image url
1225          * @return string avatar resource
1226          */
1227         public static function uploadBanner(int $uid, array $files = [], string $url = ''): string
1228         {
1229                 if (!empty($files)) {
1230                         $data = self::uploadImage($files);
1231                         if (empty($data)) {
1232                                 Logger::info('upload failed');
1233                                 return '';
1234                         }
1235                 } elseif (!empty($url)) {
1236                         $data = self::loadImageFromURL($url);
1237                         if (empty($data)) {
1238                                 Logger::info('loading from external url failed');
1239                                 return '';
1240                         }
1241                 } else {
1242                         Logger::info('Neither files nor url provided');
1243                         return '';
1244                 }
1245
1246                 $image    = $data['image'];
1247                 $filename = $data['filename'];
1248                 $width    = $image->getWidth();
1249                 $height   = $image->getHeight();
1250
1251                 $resource_id = self::newResource();
1252                 $album       = DI::l10n()->t(self::BANNER_PHOTOS);
1253
1254                 if ($width > 960) {
1255                         $image->scaleDown(960);
1256                 }
1257
1258                 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 3, self::USER_BANNER);
1259                 if (!$r) {
1260                         logger::warning('profile banner upload with scale 3 (960) failed');
1261                 }
1262
1263                 logger::info('new profile banner upload ended');
1264
1265                 $condition = ["`photo-type` = ? AND `resource-id` != ? AND `uid` = ?", self::USER_BANNER, $resource_id, $uid];
1266                 self::update(['photo-type' => self::DEFAULT], $condition);
1267
1268                 Contact::updateSelfFromUserID($uid, true);
1269
1270                 // Update global directory in background
1271                 Profile::publishUpdate($uid);
1272
1273                 return $resource_id;
1274         }
1275 }
1276