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