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