]> git.mxchange.org Git - friendica.git/blob - src/Model/Photo.php
some renamings
[friendica.git] / src / Model / Photo.php
1 <?php
2
3 /**
4  * @file src/Model/Photo.php
5  * @brief This file contains the Photo class for database interface
6  */
7 namespace Friendica\Model;
8
9 use Friendica\BaseObject;
10 use Friendica\Core\Cache;
11 use Friendica\Core\Config;
12 use Friendica\Core\L10n;
13 use Friendica\Core\StorageManager;
14 use Friendica\Core\System;
15 use Friendica\Database\DBA;
16 use Friendica\Database\DBStructure;
17 use Friendica\Model\Storage\IStorage;
18 use Friendica\Object\Image;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Network;
21 use Friendica\Util\Security;
22
23 require_once "include/dba.php";
24
25 /**
26  * Class to handle photo dabatase table
27  */
28 class Photo extends BaseObject
29 {
30         /**
31          * @brief Select rows from the photo table
32          *
33          * @param array $fields     Array of selected fields, empty for all
34          * @param array $conditions Array of fields for conditions
35          * @param array $params     Array of several parameters
36          *
37          * @return boolean|array
38          *
39          * @throws \Exception
40          * @see   \Friendica\Database\DBA::select
41          */
42         public static function select(array $fields = [], array $conditions = [], array $params = [])
43         {
44                 if (empty($fields)) {
45                         $fields = self::getFields();
46                 }
47
48                 $r = DBA::select("photo", $fields, $conditions, $params);
49                 return DBA::toArray($r);
50         }
51
52         /**
53          * @brief Retrieve a single record from the photo table
54          *
55          * @param array $fields     Array of selected fields, empty for all
56          * @param array $conditions Array of fields for conditions
57          * @param array $params     Array of several parameters
58          *
59          * @return bool|array
60          *
61          * @throws \Exception
62          * @see   \Friendica\Database\DBA::select
63          */
64         public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
65         {
66                 if (empty($fields)) {
67                         $fields = self::getFields();
68                 }
69
70                 return DBA::selectFirst("photo", $fields, $conditions, $params);
71         }
72
73         /**
74          * @brief Get photos for user id
75          *
76          * @param integer $uid        User id
77          * @param string  $resourceid Rescource ID of the photo
78          * @param array   $conditions Array of fields for conditions
79          * @param array   $params     Array of several parameters
80          *
81          * @return bool|array
82          *
83          * @throws \Exception
84          * @see   \Friendica\Database\DBA::select
85          */
86         public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
87         {
88                 $conditions["resource-id"] = $resourceid;
89                 $conditions["uid"] = $uid;
90
91                 return self::select([], $conditions, $params);
92         }
93
94         /**
95          * @brief Get a photo for user id
96          *
97          * @param integer $uid        User id
98          * @param string  $resourceid Rescource ID of the photo
99          * @param integer $scale      Scale of the photo. Defaults to 0
100          * @param array   $conditions Array of fields for conditions
101          * @param array   $params     Array of several parameters
102          *
103          * @return bool|array
104          *
105          * @throws \Exception
106          * @see   \Friendica\Database\DBA::select
107          */
108         public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
109         {
110                 $conditions["resource-id"] = $resourceid;
111                 $conditions["uid"] = $uid;
112                 $conditions["scale"] = $scale;
113
114                 return self::selectFirst([], $conditions, $params);
115         }
116
117         /**
118          * @brief Get a single photo given resource id and scale
119          *
120          * This method checks for permissions. Returns associative array
121          * on success, "no sign" image info, if user has no permission,
122          * false if photo does not exists
123          *
124          * @param string  $resourceid Rescource ID of the photo
125          * @param integer $scale      Scale of the photo. Defaults to 0
126          *
127          * @return boolean|array
128          * @throws \Exception
129          */
130         public static function getPhoto($resourceid, $scale = 0)
131         {
132                 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
133                 if ($r === false) {
134                         return false;
135                 }
136
137                 $sql_acl = Security::getPermissionsSQLByUserId($r["uid"]);
138
139                 $conditions = [
140                         "`resource-id` = ? AND `scale` <= ? " . $sql_acl,
141                         $resourceid, $scale
142                 ];
143
144                 $params = ["order" => ["scale" => true]];
145
146                 $photo = self::selectFirst([], $conditions, $params);
147
148                 return $photo;
149         }
150
151         /**
152          * @brief Check if photo with given conditions exists
153          *
154          * @param array $conditions Array of extra conditions
155          *
156          * @return boolean
157          * @throws \Exception
158          */
159         public static function exists(array $conditions)
160         {
161                 return DBA::exists("photo", $conditions);
162         }
163
164
165         /**
166          * @brief Get Image object for given row id. null if row id does not exist
167          *
168          * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
169          *
170          * @return \Friendica\Object\Image
171          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
172          * @throws \ImagickException
173          */
174         public static function getImageForPhoto(array $photo)
175         {
176                 $data = "";
177
178                 if ($photo["backend-class"] == "") {
179                         // legacy data storage in "data" column
180                         $i = self::selectFirst(["data"], ["id" => $photo["id"]]);
181                         if ($i === false) {
182                                 return null;
183                         }
184                         $data = $i["data"];
185                 } else {
186                         $backendClass = $photo["backend-class"];
187                         $backendRef = $photo["backend-ref"];
188                         $data = $backendClass::get($backendRef);
189                 }
190
191                 if ($data === "") {
192                         return null;
193                 }
194
195                 return new Image($data, $photo["type"]);
196         }
197
198         /**
199          * @brief Return a list of fields that are associated with the photo table
200          *
201          * @return array field list
202          * @throws \Exception
203          */
204         private static function getFields()
205         {
206                 $allfields = DBStructure::definition(self::getApp()->getBasePath(), false);
207                 $fields = array_keys($allfields["photo"]["fields"]);
208                 array_splice($fields, array_search("data", $fields), 1);
209                 return $fields;
210         }
211
212         /**
213          * @brief Construct a photo array for a system resource image
214          *
215          * @param string $filename Image file name relative to code root
216          * @param string $mimetype Image mime type. Defaults to "image/jpeg"
217          *
218          * @return array
219          * @throws \Exception
220          */
221         public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
222         {
223                 $fields = self::getFields();
224                 $values = array_fill(0, count($fields), "");
225
226                 $photo = array_combine($fields, $values);
227                 $photo["backend-class"] = Storage\SystemResource::class;
228                 $photo["backend-ref"] = $filename;
229                 $photo["type"] = $mimetype;
230                 $photo["cacheable"] = false;
231
232                 return $photo;
233         }
234
235
236         /**
237          * @brief store photo metadata in db and binary in default backend
238          *
239          * @param Image   $Image     Image object with data
240          * @param integer $uid       User ID
241          * @param integer $cid       Contact ID
242          * @param integer $rid       Resource ID
243          * @param string  $filename  Filename
244          * @param string  $album     Album name
245          * @param integer $scale     Scale
246          * @param integer $profile   Is a profile image? optional, default = 0
247          * @param string  $allow_cid Permissions, allowed contacts. optional, default = ""
248          * @param string  $allow_gid Permissions, allowed groups. optional, default = ""
249          * @param string  $deny_cid  Permissions, denied contacts.optional, default = ""
250          * @param string  $deny_gid  Permissions, denied greoup.optional, default = ""
251          * @param string  $desc      Photo caption. optional, default = ""
252          *
253          * @return boolean True on success
254          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255          */
256         public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
257         {
258                 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
259                 if (DBA::isResult($photo)) {
260                         $guid = $photo["guid"];
261                 } else {
262                         $guid = System::createGUID();
263                 }
264
265                 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
266                 $created = DateTimeFormat::utcNow();
267                 if (DBA::isResult($existing_photo)) {
268                         $created = $existing_photo["created"];
269                 }
270
271                 // Get defined storage backend.
272                 // if no storage backend, we use old "data" column in photo table.
273                 // if is an existing photo, reuse same backend
274                 $data = "";
275                 $backend_ref = "";
276
277                 /** @var IStorage $backend_class */
278                 if (DBA::isResult($existing_photo)) {
279                         $backend_ref = (string)$existing_photo["backend-ref"];
280                         $backend_class = (string)$existing_photo["backend-class"];
281                 } else {
282                         $backend_class = StorageManager::getBackend();
283                 }
284
285                 if ($backend_class === "") {
286                         $data = $Image->asString();
287                 } else {
288                         $backend_ref = $backend_class::put($Image->asString(), $backend_ref);
289                 }
290
291
292                 $fields = [
293                         "uid" => $uid,
294                         "contact-id" => $cid,
295                         "guid" => $guid,
296                         "resource-id" => $rid,
297                         "created" => $created,
298                         "edited" => DateTimeFormat::utcNow(),
299                         "filename" => basename($filename),
300                         "type" => $Image->getType(),
301                         "album" => $album,
302                         "height" => $Image->getHeight(),
303                         "width" => $Image->getWidth(),
304                         "datasize" => strlen($Image->asString()),
305                         "data" => $data,
306                         "scale" => $scale,
307                         "profile" => $profile,
308                         "allow_cid" => $allow_cid,
309                         "allow_gid" => $allow_gid,
310                         "deny_cid" => $deny_cid,
311                         "deny_gid" => $deny_gid,
312                         "desc" => $desc,
313                         "backend-class" => $backend_class,
314                         "backend-ref" => $backend_ref
315                 ];
316
317                 if (DBA::isResult($existing_photo)) {
318                         $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
319                 } else {
320                         $r = DBA::insert("photo", $fields);
321                 }
322
323                 return $r;
324         }
325
326
327         /**
328          * @brief Delete info from table and data from storage
329          *
330          * @param array $conditions Field condition(s)
331          * @param array $options    Options array, Optional
332          *
333          * @return boolean
334          *
335          * @throws \Exception
336          * @see   \Friendica\Database\DBA::delete
337          */
338         public static function delete(array $conditions, array $options = [])
339         {
340                 // get photo to delete data info
341                 $photos = self::select(["backend-class","backend-ref"], $conditions);
342
343                 foreach($photos as $photo) {
344                         /** @var IStorage $backend_class */
345                         $backend_class = (string)$photo["backend-class"];
346                         if ($backend_class !== "") {
347                                 $backend_class::delete($photo["backend-ref"]);
348                         }
349                 }
350
351                 return DBA::delete("photo", $conditions, $options);
352         }
353
354         /**
355          * @brief This function is used by the fromgplus addon
356          *
357          * Stores a photo based on image data or an URL
358          *
359          * @param integer $uid       user id
360          * @param string  $imagedata optional, default empty
361          * @param string  $url       optional, default empty
362          * @return array
363          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
364          * @throws \ImagickException
365          */
366         public static function storeByData($uid, $imagedata = "", $url = "")
367         {
368                 $a = self::getApp();
369                 $logger = $a->getLogger();
370                 $profiler = $a->getProfiler();
371
372                 $userStmt = DBA::p(
373                         "SELECT `user`.`nickname`, `user`.`page-flags`, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
374                         WHERE `user`.`uid` = %d AND `user`.`blocked` = 0 AND `contact`.`self` = 1 LIMIT 1",
375                         intval($uid)
376                 );
377
378                 if (!DBA::isResult($userStmt)) {
379                         $logger->info("Can't detect user data.", ['uid' => $uid]);
380                         return [];
381                 } else {
382                         $user = DBA::toArray($userStmt);
383                 }
384
385                 $page_owner_nick  = $user[0]['nickname'];
386
387                 /// @TODO
388                 /// $default_cid      = $isStored[0]['id'];
389                 /// $community_page   = (($isStored[0]['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
390
391                 if ((strlen($imagedata) == 0) && ($url == "")) {
392                         $logger->info("No image data and no url provided");
393                         return [];
394                 } elseif (strlen($imagedata) == 0) {
395                         $logger->info("Uploading picture,", ['url' => $url]);
396
397                         $stamp1 = microtime(true);
398                         $imagedata = @file_get_contents($url);
399                         $profiler->saveTimestamp($stamp1, "file", System::callstack());
400                 }
401
402                 $maxImageSize = Config::get('system', 'maximagesize');
403
404                 if (($maxImageSize) && (strlen($imagedata) > $maxImageSize)) {
405                         $logger->info("Image exceeds size limit.", ['max' => $maxImageSize, 'current' => strlen($imagedata)]);
406                         return [];
407                 }
408
409                 $tempFile = tempnam(get_temppath(), "cache");
410
411                 $stamp1 = microtime(true);
412                 file_put_contents($tempFile, $imagedata);
413                 $profiler->saveTimestamp($stamp1, "file", System::callstack());
414
415                 $data = getimagesize($tempFile);
416
417                 if (!isset($data["mime"])) {
418                         unlink($tempFile);
419                         $logger->info("File is no picture");
420                         return [];
421                 }
422
423                 $image = new Image($imagedata, $data["mime"]);
424
425                 if (!$image->isValid()) {
426                         unlink($tempFile);
427                         $logger->info("Picture is no valid picture");
428                         return [];
429                 }
430
431                 $image->orient($tempFile);
432                 unlink($tempFile);
433
434                 $max_length = Config::get('system', 'max_image_length');
435                 if (! $max_length) {
436                         $max_length = MAX_IMAGE_LENGTH;
437                 }
438
439                 if ($max_length > 0) {
440                         $image->scaleDown($max_length);
441                 }
442
443                 $width = $image->getWidth();
444                 $height = $image->getHeight();
445
446                 $hash = self::newResource();
447
448                 // Pictures are always public by now
449                 //$defperm = '<'.$default_cid.'>';
450                 $defperm = "";
451                 $visitor = 0;
452
453                 $isStored = Photo::store($image, $uid, $visitor, $hash, $tempFile, L10n::t('Wall Photos'), 0, 0, $defperm);
454
455                 if (!$isStored) {
456                         $logger->info("Picture couldn't be stored");
457                         return [];
458                 }
459
460                 $image = ["page" => $a->getBaseURL() . '/photos/' . $page_owner_nick . '/image/' . $hash,
461                         "full" => $a->getBaseURL() . "/photo/{$hash}-0." . $image->getExt()];
462
463                 if ($width > 800 || $height > 800) {
464                         $image["large"] = $a->getBaseURL() . "/photo/{$hash}-0." . $image->getExt();
465                 }
466
467                 if ($width > 640 || $height > 640) {
468                         $image->scaleDown(640);
469                         $isStored = self::store($image, $uid, $visitor, $hash, $tempFile, L10n::t('Wall Photos'), 1, 0, $defperm);
470                         if ($isStored) {
471                                 $image["medium"] = $a->getBaseURL() . "/photo/{$hash}-1." . $image->getExt();
472                         }
473                 }
474
475                 if ($width > 320 || $height > 320) {
476                         $image->scaleDown(320);
477                         $isStored = self::store($image, $uid, $visitor, $hash, $tempFile, L10n::t('Wall Photos'), 2, 0, $defperm);
478                         if ($isStored) {
479                                 $image["small"] = $a->getBaseURL() . "/photo/{$hash}-2." . $image->getExt();
480                         }
481                 }
482
483                 if ($width > 160 && $height > 160) {
484                         $x = 0;
485                         $y = 0;
486
487                         $min = $image->getWidth();
488                         if ($min > 160) {
489                                 $x = ($min - 160) / 2;
490                         }
491
492                         if ($image->getHeight() < $min) {
493                                 $min = $image->getHeight();
494                                 if ($min > 160) {
495                                         $y = ($min - 160) / 2;
496                                 }
497                         }
498
499                         $min = 160;
500                         $image->crop(160, $x, $y, $min, $min);
501
502                         $isStored = self::store($image, $uid, $visitor, $hash, $tempFile, L10n::t('Wall Photos'), 3, 0, $defperm);
503                         if ($isStored) {
504                                 $image["thumb"] = $a->getBaseURL() . "/photo/{$hash}-3." . $image->getExt();
505                         }
506                 }
507
508                 // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
509                 $image["preview"] = $image["full"];
510
511                 // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
512                 //if (isset($image["thumb"]))
513                 //  $image["preview"] = $image["thumb"];
514
515                 // Unsure, if this should be activated or deactivated
516                 //if (isset($image["small"]))
517                 //  $image["preview"] = $image["small"];
518
519                 if (isset($image["medium"])) {
520                         $image["preview"] = $image["medium"];
521                 }
522
523                 return $image;
524         }
525
526         /**
527          * @brief Update a photo
528          *
529          * @param array         $fields     Contains the fields that are updated
530          * @param array         $conditions Condition array with the key values
531          * @param Image         $img        Image to update. Optional, default null.
532          * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
533          *
534          * @return boolean  Was the update successfull?
535          *
536          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
537          * @see   \Friendica\Database\DBA::update
538          */
539         public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
540         {
541                 if (!is_null($img)) {
542                         // get photo to update
543                         $photos = self::select(["backend-class","backend-ref"], $conditions);
544
545                         foreach($photos as $photo) {
546                                 /** @var IStorage $backend_class */
547                                 $backend_class = (string)$photo["backend-class"];
548                                 if ($backend_class !== "") {
549                                         $fields["backend-ref"] = $backend_class::put($img->asString(), $photo["backend-ref"]);
550                                 } else {
551                                         $fields["data"] = $img->asString();
552                                 }
553                         }
554                         $fields['updated'] = DateTimeFormat::utcNow();
555                 }
556
557                 $fields['edited'] = DateTimeFormat::utcNow();
558
559                 return DBA::update("photo", $fields, $conditions, $old_fields);
560         }
561
562         /**
563          * @param string  $image_url     Remote URL
564          * @param integer $uid           user id
565          * @param integer $cid           contact id
566          * @param boolean $quit_on_error optional, default false
567          * @return array
568          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
569          * @throws \ImagickException
570          */
571         public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
572         {
573                 $thumb = "";
574                 $micro = "";
575
576                 $photo = DBA::selectFirst(
577                         "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
578                 );
579                 if (!empty($photo['resource-id'])) {
580                         $hash = $photo["resource-id"];
581                 } else {
582                         $hash = self::newResource();
583                 }
584
585                 $photo_failure = false;
586
587                 $filename = basename($image_url);
588                 $img_str = Network::fetchUrl($image_url, true);
589
590                 if ($quit_on_error && ($img_str == "")) {
591                         return false;
592                 }
593
594                 $type = Image::guessType($image_url, true);
595                 $Image = new Image($img_str, $type);
596                 if ($Image->isValid()) {
597                         $Image->scaleToSquare(300);
598
599                         $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 4);
600
601                         if ($r === false) {
602                                 $photo_failure = true;
603                         }
604
605                         $Image->scaleDown(80);
606
607                         $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 5);
608
609                         if ($r === false) {
610                                 $photo_failure = true;
611                         }
612
613                         $Image->scaleDown(48);
614
615                         $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 6);
616
617                         if ($r === false) {
618                                 $photo_failure = true;
619                         }
620
621                         $suffix = "?ts=" . time();
622
623                         $image_url = System::baseUrl() . "/photo/" . $hash . "-4." . $Image->getExt() . $suffix;
624                         $thumb = System::baseUrl() . "/photo/" . $hash . "-5." . $Image->getExt() . $suffix;
625                         $micro = System::baseUrl() . "/photo/" . $hash . "-6." . $Image->getExt() . $suffix;
626
627                         // Remove the cached photo
628                         $a = \get_app();
629                         $basepath = $a->getBasePath();
630
631                         if (is_dir($basepath . "/photo")) {
632                                 $filename = $basepath . "/photo/" . $hash . "-4." . $Image->getExt();
633                                 if (file_exists($filename)) {
634                                         unlink($filename);
635                                 }
636                                 $filename = $basepath . "/photo/" . $hash . "-5." . $Image->getExt();
637                                 if (file_exists($filename)) {
638                                         unlink($filename);
639                                 }
640                                 $filename = $basepath . "/photo/" . $hash . "-6." . $Image->getExt();
641                                 if (file_exists($filename)) {
642                                         unlink($filename);
643                                 }
644                         }
645                 } else {
646                         $photo_failure = true;
647                 }
648
649                 if ($photo_failure && $quit_on_error) {
650                         return false;
651                 }
652
653                 if ($photo_failure) {
654                         $image_url = System::baseUrl() . "/images/person-300.jpg";
655                         $thumb = System::baseUrl() . "/images/person-80.jpg";
656                         $micro = System::baseUrl() . "/images/person-48.jpg";
657                 }
658
659                 return [$image_url, $thumb, $micro];
660         }
661
662         /**
663          * @param array $exifCoord coordinate
664          * @param string $hemi      hemi
665          * @return float
666          */
667         public static function getGps($exifCoord, $hemi)
668         {
669                 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
670                 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
671                 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
672
673                 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
674
675                 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
676         }
677
678         /**
679          * @param string $coordPart coordPart
680          * @return float
681          */
682         private static function gps2Num($coordPart)
683         {
684                 $parts = explode("/", $coordPart);
685
686                 if (count($parts) <= 0) {
687                         return 0;
688                 }
689
690                 if (count($parts) == 1) {
691                         return $parts[0];
692                 }
693
694                 return floatval($parts[0]) / floatval($parts[1]);
695         }
696
697         /**
698          * @brief Fetch the photo albums that are available for a viewer
699          *
700          * The query in this function is cost intensive, so it is cached.
701          *
702          * @param int  $uid    User id of the photos
703          * @param bool $update Update the cache
704          *
705          * @return array Returns array of the photo albums
706          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
707          */
708         public static function getAlbums($uid, $update = false)
709         {
710                 $sql_extra = Security::getPermissionsSQLByUserId($uid);
711
712                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
713                 $albums = Cache::get($key);
714                 if (is_null($albums) || $update) {
715                         if (!Config::get("system", "no_count", false)) {
716                                 /// @todo This query needs to be renewed. It is really slow
717                                 // At this time we just store the data in the cache
718                                 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
719                                         FROM `photo`
720                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra
721                                         GROUP BY `album` ORDER BY `created` DESC",
722                                         intval($uid),
723                                         DBA::escape("Contact Photos"),
724                                         DBA::escape(L10n::t("Contact Photos"))
725                                 );
726                         } else {
727                                 // This query doesn't do the count and is much faster
728                                 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
729                                         FROM `photo` USE INDEX (`uid_album_scale_created`)
730                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra",
731                                         intval($uid),
732                                         DBA::escape("Contact Photos"),
733                                         DBA::escape(L10n::t("Contact Photos"))
734                                 );
735                         }
736                         Cache::set($key, $albums, Cache::DAY);
737                 }
738                 return $albums;
739         }
740
741         /**
742          * @param int $uid User id of the photos
743          * @return void
744          * @throws \Exception
745          */
746         public static function clearAlbumCache($uid)
747         {
748                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
749                 Cache::set($key, null, Cache::DAY);
750         }
751
752         /**
753          * Generate a unique photo ID.
754          *
755          * @return string
756          * @throws \Exception
757          */
758         public static function newResource()
759         {
760                 return System::createGUID(32, false);
761         }
762 }