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