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