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