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