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