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