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