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