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