]> git.mxchange.org Git - friendica.git/blob - src/Model/Photo.php
Moving Model call outside Object Namespace
[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                 $r = 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($r)) {
379                         $logger->info("Can't detect user data.", ['uid' => $uid]);
380                         return([]);
381                 }
382
383                 $page_owner_nick  = $r[0]['nickname'];
384
385                 /// @TODO
386                 /// $default_cid      = $r[0]['id'];
387                 /// $community_page   = (($r[0]['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
388
389                 if ((strlen($imagedata) == 0) && ($url == "")) {
390                         $logger->info("No image data and no url provided");
391                         return([]);
392                 } elseif (strlen($imagedata) == 0) {
393                         $logger->info("Uploading picture,", ['url' => $url]);
394
395                         $stamp1 = microtime(true);
396                         $imagedata = @file_get_contents($url);
397                         $profiler->saveTimestamp($stamp1, "file", System::callstack());
398                 }
399
400                 $maximagesize = Config::get('system', 'maximagesize');
401
402                 if (($maximagesize) && (strlen($imagedata) > $maximagesize)) {
403                         $logger->info("Image exceeds size limit.", ['max' => $maximagesize, 'current' => strlen($imagedata)]);
404                         return([]);
405                 }
406
407                 $tempfile = tempnam(get_temppath(), "cache");
408
409                 $stamp1 = microtime(true);
410                 file_put_contents($tempfile, $imagedata);
411                 $profiler->saveTimestamp($stamp1, "file", System::callstack());
412
413                 $data = getimagesize($tempfile);
414
415                 if (!isset($data["mime"])) {
416                         unlink($tempfile);
417                         $logger->info("File is no picture");
418                         return([]);
419                 }
420
421                 $Image = new Image($imagedata, $data["mime"]);
422
423                 if (!$Image->isValid()) {
424                         unlink($tempfile);
425                         $logger->info("Picture is no valid picture");
426                         return([]);
427                 }
428
429                 $Image->orient($tempfile);
430                 unlink($tempfile);
431
432                 $max_length = Config::get('system', 'max_image_length');
433                 if (! $max_length) {
434                         $max_length = MAX_IMAGE_LENGTH;
435                 }
436
437                 if ($max_length > 0) {
438                         $Image->scaleDown($max_length);
439                 }
440
441                 $width = $Image->getWidth();
442                 $height = $Image->getHeight();
443
444                 $hash = Photo::newResource();
445
446                 // Pictures are always public by now
447                 //$defperm = '<'.$default_cid.'>';
448                 $defperm = "";
449                 $visitor = 0;
450
451                 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 0, 0, $defperm);
452
453                 if (!$r) {
454                         $logger->info("Picture couldn't be stored");
455                         return([]);
456                 }
457
458                 $image = ["page" => System::baseUrl().'/photos/'.$page_owner_nick.'/image/'.$hash,
459                         "full" => $a->getBaseURL()."/photo/{$hash}-0.".$Image->getExt()];
460
461                 if ($width > 800 || $height > 800) {
462                         $image["large"] = System::baseUrl()."/photo/{$hash}-0.".$Image->getExt();
463                 }
464
465                 if ($width > 640 || $height > 640) {
466                         $Image->scaleDown(640);
467                         $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 1, 0, $defperm);
468                         if ($r) {
469                                 $image["medium"] = System::baseUrl()."/photo/{$hash}-1.".$Image->getExt();
470                         }
471                 }
472
473                 if ($width > 320 || $height > 320) {
474                         $Image->scaleDown(320);
475                         $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 2, 0, $defperm);
476                         if ($r) {
477                                 $image["small"] = System::baseUrl()."/photo/{$hash}-2.".$Image->getExt();
478                         }
479                 }
480
481                 if ($width > 160 && $height > 160) {
482                         $x = 0;
483                         $y = 0;
484
485                         $min = $Image->getWidth();
486                         if ($min > 160) {
487                                 $x = ($min - 160) / 2;
488                         }
489
490                         if ($Image->getHeight() < $min) {
491                                 $min = $Image->getHeight();
492                                 if ($min > 160) {
493                                         $y = ($min - 160) / 2;
494                                 }
495                         }
496
497                         $min = 160;
498                         $Image->crop(160, $x, $y, $min, $min);
499
500                         $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 3, 0, $defperm);
501                         if ($r) {
502                                 $image["thumb"] = $a->getBaseURL() . "/photo/{$hash}-3." . $Image->getExt();
503                         }
504                 }
505
506                 // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
507                 $image["preview"] = $image["full"];
508
509                 // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
510                 //if (isset($image["thumb"]))
511                 //  $image["preview"] = $image["thumb"];
512
513                 // Unsure, if this should be activated or deactivated
514                 //if (isset($image["small"]))
515                 //  $image["preview"] = $image["small"];
516
517                 if (isset($image["medium"])) {
518                         $image["preview"] = $image["medium"];
519                 }
520
521                 return($image);
522         }
523
524         /**
525          * @brief Update a photo
526          *
527          * @param array         $fields     Contains the fields that are updated
528          * @param array         $conditions Condition array with the key values
529          * @param Image         $img        Image to update. Optional, default null.
530          * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
531          *
532          * @return boolean  Was the update successfull?
533          *
534          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
535          * @see   \Friendica\Database\DBA::update
536          */
537         public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
538         {
539                 if (!is_null($img)) {
540                         // get photo to update
541                         $photos = self::select(["backend-class","backend-ref"], $conditions);
542
543                         foreach($photos as $photo) {
544                                 /** @var IStorage $backend_class */
545                                 $backend_class = (string)$photo["backend-class"];
546                                 if ($backend_class !== "") {
547                                         $fields["backend-ref"] = $backend_class::put($img->asString(), $photo["backend-ref"]);
548                                 } else {
549                                         $fields["data"] = $img->asString();
550                                 }
551                         }
552                         $fields['updated'] = DateTimeFormat::utcNow();
553                 }
554
555                 $fields['edited'] = DateTimeFormat::utcNow();
556
557                 return DBA::update("photo", $fields, $conditions, $old_fields);
558         }
559
560         /**
561          * @param string  $image_url     Remote URL
562          * @param integer $uid           user id
563          * @param integer $cid           contact id
564          * @param boolean $quit_on_error optional, default false
565          * @return array
566          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
567          * @throws \ImagickException
568          */
569         public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
570         {
571                 $thumb = "";
572                 $micro = "";
573
574                 $photo = DBA::selectFirst(
575                         "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
576                 );
577                 if (!empty($photo['resource-id'])) {
578                         $hash = $photo["resource-id"];
579                 } else {
580                         $hash = self::newResource();
581                 }
582
583                 $photo_failure = false;
584
585                 $filename = basename($image_url);
586                 $img_str = Network::fetchUrl($image_url, true);
587
588                 if ($quit_on_error && ($img_str == "")) {
589                         return false;
590                 }
591
592                 $type = Image::guessType($image_url, true);
593                 $Image = new Image($img_str, $type);
594                 if ($Image->isValid()) {
595                         $Image->scaleToSquare(300);
596
597                         $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 4);
598
599                         if ($r === false) {
600                                 $photo_failure = true;
601                         }
602
603                         $Image->scaleDown(80);
604
605                         $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 5);
606
607                         if ($r === false) {
608                                 $photo_failure = true;
609                         }
610
611                         $Image->scaleDown(48);
612
613                         $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 6);
614
615                         if ($r === false) {
616                                 $photo_failure = true;
617                         }
618
619                         $suffix = "?ts=" . time();
620
621                         $image_url = System::baseUrl() . "/photo/" . $hash . "-4." . $Image->getExt() . $suffix;
622                         $thumb = System::baseUrl() . "/photo/" . $hash . "-5." . $Image->getExt() . $suffix;
623                         $micro = System::baseUrl() . "/photo/" . $hash . "-6." . $Image->getExt() . $suffix;
624
625                         // Remove the cached photo
626                         $a = \get_app();
627                         $basepath = $a->getBasePath();
628
629                         if (is_dir($basepath . "/photo")) {
630                                 $filename = $basepath . "/photo/" . $hash . "-4." . $Image->getExt();
631                                 if (file_exists($filename)) {
632                                         unlink($filename);
633                                 }
634                                 $filename = $basepath . "/photo/" . $hash . "-5." . $Image->getExt();
635                                 if (file_exists($filename)) {
636                                         unlink($filename);
637                                 }
638                                 $filename = $basepath . "/photo/" . $hash . "-6." . $Image->getExt();
639                                 if (file_exists($filename)) {
640                                         unlink($filename);
641                                 }
642                         }
643                 } else {
644                         $photo_failure = true;
645                 }
646
647                 if ($photo_failure && $quit_on_error) {
648                         return false;
649                 }
650
651                 if ($photo_failure) {
652                         $image_url = System::baseUrl() . "/images/person-300.jpg";
653                         $thumb = System::baseUrl() . "/images/person-80.jpg";
654                         $micro = System::baseUrl() . "/images/person-48.jpg";
655                 }
656
657                 return [$image_url, $thumb, $micro];
658         }
659
660         /**
661          * @param array $exifCoord coordinate
662          * @param string $hemi      hemi
663          * @return float
664          */
665         public static function getGps($exifCoord, $hemi)
666         {
667                 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
668                 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
669                 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
670
671                 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
672
673                 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
674         }
675
676         /**
677          * @param string $coordPart coordPart
678          * @return float
679          */
680         private static function gps2Num($coordPart)
681         {
682                 $parts = explode("/", $coordPart);
683
684                 if (count($parts) <= 0) {
685                         return 0;
686                 }
687
688                 if (count($parts) == 1) {
689                         return $parts[0];
690                 }
691
692                 return floatval($parts[0]) / floatval($parts[1]);
693         }
694
695         /**
696          * @brief Fetch the photo albums that are available for a viewer
697          *
698          * The query in this function is cost intensive, so it is cached.
699          *
700          * @param int  $uid    User id of the photos
701          * @param bool $update Update the cache
702          *
703          * @return array Returns array of the photo albums
704          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
705          */
706         public static function getAlbums($uid, $update = false)
707         {
708                 $sql_extra = Security::getPermissionsSQLByUserId($uid);
709
710                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
711                 $albums = Cache::get($key);
712                 if (is_null($albums) || $update) {
713                         if (!Config::get("system", "no_count", false)) {
714                                 /// @todo This query needs to be renewed. It is really slow
715                                 // At this time we just store the data in the cache
716                                 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
717                                         FROM `photo`
718                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra
719                                         GROUP BY `album` ORDER BY `created` DESC",
720                                         intval($uid),
721                                         DBA::escape("Contact Photos"),
722                                         DBA::escape(L10n::t("Contact Photos"))
723                                 );
724                         } else {
725                                 // This query doesn't do the count and is much faster
726                                 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
727                                         FROM `photo` USE INDEX (`uid_album_scale_created`)
728                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra",
729                                         intval($uid),
730                                         DBA::escape("Contact Photos"),
731                                         DBA::escape(L10n::t("Contact Photos"))
732                                 );
733                         }
734                         Cache::set($key, $albums, Cache::DAY);
735                 }
736                 return $albums;
737         }
738
739         /**
740          * @param int $uid User id of the photos
741          * @return void
742          * @throws \Exception
743          */
744         public static function clearAlbumCache($uid)
745         {
746                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
747                 Cache::set($key, null, Cache::DAY);
748         }
749
750         /**
751          * Generate a unique photo ID.
752          *
753          * @return string
754          * @throws \Exception
755          */
756         public static function newResource()
757         {
758                 return System::createGUID(32, false);
759         }
760 }