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