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