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