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