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