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