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