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