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