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