]> git.mxchange.org Git - friendica.git/blob - mod/photos.php
Merge pull request #7067 from MrPetovan/task/remove-app-error
[friendica.git] / mod / photos.php
1 <?php
2 /**
3  * @file mod/photos.php
4  */
5
6 use Friendica\App;
7 use Friendica\Content\Feature;
8 use Friendica\Content\Nav;
9 use Friendica\Content\Pager;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Core\ACL;
12 use Friendica\Core\Config;
13 use Friendica\Core\Hook;
14 use Friendica\Core\L10n;
15 use Friendica\Core\Logger;
16 use Friendica\Core\Renderer;
17 use Friendica\Core\System;
18 use Friendica\Database\DBA;
19 use Friendica\Model\Contact;
20 use Friendica\Model\Group;
21 use Friendica\Model\Item;
22 use Friendica\Model\Photo;
23 use Friendica\Model\Profile;
24 use Friendica\Model\User;
25 use Friendica\Network\Probe;
26 use Friendica\Object\Image;
27 use Friendica\Protocol\DFRN;
28 use Friendica\Util\Crypto;
29 use Friendica\Util\DateTimeFormat;
30 use Friendica\Util\Map;
31 use Friendica\Util\Security;
32 use Friendica\Util\Temporal;
33 use Friendica\Util\Strings;
34 use Friendica\Util\XML;
35
36 function photos_init(App $a) {
37
38         if ($a->argc > 1) {
39                 DFRN::autoRedir($a, $a->argv[1]);
40         }
41
42         if (Config::get('system', 'block_public') && !local_user() && !remote_user()) {
43                 return;
44         }
45
46         Nav::setSelected('home');
47
48         if ($a->argc > 1) {
49                 $nick = $a->argv[1];
50                 $user = DBA::selectFirst('user', [], ['nickname' => $nick, 'blocked' => false]);
51
52                 if (!DBA::isResult($user)) {
53                         return;
54                 }
55
56                 $a->data['user'] = $user;
57                 $a->profile_uid = $user['uid'];
58                 $is_owner = (local_user() && (local_user() == $a->profile_uid));
59
60                 $profile = Profile::getByNickname($nick, $a->profile_uid);
61
62                 $account_type = Contact::getAccountType($profile);
63
64                 $tpl = Renderer::getMarkupTemplate("vcard-widget.tpl");
65
66                 $vcard_widget = Renderer::replaceMacros($tpl, [
67                         '$name' => $profile['name'],
68                         '$photo' => $profile['photo'],
69                         '$addr' => defaults($profile, 'addr', ''),
70                         '$account_type' => $account_type,
71                         '$pdesc' => defaults($profile, 'pdesc', ''),
72                 ]);
73
74                 $albums = Photo::getAlbums($a->data['user']['uid']);
75
76                 $albums_visible = ((intval($a->data['user']['hidewall']) && !local_user() && !remote_user()) ? false : true);
77
78                 // add various encodings to the array so we can just loop through and pick them out in a template
79                 $ret = ['success' => false];
80
81                 if ($albums) {
82                         $a->data['albums'] = $albums;
83
84                         if ($albums_visible) {
85                                 $ret['success'] = true;
86                         }
87
88                         $ret['albums'] = [];
89                         foreach ($albums as $k => $album) {
90                                 //hide profile photos to others
91                                 if (!$is_owner && !remote_user() && ($album['album'] == L10n::t('Profile Photos')))
92                                         continue;
93                                 $entry = [
94                                         'text'      => $album['album'],
95                                         'total'     => $album['total'],
96                                         'url'       => 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album['album']),
97                                         'urlencode' => urlencode($album['album']),
98                                         'bin2hex'   => bin2hex($album['album'])
99                                 ];
100                                 $ret['albums'][] = $entry;
101                         }
102                 }
103
104                 if (local_user() && $a->data['user']['uid'] == local_user()) {
105                         $can_post = true;
106                 } else {
107                         $can_post = false;
108                 }
109
110                 if ($ret['success']) {
111                         $photo_albums_widget = Renderer::replaceMacros(Renderer::getMarkupTemplate('photo_albums.tpl'), [
112                                 '$nick'     => $a->data['user']['nickname'],
113                                 '$title'    => L10n::t('Photo Albums'),
114                                 '$recent'   => L10n::t('Recent Photos'),
115                                 '$albums'   => $ret['albums'],
116                                 '$baseurl'  => System::baseUrl(),
117                                 '$upload'   => [L10n::t('Upload New Photos'), 'photos/' . $a->data['user']['nickname'] . '/upload'],
118                                 '$can_post' => $can_post
119                         ]);
120                 }
121
122                 if (empty($a->page['aside'])) {
123                         $a->page['aside'] = '';
124                 }
125
126                 $a->page['aside'] .= $vcard_widget;
127
128                 if (!empty($photo_albums_widget)) {
129                         $a->page['aside'] .= $photo_albums_widget;
130                 }
131
132                 $tpl = Renderer::getMarkupTemplate("photos_head.tpl");
133
134                 $a->page['htmlhead'] .= Renderer::replaceMacros($tpl,[
135                         '$ispublic' => L10n::t('everybody')
136                 ]);
137         }
138
139         return;
140 }
141
142 function photos_post(App $a)
143 {
144         Logger::log('mod-photos: photos_post: begin' , Logger::DEBUG);
145         Logger::log('mod_photos: REQUEST ' . print_r($_REQUEST, true), Logger::DATA);
146         Logger::log('mod_photos: FILES '   . print_r($_FILES, true), Logger::DATA);
147
148         $phototypes = Image::supportedTypes();
149
150         $can_post  = false;
151         $visitor   = 0;
152
153         $page_owner_uid = $a->data['user']['uid'];
154         $community_page = $a->data['user']['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
155
156         if (local_user() && (local_user() == $page_owner_uid)) {
157                 $can_post = true;
158         } elseif ($community_page && remote_user()) {
159                 $contact_id = 0;
160
161                 if (!empty($_SESSION['remote']) && is_array($_SESSION['remote'])) {
162                         foreach ($_SESSION['remote'] as $v) {
163                                 if ($v['uid'] == $page_owner_uid) {
164                                         $contact_id = $v['cid'];
165                                         break;
166                                 }
167                         }
168                 }
169
170                 if ($contact_id > 0) {
171                         if (DBA::exists('contact', ['id' => $contact_id, 'uid' => $page_owner_uid, 'blocked' => false, 'pending' => false])) {
172                                 $can_post = true;
173                                 $visitor = $contact_id;
174                         }
175                 }
176         }
177
178         if (!$can_post) {
179                 notice(L10n::t('Permission denied.') . EOL);
180                 exit();
181         }
182
183         $owner_record = User::getOwnerDataById($page_owner_uid);
184
185         if (!$owner_record) {
186                 notice(L10n::t('Contact information unavailable') . EOL);
187                 Logger::log('photos_post: unable to locate contact record for page owner. uid=' . $page_owner_uid);
188                 exit();
189         }
190
191         if ($a->argc > 3 && $a->argv[2] === 'album') {
192                 $album = hex2bin($a->argv[3]);
193
194                 if ($album === L10n::t('Profile Photos') || $album === 'Contact Photos' || $album === L10n::t('Contact Photos')) {
195                         $a->internalRedirect($_SESSION['photo_return']);
196                         return; // NOTREACHED
197                 }
198
199                 $r = q("SELECT `album` FROM `photo` WHERE `album` = '%s' AND `uid` = %d",
200                         DBA::escape($album),
201                         intval($page_owner_uid)
202                 );
203
204                 if (!DBA::isResult($r)) {
205                         notice(L10n::t('Album not found.') . EOL);
206                         $a->internalRedirect($_SESSION['photo_return']);
207                         return; // NOTREACHED
208                 }
209
210                 // Check if the user has responded to a delete confirmation query
211                 if (!empty($_REQUEST['canceled'])) {
212                         $a->internalRedirect($_SESSION['photo_return']);
213                 }
214
215                 // RENAME photo album
216                 $newalbum = Strings::escapeTags(trim($_POST['albumname']));
217                 if ($newalbum != $album) {
218                         q("UPDATE `photo` SET `album` = '%s' WHERE `album` = '%s' AND `uid` = %d",
219                                 DBA::escape($newalbum),
220                                 DBA::escape($album),
221                                 intval($page_owner_uid)
222                         );
223                         // Update the photo albums cache
224                         Photo::clearAlbumCache($page_owner_uid);
225
226                         $a->internalRedirect('photos/' . $a->user['nickname'] . '/album/' . bin2hex($newalbum));
227                         return; // NOTREACHED
228                 }
229
230                 /*
231                  * DELETE all photos filed in a given album
232                  */
233                 if (!empty($_POST['dropalbum'])) {
234                         $res = [];
235
236                         // get the list of photos we are about to delete
237                         if ($visitor) {
238                                 $r = q("SELECT distinct(`resource-id`) as `rid` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d AND `album` = '%s'",
239                                         intval($visitor),
240                                         intval($page_owner_uid),
241                                         DBA::escape($album)
242                                 );
243                         } else {
244                                 $r = q("SELECT distinct(`resource-id`) as `rid` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
245                                         intval(local_user()),
246                                         DBA::escape($album)
247                                 );
248                         }
249
250                         if (DBA::isResult($r)) {
251                                 foreach ($r as $rr) {
252                                         $res[] = $rr['rid'];
253                                 }
254
255                                 // remove the associated photos
256                                 Photo::delete(['resource-id' => $res, 'uid' => $page_owner_uid]);
257
258                                 // find and delete the corresponding item with all the comments and likes/dislikes
259                                 Item::deleteForUser(['resource-id' => $res, 'uid' => $page_owner_uid], $page_owner_uid);
260
261                                 // Update the photo albums cache
262                                 Photo::clearAlbumCache($page_owner_uid);
263                                 notice(L10n::t('Album successfully deleted'));
264                         } else {
265                                 notice(L10n::t('Album was empty.'));
266                         }
267                 }
268
269                 $a->internalRedirect('photos/' . $a->argv[1]);
270         }
271
272         if ($a->argc > 3 && $a->argv[2] === 'image') {
273                 // Check if the user has responded to a delete confirmation query for a single photo
274                 if (!empty($_POST['canceled'])) {
275                         $a->internalRedirect('photos/' . $a->argv[1] . '/image/' . $a->argv[3]);
276                 }
277
278                 if (!empty($_POST['delete'])) {
279                         // same as above but remove single photo
280                         if ($visitor) {
281                                 $condition = ['contact-id' => $visitor, 'uid' => $page_owner_uid, 'resource-id' => $a->argv[3]];
282
283                         } else {
284                                 $condition = ['uid' => local_user(), 'resource-id' => $a->argv[3]];
285                         }
286
287                         $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
288
289                         if (DBA::isResult($photo)) {
290                                 Photo::delete(['uid' => $page_owner_uid, 'resource-id' => $photo['resource-id']]);
291
292                                 Item::deleteForUser(['resource-id' => $photo['resource-id'], 'uid' => $page_owner_uid], $page_owner_uid);
293
294                                 // Update the photo albums cache
295                                 Photo::clearAlbumCache($page_owner_uid);
296                                 notice('Successfully deleted the photo.');
297                         } else {
298                                 notice('Failed to delete the photo.');
299                                 $a->internalRedirect('photos/' . $a->argv[1] . '/image/' . $a->argv[3]);
300                         }
301
302                         $a->internalRedirect('photos/' . $a->argv[1]);
303                         return; // NOTREACHED
304                 }
305         }
306
307         if ($a->argc > 2 && (!empty($_POST['desc']) || !empty($_POST['newtag']) || isset($_POST['albname']))) {
308                 $desc        = !empty($_POST['desc'])      ? Strings::escapeTags(trim($_POST['desc']))      : '';
309                 $rawtags     = !empty($_POST['newtag'])    ? Strings::escapeTags(trim($_POST['newtag']))    : '';
310                 $item_id     = !empty($_POST['item_id'])   ? intval($_POST['item_id'])                      : 0;
311                 $albname     = !empty($_POST['albname'])   ? Strings::escapeTags(trim($_POST['albname']))   : '';
312                 $origaname   = !empty($_POST['origaname']) ? Strings::escapeTags(trim($_POST['origaname'])) : '';
313
314                 $str_group_allow   = !empty($_POST['group_allow'])   ? perms2str($_POST['group_allow'])   : '';
315                 $str_contact_allow = !empty($_POST['contact_allow']) ? perms2str($_POST['contact_allow']) : '';
316                 $str_group_deny    = !empty($_POST['group_deny'])    ? perms2str($_POST['group_deny'])    : '';
317                 $str_contact_deny  = !empty($_POST['contact_deny'])  ? perms2str($_POST['contact_deny'])  : '';
318
319                 $resource_id = $a->argv[2];
320
321                 if (!strlen($albname)) {
322                         $albname = DateTimeFormat::localNow('Y');
323                 }
324
325                 if (!empty($_POST['rotate']) && (intval($_POST['rotate']) == 1 || intval($_POST['rotate']) == 2)) {
326                         Logger::log('rotate');
327
328                         $photo = Photo::getPhotoForUser($page_owner_uid, $resource_id);
329
330                         if (DBA::isResult($photo)) {
331                                 $image = Photo::getImageForPhoto($photo);
332
333                                 if ($image->isValid()) {
334                                         $rotate_deg = ((intval($_POST['rotate']) == 1) ? 270 : 90);
335                                         $image->rotate($rotate_deg);
336
337                                         $width  = $image->getWidth();
338                                         $height = $image->getHeight();
339
340                                         Photo::update(['height' => $height, 'width' => $width], ['resource-id' => $resource_id, 'uid' => $page_owner_uid, 'scale' => 0], $image);
341
342                                         if ($width > 640 || $height > 640) {
343                                                 $image->scaleDown(640);
344                                                 $width  = $image->getWidth();
345                                                 $height = $image->getHeight();
346
347                                                 Photo::update(['height' => $height, 'width' => $width], ['resource-id' => $resource_id, 'uid' => $page_owner_uid, 'scale' => 1], $image);
348                                         }
349
350                                         if ($width > 320 || $height > 320) {
351                                                 $image->scaleDown(320);
352                                                 $width  = $image->getWidth();
353                                                 $height = $image->getHeight();
354
355                                                 Photo::update(['height' => $height, 'width' => $width], ['resource-id' => $resource_id, 'uid' => $page_owner_uid, 'scale' => 2], $image);
356                                         }
357                                 }
358                         }
359                 }
360
361                 $photos_stmt = DBA::select('photo', [], ['resource-id' => $resource_id, 'uid' => $page_owner_uid], ['order' => ['scale' => true]]);
362
363                 $photos = DBA::toArray($photos_stmt);
364
365                 if (DBA::isResult($photos)) {
366                         $photo = $photos[0];
367                         $ext = $phototypes[$photo['type']];
368                         Photo::update(
369                                 ['desc' => $desc, 'album' => $albname, 'allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow, 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny],
370                                 ['resource-id' => $resource_id, 'uid' => $page_owner_uid]
371                         );
372
373                         // Update the photo albums cache if album name was changed
374                         if ($albname !== $origaname) {
375                                 Photo::clearAlbumCache($page_owner_uid);
376                         }
377                         /* Don't make the item visible if the only change was the album name */
378
379                         $visibility = 0;
380                         if ($photo['desc'] !== $desc || strlen($rawtags)) {
381                                 $visibility = 1;
382                         }
383                 }
384
385                 if (DBA::isResult($photos) && !$item_id) {
386                         // Create item container
387                         $title = '';
388                         $uri = Item::newURI($page_owner_uid);
389
390                         $arr = [];
391                         $arr['guid']          = System::createUUID();
392                         $arr['uid']           = $page_owner_uid;
393                         $arr['uri']           = $uri;
394                         $arr['parent-uri']    = $uri;
395                         $arr['post-type']     = Item::PT_IMAGE;
396                         $arr['wall']          = 1;
397                         $arr['resource-id']   = $photo['resource-id'];
398                         $arr['contact-id']    = $owner_record['id'];
399                         $arr['owner-name']    = $owner_record['name'];
400                         $arr['owner-link']    = $owner_record['url'];
401                         $arr['owner-avatar']  = $owner_record['thumb'];
402                         $arr['author-name']   = $owner_record['name'];
403                         $arr['author-link']   = $owner_record['url'];
404                         $arr['author-avatar'] = $owner_record['thumb'];
405                         $arr['title']         = $title;
406                         $arr['allow_cid']     = $photo['allow_cid'];
407                         $arr['allow_gid']     = $photo['allow_gid'];
408                         $arr['deny_cid']      = $photo['deny_cid'];
409                         $arr['deny_gid']      = $photo['deny_gid'];
410                         $arr['visible']       = $visibility;
411                         $arr['origin']        = 1;
412
413                         $arr['body']          = '[url=' . System::baseUrl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $photo['resource-id'] . ']'
414                                                 . '[img]' . System::baseUrl() . '/photo/' . $photo['resource-id'] . '-' . $photo['scale'] . '.'. $ext . '[/img]'
415                                                 . '[/url]';
416
417                         $item_id = Item::insert($arr);
418                 }
419
420                 if ($item_id) {
421                         $item = Item::selectFirst(['tag', 'inform'], ['id' => $item_id, 'uid' => $page_owner_uid]);
422                 }
423                 if (DBA::isResult($item)) {
424                         $old_tag    = $item['tag'];
425                         $old_inform = $item['inform'];
426                 }
427
428                 if (strlen($rawtags)) {
429                         $str_tags = '';
430                         $inform   = '';
431
432                         // if the new tag doesn't have a namespace specifier (@foo or #foo) give it a hashtag
433                         $x = substr($rawtags, 0, 1);
434                         if ($x !== '@' && $x !== '#') {
435                                 $rawtags = '#' . $rawtags;
436                         }
437
438                         $taginfo = [];
439                         $tags = BBCode::getTags($rawtags);
440
441                         if (count($tags)) {
442                                 foreach ($tags as $tag) {
443                                         if (strpos($tag, '@') === 0) {
444                                                 $profile = '';
445                                                 $contact = null;
446                                                 $name = substr($tag,1);
447
448                                                 if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
449                                                         $newname = $name;
450                                                         $links = @Probe::lrdd($name);
451
452                                                         if (count($links)) {
453                                                                 foreach ($links as $link) {
454                                                                         if ($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page') {
455                                                                                 $profile = $link['@attributes']['href'];
456                                                                         }
457
458                                                                         if ($link['@attributes']['rel'] === 'salmon') {
459                                                                                 $salmon = '$url:' . str_replace(',', '%sc', $link['@attributes']['href']);
460
461                                                                                 if (strlen($inform)) {
462                                                                                         $inform .= ',';
463                                                                                 }
464
465                                                                                 $inform .= $salmon;
466                                                                         }
467                                                                 }
468                                                         }
469
470                                                         $taginfo[] = [$newname, $profile, $salmon];
471                                                 } else {
472                                                         $newname = $name;
473                                                         $tagcid = 0;
474
475                                                         if (strrpos($newname, '+')) {
476                                                                 $tagcid = intval(substr($newname, strrpos($newname, '+') + 1));
477                                                         }
478
479                                                         if ($tagcid) {
480                                                                 $contact = DBA::selectFirst('contact', [], ['id' => $tagcid, 'uid' => $page_owner_uid]);
481                                                         } else {
482                                                                 $newname = str_replace('_',' ',$name);
483
484                                                                 //select someone from this user's contacts by name
485                                                                 $contact = DBA::selectFirst('contact', [], ['name' => $newname, 'uid' => $page_owner_uid]);
486                                                                 if (!DBA::isResult($contact)) {
487                                                                         //select someone by attag or nick and the name passed in
488                                                                         $contact = DBA::selectFirst('contact', [],
489                                                                                 ['(`attag` = ? OR `nick` = ?) AND `uid` = ?', $name, $name, $page_owner_uid],
490                                                                                 ['order' => ['attag' => true]]
491                                                                         );
492                                                                 }
493                                                         }
494
495                                                         if (DBA::isResult($contact)) {
496                                                                 $newname = $contact['name'];
497                                                                 $profile = $contact['url'];
498
499                                                                 $notify = 'cid:' . $contact['id'];
500                                                                 if (strlen($inform)) {
501                                                                         $inform .= ',';
502                                                                 }
503                                                                 $inform .= $notify;
504                                                         }
505                                                 }
506
507                                                 if ($profile) {
508                                                         if (!empty($contact)) {
509                                                                 $taginfo[] = [$newname, $profile, $notify, $contact, '@[url=' . str_replace(',', '%2c', $profile) . ']' . $newname . '[/url]'];
510                                                         } else {
511                                                                 $taginfo[] = [$newname, $profile, $notify, null, $str_tags .= '@[url=' . $profile . ']' . $newname . '[/url]'];
512                                                         }
513
514                                                         if (strlen($str_tags)) {
515                                                                 $str_tags .= ',';
516                                                         }
517
518                                                         $profile = str_replace(',', '%2c', $profile);
519                                                         $str_tags .= '@[url=' . $profile . ']' . $newname . '[/url]';
520                                                 }
521                                         } elseif (strpos($tag, '#') === 0) {
522                                                 $tagname = substr($tag, 1);
523                                                 $str_tags .= '#[url=' . System::baseUrl() . "/search?tag=" . $tagname . ']' . $tagname . '[/url],';
524                                         }
525                                 }
526                         }
527
528                         $newtag = $old_tag;
529                         if (strlen($newtag) && strlen($str_tags)) {
530                                 $newtag .= ',';
531                         }
532                         $newtag .= $str_tags;
533
534                         $newinform = $old_inform;
535                         if (strlen($newinform) && strlen($inform)) {
536                                 $newinform .= ',';
537                         }
538                         $newinform .= $inform;
539
540                         $fields = ['tag' => $newtag, 'inform' => $newinform, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
541                         $condition = ['id' => $item_id];
542                         Item::update($fields, $condition);
543
544                         $best = 0;
545                         foreach ($photos as $scales) {
546                                 if (intval($scales['scale']) == 2) {
547                                         $best = 2;
548                                         break;
549                                 }
550
551                                 if (intval($scales['scale']) == 4) {
552                                         $best = 4;
553                                         break;
554                                 }
555                         }
556
557                         if (count($taginfo)) {
558                                 foreach ($taginfo as $tagged) {
559                                         $uri = Item::newURI($page_owner_uid);
560
561                                         $arr = [];
562                                         $arr['guid']          = System::createUUID();
563                                         $arr['uid']           = $page_owner_uid;
564                                         $arr['uri']           = $uri;
565                                         $arr['parent-uri']    = $uri;
566                                         $arr['wall']          = 1;
567                                         $arr['contact-id']    = $owner_record['id'];
568                                         $arr['owner-name']    = $owner_record['name'];
569                                         $arr['owner-link']    = $owner_record['url'];
570                                         $arr['owner-avatar']  = $owner_record['thumb'];
571                                         $arr['author-name']   = $owner_record['name'];
572                                         $arr['author-link']   = $owner_record['url'];
573                                         $arr['author-avatar'] = $owner_record['thumb'];
574                                         $arr['title']         = '';
575                                         $arr['allow_cid']     = $photo['allow_cid'];
576                                         $arr['allow_gid']     = $photo['allow_gid'];
577                                         $arr['deny_cid']      = $photo['deny_cid'];
578                                         $arr['deny_gid']      = $photo['deny_gid'];
579                                         $arr['visible']       = 1;
580                                         $arr['verb']          = ACTIVITY_TAG;
581                                         $arr['gravity']       = GRAVITY_PARENT;
582                                         $arr['object-type']   = ACTIVITY_OBJ_PERSON;
583                                         $arr['target-type']   = ACTIVITY_OBJ_IMAGE;
584                                         $arr['tag']           = $tagged[4];
585                                         $arr['inform']        = $tagged[2];
586                                         $arr['origin']        = 1;
587                                         $arr['body']          = L10n::t('%1$s was tagged in %2$s by %3$s', '[url=' . $tagged[1] . ']' . $tagged[0] . '[/url]', '[url=' . System::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo['resource-id'] . ']' . L10n::t('a photo') . '[/url]', '[url=' . $owner_record['url'] . ']' . $owner_record['name'] . '[/url]') ;
588                                         $arr['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo['resource-id'] . ']' . '[img]' . System::baseUrl() . "/photo/" . $photo['resource-id'] . '-' . $best . '.' . $ext . '[/img][/url]' . "\n" ;
589
590                                         $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $tagged[0] . '</title><id>' . $tagged[1] . '/' . $tagged[0] . '</id>';
591                                         $arr['object'] .= '<link>' . XML::escape('<link rel="alternate" type="text/html" href="' . $tagged[1] . '" />' . "\n");
592                                         if ($tagged[3]) {
593                                                 $arr['object'] .= XML::escape('<link rel="photo" type="' . $photo['type'] . '" href="' . $tagged[3]['photo'] . '" />' . "\n");
594                                         }
595                                         $arr['object'] .= '</link></object>' . "\n";
596
597                                         $arr['target'] = '<target><type>' . ACTIVITY_OBJ_IMAGE . '</type><title>' . $photo['desc'] . '</title><id>'
598                                                 . System::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo['resource-id'] . '</id>';
599                                         $arr['target'] .= '<link>' . XML::escape('<link rel="alternate" type="text/html" href="' . System::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo['resource-id'] . '" />' . "\n" . '<link rel="preview" type="' . $photo['type'] . '" href="' . System::baseUrl() . "/photo/" . $photo['resource-id'] . '-' . $best . '.' . $ext . '" />') . '</link></target>';
600
601                                         Item::insert($arr);
602                                 }
603                         }
604                 }
605                 $a->internalRedirect($_SESSION['photo_return']);
606                 return; // NOTREACHED
607         }
608
609
610         // default post action - upload a photo
611         Hook::callAll('photo_post_init', $_POST);
612
613         // Determine the album to use
614         $album    = !empty($_REQUEST['album'])    ? Strings::escapeTags(trim($_REQUEST['album']))    : '';
615         $newalbum = !empty($_REQUEST['newalbum']) ? Strings::escapeTags(trim($_REQUEST['newalbum'])) : '';
616
617         Logger::log('mod/photos.php: photos_post(): album= ' . $album . ' newalbum= ' . $newalbum , Logger::DEBUG);
618
619         if (!strlen($album)) {
620                 if (strlen($newalbum)) {
621                         $album = $newalbum;
622                 } else {
623                         $album = DateTimeFormat::localNow('Y');
624                 }
625         }
626
627         /*
628          * We create a wall item for every photo, but we don't want to
629          * overwhelm the data stream with a hundred newly uploaded photos.
630          * So we will make the first photo uploaded to this album in the last several hours
631          * visible by default, the rest will become visible over time when and if
632          * they acquire comments, likes, dislikes, and/or tags
633          */
634
635         $r = Photo::select([], ['`album` = ? AND `uid` = ? AND `created` > UTC_TIMESTAMP() - INTERVAL 3 HOUR', $album, $page_owner_uid]);
636
637         if (!DBA::isResult($r) || ($album == L10n::t('Profile Photos'))) {
638                 $visible = 1;
639         } else {
640                 $visible = 0;
641         }
642
643         if (!empty($_REQUEST['not_visible']) && $_REQUEST['not_visible'] !== 'false') {
644                 $visible = 0;
645         }
646
647         $group_allow   = defaults($_REQUEST, 'group_allow'  , []);
648         $contact_allow = defaults($_REQUEST, 'contact_allow', []);
649         $group_deny    = defaults($_REQUEST, 'group_deny'   , []);
650         $contact_deny  = defaults($_REQUEST, 'contact_deny' , []);
651
652         $str_group_allow   = perms2str(is_array($group_allow)   ? $group_allow   : explode(',', $group_allow));
653         $str_contact_allow = perms2str(is_array($contact_allow) ? $contact_allow : explode(',', $contact_allow));
654         $str_group_deny    = perms2str(is_array($group_deny)    ? $group_deny    : explode(',', $group_deny));
655         $str_contact_deny  = perms2str(is_array($contact_deny)  ? $contact_deny  : explode(',', $contact_deny));
656
657         $ret = ['src' => '', 'filename' => '', 'filesize' => 0, 'type' => ''];
658
659         Hook::callAll('photo_post_file', $ret);
660
661         if (!empty($ret['src']) && !empty($ret['filesize'])) {
662                 $src      = $ret['src'];
663                 $filename = $ret['filename'];
664                 $filesize = $ret['filesize'];
665                 $type     = $ret['type'];
666                 $error    = UPLOAD_ERR_OK;
667         } elseif (!empty($_FILES['userfile'])) {
668                 $src      = $_FILES['userfile']['tmp_name'];
669                 $filename = basename($_FILES['userfile']['name']);
670                 $filesize = intval($_FILES['userfile']['size']);
671                 $type     = $_FILES['userfile']['type'];
672                 $error    = $_FILES['userfile']['error'];
673         } else {
674                 $error    = UPLOAD_ERR_NO_FILE;
675         }
676
677         if ($error !== UPLOAD_ERR_OK) {
678                 switch ($error) {
679                         case UPLOAD_ERR_INI_SIZE:
680                                 notice(L10n::t('Image exceeds size limit of %s', ini_get('upload_max_filesize')) . EOL);
681                                 break;
682                         case UPLOAD_ERR_FORM_SIZE:
683                                 notice(L10n::t('Image exceeds size limit of %s', Strings::formatBytes(defaults($_REQUEST, 'MAX_FILE_SIZE', 0))) . EOL);
684                                 break;
685                         case UPLOAD_ERR_PARTIAL:
686                                 notice(L10n::t('Image upload didn\'t complete, please try again') . EOL);
687                                 break;
688                         case UPLOAD_ERR_NO_FILE:
689                                 notice(L10n::t('Image file is missing') . EOL);
690                                 break;
691                         case UPLOAD_ERR_NO_TMP_DIR:
692                         case UPLOAD_ERR_CANT_WRITE:
693                         case UPLOAD_ERR_EXTENSION:
694                                 notice(L10n::t('Server can\'t accept new file upload at this time, please contact your administrator') . EOL);
695                                 break;
696                 }
697                 @unlink($src);
698                 $foo = 0;
699                 Hook::callAll('photo_post_end', $foo);
700                 return;
701         }
702
703         if ($type == "") {
704                 $type = Image::guessType($filename);
705         }
706
707         Logger::log('photos: upload: received file: ' . $filename . ' as ' . $src . ' ('. $type . ') ' . $filesize . ' bytes', Logger::DEBUG);
708
709         $maximagesize = Config::get('system', 'maximagesize');
710
711         if ($maximagesize && ($filesize > $maximagesize)) {
712                 notice(L10n::t('Image exceeds size limit of %s', Strings::formatBytes($maximagesize)) . EOL);
713                 @unlink($src);
714                 $foo = 0;
715                 Hook::callAll('photo_post_end', $foo);
716                 return;
717         }
718
719         if (!$filesize) {
720                 notice(L10n::t('Image file is empty.') . EOL);
721                 @unlink($src);
722                 $foo = 0;
723                 Hook::callAll('photo_post_end', $foo);
724                 return;
725         }
726
727         Logger::log('mod/photos.php: photos_post(): loading the contents of ' . $src , Logger::DEBUG);
728
729         $imagedata = @file_get_contents($src);
730
731         $image = new Image($imagedata, $type);
732
733         if (!$image->isValid()) {
734                 Logger::log('mod/photos.php: photos_post(): unable to process image' , Logger::DEBUG);
735                 notice(L10n::t('Unable to process image.') . EOL);
736                 @unlink($src);
737                 $foo = 0;
738                 Hook::callAll('photo_post_end',$foo);
739                 exit();
740         }
741
742         $exif = $image->orient($src);
743         @unlink($src);
744
745         $max_length = Config::get('system', 'max_image_length');
746         if (!$max_length) {
747                 $max_length = MAX_IMAGE_LENGTH;
748         }
749         if ($max_length > 0) {
750                 $image->scaleDown($max_length);
751         }
752
753         $width  = $image->getWidth();
754         $height = $image->getHeight();
755
756         $smallest = 0;
757
758         $photo_hash = Photo::newResource();
759
760         $r = Photo::store($image, $page_owner_uid, $visitor, $photo_hash, $filename, $album, 0 , 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
761
762         if (!$r) {
763                 Logger::log('mod/photos.php: photos_post(): image store failed', Logger::DEBUG);
764                 notice(L10n::t('Image upload failed.') . EOL);
765                 exit();
766         }
767
768         if ($width > 640 || $height > 640) {
769                 $image->scaleDown(640);
770                 Photo::store($image, $page_owner_uid, $visitor, $photo_hash, $filename, $album, 1, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
771                 $smallest = 1;
772         }
773
774         if ($width > 320 || $height > 320) {
775                 $image->scaleDown(320);
776                 Photo::store($image, $page_owner_uid, $visitor, $photo_hash, $filename, $album, 2, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
777                 $smallest = 2;
778         }
779
780         $uri = Item::newURI($page_owner_uid);
781
782         // Create item container
783         $lat = $lon = null;
784         if ($exif && $exif['GPS'] && Feature::isEnabled($page_owner_uid, 'photo_location')) {
785                 $lat = Photo::getGps($exif['GPS']['GPSLatitude'], $exif['GPS']['GPSLatitudeRef']);
786                 $lon = Photo::getGps($exif['GPS']['GPSLongitude'], $exif['GPS']['GPSLongitudeRef']);
787         }
788
789         $arr = [];
790         if ($lat && $lon) {
791                 $arr['coord'] = $lat . ' ' . $lon;
792         }
793
794         $arr['guid']          = System::createUUID();
795         $arr['uid']           = $page_owner_uid;
796         $arr['uri']           = $uri;
797         $arr['parent-uri']    = $uri;
798         $arr['type']          = 'photo';
799         $arr['wall']          = 1;
800         $arr['resource-id']   = $photo_hash;
801         $arr['contact-id']    = $owner_record['id'];
802         $arr['owner-name']    = $owner_record['name'];
803         $arr['owner-link']    = $owner_record['url'];
804         $arr['owner-avatar']  = $owner_record['thumb'];
805         $arr['author-name']   = $owner_record['name'];
806         $arr['author-link']   = $owner_record['url'];
807         $arr['author-avatar'] = $owner_record['thumb'];
808         $arr['title']         = '';
809         $arr['allow_cid']     = $str_contact_allow;
810         $arr['allow_gid']     = $str_group_allow;
811         $arr['deny_cid']      = $str_contact_deny;
812         $arr['deny_gid']      = $str_group_deny;
813         $arr['visible']       = $visible;
814         $arr['origin']        = 1;
815
816         $arr['body']          = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo_hash . ']'
817                                 . '[img]' . System::baseUrl() . "/photo/{$photo_hash}-{$smallest}.".$image->getExt() . '[/img]'
818                                 . '[/url]';
819
820         $item_id = Item::insert($arr);
821         // Update the photo albums cache
822         Photo::clearAlbumCache($page_owner_uid);
823
824         Hook::callAll('photo_post_end', $item_id);
825
826         // addon uploaders should call "killme()" [e.g. exit] within the photo_post_end hook
827         // if they do not wish to be redirected
828
829         $a->internalRedirect($_SESSION['photo_return']);
830         // NOTREACHED
831 }
832
833 function photos_content(App $a)
834 {
835         // URLs:
836         // photos/name
837         // photos/name/upload
838         // photos/name/upload/xxxxx (xxxxx is album name)
839         // photos/name/album/xxxxx
840         // photos/name/album/xxxxx/edit
841         // photos/name/album/xxxxx/drop
842         // photos/name/image/xxxxx
843         // photos/name/image/xxxxx/edit
844         // photos/name/image/xxxxx/drop
845
846         if (Config::get('system', 'block_public') && !local_user() && !remote_user()) {
847                 notice(L10n::t('Public access denied.') . EOL);
848                 return;
849         }
850
851         if (empty($a->data['user'])) {
852                 notice(L10n::t('No photos selected') . EOL);
853                 return;
854         }
855
856         $phototypes = Image::supportedTypes();
857
858         $_SESSION['photo_return'] = $a->cmd;
859
860         // Parse arguments
861         $datum = null;
862         if ($a->argc > 3) {
863                 $datatype = $a->argv[2];
864                 $datum = $a->argv[3];
865         } elseif (($a->argc > 2) && ($a->argv[2] === 'upload')) {
866                 $datatype = 'upload';
867         } else {
868                 $datatype = 'summary';
869         }
870
871         if ($a->argc > 4) {
872                 $cmd = $a->argv[4];
873         } else {
874                 $cmd = 'view';
875         }
876
877         // Setup permissions structures
878         $can_post       = false;
879         $visitor        = 0;
880         $contact        = null;
881         $remote_contact = false;
882         $contact_id     = 0;
883         $edit           = '';
884         $drop           = '';
885
886         $owner_uid = $a->data['user']['uid'];
887
888         $community_page = (($a->data['user']['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
889
890         if (local_user() && (local_user() == $owner_uid)) {
891                 $can_post = true;
892         } else {
893                 if ($community_page && remote_user()) {
894                         if (is_array($_SESSION['remote'])) {
895                                 foreach ($_SESSION['remote'] as $v) {
896                                         if ($v['uid'] == $owner_uid) {
897                                                 $contact_id = $v['cid'];
898                                                 break;
899                                         }
900                                 }
901                         }
902
903                         if ($contact_id) {
904                                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id, 'uid' => $owner_uid, 'blocked' => false, 'pending' => false]);
905
906                                 if (DBA::isResult($contact)) {
907                                         $can_post = true;
908                                         $remote_contact = true;
909                                         $visitor = $contact_id;
910                                 }
911                         }
912                 }
913         }
914
915         $groups = [];
916
917         // perhaps they're visiting - but not a community page, so they wouldn't have write access
918         if (remote_user() && !$visitor) {
919                 $contact_id = 0;
920                 if (is_array($_SESSION['remote'])) {
921                         foreach ($_SESSION['remote'] as $v) {
922                                 if ($v['uid'] == $owner_uid) {
923                                         $contact_id = $v['cid'];
924                                         break;
925                                 }
926                         }
927                 }
928
929                 if ($contact_id) {
930                         $groups = Group::getIdsByContactId($contact_id);
931
932                         $contact = DBA::selectFirst('contact', [], ['id' => $contact_id, 'uid' => $owner_uid, 'blocked' => false, 'pending' => false]);
933
934                         $remote_contact = DBA::isResult($contact);
935                 }
936         }
937
938         if (!$remote_contact && local_user()) {
939                 $contact_id = $_SESSION['cid'];
940                 $contact = $a->contact;
941         }
942
943         if ($a->data['user']['hidewall'] && (local_user() != $owner_uid) && !$remote_contact) {
944                 notice(L10n::t('Access to this item is restricted.') . EOL);
945                 return;
946         }
947
948         $sql_extra = Security::getPermissionsSQLByUserId($owner_uid, $remote_contact, $groups);
949
950         $o = "";
951
952         // tabs
953         $is_owner = (local_user() && (local_user() == $owner_uid));
954         $o .= Profile::getTabs($a, $is_owner, $a->data['user']['nickname']);
955
956         // Display upload form
957         if ($datatype === 'upload') {
958                 if (!$can_post) {
959                         notice(L10n::t('Permission denied.'));
960                         return;
961                 }
962
963                 $selname = $datum ? hex2bin($datum) : '';
964
965                 $albumselect = '';
966
967                 $albumselect .= '<option value="" ' . (!$selname ? ' selected="selected" ' : '') . '>&lt;current year&gt;</option>';
968                 if (!empty($a->data['albums'])) {
969                         foreach ($a->data['albums'] as $album) {
970                                 if (($album['album'] === '') || ($album['album'] === 'Contact Photos') || ($album['album'] === L10n::t('Contact Photos'))) {
971                                         continue;
972                                 }
973                                 $selected = (($selname === $album['album']) ? ' selected="selected" ' : '');
974                                 $albumselect .= '<option value="' . $album['album'] . '"' . $selected . '>' . $album['album'] . '</option>';
975                         }
976                 }
977
978                 $uploader = '';
979
980                 $ret = ['post_url' => 'photos/' . $a->data['user']['nickname'],
981                                 'addon_text' => $uploader,
982                                 'default_upload' => true];
983
984                 Hook::callAll('photo_upload_form',$ret);
985
986                 $default_upload_box = Renderer::replaceMacros(Renderer::getMarkupTemplate('photos_default_uploader_box.tpl'), []);
987                 $default_upload_submit = Renderer::replaceMacros(Renderer::getMarkupTemplate('photos_default_uploader_submit.tpl'), [
988                         '$submit' => L10n::t('Submit'),
989                 ]);
990
991                 $usage_message = '';
992
993                 $tpl = Renderer::getMarkupTemplate('photos_upload.tpl');
994
995                 $aclselect_e = ($visitor ? '' : ACL::getFullSelectorHTML($a->user));
996
997                 $o .= Renderer::replaceMacros($tpl,[
998                         '$pagename' => L10n::t('Upload Photos'),
999                         '$sessid' => session_id(),
1000                         '$usage' => $usage_message,
1001                         '$nickname' => $a->data['user']['nickname'],
1002                         '$newalbum' => L10n::t('New album name: '),
1003                         '$existalbumtext' => L10n::t('or select existing album:'),
1004                         '$nosharetext' => L10n::t('Do not show a status post for this upload'),
1005                         '$albumselect' => $albumselect,
1006                         '$permissions' => L10n::t('Permissions'),
1007                         '$aclselect' => $aclselect_e,
1008                         '$lockstate' => is_array($a->user)
1009                                         && (strlen($a->user['allow_cid'])
1010                                                 || strlen($a->user['allow_gid'])
1011                                                 || strlen($a->user['deny_cid'])
1012                                                 || strlen($a->user['deny_gid'])
1013                                         ) ? 'lock' : 'unlock',
1014                         '$alt_uploader' => $ret['addon_text'],
1015                         '$default_upload_box' => ($ret['default_upload'] ? $default_upload_box : ''),
1016                         '$default_upload_submit' => ($ret['default_upload'] ? $default_upload_submit : ''),
1017                         '$uploadurl' => $ret['post_url'],
1018
1019                         // ACL permissions box
1020                         '$group_perms' => L10n::t('Show to Groups'),
1021                         '$contact_perms' => L10n::t('Show to Contacts'),
1022                         '$return_path' => $a->query_string,
1023                 ]);
1024
1025                 return $o;
1026         }
1027
1028         // Display a single photo album
1029         if ($datatype === 'album') {
1030                 $album = hex2bin($datum);
1031
1032                 $total = 0;
1033                 $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s'
1034                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id`",
1035                         intval($owner_uid),
1036                         DBA::escape($album)
1037                 );
1038                 if (DBA::isResult($r)) {
1039                         $total = count($r);
1040                 }
1041
1042                 $pager = new Pager($a->query_string, 20);
1043
1044                 /// @TODO I have seen this many times, maybe generalize it script-wide and encapsulate it?
1045                 $order_field = defaults($_GET, 'order', '');
1046                 if ($order_field === 'posted') {
1047                         $order = 'ASC';
1048                 } else {
1049                         $order = 'DESC';
1050                 }
1051
1052                 $r = q("SELECT `resource-id`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`filename`) AS `filename`,
1053                         ANY_VALUE(`type`) AS `type`, max(`scale`) AS `scale`, ANY_VALUE(`desc`) as `desc`,
1054                         ANY_VALUE(`created`) as `created`
1055                         FROM `photo` WHERE `uid` = %d AND `album` = '%s'
1056                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id` ORDER BY `created` $order LIMIT %d , %d",
1057                         intval($owner_uid),
1058                         DBA::escape($album),
1059                         $pager->getStart(),
1060                         $pager->getItemsPerPage()
1061                 );
1062
1063                 if ($cmd === 'drop') {
1064                         $drop_url = $a->query_string;
1065
1066                         $extra_inputs = [
1067                                 ['name' => 'albumname', 'value' => $_POST['albumname']],
1068                         ];
1069
1070                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
1071                                 '$method' => 'post',
1072                                 '$message' => L10n::t('Do you really want to delete this photo album and all its photos?'),
1073                                 '$extra_inputs' => $extra_inputs,
1074                                 '$confirm' => L10n::t('Delete Album'),
1075                                 '$confirm_url' => $drop_url,
1076                                 '$confirm_name' => 'dropalbum',
1077                                 '$cancel' => L10n::t('Cancel'),
1078                         ]);
1079                 }
1080
1081                 // edit album name
1082                 if ($cmd === 'edit') {
1083                         if (($album !== L10n::t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== L10n::t('Contact Photos'))) {
1084                                 if ($can_post) {
1085                                         $edit_tpl = Renderer::getMarkupTemplate('album_edit.tpl');
1086
1087                                         $album_e = $album;
1088
1089                                         $o .= Renderer::replaceMacros($edit_tpl,[
1090                                                 '$nametext' => L10n::t('New album name: '),
1091                                                 '$nickname' => $a->data['user']['nickname'],
1092                                                 '$album' => $album_e,
1093                                                 '$hexalbum' => bin2hex($album),
1094                                                 '$submit' => L10n::t('Submit'),
1095                                                 '$dropsubmit' => L10n::t('Delete Album')
1096                                         ]);
1097                                 }
1098                         }
1099                 } else {
1100                         if (($album !== L10n::t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== L10n::t('Contact Photos')) && $can_post) {
1101                                 $edit = [L10n::t('Edit Album'), 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '/edit'];
1102                                 $drop = [L10n::t('Drop Album'), 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '/drop'];
1103                         }
1104                 }
1105
1106                 if ($order_field === 'posted') {
1107                         $order =  [L10n::t('Show Newest First'), 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album), 'oldest'];
1108                 } else {
1109                         $order = [L10n::t('Show Oldest First'), 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '?f=&order=posted', 'newest'];
1110                 }
1111
1112                 $photos = [];
1113
1114                 if (DBA::isResult($r)) {
1115                         // "Twist" is only used for the duepunto theme with style "slackr"
1116                         $twist = false;
1117                         foreach ($r as $rr) {
1118                                 $twist = !$twist;
1119
1120                                 $ext = $phototypes[$rr['type']];
1121
1122                                 $imgalt_e = $rr['filename'];
1123                                 $desc_e = $rr['desc'];
1124
1125                                 $photos[] = [
1126                                         'id' => $rr['id'],
1127                                         'twist' => ' ' . ($twist ? 'rotleft' : 'rotright') . rand(2,4),
1128                                         'link' => 'photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id']
1129                                                 . ($order_field === 'posted' ? '?f=&order=posted' : ''),
1130                                         'title' => L10n::t('View Photo'),
1131                                         'src' => 'photo/' . $rr['resource-id'] . '-' . $rr['scale'] . '.' .$ext,
1132                                         'alt' => $imgalt_e,
1133                                         'desc'=> $desc_e,
1134                                         'ext' => $ext,
1135                                         'hash'=> $rr['resource-id'],
1136                                 ];
1137                         }
1138                 }
1139
1140                 $tpl = Renderer::getMarkupTemplate('photo_album.tpl');
1141                 $o .= Renderer::replaceMacros($tpl, [
1142                         '$photos' => $photos,
1143                         '$album' => $album,
1144                         '$can_post' => $can_post,
1145                         '$upload' => [L10n::t('Upload New Photos'), 'photos/' . $a->data['user']['nickname'] . '/upload/' . bin2hex($album)],
1146                         '$order' => $order,
1147                         '$edit' => $edit,
1148                         '$drop' => $drop,
1149                         '$paginate' => $pager->renderFull($total),
1150                 ]);
1151
1152                 return $o;
1153
1154         }
1155
1156         // Display one photo
1157         if ($datatype === 'image') {
1158                 // fetch image, item containing image, then comments
1159                 $ph = q("SELECT * FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'
1160                         $sql_extra ORDER BY `scale` ASC ",
1161                         intval($owner_uid),
1162                         DBA::escape($datum)
1163                 );
1164
1165                 if (!DBA::isResult($ph)) {
1166                         if (DBA::exists('photo', ['resource-id' => $datum, 'uid' => $owner_uid])) {
1167                                 notice(L10n::t('Permission denied. Access to this item may be restricted.'));
1168                         } else {
1169                                 notice(L10n::t('Photo not available') . EOL);
1170                         }
1171                         return;
1172                 }
1173
1174                 if ($cmd === 'drop') {
1175                         $drop_url = $a->query_string;
1176
1177                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
1178                                 '$method' => 'post',
1179                                 '$message' => L10n::t('Do you really want to delete this photo?'),
1180                                 '$extra_inputs' => [],
1181                                 '$confirm' => L10n::t('Delete Photo'),
1182                                 '$confirm_url' => $drop_url,
1183                                 '$confirm_name' => 'delete',
1184                                 '$cancel' => L10n::t('Cancel'),
1185                         ]);
1186                 }
1187
1188                 $prevlink = '';
1189                 $nextlink = '';
1190
1191                 /*
1192                  * @todo This query is totally bad, the whole functionality has to be changed
1193                  * The query leads to a really intense used index.
1194                  * By now we hide it if someone wants to.
1195                  */
1196                 if ($cmd === 'view' && !Config::get('system', 'no_count', false)) {
1197                         $order_field = defaults($_GET, 'order', '');
1198
1199                         if ($order_field === 'posted') {
1200                                 $order = 'ASC';
1201                         } else {
1202                                 $order = 'DESC';
1203                         }
1204
1205                         $prvnxt = q("SELECT `resource-id` FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `scale` = 0
1206                                 $sql_extra ORDER BY `created` $order ",
1207                                 DBA::escape($ph[0]['album']),
1208                                 intval($owner_uid)
1209                         );
1210
1211                         if (DBA::isResult($prvnxt)) {
1212                                 $prv = null;
1213                                 $nxt = null;
1214                                 foreach ($prvnxt as $z => $entry) {
1215                                         if ($entry['resource-id'] == $ph[0]['resource-id']) {
1216                                                 $prv = $z - 1;
1217                                                 $nxt = $z + 1;
1218                                                 if ($prv < 0) {
1219                                                         $prv = count($prvnxt) - 1;
1220                                                 }
1221                                                 if ($nxt >= count($prvnxt)) {
1222                                                         $nxt = 0;
1223                                                 }
1224                                                 break;
1225                                         }
1226                                 }
1227
1228                                 if (!is_null($prv)) {
1229                                         $prevlink = 'photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . ($order_field === 'posted' ? '?f=&order=posted' : '');
1230                                 }
1231                                 if (!is_null($nxt)) {
1232                                         $nextlink = 'photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . ($order_field === 'posted' ? '?f=&order=posted' : '');
1233                                 }
1234
1235                                 $tpl = Renderer::getMarkupTemplate('photo_edit_head.tpl');
1236                                 $a->page['htmlhead'] .= Renderer::replaceMacros($tpl,[
1237                                         '$prevlink' => $prevlink,
1238                                         '$nextlink' => $nextlink
1239                                 ]);
1240
1241                                 if ($prevlink) {
1242                                         $prevlink = [$prevlink, '<div class="icon prev"></div>'];
1243                                 }
1244
1245                                 if ($nextlink) {
1246                                         $nextlink = [$nextlink, '<div class="icon next"></div>'];
1247                                 }
1248                         }
1249                 }
1250
1251                 if (count($ph) == 1) {
1252                         $hires = $lores = $ph[0];
1253                 }
1254
1255                 if (count($ph) > 1) {
1256                         if ($ph[1]['scale'] == 2) {
1257                                 // original is 640 or less, we can display it directly
1258                                 $hires = $lores = $ph[0];
1259                         } else {
1260                                 $hires = $ph[0];
1261                                 $lores = $ph[1];
1262                         }
1263                 }
1264
1265                 $album_link = 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($ph[0]['album']);
1266
1267                 $tools = null;
1268
1269                 if ($can_post && ($ph[0]['uid'] == $owner_uid)) {
1270                         $tools = [];
1271                         if ($cmd === 'edit') {
1272                                 $tools['view'] = ['photos/' . $a->data['user']['nickname'] . '/image/' . $datum, L10n::t('View photo')];
1273                         } else {
1274                                 $tools['edit'] = ['photos/' . $a->data['user']['nickname'] . '/image/' . $datum . '/edit', L10n::t('Edit photo')];
1275                                 $tools['delete'] = ['photos/' . $a->data['user']['nickname'] . '/image/' . $datum . '/drop', L10n::t('Delete photo')];
1276                                 $tools['profile'] = ['profile_photo/use/'.$ph[0]['resource-id'], L10n::t('Use as profile photo')];
1277                         }
1278
1279                         if (
1280                                 $ph[0]['uid'] == local_user()
1281                                 && (strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid']) || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid']))
1282                         ) {
1283                                 $tools['lock'] = L10n::t('Private Photo');
1284                         }
1285                 }
1286
1287                 $photo = [
1288                         'href' => 'photo/' . $hires['resource-id'] . '-' . $hires['scale'] . '.' . $phototypes[$hires['type']],
1289                         'title'=> L10n::t('View Full Size'),
1290                         'src'  => 'photo/' . $lores['resource-id'] . '-' . $lores['scale'] . '.' . $phototypes[$lores['type']] . '?f=&_u=' . DateTimeFormat::utcNow('ymdhis'),
1291                         'height' => $hires['height'],
1292                         'width' => $hires['width'],
1293                         'album' => $hires['album'],
1294                         'filename' => $hires['filename'],
1295                 ];
1296
1297                 // Do we have an item for this photo?
1298
1299                 // FIXME! - replace following code to display the conversation with our normal
1300                 // conversation functions so that it works correctly and tracks changes
1301                 // in the evolving conversation code.
1302                 // The difference is that we won't be displaying the conversation head item
1303                 // as a "post" but displaying instead the photo it is linked to
1304
1305                 /// @todo Rewrite this query. To do so, $sql_extra must be changed
1306                 $linked_items = q("SELECT `id` FROM `item` WHERE `resource-id` = '%s' $sql_extra LIMIT 1",
1307                         DBA::escape($datum)
1308                 );
1309
1310                 $map = null;
1311                 $link_item = [];
1312                 $total = 0;
1313
1314                 if (DBA::isResult($linked_items)) {
1315                         // This is a workaround to not being forced to rewrite the while $sql_extra handling
1316                         $link_item = Item::selectFirst([], ['id' => $linked_items[0]['id']]);
1317
1318                         $condition = ["`parent` = ? AND `parent` != `id`",  $link_item['parent']];
1319                         $total = DBA::count('item', $condition);
1320
1321                         $pager = new Pager($a->query_string);
1322
1323                         $params = ['order' => ['id'], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1324                         $result = Item::selectForUser($link_item['uid'], Item::ITEM_FIELDLIST, $condition, $params);
1325                         $items = Item::inArray($result);
1326
1327                         if (local_user() && (local_user() == $link_item['uid'])) {
1328                                 Item::update(['unseen' => false], ['parent' => $link_item['parent']]);
1329                         }
1330
1331                         if ($link_item['coord']) {
1332                                 $map = Map::byCoordinates($link_item['coord']);
1333                         }
1334                 }
1335
1336                 $tags = null;
1337
1338                 if (count($linked_items) && strlen($link_item['tag'])) {
1339                         $arr = explode(',', $link_item['tag']);
1340                         // parse tags and add links
1341                         $tag_arr = [];
1342                         foreach ($arr as $tag) {
1343                                 $tag_arr[] = [
1344                                         'name' => BBCode::convert($tag),
1345                                         'removeurl' => '/tagrm/'.$link_item['id'] . '/' . bin2hex($tag)
1346                                 ];
1347                         }
1348                         $tags = ['title' => L10n::t('Tags: '), 'tags' => $tag_arr];
1349                         if ($cmd === 'edit') {
1350                                 $tags['removeanyurl'] = 'tagrm/' . $link_item['id'];
1351                                 $tags['removetitle'] = L10n::t('[Select tags to remove]');
1352                         }
1353                 }
1354
1355
1356                 $edit = Null;
1357                 if ($cmd === 'edit' && $can_post) {
1358                         $edit_tpl = Renderer::getMarkupTemplate('photo_edit.tpl');
1359
1360                         $album_e = $ph[0]['album'];
1361                         $caption_e = $ph[0]['desc'];
1362                         $aclselect_e = ACL::getFullSelectorHTML($a->user, false, $ph[0]);
1363
1364                         $edit = Renderer::replaceMacros($edit_tpl, [
1365                                 '$id' => $ph[0]['id'],
1366                                 '$album' => ['albname', L10n::t('New album name'), $album_e,''],
1367                                 '$caption' => ['desc', L10n::t('Caption'), $caption_e, ''],
1368                                 '$tags' => ['newtag', L10n::t('Add a Tag'), "", L10n::t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping')],
1369                                 '$rotate_none' => ['rotate', L10n::t('Do not rotate'),0,'', true],
1370                                 '$rotate_cw' => ['rotate', L10n::t("Rotate CW \x28right\x29"),1,''],
1371                                 '$rotate_ccw' => ['rotate', L10n::t("Rotate CCW \x28left\x29"),2,''],
1372
1373                                 '$nickname' => $a->data['user']['nickname'],
1374                                 '$resource_id' => $ph[0]['resource-id'],
1375                                 '$permissions' => L10n::t('Permissions'),
1376                                 '$aclselect' => $aclselect_e,
1377
1378                                 '$item_id' => defaults($link_item, 'id', 0),
1379                                 '$submit' => L10n::t('Submit'),
1380                                 '$delete' => L10n::t('Delete Photo'),
1381
1382                                 // ACL permissions box
1383                                 '$group_perms' => L10n::t('Show to Groups'),
1384                                 '$contact_perms' => L10n::t('Show to Contacts'),
1385                                 '$return_path' => $a->query_string,
1386                         ]);
1387                 }
1388
1389                 $like = '';
1390                 $dislike = '';
1391                 $likebuttons = '';
1392                 $comments = '';
1393                 $paginate = '';
1394                 $responses = '';
1395
1396                 if (count($linked_items)) {
1397                         $cmnt_tpl = Renderer::getMarkupTemplate('comment_item.tpl');
1398                         $tpl = Renderer::getMarkupTemplate('photo_item.tpl');
1399                         $return_path = $a->cmd;
1400
1401                         if ($cmd === 'view' && ($can_post || Security::canWriteToUserWall($owner_uid))) {
1402                                 $like_tpl = Renderer::getMarkupTemplate('like_noshare.tpl');
1403                                 $likebuttons = Renderer::replaceMacros($like_tpl, [
1404                                         '$id' => $link_item['id'],
1405                                         '$likethis' => L10n::t("I like this \x28toggle\x29"),
1406                                         '$nolike' => L10n::t("I don't like this \x28toggle\x29"),
1407                                         '$wait' => L10n::t('Please wait'),
1408                                         '$return_path' => $a->query_string,
1409                                 ]);
1410                         }
1411
1412                         if (!DBA::isResult($items)) {
1413                                 if (($can_post || Security::canWriteToUserWall($owner_uid))) {
1414                                         $comments .= Renderer::replaceMacros($cmnt_tpl, [
1415                                                 '$return_path' => '',
1416                                                 '$jsreload' => $return_path,
1417                                                 '$id' => $link_item['id'],
1418                                                 '$parent' => $link_item['id'],
1419                                                 '$profile_uid' =>  $owner_uid,
1420                                                 '$mylink' => $contact['url'],
1421                                                 '$mytitle' => L10n::t('This is you'),
1422                                                 '$myphoto' => $contact['thumb'],
1423                                                 '$comment' => L10n::t('Comment'),
1424                                                 '$submit' => L10n::t('Submit'),
1425                                                 '$preview' => L10n::t('Preview'),
1426                                                 '$sourceapp' => L10n::t($a->sourcename),
1427                                                 '$ww' => '',
1428                                                 '$rand_num' => Crypto::randomDigits(12)
1429                                         ]);
1430                                 }
1431                         }
1432
1433                         $conv_responses = [
1434                                 'like' => ['title' => L10n::t('Likes','title')],'dislike' => ['title' => L10n::t('Dislikes','title')],
1435                                 'attendyes' => ['title' => L10n::t('Attending','title')], 'attendno' => ['title' => L10n::t('Not attending','title')], 'attendmaybe' => ['title' => L10n::t('Might attend','title')]
1436                         ];
1437
1438                         // display comments
1439                         if (DBA::isResult($items)) {
1440                                 foreach ($items as $item) {
1441                                         builtin_activity_puller($item, $conv_responses);
1442                                 }
1443
1444                                 if (!empty($conv_responses['like'][$link_item['uri']])) {
1445                                         $like = format_like($conv_responses['like'][$link_item['uri']], $conv_responses['like'][$link_item['uri'] . '-l'], 'like', $link_item['id']);
1446                                 }
1447
1448                                 if (!empty($conv_responses['dislike'][$link_item['uri']])) {
1449                                         $dislike = format_like($conv_responses['dislike'][$link_item['uri']], $conv_responses['dislike'][$link_item['uri'] . '-l'], 'dislike', $link_item['id']);
1450                                 }
1451
1452                                 if (($can_post || Security::canWriteToUserWall($owner_uid))) {
1453                                         $comments .= Renderer::replaceMacros($cmnt_tpl,[
1454                                                 '$return_path' => '',
1455                                                 '$jsreload' => $return_path,
1456                                                 '$id' => $link_item['id'],
1457                                                 '$parent' => $link_item['id'],
1458                                                 '$profile_uid' =>  $owner_uid,
1459                                                 '$mylink' => $contact['url'],
1460                                                 '$mytitle' => L10n::t('This is you'),
1461                                                 '$myphoto' => $contact['thumb'],
1462                                                 '$comment' => L10n::t('Comment'),
1463                                                 '$submit' => L10n::t('Submit'),
1464                                                 '$preview' => L10n::t('Preview'),
1465                                                 '$sourceapp' => L10n::t($a->sourcename),
1466                                                 '$ww' => '',
1467                                                 '$rand_num' => Crypto::randomDigits(12)
1468                                         ]);
1469                                 }
1470
1471                                 foreach ($items as $item) {
1472                                         $comment = '';
1473                                         $template = $tpl;
1474                                         $sparkle = '';
1475
1476                                         if ((activity_match($item['verb'], ACTIVITY_LIKE) || activity_match($item['verb'], ACTIVITY_DISLIKE)) && ($item['id'] != $item['parent'])) {
1477                                                 continue;
1478                                         }
1479
1480                                         $profile_url = Contact::magicLinkbyId($item['author-id']);
1481                                         if (strpos($profile_url, 'redir/') === 0) {
1482                                                 $sparkle = ' sparkle';
1483                                         } else {
1484                                                 $sparkle = '';
1485                                         }
1486
1487                                         $dropping = (($item['contact-id'] == $contact_id) || ($item['uid'] == local_user()));
1488                                         $drop = [
1489                                                 'dropping' => $dropping,
1490                                                 'pagedrop' => false,
1491                                                 'select' => L10n::t('Select'),
1492                                                 'delete' => L10n::t('Delete'),
1493                                         ];
1494
1495                                         $title_e = $item['title'];
1496                                         $body_e = BBCode::convert($item['body']);
1497
1498                                         $comments .= Renderer::replaceMacros($template,[
1499                                                 '$id' => $item['id'],
1500                                                 '$profile_url' => $profile_url,
1501                                                 '$name' => $item['author-name'],
1502                                                 '$thumb' => $item['author-avatar'],
1503                                                 '$sparkle' => $sparkle,
1504                                                 '$title' => $title_e,
1505                                                 '$body' => $body_e,
1506                                                 '$ago' => Temporal::getRelativeDate($item['created']),
1507                                                 '$indent' => (($item['parent'] != $item['item_id']) ? ' comment' : ''),
1508                                                 '$drop' => $drop,
1509                                                 '$comment' => $comment
1510                                         ]);
1511
1512                                         if (($can_post || Security::canWriteToUserWall($owner_uid))) {
1513                                                 $comments .= Renderer::replaceMacros($cmnt_tpl, [
1514                                                         '$return_path' => '',
1515                                                         '$jsreload' => $return_path,
1516                                                         '$id' => $item['item_id'],
1517                                                         '$parent' => $item['parent'],
1518                                                         '$profile_uid' =>  $owner_uid,
1519                                                         '$mylink' => $contact['url'],
1520                                                         '$mytitle' => L10n::t('This is you'),
1521                                                         '$myphoto' => $contact['thumb'],
1522                                                         '$comment' => L10n::t('Comment'),
1523                                                         '$submit' => L10n::t('Submit'),
1524                                                         '$preview' => L10n::t('Preview'),
1525                                                         '$sourceapp' => L10n::t($a->sourcename),
1526                                                         '$ww' => '',
1527                                                         '$rand_num' => Crypto::randomDigits(12)
1528                                                 ]);
1529                                         }
1530                                 }
1531                         }
1532                         $response_verbs = ['like'];
1533                         $response_verbs[] = 'dislike';
1534                         $responses = get_responses($conv_responses, $response_verbs, $link_item);
1535
1536                         $paginate = $pager->renderFull($total);
1537                 }
1538
1539                 $photo_tpl = Renderer::getMarkupTemplate('photo_view.tpl');
1540                 $o .= Renderer::replaceMacros($photo_tpl, [
1541                         '$id' => $ph[0]['id'],
1542                         '$album' => [$album_link, $ph[0]['album']],
1543                         '$tools' => $tools,
1544                         '$photo' => $photo,
1545                         '$prevlink' => $prevlink,
1546                         '$nextlink' => $nextlink,
1547                         '$desc' => $ph[0]['desc'],
1548                         '$tags' => $tags,
1549                         '$edit' => $edit,
1550                         '$map' => $map,
1551                         '$map_text' => L10n::t('Map'),
1552                         '$likebuttons' => $likebuttons,
1553                         '$like' => $like,
1554                         '$dislike' => $dislike,
1555                         'responses' => $responses,
1556                         '$comments' => $comments,
1557                         '$paginate' => $paginate,
1558                 ]);
1559
1560                 $a->page['htmlhead'] .= "\n" . '<meta name="twitter:card" content="summary_large_image" />' . "\n";
1561                 $a->page['htmlhead'] .= '<meta name="twitter:title" content="' . $photo["album"] . '" />' . "\n";
1562                 $a->page['htmlhead'] .= '<meta name="twitter:image" content="' . $photo["href"] . '" />' . "\n";
1563                 $a->page['htmlhead'] .= '<meta name="twitter:image:width" content="' . $photo["width"] . '" />' . "\n";
1564                 $a->page['htmlhead'] .= '<meta name="twitter:image:height" content="' . $photo["height"] . '" />' . "\n";
1565
1566                 return $o;
1567         }
1568
1569         // Default - show recent photos with upload link (if applicable)
1570         //$o = '';
1571         $total = 0;
1572         $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s'
1573                 $sql_extra GROUP BY `resource-id`",
1574                 intval($a->data['user']['uid']),
1575                 DBA::escape('Contact Photos'),
1576                 DBA::escape(L10n::t('Contact Photos'))
1577         );
1578         if (DBA::isResult($r)) {
1579                 $total = count($r);
1580         }
1581
1582         $pager = new Pager($a->query_string, 20);
1583
1584         $r = q("SELECT `resource-id`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`filename`) AS `filename`,
1585                 ANY_VALUE(`type`) AS `type`, ANY_VALUE(`album`) AS `album`, max(`scale`) AS `scale`,
1586                 ANY_VALUE(`created`) AS `created` FROM `photo`
1587                 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s'
1588                 $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d",
1589                 intval($a->data['user']['uid']),
1590                 DBA::escape('Contact Photos'),
1591                 DBA::escape(L10n::t('Contact Photos')),
1592                 $pager->getStart(),
1593                 $pager->getItemsPerPage()
1594         );
1595
1596         $photos = [];
1597         if (DBA::isResult($r)) {
1598                 // "Twist" is only used for the duepunto theme with style "slackr"
1599                 $twist = false;
1600                 foreach ($r as $rr) {
1601                         //hide profile photos to others
1602                         if (!$is_owner && !remote_user() && ($rr['album'] == L10n::t('Profile Photos'))) {
1603                                 continue;
1604                         }
1605
1606                         $twist = !$twist;
1607                         $ext = $phototypes[$rr['type']];
1608
1609                         $alt_e = $rr['filename'];
1610                         $name_e = $rr['album'];
1611
1612                         $photos[] = [
1613                                 'id'    => $rr['id'],
1614                                 'twist' => ' ' . ($twist ? 'rotleft' : 'rotright') . rand(2,4),
1615                                 'link'  => 'photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'],
1616                                 'title' => L10n::t('View Photo'),
1617                                 'src'   => 'photo/' . $rr['resource-id'] . '-' . ((($rr['scale']) == 6) ? 4 : $rr['scale']) . '.' . $ext,
1618                                 'alt'   => $alt_e,
1619                                 'album' => [
1620                                         'link' => 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($rr['album']),
1621                                         'name' => $name_e,
1622                                         'alt'  => L10n::t('View Album'),
1623                                 ],
1624
1625                         ];
1626                 }
1627         }
1628
1629         $tpl = Renderer::getMarkupTemplate('photos_recent.tpl');
1630         $o .= Renderer::replaceMacros($tpl, [
1631                 '$title' => L10n::t('Recent Photos'),
1632                 '$can_post' => $can_post,
1633                 '$upload' => [L10n::t('Upload New Photos'), 'photos/'.$a->data['user']['nickname'].'/upload'],
1634                 '$photos' => $photos,
1635                 '$paginate' => $pager->renderFull($total),
1636         ]);
1637
1638         return $o;
1639 }