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