]> git.mxchange.org Git - friendica.git/blob - mod/photos.php
changes to support a mobile theme
[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         $max_length = get_config('system','max_image_length');
747         if(! $max_length)
748                 $max_length = MAX_IMAGE_LENGTH;
749         if($max_length > 0)
750                 $ph->scaleImage($max_length);
751
752         $width  = $ph->getWidth();
753         $height = $ph->getHeight();
754
755         $smallest = 0;
756
757         $photo_hash = photo_new_resource();
758
759         $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);
760
761         if(! $r) {
762                 logger('mod/photos.php: photos_post(): image store failed' , LOGGER_DEBUG);
763                 notice( t('Image upload failed.') . EOL );
764                 killme();
765         }
766
767         if($width > 640 || $height > 640) {
768                 $ph->scaleImage(640);
769                 $ph->store($page_owner_uid, $visitor, $photo_hash, $filename, $album, 1, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
770                 $smallest = 1;
771         }
772
773         if($width > 320 || $height > 320) {
774                 $ph->scaleImage(320);
775                 $ph->store($page_owner_uid, $visitor, $photo_hash, $filename, $album, 2, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
776                 $smallest = 2;
777         }
778         
779         $basename = basename($filename);
780         $uri = item_new_uri($a->get_hostname(), $page_owner_uid);
781
782         // Create item container
783
784         $arr = array();
785
786         $arr['uid']           = $page_owner_uid;
787         $arr['uri']           = $uri;
788         $arr['parent-uri']    = $uri;
789         $arr['type']          = 'photo';
790         $arr['wall']          = 1;
791         $arr['resource-id']   = $photo_hash;
792         $arr['contact-id']    = $owner_record['id'];
793         $arr['owner-name']    = $owner_record['name'];
794         $arr['owner-link']    = $owner_record['url'];
795         $arr['owner-avatar']  = $owner_record['thumb'];
796         $arr['author-name']   = $owner_record['name'];
797         $arr['author-link']   = $owner_record['url'];
798         $arr['author-avatar'] = $owner_record['thumb'];
799         $arr['title']         = '';
800         $arr['allow_cid']     = $str_contact_allow;
801         $arr['allow_gid']     = $str_group_allow;
802         $arr['deny_cid']      = $str_contact_deny;
803         $arr['deny_gid']      = $str_group_deny;
804         $arr['last-child']    = 1;
805         $arr['visible']       = $visible;
806         $arr['origin']        = 1;
807
808         $arr['body']          = '[url=' . $a->get_baseurl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo_hash . ']' 
809                                 . '[img]' . $a->get_baseurl() . "/photo/{$photo_hash}-{$smallest}.".$ph->getExt() . '[/img]' 
810                                 . '[/url]';
811
812         $item_id = item_store($arr);
813
814         if($item_id) {
815                 q("UPDATE `item` SET `plink` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
816                         dbesc($a->get_baseurl() . '/display/' . $owner_record['nickname'] . '/' . $item_id),
817                         intval($page_owner_uid),
818                         intval($item_id)
819                 );
820         }
821         
822         if($visible) 
823                 proc_run('php', "include/notifier.php", 'wall-new', $item_id);
824
825         call_hooks('photo_post_end',intval($item_id));
826
827         // addon uploaders should call "killme()" [e.g. exit] within the photo_post_end hook
828         // if they do not wish to be redirected
829
830         goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
831         // NOTREACHED
832 }
833
834
835
836 function photos_content(&$a) {
837
838         // URLs:
839         // photos/name
840         // photos/name/upload
841         // photos/name/upload/xxxxx (xxxxx is album name)
842         // photos/name/album/xxxxx
843         // photos/name/album/xxxxx/edit
844         // photos/name/image/xxxxx
845         // photos/name/image/xxxxx/edit
846
847
848         if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
849                 notice( t('Public access denied.') . EOL);
850                 return;
851         }
852         
853         
854         require_once('include/bbcode.php');
855         require_once('include/security.php');
856         require_once('include/conversation.php');
857
858         if(! x($a->data,'user')) {
859                 notice( t('No photos selected') . EOL );
860                 return;
861         }
862
863         $phototypes = Photo::supportedTypes();
864
865         $_SESSION['photo_return'] = $a->cmd;
866
867         //
868         // Parse arguments 
869         //
870
871         if($a->argc > 3) {
872                 $datatype = $a->argv[2];
873                 $datum = $a->argv[3];
874         }
875         elseif(($a->argc > 2) && ($a->argv[2] === 'upload'))
876                 $datatype = 'upload';
877         else
878                 $datatype = 'summary';
879
880         if($a->argc > 4)
881                 $cmd = $a->argv[4];
882         else
883                 $cmd = 'view';
884
885         //
886         // Setup permissions structures
887         //
888
889         $can_post       = false;
890         $visitor        = 0;
891         $contact        = null;
892         $remote_contact = false;
893
894         $owner_uid = $a->data['user']['uid'];
895
896         $community_page = (($a->data['user']['page-flags'] == PAGE_COMMUNITY) ? true : false);
897
898         if((local_user()) && (local_user() == $owner_uid))
899                 $can_post = true;
900         else {
901                 if($community_page && remote_user()) {
902                         $r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
903                                 intval(remote_user()),
904                                 intval($owner_uid)
905                         );
906                         if(count($r)) {
907                                 $can_post = true;
908                                 $contact  = $r[0];
909                                 $remote_contact = true;
910                                 $visitor = remote_user();
911                         }
912                 }
913         }
914
915         // perhaps they're visiting - but not a community page, so they wouldn't have write access
916
917         if(remote_user() && (! $visitor)) {
918                 $contact_id = $_SESSION['visitor_id'];
919                 $groups = init_groups_visitor($contact_id);
920                 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
921                         intval(remote_user()),
922                         intval($owner_uid)
923                 );
924                 if(count($r)) {
925                         $contact = $r[0];
926                         $remote_contact = true;
927                 }
928         }
929
930         if(! $remote_contact) {
931                 if(local_user()) {
932                         $contact_id = $_SESSION['cid'];
933                         $contact = $a->contact;
934                 }
935         }
936
937         if($a->data['user']['hidewall'] && (local_user() != $owner_uid) && (! $remote_contact)) {
938                 notice( t('Access to this item is restricted.') . EOL);
939                 return;
940         }
941
942         $sql_extra = permissions_sql($owner_uid,$remote_contact,$groups);
943
944         $o = "";
945
946         // tabs
947         $_is_owner = (local_user() && (local_user() == $owner_uid));
948         $o .= profile_tabs($a,$_is_owner, $a->data['user']['nickname']);        
949
950         //
951         // dispatch request
952         //
953
954
955         if($datatype === 'upload') {
956                 if(! ($can_post)) {
957                         notice( t('Permission denied.'));
958                         return;
959                 }
960
961
962                 $selname = (($datum) ? hex2bin($datum) : '');
963
964
965                 $albumselect = '<select id="photos-upload-album-select" name="album" size="4">';
966
967                 
968                 $albumselect .= '<option value="" ' . ((! $selname) ? ' selected="selected" ' : '') . '>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
969                 if(count($a->data['albums'])) {
970                         foreach($a->data['albums'] as $album) {
971                                 if(($album['album'] === '') || ($album['album'] === 'Contact Photos') || ($album['album'] === t('Contact Photos')))
972                                         continue;
973                                 $selected = (($selname === $album['album']) ? ' selected="selected" ' : '');
974                                 $albumselect .= '<option value="' . $album['album'] . '"' . $selected . '>' . $album['album'] . '</option>';
975                         }
976                 }
977
978                 $celeb = ((($a->user['page-flags'] == PAGE_SOAPBOX) || ($a->user['page-flags'] == PAGE_COMMUNITY)) ? true : false);
979
980                 $albumselect .= '</select>';
981
982                 $uploader = '';
983
984                 $ret = array('post_url' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'],
985                                 'addon_text' => $uploader,
986                                 'default_upload' => true);
987
988
989                 call_hooks('photo_upload_form',$ret);
990
991                 $default_upload = '<input id="photos-upload-choose" type="file" name="userfile" />      <div class="photos-upload-submit-wrapper" >
992                 <input type="submit" name="submit" value="' . t('Submit') . '" id="photos-upload-submit" /> </div>';
993
994
995                 $r = q("select sum(octet_length(data)) as total from photo where uid = %d and scale = 0 and album != 'Contact Photos' ",
996                         intval($a->data['user']['uid'])
997                 );
998
999
1000                 $limit = service_class_fetch($a->data['user']['uid'],'photo_upload_limit');
1001                 if($limit !== false) {
1002                         $usage_message = sprintf( t("You have used %1$.2f Mbytes of %2$.2f Mbytes photo storage."), $r[0]['total'] / 1024000, $limit / 1024000 );
1003                 }
1004                 else {
1005                         $usage_message = sprintf( t('You have used %1$.2f Mbytes of photo storage.'), $r[0]['total'] / 1024000 );
1006                 }
1007
1008
1009                 $tpl = get_markup_template('photos_upload.tpl');
1010                 $o .= replace_macros($tpl,array(
1011                         '$pagename' => t('Upload Photos'),
1012                         '$sessid' => session_id(),
1013                         '$usage' => $usage_message,
1014                         '$nickname' => $a->data['user']['nickname'],
1015                         '$newalbum' => t('New album name: '),
1016                         '$existalbumtext' => t('or existing album name: '),
1017                         '$nosharetext' => t('Do not show a status post for this upload'),
1018                         '$albumselect' => template_escape($albumselect),
1019                         '$permissions' => t('Permissions'),
1020                         '$aclselect' => (($visitor) ? '' : template_escape(populate_acl($a->user, $celeb))),
1021                         '$uploader' => $ret['addon_text'],
1022                         '$default' => (($ret['default_upload']) ? $default_upload : ''),
1023                         '$uploadurl' => $ret['post_url']
1024
1025                 ));
1026
1027                 return $o; 
1028         }
1029
1030         if($datatype === 'album') {
1031
1032                 $album = hex2bin($datum);
1033
1034                 $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s' 
1035                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id`",
1036                         intval($owner_uid),
1037                         dbesc($album)
1038                 );
1039                 if(count($r)) {
1040                         $a->set_pager_total(count($r));
1041                         $a->set_pager_itemspage(20);
1042                 }
1043
1044                 $r = q("SELECT `resource-id`, `id`, `filename`, type, max(`scale`) AS `scale`, `desc` FROM `photo` WHERE `uid` = %d AND `album` = '%s' 
1045                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d",
1046                         intval($owner_uid),
1047                         dbesc($album),
1048                         intval($a->pager['start']),
1049                         intval($a->pager['itemspage'])
1050                 );
1051
1052                 $o .= '<h3>' . $album . '</h3>';
1053                 
1054                 if($cmd === 'edit') {           
1055                         if(($album !== t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== t('Contact Photos'))) {
1056                                 if($can_post) {
1057                                         $edit_tpl = get_markup_template('album_edit.tpl');
1058                                         $o .= replace_macros($edit_tpl,array(
1059                                                 '$nametext' => t('New album name: '),
1060                                                 '$nickname' => $a->data['user']['nickname'],
1061                                                 '$album' => template_escape($album),
1062                                                 '$hexalbum' => bin2hex($album),
1063                                                 '$submit' => t('Submit'),
1064                                                 '$dropsubmit' => t('Delete Album')
1065                                         ));
1066                                 }
1067                         }
1068                 }
1069                 else {
1070                         if(($album !== t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== t('Contact Photos'))) {
1071                                 if($can_post) {
1072                                         $o .= '<div id="album-edit-link"><a href="'. $a->get_baseurl() . '/photos/' 
1073                                                 . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '/edit' . '">' 
1074                                                 . t('Edit Album') . '</a></div>';
1075                                 }
1076                         }
1077                 }
1078
1079                 if($can_post) {
1080                         $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>';
1081                 }
1082
1083                 $tpl = get_markup_template('photo_album.tpl');
1084                 if(count($r))
1085                         $twist = 'rotright';
1086                         foreach($r as $rr) {
1087                                 if($twist == 'rotright')
1088                                         $twist = 'rotleft';
1089                                 else
1090                                         $twist = 'rotright';
1091                                 
1092                                 $ext = $phototypes[$rr['type']];
1093
1094                                 $o .= replace_macros($tpl,array(
1095                                         '$id' => $rr['id'],
1096                                         '$twist' => ' ' . $twist . rand(2,4),
1097                                         '$photolink' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'],
1098                                         '$phototitle' => t('View Photo'),
1099                                         '$imgsrc' => $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . $rr['scale'] . '.' .$ext,
1100                                         '$imgalt' => template_escape($rr['filename']),
1101                                         '$desc'=> template_escape($rr['desc'])
1102                                 ));
1103
1104                 }
1105                 $o .= '<div id="photo-album-end"></div>';
1106                 $o .= paginate($a);
1107
1108                 return $o;
1109
1110         }       
1111
1112
1113         if($datatype === 'image') {
1114
1115
1116
1117                 //$o = '';
1118                 // fetch image, item containing image, then comments
1119
1120                 $ph = q("SELECT * FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' 
1121                         $sql_extra ORDER BY `scale` ASC ",
1122                         intval($owner_uid),
1123                         dbesc($datum)
1124                 );
1125
1126                 if(! count($ph)) {
1127                         $ph = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' 
1128                                 LIMIT 1",
1129                                 intval($owner_uid),
1130                                 dbesc($datum)
1131                         );
1132                         if(count($ph)) 
1133                                 notice( t('Permission denied. Access to this item may be restricted.'));
1134                         else
1135                                 notice( t('Photo not available') . EOL );
1136                         return;
1137                 }
1138
1139                 $prevlink = '';
1140                 $nextlink = '';
1141
1142                 $prvnxt = q("SELECT `resource-id` FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `scale` = 0 
1143                         $sql_extra ORDER BY `created` DESC ",
1144                         dbesc($ph[0]['album']),
1145                         intval($owner_uid)
1146                 ); 
1147
1148                 if(count($prvnxt)) {
1149                         for($z = 0; $z < count($prvnxt); $z++) {
1150                                 if($prvnxt[$z]['resource-id'] == $ph[0]['resource-id']) {
1151                                         $prv = $z - 1;
1152                                         $nxt = $z + 1;
1153                                         if($prv < 0)
1154                                                 $prv = count($prvnxt) - 1;
1155                                         if($nxt >= count($prvnxt))
1156                                                 $nxt = 0;
1157                                         break;
1158                                 }
1159                         }
1160                         $edit_suffix = ((($cmd === 'edit') && ($can_post)) ? '/edit' : '');
1161                         $prevlink = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . $edit_suffix;
1162                         $nextlink = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . $edit_suffix;
1163                 }
1164
1165
1166                 if(count($ph) == 1)
1167                         $hires = $lores = $ph[0];
1168                 if(count($ph) > 1) {
1169                         if($ph[1]['scale'] == 2) {
1170                                 // original is 640 or less, we can display it directly
1171                                 $hires = $lores = $ph[0];
1172                         }
1173                         else {
1174                         $hires = $ph[0];
1175                         $lores = $ph[1];
1176                         }
1177                 }
1178
1179                 $album_link = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($ph[0]['album']);
1180                 $tools = Null;
1181                 $lock = Null;
1182  
1183                 if($can_post && ($ph[0]['uid'] == $owner_uid)) {
1184                         $tools = array(
1185                                 'edit'  => array($a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $datum . (($cmd === 'edit') ? '' : '/edit'), (($cmd === 'edit') ? t('View photo') : t('Edit photo'))),
1186                                 'profile'=>array($a->get_baseurl() . '/profile_photo/use/'.$ph[0]['resource-id'], t('Use as profile photo')),
1187                         );
1188
1189                         // lock
1190                         $lock = ( ( ($ph[0]['uid'] == local_user()) && (strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid']) 
1191                                         || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid'])) ) 
1192                                         ? t('Private Message')
1193                                         : Null);
1194                         
1195                         
1196                 }
1197
1198                 if(! $cmd !== 'edit') {
1199                         $a->page['htmlhead'] .= '<script>
1200                                 $(document).keydown(function(event) {' . "\n";
1201
1202                         if($prevlink)
1203                                 $a->page['htmlhead'] .= 'if(event.ctrlKey && event.keyCode == 37) { event.preventDefault(); window.location.href = \'' . $prevlink . '\'; }' . "\n";
1204                         if($nextlink)
1205                                 $a->page['htmlhead'] .= 'if(event.ctrlKey && event.keyCode == 39) { event.preventDefault(); window.location.href = \'' . $nextlink . '\'; }' . "\n";
1206                         $a->page['htmlhead'] .= '});</script>';
1207                 }
1208
1209                 if($prevlink)
1210                         $prevlink = array($prevlink, '<div class="icon prev"></div>') ;
1211
1212                 $photo = array(
1213                         'href' => $a->get_baseurl() . '/photo/' . $hires['resource-id'] . '-' . $hires['scale'] . '.' . $phototypes[$hires['type']],
1214                         'title'=> t('View Full Size'),
1215                         'src'  => $a->get_baseurl() . '/photo/' . $lores['resource-id'] . '-' . $lores['scale'] . '.' . $phototypes[$lores['type']] . '?f=&_u=' . datetime_convert('','','','ymdhis')
1216                 );
1217
1218                 if($nextlink)
1219                         $nextlink = array($nextlink, '<div class="icon next"></div>');
1220
1221
1222                 // Do we have an item for this photo?
1223
1224                 $linked_items = q("SELECT * FROM `item` WHERE `resource-id` = '%s' $sql_extra LIMIT 1",
1225                         dbesc($datum)
1226                 );
1227                 if(count($linked_items)) {
1228                         $link_item = $linked_items[0];
1229                         $r = q("SELECT COUNT(*) AS `total`
1230                                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1231                                 WHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1232                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1233                                 AND `item`.`uid` = %d 
1234                                 $sql_extra ",
1235                                 dbesc($link_item['uri']),
1236                                 dbesc($link_item['uri']),
1237                                 intval($link_item['uid'])
1238
1239                         );
1240
1241                         if(count($r))
1242                                 $a->set_pager_total($r[0]['total']);
1243
1244
1245                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
1246                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`network`, 
1247                                 `contact`.`rel`, `contact`.`thumb`, `contact`.`self`, 
1248                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1249                                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1250                                 WHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1251                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1252                                 AND `item`.`uid` = %d
1253                                 $sql_extra
1254                                 ORDER BY `parent` DESC, `id` ASC LIMIT %d ,%d ",
1255                                 dbesc($link_item['uri']),
1256                                 dbesc($link_item['uri']),
1257                                 intval($link_item['uid']),
1258                                 intval($a->pager['start']),
1259                                 intval($a->pager['itemspage'])
1260
1261                         );
1262                 
1263                         if((local_user()) && (local_user() == $link_item['uid'])) {
1264                                 q("UPDATE `item` SET `unseen` = 0 WHERE `parent` = %d and `uid` = %d",
1265                                         intval($link_item['parent']),
1266                                         intval(local_user())
1267                                 );
1268                         }
1269                 }
1270
1271                 $tags=Null;
1272
1273                 if(count($linked_items) && strlen($link_item['tag'])) {
1274                         $arr = explode(',',$link_item['tag']);
1275                         // parse tags and add links
1276                         $tag_str = '';
1277                         foreach($arr as $t) {
1278                                 if(strlen($tag_str))
1279                                         $tag_str .= ', ';
1280                                 $tag_str .= bbcode($t);
1281                         } 
1282                         $tags = array(t('Tags: '), $tag_str);
1283                         if($cmd === 'edit') {
1284                                 $tags[] = $a->get_baseurl() . '/tagrm/' . $link_item['id'];
1285                                 $tags[] = t('[Remove any tag]');
1286                         }
1287                 }
1288
1289
1290                 $edit = Null;
1291                 if(($cmd === 'edit') && ($can_post)) {
1292                         $edit_tpl = get_markup_template('photo_edit.tpl');
1293                         $edit = replace_macros($edit_tpl, array(
1294                                 '$id' => $ph[0]['id'],
1295                                 '$rotatecw' => t('Rotate CW (right)'),
1296                                 '$rotateccw' => t('Rotate CCW (left)'),
1297                                 '$album' => template_escape($ph[0]['album']),
1298                                 '$newalbum' => t('New album name'), 
1299                                 '$nickname' => $a->data['user']['nickname'],
1300                                 '$resource_id' => $ph[0]['resource-id'],
1301                                 '$capt_label' => t('Caption'),
1302                                 '$caption' => template_escape($ph[0]['desc']),
1303                                 '$tag_label' => t('Add a Tag'),
1304                                 '$tags' => $link_item['tag'],
1305                                 '$permissions' => t('Permissions'),
1306                                 '$aclselect' => template_escape(populate_acl($ph[0])),
1307                                 '$help_tags' => t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping'),
1308                                 '$item_id' => ((count($linked_items)) ? $link_item['id'] : 0),
1309                                 '$submit' => t('Submit'),
1310                                 '$delete' => t('Delete Photo')
1311                         ));
1312                 }
1313
1314                 if(count($linked_items)) {
1315
1316                         $cmnt_tpl = get_markup_template('comment_item.tpl');
1317                         $tpl = get_markup_template('photo_item.tpl');
1318                         $return_url = $a->cmd;
1319
1320                         $like_tpl = get_markup_template('like_noshare.tpl');
1321
1322                         $likebuttons = '';
1323
1324                         if($can_post || can_write_wall($a,$owner_uid)) {
1325                                 $likebuttons = replace_macros($like_tpl,array(
1326                                         '$id' => $link_item['id'],
1327                                         '$likethis' => t("I like this \x28toggle\x29"),
1328                                         '$nolike' => t("I don't like this \x28toggle\x29"),
1329                                         '$share' => t('Share'),
1330                                         '$wait' => t('Please wait')
1331                                 ));
1332                         }
1333
1334                         $comments = '';
1335                         if(! count($r)) {
1336                                 if($can_post || can_write_wall($a,$owner_uid)) {
1337                                         if($link_item['last-child']) {
1338                                                 $comments .= replace_macros($cmnt_tpl,array(
1339                                                         '$return_path' => '', 
1340                                                         '$jsreload' => $return_url,
1341                                                         '$type' => 'wall-comment',
1342                                                         '$id' => $link_item['id'],
1343                                                         '$parent' => $link_item['id'],
1344                                                         '$profile_uid' =>  $owner_uid,
1345                                                         '$mylink' => $contact['url'],
1346                                                         '$mytitle' => t('This is you'),
1347                                                         '$myphoto' => $contact['thumb'],
1348                                                         '$comment' => t('Comment'),
1349                                                         '$submit' => t('Submit'),
1350                                                         '$preview' => t('Preview'),
1351                                                         '$ww' => ''
1352                                                 ));
1353                                         }
1354                                 }
1355                         }
1356
1357                         $alike = array();
1358                         $dlike = array();
1359                         
1360                         $like = '';
1361                         $dislike = '';
1362
1363                         // display comments
1364                         if(count($r)) {
1365
1366                                 foreach($r as $item) {
1367                                         like_puller($a,$item,$alike,'like');
1368                                         like_puller($a,$item,$dlike,'dislike');
1369                                 }
1370
1371                                 $like    = ((isset($alike[$link_item['id']])) ? format_like($alike[$link_item['id']],$alike[$link_item['id'] . '-l'],'like',$link_item['id']) : '');
1372                                 $dislike = ((isset($dlike[$link_item['id']])) ? format_like($dlike[$link_item['id']],$dlike[$link_item['id'] . '-l'],'dislike',$link_item['id']) : '');
1373
1374
1375
1376                                 if($can_post || can_write_wall($a,$owner_uid)) {
1377                                         if($link_item['last-child']) {
1378                                                 $comments .= replace_macros($cmnt_tpl,array(
1379                                                         '$return_path' => '',
1380                                                         '$jsreload' => $return_url,
1381                                                         '$type' => 'wall-comment',
1382                                                         '$id' => $link_item['id'],
1383                                                         '$parent' => $link_item['id'],
1384                                                         '$profile_uid' =>  $owner_uid,
1385                                                         '$mylink' => $contact['url'],
1386                                                         '$mytitle' => t('This is you'),
1387                                                         '$myphoto' => $contact['thumb'],
1388                                                         '$comment' => t('Comment'),
1389                                                         '$submit' => t('Submit'),
1390                                                         '$ww' => ''
1391                                                 ));
1392                                         }
1393                                 }
1394
1395
1396                                 foreach($r as $item) {
1397                                         $comment = '';
1398                                         $template = $tpl;
1399                                         $sparkle = '';
1400
1401                                         if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE))) && ($item['id'] != $item['parent']))
1402                                                 continue;
1403
1404                                         $redirect_url = $a->get_baseurl() . '/redir/' . $item['cid'] ;
1405                         
1406                                         if($can_post || can_write_wall($a,$owner_uid)) {
1407
1408                                                 if($item['last-child']) {
1409                                                         $comments .= replace_macros($cmnt_tpl,array(
1410                                                                 '$return_path' => '',
1411                                                                 '$jsreload' => $return_url,
1412                                                                 '$type' => 'wall-comment',
1413                                                                 '$id' => $item['item_id'],
1414                                                                 '$parent' => $item['parent'],
1415                                                                 '$profile_uid' =>  $owner_uid,
1416                                                                 '$mylink' => $contact['url'],
1417                                                                 '$mytitle' => t('This is you'),
1418                                                                 '$myphoto' => $contact['thumb'],
1419                                                                 '$comment' => t('Comment'),
1420                                                                 '$submit' => t('Submit'),
1421                                                                 '$ww' => ''
1422                                                         ));
1423                                                 }
1424                                         }
1425
1426
1427                                         if(local_user() && ($item['contact-uid'] == local_user()) 
1428                                                 && ($item['network'] == 'dfrn') && (! $item['self'] )) {
1429                                                 $profile_url = $redirect_url;
1430                                                 $sparkle = ' sparkle';
1431                                         }
1432                                         else {
1433                                                 $profile_url = $item['url'];
1434                                                 $sparkle = '';
1435                                         }
1436  
1437                                         $diff_author = (($item['url'] !== $item['author-link']) ? true : false);
1438
1439                                         $profile_name   = (((strlen($item['author-name']))   && $diff_author) ? $item['author-name']   : $item['name']);
1440                                         $profile_avatar = (((strlen($item['author-avatar'])) && $diff_author) ? $item['author-avatar'] : $item['thumb']);
1441
1442                                         $profile_link = $profile_url;
1443
1444                                         $drop = '';
1445
1446                                         if(($item['contact-id'] == remote_user()) || ($item['uid'] == local_user()))
1447                                                 $drop = replace_macros(get_markup_template('photo_drop.tpl'), array('$id' => $item['id'], '$delete' => t('Delete')));
1448
1449
1450                                         $comments .= replace_macros($template,array(
1451                                                 '$id' => $item['item_id'],
1452                                                 '$profile_url' => $profile_link,
1453                                                 '$name' => template_escape($profile_name),
1454                                                 '$thumb' => $profile_avatar,
1455                                                 '$sparkle' => $sparkle,
1456                                                 '$title' => template_escape($item['title']),
1457                                                 '$body' => template_escape(bbcode($item['body'])),
1458                                                 '$ago' => relative_date($item['created']),
1459                                                 '$indent' => (($item['parent'] != $item['item_id']) ? ' comment' : ''),
1460                                                 '$drop' => $drop,
1461                                                 '$comment' => $comment
1462                                         ));
1463                                 }
1464                         }
1465
1466                         $paginate = paginate($a);
1467                 }
1468                 
1469                 $photo_tpl = get_markup_template('photo_view.tpl');
1470                 $o .= replace_macros($photo_tpl, array(
1471                         '$id' => $ph[0]['id'],
1472                         '$album' => array($album_link,template_escape($ph[0]['album'])),
1473                         '$tools' => $tools,
1474                         '$lock' => $lock,
1475                         '$photo' => $photo,
1476                         '$prevlink' => $prevlink,
1477                         '$nextlink' => $nextlink,
1478                         '$desc' => $ph[0]['desc'],
1479                         '$tags' => template_escape($tags),
1480                         '$edit' => $edit,       
1481                         '$likebuttons' => $likebuttons,
1482                         '$like' => template_escape($like),
1483                         '$dislike' => template_escape($dislike),
1484                         '$comments' => $comments,
1485                         '$paginate' => $paginate,
1486                 ));
1487                 
1488                 return $o;
1489         }
1490
1491         // Default - show recent photos with upload link (if applicable)
1492         //$o = '';
1493
1494         $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' 
1495                 $sql_extra GROUP BY `resource-id`",
1496                 intval($a->data['user']['uid']),
1497                 dbesc('Contact Photos'),
1498                 dbesc( t('Contact Photos'))
1499         );
1500         if(count($r)) {
1501                 $a->set_pager_total(count($r));
1502                 $a->set_pager_itemspage(20);
1503         }
1504
1505         $r = q("SELECT `resource-id`, `id`, `filename`, type, `album`, max(`scale`) AS `scale` FROM `photo`
1506                 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s'  
1507                 $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d",
1508                 intval($a->data['user']['uid']),
1509                 dbesc('Contact Photos'),
1510                 dbesc( t('Contact Photos')),
1511                 intval($a->pager['start']),
1512                 intval($a->pager['itemspage'])
1513         );
1514
1515
1516
1517         $photos = array();
1518         if(count($r)) {
1519                 $twist = 'rotright';
1520                 foreach($r as $rr) {
1521                         if($twist == 'rotright')
1522                                 $twist = 'rotleft';
1523                         else
1524                                 $twist = 'rotright';
1525                         $ext = $phototypes[$rr['type']];
1526                         
1527                         $photos[] = array(
1528                                 'id'       => $rr['id'],
1529                                 'twist'    => ' ' . $twist . rand(2,4),
1530                                 'link'          => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'],
1531                                 'title'         => t('View Photo'),
1532                                 'src'           => $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . ((($rr['scale']) == 6) ? 4 : $rr['scale']) . '.' . $ext,
1533                                 'alt'           => template_escape($rr['filename']),
1534                                 'album' => array(
1535                                         'link'  => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($rr['album']),
1536                                         'name'  => template_escape($rr['album']),
1537                                         'alt'   => t('View Album'),
1538                                 ),
1539                                 
1540                         );
1541                 }
1542         }
1543         
1544         $tpl = get_markup_template('photos_recent.tpl'); 
1545         $o .= replace_macros($tpl,array(
1546                 '$title' => t('Recent Photos'),
1547                 '$can_post' => $can_post,
1548                 '$upload' => array(t('Upload New Photos'), $a->get_baseurl().'/photos/'.$a->data['user']['nickname'].'/upload'),
1549                 '$photos' => $photos,
1550         ));
1551
1552         
1553         $o .= paginate($a);
1554         return $o;
1555 }
1556