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