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