]> git.mxchange.org Git - friendica.git/blob - mod/photos.php
Merge branch 'pull'
[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                         $arr['origin']        = 1;
352                         
353                         $arr['body']          = '[url=' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $p[0]['resource-id'] . ']' 
354                                                 . '[img]' . $a->get_baseurl() . '/photo/' . $p[0]['resource-id'] . '-' . $p[0]['scale'] . '.jpg' . '[/img]' 
355                                                 . '[/url]';
356                 
357                         $item_id = item_store($arr);
358
359                 }
360
361                 if($item_id) {
362                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
363                                 intval($item_id),
364                                 intval($page_owner_uid)
365                         );
366                 }
367                 if(count($r)) {
368                         $old_tag    = $r[0]['tag'];
369                         $old_inform = $r[0]['inform'];
370                 }
371
372                 if(strlen($rawtags)) {
373
374                         $str_tags = '';
375                         $inform   = '';
376
377                         // if the new tag doesn't have a namespace specifier (@foo or #foo) give it a hashtag
378
379                         $x = substr($rawtags,0,1);
380                         if($x !== '@' && $x !== '#')
381                                 $rawtags = '#' . $rawtags;
382
383                         $taginfo = array();
384                         $tags = get_tags($rawtags);
385
386                         if(count($tags)) {
387                                 foreach($tags as $tag) {
388                                         if(isset($profile))
389                                                 unset($profile);
390                                         if(strpos($tag,'@') === 0) {
391                                                 $name = substr($tag,1);
392                                                 if((strpos($name,'@')) || (strpos($name,'http://'))) {
393                                                         $newname = $name;
394                                                         $links = @lrdd($name);
395                                                         if(count($links)) {
396                                                                 foreach($links as $link) {
397                                                                         if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
398                                                         $profile = $link['@attributes']['href'];
399                                                                         if($link['@attributes']['rel'] === 'salmon') {
400                                                                                 $salmon = '$url:' . str_replace(',','%sc',$link['@attributes']['href']);
401                                                                                 if(strlen($inform))
402                                                                                         $inform .= ',';
403                                                         $inform .= $salmon;
404                                                                         }
405                                                                 }
406                                                         }
407                                                         $taginfo[] = array($newname,$profile,$salmon);
408                                                 }
409                                                 else {
410                                                         $newname = $name;
411                                                         if(strstr($name,'_') || strstr($name,' ')) {
412                                                                 $newname = str_replace('_',' ',$name);
413                                                                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
414                                                                         dbesc($newname),
415                                                                         intval($page_owner_uid)
416                                                                 );
417                                                         }
418                                                         else {
419                                                                 $r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
420                                                                         dbesc($name),
421                                                                         dbesc($name),
422                                                                         intval($page_owner_uid)
423                                                                 );
424                                                         }
425                                                         if(count($r)) {
426                                                                 $newname = $r[0]['name'];
427                                                                 $profile = $r[0]['url'];
428                                                                 $notify = 'cid:' . $r[0]['id'];
429                                                                 if(strlen($inform))
430                                                                         $inform .= ',';
431                                                                 $inform .= $notify;
432                                                         }
433                                                 }
434                                                 if($profile) {
435                                                         if(substr($notify,0,4) === 'cid:')
436                                                                 $taginfo[] = array($newname,$profile,$notify,$r[0],'@[url=' . str_replace(',','%2c',$profile) . ']' . $newname  . '[/url]');
437                                                         else
438                                                                 $taginfo[] = array($newname,$profile,$notify,null,$str_tags .= '@[url=' . $profile . ']' . $newname     . '[/url]');
439                                                         if(strlen($str_tags))
440                                                                 $str_tags .= ',';
441                                                         $profile = str_replace(',','%2c',$profile);
442                                                         $str_tags .= '@[url=' . $profile . ']' . $newname       . '[/url]';
443                                                 }
444                                         }
445                                 }
446                         }
447
448                         $newtag = $old_tag;
449                         if(strlen($newtag) && strlen($str_tags)) 
450                                 $newtag .= ',';
451                         $newtag .= $str_tags;
452
453                         $newinform = $old_inform;
454                         if(strlen($newinform) && strlen($inform))
455                                 $newinform .= ',';
456                         $newinform .= $inform;
457
458                         $r = q("UPDATE `item` SET `tag` = '%s', `inform` = '%s', `edited` = '%s', `changed` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
459                                 dbesc($newtag),
460                                 dbesc($newinform),
461                                 dbesc(datetime_convert()),
462                                 dbesc(datetime_convert()),
463                                 intval($item_id),
464                                 intval($page_owner_uid)
465                         );
466
467                         $best = 0;
468                         foreach($p as $scales) {
469                                 if(intval($scales['scale']) == 2) {
470                                         $best = 2;
471                                         break;
472                                 }
473                                 if(intval($scales['scale']) == 4) {
474                                         $best = 4;
475                                         break;
476                                 }
477                         }
478
479                         if(count($taginfo)) {
480                                 foreach($taginfo as $tagged) {
481                 
482                                         $uri = item_new_uri($a->get_hostname(),$page_owner_uid);
483
484                                         $arr = array();
485
486                                         $arr['uid']           = $page_owner_uid;
487                                         $arr['uri']           = $uri;
488                                         $arr['parent-uri']    = $uri;
489                                         $arr['type']          = 'activity';
490                                         $arr['wall']          = 1;
491                                         $arr['contact-id']    = $owner_record['id'];
492                                         $arr['owner-name']    = $owner_record['name'];
493                                         $arr['owner-link']    = $owner_record['url'];
494                                         $arr['owner-avatar']  = $owner_record['thumb'];
495                                         $arr['author-name']   = $owner_record['name'];
496                                         $arr['author-link']   = $owner_record['url'];
497                                         $arr['author-avatar'] = $owner_record['thumb'];
498                                         $arr['title']         = '';
499                                         $arr['allow_cid']     = $p[0]['allow_cid'];
500                                         $arr['allow_gid']     = $p[0]['allow_gid'];
501                                         $arr['deny_cid']      = $p[0]['deny_cid'];
502                                         $arr['deny_gid']      = $p[0]['deny_gid'];
503                                         $arr['last-child']    = 1;
504                                         $arr['visible']       = 1;
505                                         $arr['verb']          = ACTIVITY_TAG;
506                                         $arr['object-type']   = ACTIVITY_OBJ_PERSON;
507                                         $arr['target-type']   = ACTIVITY_OBJ_PHOTO;
508                                         $arr['tag']           = $tagged[4];
509                                         $arr['inform']        = $tagged[2];
510                                         $arr['origin']        = 1;
511                                         $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]' ;
512                                         $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" ;
513
514                                         $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $tagged[0] . '</title><id>' . $tagged[1] . '/' . $tagged[0] . '</id>';
515                                         $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $tagged[1] . '" />' . "\n");
516                                         if($tagged[3])
517                                                 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $tagged[3]['photo'] . '" />' . "\n");
518                                         $arr['object'] .= '</link></object>' . "\n";
519
520                                         $arr['target'] = '<target><type>' . ACTIVITY_OBJ_PHOTO . '</type><title>' . $p[0]['desc'] . '</title><id>'
521                                                 . $a->get_baseurl() . '/photos/' . $owner_record['nickname'] . '/image/' . $p[0]['resource-id'] . '</id>';
522                                         $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>';
523
524                                         $item_id = item_store($arr);
525                                         if($item_id) {
526                                                 q("UPDATE `item` SET `plink` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
527                                                         dbesc($a->get_baseurl() . '/display/' . $owner_record['nickname'] . '/' . $item_id),
528                                                         intval($page_owner_uid),
529                                                         intval($item_id)
530                                                 );
531
532                                                 proc_run('php',"include/notifier.php","tag","$item_id");
533                                         }
534                                 }
535
536                         }
537
538                 }
539                 goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
540                 return; // NOTREACHED
541         }
542
543
544         /**
545          * default post action - upload a photo
546          */
547
548         call_hooks('photo_post_init', $_POST);
549
550         /**
551          * Determine the album to use
552          */
553
554         $album    = notags(trim($_REQUEST['album']));
555         $newalbum = notags(trim($_REQUEST['newalbum']));
556
557         logger('mod/photos.php: photos_post(): album= ' . $album . ' newalbum= ' . $newalbum , 'LOGGER_DEBUG');
558
559         if(! strlen($album)) {
560                 if(strlen($newalbum))
561                         $album = $newalbum;
562                 else
563                         $album = datetime_convert('UTC',date_default_timezone_get(),'now', 'Y');
564         }
565
566         /**
567          *
568          * We create a wall item for every photo, but we don't want to
569          * overwhelm the data stream with a hundred newly uploaded photos.
570          * So we will make the first photo uploaded to this album in the last several hours
571          * visible by default, the rest will become visible over time when and if
572          * they acquire comments, likes, dislikes, and/or tags 
573          *
574          */
575
576         $r = q("SELECT * FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `created` > UTC_TIMESTAMP() - INTERVAL 3 HOUR ",
577                 dbesc($album),
578                 intval($page_owner_uid)
579         );
580         if((! count($r)) || ($album == t('Profile Photos')))
581                 $visible = 1;
582         else
583                 $visible = 0;
584
585         if(intval($_REQUEST['not_visible']))
586                 $visible = 0;
587
588         $str_group_allow   = perms2str(((is_array($_REQUEST['group_allow']))   ? $_REQUEST['group_allow']   : explode(',',$_REQUEST['group_allow'])));
589         $str_contact_allow = perms2str(((is_array($_REQUEST['contact_allow'])) ? $_REQUEST['contact_allow'] : explode(',',$_REQUEST['contact_allow'])));
590         $str_group_deny    = perms2str(((is_array($_REQUEST['group_deny']))    ? $_REQUEST['group_deny']    : explode(',',$_REQUEST['group_deny'])));
591         $str_contact_deny  = perms2str(((is_array($_REQUEST['contact_deny']))  ? $_REQUEST['contact_deny']  : explode(',',$_REQUEST['contact_deny'])));
592
593         $ret = array('src' => '', 'filename' => '', 'filesize' => 0);
594
595         call_hooks('photo_post_file',$ret);
596
597         if(x($ret,'src') && x($ret,'filesize')) {
598                 $src      = $ret['src'];
599                 $filename = $ret['filename'];
600                 $filesize = $ret['filesize'];
601         }
602         else {
603                 $src        = $_FILES['userfile']['tmp_name'];
604                 $filename   = basename($_FILES['userfile']['name']);
605                 $filesize   = intval($_FILES['userfile']['size']);
606         }
607
608
609         logger('photos: upload: received file: ' . $filename . ' as ' . $src . ' ' . $filesize . ' bytes', LOGGER_DEBUG);
610
611         $maximagesize = get_config('system','maximagesize');
612
613         if(($maximagesize) && ($filesize > $maximagesize)) {
614                 notice( t('Image exceeds size limit of ') . $maximagesize . EOL);
615                 @unlink($src);
616                 $foo = 0;
617                 call_hooks('photo_post_end',$foo);
618                 return;
619         }
620
621         if(! $filesize) {
622                 notice( t('Image file is empty.') . EOL);
623                 @unlink($src);
624                 $foo = 0;
625                 call_hooks('photo_post_end',$foo);
626                 return;
627         }
628
629         logger('mod/photos.php: photos_post(): loading the contents of ' . $src , 'LOGGER_DEBUG');
630
631         $imagedata = @file_get_contents($src);
632         $ph = new Photo($imagedata);
633
634         if(! $ph->is_valid()) {
635                 logger('mod/photos.php: photos_post(): unable to process image' , 'LOGGER_DEBUG');
636                 notice( t('Unable to process image.') . EOL );
637                 @unlink($src);
638                 $foo = 0;
639                 call_hooks('photo_post_end',$foo);
640                 killme();
641         }
642
643         @unlink($src);
644
645         $width  = $ph->getWidth();
646         $height = $ph->getHeight();
647
648         $smallest = 0;
649
650         $photo_hash = photo_new_resource();
651
652         $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);
653
654         if(! $r) {
655                 logger('mod/photos.php: photos_post(): image store failed' , 'LOGGER_DEBUG');
656                 notice( t('Image upload failed.') . EOL );
657                 killme();
658         }
659
660         if($width > 640 || $height > 640) {
661                 $ph->scaleImage(640);
662                 $ph->store($page_owner_uid, $visitor, $photo_hash, $filename, $album, 1, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
663                 $smallest = 1;
664         }
665
666         if($width > 320 || $height > 320) {
667                 $ph->scaleImage(320);
668                 $ph->store($page_owner_uid, $visitor, $photo_hash, $filename, $album, 2, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
669                 $smallest = 2;
670         }
671         
672         $basename = basename($filename);
673         $uri = item_new_uri($a->get_hostname(), $page_owner_uid);
674
675         // Create item container
676
677         $arr = array();
678
679         $arr['uid']           = $page_owner_uid;
680         $arr['uri']           = $uri;
681         $arr['parent-uri']    = $uri;
682         $arr['type']          = 'photo';
683         $arr['wall']          = 1;
684         $arr['resource-id']   = $photo_hash;
685         $arr['contact-id']    = $owner_record['id'];
686         $arr['owner-name']    = $owner_record['name'];
687         $arr['owner-link']    = $owner_record['url'];
688         $arr['owner-avatar']  = $owner_record['thumb'];
689         $arr['author-name']   = $owner_record['name'];
690         $arr['author-link']   = $owner_record['url'];
691         $arr['author-avatar'] = $owner_record['thumb'];
692         $arr['title']         = '';
693         $arr['allow_cid']     = $str_contact_allow;
694         $arr['allow_gid']     = $str_group_allow;
695         $arr['deny_cid']      = $str_contact_deny;
696         $arr['deny_gid']      = $str_group_deny;
697         $arr['last-child']    = 1;
698         $arr['visible']       = $visible;
699         $arr['origin']        = 1;
700
701         $arr['body']          = '[url=' . $a->get_baseurl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo_hash . ']' 
702                                 . '[img]' . $a->get_baseurl() . "/photo/{$photo_hash}-{$smallest}.jpg" . '[/img]' 
703                                 . '[/url]';
704
705         $item_id = item_store($arr);
706
707         if($item_id) {
708                 q("UPDATE `item` SET `plink` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
709                         dbesc($a->get_baseurl() . '/display/' . $owner_record['nickname'] . '/' . $item_id),
710                         intval($page_owner_uid),
711                         intval($item_id)
712                 );
713         }
714         
715         if($visible) 
716                 proc_run('php', "include/notifier.php", 'wall-new', $item_id);
717
718         call_hooks('photo_post_end',intval($item_id));
719
720         // addon uploaders should call "killme()" [e.g. exit] within the photo_post_end hook
721         // if they do not wish to be redirected
722
723         goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
724         // NOTREACHED
725 }
726
727
728
729 function photos_content(&$a) {
730
731         // URLs:
732         // photos/name
733         // photos/name/upload
734         // photos/name/album/xxxxx
735         // photos/name/album/xxxxx/edit
736         // photos/name/image/xxxxx
737         // photos/name/image/xxxxx/edit
738
739
740         if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
741                 notice( t('Public access denied.') . EOL);
742                 return;
743         }
744
745
746         require_once('include/bbcode.php');
747         require_once('include/security.php');
748         require_once('include/conversation.php');
749
750         if(! x($a->data,'user')) {
751                 notice( t('No photos selected') . EOL );
752                 return;
753         }
754
755         $_SESSION['photo_return'] = $a->cmd;
756
757         //
758         // Parse arguments 
759         //
760
761         if($a->argc > 3) {
762                 $datatype = $a->argv[2];
763                 $datum = $a->argv[3];
764         }
765         elseif(($a->argc > 2) && ($a->argv[2] === 'upload'))
766                 $datatype = 'upload';
767         else
768                 $datatype = 'summary';
769
770         if($a->argc > 4)
771                 $cmd = $a->argv[4];
772         else
773                 $cmd = 'view';
774
775         //
776         // Setup permissions structures
777         //
778
779         $can_post       = false;
780         $visitor        = 0;
781         $contact        = null;
782         $remote_contact = false;
783
784         $owner_uid = $a->data['user']['uid'];
785
786         $community_page = (($a->data['user']['page-flags'] == PAGE_COMMUNITY) ? true : false);
787
788         if((local_user()) && (local_user() == $owner_uid))
789                 $can_post = true;
790         else {
791                 if($community_page && remote_user()) {
792                         $r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
793                                 intval(remote_user()),
794                                 intval($owner_uid)
795                         );
796                         if(count($r)) {
797                                 $can_post = true;
798                                 $contact  = $r[0];
799                                 $remote_contact = true;
800                                 $visitor = remote_user();
801                         }
802                 }
803         }
804
805         // perhaps they're visiting - but not a community page, so they wouldn't have write access
806
807         if(remote_user() && (! $visitor)) {
808                 $contact_id = $_SESSION['visitor_id'];
809                 $groups = init_groups_visitor($contact_id);
810                 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
811                         intval(remote_user()),
812                         intval($owner_uid)
813                 );
814                 if(count($r)) {
815                         $contact = $r[0];
816                         $remote_contact = true;
817                 }
818         }
819
820         if(! $remote_contact) {
821                 if(local_user()) {
822                         $contact_id = $_SESSION['cid'];
823                         $contact = $a->contact;
824                 }
825         }
826
827         if($a->data['user']['hidewall'] && (local_user() != $owner_uid) && (! $remote_contact)) {
828                 notice( t('Access to this item is restricted.') . EOL);
829                 return;
830         }
831
832         $sql_extra = permissions_sql($owner_uid,$remote_contact,$groups);
833
834         $o = "";
835
836         // tabs
837         $_is_owner = (local_user() && (local_user() == $owner_uid));
838         $o .= profile_tabs($a,$_is_owner, $a->data['user']['nickname']);        
839
840         //
841         // dispatch request
842         //
843
844
845         if($datatype === 'upload') {
846                 if(! ($can_post)) {
847                         notice( t('Permission denied.'));
848                         return;
849                 }
850                 $albumselect = '<select id="photos-upload-album-select" name="album" size="4">';
851
852                 $albumselect .= '<option value="" selected="selected" >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
853                 if(count($a->data['albums'])) {
854                         foreach($a->data['albums'] as $album) {
855                                 if(($album['album'] === '') || ($album['album'] === 'Contact Photos') || ($album['album'] === t('Contact Photos')))
856                                         continue;
857                                 $albumselect .= '<option value="' . $album['album'] . '">' . $album['album'] . '</option>';
858                         }
859                 }
860
861                 $celeb = ((($a->user['page-flags'] == PAGE_SOAPBOX) || ($a->user['page-flags'] == PAGE_COMMUNITY)) ? true : false);
862
863                 $albumselect .= '</select>';
864
865                 $uploader = '';
866
867                 $ret = array('post_url' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'],
868                                 'addon_text' => $uploader,
869                                 'default_upload' => true);
870
871
872                 call_hooks('photo_upload_form',$ret);
873
874                 $default_upload = '<input type="file" name="userfile" />        <div class="photos-upload-submit-wrapper" >
875                 <input type="submit" name="submit" value="' . t('Submit') . '" id="photos-upload-submit" /> </div>';
876
877
878  
879
880                 $tpl = get_markup_template('photos_upload.tpl');
881                 $o .= replace_macros($tpl,array(
882                         '$pagename' => t('Upload Photos'),
883                         '$sessid' => session_id(),
884                         '$nickname' => $a->data['user']['nickname'],
885                         '$newalbum' => t('New album name: '),
886                         '$existalbumtext' => t('or existing album name: '),
887                         '$nosharetext' => t('Do not show a status post for this upload'),
888                         '$albumselect' => template_escape($albumselect),
889                         '$permissions' => t('Permissions'),
890                         '$aclselect' => (($visitor) ? '' : template_escape(populate_acl($a->user, $celeb))),
891                         '$uploader' => $ret['addon_text'],
892                         '$default' => (($ret['default_upload']) ? $default_upload : ''),
893                         '$uploadurl' => $ret['post_url']
894
895                 ));
896
897                 return $o; 
898         }
899
900         if($datatype === 'album') {
901
902                 $album = hex2bin($datum);
903
904                 $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s' 
905                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id`",
906                         intval($owner_uid),
907                         dbesc($album)
908                 );
909                 if(count($r)) {
910                         $a->set_pager_total(count($r));
911                         $a->set_pager_itemspage(20);
912                 }
913
914                 $r = q("SELECT `resource-id`, `id`, `filename`, max(`scale`) AS `scale`, `desc` FROM `photo` WHERE `uid` = %d AND `album` = '%s' 
915                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d",
916                         intval($owner_uid),
917                         dbesc($album),
918                         intval($a->pager['start']),
919                         intval($a->pager['itemspage'])
920                 );
921
922                 $o .= '<h3>' . $album . '</h3>';
923                 
924                 if($cmd === 'edit') {           
925                         if(($album !== t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== t('Contact Photos'))) {
926                                 if($can_post) {
927                                         $edit_tpl = get_markup_template('album_edit.tpl');
928                                         $o .= replace_macros($edit_tpl,array(
929                                                 '$nametext' => t('New album name: '),
930                                                 '$nickname' => $a->data['user']['nickname'],
931                                                 '$album' => template_escape($album),
932                                                 '$hexalbum' => bin2hex($album),
933                                                 '$submit' => t('Submit'),
934                                                 '$dropsubmit' => t('Delete Album')
935                                         ));
936                                 }
937                         }
938                 }
939                 else {
940                         if(($album !== t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== t('Contact Photos'))) {
941                                 if($can_post) {
942                                         $o .= '<div id="album-edit-link"><a href="'. $a->get_baseurl() . '/photos/' 
943                                                 . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '/edit' . '">' 
944                                                 . t('Edit Album') . '</a></div>';
945                                 }
946                         }
947                 }
948                 $tpl = get_markup_template('photo_album.tpl');
949                 if(count($r))
950                         foreach($r as $rr) {
951                                 $o .= replace_macros($tpl,array(
952                                         '$id' => $rr['id'],
953                                         '$photolink' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'],
954                                         '$phototitle' => t('View Photo'),
955                                         '$imgsrc' => $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . $rr['scale'] . '.jpg',
956                                         '$imgalt' => template_escape($rr['filename']),
957                                         '$desc'=> template_escape($rr['desc'])
958                                 ));
959
960                 }
961                 $o .= '<div id="photo-album-end"></div>';
962                 $o .= paginate($a);
963
964                 return $o;
965
966         }       
967
968
969         if($datatype === 'image') {
970
971
972
973                 //$o = '';
974                 // fetch image, item containing image, then comments
975
976                 $ph = q("SELECT * FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' 
977                         $sql_extra ORDER BY `scale` ASC ",
978                         intval($owner_uid),
979                         dbesc($datum)
980                 );
981
982                 if(! count($ph)) {
983                         $ph = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' 
984                                 LIMIT 1",
985                                 intval($owner_uid),
986                                 dbesc($datum)
987                         );
988                         if(count($ph)) 
989                                 notice( t('Permission denied. Access to this item may be restricted.'));
990                         else
991                                 notice( t('Photo not available') . EOL );
992                         return;
993                 }
994
995                 $prevlink = '';
996                 $nextlink = '';
997
998                 $prvnxt = q("SELECT `resource-id` FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `scale` = 0 
999                         $sql_extra ORDER BY `created` DESC ",
1000                         dbesc($ph[0]['album']),
1001                         intval($owner_uid)
1002                 ); 
1003
1004                 if(count($prvnxt)) {
1005                         for($z = 0; $z < count($prvnxt); $z++) {
1006                                 if($prvnxt[$z]['resource-id'] == $ph[0]['resource-id']) {
1007                                         $prv = $z - 1;
1008                                         $nxt = $z + 1;
1009                                         if($prv < 0)
1010                                                 $prv = count($prvnxt) - 1;
1011                                         if($nxt >= count($prvnxt))
1012                                                 $nxt = 0;
1013                                         break;
1014                                 }
1015                         }
1016                         $edit_suffix = ((($cmd === 'edit') && ($can_post)) ? '/edit' : '');
1017                         $prevlink = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . $edit_suffix;
1018                         $nextlink = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . $edit_suffix;
1019                 }
1020
1021
1022                 if(count($ph) == 1)
1023                         $hires = $lores = $ph[0];
1024                 if(count($ph) > 1) {
1025                         if($ph[1]['scale'] == 2) {
1026                                 // original is 640 or less, we can display it directly
1027                                 $hires = $lores = $ph[0];
1028                         }
1029                         else {
1030                         $hires = $ph[0];
1031                         $lores = $ph[1];
1032                         }
1033                 }
1034
1035                 $album_link = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($ph[0]['album']);
1036                 $tools = Null;
1037                 $lock = Null;
1038  
1039                 if($can_post && ($ph[0]['uid'] == $owner_uid)) {
1040                         $tools = array(
1041                                 'edit'  => array($a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $datum . (($cmd === 'edit') ? '' : '/edit'), (($cmd === 'edit') ? t('View photo') : t('Edit photo'))),
1042                                 'profile'=>array($a->get_baseurl() . '/profile_photo/use/'.$ph[0]['resource-id'], t('Use as profile photo')),
1043                         );
1044
1045                         // lock
1046                         $lock = ( ( ($ph[0]['uid'] == local_user()) && (strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid']) 
1047                                         || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid'])) ) 
1048                                         ? t('Private Message')
1049                                         : Null);
1050                         
1051                         
1052                 }
1053
1054                 if($prevlink)
1055                         $prevlink = array($prevlink, '<div class="icon prev"></div>') ;
1056
1057                 $photo = array(
1058                         'href' => $a->get_baseurl() . '/photo/' . $hires['resource-id'] . '-' . $hires['scale'] . '.jpg',
1059                         'title'=> t('View Full Size'),
1060                         'src'  => $a->get_baseurl() . '/photo/' . $lores['resource-id'] . '-' . $lores['scale'] . '.jpg'
1061                 );
1062
1063                 if($nextlink)
1064                         $nextlink = array($nextlink, '<div class="icon next"></div>');
1065
1066
1067                 // Do we have an item for this photo?
1068
1069                 $linked_items = q("SELECT * FROM `item` WHERE `resource-id` = '%s' $sql_extra LIMIT 1",
1070                         dbesc($datum)
1071                 );
1072                 if(count($linked_items)) {
1073                         $link_item = $linked_items[0];
1074                         $r = q("SELECT COUNT(*) AS `total`
1075                                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1076                                 WHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0
1077                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1078                                 AND `item`.`uid` = %d 
1079                                 $sql_extra ",
1080                                 dbesc($link_item['uri']),
1081                                 dbesc($link_item['uri']),
1082                                 intval($link_item['uid'])
1083
1084                         );
1085
1086                         if(count($r))
1087                                 $a->set_pager_total($r[0]['total']);
1088
1089
1090                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
1091                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`network`, 
1092                                 `contact`.`rel`, `contact`.`thumb`, `contact`.`self`, 
1093                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1094                                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1095                                 WHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0
1096                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1097                                 AND `item`.`uid` = %d
1098                                 $sql_extra
1099                                 ORDER BY `parent` DESC, `id` ASC LIMIT %d ,%d ",
1100                                 dbesc($link_item['uri']),
1101                                 dbesc($link_item['uri']),
1102                                 intval($link_item['uid']),
1103                                 intval($a->pager['start']),
1104                                 intval($a->pager['itemspage'])
1105
1106                         );
1107                 
1108                         if((local_user()) && (local_user() == $link_item['uid'])) {
1109                                 q("UPDATE `item` SET `unseen` = 0 WHERE `parent` = %d and `uid` = %d",
1110                                         intval($link_item['parent']),
1111                                         intval(local_user())
1112                                 );
1113                         }
1114                 }
1115
1116                 $tags=Null;
1117
1118                 if(count($linked_items) && strlen($link_item['tag'])) {
1119                         $arr = explode(',',$link_item['tag']);
1120                         // parse tags and add links
1121                         $tag_str = '';
1122                         foreach($arr as $t) {
1123                                 if(strlen($tag_str))
1124                                         $tag_str .= ', ';
1125                                 $tag_str .= bbcode($t);
1126                         } 
1127                         $tags = array(t('Tags: '), $tag_str);
1128                         if($cmd === 'edit') {
1129                                 $tags[] = $a->get_baseurl() . '/tagrm/' . $link_item['id'];
1130                                 $tags[] = t('[Remove any tag]');
1131                         }
1132                 }
1133
1134
1135                 $edit = Null;
1136                 if(($cmd === 'edit') && ($can_post)) {
1137                         $edit_tpl = get_markup_template('photo_edit.tpl');
1138                         $edit = replace_macros($edit_tpl, array(
1139                                 '$id' => $ph[0]['id'],
1140                                 '$album' => template_escape($ph[0]['album']),
1141                                 '$newalbum' => t('New album name'), 
1142                                 '$nickname' => $a->data['user']['nickname'],
1143                                 '$resource_id' => $ph[0]['resource-id'],
1144                                 '$capt_label' => t('Caption'),
1145                                 '$caption' => template_escape($ph[0]['desc']),
1146                                 '$tag_label' => t('Add a Tag'),
1147                                 '$tags' => $link_item['tag'],
1148                                 '$permissions' => t('Permissions'),
1149                                 '$aclselect' => template_escape(populate_acl($ph[0])),
1150                                 '$help_tags' => t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping'),
1151                                 '$item_id' => ((count($linked_items)) ? $link_item['id'] : 0),
1152                                 '$submit' => t('Submit'),
1153                                 '$delete' => t('Delete Photo')
1154                         ));
1155                 }
1156
1157                 if(count($linked_items)) {
1158
1159                         $cmnt_tpl = get_markup_template('comment_item.tpl');
1160                         $tpl = get_markup_template('photo_item.tpl');
1161                         $return_url = $a->cmd;
1162
1163                         $like_tpl = get_markup_template('like_noshare.tpl');
1164
1165                         $likebuttons = '';
1166
1167                         if($can_post || can_write_wall($a,$owner_uid)) {
1168                                 $likebuttons = replace_macros($like_tpl,array(
1169                                         '$id' => $link_item['id'],
1170                                         '$likethis' => t("I like this \x28toggle\x29"),
1171                                         '$nolike' => t("I don't like this \x28toggle\x29"),
1172                                         '$share' => t('Share'),
1173                                         '$wait' => t('Please wait')
1174                                 ));
1175                         }
1176
1177                         $comments = '';
1178                         if(! count($r)) {
1179                                 if($can_post || can_write_wall($a,$owner_uid)) {
1180                                         if($link_item['last-child']) {
1181                                                 $comments .= replace_macros($cmnt_tpl,array(
1182                                                         '$return_path' => '', 
1183                                                         '$jsreload' => $return_url,
1184                                                         '$type' => 'wall-comment',
1185                                                         '$id' => $link_item['id'],
1186                                                         '$parent' => $link_item['id'],
1187                                                         '$profile_uid' =>  $owner_uid,
1188                                                         '$mylink' => $contact['url'],
1189                                                         '$mytitle' => t('This is you'),
1190                                                         '$myphoto' => $contact['thumb'],
1191                                                         '$comment' => t('Comment'),
1192                                                         '$submit' => t('Submit'),
1193                                                         '$ww' => ''
1194                                                 ));
1195                                         }
1196                                 }
1197                         }
1198
1199                         $alike = array();
1200                         $dlike = array();
1201                         
1202                         $like = '';
1203                         $dislike = '';
1204
1205                         // display comments
1206                         if(count($r)) {
1207
1208                                 foreach($r as $item) {
1209                                         like_puller($a,$item,$alike,'like');
1210                                         like_puller($a,$item,$dlike,'dislike');
1211                                 }
1212
1213                                 $like    = ((isset($alike[$link_item['id']])) ? format_like($alike[$link_item['id']],$alike[$link_item['id'] . '-l'],'like',$link_item['id']) : '');
1214                                 $dislike = ((isset($dlike[$link_item['id']])) ? format_like($dlike[$link_item['id']],$dlike[$link_item['id'] . '-l'],'dislike',$link_item['id']) : '');
1215
1216
1217
1218                                 if($can_post || can_write_wall($a,$owner_uid)) {
1219                                         if($link_item['last-child']) {
1220                                                 $comments .= replace_macros($cmnt_tpl,array(
1221                                                         '$return_path' => '',
1222                                                         '$jsreload' => $return_url,
1223                                                         '$type' => 'wall-comment',
1224                                                         '$id' => $link_item['id'],
1225                                                         '$parent' => $link_item['id'],
1226                                                         '$profile_uid' =>  $owner_uid,
1227                                                         '$mylink' => $contact['url'],
1228                                                         '$mytitle' => t('This is you'),
1229                                                         '$myphoto' => $contact['thumb'],
1230                                                         '$comment' => t('Comment'),
1231                                                         '$submit' => t('Submit'),
1232                                                         '$ww' => ''
1233                                                 ));
1234                                         }
1235                                 }
1236
1237
1238                                 foreach($r as $item) {
1239                                         $comment = '';
1240                                         $template = $tpl;
1241                                         $sparkle = '';
1242
1243                                         if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE))) && ($item['id'] != $item['parent']))
1244                                                 continue;
1245
1246                                         $redirect_url = $a->get_baseurl() . '/redir/' . $item['cid'] ;
1247                         
1248                                         if($can_post || can_write_wall($a,$owner_uid)) {
1249
1250                                                 if($item['last-child']) {
1251                                                         $comments .= replace_macros($cmnt_tpl,array(
1252                                                                 '$return_path' => '',
1253                                                                 '$jsreload' => $return_url,
1254                                                                 '$type' => 'wall-comment',
1255                                                                 '$id' => $item['item_id'],
1256                                                                 '$parent' => $item['parent'],
1257                                                                 '$profile_uid' =>  $owner_uid,
1258                                                                 '$mylink' => $contact['url'],
1259                                                                 '$mytitle' => t('This is you'),
1260                                                                 '$myphoto' => $contact['thumb'],
1261                                                                 '$comment' => t('Comment'),
1262                                                                 '$submit' => t('Submit'),
1263                                                                 '$ww' => ''
1264                                                         ));
1265                                                 }
1266                                         }
1267
1268
1269                                         if(local_user() && ($item['contact-uid'] == local_user()) 
1270                                                 && ($item['network'] == 'dfrn') && (! $item['self'] )) {
1271                                                 $profile_url = $redirect_url;
1272                                                 $sparkle = ' sparkle';
1273                                         }
1274                                         else {
1275                                                 $profile_url = $item['url'];
1276                                                 $sparkle = '';
1277                                         }
1278  
1279                                         $diff_author = (($item['url'] !== $item['author-link']) ? true : false);
1280
1281                                         $profile_name   = (((strlen($item['author-name']))   && $diff_author) ? $item['author-name']   : $item['name']);
1282                                         $profile_avatar = (((strlen($item['author-avatar'])) && $diff_author) ? $item['author-avatar'] : $item['thumb']);
1283
1284                                         $profile_link = $profile_url;
1285
1286                                         $drop = '';
1287
1288                                         if(($item['contact-id'] == remote_user()) || ($item['uid'] == local_user()))
1289                                                 $drop = replace_macros(get_markup_template('photo_drop.tpl'), array('$id' => $item['id'], '$delete' => t('Delete')));
1290
1291
1292                                         $comments .= replace_macros($template,array(
1293                                                 '$id' => $item['item_id'],
1294                                                 '$profile_url' => $profile_link,
1295                                                 '$name' => template_escape($profile_name),
1296                                                 '$thumb' => $profile_avatar,
1297                                                 '$sparkle' => $sparkle,
1298                                                 '$title' => template_escape($item['title']),
1299                                                 '$body' => template_escape(bbcode($item['body'])),
1300                                                 '$ago' => relative_date($item['created']),
1301                                                 '$indent' => (($item['parent'] != $item['item_id']) ? ' comment' : ''),
1302                                                 '$drop' => $drop,
1303                                                 '$comment' => $comment
1304                                         ));
1305                                 }
1306                         }
1307
1308                         $paginate = paginate($a);
1309                 }
1310                 
1311                 $photo_tpl = get_markup_template('photo_view.tpl');
1312                 $o .= replace_macros($photo_tpl, array(
1313                         '$id' => $ph[0]['id'],
1314                         '$album' => array($album_link,template_escape($ph[0]['album'])),
1315                         '$tools' => $tools,
1316                         '$lock' => $lock,
1317                         '$photo' => $photo,
1318                         '$prevlink' => $prevlink,
1319                         '$nextlink' => $nextlink,
1320                         '$desc' => $ph[0]['desc'],
1321                         '$tags' => template_escape($tags),
1322                         '$edit' => $edit,       
1323                         '$likebuttons' => $likebuttons,
1324                         '$like' => template_escape($like),
1325                         '$dislike' => template_escape($dislike),
1326                         '$comments' => $comments,
1327                         '$paginate' => $paginate,
1328                 ));
1329                 
1330                 return $o;
1331         }
1332
1333         // Default - show recent photos with upload link (if applicable)
1334         //$o = '';
1335
1336         $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' 
1337                 $sql_extra GROUP BY `resource-id`",
1338                 intval($a->data['user']['uid']),
1339                 dbesc('Contact Photos'),
1340                 dbesc( t('Contact Photos'))
1341         );
1342         if(count($r)) {
1343                 $a->set_pager_total(count($r));
1344                 $a->set_pager_itemspage(20);
1345         }
1346
1347         $r = q("SELECT `resource-id`, `id`, `filename`, `album`, max(`scale`) AS `scale` FROM `photo`
1348                 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s'  
1349                 $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d",
1350                 intval($a->data['user']['uid']),
1351                 dbesc('Contact Photos'),
1352                 dbesc( t('Contact Photos')),
1353                 intval($a->pager['start']),
1354                 intval($a->pager['itemspage'])
1355         );
1356
1357         $o .= '<h3>' . t('Recent Photos') . '</h3>';
1358
1359         if($can_post) {
1360                 $o .= '<div id="photo-top-links"><a id="photo-top-upload-link" href="'. $a->get_baseurl() . '/photos/' 
1361                         . $a->data['user']['nickname'] . '/upload' . '">' . t('Upload New Photos') . '</a></div>';
1362         }
1363
1364         $tpl = get_markup_template('photo_top.tpl');
1365         if(count($r)) {
1366                 foreach($r as $rr) {
1367                         $o .= replace_macros($tpl,array(
1368                                 '$id'         => $rr['id'],
1369                                 '$photolink'  => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'],
1370                                 '$phototitle' => t('View Photo'),
1371                                 '$imgsrc'     => $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . ((($rr['scale']) == 6) ? 4 : $rr['scale']) . '.jpg',
1372                                 '$albumlink'  => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($rr['album']),
1373                                 '$albumname'  => template_escape($rr['album']),
1374                                 '$albumalt'   => t('View Album'),
1375                                 '$imgalt'     => template_escape($rr['filename'])
1376                         ));
1377
1378                 }
1379                 $o .= '<div id="photo-top-end"></div>';
1380         }
1381         $o .= paginate($a);
1382         return $o;
1383 }
1384