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