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