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