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