]> git.mxchange.org Git - friendica.git/blob - mod/photos.php
Merge pull request #26 from fabrixxm/master
[friendica.git] / mod / photos.php
1 <?php
2 require_once('include/Photo.php');
3 require_once('include/items.php');
4 require_once('include/acl_selectors.php');
5 require_once('include/bbcode.php');
6 require_once('include/security.php');
7
8 function photos_init(&$a) {
9
10
11         if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
12                 return;
13         }
14         $o = '';
15
16         if($a->argc > 1) {
17                 $nick = $a->argv[1];
18                 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' AND `blocked` = 0 LIMIT 1",
19                         dbesc($nick)
20                 );
21
22                 if(! count($r))
23                         return;
24
25                 $a->data['user'] = $r[0];
26
27                 $sql_extra = permissions_sql($a->data['user']['uid']);
28
29                 $albums = q("SELECT distinct(`album`) AS `album` FROM `photo` WHERE `uid` = %d $sql_extra ",
30                         intval($a->data['user']['uid'])
31                 );
32
33                 if(count($albums)) {
34                         $a->data['albums'] = $albums;
35
36                         $o .= '<div class="vcard">';
37                         $o .= '<div class="fn">' . $a->data['user']['username'] . '</div>';
38                         $o .= '<div id="profile-photo-wrapper"><img class="photo" style="width: 175px; height: 175px;" src="' . $a->get_baseurl() . '/photo/profile/' . $a->data['user']['uid'] . '.jpg" alt="' . $a->data['user']['username'] . '" /></div>';
39                         $o .= '</div>';
40                         
41                         $o .= '<div id="side-bar-photos-albums" class="widget">';
42                         $o .= '<h3>' . '<a href="' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '">' . t('Photo Albums') . '</a></h4>';
43                                         
44                         $o .= '<ul>';
45                         foreach($albums as $album) {
46
47                                 // don't show contact photos. We once translated this name, but then you could still access it under
48                                 // a different language setting. Now we store the name in English and check in English (and translated for legacy albums).
49
50                                 if((! strlen($album['album'])) || ($album['album'] === 'Contact Photos') || ($album['album'] === t('Contact Photos')))
51                                         continue;
52                                 $o .= '<li>' . '<a href="photos/' . $a->argv[1] . '/album/' . bin2hex($album['album']) . '" />' . $album['album'] . '</a></li>'; 
53                         }
54                         $o .= '</ul>';
55                 }
56
57                 if(! x($a->page,'aside'))
58                         $a->page['aside'] = '';
59                 $a->page['aside'] .= $o;
60
61
62                 $a->page['htmlhead'] .= "<script> var ispublic = '" . t('everybody') . "';" ;
63
64                 $a->page['htmlhead'] .= <<< EOT
65
66                 $(document).ready(function() {
67
68                         $('#contact_allow, #contact_deny, #group_allow, #group_deny').change(function() {
69                                 var selstr;
70                                 $('#contact_allow option:selected, #contact_deny option:selected, #group_allow option:selected, #group_deny option:selected').each( function() {
71                                         selstr = $(this).text();
72                                         $('#jot-perms-icon').removeClass('unlock').addClass('lock');
73                                         $('#jot-public').hide();
74                                 });
75                                 if(selstr == null) { 
76                                         $('#jot-perms-icon').removeClass('lock').addClass('unlock');
77                                         $('#jot-public').show();
78                                 }
79
80                         }).trigger('change');
81
82                 });
83
84                 </script>
85 EOT;
86         }
87
88         return;
89 }
90
91
92
93 function photos_post(&$a) {
94
95         logger('mod-photos: photos_post(): begin' , 'LOGGER_DEBUG');
96
97
98         logger('mod_photos: REQUEST ' . print_r($_REQUEST,true), LOGGER_DATA);
99         logger('mod_photos: FILES '   . print_r($_FILES,true), LOGGER_DATA);
100
101         $can_post  = false;
102         $visitor   = 0;
103
104         $page_owner_uid = $a->data['user']['uid'];
105         $community_page = (($a->data['user']['page-flags'] == PAGE_COMMUNITY) ? true : false);
106
107         if((local_user()) && (local_user() == $page_owner_uid))
108                 $can_post = true;
109         else {
110                 if($community_page && remote_user()) {
111                         $r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
112                                 intval(remote_user()),
113                                 intval($page_owner_uid)
114                         );
115                         if(count($r)) {
116                                 $can_post = true;
117                                 $visitor = remote_user();
118                         }
119                 }
120         }
121
122         if(! $can_post) {
123                 notice( t('Permission denied.') . EOL );
124                 killme();
125         }
126
127         $r = q("SELECT `contact`.*, `user`.`nickname` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
128                 WHERE `user`.`uid` = %d AND `self` = 1 LIMIT 1",
129                 intval($page_owner_uid)
130         );
131
132         if(! count($r)) {
133                 notice( t('Contact information unavailable') . EOL);
134                 logger('photos_post: unable to locate contact record for page owner. uid=' . $page_owner_uid);
135                 killme();
136         }
137
138         $owner_record = $r[0];  
139
140
141         if(($a->argc > 3) && ($a->argv[2] === 'album')) {
142                 $album = hex2bin($a->argv[3]);
143
144                 if($album === t('Profile Photos') || $album === 'Contact Photos' || $album === t('Contact Photos')) {
145                         goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
146                         return; // NOTREACHED
147                 }
148
149                 $r = q("SELECT count(*) FROM `photo` WHERE `album` = '%s' AND `uid` = %d",
150                         dbesc($album),
151                         intval($page_owner_uid)
152                 );
153                 if(! count($r)) {
154                         notice( t('Album not found.') . EOL);
155                         goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
156                         return; // NOTREACHED
157                 }
158
159                 $newalbum = notags(trim($_POST['albumname']));
160                 if($newalbum != $album) {
161                         q("UPDATE `photo` SET `album` = '%s' WHERE `album` = '%s' AND `uid` = %d",
162                                 dbesc($newalbum),
163                                 dbesc($album),
164                                 intval($page_owner_uid)
165                         );
166                         $newurl = str_replace(bin2hex($album),bin2hex($newalbum),$_SESSION['photo_return']);
167                         goaway($a->get_baseurl() . '/' . $newurl);
168                         return; // NOTREACHED
169                 }
170
171
172                 if($_POST['dropalbum'] == t('Delete Album')) {
173
174                         $res = array();
175
176                         // get the list of photos we are about to delete
177
178                         if($visitor) {
179                                 $r = q("SELECT distinct(`resource-id`) as `rid` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d AND `album` = '%s'",
180                                         intval($visitor),
181                                         intval($page_owner_uid),
182                                         dbesc($album)
183                                 );
184                         }
185                         else {
186                                 $r = q("SELECT distinct(`resource-id`) as `rid` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
187                                         intval(local_user()),
188                                         dbesc($album)
189                                 );
190                         }
191                         if(count($r)) {
192                                 foreach($r as $rr) {
193                                         $res[] = "'" . dbesc($rr['rid']) . "'" ;
194                                 }
195                         }
196                         else {
197                                 goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
198                                 return; // NOTREACHED
199                         }
200
201                         $str_res = implode(',', $res);
202
203                         // remove the associated photos
204
205                         q("DELETE FROM `photo` WHERE `resource-id` IN ( $str_res ) AND `uid` = %d",
206                                 intval($page_owner_uid)
207                         );
208
209                         // find and delete the corresponding item with all the comments and likes/dislikes
210
211                         $r = q("SELECT `parent-uri` FROM `item` WHERE `resource-id` IN ( $str_res ) AND `uid` = %d",
212                                 intval($page_owner_uid)
213                         );
214                         if(count($r)) {
215                                 foreach($r as $rr) {
216                                         q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
217                                                 dbesc(datetime_convert()),
218                                                 dbesc($rr['parent-uri']),
219                                                 intval($page_owner_uid)
220                                         );
221
222                                         $drop_id = intval($rr['id']);
223
224                                         // send the notification upstream/downstream as the case may be
225
226                                         if($rr['visible'])
227                                                 proc_run('php',"include/notifier.php","drop","$drop_id");
228                                 }
229                         }
230                 }
231                 goaway($a->get_baseurl() . '/photos/' . $a->data['user']['nickname']);
232                 return; // NOTREACHED
233         }
234
235         if(($a->argc > 2) && (x($_POST,'delete')) && ($_POST['delete'] == t('Delete Photo'))) {
236
237                 // same as above but remove single photo
238
239                 if($visitor) {
240                         $r = q("SELECT `id`, `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d AND `resource-id` = '%s' LIMIT 1",
241                                 intval($visitor),
242                                 intval($page_owner_uid),
243                                 dbesc($a->argv[2])
244                         );
245                 }
246                 else {
247                         $r = q("SELECT `id`, `resource-id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' LIMIT 1",
248                                 intval(local_user()),
249                                 dbesc($a->argv[2])
250                         );
251                 }
252                 if(count($r)) {
253                         q("DELETE FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
254                                 intval($page_owner_uid),
255                                 dbesc($r[0]['resource-id'])
256                         );
257                         $i = q("SELECT * FROM `item` WHERE `resource-id` = '%s' AND `uid` = %d LIMIT 1",
258                                 dbesc($r[0]['resource-id']),
259                                 intval($page_owner_uid)
260                         );
261                         if(count($i)) {
262                                 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
263                                         dbesc(datetime_convert()),
264                                         dbesc(datetime_convert()),
265                                         dbesc($i[0]['uri']),
266                                         intval($page_owner_uid)
267                                 );
268
269                                 $url = $a->get_baseurl();
270                                 $drop_id = intval($i[0]['id']);
271
272                                 if($i[0]['visible'])
273                                         proc_run('php',"include/notifier.php","drop","$drop_id");
274                         }
275                 }
276
277                 goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
278                 return; // NOTREACHED
279         }
280
281         if(($a->argc > 2) && ((x($_POST,'desc') !== false) || (x($_POST,'newtag') !== false)) || (x($_POST,'albname') !== false)) {
282
283                 $desc        = ((x($_POST,'desc'))    ? notags(trim($_POST['desc']))    : '');
284                 $rawtags     = ((x($_POST,'newtag'))  ? notags(trim($_POST['newtag']))  : '');
285                 $item_id     = ((x($_POST,'item_id')) ? intval($_POST['item_id'])       : 0);
286                 $albname     = ((x($_POST,'albname')) ? notags(trim($_POST['albname'])) : '');
287                 $str_group_allow   = perms2str($_POST['group_allow']);
288                 $str_contact_allow = perms2str($_POST['contact_allow']);
289                 $str_group_deny    = perms2str($_POST['group_deny']);
290                 $str_contact_deny  = perms2str($_POST['contact_deny']);
291
292                 $resource_id = $a->argv[2];
293
294                 if(! strlen($albname))
295                         $albname = datetime_convert('UTC',date_default_timezone_get(),'now', 'Y');
296                 
297
298                 $p = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ORDER BY `scale` DESC",
299                         dbesc($resource_id),
300                         intval($page_owner_uid)
301                 );
302                 if(count($p)) {
303                         $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",
304                                 dbesc($desc),
305                                 dbesc($albname),
306                                 dbesc($str_contact_allow),
307                                 dbesc($str_group_allow),
308                                 dbesc($str_contact_deny),
309                                 dbesc($str_group_deny),
310                                 dbesc($resource_id),
311                                 intval($page_owner_uid)
312                         );
313                 }
314
315                 /* Don't make the item visible if the only change was the album name */
316
317                 $visibility = 0;
318                 if($p[0]['desc'] !== $desc || strlen($rawtags))
319                         $visibility = 1;
320                 
321                 if(! $item_id) {
322
323                         // Create item container
324
325                         $title = '';
326                         $basename = basename($filename);
327                         $uri = item_new_uri($a->get_hostname(),$page_owner_uid);
328
329                         $arr = array();
330
331                         $arr['uid']           = $page_owner_uid;
332                         $arr['uri']           = $uri;
333                         $arr['parent-uri']    = $uri; 
334                         $arr['type']          = 'photo';
335                         $arr['wall']          = 1;
336                         $arr['resource-id']   = $p[0]['resource-id'];
337                         $arr['contact-id']    = $owner_record['id'];
338                         $arr['owner-name']    = $owner_record['name'];
339                         $arr['owner-link']    = $owner_record['url'];
340                         $arr['owner-avatar']  = $owner_record['thumb'];
341                         $arr['author-name']   = $owner_record['name'];
342                         $arr['author-link']   = $owner_record['url'];
343                         $arr['author-avatar'] = $owner_record['thumb'];
344                         $arr['title']         = $title;
345                         $arr['allow_cid']     = $p[0]['allow_cid'];
346                         $arr['allow_gid']     = $p[0]['allow_gid'];
347                         $arr['deny_cid']      = $p[0]['deny_cid'];
348                         $arr['deny_gid']      = $p[0]['deny_gid'];
349                         $arr['last-child']    = 1;
350                         $arr['visible']       = $visibility;
351                         
352                         $arr['body']          = '[url=' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $p[0]['resource-id'] . ']' 
353                                                 . '[img]' . $a->get_baseurl() . '/photo/' . $p[0]['resource-id'] . '-' . $p[0]['scale'] . '.jpg' . '[/img]' 
354                                                 . '[/url]';
355                 
356                         $item_id = item_store($arr);
357
358                 }
359
360                 if($item_id) {
361                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
362                                 intval($item_id),
363                                 intval($page_owner_uid)
364                         );
365                 }
366                 if(count($r)) {
367                         $old_tag    = $r[0]['tag'];
368                         $old_inform = $r[0]['inform'];
369                 }
370
371                 if(strlen($rawtags)) {
372
373                         $str_tags = '';
374                         $inform   = '';
375
376                         // if the new tag doesn't have a namespace specifier (@foo or #foo) give it a hashtag
377
378                         $x = substr($rawtags,0,1);
379                         if($x !== '@' && $x !== '#')
380                                 $rawtags = '#' . $rawtags;
381
382                         $taginfo = array();
383                         $tags = get_tags($rawtags);
384
385                         if(count($tags)) {
386                                 foreach($tags as $tag) {
387                                         if(isset($profile))
388                                                 unset($profile);
389                                         if(strpos($tag,'@') === 0) {
390                                                 $name = substr($tag,1);
391                                                 if((strpos($name,'@')) || (strpos($name,'http://'))) {
392                                                         $newname = $name;
393                                                         $links = @lrdd($name);
394                                                         if(count($links)) {
395                                                                 foreach($links as $link) {
396                                                                         if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
397                                                         $profile = $link['@attributes']['href'];
398                                                                         if($link['@attributes']['rel'] === 'salmon') {
399                                                                                 $salmon = '$url:' . str_replace(',','%sc',$link['@attributes']['href']);
400                                                                                 if(strlen($inform))
401                                                                                         $inform .= ',';
402                                                         $inform .= $salmon;
403                                                                         }
404                                                                 }
405                                                         }
406                                                         $taginfo[] = array($newname,$profile,$salmon);
407                                                 }
408                                                 else {
409                                                         $newname = $name;
410                                                         if(strstr($name,'_') || strstr($name,' ')) {
411                                                                 $newname = str_replace('_',' ',$name);
412                                                                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
413                                                                         dbesc($newname),
414                                                                         intval($page_owner_uid)
415                                                                 );
416                                                         }
417                                                         else {
418                                                                 $r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
419                                                                         dbesc($name),
420                                                                         dbesc($name),
421                                                                         intval($page_owner_uid)
422                                                                 );
423                                                         }
424                                                         if(count($r)) {
425                                                                 $newname = $r[0]['name'];
426                                                                 $profile = $r[0]['url'];
427                                                                 $notify = 'cid:' . $r[0]['id'];
428                                                                 if(strlen($inform))
429                                                                         $inform .= ',';
430                                                                 $inform .= $notify;
431                                                         }
432                                                 }
433                                                 if($profile) {
434                                                         if(substr($notify,0,4) === 'cid:')
435                                                                 $taginfo[] = array($newname,$profile,$notify,$r[0],'@[url=' . str_replace(',','%2c',$profile) . ']' . $newname  . '[/url]');
436                                                         else
437                                                                 $taginfo[] = array($newname,$profile,$notify,null,$str_tags .= '@[url=' . $profile . ']' . $newname     . '[/url]');
438                                                         if(strlen($str_tags))
439                                                                 $str_tags .= ',';
440                                                         $profile = str_replace(',','%2c',$profile);
441                                                         $str_tags .= '@[url=' . $profile . ']' . $newname       . '[/url]';
442                                                 }
443                                         }
444                                 }
445                         }
446
447                         $newtag = $old_tag;
448                         if(strlen($newtag) && strlen($str_tags)) 
449                                 $newtag .= ',';
450                         $newtag .= $str_tags;
451
452                         $newinform = $old_inform;
453                         if(strlen($newinform) && strlen($inform))
454                                 $newinform .= ',';
455                         $newinform .= $inform;
456
457                         $r = q("UPDATE `item` SET `tag` = '%s', `inform` = '%s', `edited` = '%s', `changed` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
458                                 dbesc($newtag),
459                                 dbesc($newinform),
460                                 dbesc(datetime_convert()),
461                                 dbesc(datetime_convert()),
462                                 intval($item_id),
463                                 intval($page_owner_uid)
464                         );
465
466                         $best = 0;
467                         foreach($p as $scales) {
468                                 if(intval($scales['scale']) == 2) {
469                                         $best = 2;
470                                         break;
471                                 }
472                                 if(intval($scales['scale']) == 4) {
473                                         $best = 4;
474                                         break;
475                                 }
476                         }
477
478                         if(count($taginfo)) {
479                                 foreach($taginfo as $tagged) {
480                 
481                                         $uri = item_new_uri($a->get_hostname(),$page_owner_uid);
482
483                                         $arr = array();
484
485                                         $arr['uid']           = $page_owner_uid;
486                                         $arr['uri']           = $uri;
487                                         $arr['parent-uri']    = $uri;
488                                         $arr['type']          = 'activity';
489                                         $arr['wall']          = 1;
490                                         $arr['contact-id']    = $owner_record['id'];
491                                         $arr['owner-name']    = $owner_record['name'];
492                                         $arr['owner-link']    = $owner_record['url'];
493                                         $arr['owner-avatar']  = $owner_record['thumb'];
494                                         $arr['author-name']   = $owner_record['name'];
495                                         $arr['author-link']   = $owner_record['url'];
496                                         $arr['author-avatar'] = $owner_record['thumb'];
497                                         $arr['title']         = '';
498                                         $arr['allow_cid']     = $p[0]['allow_cid'];
499                                         $arr['allow_gid']     = $p[0]['allow_gid'];
500                                         $arr['deny_cid']      = $p[0]['deny_cid'];
501                                         $arr['deny_gid']      = $p[0]['deny_gid'];
502                                         $arr['last-child']    = 1;
503                                         $arr['visible']       = 1;
504                                         $arr['verb']          = ACTIVITY_TAG;
505                                         $arr['object-type']   = ACTIVITY_OBJ_PERSON;
506                                         $arr['target-type']   = ACTIVITY_OBJ_PHOTO;
507                                         $arr['tag']           = $tagged[4];
508                                         $arr['inform']        = $tagged[2];
509
510                                         $arr['body']          = '[url=' . $tagged[1] . ']' . $tagged[0] . '[/url]' . ' ' . t('was tagged in a') . ' ' . '[url=' . $a->get_baseurl() . '/photos/' . $owner_record['nickname'] . '/image/' . $p[0]['resource-id'] . ']' . t('photo') . '[/url]' . ' ' . t('by') . ' ' . '[url=' . $owner_record['url'] . ']' . $owner_record['name'] . '[/url]' ;
511                                         $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 . '.jpg' . '[/img][/url]' . "\n" ;
512
513                                         $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $tagged[0] . '</title><id>' . $tagged[1] . '/' . $tagged[0] . '</id>';
514                                         $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $tagged[1] . '" />' . "\n");
515                                         if($tagged[3])
516                                                 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $tagged[3]['photo'] . '" />' . "\n");
517                                         $arr['object'] .= '</link></object>' . "\n";
518
519                                         $arr['target'] = '<target><type>' . ACTIVITY_OBJ_PHOTO . '</type><title>' . $p[0]['desc'] . '</title><id>'
520                                                 . $a->get_baseurl() . '/photos/' . $owner_record['nickname'] . '/image/' . $p[0]['resource-id'] . '</id>';
521                                         $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="image/jpeg" href="' . $a->get_baseurl() . "/photo/" . $p[0]['resource-id'] . '-' . $best . '.jpg' . '" />') . '</link></target>';
522
523                                         $item_id = item_store($arr);
524                                         if($item_id) {
525                                                 q("UPDATE `item` SET `plink` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
526                                                         dbesc($a->get_baseurl() . '/display/' . $owner_record['nickname'] . '/' . $item_id),
527                                                         intval($page_owner_uid),
528                                                         intval($item_id)
529                                                 );
530
531                                                 proc_run('php',"include/notifier.php","tag","$item_id");
532                                         }
533                                 }
534
535                         }
536
537                 }
538                 goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
539                 return; // NOTREACHED
540         }
541
542
543         /**
544          * default post action - upload a photo
545          */
546
547         call_hooks('photo_post_init', $_POST);
548
549         /**
550          * Determine the album to use
551          */
552
553         $album    = notags(trim($_REQUEST['album']));
554         $newalbum = notags(trim($_REQUEST['newalbum']));
555
556         logger('mod/photos.php: photos_post(): album= ' . $album . ' newalbum= ' . $newalbum , 'LOGGER_DEBUG');
557
558         if(! strlen($album)) {
559                 if(strlen($newalbum))
560                         $album = $newalbum;
561                 else
562                         $album = datetime_convert('UTC',date_default_timezone_get(),'now', 'Y');
563         }
564
565         /**
566          *
567          * We create a wall item for every photo, but we don't want to
568          * overwhelm the data stream with a hundred newly uploaded photos.
569          * So we will make the first photo uploaded to this album in the last several hours
570          * visible by default, the rest will become visible over time when and if
571          * they acquire comments, likes, dislikes, and/or tags 
572          *
573          */
574
575         $r = q("SELECT * FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `created` > UTC_TIMESTAMP() - INTERVAL 3 HOUR ",
576                 dbesc($album),
577                 intval($page_owner_uid)
578         );
579         if((! count($r)) || ($album == t('Profile Photos')))
580                 $visible = 1;
581         else
582                 $visible = 0;
583
584         if(intval($_REQUEST['not_visible']))
585                 $visible = 0;
586
587         $str_group_allow   = perms2str(((is_array($_REQUEST['group_allow']))   ? $_REQUEST['group_allow']   : explode(',',$_REQUEST['group_allow'])));
588         $str_contact_allow = perms2str(((is_array($_REQUEST['contact_allow'])) ? $_REQUEST['contact_allow'] : explode(',',$_REQUEST['contact_allow'])));
589         $str_group_deny    = perms2str(((is_array($_REQUEST['group_deny']))    ? $_REQUEST['group_deny']    : explode(',',$_REQUEST['group_deny'])));
590         $str_contact_deny  = perms2str(((is_array($_REQUEST['contact_deny']))  ? $_REQUEST['contact_deny']  : explode(',',$_REQUEST['contact_deny'])));
591
592         $ret = array('src' => '', 'filename' => '', 'filesize' => 0);
593
594         call_hooks('photo_post_file',$ret);
595
596         if(x($ret,'src') && x($ret,'filesize')) {
597                 $src      = $ret['src'];
598                 $filename = $ret['filename'];
599                 $filesize = $ret['filesize'];
600         }
601         else {
602                 $src        = $_FILES['userfile']['tmp_name'];
603                 $filename   = basename($_FILES['userfile']['name']);
604                 $filesize   = intval($_FILES['userfile']['size']);
605         }
606
607
608         logger('photos: upload: received file: ' . $filename . ' as ' . $src . ' ' . $filesize . ' bytes', LOGGER_DEBUG);
609
610         $maximagesize = get_config('system','maximagesize');
611
612         if(($maximagesize) && ($filesize > $maximagesize)) {
613                 notice( t('Image exceeds size limit of ') . $maximagesize . EOL);
614                 @unlink($src);
615                 $foo = 0;
616                 call_hooks('photo_post_end',$foo);
617                 return;
618         }
619
620         if(! $filesize) {
621                 notice( t('Image file is empty.') . EOL);
622                 @unlink($src);
623                 $foo = 0;
624                 call_hooks('photo_post_end',$foo);
625                 return;
626         }
627
628         logger('mod/photos.php: photos_post(): loading the contents of ' . $src , 'LOGGER_DEBUG');
629
630         $imagedata = @file_get_contents($src);
631         $ph = new Photo($imagedata);
632
633         if(! $ph->is_valid()) {
634                 logger('mod/photos.php: photos_post(): unable to process image' , 'LOGGER_DEBUG');
635                 notice( t('Unable to process image.') . EOL );
636                 @unlink($src);
637                 $foo = 0;
638                 call_hooks('photo_post_end',$foo);
639                 killme();
640         }
641
642         @unlink($src);
643
644         $width  = $ph->getWidth();
645         $height = $ph->getHeight();
646
647         $smallest = 0;
648
649         $photo_hash = photo_new_resource();
650
651         $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);
652
653         if(! $r) {
654                 logger('mod/photos.php: photos_post(): image store failed' , 'LOGGER_DEBUG');
655                 notice( t('Image upload failed.') . EOL );
656                 killme();
657         }
658
659         if($width > 640 || $height > 640) {
660                 $ph->scaleImage(640);
661                 $ph->store($page_owner_uid, $visitor, $photo_hash, $filename, $album, 1, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
662                 $smallest = 1;
663         }
664
665         if($width > 320 || $height > 320) {
666                 $ph->scaleImage(320);
667                 $ph->store($page_owner_uid, $visitor, $photo_hash, $filename, $album, 2, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
668                 $smallest = 2;
669         }
670         
671         $basename = basename($filename);
672         $uri = item_new_uri($a->get_hostname(), $page_owner_uid);
673
674         // Create item container
675
676         $arr = array();
677
678         $arr['uid']           = $page_owner_uid;
679         $arr['uri']           = $uri;
680         $arr['parent-uri']    = $uri;
681         $arr['type']          = 'photo';
682         $arr['wall']          = 1;
683         $arr['resource-id']   = $photo_hash;
684         $arr['contact-id']    = $owner_record['id'];
685         $arr['owner-name']    = $owner_record['name'];
686         $arr['owner-link']    = $owner_record['url'];
687         $arr['owner-avatar']  = $owner_record['thumb'];
688         $arr['author-name']   = $owner_record['name'];
689         $arr['author-link']   = $owner_record['url'];
690         $arr['author-avatar'] = $owner_record['thumb'];
691         $arr['title']         = '';
692         $arr['allow_cid']     = $str_contact_allow;
693         $arr['allow_gid']     = $str_group_allow;
694         $arr['deny_cid']      = $str_contact_deny;
695         $arr['deny_gid']      = $str_group_deny;
696         $arr['last-child']    = 1;
697         $arr['visible']       = $visible;
698         $arr['body']          = '[url=' . $a->get_baseurl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo_hash . ']' 
699                                 . '[img]' . $a->get_baseurl() . "/photo/{$photo_hash}-{$smallest}.jpg" . '[/img]' 
700                                 . '[/url]';
701
702         $item_id = item_store($arr);
703
704         if($item_id) {
705                 q("UPDATE `item` SET `plink` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
706                         dbesc($a->get_baseurl() . '/display/' . $owner_record['nickname'] . '/' . $item_id),
707                         intval($page_owner_uid),
708                         intval($item_id)
709                 );
710         }
711         
712         if($visible) 
713                 proc_run('php', "include/notifier.php", 'wall-new', $item_id);
714
715         call_hooks('photo_post_end',intval($item_id));
716
717         // addon uploaders should call "killme()" [e.g. exit] within the photo_post_end hook
718         // if they do not wish to be redirected
719
720         goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
721         // NOTREACHED
722 }
723
724
725
726 function photos_content(&$a) {
727
728         // URLs:
729         // photos/name
730         // photos/name/upload
731         // photos/name/album/xxxxx
732         // photos/name/album/xxxxx/edit
733         // photos/name/image/xxxxx
734         // photos/name/image/xxxxx/edit
735
736
737         if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
738                 notice( t('Public access denied.') . EOL);
739                 return;
740         }
741
742
743         require_once('include/bbcode.php');
744         require_once('include/security.php');
745         require_once('include/conversation.php');
746
747         if(! x($a->data,'user')) {
748                 notice( t('No photos selected') . EOL );
749                 return;
750         }
751
752         $_SESSION['photo_return'] = $a->cmd;
753
754         //
755         // Parse arguments 
756         //
757
758         if($a->argc > 3) {
759                 $datatype = $a->argv[2];
760                 $datum = $a->argv[3];
761         }
762         elseif(($a->argc > 2) && ($a->argv[2] === 'upload'))
763                 $datatype = 'upload';
764         else
765                 $datatype = 'summary';
766
767         if($a->argc > 4)
768                 $cmd = $a->argv[4];
769         else
770                 $cmd = 'view';
771
772         //
773         // Setup permissions structures
774         //
775
776         $can_post       = false;
777         $visitor        = 0;
778         $contact        = null;
779         $remote_contact = false;
780
781         $owner_uid = $a->data['user']['uid'];
782
783         $community_page = (($a->data['user']['page-flags'] == PAGE_COMMUNITY) ? true : false);
784
785         if((local_user()) && (local_user() == $owner_uid))
786                 $can_post = true;
787         else {
788                 if($community_page && remote_user()) {
789                         $r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
790                                 intval(remote_user()),
791                                 intval($owner_uid)
792                         );
793                         if(count($r)) {
794                                 $can_post = true;
795                                 $contact  = $r[0];
796                                 $remote_contact = true;
797                                 $visitor = remote_user();
798                         }
799                 }
800         }
801
802         // perhaps they're visiting - but not a community page, so they wouldn't have write access
803
804         if(remote_user() && (! $visitor)) {
805                 $contact_id = $_SESSION['visitor_id'];
806                 $groups = init_groups_visitor($contact_id);
807                 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
808                         intval(remote_user()),
809                         intval($owner_uid)
810                 );
811                 if(count($r)) {
812                         $contact = $r[0];
813                         $remote_contact = true;
814                 }
815         }
816
817         if(! $remote_contact) {
818                 if(local_user()) {
819                         $contact_id = $_SESSION['cid'];
820                         $contact = $a->contact;
821                 }
822         }
823
824         if($a->data['user']['hidewall'] && (local_user() != $owner_uid) && (! $remote_contact)) {
825                 notice( t('Access to this item is restricted.') . EOL);
826                 return;
827         }
828
829         $sql_extra = permissions_sql($owner_uid,$remote_contact,$groups);
830
831         $o = "";
832
833         // tabs
834         $_is_owner = (local_user() && (local_user() == $owner_uid));
835         $o .= profile_tabs($a,$_is_owner);      
836
837         //
838         // dispatch request
839         //
840
841
842         if($datatype === 'upload') {
843                 if(! ($can_post)) {
844                         notice( t('Permission denied.'));
845                         return;
846                 }
847                 $albumselect = '<select id="photos-upload-album-select" name="album" size="4">';
848
849                 $albumselect .= '<option value="" selected="selected" >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
850                 if(count($a->data['albums'])) {
851                         foreach($a->data['albums'] as $album) {
852                                 if(($album['album'] === '') || ($album['album'] === 'Contact Photos') || ($album['album'] === t('Contact Photos')))
853                                         continue;
854                                 $albumselect .= '<option value="' . $album['album'] . '">' . $album['album'] . '</option>';
855                         }
856                 }
857
858                 $celeb = ((($a->user['page-flags'] == PAGE_SOAPBOX) || ($a->user['page-flags'] == PAGE_COMMUNITY)) ? true : false);
859
860                 $albumselect .= '</select>';
861
862                 $uploader = '';
863
864                 $ret = array('post_url' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'],
865                                 'addon_text' => $uploader,
866                                 'default_upload' => true);
867
868
869                 call_hooks('photo_upload_form',$ret);
870
871                 $default_upload = '<input type="file" name="userfile" />        <div class="photos-upload-submit-wrapper" >
872                 <input type="submit" name="submit" value="' . t('Submit') . '" id="photos-upload-submit" /> </div>';
873
874
875  
876
877                 $tpl = get_markup_template('photos_upload.tpl');
878                 $o .= replace_macros($tpl,array(
879                         '$pagename' => t('Upload Photos'),
880                         '$sessid' => session_id(),
881                         '$nickname' => $a->data['user']['nickname'],
882                         '$newalbum' => t('New album name: '),
883                         '$existalbumtext' => t('or existing album name: '),
884                         '$nosharetext' => t('Do not show a status post for this upload'),
885                         '$albumselect' => template_escape($albumselect),
886                         '$permissions' => t('Permissions'),
887                         '$aclselect' => (($visitor) ? '' : template_escape(populate_acl($a->user, $celeb))),
888                         '$uploader' => $ret['addon_text'],
889                         '$default' => (($ret['default_upload']) ? $default_upload : ''),
890                         '$uploadurl' => $ret['post_url']
891
892                 ));
893
894                 return $o; 
895         }
896
897         if($datatype === 'album') {
898
899                 $album = hex2bin($datum);
900
901                 $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s' 
902                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id`",
903                         intval($owner_uid),
904                         dbesc($album)
905                 );
906                 if(count($r)) {
907                         $a->set_pager_total(count($r));
908                         $a->set_pager_itemspage(20);
909                 }
910
911                 $r = q("SELECT `resource-id`, `id`, `filename`, max(`scale`) AS `scale`, `desc` FROM `photo` WHERE `uid` = %d AND `album` = '%s' 
912                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d",
913                         intval($owner_uid),
914                         dbesc($album),
915                         intval($a->pager['start']),
916                         intval($a->pager['itemspage'])
917                 );
918
919                 $o .= '<h3>' . $album . '</h3>';
920                 
921                 if($cmd === 'edit') {           
922                         if(($album !== t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== t('Contact Photos'))) {
923                                 if($can_post) {
924                                         $edit_tpl = get_markup_template('album_edit.tpl');
925                                         $o .= replace_macros($edit_tpl,array(
926                                                 '$nametext' => t('New album name: '),
927                                                 '$nickname' => $a->data['user']['nickname'],
928                                                 '$album' => template_escape($album),
929                                                 '$hexalbum' => bin2hex($album),
930                                                 '$submit' => t('Submit'),
931                                                 '$dropsubmit' => t('Delete Album')
932                                         ));
933                                 }
934                         }
935                 }
936                 else {
937                         if(($album !== t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== t('Contact Photos'))) {
938                                 if($can_post) {
939                                         $o .= '<div id="album-edit-link"><a href="'. $a->get_baseurl() . '/photos/' 
940                                                 . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '/edit' . '">' 
941                                                 . t('Edit Album') . '</a></div>';
942                                 }
943                         }
944                 }
945                 $tpl = get_markup_template('photo_album.tpl');
946                 if(count($r))
947                         foreach($r as $rr) {
948                                 $o .= replace_macros($tpl,array(
949                                         '$id' => $rr['id'],
950                                         '$photolink' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'],
951                                         '$phototitle' => t('View Photo'),
952                                         '$imgsrc' => $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . $rr['scale'] . '.jpg',
953                                         '$imgalt' => template_escape($rr['filename']),
954                                         '$desc'=> template_escape($rr['desc'])
955                                 ));
956
957                 }
958                 $o .= '<div id="photo-album-end"></div>';
959                 $o .= paginate($a);
960
961                 return $o;
962
963         }       
964
965
966         if($datatype === 'image') {
967
968
969
970                 //$o = '';
971                 // fetch image, item containing image, then comments
972
973                 $ph = q("SELECT * FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' 
974                         $sql_extra ORDER BY `scale` ASC ",
975                         intval($owner_uid),
976                         dbesc($datum)
977                 );
978
979                 if(! count($ph)) {
980                         $ph = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' 
981                                 LIMIT 1",
982                                 intval($owner_uid),
983                                 dbesc($datum)
984                         );
985                         if(count($ph)) 
986                                 notice( t('Permission denied. Access to this item may be restricted.'));
987                         else
988                                 notice( t('Photo not available') . EOL );
989                         return;
990                 }
991
992                 $prevlink = '';
993                 $nextlink = '';
994
995                 $prvnxt = q("SELECT `resource-id` FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `scale` = 0 
996                         $sql_extra ORDER BY `created` DESC ",
997                         dbesc($ph[0]['album']),
998                         intval($owner_uid)
999                 ); 
1000
1001                 if(count($prvnxt)) {
1002                         for($z = 0; $z < count($prvnxt); $z++) {
1003                                 if($prvnxt[$z]['resource-id'] == $ph[0]['resource-id']) {
1004                                         $prv = $z - 1;
1005                                         $nxt = $z + 1;
1006                                         if($prv < 0)
1007                                                 $prv = count($prvnxt) - 1;
1008                                         if($nxt >= count($prvnxt))
1009                                                 $nxt = 0;
1010                                         break;
1011                                 }
1012                         }
1013                         $edit_suffix = ((($cmd === 'edit') && ($can_post)) ? '/edit' : '');
1014                         $prevlink = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . $edit_suffix;
1015                         $nextlink = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . $edit_suffix;
1016                 }
1017
1018
1019                 if(count($ph) == 1)
1020                         $hires = $lores = $ph[0];
1021                 if(count($ph) > 1) {
1022                         if($ph[1]['scale'] == 2) {
1023                                 // original is 640 or less, we can display it directly
1024                                 $hires = $lores = $ph[0];
1025                         }
1026                         else {
1027                         $hires = $ph[0];
1028                         $lores = $ph[1];
1029                         }
1030                 }
1031
1032                 $album_link = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($ph[0]['album']);
1033                 $tools = Null;
1034                 $lock = Null;
1035  
1036                 if($can_post && ($ph[0]['uid'] == $owner_uid)) {
1037                         $tools = array(
1038                                 'edit'  => array($a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $datum . (($cmd === 'edit') ? '' : '/edit'), (($cmd === 'edit') ? t('View photo') : t('Edit photo'))),
1039                                 'profile'=>array($a->get_baseurl() . '/profile_photo/use/'.$ph[0]['resource-id'], t('Use as profile photo')),
1040                         );
1041
1042                         // lock
1043                         $lock = ( ( ($ph[0]['uid'] == local_user()) && (strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid']) 
1044                                         || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid'])) ) 
1045                                         ? t('Private Message')
1046                                         : Null);
1047                         
1048                         
1049                 }
1050
1051                 if($prevlink)
1052                         $prevlink = array($prevlink, '<div class="icon prev"></div>') ;
1053
1054                 $photo = array(
1055                         'href' => $a->get_baseurl() . '/photo/' . $hires['resource-id'] . '-' . $hires['scale'] . '.jpg',
1056                         'title'=> t('View Full Size'),
1057                         'src'  => $a->get_baseurl() . '/photo/' . $lores['resource-id'] . '-' . $lores['scale'] . '.jpg'
1058                 );
1059
1060                 if($nextlink)
1061                         $nextlink = array($nextlink, '<div class="icon next"></div>');
1062
1063
1064                 // Do we have an item for this photo?
1065
1066                 $linked_items = q("SELECT * FROM `item` WHERE `resource-id` = '%s' $sql_extra LIMIT 1",
1067                         dbesc($datum)
1068                 );
1069                 if(count($linked_items)) {
1070                         $link_item = $linked_items[0];
1071                         $r = q("SELECT COUNT(*) AS `total`
1072                                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1073                                 WHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0
1074                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1075                                 AND `item`.`uid` = %d 
1076                                 $sql_extra ",
1077                                 dbesc($link_item['uri']),
1078                                 dbesc($link_item['uri']),
1079                                 intval($link_item['uid'])
1080
1081                         );
1082
1083                         if(count($r))
1084                                 $a->set_pager_total($r[0]['total']);
1085
1086
1087                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
1088                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`network`, 
1089                                 `contact`.`rel`, `contact`.`thumb`, `contact`.`self`, 
1090                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1091                                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1092                                 WHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0
1093                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1094                                 AND `item`.`uid` = %d
1095                                 $sql_extra
1096                                 ORDER BY `parent` DESC, `id` ASC LIMIT %d ,%d ",
1097                                 dbesc($link_item['uri']),
1098                                 dbesc($link_item['uri']),
1099                                 intval($link_item['uid']),
1100                                 intval($a->pager['start']),
1101                                 intval($a->pager['itemspage'])
1102
1103                         );
1104                 
1105                         if((local_user()) && (local_user() == $link_item['uid'])) {
1106                                 q("UPDATE `item` SET `unseen` = 0 WHERE `parent` = %d and `uid` = %d",
1107                                         intval($link_item['parent']),
1108                                         intval(local_user())
1109                                 );
1110                         }
1111                 }
1112
1113                 $tags=Null;
1114
1115                 if(count($linked_items) && strlen($link_item['tag'])) {
1116                         $arr = explode(',',$link_item['tag']);
1117                         // parse tags and add links
1118                         $tag_str = '';
1119                         foreach($arr as $t) {
1120                                 if(strlen($tag_str))
1121                                         $tag_str .= ', ';
1122                                 $tag_str .= bbcode($t);
1123                         } 
1124                         $tags = array(t('Tags: '), $tag_str);
1125                         if($cmd === 'edit') {
1126                                 $tags[] = $a->get_baseurl() . '/tagrm/' . $link_item['id'];
1127                                 $tags[] = t('[Remove any tag]');
1128                         }
1129                 }
1130
1131
1132                 $edit = Null;
1133                 if(($cmd === 'edit') && ($can_post)) {
1134                         $edit_tpl = get_markup_template('photo_edit.tpl');
1135                         $edit = replace_macros($edit_tpl, array(
1136                                 '$id' => $ph[0]['id'],
1137                                 '$album' => template_escape($ph[0]['album']),
1138                                 '$newalbum' => t('New album name'), 
1139                                 '$nickname' => $a->data['user']['nickname'],
1140                                 '$resource_id' => $ph[0]['resource-id'],
1141                                 '$capt_label' => t('Caption'),
1142                                 '$caption' => template_escape($ph[0]['desc']),
1143                                 '$tag_label' => t('Add a Tag'),
1144                                 '$tags' => $link_item['tag'],
1145                                 '$permissions' => t('Permissions'),
1146                                 '$aclselect' => template_escape(populate_acl($ph[0])),
1147                                 '$help_tags' => t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping'),
1148                                 '$item_id' => ((count($linked_items)) ? $link_item['id'] : 0),
1149                                 '$submit' => t('Submit'),
1150                                 '$delete' => t('Delete Photo')
1151                         ));
1152                 }
1153
1154                 if(count($linked_items)) {
1155
1156                         $cmnt_tpl = get_markup_template('comment_item.tpl');
1157                         $tpl = get_markup_template('photo_item.tpl');
1158                         $return_url = $a->cmd;
1159
1160                         $like_tpl = get_markup_template('like_noshare.tpl');
1161
1162                         $likebuttons = '';
1163
1164                         if($can_post || can_write_wall($a,$owner_uid)) {
1165                                 $likebuttons = replace_macros($like_tpl,array(
1166                                         '$id' => $link_item['id'],
1167                                         '$likethis' => t("I like this \x28toggle\x29"),
1168                                         '$nolike' => t("I don't like this \x28toggle\x29"),
1169                                         '$share' => t('Share'),
1170                                         '$wait' => t('Please wait')
1171                                 ));
1172                         }
1173
1174                         $comments = '';
1175                         if(! count($r)) {
1176                                 if($can_post || can_write_wall($a,$owner_uid)) {
1177                                         if($link_item['last-child']) {
1178                                                 $comments .= replace_macros($cmnt_tpl,array(
1179                                                         '$return_path' => '', 
1180                                                         '$jsreload' => $return_url,
1181                                                         '$type' => 'wall-comment',
1182                                                         '$id' => $link_item['id'],
1183                                                         '$parent' => $link_item['id'],
1184                                                         '$profile_uid' =>  $owner_uid,
1185                                                         '$mylink' => $contact['url'],
1186                                                         '$mytitle' => t('This is you'),
1187                                                         '$myphoto' => $contact['thumb'],
1188                                                         '$comment' => t('Comment'),
1189                                                         '$submit' => t('Submit'),
1190                                                         '$ww' => ''
1191                                                 ));
1192                                         }
1193                                 }
1194                         }
1195
1196                         $alike = array();
1197                         $dlike = array();
1198                         
1199                         $like = '';
1200                         $dislike = '';
1201
1202                         // display comments
1203                         if(count($r)) {
1204
1205                                 foreach($r as $item) {
1206                                         like_puller($a,$item,$alike,'like');
1207                                         like_puller($a,$item,$dlike,'dislike');
1208                                 }
1209
1210                                 $like    = ((isset($alike[$link_item['id']])) ? format_like($alike[$link_item['id']],$alike[$link_item['id'] . '-l'],'like',$link_item['id']) : '');
1211                                 $dislike = ((isset($dlike[$link_item['id']])) ? format_like($dlike[$link_item['id']],$dlike[$link_item['id'] . '-l'],'dislike',$link_item['id']) : '');
1212
1213
1214
1215                                 if($can_post || can_write_wall($a,$owner_uid)) {
1216                                         if($link_item['last-child']) {
1217                                                 $comments .= replace_macros($cmnt_tpl,array(
1218                                                         '$return_path' => '',
1219                                                         '$jsreload' => $return_url,
1220                                                         '$type' => 'wall-comment',
1221                                                         '$id' => $link_item['id'],
1222                                                         '$parent' => $link_item['id'],
1223                                                         '$profile_uid' =>  $owner_uid,
1224                                                         '$mylink' => $contact['url'],
1225                                                         '$mytitle' => t('This is you'),
1226                                                         '$myphoto' => $contact['thumb'],
1227                                                         '$comment' => t('Comment'),
1228                                                         '$submit' => t('Submit'),
1229                                                         '$ww' => ''
1230                                                 ));
1231                                         }
1232                                 }
1233
1234
1235                                 foreach($r as $item) {
1236                                         $comment = '';
1237                                         $template = $tpl;
1238                                         $sparkle = '';
1239
1240                                         if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE))) && ($item['id'] != $item['parent']))
1241                                                 continue;
1242
1243                                         $redirect_url = $a->get_baseurl() . '/redir/' . $item['cid'] ;
1244                         
1245                                         if($can_post || can_write_wall($a,$owner_uid)) {
1246
1247                                                 if($item['last-child']) {
1248                                                         $comments .= replace_macros($cmnt_tpl,array(
1249                                                                 '$return_path' => '',
1250                                                                 '$jsreload' => $return_url,
1251                                                                 '$type' => 'wall-comment',
1252                                                                 '$id' => $item['item_id'],
1253                                                                 '$parent' => $item['parent'],
1254                                                                 '$profile_uid' =>  $owner_uid,
1255                                                                 '$mylink' => $contact['url'],
1256                                                                 '$mytitle' => t('This is you'),
1257                                                                 '$myphoto' => $contact['thumb'],
1258                                                                 '$comment' => t('Comment'),
1259                                                                 '$submit' => t('Submit'),
1260                                                                 '$ww' => ''
1261                                                         ));
1262                                                 }
1263                                         }
1264
1265
1266                                         if(local_user() && ($item['contact-uid'] == local_user()) 
1267                                                 && ($item['network'] == 'dfrn') && (! $item['self'] )) {
1268                                                 $profile_url = $redirect_url;
1269                                                 $sparkle = ' sparkle';
1270                                         }
1271                                         else {
1272                                                 $profile_url = $item['url'];
1273                                                 $sparkle = '';
1274                                         }
1275  
1276                                         $diff_author = (($item['url'] !== $item['author-link']) ? true : false);
1277
1278                                         $profile_name   = (((strlen($item['author-name']))   && $diff_author) ? $item['author-name']   : $item['name']);
1279                                         $profile_avatar = (((strlen($item['author-avatar'])) && $diff_author) ? $item['author-avatar'] : $item['thumb']);
1280
1281                                         $profile_link = $profile_url;
1282
1283                                         $drop = '';
1284
1285                                         if(($item['contact-id'] == remote_user()) || ($item['uid'] == local_user()))
1286                                                 $drop = replace_macros(get_markup_template('photo_drop.tpl'), array('$id' => $item['id'], '$delete' => t('Delete')));
1287
1288
1289                                         $comments .= replace_macros($template,array(
1290                                                 '$id' => $item['item_id'],
1291                                                 '$profile_url' => $profile_link,
1292                                                 '$name' => template_escape($profile_name),
1293                                                 '$thumb' => $profile_avatar,
1294                                                 '$sparkle' => $sparkle,
1295                                                 '$title' => template_escape($item['title']),
1296                                                 '$body' => template_escape(bbcode($item['body'])),
1297                                                 '$ago' => relative_date($item['created']),
1298                                                 '$indent' => (($item['parent'] != $item['item_id']) ? ' comment' : ''),
1299                                                 '$drop' => $drop,
1300                                                 '$comment' => $comment
1301                                         ));
1302                                 }
1303                         }
1304
1305                         $paginate = paginate($a);
1306                 }
1307                 
1308                 $photo_tpl = get_markup_template('photo_view.tpl');
1309                 $o .= replace_macros($photo_tpl, array(
1310                         '$id' => $ph[0]['id'],
1311                         '$album' => array($album_link,template_escape($ph[0]['album'])),
1312                         '$tools' => $tools,
1313                         '$lock' => $lock,
1314                         '$photo' => $photo,
1315                         '$prevlink' => $prevlink,
1316                         '$nextlink' => $nextlink,
1317                         '$desc' => $ph[0]['desc'],
1318                         '$tags' => template_escape($tags),
1319                         '$edit' => $edit,       
1320                         '$likebuttons' => $likebuttons,
1321                         '$like' => template_escape($like),
1322                         '$dislike' => template_escape($dislike),
1323                         '$comments' => $comments,
1324                         '$paginate' => $paginate,
1325                 ));
1326                 
1327                 return $o;
1328         }
1329
1330         // Default - show recent photos with upload link (if applicable)
1331         //$o = '';
1332
1333         $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' 
1334                 $sql_extra GROUP BY `resource-id`",
1335                 intval($a->data['user']['uid']),
1336                 dbesc('Contact Photos'),
1337                 dbesc( t('Contact Photos'))
1338         );
1339         if(count($r)) {
1340                 $a->set_pager_total(count($r));
1341                 $a->set_pager_itemspage(20);
1342         }
1343
1344         $r = q("SELECT `resource-id`, `id`, `filename`, `album`, max(`scale`) AS `scale` FROM `photo`
1345                 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s'  
1346                 $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d",
1347                 intval($a->data['user']['uid']),
1348                 dbesc('Contact Photos'),
1349                 dbesc( t('Contact Photos')),
1350                 intval($a->pager['start']),
1351                 intval($a->pager['itemspage'])
1352         );
1353
1354         $o .= '<h3>' . t('Recent Photos') . '</h3>';
1355
1356         if($can_post) {
1357                 $o .= '<div id="photo-top-links"><a id="photo-top-upload-link" href="'. $a->get_baseurl() . '/photos/' 
1358                         . $a->data['user']['nickname'] . '/upload' . '">' . t('Upload New Photos') . '</a></div>';
1359         }
1360
1361         $tpl = get_markup_template('photo_top.tpl');
1362         if(count($r)) {
1363                 foreach($r as $rr) {
1364                         $o .= replace_macros($tpl,array(
1365                                 '$id'         => $rr['id'],
1366                                 '$photolink'  => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'],
1367                                 '$phototitle' => t('View Photo'),
1368                                 '$imgsrc'     => $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . ((($rr['scale']) == 6) ? 4 : $rr['scale']) . '.jpg',
1369                                 '$albumlink'  => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($rr['album']),
1370                                 '$albumname'  => template_escape($rr['album']),
1371                                 '$albumalt'   => t('View Album'),
1372                                 '$imgalt'     => template_escape($rr['filename'])
1373                         ));
1374
1375                 }
1376                 $o .= '<div id="photo-top-end"></div>';
1377         }
1378         $o .= paginate($a);
1379         return $o;
1380 }
1381