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