Example #1
0
function attach_init(&$a)
{
    if ($a->argc != 2) {
        notice(t('Item not available.') . EOL);
        return;
    }
    $item_id = intval($a->argv[1]);
    // Check for existence, which will also provide us the owner uid
    $r = q("SELECT * FROM `attach` WHERE `id` = %d LIMIT 1", intval($item_id));
    if (!count($r)) {
        notice(t('Item was not found.') . EOL);
        return;
    }
    $sql_extra = permissions_sql($r[0]['uid']);
    // Now we'll see if we can access the attachment
    $r = q("SELECT * FROM `attach` WHERE `id` = '%d' {$sql_extra} LIMIT 1", dbesc($item_id));
    if (!count($r)) {
        notice(t('Permission denied.') . EOL);
        return;
    }
    // Use quotes around the filename to prevent a "multiple Content-Disposition"
    // error in Chrome for filenames with commas in them
    header('Content-type: ' . $r[0]['filetype']);
    header('Content-length: ' . $r[0]['filesize']);
    if (isset($_GET['attachment']) && $_GET['attachment'] === '0') {
        header('Content-disposition: filename="' . $r[0]['filename'] . '"');
    } else {
        header('Content-disposition: attachment; filename="' . $r[0]['filename'] . '"');
    }
    echo $r[0]['data'];
    killme();
    // NOTREACHED
}
Example #2
0
function attach_init(&$a)
{
    if ($a->argc != 2) {
        notice(t('Item not available.') . EOL);
        return;
    }
    $item_id = intval($a->argv[1]);
    // Check for existence, which will also provide us the owner uid
    $r = q("SELECT * FROM `attach` WHERE `id` = %d LIMIT 1", intval($item_id));
    if (!count($r)) {
        notice(t('Item was not found.') . EOL);
        return;
    }
    $sql_extra = permissions_sql($r[0]['uid']);
    // Now we'll see if we can access the attachment
    $r = q("SELECT * FROM `attach` WHERE `id` = '%d' {$sql_extra} LIMIT 1", dbesc($item_id));
    if (!count($r)) {
        notice(t('Permission denied.') . EOL);
        return;
    }
    header('Content-type: ' . $r[0]['filetype']);
    header('Content-disposition: attachment; filename=' . $r[0]['filename']);
    echo $r[0]['data'];
    killme();
    // NOTREACHED
}
Example #3
0
 /**
  * Copied from include/widgets.php::widget_album() with a modification to get the profile_uid from
  * the input array as in widget_item()
  * @param type $name
  * @return string
  */
 function embedphotos_widget_album($args)
 {
     $channel_id = 0;
     if (array_key_exists('channel', $args)) {
         $channel = $args['channel'];
     }
     $channel_id = intval($channel['channel_id']);
     if (!$channel_id) {
         $channel_id = \App::$profile_uid;
     }
     if (!$channel_id) {
         return '';
     }
     $owner_uid = $channel_id;
     require_once 'include/security.php';
     $sql_extra = permissions_sql($channel_id);
     if (!perm_is_allowed($channel_id, get_observer_hash(), 'view_storage')) {
         return '';
     }
     if ($args['album']) {
         $album = $args['album'];
     }
     if ($args['title']) {
         $title = $args['title'];
     }
     /** 
      * This may return incorrect permissions if you have multiple directories of the same name.
      * It is a limitation of the photo table using a name for a photo album instead of a folder hash
      */
     if ($album) {
         $x = q("select hash from attach where filename = '%s' and uid = %d limit 1", dbesc($album), intval($owner_uid));
         if ($x) {
             $y = attach_can_view_folder($owner_uid, get_observer_hash(), $x[0]['hash']);
             if (!$y) {
                 return '';
             }
         }
     }
     $order = 'DESC';
     $r = q("SELECT p.resource_id, p.id, p.filename, p.mimetype, p.imgscale, p.description, p.created FROM photo p INNER JOIN\n\t\t\t\t(SELECT resource_id, max(imgscale) imgscale FROM photo WHERE uid = %d AND album = '%s' AND imgscale <= 4 AND photo_usage IN ( %d, %d ) {$sql_extra} GROUP BY resource_id) ph \n\t\t\t\tON (p.resource_id = ph.resource_id AND p.imgscale = ph.imgscale)\n\t\t\tORDER BY created {$order}", intval($owner_uid), dbesc($album), intval(PHOTO_NORMAL), intval(PHOTO_PROFILE));
     $photos = array();
     if (count($r)) {
         $twist = 'rotright';
         foreach ($r as $rr) {
             if ($twist == 'rotright') {
                 $twist = 'rotleft';
             } else {
                 $twist = 'rotright';
             }
             $ext = $phototypes[$rr['mimetype']];
             $imgalt_e = $rr['filename'];
             $desc_e = $rr['description'];
             $imagelink = z_root() . '/photos/' . \App::$data['channel']['channel_address'] . '/image/' . $rr['resource_id'] . ($_GET['order'] === 'posted' ? '?f=&order=posted' : '');
             $photos[] = array('id' => $rr['id'], 'twist' => ' ' . $twist . rand(2, 4), 'link' => $imagelink, 'title' => t('View Photo'), 'src' => z_root() . '/photo/' . $rr['resource_id'] . '-' . $rr['imgscale'] . '.' . $ext, 'alt' => $imgalt_e, 'desc' => $desc_e, 'ext' => $ext, 'hash' => $rr['resource_id'], 'unknown' => t('Unknown'));
         }
     }
     $tpl = get_markup_template('photo_album.tpl');
     $o .= replace_macros($tpl, array('$photos' => $photos, '$album' => $title ? $title : $album, '$album_id' => rand(), '$album_edit' => array(t('Edit Album'), $album_edit), '$can_post' => false, '$upload' => array(t('Upload'), z_root() . '/photos/' . \App::$profile['channel_address'] . '/upload/' . bin2hex($album)), '$order' => false, '$upload_form' => $upload_form, '$no_fullscreen_btn' => true));
     return $o;
 }
Example #4
0
File: menu.php Project: Mauru/red
function menu_fetch($name, $uid, $observer_xchan)
{
    $sql_options = permissions_sql($uid);
    $r = q("select * from menu where menu_channel_id = %d and menu_name = '%s' limit 1", intval($uid), dbesc($name));
    if ($r) {
        $x = q("select * from menu_item where mitem_menu_id = %d and mitem_channel_id = %d\n\t\t\t{$sql_options} \n\t\t\torder by mitem_order asc, mitem_desc asc", intval($r[0]['menu_id']), intval($uid));
        return array('menu' => $r[0], 'items' => $x);
    }
    return null;
}
Example #5
0
 function get()
 {
     $status = strip_tags($_REQUEST['status']);
     $room_id = intval(\App::$data['chat']['room_id']);
     $stopped = x($_REQUEST, 'stopped') && intval($_REQUEST['stopped']) ? true : false;
     if ($status && $room_id) {
         $x = q("select channel_address from channel where channel_id = %d limit 1", intval(\App::$data['chat']['uid']));
         $r = q("update chatpresence set cp_status = '%s', cp_last = '%s' where cp_room = %d and cp_xchan = '%s' and cp_client = '%s'", dbesc($status), dbesc(datetime_convert()), intval($room_id), dbesc(get_observer_hash()), dbesc($_SERVER['REMOTE_ADDR']));
         goaway(z_root() . '/chat/' . $x[0]['channel_address'] . '/' . $room_id);
     }
     if (!$stopped) {
         $lastseen = intval($_REQUEST['last']);
         $ret = array('success' => false);
         $sql_extra = permissions_sql(\App::$data['chat']['uid']);
         $r = q("select * from chatroom where cr_uid = %d and cr_id = %d {$sql_extra}", intval(\App::$data['chat']['uid']), intval(\App::$data['chat']['room_id']));
         if (!$r) {
             json_return_and_die($ret);
         }
         $inroom = array();
         $r = q("select * from chatpresence left join xchan on xchan_hash = cp_xchan where cp_room = %d order by xchan_name", intval(\App::$data['chat']['room_id']));
         if ($r) {
             foreach ($r as $rr) {
                 switch ($rr['cp_status']) {
                     case 'away':
                         $status = t('Away');
                         $status_class = 'away';
                         break;
                     case 'online':
                     default:
                         $status = t('Online');
                         $status_class = 'online';
                         break;
                 }
                 $inroom[] = array('img' => zid($rr['xchan_photo_m']), 'img_type' => $rr['xchan_photo_mimetype'], 'name' => $rr['xchan_name'], 'status' => $status, 'status_class' => $status_class);
             }
         }
         $chats = array();
         $r = q("select * from chat left join xchan on chat_xchan = xchan_hash where chat_room = %d and chat_id > %d order by created", intval(\App::$data['chat']['room_id']), intval($lastseen));
         if ($r) {
             foreach ($r as $rr) {
                 $chats[] = array('id' => $rr['chat_id'], 'img' => zid($rr['xchan_photo_m']), 'img_type' => $rr['xchan_photo_mimetype'], 'name' => $rr['xchan_name'], 'isotime' => datetime_convert('UTC', date_default_timezone_get(), $rr['created'], 'c'), 'localtime' => datetime_convert('UTC', date_default_timezone_get(), $rr['created'], 'r'), 'text' => smilies(bbcode($rr['chat_text'])), 'self' => get_observer_hash() == $rr['chat_xchan'] ? 'self' : '');
             }
         }
     }
     $r = q("update chatpresence set cp_last = '%s' where cp_room = %d and cp_xchan = '%s' and cp_client = '%s'", dbesc(datetime_convert()), intval(\App::$data['chat']['room_id']), dbesc(get_observer_hash()), dbesc($_SERVER['REMOTE_ADDR']));
     $ret['success'] = true;
     if (!$stopped) {
         $ret['inroom'] = $inroom;
         $ret['chats'] = $chats;
     }
     json_return_and_die($ret);
 }
Example #6
0
 function init()
 {
     $prvcachecontrol = false;
     $streaming = null;
     $channel = null;
     switch (argc()) {
         case 4:
             $person = argv(3);
             $res = argv(2);
             $type = argv(1);
             break;
         case 2:
             $photo = argv(1);
             break;
         case 1:
         default:
             killme();
             // NOTREACHED
     }
     $observer_xchan = get_observer_hash();
     $default = get_default_profile_photo();
     if (isset($type)) {
         /**
          * Profile photos - Access controls on default profile photos are not honoured since they need to be exchanged with remote sites.
          * 
          */
         if ($type === 'profile') {
             switch ($res) {
                 case 'm':
                     $resolution = 5;
                     $default = get_default_profile_photo(80);
                     break;
                 case 's':
                     $resolution = 6;
                     $default = get_default_profile_photo(48);
                     break;
                 case 'l':
                 default:
                     $resolution = 4;
                     break;
             }
         }
         $uid = $person;
         $d = ['imgscale' => $resolution, 'channel_id' => $uid, 'default' => $default, 'data' => '', 'mimetype' => ''];
         call_hooks('get_profile_photo', $d);
         $resolution = $d['imgscale'];
         $uid = $d['channel_id'];
         $default = $d['default'];
         $data = $d['data'];
         $mimetype = $d['mimetype'];
         if (!$data) {
             $r = q("SELECT * FROM photo WHERE imgscale = %d AND uid = %d AND photo_usage = %d LIMIT 1", intval($resolution), intval($uid), intval(PHOTO_PROFILE));
             if ($r) {
                 $data = dbunescbin($r[0]['content']);
                 $mimetype = $r[0]['mimetype'];
             }
             if (intval($r[0]['os_storage'])) {
                 $data = file_get_contents($data);
             }
         }
         if (!$data) {
             $data = file_get_contents($default);
         }
         if (!$mimetype) {
             $mimetype = 'image/png';
         }
     } else {
         /**
          * Other photos
          */
         /* Check for a cookie to indicate display pixel density, in order to detect high-resolution
         			   displays. This procedure was derived from the "Retina Images" by Jeremey Worboys,
         			   used in accordance with the Creative Commons Attribution 3.0 Unported License.
         			   Project link: https://github.com/Retina-Images/Retina-Images
         			   License link: http://creativecommons.org/licenses/by/3.0/
         			*/
         $cookie_value = false;
         if (isset($_COOKIE['devicePixelRatio'])) {
             $cookie_value = intval($_COOKIE['devicePixelRatio']);
         } else {
             // Force revalidation of cache on next request
             $cache_directive = 'no-cache';
             $status = 'no cookie';
         }
         $resolution = 0;
         if (strpos($photo, '.') !== false) {
             $photo = substr($photo, 0, strpos($photo, '.'));
         }
         if (substr($photo, -2, 1) == '-') {
             $resolution = intval(substr($photo, -1, 1));
             $photo = substr($photo, 0, -2);
             // If viewing on a high-res screen, attempt to serve a higher resolution image:
             if ($resolution == 2 && $cookie_value > 1) {
                 $resolution = 1;
             }
         }
         // If using resolution 1, make sure it exists before proceeding:
         if ($resolution == 1) {
             $r = q("SELECT uid FROM photo WHERE resource_id = '%s' AND imgscale = %d LIMIT 1", dbesc($photo), intval($resolution));
             if (!$r) {
                 $resolution = 2;
             }
         }
         $r = q("SELECT uid FROM photo WHERE resource_id = '%s' AND imgscale = %d LIMIT 1", dbesc($photo), intval($resolution));
         if ($r) {
             $allowed = $r[0]['uid'] ? perm_is_allowed($r[0]['uid'], $observer_xchan, 'view_storage') : true;
             $sql_extra = permissions_sql($r[0]['uid']);
             if (!$sql_extra) {
                 $sql_extra = ' and true ';
             }
             // Only check permissions on normal photos. Those photos we don't check includes
             // profile photos, xchan photos (which are also profile photos), 'thing' photos,
             // and cover photos
             $sql_extra = " and (( photo_usage = 0 {$sql_extra} ) or photo_usage != 0 )";
             $channel = channelx_by_n($r[0]['uid']);
             // Now we'll see if we can access the photo
             $r = q("SELECT * FROM photo WHERE resource_id = '%s' AND imgscale = %d {$sql_extra} LIMIT 1", dbesc($photo), intval($resolution));
             if ($r && $allowed) {
                 $data = dbunescbin($r[0]['content']);
                 $mimetype = $r[0]['mimetype'];
                 if (intval($r[0]['os_storage'])) {
                     $streaming = $data;
                 }
             } else {
                 // Does the picture exist? It may be a remote person with no credentials,
                 // but who should otherwise be able to view it. Show a default image to let
                 // them know permissions was denied. It may be possible to view the image
                 // through an authenticated profile visit.
                 // There won't be many completely unauthorised people seeing this because
                 // they won't have the photo link, so there's a reasonable chance that the person
                 // might be able to obtain permission to view it.
                 $r = q("SELECT * FROM `photo` WHERE `resource_id` = '%s' AND `imgscale` = %d LIMIT 1", dbesc($photo), intval($resolution));
                 if ($r) {
                     logger('mod_photo: forbidden. ' . \App::$query_string);
                     $observer = \App::get_observer();
                     logger('mod_photo: observer = ' . ($observer ? $observer['xchan_addr'] : '(not authenticated)'));
                     $data = file_get_contents('images/nosign.png');
                     $mimetype = 'image/png';
                     $prvcachecontrol = true;
                 }
             }
         }
     }
     if (!isset($data)) {
         if (isset($resolution)) {
             switch ($resolution) {
                 case 4:
                     $data = file_get_contents(get_default_profile_photo());
                     $mimetype = 'image/png';
                     break;
                 case 5:
                     $data = file_get_contents(get_default_profile_photo(80));
                     $mimetype = 'image/png';
                     break;
                 case 6:
                     $data = file_get_contents(get_default_profile_photo(48));
                     $mimetype = 'image/png';
                     break;
                 default:
                     killme();
                     // NOTREACHED
                     break;
             }
         }
     }
     if (isset($res) && intval($res) && $res < 500) {
         $ph = photo_factory($data, $mimetype);
         if ($ph->is_valid()) {
             $ph->scaleImageSquare($res);
             $data = $ph->imageString();
             $mimetype = $ph->getType();
         }
     }
     // Writing in cachefile
     if (isset($cachefile) && $cachefile != '') {
         file_put_contents($cachefile, $data);
     }
     if (function_exists('header_remove')) {
         header_remove('Pragma');
         header_remove('pragma');
     }
     header("Content-type: " . $mimetype);
     if ($prvcachecontrol) {
         // it is a private photo that they have no permission to view.
         // tell the browser not to cache it, in case they authenticate
         // and subsequently have permission to see it
         header("Cache-Control: no-store, no-cache, must-revalidate");
     } else {
         // The photo cache default is 1 day to provide a privacy trade-off,
         // as somebody reducing photo permissions on a photo that is already
         // "in the wild" won't be able to stop the photo from being viewed
         // for this amount amount of time once it is in the browser cache.
         // The privacy expectations of your site members and their perception
         // of privacy where it affects the entire project may be affected.
         // This has performance considerations but we highly recommend you
         // leave it alone.
         $cache = get_config('system', 'photo_cache_time');
         if (!$cache) {
             $cache = 3600 * 24;
         }
         // 1 day
         header("Expires: " . gmdate("D, d M Y H:i:s", time() + $cache) . " GMT");
         header("Cache-Control: max-age=" . $cache);
     }
     // If it's a file resource, stream it.
     if ($streaming && $channel) {
         if (strpos($streaming, 'store') !== false) {
             $istream = fopen($streaming, 'rb');
         } else {
             $istream = fopen('store/' . $channel['channel_address'] . '/' . $streaming, 'rb');
         }
         $ostream = fopen('php://output', 'wb');
         if ($istream && $ostream) {
             pipe_streams($istream, $ostream);
             fclose($istream);
             fclose($ostream);
         }
     } else {
         echo $data;
     }
     killme();
     // NOTREACHED
 }
Example #7
0
function chat_content(&$a)
{
    if (local_channel()) {
        $channel = $a->get_channel();
    }
    $ob = $a->get_observer();
    $observer = get_observer_hash();
    if (!$observer) {
        notice(t('Permission denied.') . EOL);
        return;
    }
    if (!perm_is_allowed($a->profile['profile_uid'], $observer, 'chat')) {
        notice(t('Permission denied.') . EOL);
        return;
    }
    if (argc() > 3 && intval(argv(2)) && argv(3) === 'leave') {
        chatroom_leave($observer, argv(2), $_SERVER['REMOTE_ADDR']);
        goaway(z_root() . '/channel/' . argv(1));
    }
    if (argc() > 3 && intval(argv(2)) && argv(3) === 'status') {
        $ret = array('success' => false);
        $room_id = intval(argv(2));
        if (!$room_id || !$observer) {
            return;
        }
        $r = q("select * from chatroom where cr_id = %d limit 1", intval($room_id));
        if (!$r) {
            json_return_and_die($ret);
        }
        require_once 'include/security.php';
        $sql_extra = permissions_sql($r[0]['cr_uid']);
        $x = q("select * from chatroom where cr_id = %d and cr_uid = %d {$sql_extra} limit 1", intval($room_id), intval($r[0]['cr_uid']));
        if (!$x) {
            json_return_and_die($ret);
        }
        $y = q("select count(*) as total from chatpresence where cp_room = %d", intval($room_id));
        if ($y) {
            $ret['success'] = true;
            $ret['chatroom'] = $r[0]['cr_name'];
            $ret['inroom'] = $y[0]['total'];
        }
        // figure out how to present a timestamp of the last activity, since we don't know the observer's timezone.
        $z = q("select created from chat where chat_room = %d order by created desc limit 1", intval($room_id));
        if ($z) {
            $ret['last'] = $z[0]['created'];
        }
        json_return_and_die($ret);
    }
    if (argc() > 2 && intval(argv(2))) {
        $room_id = intval(argv(2));
        $bookmark_link = get_bookmark_link($ob);
        $x = chatroom_enter($observer, $room_id, 'online', $_SERVER['REMOTE_ADDR']);
        if (!$x) {
            return;
        }
        $x = q("select * from chatroom where cr_id = %d and cr_uid = %d {$sql_extra} limit 1", intval($room_id), intval($a->profile['profile_uid']));
        if ($x) {
            $acl = new AccessList(false);
            $acl->set($x[0]);
            $private = $acl->is_private();
            $room_name = $x[0]['cr_name'];
            if ($bookmark_link) {
                $bookmark_link .= '&url=' . z_root() . '/chat/' . argv(1) . '/' . argv(2) . '&title=' . urlencode($x[0]['cr_name']) . ($private ? '&private=1' : '') . '&ischat=1';
            }
        } else {
            notice(t('Room not found') . EOL);
            return;
        }
        $o = replace_macros(get_markup_template('chat.tpl'), array('$is_owner' => local_channel() && local_channel() == $x[0]['cr_uid'] ? true : false, '$room_name' => $room_name, '$room_id' => $room_id, '$baseurl' => z_root(), '$nickname' => argv(1), '$submit' => t('Submit'), '$leave' => t('Leave Room'), '$drop' => t('Delete This Room'), '$away' => t('I am away right now'), '$online' => t('I am online'), '$bookmark_link' => $bookmark_link, '$bookmark' => t('Bookmark this room')));
        return $o;
    }
    if (local_channel() && argc() > 2 && argv(2) === 'new') {
        $acl = new AccessList($channel);
        $channel_acl = $acl->get();
        require_once 'include/acl_selectors.php';
        $o = replace_macros(get_markup_template('chatroom_new.tpl'), array('$header' => t('New Chatroom'), '$name' => array('room_name', t('Chatroom Name'), '', ''), '$chat_expire' => array('chat_expire', t('Expiration of chats (minutes)'), 120, ''), '$permissions' => t('Permissions'), '$acl' => populate_acl($channel_acl, false), '$submit' => t('Submit')));
        return $o;
    }
    require_once 'include/conversation.php';
    $o = profile_tabs($a, local_channel() && local_channel() == $a->profile['profile_uid'] ? true : false, $a->profile['channel_address']);
    require_once 'include/widgets.php';
    $o .= replace_macros(get_markup_template('chatrooms.tpl'), array('$header' => sprintf(t('%1$s\'s Chatrooms'), $a->profile['name']), '$baseurl' => z_root(), '$nickname' => $channel['channel_address'], '$rooms' => widget_chatroom_list(array()), '$newroom' => t('New Chatroom'), '$is_owner' => local_channel() && local_channel() == $a->profile['profile_uid'] ? 1 : 0));
    return $o;
}
Example #8
0
function photo_init(&$a)
{
    global $_SERVER;
    $prvcachecontrol = false;
    $file = "";
    switch ($a->argc) {
        case 4:
            $person = $a->argv[3];
            $customres = intval($a->argv[2]);
            $type = $a->argv[1];
            break;
        case 3:
            $person = $a->argv[2];
            $type = $a->argv[1];
            break;
        case 2:
            $photo = $a->argv[1];
            $file = $photo;
            break;
        case 1:
        default:
            killme();
            // NOTREACHED
    }
    //	strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($localFileName)) {
    if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
        header('HTTP/1.1 304 Not Modified');
        header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
        header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
        header("Expires: " . gmdate("D, d M Y H:i:s", time() + 31536000) . " GMT");
        header("Cache-Control: max-age=31536000");
        if (function_exists('header_remove')) {
            header_remove('Last-Modified');
            header_remove('Expires');
            header_remove('Cache-Control');
        }
        exit;
    }
    $default = 'images/person-175.jpg';
    if (isset($type)) {
        /**
         * Profile photos
         */
        switch ($type) {
            case 'profile':
            case 'custom':
                $resolution = 4;
                break;
            case 'micro':
                $resolution = 6;
                $default = 'images/person-48.jpg';
                break;
            case 'avatar':
            default:
                $resolution = 5;
                $default = 'images/person-80.jpg';
                break;
        }
        $uid = str_replace(array('.jpg', '.png'), array('', ''), $person);
        $r = q("SELECT * FROM `photo` WHERE `scale` = %d AND `uid` = %d AND `profile` = 1 LIMIT 1", intval($resolution), intval($uid));
        if (count($r)) {
            $data = $r[0]['data'];
            $mimetype = $r[0]['type'];
        }
        if (!isset($data)) {
            $data = file_get_contents($default);
            $mimetype = 'image/jpeg';
        }
    } else {
        /**
         * Other photos
         */
        $resolution = 0;
        foreach (Photo::supportedTypes() as $m => $e) {
            $photo = str_replace(".{$e}", '', $photo);
        }
        if (substr($photo, -2, 1) == '-') {
            $resolution = intval(substr($photo, -1, 1));
            $photo = substr($photo, 0, -2);
        }
        $r = q("SELECT `uid` FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d LIMIT 1", dbesc($photo), intval($resolution));
        if (count($r)) {
            $sql_extra = permissions_sql($r[0]['uid']);
            // Now we'll see if we can access the photo
            $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d {$sql_extra} LIMIT 1", dbesc($photo), intval($resolution));
            $public = $r[0]['allow_cid'] == '' and $r[0]['allow_gid'] == '' and $r[0]['deny_cid'] == '' and $r[0]['deny_gid'] == '';
            if (count($r)) {
                $data = $r[0]['data'];
                $mimetype = $r[0]['type'];
            } else {
                // Does the picture exist? It may be a remote person with no credentials,
                // but who should otherwise be able to view it. Show a default image to let
                // them know permissions was denied. It may be possible to view the image
                // through an authenticated profile visit.
                // There won't be many completely unauthorised people seeing this because
                // they won't have the photo link, so there's a reasonable chance that the person
                // might be able to obtain permission to view it.
                $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d LIMIT 1", dbesc($photo), intval($resolution));
                if (count($r)) {
                    $data = file_get_contents('images/nosign.jpg');
                    $mimetype = 'image/jpeg';
                    $prvcachecontrol = true;
                }
            }
        }
    }
    if (!isset($data)) {
        if (isset($resolution)) {
            switch ($resolution) {
                case 4:
                    $data = file_get_contents('images/person-175.jpg');
                    $mimetype = 'image/jpeg';
                    break;
                case 5:
                    $data = file_get_contents('images/person-80.jpg');
                    $mimetype = 'image/jpeg';
                    break;
                case 6:
                    $data = file_get_contents('images/person-48.jpg');
                    $mimetype = 'image/jpeg';
                    break;
                default:
                    killme();
                    // NOTREACHED
                    break;
            }
        }
    }
    // Resize only if its not a GIF
    if ($mime != "image/gif") {
        $ph = new Photo($data, $mimetype);
        if ($ph->is_valid()) {
            if (isset($customres) && $customres > 0 && $customres < 500) {
                $ph->scaleImageSquare($customres);
            }
            $data = $ph->imageString();
            $mimetype = $ph->getType();
        }
    }
    if (function_exists('header_remove')) {
        header_remove('Pragma');
        header_remove('pragma');
    }
    header("Content-type: " . $mimetype);
    if ($prvcachecontrol) {
        // it is a private photo that they have no permission to view.
        // tell the browser not to cache it, in case they authenticate
        // and subsequently have permission to see it
        header("Cache-Control: no-store, no-cache, must-revalidate");
    } else {
        header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
        header('Etag: "' . md5($data) . '"');
        header("Expires: " . gmdate("D, d M Y H:i:s", time() + 31536000) . " GMT");
        header("Cache-Control: max-age=31536000");
    }
    echo $data;
    // If the photo is public and there is an existing photo directory store the photo there
    if ($public and $file != "") {
        if (is_dir($_SERVER["DOCUMENT_ROOT"] . "/photo")) {
            file_put_contents($_SERVER["DOCUMENT_ROOT"] . "/photo/" . $file, $data);
        }
    }
    killme();
    // NOTREACHED
}
Example #9
0
function display_content(&$a)
{
    if (get_config('system', 'block_public') && !local_user() && !remote_user()) {
        notice(t('Public access denied.') . EOL);
        return;
    }
    require_once "include/bbcode.php";
    require_once 'include/security.php';
    require_once 'include/conversation.php';
    $o = '<div id="live-display"></div>' . "\r\n";
    $a->page['htmlhead'] .= '<script>$(document).ready(function() {	$(".comment-edit-wrapper  textarea").contact_autocomplete(baseurl+"/acl"); });</script>';
    $nick = $a->argc > 1 ? $a->argv[1] : '';
    profile_load($a, $nick);
    $item_id = $a->argc > 2 ? intval($a->argv[2]) : 0;
    if (!$item_id) {
        $a->error = 404;
        notice(t('Item not found.') . EOL);
        return;
    }
    $groups = array();
    $contact = null;
    $remote_contact = false;
    if (remote_user()) {
        $contact_id = $_SESSION['visitor_id'];
        $groups = init_groups_visitor($contact_id);
        $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($contact_id), intval($a->profile['uid']));
        if (count($r)) {
            $contact = $r[0];
            $remote_contact = true;
        }
    }
    if (!$remote_contact) {
        if (local_user()) {
            $contact_id = $_SESSION['cid'];
            $contact = $a->contact;
        }
    }
    $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1", intval($a->profile['uid']));
    if (count($r)) {
        $a->page_contact = $r[0];
    }
    $is_owner = local_user() && local_user() == $a->profile['profile_uid'] ? true : false;
    if ($a->profile['hidewall'] && !$is_owner && !$remote_contact) {
        notice(t('Access to this profile has been restricted.') . EOL);
        return;
    }
    $sql_extra = permissions_sql($a->profile['uid'], $remote_contact, $groups);
    $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, \n\t\t`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,\n\t\t`contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`, \n\t\t`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`\n\t\tFROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\tAND `item`.`parent` = ( SELECT `parent` FROM `item` WHERE ( `id` = '%s' OR `uri` = '%s' ))\n\t\t{$sql_extra}\n\t\tORDER BY `parent` DESC, `gravity` ASC, `id` ASC ", intval($a->profile['uid']), dbesc($item_id), dbesc($item_id));
    if (count($r)) {
        if (local_user() && local_user() == $a->profile['uid']) {
            q("UPDATE `item` SET `unseen` = 0 \n\t\t\t\tWHERE `parent` = %d AND `unseen` = 1", intval($r[0]['parent']));
        }
        $o .= conversation($a, $r, 'display', false);
    } else {
        $r = q("SELECT `id` FROM `item` WHERE `id` = '%s' OR `uri` = '%s' LIMIT 1", dbesc($item_id), dbesc($item_id));
        if (count($r)) {
            if ($r[0]['deleted']) {
                notice(t('Item has been removed.') . EOL);
            } else {
                notice(t('Permission denied.') . EOL);
            }
        } else {
            notice(t('Item not found.') . EOL);
        }
    }
    return $o;
}
Example #10
0
function photos_content(&$a)
{
    // URLs:
    // photos/name
    // photos/name/upload
    // photos/name/upload/xxxxx (xxxxx is album name)
    // photos/name/album/xxxxx
    // photos/name/album/xxxxx/edit
    // photos/name/image/xxxxx
    // photos/name/image/xxxxx/edit
    if (get_config('system', 'block_public') && !local_user() && !remote_user()) {
        notice(t('Public access denied.') . EOL);
        return;
    }
    require_once 'include/bbcode.php';
    require_once 'include/security.php';
    require_once 'include/conversation.php';
    if (!x($a->data, 'user')) {
        notice(t('No photos selected') . EOL);
        return;
    }
    $_SESSION['photo_return'] = $a->cmd;
    //
    // Parse arguments
    //
    if ($a->argc > 3) {
        $datatype = $a->argv[2];
        $datum = $a->argv[3];
    } elseif ($a->argc > 2 && $a->argv[2] === 'upload') {
        $datatype = 'upload';
    } else {
        $datatype = 'summary';
    }
    if ($a->argc > 4) {
        $cmd = $a->argv[4];
    } else {
        $cmd = 'view';
    }
    //
    // Setup permissions structures
    //
    $can_post = false;
    $visitor = 0;
    $contact = null;
    $remote_contact = false;
    $owner_uid = $a->data['user']['uid'];
    $community_page = $a->data['user']['page-flags'] == PAGE_COMMUNITY ? true : false;
    if (local_user() && local_user() == $owner_uid) {
        $can_post = true;
    } else {
        if ($community_page && remote_user()) {
            $r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1", intval(remote_user()), intval($owner_uid));
            if (count($r)) {
                $can_post = true;
                $contact = $r[0];
                $remote_contact = true;
                $visitor = remote_user();
            }
        }
    }
    // perhaps they're visiting - but not a community page, so they wouldn't have write access
    if (remote_user() && !$visitor) {
        $contact_id = $_SESSION['visitor_id'];
        $groups = init_groups_visitor($contact_id);
        $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1", intval(remote_user()), intval($owner_uid));
        if (count($r)) {
            $contact = $r[0];
            $remote_contact = true;
        }
    }
    if (!$remote_contact) {
        if (local_user()) {
            $contact_id = $_SESSION['cid'];
            $contact = $a->contact;
        }
    }
    if ($a->data['user']['hidewall'] && local_user() != $owner_uid && !$remote_contact) {
        notice(t('Access to this item is restricted.') . EOL);
        return;
    }
    $sql_extra = permissions_sql($owner_uid, $remote_contact, $groups);
    $o = "";
    // tabs
    $_is_owner = local_user() && local_user() == $owner_uid;
    $o .= profile_tabs($a, $_is_owner, $a->data['user']['nickname']);
    //
    // dispatch request
    //
    if ($datatype === 'upload') {
        if (!$can_post) {
            notice(t('Permission denied.'));
            return;
        }
        $selname = $datum ? hex2bin($datum) : '';
        $albumselect = '<select id="photos-upload-album-select" name="album" size="4">';
        $albumselect .= '<option value="" ' . (!$selname ? ' selected="selected" ' : '') . '>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
        if (count($a->data['albums'])) {
            foreach ($a->data['albums'] as $album) {
                if ($album['album'] === '' || $album['album'] === 'Contact Photos' || $album['album'] === t('Contact Photos')) {
                    continue;
                }
                $selected = $selname === $album['album'] ? ' selected="selected" ' : '';
                $albumselect .= '<option value="' . $album['album'] . '"' . $selected . '>' . $album['album'] . '</option>';
            }
        }
        $celeb = $a->user['page-flags'] == PAGE_SOAPBOX || $a->user['page-flags'] == PAGE_COMMUNITY ? true : false;
        $albumselect .= '</select>';
        $uploader = '';
        $ret = array('post_url' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'], 'addon_text' => $uploader, 'default_upload' => true);
        call_hooks('photo_upload_form', $ret);
        $default_upload = '<input type="file" name="userfile" /> 	<div class="photos-upload-submit-wrapper" >
		<input type="submit" name="submit" value="' . t('Submit') . '" id="photos-upload-submit" /> </div>';
        $tpl = get_markup_template('photos_upload.tpl');
        $o .= replace_macros($tpl, array('$pagename' => t('Upload Photos'), '$sessid' => session_id(), '$nickname' => $a->data['user']['nickname'], '$newalbum' => t('New album name: '), '$existalbumtext' => t('or existing album name: '), '$nosharetext' => t('Do not show a status post for this upload'), '$albumselect' => template_escape($albumselect), '$permissions' => t('Permissions'), '$aclselect' => $visitor ? '' : template_escape(populate_acl($a->user, $celeb)), '$uploader' => $ret['addon_text'], '$default' => $ret['default_upload'] ? $default_upload : '', '$uploadurl' => $ret['post_url']));
        return $o;
    }
    if ($datatype === 'album') {
        $album = hex2bin($datum);
        $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s' \n\t\t\tAND `scale` <= 4 {$sql_extra} GROUP BY `resource-id`", intval($owner_uid), dbesc($album));
        if (count($r)) {
            $a->set_pager_total(count($r));
            $a->set_pager_itemspage(20);
        }
        $r = q("SELECT `resource-id`, `id`, `filename`, max(`scale`) AS `scale`, `desc` FROM `photo` WHERE `uid` = %d AND `album` = '%s' \n\t\t\tAND `scale` <= 4 {$sql_extra} GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d", intval($owner_uid), dbesc($album), intval($a->pager['start']), intval($a->pager['itemspage']));
        $o .= '<h3>' . $album . '</h3>';
        if ($cmd === 'edit') {
            if ($album !== t('Profile Photos') && $album !== 'Contact Photos' && $album !== t('Contact Photos')) {
                if ($can_post) {
                    $edit_tpl = get_markup_template('album_edit.tpl');
                    $o .= replace_macros($edit_tpl, array('$nametext' => t('New album name: '), '$nickname' => $a->data['user']['nickname'], '$album' => template_escape($album), '$hexalbum' => bin2hex($album), '$submit' => t('Submit'), '$dropsubmit' => t('Delete Album')));
                }
            }
        } else {
            if ($album !== t('Profile Photos') && $album !== 'Contact Photos' && $album !== t('Contact Photos')) {
                if ($can_post) {
                    $o .= '<div id="album-edit-link"><a href="' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '/edit' . '">' . t('Edit Album') . '</a></div>';
                }
            }
        }
        if ($can_post) {
            $o .= '<div class="photos-upload-link" ><a href="' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/upload/' . bin2hex($album) . '" >' . t('Upload New Photos') . '</a></div>';
        }
        $tpl = get_markup_template('photo_album.tpl');
        if (count($r)) {
            $twist = 'rotright';
        }
        foreach ($r as $rr) {
            if ($twist == 'rotright') {
                $twist = 'rotleft';
            } else {
                $twist = 'rotright';
            }
            $o .= replace_macros($tpl, array('$id' => $rr['id'], '$twist' => ' ' . $twist . rand(2, 4), '$photolink' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'], '$phototitle' => t('View Photo'), '$imgsrc' => $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . $rr['scale'] . '.jpg', '$imgalt' => template_escape($rr['filename']), '$desc' => template_escape($rr['desc'])));
        }
        $o .= '<div id="photo-album-end"></div>';
        $o .= paginate($a);
        return $o;
    }
    if ($datatype === 'image') {
        //$o = '';
        // fetch image, item containing image, then comments
        $ph = q("SELECT * FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' \n\t\t\t{$sql_extra} ORDER BY `scale` ASC ", intval($owner_uid), dbesc($datum));
        if (!count($ph)) {
            $ph = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' \n\t\t\t\tLIMIT 1", intval($owner_uid), dbesc($datum));
            if (count($ph)) {
                notice(t('Permission denied. Access to this item may be restricted.'));
            } else {
                notice(t('Photo not available') . EOL);
            }
            return;
        }
        $prevlink = '';
        $nextlink = '';
        $prvnxt = q("SELECT `resource-id` FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `scale` = 0 \n\t\t\t{$sql_extra} ORDER BY `created` DESC ", dbesc($ph[0]['album']), intval($owner_uid));
        if (count($prvnxt)) {
            for ($z = 0; $z < count($prvnxt); $z++) {
                if ($prvnxt[$z]['resource-id'] == $ph[0]['resource-id']) {
                    $prv = $z - 1;
                    $nxt = $z + 1;
                    if ($prv < 0) {
                        $prv = count($prvnxt) - 1;
                    }
                    if ($nxt >= count($prvnxt)) {
                        $nxt = 0;
                    }
                    break;
                }
            }
            $edit_suffix = $cmd === 'edit' && $can_post ? '/edit' : '';
            $prevlink = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . $edit_suffix;
            $nextlink = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . $edit_suffix;
        }
        if (count($ph) == 1) {
            $hires = $lores = $ph[0];
        }
        if (count($ph) > 1) {
            if ($ph[1]['scale'] == 2) {
                // original is 640 or less, we can display it directly
                $hires = $lores = $ph[0];
            } else {
                $hires = $ph[0];
                $lores = $ph[1];
            }
        }
        $album_link = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($ph[0]['album']);
        $tools = Null;
        $lock = Null;
        if ($can_post && $ph[0]['uid'] == $owner_uid) {
            $tools = array('edit' => array($a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $datum . ($cmd === 'edit' ? '' : '/edit'), $cmd === 'edit' ? t('View photo') : t('Edit photo')), 'profile' => array($a->get_baseurl() . '/profile_photo/use/' . $ph[0]['resource-id'], t('Use as profile photo')));
            // lock
            $lock = $ph[0]['uid'] == local_user() && (strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid']) || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid'])) ? t('Private Message') : Null;
        }
        if (!$cmd !== 'edit') {
            $a->page['htmlhead'] .= '<script>
				$(document).keydown(function(event) {' . "\n";
            if ($prevlink) {
                $a->page['htmlhead'] .= 'if(event.ctrlKey && event.keyCode == 37) { event.preventDefault(); window.location.href = \'' . $prevlink . '\'; }' . "\n";
            }
            if ($nextlink) {
                $a->page['htmlhead'] .= 'if(event.ctrlKey && event.keyCode == 39) { event.preventDefault(); window.location.href = \'' . $nextlink . '\'; }' . "\n";
            }
            $a->page['htmlhead'] .= '});</script>';
        }
        if ($prevlink) {
            $prevlink = array($prevlink, '<div class="icon prev"></div>');
        }
        $photo = array('href' => $a->get_baseurl() . '/photo/' . $hires['resource-id'] . '-' . $hires['scale'] . '.jpg', 'title' => t('View Full Size'), 'src' => $a->get_baseurl() . '/photo/' . $lores['resource-id'] . '-' . $lores['scale'] . '.jpg' . '?f=&_u=' . datetime_convert('', '', '', 'ymdhis'));
        if ($nextlink) {
            $nextlink = array($nextlink, '<div class="icon next"></div>');
        }
        // Do we have an item for this photo?
        $linked_items = q("SELECT * FROM `item` WHERE `resource-id` = '%s' {$sql_extra} LIMIT 1", dbesc($datum));
        if (count($linked_items)) {
            $link_item = $linked_items[0];
            $r = q("SELECT COUNT(*) AS `total`\n\t\t\t\tFROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\t\tWHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0 and `item`.`moderated` = 0\n\t\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\tAND `item`.`uid` = %d \n\t\t\t\t{$sql_extra} ", dbesc($link_item['uri']), dbesc($link_item['uri']), intval($link_item['uid']));
            if (count($r)) {
                $a->set_pager_total($r[0]['total']);
            }
            $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, \n\t\t\t\t`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`network`, \n\t\t\t\t`contact`.`rel`, `contact`.`thumb`, `contact`.`self`, \n\t\t\t\t`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`\n\t\t\t\tFROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\t\tWHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0 and `item`.`moderated` = 0\n\t\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\tAND `item`.`uid` = %d\n\t\t\t\t{$sql_extra}\n\t\t\t\tORDER BY `parent` DESC, `id` ASC LIMIT %d ,%d ", dbesc($link_item['uri']), dbesc($link_item['uri']), intval($link_item['uid']), intval($a->pager['start']), intval($a->pager['itemspage']));
            if (local_user() && local_user() == $link_item['uid']) {
                q("UPDATE `item` SET `unseen` = 0 WHERE `parent` = %d and `uid` = %d", intval($link_item['parent']), intval(local_user()));
            }
        }
        $tags = Null;
        if (count($linked_items) && strlen($link_item['tag'])) {
            $arr = explode(',', $link_item['tag']);
            // parse tags and add links
            $tag_str = '';
            foreach ($arr as $t) {
                if (strlen($tag_str)) {
                    $tag_str .= ', ';
                }
                $tag_str .= bbcode($t);
            }
            $tags = array(t('Tags: '), $tag_str);
            if ($cmd === 'edit') {
                $tags[] = $a->get_baseurl() . '/tagrm/' . $link_item['id'];
                $tags[] = t('[Remove any tag]');
            }
        }
        $edit = Null;
        if ($cmd === 'edit' && $can_post) {
            $edit_tpl = get_markup_template('photo_edit.tpl');
            $edit = replace_macros($edit_tpl, array('$id' => $ph[0]['id'], '$rotate' => t('Rotate CW'), '$album' => template_escape($ph[0]['album']), '$newalbum' => t('New album name'), '$nickname' => $a->data['user']['nickname'], '$resource_id' => $ph[0]['resource-id'], '$capt_label' => t('Caption'), '$caption' => template_escape($ph[0]['desc']), '$tag_label' => t('Add a Tag'), '$tags' => $link_item['tag'], '$permissions' => t('Permissions'), '$aclselect' => template_escape(populate_acl($ph[0])), '$help_tags' => t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping'), '$item_id' => count($linked_items) ? $link_item['id'] : 0, '$submit' => t('Submit'), '$delete' => t('Delete Photo')));
        }
        if (count($linked_items)) {
            $cmnt_tpl = get_markup_template('comment_item.tpl');
            $tpl = get_markup_template('photo_item.tpl');
            $return_url = $a->cmd;
            $like_tpl = get_markup_template('like_noshare.tpl');
            $likebuttons = '';
            if ($can_post || can_write_wall($a, $owner_uid)) {
                $likebuttons = replace_macros($like_tpl, array('$id' => $link_item['id'], '$likethis' => t("I like this (toggle)"), '$nolike' => t("I don't like this (toggle)"), '$share' => t('Share'), '$wait' => t('Please wait')));
            }
            $comments = '';
            if (!count($r)) {
                if ($can_post || can_write_wall($a, $owner_uid)) {
                    if ($link_item['last-child']) {
                        $comments .= replace_macros($cmnt_tpl, array('$return_path' => '', '$jsreload' => $return_url, '$type' => 'wall-comment', '$id' => $link_item['id'], '$parent' => $link_item['id'], '$profile_uid' => $owner_uid, '$mylink' => $contact['url'], '$mytitle' => t('This is you'), '$myphoto' => $contact['thumb'], '$comment' => t('Comment'), '$submit' => t('Submit'), '$preview' => t('Preview'), '$ww' => ''));
                    }
                }
            }
            $alike = array();
            $dlike = array();
            $like = '';
            $dislike = '';
            // display comments
            if (count($r)) {
                foreach ($r as $item) {
                    like_puller($a, $item, $alike, 'like');
                    like_puller($a, $item, $dlike, 'dislike');
                }
                $like = isset($alike[$link_item['id']]) ? format_like($alike[$link_item['id']], $alike[$link_item['id'] . '-l'], 'like', $link_item['id']) : '';
                $dislike = isset($dlike[$link_item['id']]) ? format_like($dlike[$link_item['id']], $dlike[$link_item['id'] . '-l'], 'dislike', $link_item['id']) : '';
                if ($can_post || can_write_wall($a, $owner_uid)) {
                    if ($link_item['last-child']) {
                        $comments .= replace_macros($cmnt_tpl, array('$return_path' => '', '$jsreload' => $return_url, '$type' => 'wall-comment', '$id' => $link_item['id'], '$parent' => $link_item['id'], '$profile_uid' => $owner_uid, '$mylink' => $contact['url'], '$mytitle' => t('This is you'), '$myphoto' => $contact['thumb'], '$comment' => t('Comment'), '$submit' => t('Submit'), '$ww' => ''));
                    }
                }
                foreach ($r as $item) {
                    $comment = '';
                    $template = $tpl;
                    $sparkle = '';
                    if ((activity_match($item['verb'], ACTIVITY_LIKE) || activity_match($item['verb'], ACTIVITY_DISLIKE)) && $item['id'] != $item['parent']) {
                        continue;
                    }
                    $redirect_url = $a->get_baseurl() . '/redir/' . $item['cid'];
                    if ($can_post || can_write_wall($a, $owner_uid)) {
                        if ($item['last-child']) {
                            $comments .= replace_macros($cmnt_tpl, array('$return_path' => '', '$jsreload' => $return_url, '$type' => 'wall-comment', '$id' => $item['item_id'], '$parent' => $item['parent'], '$profile_uid' => $owner_uid, '$mylink' => $contact['url'], '$mytitle' => t('This is you'), '$myphoto' => $contact['thumb'], '$comment' => t('Comment'), '$submit' => t('Submit'), '$ww' => ''));
                        }
                    }
                    if (local_user() && $item['contact-uid'] == local_user() && $item['network'] == 'dfrn' && !$item['self']) {
                        $profile_url = $redirect_url;
                        $sparkle = ' sparkle';
                    } else {
                        $profile_url = $item['url'];
                        $sparkle = '';
                    }
                    $diff_author = $item['url'] !== $item['author-link'] ? true : false;
                    $profile_name = strlen($item['author-name']) && $diff_author ? $item['author-name'] : $item['name'];
                    $profile_avatar = strlen($item['author-avatar']) && $diff_author ? $item['author-avatar'] : $item['thumb'];
                    $profile_link = $profile_url;
                    $drop = '';
                    if ($item['contact-id'] == remote_user() || $item['uid'] == local_user()) {
                        $drop = replace_macros(get_markup_template('photo_drop.tpl'), array('$id' => $item['id'], '$delete' => t('Delete')));
                    }
                    $comments .= replace_macros($template, array('$id' => $item['item_id'], '$profile_url' => $profile_link, '$name' => template_escape($profile_name), '$thumb' => $profile_avatar, '$sparkle' => $sparkle, '$title' => template_escape($item['title']), '$body' => template_escape(bbcode($item['body'])), '$ago' => relative_date($item['created']), '$indent' => $item['parent'] != $item['item_id'] ? ' comment' : '', '$drop' => $drop, '$comment' => $comment));
                }
            }
            $paginate = paginate($a);
        }
        $photo_tpl = get_markup_template('photo_view.tpl');
        $o .= replace_macros($photo_tpl, array('$id' => $ph[0]['id'], '$album' => array($album_link, template_escape($ph[0]['album'])), '$tools' => $tools, '$lock' => $lock, '$photo' => $photo, '$prevlink' => $prevlink, '$nextlink' => $nextlink, '$desc' => $ph[0]['desc'], '$tags' => template_escape($tags), '$edit' => $edit, '$likebuttons' => $likebuttons, '$like' => template_escape($like), '$dislike' => template_escape($dislike), '$comments' => $comments, '$paginate' => $paginate));
        return $o;
    }
    // Default - show recent photos with upload link (if applicable)
    //$o = '';
    $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' \n\t\t{$sql_extra} GROUP BY `resource-id`", intval($a->data['user']['uid']), dbesc('Contact Photos'), dbesc(t('Contact Photos')));
    if (count($r)) {
        $a->set_pager_total(count($r));
        $a->set_pager_itemspage(20);
    }
    $r = q("SELECT `resource-id`, `id`, `filename`, `album`, max(`scale`) AS `scale` FROM `photo`\n\t\tWHERE `uid` = %d AND `album` != '%s' AND `album` != '%s'  \n\t\t{$sql_extra} GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d", intval($a->data['user']['uid']), dbesc('Contact Photos'), dbesc(t('Contact Photos')), intval($a->pager['start']), intval($a->pager['itemspage']));
    $photos = array();
    if (count($r)) {
        $twist = 'rotright';
        foreach ($r as $rr) {
            if ($twist == 'rotright') {
                $twist = 'rotleft';
            } else {
                $twist = 'rotright';
            }
            $photos[] = array('id' => $rr['id'], 'twist' => ' ' . $twist . rand(2, 4), 'link' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'], 'title' => t('View Photo'), 'src' => $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . ($rr['scale'] == 6 ? 4 : $rr['scale']) . '.jpg', 'alt' => template_escape($rr['filename']), 'album' => array('link' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($rr['album']), 'name' => template_escape($rr['album']), 'alt' => t('View Album')));
        }
    }
    $tpl = get_markup_template('photos_recent.tpl');
    $o .= replace_macros($tpl, array('$title' => t('Recent Photos'), '$can_post' => $can_post, '$upload' => array(t('Upload New Photos'), $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/upload'), '$photos' => $photos));
    $o .= paginate($a);
    return $o;
}
Example #11
0
File: chat.php Project: Mauru/red
/**
 * create a chat message via API.
 * It is the caller's responsibility to enter the room.
 */
function chat_message($uid, $room_id, $xchan, $text)
{
    $ret = array('success' => false);
    if (!$text) {
        return;
    }
    $sql_extra = permissions_sql($uid);
    $r = q("select * from chatroom where cr_uid = %d and cr_id = %d {$sql_extra}", intval($uid), intval($room_id));
    if (!$r) {
        return $ret;
    }
    $arr = array('chat_room' => $room_id, 'chat_xchan' => $xchan, 'chat_text' => $text);
    call_hooks('chat_message', $arr);
    $x = q("insert into chat ( chat_room, chat_xchan, created, chat_text )\n\t\tvalues( %d, '%s', '%s', '%s' )", intval($room_id), dbesc($xchan), dbesc(datetime_convert()), dbesc($arr['chat_text']));
    $ret['success'] = true;
    return $ret;
}
Example #12
0
/**
 * @brief
 *
 * @param array $channel
 * @param array $observer
 * @param string $album default empty
 * @return boolean|array
 */
function photos_list_photos($channel, $observer, $album = '')
{
    $channel_id = $channel['channel_id'];
    $observer_xchan = $observer ? $observer['xchan_hash'] : '';
    if (!perm_is_allowed($channel_id, $observer_xchan, 'view_storage')) {
        return false;
    }
    $sql_extra = permissions_sql($channel_id);
    if ($album) {
        $sql_extra .= " and album = '" . protect_sprintf(dbesc($album)) . "' ";
    }
    $ret = array('success' => false);
    $r = q("select resource_id, created, edited, title, description, album, filename, mimetype, height, width, filesize, imgscale, photo_usage, allow_cid, allow_gid, deny_cid, deny_gid from photo where uid = %d and photo_usage in ( %d, %d ) {$sql_extra} ", intval($channel_id), intval(PHOTO_NORMAL), intval(PHOTO_PROFILE));
    if ($r) {
        for ($x = 0; $x < count($r); $x++) {
            $r[$x]['src'] = z_root() . '/photo/' . $r[$x]['resource_id'] . '-' . $r[$x]['imgscale'];
        }
        $ret['success'] = true;
        $ret['photos'] = $r;
    }
    return $ret;
}
Example #13
0
File: photos.php Project: Mauru/red
function photos_content(&$a)
{
    // URLs:
    // photos/name
    // photos/name/upload
    // photos/name/upload/xxxxx (xxxxx is album name)
    // photos/name/album/xxxxx
    // photos/name/album/xxxxx/edit
    // photos/name/image/xxxxx
    // photos/name/image/xxxxx/edit
    if (get_config('system', 'block_public') && !local_user() && !remote_user()) {
        notice(t('Public access denied.') . EOL);
        return;
    }
    require_once 'include/bbcode.php';
    require_once 'include/security.php';
    require_once 'include/conversation.php';
    if (!x($a->data, 'channel')) {
        notice(t('No photos selected') . EOL);
        return;
    }
    $ph = photo_factory('');
    $phototypes = $ph->supportedTypes();
    $_SESSION['photo_return'] = $a->cmd;
    //
    // Parse arguments
    //
    $can_comment = perm_is_allowed($a->profile['profile_uid'], get_observer_hash(), 'post_comments');
    if (argc() > 3) {
        $datatype = argv(2);
        $datum = argv(3);
    } elseif (argc() > 2 && argv(2) === 'upload') {
        $datatype = 'upload';
    } else {
        $datatype = 'summary';
    }
    if (argc() > 4) {
        $cmd = argv(4);
    } else {
        $cmd = 'view';
    }
    //
    // Setup permissions structures
    //
    $can_post = false;
    $visitor = 0;
    $owner_uid = $a->data['channel']['channel_id'];
    $owner_aid = $a->data['channel']['channel_account_id'];
    $observer = $a->get_observer();
    $can_post = perm_is_allowed($owner_uid, $observer['xchan_hash'], 'post_photos');
    $can_view = perm_is_allowed($owner_uid, $observer['xchan_hash'], 'view_photos');
    if (!$can_view) {
        notice(t('Access to this item is restricted.') . EOL);
        return;
    }
    $sql_extra = permissions_sql($owner_uid);
    $o = "";
    $o .= "<script> var profile_uid = " . $a->profile['profile_uid'] . "; var netargs = '?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
    // tabs
    $_is_owner = local_user() && local_user() == $owner_uid;
    $o .= profile_tabs($a, $_is_owner, $a->data['channel']['channel_address']);
    //
    // dispatch request
    //
    /**
     * Display upload form
     */
    if ($datatype === 'upload') {
        if (!$can_post) {
            notice(t('Permission denied.'));
            return;
        }
        if (array_key_exists('albums', $a->data)) {
            $albums = get_app()->data['albums'];
        } else {
            $albums = photos_albums_list($a->data['channel'], $a->data['observer']);
        }
        $selname = $datum ? hex2bin($datum) : '';
        $albumselect = '<select id="photos-upload-album-select" name="album" size="4">';
        $albumselect .= '<option value="" ' . (!$selname ? ' selected="selected" ' : '') . '>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
        if (count($albums['albums'])) {
            foreach ($albums['albums'] as $album) {
                if (!$album['text']) {
                    continue;
                }
                $selected = $selname === $album['text'] ? ' selected="selected" ' : '';
                $albumselect .= '<option value="' . $album['text'] . '"' . $selected . '>' . $album['text'] . '</option>';
            }
        }
        $albumselect .= '</select>';
        $uploader = '';
        $ret = array('post_url' => $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'], 'addon_text' => $uploader, 'default_upload' => true);
        call_hooks('photo_upload_form', $ret);
        $default_upload = '<input id="photos-upload-choose" type="file" name="userfile" /> 	<div class="photos-upload-submit-wrapper" >
		<input type="submit" name="submit" value="' . t('Submit') . '" id="photos-upload-submit" /> </div>';
        /* Show space usage */
        $r = q("select sum(size) as total from photo where aid = %d and scale = 0 ", intval($a->data['channel']['channel_account_id']));
        $limit = service_class_fetch($a->data['channel']['channel_id'], 'photo_upload_limit');
        if ($limit !== false) {
            $usage_message = sprintf(t("You have used %1\$.2f Mbytes of %2\$.2f Mbytes photo storage."), $r[0]['total'] / 1024000, $limit / 1024000);
        } else {
            $usage_message = sprintf(t('You have used %1$.2f Mbytes of photo storage.'), $r[0]['total'] / 1024000);
        }
        if ($_is_owner) {
            $channel = $a->get_channel();
            $channel_acl = array('allow_cid' => $channel['channel_allow_cid'], 'allow_gid' => $channel['channel_allow_gid'], 'deny_cid' => $channel['channel_deny_cid'], 'deny_gid' => $channel['channel_deny_gid']);
        }
        $albumselect_e = $albumselect;
        $aclselect_e = $_is_owner ? populate_acl($channel_acl, false) : '';
        $tpl = get_markup_template('photos_upload.tpl');
        $o .= replace_macros($tpl, array('$pagename' => t('Upload Photos'), '$sessid' => session_id(), '$usage' => $usage_message, '$nickname' => $a->data['channel']['channel_address'], '$newalbum' => t('New album name: '), '$existalbumtext' => t('or existing album name: '), '$nosharetext' => t('Do not show a status post for this upload'), '$albumselect' => $albumselect_e, '$permissions' => t('Permissions'), '$aclselect' => $aclselect_e, '$uploader' => $ret['addon_text'], '$default' => $ret['default_upload'] ? $default_upload : '', '$uploadurl' => $ret['post_url']));
        return $o;
    }
    /*
     * Display a single photo album
     */
    if ($datatype === 'album') {
        if (strlen($datum) & 1 || !ctype_xdigit($datum)) {
            notice(t('Album name could not be decoded') . EOL);
            logger('mod_photos: illegal album encoding: ' . $datum);
            $datum = '';
        }
        $album = hex2bin($datum);
        $r = q("SELECT `resource_id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s' \n\t\t\tAND `scale` <= 4 and (photo_flags = %d or photo_flags = %d ) {$sql_extra} GROUP BY `resource_id`", intval($owner_uid), dbesc($album), intval(PHOTO_NORMAL), intval(PHOTO_PROFILE));
        if (count($r)) {
            $a->set_pager_total(count($r));
            $a->set_pager_itemspage(60);
        }
        if ($_GET['order'] === 'posted') {
            $order = 'ASC';
        } else {
            $order = 'DESC';
        }
        $r = q("SELECT `resource_id`, `id`, `filename`, type, max(`scale`) AS `scale`, `description` FROM `photo` WHERE `uid` = %d AND `album` = '%s' \n\t\t\tAND `scale` <= 4 and (photo_flags = %d or photo_flags = %d ) {$sql_extra} GROUP BY `resource_id` ORDER BY `created` {$order} LIMIT %d , %d", intval($owner_uid), dbesc($album), intvaL(PHOTO_NORMAL), intval(PHOTO_PROFILE), intval($a->pager['start']), intval($a->pager['itemspage']));
        $o .= '<h3>' . $album . '</h3>';
        if ($cmd === 'edit') {
            if ($album !== t('Profile Photos') && $album !== 'Contact Photos' && $album !== t('Contact Photos')) {
                if ($can_post) {
                    if ($a->get_template_engine() === 'internal') {
                        $album_e = template_escape($album);
                    } else {
                        $album_e = $album;
                    }
                    $edit_tpl = get_markup_template('album_edit.tpl');
                    $o .= replace_macros($edit_tpl, array('$nametext' => t('New album name: '), '$nickname' => $a->data['channel']['channel_address'], '$album' => $album_e, '$hexalbum' => bin2hex($album), '$submit' => t('Submit'), '$dropsubmit' => t('Delete Album')));
                }
            }
        } else {
            if ($album !== t('Profile Photos') && $album !== 'Contact Photos' && $album !== t('Contact Photos')) {
                if ($can_post) {
                    $o .= '<div id="album-edit-link"><a href="' . $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/album/' . bin2hex($album) . '/edit' . '">' . t('Edit Album') . '</a></div>';
                }
            }
        }
        if ($_GET['order'] === 'posted') {
            $o .= '<div class="photos-upload-link" ><a href="' . $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/album/' . bin2hex($album) . '" >' . t('Show Newest First') . '</a></div>';
        } else {
            $o .= '<div class="photos-upload-link" ><a href="' . $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/album/' . bin2hex($album) . '?f=&order=posted" >' . t('Show Oldest First') . '</a></div>';
        }
        if ($can_post) {
            $o .= '<div class="photos-upload-link" ><a href="' . $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/upload/' . bin2hex($album) . '" >' . t('Upload New Photos') . '</a></div>';
        }
        $ajaxout = '';
        $tpl = get_markup_template('photo_album.tpl');
        if (count($r)) {
            $twist = 'rotright';
            $o .= "<script> var page_query = '" . $_GET['q'] . "'; var extra_args = '" . extra_query_args() . "' ; </script>";
            $o .= '<div id="photo-album-contents">';
            foreach ($r as $rr) {
                if ($twist == 'rotright') {
                    $twist = 'rotleft';
                } else {
                    $twist = 'rotright';
                }
                $ext = $phototypes[$rr['type']];
                $imgalt_e = $rr['filename'];
                $desc_e = $rr['description'];
                // prettyphoto has potential license issues, so we can no longer include it in core
                // The following lines would need to be modified so that they are provided in theme specific files
                // instead of core modules for themes that wish to make use of prettyphoto. I would suggest
                // the feature as a per-theme display option and putting the rel line inside a template.
                //				if(feature_enabled($a->data['channel']['channel_id'],'prettyphoto')){
                //				      $imagelink = ($a->get_baseurl() . '/photo/' . $rr['resource_id'] . '.' . $ext );
                //				      $rel=("prettyPhoto[pp_gal]");
                //				}
                //				else {
                $imagelink = $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/image/' . $rr['resource_id'] . ($_GET['order'] === 'posted' ? '?f=&order=posted' : '');
                $rel = "photo";
                //				}
                $tmp = replace_macros($tpl, array('$id' => $rr['id'], '$twist' => ' ' . $twist . rand(2, 4), '$photolink' => $imagelink, '$rel' => $rel, '$phototitle' => t('View Photo'), '$imgsrc' => $a->get_baseurl() . '/photo/' . $rr['resource_id'] . '-' . $rr['scale'] . '.' . $ext, '$imgalt' => $imgalt_e, '$desc' => $desc_e, '$ext' => $ext, '$hash' => $rr['resource_id']));
                if ($_REQUEST['aj']) {
                    $ajaxout .= $tmp;
                } else {
                    $o .= $tmp;
                }
            }
        }
        if ($_REQUEST['aj']) {
            if (!$r) {
                $ajaxout .= '<div id="content-complete"></div>';
            }
            echo $ajaxout;
            killme();
        }
        $o .= '<div id="page-end"></div>';
        $o .= '</div>';
        // photo-album-contents
        $o .= '<div id="photo-album-end"></div>';
        $o .= '<script>$(document).ready(function() { loadingPage = false;});</script>';
        $o .= '<div id="page-spinner"></div>';
        //		$o .= paginate($a);
        return $o;
    }
    /** 
     * Display one photo
     */
    if ($datatype === 'image') {
        // fetch image, item containing image, then comments
        $ph = q("SELECT aid,uid,xchan,resource_id,created,edited,title,`description`,album,filename,`type`,height,width,`size`,scale,profile,photo_flags,allow_cid,allow_gid,deny_cid,deny_gid FROM `photo` WHERE `uid` = %d AND `resource_id` = '%s' \n\t\t\tand (photo_flags = %d or photo_flags = %d ) {$sql_extra} ORDER BY `scale` ASC ", intval($owner_uid), dbesc($datum), intval(PHOTO_NORMAL), intval(PHOTO_PROFILE));
        if (!$ph) {
            /* Check again - this time without specifying permissions */
            $ph = q("SELECT id FROM photo WHERE uid = %d AND resource_id = '%s' \n\t\t\t\tand ( photo_flags = %d or photo_flags = %d )\n\t\t\t\tLIMIT 1", intval($owner_uid), dbesc($datum), intval(PHOTO_NORMAL), intval(PHOTO_PROFILE));
            if ($ph) {
                notice(t('Permission denied. Access to this item may be restricted.') . EOL);
            } else {
                notice(t('Photo not available') . EOL);
            }
            return;
        }
        $prevlink = '';
        $nextlink = '';
        if ($_GET['order'] === 'posted') {
            $order = 'ASC';
        } else {
            $order = 'DESC';
        }
        $prvnxt = q("SELECT `resource_id` FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `scale` = 0 \n\t\t\tand ( photo_flags = %d or photo_flags = %d ) {$sql_extra} ORDER BY `created` {$order} ", dbesc($ph[0]['album']), intval($owner_uid), intval(PHOTO_NORMAL), intval(PHOTO_PROFILE));
        if (count($prvnxt)) {
            for ($z = 0; $z < count($prvnxt); $z++) {
                if ($prvnxt[$z]['resource_id'] == $ph[0]['resource_id']) {
                    $prv = $z - 1;
                    $nxt = $z + 1;
                    if ($prv < 0) {
                        $prv = count($prvnxt) - 1;
                    }
                    if ($nxt >= count($prvnxt)) {
                        $nxt = 0;
                    }
                    break;
                }
            }
            $prevlink = $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/image/' . $prvnxt[$prv]['resource_id'] . ($_GET['order'] === 'posted' ? '?f=&order=posted' : '');
            $nextlink = $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/image/' . $prvnxt[$nxt]['resource_id'] . ($_GET['order'] === 'posted' ? '?f=&order=posted' : '');
        }
        if (count($ph) == 1) {
            $hires = $lores = $ph[0];
        }
        if (count($ph) > 1) {
            if ($ph[1]['scale'] == 2) {
                // original is 640 or less, we can display it directly
                $hires = $lores = $ph[0];
            } else {
                $hires = $ph[0];
                $lores = $ph[1];
            }
        }
        $album_link = $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/album/' . bin2hex($ph[0]['album']);
        $tools = Null;
        $lock = Null;
        if ($can_post && $ph[0]['uid'] == $owner_uid) {
            $tools = array('profile' => array($a->get_baseurl() . '/profile_photo/use/' . $ph[0]['resource_id'], t('Use as profile photo')));
            // lock
            $lock = $ph[0]['uid'] == local_user() && (strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid']) || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid'])) ? t('Private Message') : Null;
        }
        $a->page['htmlhead'] .= '<script>$(document).keydown(function(event) {' . "\n";
        if ($prevlink) {
            $a->page['htmlhead'] .= 'if(event.ctrlKey && event.keyCode == 37) { event.preventDefault(); window.location.href = \'' . $prevlink . '\'; }' . "\n";
        }
        if ($nextlink) {
            $a->page['htmlhead'] .= 'if(event.ctrlKey && event.keyCode == 39) { event.preventDefault(); window.location.href = \'' . $nextlink . '\'; }' . "\n";
        }
        $a->page['htmlhead'] .= '});</script>';
        if ($prevlink) {
            $prevlink = array($prevlink, '<i class="icon-backward photo-icons""></i>');
        }
        $photo = array('href' => $a->get_baseurl() . '/photo/' . $hires['resource_id'] . '-' . $hires['scale'] . '.' . $phototypes[$hires['type']], 'title' => t('View Full Size'), 'src' => $a->get_baseurl() . '/photo/' . $lores['resource_id'] . '-' . $lores['scale'] . '.' . $phototypes[$lores['type']] . '?f=&_u=' . datetime_convert('', '', '', 'ymdhis'));
        if ($nextlink) {
            $nextlink = array($nextlink, '<i class="icon-forward photo-icons"></i>');
        }
        // Do we have an item for this photo?
        $linked_items = q("SELECT * FROM item WHERE resource_id = '%s' and resource_type = 'photo' \n\t\t\t{$sql_extra} LIMIT 1", dbesc($datum));
        if ($linked_items) {
            xchan_query($linked_items);
            $linked_items = fetch_post_tags($linked_items, true);
            $link_item = $linked_items[0];
            $r = q("select * from item where parent_mid = '%s' \n\t\t\t\tand item_restrict = 0 and uid = %d {$sql_extra} ", dbesc($link_item['mid']), intval($link_item['uid']));
            if ($r) {
                xchan_query($r);
                $r = fetch_post_tags($r, true);
                $r = conv_sort($r, 'commented');
            }
            $tags = array();
            if ($link_item['term']) {
                $cnt = 0;
                foreach ($link_item['term'] as $t) {
                    $tags[$cnt] = array(0 => format_term_for_display($t));
                }
                if ($can_post && $ph[0]['uid'] == $owner_uid) {
                    $tags[$cnt][1] = 'tagrm?f=&item=' . $link_item['id'];
                    $tags[$cnt][2] = t('Remove');
                }
                $cnt++;
            }
            if (local_user() && local_user() == $link_item['uid']) {
                q("UPDATE `item` SET item_flags = (item_flags ^ %d) WHERE parent = %d and uid = %d and (item_flags & %d)", intval(ITEM_UNSEEN), intval($link_item['parent']), intval(local_user()), intval(ITEM_UNSEEN));
            }
        }
        //		logger('mod_photo: link_item' . print_r($link_item,true));
        // FIXME - remove this when we move to conversation module
        $r = $r[0]['children'];
        $edit = null;
        if ($can_post) {
            if (array_key_exists('albums', $a->data)) {
                $albums = get_app()->data['albums'];
            } else {
                $albums = photos_albums_list($a->data['channel'], $a->data['observer']);
            }
            $album_e = $ph[0]['album'];
            $caption_e = $ph[0]['description'];
            $aclselect_e = populate_acl($ph[0]);
            $edit = array('edit' => t('Edit photo'), 'id' => $ph[0]['id'], 'rotatecw' => t('Rotate CW (right)'), 'rotateccw' => t('Rotate CCW (left)'), 'albums' => $albums['albums'], 'album' => $album_e, 'newalbum' => t('New album name'), 'nickname' => $a->data['channel']['channel_address'], 'resource_id' => $ph[0]['resource_id'], 'capt_label' => t('Caption'), 'caption' => $caption_e, 'tag_label' => t('Add a Tag'), 'permissions' => t('Permissions'), 'aclselect' => $aclselect_e, 'help_tags' => t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping'), 'item_id' => count($linked_items) ? $link_item['id'] : 0, 'submit' => t('Submit'), 'delete' => t('Delete Photo'));
        }
        if (count($linked_items)) {
            $cmnt_tpl = get_markup_template('comment_item.tpl');
            $tpl = get_markup_template('photo_item.tpl');
            $return_url = $a->cmd;
            $like_tpl = get_markup_template('like_noshare.tpl');
            $likebuttons = '';
            if ($can_post || $can_comment) {
                $likebuttons = replace_macros($like_tpl, array('$id' => $link_item['id'], '$likethis' => t("I like this (toggle)"), '$nolike' => t("I don't like this (toggle)"), '$share' => t('Share'), '$wait' => t('Please wait')));
            }
            $comments = '';
            if (!count($r)) {
                if ($can_post || $can_comment) {
                    $comments .= replace_macros($cmnt_tpl, array('$return_path' => '', '$mode' => 'photos', '$jsreload' => $return_url, '$type' => 'wall-comment', '$id' => $link_item['id'], '$parent' => $link_item['id'], '$profile_uid' => $owner_uid, '$mylink' => $observer['xchan_url'], '$mytitle' => t('This is you'), '$myphoto' => $observer['xchan_photo_s'], '$comment' => t('Comment'), '$submit' => t('Submit'), '$preview' => t('Preview'), '$ww' => '', '$feature_encrypt' => false));
                }
            }
            $alike = array();
            $dlike = array();
            $like = '';
            $dislike = '';
            // display comments
            if ($r) {
                foreach ($r as $item) {
                    like_puller($a, $item, $alike, 'like');
                    like_puller($a, $item, $dlike, 'dislike');
                }
                $like = isset($alike[$link_item['id']]) ? format_like($alike[$link_item['id']], $alike[$link_item['id'] . '-l'], 'like', $link_item['id']) : '';
                $dislike = isset($dlike[$link_item['id']]) ? format_like($dlike[$link_item['id']], $dlike[$link_item['id'] . '-l'], 'dislike', $link_item['id']) : '';
                foreach ($r as $item) {
                    $comment = '';
                    $template = $tpl;
                    $sparkle = '';
                    if ((activity_match($item['verb'], ACTIVITY_LIKE) || activity_match($item['verb'], ACTIVITY_DISLIKE)) && $item['id'] != $item['parent']) {
                        continue;
                    }
                    $redirect_url = $a->get_baseurl() . '/redir/' . $item['cid'];
                    $profile_url = zid($item['author']['xchan_url']);
                    $sparkle = '';
                    $profile_name = $item['author']['xchan_name'];
                    $profile_avatar = $item['author']['xchan_photo_m'];
                    $profile_link = $profile_url;
                    $drop = '';
                    if ($observer['xchan_hash'] === $item['author_xchan'] || $observer['xchan_hash'] === $item['owner_xchan']) {
                        $drop = replace_macros(get_markup_template('photo_drop.tpl'), array('$id' => $item['id'], '$delete' => t('Delete')));
                    }
                    $name_e = $profile_name;
                    $title_e = $item['title'];
                    unobscure($item);
                    $body_e = prepare_text($item['body'], $item['mimetype']);
                    $comments .= replace_macros($template, array('$id' => $item['item_id'], '$mode' => 'photos', '$profile_url' => $profile_link, '$name' => $name_e, '$thumb' => $profile_avatar, '$sparkle' => $sparkle, '$title' => $title_e, '$body' => $body_e, '$ago' => relative_date($item['created']), '$indent' => $item['parent'] != $item['item_id'] ? ' comment' : '', '$drop' => $drop, '$comment' => $comment));
                }
                if ($can_post || $can_comment) {
                    $comments .= replace_macros($cmnt_tpl, array('$return_path' => '', '$jsreload' => $return_url, '$type' => 'wall-comment', '$id' => $link_item['id'], '$parent' => $link_item['id'], '$profile_uid' => $owner_uid, '$mylink' => $observer['xchan_url'], '$mytitle' => t('This is you'), '$myphoto' => $observer['xchan_photo_s'], '$comment' => t('Comment'), '$submit' => t('Submit'), '$ww' => ''));
                }
            }
            $paginate = paginate($a);
        }
        $album_e = array($album_link, $ph[0]['album']);
        $like_e = $like;
        $dislike_e = $dislike;
        $photo_tpl = get_markup_template('photo_view.tpl');
        $o .= replace_macros($photo_tpl, array('$id' => $ph[0]['id'], '$album' => $album_e, '$tools' => $tools, '$lock' => $lock, '$photo' => $photo, '$prevlink' => $prevlink, '$nextlink' => $nextlink, '$desc' => $ph[0]['description'], '$tag_hdr' => t('In This Photo:'), '$tags' => $tags, '$edit' => $edit, '$likebuttons' => $likebuttons, '$like' => $like_e, '$dislike' => $dislike_e, '$comments' => $comments, '$paginate' => $paginate));
        $a->data['photo_html'] = $o;
        return $o;
    }
    // Default - show recent photos with upload link (if applicable)
    //$o = '';
    $r = q("SELECT `resource_id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' \n\t\tand ( photo_flags = %d or photo_flags = %d ) {$sql_extra} GROUP BY `resource_id`", intval($a->data['channel']['channel_id']), dbesc('Contact Photos'), dbesc(t('Contact Photos')), intval(PHOTO_NORMAL), intval(PHOTO_PROFILE));
    if (count($r)) {
        $a->set_pager_total(count($r));
        $a->set_pager_itemspage(60);
    }
    $r = q("SELECT `resource_id`, `id`, `filename`, type, `album`, max(`scale`) AS `scale` FROM `photo`\n\t\tWHERE `uid` = %d AND `album` != '%s' AND `album` != '%s'\n\t\tand ( photo_flags = %d or photo_flags = %d )  \n\t\t{$sql_extra} GROUP BY `resource_id` ORDER BY `created` DESC LIMIT %d , %d", intval($a->data['channel']['channel_id']), dbesc('Contact Photos'), dbesc(t('Contact Photos')), intval(PHOTO_NORMAL), intval(PHOTO_PROFILE), intval($a->pager['start']), intval($a->pager['itemspage']));
    $photos = array();
    if (count($r)) {
        $twist = 'rotright';
        foreach ($r as $rr) {
            if ($twist == 'rotright') {
                $twist = 'rotleft';
            } else {
                $twist = 'rotright';
            }
            $ext = $phototypes[$rr['type']];
            if ($a->get_template_engine() === 'internal') {
                $alt_e = template_escape($rr['filename']);
                $name_e = template_escape($rr['album']);
            } else {
                $alt_e = $rr['filename'];
                $name_e = $rr['album'];
            }
            $photos[] = array('id' => $rr['id'], 'twist' => ' ' . $twist . rand(2, 4), 'link' => $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/image/' . $rr['resource_id'], 'title' => t('View Photo'), 'src' => $a->get_baseurl() . '/photo/' . $rr['resource_id'] . '-' . ($rr['scale'] == 6 ? 4 : $rr['scale']) . '.' . $ext, 'alt' => $alt_e, 'album' => array('link' => $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/album/' . bin2hex($rr['album']), 'name' => $name_e, 'alt' => t('View Album')));
        }
    }
    if ($_REQUEST['aj']) {
        if ($photos) {
            $o = replace_macros(get_markup_template('photosajax.tpl'), array('$photos' => $photos));
        } else {
            $o = '<div id="content-complete"></div>';
        }
        echo $o;
        killme();
    } else {
        $o .= "<script> var page_query = '" . $_GET['q'] . "'; var extra_args = '" . extra_query_args() . "' ; </script>";
        $tpl = get_markup_template('photos_recent.tpl');
        $o .= replace_macros($tpl, array('$title' => t('Recent Photos'), '$can_post' => $can_post, '$upload' => array(t('Upload New Photos'), $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/upload'), '$photos' => $photos));
    }
    if (!$photos && $_REQUEST['aj']) {
        $o .= '<div id="content-complete"></div>';
        echo $o;
        killme();
    }
    //	$o .= paginate($a);
    return $o;
}
Example #14
0
function photo_init(&$a)
{
    switch ($a->argc) {
        case 4:
            $person = $a->argv[3];
            $customres = intval($a->argv[2]);
            $type = $a->argv[1];
            break;
        case 3:
            $person = $a->argv[2];
            $type = $a->argv[1];
            break;
        case 2:
            $photo = $a->argv[1];
            break;
        case 1:
        default:
            killme();
            // NOTREACHED
    }
    $default = 'images/default-profile.jpg';
    if (isset($type)) {
        /**
         * Profile photos
         */
        switch ($type) {
            case 'profile':
            case 'custom':
                $resolution = 4;
                break;
            case 'micro':
                $resolution = 6;
                $default = 'images/default-profile-mm.jpg';
                break;
            case 'avatar':
            default:
                $resolution = 5;
                $default = 'images/default-profile-sm.jpg';
                break;
        }
        $uid = str_replace('.jpg', '', $person);
        $r = q("SELECT * FROM `photo` WHERE `scale` = %d AND `uid` = %d AND `profile` = 1 LIMIT 1", intval($resolution), intval($uid));
        if (count($r)) {
            $data = $r[0]['data'];
        }
        if (!isset($data)) {
            $data = file_get_contents($default);
        }
    } else {
        /**
         * Other photos
         */
        $resolution = 0;
        $photo = str_replace('.jpg', '', $photo);
        if (substr($photo, -2, 1) == '-') {
            $resolution = intval(substr($photo, -1, 1));
            $photo = substr($photo, 0, -2);
        }
        $r = q("SELECT `uid` FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d LIMIT 1", dbesc($photo), intval($resolution));
        if (count($r)) {
            $sql_extra = permissions_sql($r[0]['uid']);
            // Now we'll see if we can access the photo
            $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d {$sql_extra} LIMIT 1", dbesc($photo), intval($resolution));
            if (count($r)) {
                $data = $r[0]['data'];
            } else {
                // Does the picture exist? It may be a remote person with no credentials,
                // but who should otherwise be able to view it. Show a default image to let
                // them know permissions was denied. It may be possible to view the image
                // through an authenticated profile visit.
                // There won't be many completely unauthorised people seeing this because
                // they won't have the photo link, so there's a reasonable chance that the person
                // might be able to obtain permission to view it.
                $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d LIMIT 1", dbesc($photo), intval($resolution));
                if (count($r)) {
                    $data = file_get_contents('images/nosign.jpg');
                }
            }
        }
    }
    if (!isset($data)) {
        killme();
        // NOTREACHED
    }
    if (intval($customres) && $customres > 0 && $customres < 500) {
        require_once 'include/Photo.php';
        $ph = new Photo($data);
        if ($ph->is_valid()) {
            $ph->scaleImageSquare($customres);
            $data = $ph->imageString();
        }
    }
    if (function_exists('header_remove')) {
        header_remove('Pragma');
        header_remove('pragma');
    }
    header("Content-type: image/jpeg");
    header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600 * 24) . " GMT");
    header("Cache-Control: max-age=" . 3600 * 24);
    echo $data;
    killme();
    // NOTREACHED
}
Example #15
0
File: photo.php Project: Mauru/red
function photo_init(&$a)
{
    $prvcachecontrol = false;
    switch (argc()) {
        case 4:
            $person = argv(3);
            $res = argv(2);
            $type = argv(1);
            break;
        case 2:
            $photo = argv(1);
            break;
        case 1:
        default:
            killme();
            // NOTREACHED
    }
    if ($photo === 'qr') {
        $t = $_GET['qr'];
        require_once 'library/phpqrcode/phpqrcode.php';
        header("Content-type: image/png");
        QRcode::png($t ? $t : '.');
        killme();
    }
    $observer_xchan = get_observer_hash();
    $default = get_default_profile_photo();
    if (isset($type)) {
        /**
         * Profile photos - Access controls on default profile photos are not honoured since they need to be exchanged with remote sites.
         * 
         */
        if ($type === 'profile') {
            switch ($res) {
                case 'm':
                    $resolution = 5;
                    $default = get_default_profile_photo(80);
                    break;
                case 's':
                    $resolution = 6;
                    $default = get_default_profile_photo(48);
                    break;
                case 'l':
                default:
                    $resolution = 4;
                    break;
            }
        }
        $uid = $person;
        $r = q("SELECT * FROM photo WHERE scale = %d AND uid = %d AND profile = 1 LIMIT 1", intval($resolution), intval($uid));
        if (count($r)) {
            $data = $r[0]['data'];
            $mimetype = $r[0]['type'];
        }
        if (!isset($data)) {
            $data = file_get_contents($default);
            $mimetype = 'image/jpeg';
        }
    } else {
        /**
         * Other photos
         */
        /* Check for a cookie to indicate display pixel density, in order to detect high-resolution
        		   displays. This procedure was derived from the "Retina Images" by Jeremey Worboys,
        		   used in accordance with the Creative Commons Attribution 3.0 Unported License.
        		   Project link: https://github.com/Retina-Images/Retina-Images
        		   License link: http://creativecommons.org/licenses/by/3.0/
        		*/
        $cookie_value = false;
        if (isset($_COOKIE['devicePixelRatio'])) {
            $cookie_value = intval($_COOKIE['devicePixelRatio']);
        } else {
            // Force revalidation of cache on next request
            $cache_directive = 'no-cache';
            $status = 'no cookie';
        }
        $resolution = 0;
        if (strpos($photo, '.') !== false) {
            $photo = substr($photo, 0, strpos($photo, '.'));
        }
        if (substr($photo, -2, 1) == '-') {
            $resolution = intval(substr($photo, -1, 1));
            $photo = substr($photo, 0, -2);
            // If viewing on a high-res screen, attempt to serve a higher resolution image:
            if ($resolution == 2 && $cookie_value > 1) {
                $resolution = 1;
            }
        }
        // If using resolution 1, make sure it exists before proceeding:
        if ($resolution == 1) {
            $r = q("SELECT uid FROM photo WHERE resource_id = '%s' AND scale = %d LIMIT 1", dbesc($photo), intval($resolution));
            if (!$r) {
                $resolution = 2;
            }
        }
        $r = q("SELECT uid FROM photo WHERE resource_id = '%s' AND scale = %d LIMIT 1", dbesc($photo), intval($resolution));
        if ($r) {
            $allowed = $r[0]['uid'] ? perm_is_allowed($r[0]['uid'], $observer_xchan, 'view_photos') : true;
            $sql_extra = permissions_sql($r[0]['uid']);
            // Now we'll see if we can access the photo
            $r = q("SELECT * FROM photo WHERE resource_id = '%s' AND scale = %d {$sql_extra} LIMIT 1", dbesc($photo), intval($resolution));
            if ($r && $allowed) {
                $data = $r[0]['data'];
                $mimetype = $r[0]['type'];
            } else {
                // Does the picture exist? It may be a remote person with no credentials,
                // but who should otherwise be able to view it. Show a default image to let
                // them know permissions was denied. It may be possible to view the image
                // through an authenticated profile visit.
                // There won't be many completely unauthorised people seeing this because
                // they won't have the photo link, so there's a reasonable chance that the person
                // might be able to obtain permission to view it.
                $r = q("SELECT * FROM `photo` WHERE `resource_id` = '%s' AND `scale` = %d LIMIT 1", dbesc($photo), intval($resolution));
                if ($r) {
                    logger('mod_photo: forbidden. ' . $a->query_string);
                    $observer = $a->get_observer();
                    logger('mod_photo: observer = ' . ($observer ? $observer['xchan_addr'] : '(not authenticated)'));
                    $data = file_get_contents('images/nosign.png');
                    $mimetype = 'image/png';
                    $prvcachecontrol = true;
                }
            }
        }
    }
    if (!isset($data)) {
        if (isset($resolution)) {
            switch ($resolution) {
                case 4:
                    $data = file_get_contents(get_default_profile_photo());
                    $mimetype = 'image/jpeg';
                    break;
                case 5:
                    $data = file_get_contents(get_default_profile_photo(80));
                    $mimetype = 'image/jpeg';
                    break;
                case 6:
                    $data = file_get_contents(get_default_profile_photo(48));
                    $mimetype = 'image/jpeg';
                    break;
                default:
                    killme();
                    // NOTREACHED
                    break;
            }
        }
    }
    if (isset($res) && intval($res) && $res < 500) {
        $ph = photo_factory($data, $mimetype);
        if ($ph->is_valid()) {
            $ph->scaleImageSquare($res);
            $data = $ph->imageString();
            $mimetype = $ph->getType();
        }
    }
    // Writing in cachefile
    if (isset($cachefile) && $cachefile != '') {
        file_put_contents($cachefile, $data);
    }
    if (function_exists('header_remove')) {
        header_remove('Pragma');
        header_remove('pragma');
    }
    header("Content-type: " . $mimetype);
    if ($prvcachecontrol) {
        // it is a private photo that they have no permission to view.
        // tell the browser not to cache it, in case they authenticate
        // and subsequently have permission to see it
        header("Cache-Control: no-store, no-cache, must-revalidate");
    } else {
        header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600 * 24) . " GMT");
        header("Cache-Control: max-age=" . 3600 * 24);
    }
    echo $data;
    killme();
    // NOTREACHED
}
Example #16
0
 function oep_photo_reply($args)
 {
     $ret = array();
     $url = $args['url'];
     $maxwidth = intval($args['maxwidth']);
     $maxheight = intval($args['maxheight']);
     if (preg_match('|//(.*?)/(.*?)/(.*?)/image/|', $url, $matches)) {
         $chn = $matches[3];
         $res = basename($url);
     }
     if (!($chn && $res)) {
         return;
     }
     $c = q("select * from channel where channel_address = '%s' limit 1", dbesc($chn));
     if (!$c) {
         return;
     }
     $sql_extra = permissions_sql($c[0]['channel_id']);
     $r = q("select height, width, scale, resource_id from photo where uid = %d and resource_id = '%s' {$sql_extra} order by scale asc", intval($c[0]['channel_id']), dbesc($res));
     if ($r) {
         foreach ($r as $rr) {
             $foundres = false;
             if ($maxheight && $rr['height'] > $maxheight) {
                 continue;
             }
             if ($maxwidth && $rr['width'] > $maxwidth) {
                 continue;
             }
             $foundres = true;
             break;
         }
         if ($foundres) {
             $ret['type'] = 'link';
             $ret['thumbnail_url'] = z_root() . '/photo/' . '/' . $rr['resource_id'] . '-' . $rr['scale'];
             $ret['thumbnail_width'] = $rr['width'];
             $ret['thumbnail_height'] = $rr['height'];
         }
     }
     return $ret;
 }
Example #17
0
function profile_content(&$a, $update = 0)
{
    if (get_config('system', 'block_public') && !local_user() && !remote_user()) {
        return login();
    }
    require_once "include/bbcode.php";
    require_once 'include/security.php';
    require_once 'include/conversation.php';
    require_once 'include/acl_selectors.php';
    $groups = array();
    $tab = 'posts';
    $o = '';
    if ($update) {
        // Ensure we've got a profile owner if updating.
        $a->profile['profile_uid'] = $update;
    } else {
        if ($a->profile['profile_uid'] == local_user()) {
            nav_set_selected('home');
        }
    }
    $contact = null;
    $remote_contact = false;
    if (remote_user()) {
        $contact_id = $_SESSION['visitor_id'];
        $groups = init_groups_visitor($contact_id);
        $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($contact_id), intval($a->profile['profile_uid']));
        if (count($r)) {
            $contact = $r[0];
            $remote_contact = true;
        }
    }
    if (!$remote_contact) {
        if (local_user()) {
            $contact_id = $_SESSION['cid'];
            $contact = $a->contact;
        }
    }
    $is_owner = local_user() && local_user() == $a->profile['profile_uid'] ? true : false;
    if ($a->profile['hidewall'] && !$is_owner && !$remote_contact) {
        notice(t('Access to this profile has been restricted.') . EOL);
        return;
    }
    if (!$update) {
        if (x($_GET, 'tab')) {
            $tab = notags(trim($_GET['tab']));
        }
        $o .= profile_tabs($a, $is_owner, $a->profile['nickname']);
        if ($tab === 'profile') {
            require_once 'include/profile_advanced.php';
            $o .= advanced_profile($a);
            call_hooks('profile_advanced', $o);
            return $o;
        }
        if (x($_SESSION, 'new_member') && $_SESSION['new_member'] && $is_owner) {
            $o .= '<a href="newmember">' . t('Tips for New Members') . '</a>' . EOL;
        }
        $commpage = $a->profile['page-flags'] == PAGE_COMMUNITY ? true : false;
        $commvisitor = $commpage && $remote_contact == true ? true : false;
        $celeb = $a->profile['page-flags'] == PAGE_SOAPBOX || $a->profile['page-flags'] == PAGE_COMMUNITY ? true : false;
        if (can_write_wall($a, $a->profile['profile_uid'])) {
            $x = array('is_owner' => $is_owner, 'allow_location' => ($is_owner || $commvisitor) && $a->profile['allow_location'] ? true : false, 'default_location' => $is_owner ? $a->user['default-location'] : '', 'nickname' => $a->profile['nickname'], 'lockstate' => is_array($a->user) && (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) || strlen($a->user['deny_cid']) || strlen($a->user['deny_gid'])) ? 'lock' : 'unlock', 'acl' => $is_owner ? populate_acl($a->user, $celeb) : '', 'bang' => '', 'visitor' => $is_owner || $commvisitor ? 'block' : 'none', 'profile_uid' => $a->profile['profile_uid']);
            $o .= status_editor($a, $x);
        }
    }
    if ($is_owner) {
        $r = q("UPDATE `item` SET `unseen` = 0 \n\t\t\tWHERE `wall` = 1 AND `unseen` = 1 AND `uid` = %d", intval(local_user()));
    }
    /**
     * Get permissions SQL - if $remote_contact is true, our remote user has been pre-verified and we already have fetched his/her groups
     */
    $sql_extra = permissions_sql($a->profile['profile_uid'], $remote_contact, $groups);
    $r = q("SELECT COUNT(*) AS `total`\n\t\tFROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0 \n\t\tAND `item`.`id` = `item`.`parent` AND `item`.`wall` = 1\n\t\t{$sql_extra} ", intval($a->profile['profile_uid']));
    if (count($r)) {
        $a->set_pager_total($r[0]['total']);
        $a->set_pager_itemspage(40);
    }
    $r = q("SELECT `item`.`id` AS `item_id`, `contact`.`uid` AS `contact-uid`\n\t\tFROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\tAND `item`.`id` = `item`.`parent` AND `item`.`wall` = 1\n\t\t{$sql_extra}\n\t\tORDER BY `item`.`created` DESC LIMIT %d ,%d ", intval($a->profile['profile_uid']), intval($a->pager['start']), intval($a->pager['itemspage']));
    $parents_arr = array();
    $parents_str = '';
    if (count($r)) {
        foreach ($r as $rr) {
            $parents_arr[] = $rr['item_id'];
        }
        $parents_str = implode(', ', $parents_arr);
        $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, \n\t\t\t`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`network`, `contact`.`rel`, \n\t\t\t`contact`.`thumb`, `contact`.`self`, `contact`.`writable`, \n\t\t\t`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`\n\t\t\tFROM `item`, (SELECT `p`.`id`,`p`.`created` FROM `item` AS `p` WHERE `p`.`parent` = `p`.`id`) AS `parentitem`, `contact`\n\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\t\tAND `contact`.`id` = `item`.`contact-id`\n\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\tAND `item`.`parent` = `parentitem`.`id` AND `item`.`parent` IN ( %s )\n\t\t\t{$sql_extra}\n\t\t\tORDER BY `parentitem`.`created` DESC, `gravity` ASC, `item`.`created` ASC ", intval($a->profile['profile_uid']), dbesc($parents_str));
    }
    if ($is_owner && !$update) {
        $o .= get_birthdays();
        $o .= get_events();
    }
    if (!$update && $tab === 'posts') {
        // This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
        // because browser prefetching might change it on us. We have to deliver it with the page.
        $o .= '<div id="live-profile"></div>' . "\r\n";
        $o .= "<script> var profile_uid = " . $a->profile['profile_uid'] . "; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
    }
    $o .= conversation($a, $r, 'profile', $update);
    if (!$update) {
        $o .= paginate($a);
    }
    return $o;
}
Example #18
0
function events_content(&$a)
{
    if (argc() > 2 && argv(1) == 'ical') {
        $event_id = argv(2);
        require_once 'include/security.php';
        $sql_extra = permissions_sql(local_channel());
        $r = q("select * from event where event_hash = '%s' {$sql_extra} limit 1", dbesc($event_id));
        if ($r) {
            header('Content-type: text/calendar');
            header('content-disposition: attachment; filename="' . t('event') . '-' . $event_id . '.ics"');
            echo ical_wrapper($r);
            killme();
        } else {
            notice(t('Event not found.') . EOL);
            return;
        }
    }
    if (!local_channel()) {
        notice(t('Permission denied.') . EOL);
        return;
    }
    nav_set_selected('all_events');
    if (argc() > 2 && argv(1) === 'ignore' && intval(argv(2))) {
        $r = q("update event set ignore = 1 where id = %d and uid = %d", intval(argv(2)), intval(local_channel()));
    }
    if (argc() > 2 && argv(1) === 'unignore' && intval(argv(2))) {
        $r = q("update event set ignore = 0 where id = %d and uid = %d", intval(argv(2)), intval(local_channel()));
    }
    $first_day = get_pconfig(local_channel(), 'system', 'cal_first_day');
    $first_day = $first_day ? $first_day : 0;
    $htpl = get_markup_template('event_head.tpl');
    $a->page['htmlhead'] .= replace_macros($htpl, array('$baseurl' => $a->get_baseurl(), '$lang' => $a->language, '$first_day' => $first_day));
    $o = '';
    $channel = $a->get_channel();
    $mode = 'view';
    $y = 0;
    $m = 0;
    $ignored = x($_REQUEST, 'ignored') ? " and ignored = " . intval($_REQUEST['ignored']) . " " : '';
    if (argc() > 1) {
        if (argc() > 2 && argv(1) === 'add') {
            $mode = 'add';
            $item_id = intval(argv(2));
        }
        if (argc() > 2 && argv(1) === 'drop') {
            $mode = 'drop';
            $event_id = argv(2);
        }
        if (argc() > 2 && intval(argv(1)) && intval(argv(2))) {
            $mode = 'view';
            $y = intval(argv(1));
            $m = intval(argv(2));
        }
        if (argc() <= 2) {
            $mode = 'view';
            $event_id = argv(1);
        }
    }
    if ($mode === 'add') {
        event_addtocal($item_id, local_channel());
        killme();
    }
    if ($mode == 'view') {
        /* edit/create form */
        if ($event_id) {
            $r = q("SELECT * FROM `event` WHERE event_hash = '%s' AND `uid` = %d LIMIT 1", dbesc($event_id), intval(local_channel()));
            if (count($r)) {
                $orig_event = $r[0];
            }
        }
        $channel = $a->get_channel();
        // Passed parameters overrides anything found in the DB
        if (!x($orig_event)) {
            $orig_event = array();
        }
        // In case of an error the browser is redirected back here, with these parameters filled in with the previous values
        /*
        if(x($_REQUEST,'nofinish')) $orig_event['nofinish'] = $_REQUEST['nofinish'];
        if(x($_REQUEST,'adjust')) $orig_event['adjust'] = $_REQUEST['adjust'];
        if(x($_REQUEST,'summary')) $orig_event['summary'] = $_REQUEST['summary'];
        if(x($_REQUEST,'description')) $orig_event['description'] = $_REQUEST['description'];
        if(x($_REQUEST,'location')) $orig_event['location'] = $_REQUEST['location'];
        if(x($_REQUEST,'start')) $orig_event['start'] = $_REQUEST['start'];
        if(x($_REQUEST,'finish')) $orig_event['finish'] = $_REQUEST['finish'];
        if(x($_REQUEST,'type')) $orig_event['type'] = $_REQUEST['type'];
        */
        $n_checked = x($orig_event) && $orig_event['nofinish'] ? ' checked="checked" ' : '';
        $a_checked = x($orig_event) && $orig_event['adjust'] ? ' checked="checked" ' : '';
        $t_orig = x($orig_event) ? $orig_event['summary'] : '';
        $d_orig = x($orig_event) ? $orig_event['description'] : '';
        $l_orig = x($orig_event) ? $orig_event['location'] : '';
        $eid = x($orig_event) ? $orig_event['id'] : 0;
        $event_xchan = x($orig_event) ? $orig_event['event_xchan'] : $channel['channel_hash'];
        $mid = x($orig_event) ? $orig_event['mid'] : '';
        if (!x($orig_event)) {
            $sh_checked = '';
        } else {
            $sh_checked = ($orig_event['allow_cid'] === '<' . $channel['channel_hash'] . '>' || !$orig_event['allow_cid']) && !$orig_event['allow_gid'] && !$orig_event['deny_cid'] && !$orig_event['deny_gid'] ? '' : ' checked="checked" ';
        }
        if ($orig_event['event_xchan']) {
            $sh_checked .= ' disabled="disabled" ';
        }
        $sdt = x($orig_event) ? $orig_event['start'] : 'now';
        $fdt = x($orig_event) ? $orig_event['finish'] : '+1 hour';
        $tz = date_default_timezone_get();
        if (x($orig_event)) {
            $tz = $orig_event['adjust'] ? date_default_timezone_get() : 'UTC';
        }
        $syear = datetime_convert('UTC', $tz, $sdt, 'Y');
        $smonth = datetime_convert('UTC', $tz, $sdt, 'm');
        $sday = datetime_convert('UTC', $tz, $sdt, 'd');
        $shour = datetime_convert('UTC', $tz, $sdt, 'H');
        $sminute = datetime_convert('UTC', $tz, $sdt, 'i');
        $stext = datetime_convert('UTC', $tz, $sdt);
        $stext = substr($stext, 0, 14) . "00:00";
        $fyear = datetime_convert('UTC', $tz, $fdt, 'Y');
        $fmonth = datetime_convert('UTC', $tz, $fdt, 'm');
        $fday = datetime_convert('UTC', $tz, $fdt, 'd');
        $fhour = datetime_convert('UTC', $tz, $fdt, 'H');
        $fminute = datetime_convert('UTC', $tz, $fdt, 'i');
        $ftext = datetime_convert('UTC', $tz, $fdt);
        $ftext = substr($ftext, 0, 14) . "00:00";
        $type = x($orig_event) ? $orig_event['type'] : 'event';
        $f = get_config('system', 'event_input_format');
        if (!$f) {
            $f = 'ymd';
        }
        $catsenabled = feature_enabled(local_channel(), 'categories');
        $category = '';
        if ($catsenabled && x($orig_event)) {
            $itm = q("select * from item where resource_type = 'event' and resource_id = '%s' and uid = %d limit 1", dbesc($orig_event['event_hash']), intval(local_channel()));
            $itm = fetch_post_tags($itm);
            if ($itm) {
                $cats = get_terms_oftype($itm[0]['term'], TERM_CATEGORY);
                foreach ($cats as $cat) {
                    if (strlen($category)) {
                        $category .= ', ';
                    }
                    $category .= $cat['term'];
                }
            }
        }
        require_once 'include/acl_selectors.php';
        $acl = new AccessList($channel);
        $perm_defaults = $acl->get();
        $tpl = get_markup_template('event_form.tpl');
        $form = replace_macros($tpl, array('$post' => $a->get_baseurl() . '/events', '$eid' => $eid, '$type' => $type, '$xchan' => $event_xchan, '$mid' => $mid, '$event_hash' => $event_id, '$summary' => array('summary', $event_id ? t('Edit event titel') : t('Event titel'), $t_orig, t('Required'), '*'), '$catsenabled' => $catsenabled, '$placeholdercategory' => t('Categories (comma-separated list)'), '$c_text' => $event_id ? t('Edit Category') : t('Category'), '$category' => $category, '$required' => '<span class="required" title="' . t('Required') . '">*</span>', '$s_dsel' => datetimesel($f, new DateTime(), DateTime::createFromFormat('Y', $syear + 5), DateTime::createFromFormat('Y-m-d H:i', "{$syear}-{$smonth}-{$sday} {$shour}:{$sminute}"), $event_id ? t('Edit start date and time') : t('Start date and time'), 'start_text', true, true, '', '', true, $first_day), '$n_text' => t('Finish date and time are not known or not relevant'), '$n_checked' => $n_checked, '$f_dsel' => datetimesel($f, new DateTime(), DateTime::createFromFormat('Y', $fyear + 5), DateTime::createFromFormat('Y-m-d H:i', "{$fyear}-{$fmonth}-{$fday} {$fhour}:{$fminute}"), $event_id ? t('Edit finish date and time') : t('Finish date and time'), 'finish_text', true, true, 'start_text', '', false, $first_day), '$nofinish' => array('nofinish', t('Finish date and time are not known or not relevant'), $n_checked, '', array(t('No'), t('Yes')), 'onclick="enableDisableFinishDate();"'), '$adjust' => array('adjust', t('Adjust for viewer timezone'), $a_checked, t('Important for events that happen in a particular place. Not practical for global holidays.'), array(t('No'), t('Yes'))), '$a_text' => t('Adjust for viewer timezone'), '$d_text' => $event_id ? t('Edit Description') : t('Description'), '$d_orig' => $d_orig, '$l_text' => $event_id ? t('Edit Location') : t('Location'), '$l_orig' => $l_orig, '$t_orig' => $t_orig, '$sh_text' => t('Share this event'), '$sh_checked' => $sh_checked, '$share' => array('share', t('Share this event'), $sh_checked, '', array(t('No'), t('Yes'))), '$preview' => t('Preview'), '$permissions' => t('Permission settings'), '$acl' => $orig_event['event_xchan'] ? '' : populate_acl(x($orig_event) ? $orig_event : $perm_defaults, false), '$submit' => t('Submit'), '$advanced' => t('Advanced Options')));
        /* end edit/create form */
        $thisyear = datetime_convert('UTC', date_default_timezone_get(), 'now', 'Y');
        $thismonth = datetime_convert('UTC', date_default_timezone_get(), 'now', 'm');
        if (!$y) {
            $y = intval($thisyear);
        }
        if (!$m) {
            $m = intval($thismonth);
        }
        $export = false;
        if (argc() === 4 && argv(3) === 'export') {
            $export = true;
        }
        // Put some limits on dates. The PHP date functions don't seem to do so well before 1900.
        // An upper limit was chosen to keep search engines from exploring links millions of years in the future.
        if ($y < 1901) {
            $y = 1900;
        }
        if ($y > 2099) {
            $y = 2100;
        }
        $nextyear = $y;
        $nextmonth = $m + 1;
        if ($nextmonth > 12) {
            $nextmonth = 1;
            $nextyear++;
        }
        $prevyear = $y;
        if ($m > 1) {
            $prevmonth = $m - 1;
        } else {
            $prevmonth = 12;
            $prevyear--;
        }
        $dim = get_dim($y, $m);
        $start = sprintf('%d-%d-%d %d:%d:%d', $y, $m, 1, 0, 0, 0);
        $finish = sprintf('%d-%d-%d %d:%d:%d', $y, $m, $dim, 23, 59, 59);
        if (argv(1) === 'json') {
            if (x($_GET, 'start')) {
                $start = $_GET['start'];
            }
            if (x($_GET, 'end')) {
                $finish = $_GET['end'];
            }
        }
        $start = datetime_convert('UTC', 'UTC', $start);
        $finish = datetime_convert('UTC', 'UTC', $finish);
        $adjust_start = datetime_convert('UTC', date_default_timezone_get(), $start);
        $adjust_finish = datetime_convert('UTC', date_default_timezone_get(), $finish);
        if (x($_GET, 'id')) {
            $r = q("SELECT event.*, item.plink, item.item_flags, item.author_xchan, item.owner_xchan\n                                from event left join item on resource_id = event_hash where resource_type = 'event' and event.uid = %d and event.id = %d limit 1", intval(local_channel()), intval($_GET['id']));
        } elseif ($export) {
            $r = q("SELECT * from event where uid = %d\n\t\t\t\tAND (( `adjust` = 0 AND ( `finish` >= '%s' or nofinish = 1 ) AND `start` <= '%s' ) \n\t\t\t\tOR  (  `adjust` = 1 AND ( `finish` >= '%s' or nofinish = 1 ) AND `start` <= '%s' )) ", intval(local_channel()), dbesc($start), dbesc($finish), dbesc($adjust_start), dbesc($adjust_finish));
        } else {
            // fixed an issue with "nofinish" events not showing up in the calendar.
            // There's still an issue if the finish date crosses the end of month.
            // Noting this for now - it will need to be fixed here and in Friendica.
            // Ultimately the finish date shouldn't be involved in the query.
            $r = q("SELECT event.*, item.plink, item.item_flags, item.author_xchan, item.owner_xchan\n                              from event left join item on event_hash = resource_id \n\t\t\t\twhere resource_type = 'event' and event.uid = %d {$ignored} \n\t\t\t\tAND (( adjust = 0 AND ( finish >= '%s' or nofinish = 1 ) AND start <= '%s' ) \n\t\t\t\tOR  (  adjust = 1 AND ( finish >= '%s' or nofinish = 1 ) AND start <= '%s' )) ", intval(local_channel()), dbesc($start), dbesc($finish), dbesc($adjust_start), dbesc($adjust_finish));
        }
        $links = array();
        if ($r && !$export) {
            xchan_query($r);
            $r = fetch_post_tags($r, true);
            $r = sort_by_date($r);
        }
        if ($r) {
            foreach ($r as $rr) {
                $j = $rr['adjust'] ? datetime_convert('UTC', date_default_timezone_get(), $rr['start'], 'j') : datetime_convert('UTC', 'UTC', $rr['start'], 'j');
                if (!x($links, $j)) {
                    $links[$j] = $a->get_baseurl() . '/' . $a->cmd . '#link-' . $j;
                }
            }
        }
        $events = array();
        $last_date = '';
        $fmt = t('l, F j');
        if ($r) {
            foreach ($r as $rr) {
                $j = $rr['adjust'] ? datetime_convert('UTC', date_default_timezone_get(), $rr['start'], 'j') : datetime_convert('UTC', 'UTC', $rr['start'], 'j');
                $d = $rr['adjust'] ? datetime_convert('UTC', date_default_timezone_get(), $rr['start'], $fmt) : datetime_convert('UTC', 'UTC', $rr['start'], $fmt);
                $d = day_translate($d);
                $start = $rr['adjust'] ? datetime_convert('UTC', date_default_timezone_get(), $rr['start'], 'c') : datetime_convert('UTC', 'UTC', $rr['start'], 'c');
                if ($rr['nofinish']) {
                    $end = null;
                } else {
                    $end = $rr['adjust'] ? datetime_convert('UTC', date_default_timezone_get(), $rr['finish'], 'c') : datetime_convert('UTC', 'UTC', $rr['finish'], 'c');
                }
                $is_first = $d !== $last_date;
                $last_date = $d;
                $edit = local_channel() && $rr['author_xchan'] == get_observer_hash() ? array($a->get_baseurl() . '/events/' . $rr['event_hash'] . '?expandform=1', t('Edit event'), '', '') : false;
                $drop = array($a->get_baseurl() . '/events/drop/' . $rr['event_hash'], t('Delete event'), '', '');
                $title = strip_tags(html_entity_decode(bbcode($rr['summary']), ENT_QUOTES, 'UTF-8'));
                if (!$title) {
                    list($title, $_trash) = explode("<br", bbcode($rr['desc']), 2);
                    $title = strip_tags(html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
                }
                $html = format_event_html($rr);
                $rr['desc'] = bbcode($rr['desc']);
                $rr['location'] = bbcode($rr['location']);
                $events[] = array('id' => $rr['id'], 'hash' => $rr['event_hash'], 'start' => $start, 'end' => $end, 'drop' => $drop, 'allDay' => false, 'title' => $title, 'j' => $j, 'd' => $d, 'edit' => $edit, 'is_first' => $is_first, 'item' => $rr, 'html' => $html, 'plink' => array($rr['plink'], t('Link to Source'), '', ''));
            }
        }
        if ($export) {
            header('Content-type: text/calendar');
            header('content-disposition: attachment; filename="' . t('calendar') . '-' . $channel['channel_address'] . '.ics"');
            echo ical_wrapper($r);
            killme();
        }
        if ($a->argv[1] === 'json') {
            echo json_encode($events);
            killme();
        }
        // links: array('href', 'text', 'extra css classes', 'title')
        if (x($_GET, 'id')) {
            $tpl = get_markup_template("event.tpl");
        } else {
            $tpl = get_markup_template("events-js.tpl");
        }
        $o = replace_macros($tpl, array('$baseurl' => $a->get_baseurl(), '$new_event' => array($a->get_baseurl() . '/events', $event_id ? t('Edit Event') : t('Create Event'), '', ''), '$previus' => array($a->get_baseurl() . "/events/{$prevyear}/{$prevmonth}", t('Previous'), '', ''), '$next' => array($a->get_baseurl() . "/events/{$nextyear}/{$nextmonth}", t('Next'), '', ''), '$export' => array($a->get_baseurl() . "/events/{$y}/{$m}/export", t('Export'), '', ''), '$calendar' => cal($y, $m, $links, ' eventcal'), '$events' => $events, '$upload' => t('Import'), '$submit' => t('Submit'), '$prev' => t('Previous'), '$next' => t('Next'), '$today' => t('Today'), '$form' => $form, '$expandform' => x($_GET, 'expandform') ? true : false));
        if (x($_GET, 'id')) {
            echo $o;
            killme();
        }
        return $o;
    }
    if ($mode === 'drop' && $event_id) {
        $r = q("SELECT * FROM `event` WHERE event_hash = '%s' AND `uid` = %d LIMIT 1", dbesc($event_id), intval(local_channel()));
        $sync_event = $r[0];
        if ($r) {
            $r = q("delete from event where event_hash = '%s' and uid = %d limit 1", dbesc($event_id), intval(local_channel()));
            if ($r) {
                $r = q("update item set resource_type = '', resource_id = '' where resource_type = 'event' and resource_id = '%s' and uid = %d", dbesc($event_id), intval(local_channel()));
                $sync_event['event_deleted'] = 1;
                build_sync_packet(0, array('event' => array($sync_event)));
                info(t('Event removed') . EOL);
            } else {
                notice(t('Failed to remove event') . EOL);
            }
            goaway(z_root() . '/events');
        }
    }
}
Example #19
0
function photos_content(&$a)
{
    // URLs:
    // photos/name
    // photos/name/upload
    // photos/name/upload/xxxxx (xxxxx is album name)
    // photos/name/album/xxxxx
    // photos/name/album/xxxxx/edit
    // photos/name/image/xxxxx
    // photos/name/image/xxxxx/edit
    if (get_config('system', 'block_public') && !local_user() && !remote_user()) {
        notice(t('Public access denied.') . EOL);
        return;
    }
    require_once 'include/bbcode.php';
    require_once 'include/security.php';
    require_once 'include/conversation.php';
    if (!x($a->data, 'user')) {
        notice(t('No photos selected') . EOL);
        return;
    }
    $phototypes = Photo::supportedTypes();
    $_SESSION['photo_return'] = $a->cmd;
    //
    // Parse arguments
    //
    if ($a->argc > 3) {
        $datatype = $a->argv[2];
        $datum = $a->argv[3];
    } elseif ($a->argc > 2 && $a->argv[2] === 'upload') {
        $datatype = 'upload';
    } else {
        $datatype = 'summary';
    }
    if ($a->argc > 4) {
        $cmd = $a->argv[4];
    } else {
        $cmd = 'view';
    }
    //
    // Setup permissions structures
    //
    $can_post = false;
    $visitor = 0;
    $contact = null;
    $remote_contact = false;
    $contact_id = 0;
    $owner_uid = $a->data['user']['uid'];
    $community_page = $a->data['user']['page-flags'] == PAGE_COMMUNITY ? true : false;
    if (local_user() && local_user() == $owner_uid) {
        $can_post = true;
    } else {
        if ($community_page && remote_user()) {
            if (is_array($_SESSION['remote'])) {
                foreach ($_SESSION['remote'] as $v) {
                    if ($v['uid'] == $owner_uid) {
                        $contact_id = $v['cid'];
                        break;
                    }
                }
            }
            if ($contact_id) {
                $r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1", intval($contact_id), intval($owner_uid));
                if (count($r)) {
                    $can_post = true;
                    $contact = $r[0];
                    $remote_contact = true;
                    $visitor = $cid;
                }
            }
        }
    }
    // perhaps they're visiting - but not a community page, so they wouldn't have write access
    if (remote_user() && !$visitor) {
        $contact_id = 0;
        if (is_array($_SESSION['remote'])) {
            foreach ($_SESSION['remote'] as $v) {
                if ($v['uid'] == $owner_uid) {
                    $contact_id = $v['cid'];
                    break;
                }
            }
        }
        if ($contact_id) {
            $groups = init_groups_visitor($contact_id);
            $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1", intval($contact_id), intval($owner_uid));
            if (count($r)) {
                $contact = $r[0];
                $remote_contact = true;
            }
        }
    }
    if (!$remote_contact) {
        if (local_user()) {
            $contact_id = $_SESSION['cid'];
            $contact = $a->contact;
        }
    }
    if ($a->data['user']['hidewall'] && local_user() != $owner_uid && !$remote_contact) {
        notice(t('Access to this item is restricted.') . EOL);
        return;
    }
    $sql_extra = permissions_sql($owner_uid, $remote_contact, $groups);
    $o = "";
    // tabs
    $_is_owner = local_user() && local_user() == $owner_uid;
    $o .= profile_tabs($a, $_is_owner, $a->data['user']['nickname']);
    //
    // dispatch request
    //
    if ($datatype === 'upload') {
        if (!$can_post) {
            notice(t('Permission denied.'));
            return;
        }
        $selname = $datum ? hex2bin($datum) : '';
        $albumselect = '';
        $albumselect .= '<option value="" ' . (!$selname ? ' selected="selected" ' : '') . '>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
        if (count($a->data['albums'])) {
            foreach ($a->data['albums'] as $album) {
                if ($album['album'] === '' || $album['album'] === 'Contact Photos' || $album['album'] === t('Contact Photos')) {
                    continue;
                }
                $selected = $selname === $album['album'] ? ' selected="selected" ' : '';
                $albumselect .= '<option value="' . $album['album'] . '"' . $selected . '>' . $album['album'] . '</option>';
            }
        }
        $celeb = $a->user['page-flags'] == PAGE_SOAPBOX || $a->user['page-flags'] == PAGE_COMMUNITY ? true : false;
        $uploader = '';
        $ret = array('post_url' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'], 'addon_text' => $uploader, 'default_upload' => true);
        call_hooks('photo_upload_form', $ret);
        $default_upload_box = replace_macros(get_markup_template('photos_default_uploader_box.tpl'), array());
        $default_upload_submit = replace_macros(get_markup_template('photos_default_uploader_submit.tpl'), array('$submit' => t('Submit')));
        $usage_message = '';
        $limit = service_class_fetch($a->data['user']['uid'], 'photo_upload_limit');
        if ($limit !== false) {
            $r = q("select sum(datasize) as total from photo where uid = %d and scale = 0 and album != 'Contact Photos' ", intval($a->data['user']['uid']));
            $usage_message = sprintf(t("You have used %1\$.2f Mbytes of %2\$.2f Mbytes photo storage."), $r[0]['total'] / 1024000, $limit / 1024000);
        }
        // Private/public post links for the non-JS ACL form
        $private_post = 1;
        if ($_REQUEST['public']) {
            $private_post = 0;
        }
        $query_str = $a->query_string;
        if (strpos($query_str, 'public=1') !== false) {
            $query_str = str_replace(array('?public=1', '&public=1'), array('', ''), $query_str);
        }
        // I think $a->query_string may never have ? in it, but I could be wrong
        // It looks like it's from the index.php?q=[etc] rewrite that the web
        // server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
        if (strpos($query_str, '?') === false) {
            $public_post_link = '?public=1';
        } else {
            $public_post_link = '&public=1';
        }
        $tpl = get_markup_template('photos_upload.tpl');
        if ($a->theme['template_engine'] === 'internal') {
            $albumselect_e = template_escape($albumselect);
            $aclselect_e = $visitor ? '' : template_escape(populate_acl($a->user, $celeb));
        } else {
            $albumselect_e = $albumselect;
            $aclselect_e = $visitor ? '' : populate_acl($a->user, $celeb);
        }
        $o .= replace_macros($tpl, array('$pagename' => t('Upload Photos'), '$sessid' => session_id(), '$usage' => $usage_message, '$nickname' => $a->data['user']['nickname'], '$newalbum' => t('New album name: '), '$existalbumtext' => t('or existing album name: '), '$nosharetext' => t('Do not show a status post for this upload'), '$albumselect' => $albumselect_e, '$permissions' => t('Permissions'), '$aclselect' => $aclselect_e, '$alt_uploader' => $ret['addon_text'], '$default_upload_box' => $ret['default_upload'] ? $default_upload_box : '', '$default_upload_submit' => $ret['default_upload'] ? $default_upload_submit : '', '$uploadurl' => $ret['post_url'], '$acl_data' => construct_acl_data($a, $a->user), '$group_perms' => t('Show to Groups'), '$contact_perms' => t('Show to Contacts'), '$private' => t('Private Photo'), '$public' => t('Public Photo'), '$is_private' => $private_post, '$return_path' => $query_str, '$public_link' => $public_post_link));
        return $o;
    }
    if ($datatype === 'album') {
        $album = hex2bin($datum);
        $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s' \n\t\t\tAND `scale` <= 4 {$sql_extra} GROUP BY `resource-id`", intval($owner_uid), dbesc($album));
        if (count($r)) {
            $a->set_pager_total(count($r));
            $a->set_pager_itemspage(20);
        }
        if ($_GET['order'] === 'posted') {
            $order = 'ASC';
        } else {
            $order = 'DESC';
        }
        $r = q("SELECT `resource-id`, `id`, `filename`, type, max(`scale`) AS `scale`, `desc` FROM `photo` WHERE `uid` = %d AND `album` = '%s' \n\t\t\tAND `scale` <= 4 {$sql_extra} GROUP BY `resource-id` ORDER BY `created` {$order} LIMIT %d , %d", intval($owner_uid), dbesc($album), intval($a->pager['start']), intval($a->pager['itemspage']));
        $o .= '<h3 id="photo-album-title">' . $album . '</h3>';
        if ($cmd === 'edit') {
            if ($album !== t('Profile Photos') && $album !== 'Contact Photos' && $album !== t('Contact Photos')) {
                if ($can_post) {
                    $edit_tpl = get_markup_template('album_edit.tpl');
                    if ($a->theme['template_engine'] === 'internal') {
                        $album_e = template_escape($album);
                    } else {
                        $album_e = $album;
                    }
                    $o .= replace_macros($edit_tpl, array('$nametext' => t('New album name: '), '$nickname' => $a->data['user']['nickname'], '$album' => $album_e, '$hexalbum' => bin2hex($album), '$submit' => t('Submit'), '$dropsubmit' => t('Delete Album')));
                }
            }
        } else {
            if ($album !== t('Profile Photos') && $album !== 'Contact Photos' && $album !== t('Contact Photos')) {
                if ($can_post) {
                    $o .= '<div id="album-edit-link"><a href="' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '/edit' . '">' . t('Edit Album') . '</a></div>';
                }
            }
        }
        if ($_GET['order'] === 'posted') {
            $o .= '<div class="photos-upload-link" ><a href="' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '" >' . t('Show Newest First') . '</a></div>';
        } else {
            $o .= '<div class="photos-upload-link" ><a href="' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '?f=&order=posted" >' . t('Show Oldest First') . '</a></div>';
        }
        if ($can_post) {
            $o .= '<div class="photos-upload-link" ><a href="' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/upload/' . bin2hex($album) . '" >' . t('Upload New Photos') . '</a></div>';
        }
        $tpl = get_markup_template('photo_album.tpl');
        if (count($r)) {
            $twist = 'rotright';
        }
        foreach ($r as $rr) {
            if ($twist == 'rotright') {
                $twist = 'rotleft';
            } else {
                $twist = 'rotright';
            }
            $ext = $phototypes[$rr['type']];
            if ($a->theme['template_engine'] === 'internal') {
                $imgalt_e = template_escape($rr['filename']);
                $desc_e = template_escape($rr['desc']);
            } else {
                $imgalt_e = $rr['filename'];
                $desc_e = $rr['desc'];
            }
            $o .= replace_macros($tpl, array('$id' => $rr['id'], '$twist' => ' ' . $twist . rand(2, 4), '$photolink' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'] . ($_GET['order'] === 'posted' ? '?f=&order=posted' : ''), '$phototitle' => t('View Photo'), '$imgsrc' => $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . $rr['scale'] . '.' . $ext, '$imgalt' => $imgalt_e, '$desc' => $desc_e));
        }
        $o .= '<div id="photo-album-end"></div>';
        $o .= paginate($a);
        return $o;
    }
    if ($datatype === 'image') {
        //$o = '';
        // fetch image, item containing image, then comments
        $ph = q("SELECT * FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' \n\t\t\t{$sql_extra} ORDER BY `scale` ASC ", intval($owner_uid), dbesc($datum));
        if (!count($ph)) {
            $ph = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'\n\t\t\t\tLIMIT 1", intval($owner_uid), dbesc($datum));
            if (count($ph)) {
                notice(t('Permission denied. Access to this item may be restricted.'));
            } else {
                notice(t('Photo not available') . EOL);
            }
            return;
        }
        $prevlink = '';
        $nextlink = '';
        if ($_GET['order'] === 'posted') {
            $order = 'ASC';
        } else {
            $order = 'DESC';
        }
        $prvnxt = q("SELECT `resource-id` FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `scale` = 0\n\t\t\t{$sql_extra} ORDER BY `created` {$order} ", dbesc($ph[0]['album']), intval($owner_uid));
        if (count($prvnxt)) {
            for ($z = 0; $z < count($prvnxt); $z++) {
                if ($prvnxt[$z]['resource-id'] == $ph[0]['resource-id']) {
                    $prv = $z - 1;
                    $nxt = $z + 1;
                    if ($prv < 0) {
                        $prv = count($prvnxt) - 1;
                    }
                    if ($nxt >= count($prvnxt)) {
                        $nxt = 0;
                    }
                    break;
                }
            }
            $edit_suffix = $cmd === 'edit' && $can_post ? '/edit' : '';
            $prevlink = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . $edit_suffix . ($_GET['order'] === 'posted' ? '?f=&order=posted' : '');
            $nextlink = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . $edit_suffix . ($_GET['order'] === 'posted' ? '?f=&order=posted' : '');
        }
        if (count($ph) == 1) {
            $hires = $lores = $ph[0];
        }
        if (count($ph) > 1) {
            if ($ph[1]['scale'] == 2) {
                // original is 640 or less, we can display it directly
                $hires = $lores = $ph[0];
            } else {
                $hires = $ph[0];
                $lores = $ph[1];
            }
        }
        $album_link = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($ph[0]['album']);
        $tools = Null;
        $lock = Null;
        if ($can_post && $ph[0]['uid'] == $owner_uid) {
            $tools = array('edit' => array($a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $datum . ($cmd === 'edit' ? '' : '/edit'), $cmd === 'edit' ? t('View photo') : t('Edit photo')), 'profile' => array($a->get_baseurl() . '/profile_photo/use/' . $ph[0]['resource-id'], t('Use as profile photo')));
            // lock
            $lock = $ph[0]['uid'] == local_user() && (strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid']) || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid'])) ? t('Private Message') : Null;
        }
        if ($cmd === 'edit') {
            $tpl = get_markup_template('photo_edit_head.tpl');
            $a->page['htmlhead'] .= replace_macros($tpl, array('$prevlink' => $prevlink, '$nextlink' => $nextlink));
        }
        if ($prevlink) {
            $prevlink = array($prevlink, '<div class="icon prev"></div>');
        }
        $photo = array('href' => $a->get_baseurl() . '/photo/' . $hires['resource-id'] . '-' . $hires['scale'] . '.' . $phototypes[$hires['type']], 'title' => t('View Full Size'), 'src' => $a->get_baseurl() . '/photo/' . $lores['resource-id'] . '-' . $lores['scale'] . '.' . $phototypes[$lores['type']] . '?f=&_u=' . datetime_convert('', '', '', 'ymdhis'), 'height' => $hires['height'], 'width' => $hires['width'], 'album' => $hires['album'], 'filename' => $hires['filename']);
        if ($nextlink) {
            $nextlink = array($nextlink, '<div class="icon next"></div>');
        }
        // Do we have an item for this photo?
        // FIXME! - replace following code to display the conversation with our normal
        // conversation functions so that it works correctly and tracks changes
        // in the evolving conversation code.
        // The difference is that we won't be displaying the conversation head item
        // as a "post" but displaying instead the photo it is linked to
        $linked_items = q("SELECT * FROM `item` WHERE `resource-id` = '%s' {$sql_extra} LIMIT 1", dbesc($datum));
        if (count($linked_items)) {
            $link_item = $linked_items[0];
            $r = q("SELECT COUNT(*) AS `total`\n\t\t\t\tFROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\t\tWHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0 and `item`.`moderated` = 0\n\t\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\tAND `item`.`uid` = %d\n\t\t\t\t{$sql_extra} ", dbesc($link_item['uri']), dbesc($link_item['uri']), intval($link_item['uid']));
            if (count($r)) {
                $a->set_pager_total($r[0]['total']);
            }
            $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,\n\t\t\t\t`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`network`,\n\t\t\t\t`contact`.`rel`, `contact`.`thumb`, `contact`.`self`,\n\t\t\t\t`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`\n\t\t\t\tFROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\t\tWHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0 and `item`.`moderated` = 0\n\t\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\tAND `item`.`uid` = %d\n\t\t\t\t{$sql_extra}\n\t\t\t\tORDER BY `parent` DESC, `id` ASC LIMIT %d ,%d ", dbesc($link_item['uri']), dbesc($link_item['uri']), intval($link_item['uid']), intval($a->pager['start']), intval($a->pager['itemspage']));
            if (local_user() && local_user() == $link_item['uid']) {
                q("UPDATE `item` SET `unseen` = 0 WHERE `parent` = %d and `uid` = %d", intval($link_item['parent']), intval(local_user()));
                update_thread($link_item['parent']);
            }
        }
        $tags = Null;
        if (count($linked_items) && strlen($link_item['tag'])) {
            $arr = explode(',', $link_item['tag']);
            // parse tags and add links
            $tag_str = '';
            foreach ($arr as $t) {
                if (strlen($tag_str)) {
                    $tag_str .= ', ';
                }
                $tag_str .= bbcode($t);
            }
            $tags = array(t('Tags: '), $tag_str);
            if ($cmd === 'edit') {
                $tags[] = $a->get_baseurl() . '/tagrm/' . $link_item['id'];
                $tags[] = t('[Remove any tag]');
            }
        }
        $edit = Null;
        if ($cmd === 'edit' && $can_post) {
            $edit_tpl = get_markup_template('photo_edit.tpl');
            // Private/public post links for the non-JS ACL form
            $private_post = 1;
            if ($_REQUEST['public']) {
                $private_post = 0;
            }
            $query_str = $a->query_string;
            if (strpos($query_str, 'public=1') !== false) {
                $query_str = str_replace(array('?public=1', '&public=1'), array('', ''), $query_str);
            }
            // I think $a->query_string may never have ? in it, but I could be wrong
            // It looks like it's from the index.php?q=[etc] rewrite that the web
            // server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
            if (strpos($query_str, '?') === false) {
                $public_post_link = '?public=1';
            } else {
                $public_post_link = '&public=1';
            }
            if ($a->theme['template_engine'] === 'internal') {
                $album_e = template_escape($ph[0]['album']);
                $caption_e = template_escape($ph[0]['desc']);
                $aclselect_e = template_escape(populate_acl($ph[0]));
            } else {
                $album_e = $ph[0]['album'];
                $caption_e = $ph[0]['desc'];
                $aclselect_e = populate_acl($ph[0]);
            }
            $edit = replace_macros($edit_tpl, array('$id' => $ph[0]['id'], '$rotatecw' => t('Rotate CW (right)'), '$rotateccw' => t('Rotate CCW (left)'), '$album' => $album_e, '$newalbum' => t('New album name'), '$nickname' => $a->data['user']['nickname'], '$resource_id' => $ph[0]['resource-id'], '$capt_label' => t('Caption'), '$caption' => $caption_e, '$tag_label' => t('Add a Tag'), '$tags' => $link_item['tag'], '$permissions' => t('Permissions'), '$aclselect' => $aclselect_e, '$help_tags' => t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping'), '$item_id' => count($linked_items) ? $link_item['id'] : 0, '$submit' => t('Submit'), '$delete' => t('Delete Photo'), '$acl_data' => construct_acl_data($a, $ph[0]), '$group_perms' => t('Show to Groups'), '$contact_perms' => t('Show to Contacts'), '$private' => t('Private photo'), '$public' => t('Public photo'), '$is_private' => $private_post, '$return_path' => $query_str, '$public_link' => $public_post_link));
        }
        if (count($linked_items)) {
            $cmnt_tpl = get_markup_template('comment_item.tpl');
            $tpl = get_markup_template('photo_item.tpl');
            $return_url = $a->cmd;
            $like_tpl = get_markup_template('like_noshare.tpl');
            $likebuttons = '';
            if ($can_post || can_write_wall($a, $owner_uid)) {
                $likebuttons = replace_macros($like_tpl, array('$id' => $link_item['id'], '$likethis' => t("I like this (toggle)"), '$nolike' => feature_enabled(local_user(), 'dislike') ? t("I don't like this (toggle)") : '', '$share' => t('Share'), '$wait' => t('Please wait'), '$return_path' => $a->query_string));
            }
            $comments = '';
            if (!count($r)) {
                if ($can_post || can_write_wall($a, $owner_uid)) {
                    if ($link_item['last-child']) {
                        $comments .= replace_macros($cmnt_tpl, array('$return_path' => '', '$jsreload' => $return_url, '$type' => 'wall-comment', '$id' => $link_item['id'], '$parent' => $link_item['id'], '$profile_uid' => $owner_uid, '$mylink' => $contact['url'], '$mytitle' => t('This is you'), '$myphoto' => $contact['thumb'], '$comment' => t('Comment'), '$submit' => t('Submit'), '$preview' => t('Preview'), '$sourceapp' => t($a->sourcename), '$ww' => '', '$rand_num' => random_digits(12)));
                    }
                }
            }
            $alike = array();
            $dlike = array();
            $like = '';
            $dislike = '';
            // display comments
            if (count($r)) {
                foreach ($r as $item) {
                    like_puller($a, $item, $alike, 'like');
                    like_puller($a, $item, $dlike, 'dislike');
                }
                $like = isset($alike[$link_item['id']]) ? format_like($alike[$link_item['id']], $alike[$link_item['id'] . '-l'], 'like', $link_item['id']) : '';
                $dislike = isset($dlike[$link_item['id']]) ? format_like($dlike[$link_item['id']], $dlike[$link_item['id'] . '-l'], 'dislike', $link_item['id']) : '';
                if ($can_post || can_write_wall($a, $owner_uid)) {
                    if ($link_item['last-child']) {
                        $comments .= replace_macros($cmnt_tpl, array('$return_path' => '', '$jsreload' => $return_url, '$type' => 'wall-comment', '$id' => $link_item['id'], '$parent' => $link_item['id'], '$profile_uid' => $owner_uid, '$mylink' => $contact['url'], '$mytitle' => t('This is you'), '$myphoto' => $contact['thumb'], '$comment' => t('Comment'), '$submit' => t('Submit'), '$preview' => t('Preview'), '$sourceapp' => t($a->sourcename), '$ww' => '', '$rand_num' => random_digits(12)));
                    }
                }
                foreach ($r as $item) {
                    $comment = '';
                    $template = $tpl;
                    $sparkle = '';
                    if ((activity_match($item['verb'], ACTIVITY_LIKE) || activity_match($item['verb'], ACTIVITY_DISLIKE)) && $item['id'] != $item['parent']) {
                        continue;
                    }
                    $redirect_url = $a->get_baseurl() . '/redir/' . $item['cid'];
                    if (local_user() && $item['contact-uid'] == local_user() && $item['network'] == 'dfrn' && !$item['self']) {
                        $profile_url = $redirect_url;
                        $sparkle = ' sparkle';
                    } else {
                        $profile_url = $item['url'];
                        $sparkle = '';
                    }
                    $diff_author = $item['url'] !== $item['author-link'] ? true : false;
                    $profile_name = strlen($item['author-name']) && $diff_author ? $item['author-name'] : $item['name'];
                    $profile_avatar = strlen($item['author-avatar']) && $diff_author ? $item['author-avatar'] : $item['thumb'];
                    $profile_link = $profile_url;
                    $dropping = $item['contact-id'] == $contact_id || $item['uid'] == local_user();
                    $drop = array('dropping' => $dropping, 'pagedrop' => false, 'select' => t('Select'), 'delete' => t('Delete'));
                    if ($a->theme['template_engine'] === 'internal') {
                        $name_e = template_escape($profile_name);
                        $title_e = template_escape($item['title']);
                        $body_e = template_escape(bbcode($item['body']));
                    } else {
                        $name_e = $profile_name;
                        $title_e = $item['title'];
                        $body_e = bbcode($item['body']);
                    }
                    $comments .= replace_macros($template, array('$id' => $item['item_id'], '$profile_url' => $profile_link, '$name' => $name_e, '$thumb' => $profile_avatar, '$sparkle' => $sparkle, '$title' => $title_e, '$body' => $body_e, '$ago' => relative_date($item['created']), '$indent' => $item['parent'] != $item['item_id'] ? ' comment' : '', '$drop' => $drop, '$comment' => $comment));
                    if ($can_post || can_write_wall($a, $owner_uid)) {
                        if ($item['last-child']) {
                            $comments .= replace_macros($cmnt_tpl, array('$return_path' => '', '$jsreload' => $return_url, '$type' => 'wall-comment', '$id' => $item['item_id'], '$parent' => $item['parent'], '$profile_uid' => $owner_uid, '$mylink' => $contact['url'], '$mytitle' => t('This is you'), '$myphoto' => $contact['thumb'], '$comment' => t('Comment'), '$submit' => t('Submit'), '$preview' => t('Preview'), '$sourceapp' => t($a->sourcename), '$ww' => '', '$rand_num' => random_digits(12)));
                        }
                    }
                }
            }
            $paginate = paginate($a);
        }
        $photo_tpl = get_markup_template('photo_view.tpl');
        if ($a->theme['template_engine'] === 'internal') {
            $album_e = array($album_link, template_escape($ph[0]['album']));
            $tags_e = template_escape($tags);
            $like_e = template_escape($like);
            $dislike_e = template_escape($dislike);
        } else {
            $album_e = array($album_link, $ph[0]['album']);
            $tags_e = $tags;
            $like_e = $like;
            $dislike_e = $dislike;
        }
        $o .= replace_macros($photo_tpl, array('$id' => $ph[0]['id'], '$album' => $album_e, '$tools' => $tools, '$lock' => $lock, '$photo' => $photo, '$prevlink' => $prevlink, '$nextlink' => $nextlink, '$desc' => $ph[0]['desc'], '$tags' => $tags_e, '$edit' => $edit, '$likebuttons' => $likebuttons, '$like' => $like_e, '$dislike' => $dikslike_e, '$comments' => $comments, '$paginate' => $paginate));
        $a->page['htmlhead'] .= "\n" . '<meta name="twitter:card" content="photo" />' . "\n";
        $a->page['htmlhead'] .= '<meta name="twitter:title" content="' . $photo["album"] . '" />' . "\n";
        $a->page['htmlhead'] .= '<meta name="twitter:image" content="' . $photo["href"] . '" />' . "\n";
        $a->page['htmlhead'] .= '<meta name="twitter:image:width" content="' . $photo["width"] . '" />' . "\n";
        $a->page['htmlhead'] .= '<meta name="twitter:image:height" content="' . $photo["height"] . '" />' . "\n";
        return $o;
    }
    // Default - show recent photos with upload link (if applicable)
    //$o = '';
    $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' \n\t\t{$sql_extra} GROUP BY `resource-id`", intval($a->data['user']['uid']), dbesc('Contact Photos'), dbesc(t('Contact Photos')));
    if (count($r)) {
        $a->set_pager_total(count($r));
        $a->set_pager_itemspage(20);
    }
    $r = q("SELECT `resource-id`, `id`, `filename`, type, `album`, max(`scale`) AS `scale` FROM `photo`\n\t\tWHERE `uid` = %d AND `album` != '%s' AND `album` != '%s'  \n\t\t{$sql_extra} GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d", intval($a->data['user']['uid']), dbesc('Contact Photos'), dbesc(t('Contact Photos')), intval($a->pager['start']), intval($a->pager['itemspage']));
    $photos = array();
    if (count($r)) {
        $twist = 'rotright';
        foreach ($r as $rr) {
            if ($twist == 'rotright') {
                $twist = 'rotleft';
            } else {
                $twist = 'rotright';
            }
            $ext = $phototypes[$rr['type']];
            if ($a->theme['template_engine'] === 'internal') {
                $alt_e = template_escape($rr['filename']);
                $name_e = template_escape($rr['album']);
            } else {
                $alt_e = $rr['filename'];
                $name_e = $rr['album'];
            }
            $photos[] = array('id' => $rr['id'], 'twist' => ' ' . $twist . rand(2, 4), 'link' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'], 'title' => t('View Photo'), 'src' => $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . ($rr['scale'] == 6 ? 4 : $rr['scale']) . '.' . $ext, 'alt' => $alt_e, 'album' => array('link' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($rr['album']), 'name' => $name_e, 'alt' => t('View Album')));
        }
    }
    $tpl = get_markup_template('photos_recent.tpl');
    $o .= replace_macros($tpl, array('$title' => t('Recent Photos'), '$can_post' => $can_post, '$upload' => array(t('Upload New Photos'), $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/upload'), '$photos' => $photos));
    $o .= paginate($a);
    return $o;
}
Example #20
0
/**
 * @brief Create directory.
 *
 * @param array $channel channel array of owner
 * @param string $observer_hash hash of current observer
 * @param array $arr parameter array to fulfil request
 * - Required:
 *  * \e string \b filename
 *  * \e string \b folder hash of parent directory, empty string for root directory
 * - Optional:
 *  * \e string \b hash precomputed hash for this node
 *  * \e tring  \b allow_cid
 *  * \e string \b allow_gid
 *  * \e string \b deny_cid
 *  * \e string \b deny_gid
 * @return array
 */
function attach_mkdir($channel, $observer_hash, $arr = null)
{
    $ret = array('success' => false);
    $channel_id = $channel['channel_id'];
    $sql_options = '';
    $basepath = 'store/' . $channel['channel_address'];
    logger('attach_mkdir: basepath: ' . $basepath);
    if (!is_dir($basepath)) {
        os_mkdir($basepath, STORAGE_DEFAULT_PERMISSIONS, true);
    }
    if (!perm_is_allowed($channel_id, $observer_hash, 'write_storage')) {
        $ret['message'] = t('Permission denied.');
        return $ret;
    }
    if (!$arr['filename']) {
        $ret['message'] = t('Empty pathname');
        return $ret;
    }
    $arr['hash'] = $arr['hash'] ? $arr['hash'] : random_string();
    // Check for duplicate name.
    // Check both the filename and the hash as we will be making use of both.
    $r = q("select id, hash, is_dir, flags from attach where ( filename = '%s' or hash = '%s' ) and folder = '%s' and uid = %d limit 1", dbesc($arr['filename']), dbesc($arr['hash']), dbesc($arr['folder']), intval($channel['channel_id']));
    if ($r) {
        if (array_key_exists('force', $arr) && intval($arr['force']) && intval($r[0]['is_dir'])) {
            $ret['success'] = true;
            $r = q("select * from attach where id = %d limit 1", intval($r[0]['id']));
            if ($r) {
                $ret['data'] = $r[0];
            }
            return $ret;
        }
        $ret['message'] = t('duplicate filename or path');
        return $ret;
    }
    if ($arr['folder']) {
        // Walk the directory tree from parent back to root to make sure the parent is valid and name is unique and we
        // have permission to see this path. This implies the root directory itself is public since we won't have permissions
        // set on the psuedo-directory. We can however set permissions for anything and everything contained within it.
        $lpath = '';
        $lfile = $arr['folder'];
        $sql_options = permissions_sql($channel['channel_id']);
        do {
            $r = q("select filename, hash, flags, is_dir, folder from attach where uid = %d and hash = '%s' and is_dir != 0\n\t\t\t\t{$sql_options} limit 1", intval($channel['channel_id']), dbesc($lfile));
            if (!$r) {
                logger('attach_mkdir: hash ' . $lfile . ' not found in ' . $lpath);
                $ret['message'] = t('Path not found.');
                return $ret;
            }
            if ($lfile) {
                $lpath = $r[0]['hash'] . '/' . $lpath;
            }
            $lfile = $r[0]['folder'];
        } while ($r[0]['folder'] && intval($r[0]['is_dir']));
        $path = $basepath . '/' . $lpath;
    } else {
        $path = $basepath . '/';
    }
    $path .= $arr['hash'];
    $created = datetime_convert();
    $r = q("INSERT INTO attach ( aid, uid, hash, creator, filename, filetype, filesize, revision, folder, os_storage, is_dir, data, created, edited, allow_cid, allow_gid, deny_cid, deny_gid )\n\t\tVALUES ( %d, %d, '%s', '%s', '%s', '%s', %d, %d, '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ", intval($channel['channel_account_id']), intval($channel_id), dbesc($arr['hash']), dbesc(get_observer_hash()), dbesc($arr['filename']), dbesc('multipart/mixed'), intval(0), intval(0), dbesc($arr['folder']), intval(1), intval(1), dbesc($path), dbesc($created), dbesc($created), dbesc($arr && array_key_exists('allow_cid', $arr) ? $arr['allow_cid'] : $channel['channel_allow_cid']), dbesc($arr && array_key_exists('allow_gid', $arr) ? $arr['allow_gid'] : $channel['channel_allow_gid']), dbesc($arr && array_key_exists('deny_cid', $arr) ? $arr['deny_cid'] : $channel['channel_deny_cid']), dbesc($arr && array_key_exists('deny_gid', $arr) ? $arr['deny_gid'] : $channel['channel_deny_gid']));
    if ($r) {
        if (os_mkdir($path, STORAGE_DEFAULT_PERMISSIONS, true)) {
            $ret['success'] = true;
            // update the parent folder's lastmodified timestamp
            $e = q("UPDATE attach SET edited = '%s' WHERE hash = '%s' AND uid = %d", dbesc($created), dbesc($arr['folder']), intval($channel_id));
            $z = q("select * from attach where hash = '%s' and uid = %d and is_dir = 1 limit 1", dbesc($arr['hash']), intval($channel_id));
            if ($z) {
                $ret['data'] = $z[0];
            }
        } else {
            logger('attach_mkdir: ' . mkdir . ' ' . $path . ' failed.');
            $ret['message'] = t('mkdir failed.');
        }
    } else {
        $ret['message'] = t('database storage failed.');
    }
    return $ret;
}
Example #21
0
/**
 * @brief TODO What exactly is this function for?
 *
 * @fixme function name looks like a class name, should we rename it?
 *
 * @param string $file
 *  path to file or directory
 * @param RedBasicAuth &$auth
 * @param boolean $test (optional) enable test mode
 * @return RedFile|RedDirectory|boolean|null
 * @throw \Sabre\DAV\Exception\Forbidden
 */
function RedFileData($file, &$auth, $test = false)
{
    logger($file . ($test ? ' (test mode) ' : ''), LOGGER_DATA);
    $x = strpos($file, '/cloud');
    if ($x === 0) {
        $file = substr($file, 6);
    }
    if (!$file || $file === '/') {
        return new RedDAV\RedDirectory('/', $auth);
    }
    $file = trim($file, '/');
    $path_arr = explode('/', $file);
    if (!$path_arr) {
        return null;
    }
    $channel_name = $path_arr[0];
    $r = q("select channel_id from channel where channel_address = '%s' limit 1", dbesc($channel_name));
    if (!$r) {
        return null;
    }
    $channel_id = $r[0]['channel_id'];
    $path = '/' . $channel_name;
    $auth->owner_id = $channel_id;
    $permission_error = false;
    $folder = '';
    require_once 'include/security.php';
    $perms = permissions_sql($channel_id);
    $errors = false;
    for ($x = 1; $x < count($path_arr); $x++) {
        $r = q("select id, hash, filename, flags from attach where folder = '%s' and filename = '%s' and uid = %d and (flags & %d)>0 {$perms}", dbesc($folder), dbesc($path_arr[$x]), intval($channel_id), intval(ATTACH_FLAG_DIR));
        if ($r && $r[0]['flags'] & ATTACH_FLAG_DIR) {
            $folder = $r[0]['hash'];
            $path = $path . '/' . $r[0]['filename'];
        }
        if (!$r) {
            $r = q("select id, uid, hash, filename, filetype, filesize, revision, folder, flags, created, edited from attach \n\t\t\t\twhere folder = '%s' and filename = '%s' and uid = %d {$perms} order by filename limit 1", dbesc($folder), dbesc(basename($file)), intval($channel_id));
        }
        if (!$r) {
            $errors = true;
            $r = q("select id, uid, hash, filename, filetype, filesize, revision, folder, flags, created, edited from attach \n\t\t\t\twhere folder = '%s' and filename = '%s' and uid = %d order by filename limit 1", dbesc($folder), dbesc(basename($file)), intval($channel_id));
            if ($r) {
                $permission_error = true;
            }
        }
    }
    if ($path === '/' . $file) {
        if ($test) {
            return true;
        }
        // final component was a directory.
        return new RedDAV\RedDirectory('/cloud/' . $file, $auth);
    }
    if ($errors) {
        logger('not found ' . $file);
        if ($test) {
            return false;
        }
        if ($permission_error) {
            logger('permission error ' . $file);
            throw new DAV\Exception\Forbidden('Permission denied.');
        }
        return;
    }
    if ($r) {
        if ($test) {
            return true;
        }
        if ($r[0]['flags'] & ATTACH_FLAG_DIR) {
            // @todo can't we drop '/cloud'? it gets stripped off anyway in RedDirectory
            return new RedDAV\RedDirectory('/cloud' . $path . '/' . $r[0]['filename'], $auth);
        } else {
            return new RedDAV\RedFile('/cloud' . $path . '/' . $r[0]['filename'], $r[0], $auth);
        }
    }
    return false;
}
Example #22
0
function photos_content(&$a)
{
    // URLs:
    // photos/name
    // photos/name/album/xxxxx (xxxxx is album name)
    // photos/name/image/xxxxx
    if (get_config('system', 'block_public') && !local_channel() && !remote_channel()) {
        notice(t('Public access denied.') . EOL);
        return;
    }
    $unsafe = array_key_exists('unsafe', $_REQUEST) && $_REQUEST['unsafe'] ? 1 : 0;
    require_once 'include/bbcode.php';
    require_once 'include/security.php';
    require_once 'include/conversation.php';
    if (!x($a->data, 'channel')) {
        notice(t('No photos selected') . EOL);
        return;
    }
    $ph = photo_factory('');
    $phototypes = $ph->supportedTypes();
    $_SESSION['photo_return'] = $a->cmd;
    //
    // Parse arguments
    //
    $can_comment = perm_is_allowed($a->profile['profile_uid'], get_observer_hash(), 'post_comments');
    if (argc() > 3) {
        $datatype = argv(2);
        $datum = argv(3);
    } else {
        if (argc() > 2) {
            $datatype = argv(2);
            $datum = '';
        } else {
            $datatype = 'summary';
        }
    }
    if (argc() > 4) {
        $cmd = argv(4);
    } else {
        $cmd = 'view';
    }
    //
    // Setup permissions structures
    //
    $can_post = false;
    $visitor = 0;
    $owner_uid = $a->data['channel']['channel_id'];
    $owner_aid = $a->data['channel']['channel_account_id'];
    $observer = $a->get_observer();
    $can_post = perm_is_allowed($owner_uid, $observer['xchan_hash'], 'write_storage');
    $can_view = perm_is_allowed($owner_uid, $observer['xchan_hash'], 'view_storage');
    if (!$can_view) {
        notice(t('Access to this item is restricted.') . EOL);
        return;
    }
    $sql_extra = permissions_sql($owner_uid);
    $o = "";
    $o .= "<script> var profile_uid = " . $a->profile['profile_uid'] . "; var netargs = '?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
    // tabs
    $_is_owner = local_channel() && local_channel() == $owner_uid;
    $o .= profile_tabs($a, $_is_owner, $a->data['channel']['channel_address']);
    /**
     * Display upload form
     */
    if ($can_post) {
        $uploader = '';
        $ret = array('post_url' => $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'], 'addon_text' => $uploader, 'default_upload' => true);
        call_hooks('photo_upload_form', $ret);
        /* Show space usage */
        $r = q("select sum(size) as total from photo where aid = %d and scale = 0 ", intval($a->data['channel']['channel_account_id']));
        $limit = service_class_fetch($a->data['channel']['channel_id'], 'photo_upload_limit');
        if ($limit !== false) {
            $usage_message = sprintf(t("%1\$.2f MB of %2\$.2f MB photo storage used."), $r[0]['total'] / 1024000, $limit / 1024000);
        } else {
            $usage_message = sprintf(t('%1$.2f MB photo storage used.'), $r[0]['total'] / 1024000);
        }
        if ($_is_owner) {
            $channel = $a->get_channel();
            $acl = new AccessList($channel);
            $channel_acl = $acl->get();
            $lockstate = $acl->is_private() ? 'lock' : 'unlock';
        }
        $aclselect = $_is_owner ? populate_acl($channel_acl, false) : '';
        $selname = $datum ? hex2bin($datum) : '';
        $albums = array_key_exists('albums', $a->data) ? $a->data['albums'] : photos_albums_list($a->data['channel'], $a->data['observer']);
        if (!$selname) {
            $def_album = get_pconfig($a->data['channel']['channel_id'], 'system', 'photo_path');
            if ($def_album) {
                $selname = filepath_macro($def_album);
                $albums['album'][] = array('text' => $selname);
            }
        }
        $tpl = get_markup_template('photos_upload.tpl');
        $upload_form = replace_macros($tpl, array('$pagename' => t('Upload Photos'), '$sessid' => session_id(), '$usage' => $usage_message, '$nickname' => $a->data['channel']['channel_address'], '$newalbum_label' => t('Enter an album name'), '$newalbum_placeholder' => t('or select an existing album (doubleclick)'), '$visible' => array('visible', t('Create a status post for this upload'), 0, '', array(t('No'), t('Yes'))), '$albums' => $albums['albums'], '$selname' => $selname, '$permissions' => t('Permissions'), '$aclselect' => $aclselect, '$lockstate' => $lockstate, '$uploader' => $ret['addon_text'], '$default' => $ret['default_upload'] ? true : false, '$uploadurl' => $ret['post_url'], '$submit' => t('Submit')));
    }
    //
    // dispatch request
    //
    /*
     * Display a single photo album
     */
    if ($datatype === 'album') {
        if (strlen($datum)) {
            if (strlen($datum) & 1 || !ctype_xdigit($datum)) {
                notice(t('Album name could not be decoded') . EOL);
                logger('mod_photos: illegal album encoding: ' . $datum);
                $datum = '';
            }
        }
        $album = $datum ? hex2bin($datum) : '';
        $r = q("SELECT `resource_id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s' \n\t\t\tAND `scale` <= 4 and photo_usage IN ( %d, %d ) and is_nsfw = %d {$sql_extra} GROUP BY `resource_id`", intval($owner_uid), dbesc($album), intval(PHOTO_NORMAL), intval(PHOTO_PROFILE), intval($unsafe));
        if (count($r)) {
            $a->set_pager_total(count($r));
            $a->set_pager_itemspage(60);
        } else {
            goaway($a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address']);
        }
        if ($_GET['order'] === 'posted') {
            $order = 'ASC';
        } else {
            $order = 'DESC';
        }
        $r = q("SELECT p.resource_id, p.id, p.filename, p.type, p.scale, p.description, p.created FROM photo p INNER JOIN\n\t\t\t\t(SELECT resource_id, max(scale) scale FROM photo WHERE uid = %d AND album = '%s' AND scale <= 4 AND photo_usage IN ( %d, %d ) and is_nsfw = %d {$sql_extra} GROUP BY resource_id) ph \n\t\t\t\tON (p.resource_id = ph.resource_id AND p.scale = ph.scale)\n\t\t\tORDER BY created {$order} LIMIT %d OFFSET %d", intval($owner_uid), dbesc($album), intval(PHOTO_NORMAL), intval(PHOTO_PROFILE), intval($unsafe), intval($a->pager['itemspage']), intval($a->pager['start']));
        //edit album name
        $album_edit = null;
        if ($album !== t('Profile Photos') && $album !== 'Profile Photos' && $album !== 'Contact Photos' && $album !== t('Contact Photos')) {
            if ($can_post) {
                if ($a->get_template_engine() === 'internal') {
                    $album_e = template_escape($album);
                } else {
                    $album_e = $album;
                }
                $albums = array_key_exists('albums', $a->data) ? $a->data['albums'] : photos_albums_list($a->data['channel'], $a->data['observer']);
                // @fixme - syncronise actions with DAV
                //				$edit_tpl = get_markup_template('album_edit.tpl');
                //				$album_edit = replace_macros($edit_tpl,array(
                //					'$nametext' => t('Enter a new album name'),
                //					'$name_placeholder' => t('or select an existing one (doubleclick)'),
                //					'$nickname' => $a->data['channel']['channel_address'],
                //					'$album' => $album_e,
                //					'$albums' => $albums['albums'],
                //					'$hexalbum' => bin2hex($album),
                //					'$submit' => t('Submit'),
                //					'$dropsubmit' => t('Delete Album')
                //				));
            }
        }
        if ($_GET['order'] === 'posted') {
            $order = array(t('Show Newest First'), $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/album/' . bin2hex($album));
        } else {
            $order = array(t('Show Oldest First'), $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/album/' . bin2hex($album) . '?f=&order=posted');
        }
        $photos = array();
        if (count($r)) {
            $twist = 'rotright';
            foreach ($r as $rr) {
                if ($twist == 'rotright') {
                    $twist = 'rotleft';
                } else {
                    $twist = 'rotright';
                }
                $ext = $phototypes[$rr['type']];
                $imgalt_e = $rr['filename'];
                $desc_e = $rr['description'];
                $imagelink = $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/image/' . $rr['resource_id'] . ($_GET['order'] === 'posted' ? '?f=&order=posted' : '');
                $photos[] = array('id' => $rr['id'], 'twist' => ' ' . $twist . rand(2, 4), 'link' => $imagelink, 'title' => t('View Photo'), 'src' => $a->get_baseurl() . '/photo/' . $rr['resource_id'] . '-' . $rr['scale'] . '.' . $ext, 'alt' => $imgalt_e, 'desc' => $desc_e, 'ext' => $ext, 'hash' => $rr['resource_id'], 'unknown' => t('Unknown'));
            }
        }
        if ($_REQUEST['aj']) {
            if ($photos) {
                $o = replace_macros(get_markup_template('photosajax.tpl'), array('$photos' => $photos));
            } else {
                $o = '<div id="content-complete"></div>';
            }
            echo $o;
            killme();
        } else {
            $o .= "<script> var page_query = '" . $_GET['q'] . "'; var extra_args = '" . extra_query_args() . "' ; </script>";
            $tpl = get_markup_template('photo_album.tpl');
            $o .= replace_macros($tpl, array('$photos' => $photos, '$album' => $album, '$album_edit' => array(t('Edit Album'), $album_edit), '$can_post' => $can_post, '$upload' => array(t('Upload'), $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/upload/' . bin2hex($album)), '$order' => $order, '$upload_form' => $upload_form, '$usage' => $usage_message));
        }
        if (!$photos && $_REQUEST['aj']) {
            $o .= '<div id="content-complete"></div>';
            echo $o;
            killme();
        }
        //		$o .= paginate($a);
        return $o;
    }
    /** 
     * Display one photo
     */
    if ($datatype === 'image') {
        // fetch image, item containing image, then comments
        $ph = q("SELECT id,aid,uid,xchan,resource_id,created,edited,title,`description`,album,filename,`type`,height,width,`size`,scale,photo_usage,is_nsfw,allow_cid,allow_gid,deny_cid,deny_gid FROM `photo` WHERE `uid` = %d AND `resource_id` = '%s' \n\t\t\t{$sql_extra} ORDER BY `scale` ASC ", intval($owner_uid), dbesc($datum));
        if (!$ph) {
            /* Check again - this time without specifying permissions */
            $ph = q("SELECT id FROM photo WHERE uid = %d AND resource_id = '%s' LIMIT 1", intval($owner_uid), dbesc($datum));
            if ($ph) {
                notice(t('Permission denied. Access to this item may be restricted.') . EOL);
            } else {
                notice(t('Photo not available') . EOL);
            }
            return;
        }
        $prevlink = '';
        $nextlink = '';
        if ($_GET['order'] === 'posted') {
            $order = 'ASC';
        } else {
            $order = 'DESC';
        }
        $prvnxt = q("SELECT `resource_id` FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `scale` = 0 \n\t\t\t{$sql_extra} ORDER BY `created` {$order} ", dbesc($ph[0]['album']), intval($owner_uid));
        if (count($prvnxt)) {
            for ($z = 0; $z < count($prvnxt); $z++) {
                if ($prvnxt[$z]['resource_id'] == $ph[0]['resource_id']) {
                    $prv = $z - 1;
                    $nxt = $z + 1;
                    if ($prv < 0) {
                        $prv = count($prvnxt) - 1;
                    }
                    if ($nxt >= count($prvnxt)) {
                        $nxt = 0;
                    }
                    break;
                }
            }
            $prevlink = $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/image/' . $prvnxt[$prv]['resource_id'] . ($_GET['order'] === 'posted' ? '?f=&order=posted' : '');
            $nextlink = $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/image/' . $prvnxt[$nxt]['resource_id'] . ($_GET['order'] === 'posted' ? '?f=&order=posted' : '');
        }
        if (count($ph) == 1) {
            $hires = $lores = $ph[0];
        }
        if (count($ph) > 1) {
            if ($ph[1]['scale'] == 2) {
                // original is 640 or less, we can display it directly
                $hires = $lores = $ph[0];
            } else {
                $hires = $ph[0];
                $lores = $ph[1];
            }
        }
        $album_link = $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/album/' . bin2hex($ph[0]['album']);
        $tools = Null;
        $lock = Null;
        if ($can_post && $ph[0]['uid'] == $owner_uid) {
            $tools = array('profile' => array($a->get_baseurl() . '/profile_photo/use/' . $ph[0]['resource_id'], t('Use as profile photo')));
        }
        // lockstate
        $lockstate = strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid']) || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid']) ? array('lock', t('Private Photo')) : array('unlock', Null);
        $a->page['htmlhead'] .= '<script>$(document).keydown(function(event) {' . "\n";
        if ($prevlink) {
            $a->page['htmlhead'] .= 'if(event.ctrlKey && event.keyCode == 37) { event.preventDefault(); window.location.href = \'' . $prevlink . '\'; }' . "\n";
        }
        if ($nextlink) {
            $a->page['htmlhead'] .= 'if(event.ctrlKey && event.keyCode == 39) { event.preventDefault(); window.location.href = \'' . $nextlink . '\'; }' . "\n";
        }
        $a->page['htmlhead'] .= '});</script>';
        if ($prevlink) {
            $prevlink = array($prevlink, t('Previous'));
        }
        $photo = array('href' => $a->get_baseurl() . '/photo/' . $hires['resource_id'] . '-' . $hires['scale'] . '.' . $phototypes[$hires['type']], 'title' => t('View Full Size'), 'src' => $a->get_baseurl() . '/photo/' . $lores['resource_id'] . '-' . $lores['scale'] . '.' . $phototypes[$lores['type']] . '?f=&_u=' . datetime_convert('', '', '', 'ymdhis'));
        if ($nextlink) {
            $nextlink = array($nextlink, t('Next'));
        }
        // Do we have an item for this photo?
        $linked_items = q("SELECT * FROM item WHERE resource_id = '%s' and resource_type = 'photo' \n\t\t\t{$sql_extra} LIMIT 1", dbesc($datum));
        $map = null;
        if ($linked_items) {
            xchan_query($linked_items);
            $linked_items = fetch_post_tags($linked_items, true);
            $link_item = $linked_items[0];
            $item_normal = item_normal();
            $r = q("select * from item where parent_mid = '%s' \n\t\t\t\t{$item_normal} and uid = %d {$sql_extra} ", dbesc($link_item['mid']), intval($link_item['uid']));
            if ($r) {
                xchan_query($r);
                $r = fetch_post_tags($r, true);
                $r = conv_sort($r, 'commented');
            }
            $tags = array();
            if ($link_item['term']) {
                $cnt = 0;
                foreach ($link_item['term'] as $t) {
                    $tags[$cnt] = array(0 => format_term_for_display($t));
                    if ($can_post && $ph[0]['uid'] == $owner_uid) {
                        $tags[$cnt][1] = 'tagrm/drop/' . $link_item['id'] . '/' . bin2hex($t['term']);
                        //?f=&item=' . $link_item['id'];
                        $tags[$cnt][2] = t('Remove');
                    }
                    $cnt++;
                }
            }
            if (local_channel() && local_channel() == $link_item['uid']) {
                q("UPDATE `item` SET item_unseen = 0 WHERE parent = %d and uid = %d and item_unseen = 1", intval($link_item['parent']), intval(local_channel()));
            }
            if ($link_item['coord']) {
                $map = generate_map($link_item['coord']);
            }
        }
        //		logger('mod_photo: link_item' . print_r($link_item,true));
        // FIXME - remove this when we move to conversation module
        $r = $r[0]['children'];
        $edit = null;
        if ($can_post) {
            $album_e = $ph[0]['album'];
            $caption_e = $ph[0]['description'];
            $aclselect_e = $_is_owner ? populate_acl($ph[0]) : '';
            $albums = array_key_exists('albums', $a->data) ? $a->data['albums'] : photos_albums_list($a->data['channel'], $a->data['observer']);
            $_SESSION['album_return'] = bin2hex($ph[0]['album']);
            $edit = array('edit' => t('Edit photo'), 'id' => $link_item['id'], 'rotatecw' => t('Rotate CW (right)'), 'rotateccw' => t('Rotate CCW (left)'), 'albums' => $albums['albums'], 'album' => $album_e, 'newalbum_label' => t('Enter a new album name'), 'newalbum_placeholder' => t('or select an existing one (doubleclick)'), 'nickname' => $a->data['channel']['channel_address'], 'resource_id' => $ph[0]['resource_id'], 'capt_label' => t('Caption'), 'caption' => $caption_e, 'tag_label' => t('Add a Tag'), 'permissions' => t('Permissions'), 'aclselect' => $aclselect_e, 'lockstate' => $lockstate[0], 'help_tags' => t('Example: @bob, @Barbara_Jensen, @jim@example.com'), 'item_id' => count($linked_items) ? $link_item['id'] : 0, 'adult_enabled' => feature_enabled($owner_uid, 'adult_photo_flagging'), 'adult' => array('adult', t('Flag as adult in album view'), intval($ph[0]['is_nsfw']), ''), 'submit' => t('Submit'), 'delete' => t('Delete Photo'));
        }
        if (count($linked_items)) {
            $cmnt_tpl = get_markup_template('comment_item.tpl');
            $tpl = get_markup_template('photo_item.tpl');
            $return_url = $a->cmd;
            $like_tpl = get_markup_template('like_noshare.tpl');
            $likebuttons = '';
            if ($can_post || $can_comment) {
                $likebuttons = array('id' => $link_item['id'], 'likethis' => t("I like this (toggle)"), 'nolike' => t("I don't like this (toggle)"), 'share' => t('Share'), 'wait' => t('Please wait'));
            }
            $comments = '';
            if (!count($r)) {
                if ($can_post || $can_comment) {
                    $commentbox = replace_macros($cmnt_tpl, array('$return_path' => '', '$mode' => 'photos', '$jsreload' => $return_url, '$type' => 'wall-comment', '$id' => $link_item['id'], '$parent' => $link_item['id'], '$profile_uid' => $owner_uid, '$mylink' => $observer['xchan_url'], '$mytitle' => t('This is you'), '$myphoto' => $observer['xchan_photo_s'], '$comment' => t('Comment'), '$submit' => t('Submit'), '$preview' => t('Preview'), '$ww' => '', '$feature_encrypt' => false));
                }
            }
            $alike = array();
            $dlike = array();
            $like = '';
            $dislike = '';
            $conv_responses = array('like' => array('title' => t('Likes', 'title')), 'dislike' => array('title' => t('Dislikes', 'title')), 'agree' => array('title' => t('Agree', 'title')), 'disagree' => array('title' => t('Disagree', 'title')), 'abstain' => array('title' => t('Abstain', 'title')), 'attendyes' => array('title' => t('Attending', 'title')), 'attendno' => array('title' => t('Not attending', 'title')), 'attendmaybe' => array('title' => t('Might attend', 'title')));
            if ($r) {
                foreach ($r as $item) {
                    builtin_activity_puller($item, $conv_responses);
                }
                $like_count = x($alike, $link_item['mid']) ? $alike[$link_item['mid']] : '';
                $like_list = x($alike, $link_item['mid']) ? $alike[$link_item['mid'] . '-l'] : '';
                if (count($like_list) > MAX_LIKERS) {
                    $like_list_part = array_slice($like_list, 0, MAX_LIKERS);
                    array_push($like_list_part, '<a href="#" data-toggle="modal" data-target="#likeModal-' . $this->get_id() . '"><b>' . t('View all') . '</b></a>');
                } else {
                    $like_list_part = '';
                }
                $like_button_label = tt('Like', 'Likes', $like_count, 'noun');
                //if (feature_enabled($conv->get_profile_owner(),'dislike')) {
                $dislike_count = x($dlike, $link_item['mid']) ? $dlike[$link_item['mid']] : '';
                $dislike_list = x($dlike, $link_item['mid']) ? $dlike[$link_item['mid'] . '-l'] : '';
                $dislike_button_label = tt('Dislike', 'Dislikes', $dislike_count, 'noun');
                if (count($dislike_list) > MAX_LIKERS) {
                    $dislike_list_part = array_slice($dislike_list, 0, MAX_LIKERS);
                    array_push($dislike_list_part, '<a href="#" data-toggle="modal" data-target="#dislikeModal-' . $this->get_id() . '"><b>' . t('View all') . '</b></a>');
                } else {
                    $dislike_list_part = '';
                }
                //}
                $like = isset($alike[$link_item['mid']]) ? format_like($alike[$link_item['mid']], $alike[$link_item['mid'] . '-l'], 'like', $link_item['mid']) : '';
                $dislike = isset($dlike[$link_item['mid']]) ? format_like($dlike[$link_item['mid']], $dlike[$link_item['mid'] . '-l'], 'dislike', $link_item['mid']) : '';
                // display comments
                foreach ($r as $item) {
                    $comment = '';
                    $template = $tpl;
                    $sparkle = '';
                    if ((activity_match($item['verb'], ACTIVITY_LIKE) || activity_match($item['verb'], ACTIVITY_DISLIKE)) && $item['id'] != $item['parent']) {
                        continue;
                    }
                    $redirect_url = $a->get_baseurl() . '/redir/' . $item['cid'];
                    $profile_url = zid($item['author']['xchan_url']);
                    $sparkle = '';
                    $profile_name = $item['author']['xchan_name'];
                    $profile_avatar = $item['author']['xchan_photo_m'];
                    $profile_link = $profile_url;
                    $drop = '';
                    if ($observer['xchan_hash'] === $item['author_xchan'] || $observer['xchan_hash'] === $item['owner_xchan']) {
                        $drop = replace_macros(get_markup_template('photo_drop.tpl'), array('$id' => $item['id'], '$delete' => t('Delete')));
                    }
                    $name_e = $profile_name;
                    $title_e = $item['title'];
                    unobscure($item);
                    $body_e = prepare_text($item['body'], $item['mimetype']);
                    $comments .= replace_macros($template, array('$id' => $item['id'], '$mode' => 'photos', '$profile_url' => $profile_link, '$name' => $name_e, '$thumb' => $profile_avatar, '$sparkle' => $sparkle, '$title' => $title_e, '$body' => $body_e, '$ago' => relative_date($item['created']), '$indent' => $item['parent'] != $item['id'] ? ' comment' : '', '$drop' => $drop, '$comment' => $comment));
                }
                if ($can_post || $can_comment) {
                    $commentbox = replace_macros($cmnt_tpl, array('$return_path' => '', '$jsreload' => $return_url, '$type' => 'wall-comment', '$id' => $link_item['id'], '$parent' => $link_item['id'], '$profile_uid' => $owner_uid, '$mylink' => $observer['xchan_url'], '$mytitle' => t('This is you'), '$myphoto' => $observer['xchan_photo_s'], '$comment' => t('Comment'), '$submit' => t('Submit'), '$ww' => ''));
                }
            }
            $paginate = paginate($a);
        }
        $album_e = array($album_link, $ph[0]['album']);
        $like_e = $like;
        $dislike_e = $dislike;
        $response_verbs = array('like');
        if (feature_enabled($owner_uid, 'dislike')) {
            $response_verbs[] = 'dislike';
        }
        $responses = get_responses($conv_responses, $response_verbs, '', $link_item);
        $photo_tpl = get_markup_template('photo_view.tpl');
        $o .= replace_macros($photo_tpl, array('$id' => $ph[0]['id'], '$album' => $album_e, '$tools' => $tools, '$lock' => $lockstate[1], '$photo' => $photo, '$prevlink' => $prevlink, '$nextlink' => $nextlink, '$desc' => $ph[0]['description'], '$filename' => $ph[0]['filename'], '$unknown' => t('Unknown'), '$tag_hdr' => t('In This Photo:'), '$tags' => $tags, 'responses' => $responses, '$edit' => $edit, '$map' => $map, '$map_text' => t('Map'), '$likebuttons' => $likebuttons, '$like' => $like_e, '$dislike' => $dislike_e, '$like_count' => $like_count, '$like_list' => $like_list, '$like_list_part' => $like_list_part, '$like_button_label' => $like_button_label, '$like_modal_title' => t('Likes', 'noun'), '$dislike_modal_title' => t('Dislikes', 'noun'), '$dislike_count' => $dislike_count, '$dislike_list' => $dislike_list, '$dislike_list_part' => $dislike_list_part, '$dislike_button_label' => $dislike_button_label, '$modal_dismiss' => t('Close'), '$comments' => $comments, '$commentbox' => $commentbox, '$paginate' => $paginate));
        $a->data['photo_html'] = $o;
        return $o;
    }
    // Default - show recent photos with upload link (if applicable)
    //$o = '';
    $r = q("SELECT `resource_id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' \n\t\tand photo_usage in ( %d, %d ) and is_nsfw = %d {$sql_extra} GROUP BY `resource_id`", intval($a->data['channel']['channel_id']), dbesc('Contact Photos'), dbesc(t('Contact Photos')), intval(PHOTO_NORMAL), intval(PHOTO_PROFILE), intval($unsafe));
    if (count($r)) {
        $a->set_pager_total(count($r));
        $a->set_pager_itemspage(60);
    }
    $r = q("SELECT p.resource_id, p.id, p.filename, p.type, p.album, p.scale, p.created FROM photo p INNER JOIN \n\t\t(SELECT resource_id, max(scale) scale FROM photo \n\t\t\tWHERE uid=%d AND album != '%s' AND album != '%s' \n\t\t\tAND photo_usage IN ( %d, %d ) and is_nsfw = %d {$sql_extra} group by resource_id) ph \n\t\tON (p.resource_id = ph.resource_id and p.scale = ph.scale) ORDER by p.created DESC LIMIT %d OFFSET %d", intval($a->data['channel']['channel_id']), dbesc('Contact Photos'), dbesc(t('Contact Photos')), intval(PHOTO_NORMAL), intval(PHOTO_PROFILE), intval($unsafe), intval($a->pager['itemspage']), intval($a->pager['start']));
    $photos = array();
    if (count($r)) {
        $twist = 'rotright';
        foreach ($r as $rr) {
            if ($twist == 'rotright') {
                $twist = 'rotleft';
            } else {
                $twist = 'rotright';
            }
            $ext = $phototypes[$rr['type']];
            if ($a->get_template_engine() === 'internal') {
                $alt_e = template_escape($rr['filename']);
                $name_e = template_escape($rr['album']);
            } else {
                $alt_e = $rr['filename'];
                $name_e = $rr['album'];
            }
            $photos[] = array('id' => $rr['id'], 'twist' => ' ' . $twist . rand(2, 4), 'link' => $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/image/' . $rr['resource_id'], 'title' => t('View Photo'), 'src' => $a->get_baseurl() . '/photo/' . $rr['resource_id'] . '-' . ($rr['scale'] == 6 ? 4 : $rr['scale']) . '.' . $ext, 'alt' => $alt_e, 'album' => array('link' => $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/album/' . bin2hex($rr['album']), 'name' => $name_e, 'alt' => t('View Album')));
        }
    }
    if ($_REQUEST['aj']) {
        if ($photos) {
            $o = replace_macros(get_markup_template('photosajax.tpl'), array('$photos' => $photos));
        } else {
            $o = '<div id="content-complete"></div>';
        }
        echo $o;
        killme();
    } else {
        $o .= "<script> var page_query = '" . $_GET['q'] . "'; var extra_args = '" . extra_query_args() . "' ; </script>";
        $tpl = get_markup_template('photos_recent.tpl');
        $o .= replace_macros($tpl, array('$title' => t('Recent Photos'), '$can_post' => $can_post, '$upload' => array(t('Upload'), $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/upload'), '$photos' => $photos, '$upload_form' => $upload_form, '$usage' => $usage_message));
    }
    if (!$photos && $_REQUEST['aj']) {
        $o .= '<div id="content-complete"></div>';
        echo $o;
        killme();
    }
    //	paginate($a);
    return $o;
}
Example #23
0
 function get()
 {
     if (observer_prohibited()) {
         return;
     }
     $channel = null;
     if (argc() > 1) {
         $channel = channelx_by_nick(argv(1));
     }
     if (!$channel) {
         notice(t('Channel not found.') . EOL);
         return;
     }
     // since we don't currently have an event permission - use the stream permission
     if (!perm_is_allowed($channel['channel_id'], get_observer_hash(), 'view_stream')) {
         notice(t('Permissions denied.') . EOL);
         return;
     }
     $sql_extra = permissions_sql($channel['channel_id'], get_observer_hash(), 'event');
     $first_day = get_pconfig(local_channel(), 'system', 'cal_first_day');
     $first_day = $first_day ? $first_day : 0;
     $htpl = get_markup_template('event_head.tpl');
     \App::$page['htmlhead'] .= replace_macros($htpl, array('$baseurl' => z_root(), '$module_url' => '/cal/' . $channel['channel_address'], '$modparams' => 2, '$lang' => \App::$language, '$first_day' => $first_day));
     $o = '';
     $tabs = profile_tabs($a, True, $channel['channel_address']);
     $mode = 'view';
     $y = 0;
     $m = 0;
     $ignored = x($_REQUEST, 'ignored') ? " and dismissed = " . intval($_REQUEST['ignored']) . " " : '';
     // logger('args: ' . print_r(\App::$argv,true));
     if (argc() > 3 && intval(argv(2)) && intval(argv(3))) {
         $mode = 'view';
         $y = intval(argv(2));
         $m = intval(argv(3));
     }
     if (argc() <= 3) {
         $mode = 'view';
         $event_id = argv(2);
     }
     if ($mode == 'view') {
         /* edit/create form */
         if ($event_id) {
             $r = q("SELECT * FROM `event` WHERE event_hash = '%s' AND `uid` = %d LIMIT 1", dbesc($event_id), intval($channel['channel_id']));
             if (count($r)) {
                 $orig_event = $r[0];
             }
         }
         // Passed parameters overrides anything found in the DB
         if (!x($orig_event)) {
             $orig_event = array();
         }
         $tz = date_default_timezone_get();
         if (x($orig_event)) {
             $tz = $orig_event['adjust'] ? date_default_timezone_get() : 'UTC';
         }
         $syear = datetime_convert('UTC', $tz, $sdt, 'Y');
         $smonth = datetime_convert('UTC', $tz, $sdt, 'm');
         $sday = datetime_convert('UTC', $tz, $sdt, 'd');
         $shour = datetime_convert('UTC', $tz, $sdt, 'H');
         $sminute = datetime_convert('UTC', $tz, $sdt, 'i');
         $stext = datetime_convert('UTC', $tz, $sdt);
         $stext = substr($stext, 0, 14) . "00:00";
         $fyear = datetime_convert('UTC', $tz, $fdt, 'Y');
         $fmonth = datetime_convert('UTC', $tz, $fdt, 'm');
         $fday = datetime_convert('UTC', $tz, $fdt, 'd');
         $fhour = datetime_convert('UTC', $tz, $fdt, 'H');
         $fminute = datetime_convert('UTC', $tz, $fdt, 'i');
         $ftext = datetime_convert('UTC', $tz, $fdt);
         $ftext = substr($ftext, 0, 14) . "00:00";
         $type = x($orig_event) ? $orig_event['etype'] : 'event';
         $f = get_config('system', 'event_input_format');
         if (!$f) {
             $f = 'ymd';
         }
         $catsenabled = feature_enabled($channel['channel_id'], 'categories');
         $show_bd = perm_is_allowed($channel['channel_id'], get_observer_hash(), 'view_contacts');
         if (!$show_bd) {
             $sql_extra .= " and event.etype != 'birthday' ";
         }
         $category = '';
         $thisyear = datetime_convert('UTC', date_default_timezone_get(), 'now', 'Y');
         $thismonth = datetime_convert('UTC', date_default_timezone_get(), 'now', 'm');
         if (!$y) {
             $y = intval($thisyear);
         }
         if (!$m) {
             $m = intval($thismonth);
         }
         // Put some limits on dates. The PHP date functions don't seem to do so well before 1900.
         // An upper limit was chosen to keep search engines from exploring links millions of years in the future.
         if ($y < 1901) {
             $y = 1900;
         }
         if ($y > 2099) {
             $y = 2100;
         }
         $nextyear = $y;
         $nextmonth = $m + 1;
         if ($nextmonth > 12) {
             $nextmonth = 1;
             $nextyear++;
         }
         $prevyear = $y;
         if ($m > 1) {
             $prevmonth = $m - 1;
         } else {
             $prevmonth = 12;
             $prevyear--;
         }
         $dim = get_dim($y, $m);
         $start = sprintf('%d-%d-%d %d:%d:%d', $y, $m, 1, 0, 0, 0);
         $finish = sprintf('%d-%d-%d %d:%d:%d', $y, $m, $dim, 23, 59, 59);
         if (argv(2) === 'json') {
             if (x($_GET, 'start')) {
                 $start = $_GET['start'];
             }
             if (x($_GET, 'end')) {
                 $finish = $_GET['end'];
             }
         }
         $start = datetime_convert('UTC', 'UTC', $start);
         $finish = datetime_convert('UTC', 'UTC', $finish);
         $adjust_start = datetime_convert('UTC', date_default_timezone_get(), $start);
         $adjust_finish = datetime_convert('UTC', date_default_timezone_get(), $finish);
         if (x($_GET, 'id')) {
             $r = q("SELECT event.*, item.plink, item.item_flags, item.author_xchan, item.owner_xchan\n\t                                from event left join item on resource_id = event_hash where resource_type = 'event' and event.uid = %d and event.id = %d {$sql_extra} limit 1", intval($channel['channel_id']), intval($_GET['id']));
         } else {
             // fixed an issue with "nofinish" events not showing up in the calendar.
             // There's still an issue if the finish date crosses the end of month.
             // Noting this for now - it will need to be fixed here and in Friendica.
             // Ultimately the finish date shouldn't be involved in the query.
             $r = q("SELECT event.*, item.plink, item.item_flags, item.author_xchan, item.owner_xchan\n\t                              from event left join item on event_hash = resource_id \n\t\t\t\t\twhere resource_type = 'event' and event.uid = %d {$ignored} \n\t\t\t\t\tAND (( adjust = 0 AND ( dtend >= '%s' or nofinish = 1 ) AND dtstart <= '%s' ) \n\t\t\t\t\tOR  (  adjust = 1 AND ( dtend >= '%s' or nofinish = 1 ) AND dtstart <= '%s' )) {$sql_extra} ", intval($channel['channel_id']), dbesc($start), dbesc($finish), dbesc($adjust_start), dbesc($adjust_finish));
         }
         $links = array();
         if ($r) {
             xchan_query($r);
             $r = fetch_post_tags($r, true);
             $r = sort_by_date($r);
         }
         if ($r) {
             foreach ($r as $rr) {
                 $j = $rr['adjust'] ? datetime_convert('UTC', date_default_timezone_get(), $rr['dtstart'], 'j') : datetime_convert('UTC', 'UTC', $rr['dtstart'], 'j');
                 if (!x($links, $j)) {
                     $links[$j] = z_root() . '/' . \App::$cmd . '#link-' . $j;
                 }
             }
         }
         $events = array();
         $last_date = '';
         $fmt = t('l, F j');
         if ($r) {
             foreach ($r as $rr) {
                 $j = $rr['adjust'] ? datetime_convert('UTC', date_default_timezone_get(), $rr['dtstart'], 'j') : datetime_convert('UTC', 'UTC', $rr['dtstart'], 'j');
                 $d = $rr['adjust'] ? datetime_convert('UTC', date_default_timezone_get(), $rr['dtstart'], $fmt) : datetime_convert('UTC', 'UTC', $rr['dtstart'], $fmt);
                 $d = day_translate($d);
                 $start = $rr['adjust'] ? datetime_convert('UTC', date_default_timezone_get(), $rr['dtstart'], 'c') : datetime_convert('UTC', 'UTC', $rr['dtstart'], 'c');
                 if ($rr['nofinish']) {
                     $end = null;
                 } else {
                     $end = $rr['adjust'] ? datetime_convert('UTC', date_default_timezone_get(), $rr['dtend'], 'c') : datetime_convert('UTC', 'UTC', $rr['dtend'], 'c');
                 }
                 $is_first = $d !== $last_date;
                 $last_date = $d;
                 $edit = false;
                 $drop = false;
                 $title = strip_tags(html_entity_decode(bbcode($rr['summary']), ENT_QUOTES, 'UTF-8'));
                 if (!$title) {
                     list($title, $_trash) = explode("<br", bbcode($rr['desc']), 2);
                     $title = strip_tags(html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
                 }
                 $html = format_event_html($rr);
                 $rr['desc'] = bbcode($rr['desc']);
                 $rr['location'] = bbcode($rr['location']);
                 $events[] = array('id' => $rr['id'], 'hash' => $rr['event_hash'], 'start' => $start, 'end' => $end, 'drop' => $drop, 'allDay' => false, 'title' => $title, 'j' => $j, 'd' => $d, 'edit' => $edit, 'is_first' => $is_first, 'item' => $rr, 'html' => $html, 'plink' => array($rr['plink'], t('Link to Source'), '', ''));
             }
         }
         if (argv(2) === 'json') {
             echo json_encode($events);
             killme();
         }
         // links: array('href', 'text', 'extra css classes', 'title')
         if (x($_GET, 'id')) {
             $tpl = get_markup_template("event_cal.tpl");
         } else {
             $tpl = get_markup_template("events_cal-js.tpl");
         }
         $nick = $channel['channel_address'];
         $o = replace_macros($tpl, array('$baseurl' => z_root(), '$new_event' => array(z_root() . '/cal', $event_id ? t('Edit Event') : t('Create Event'), '', ''), '$previus' => array(z_root() . "/cal/{$nick}/{$prevyear}/{$prevmonth}", t('Previous'), '', ''), '$next' => array(z_root() . "/cal/{$nick}/{$nextyear}/{$nextmonth}", t('Next'), '', ''), '$export' => array(z_root() . "/cal/{$nick}/{$y}/{$m}/export", t('Export'), '', ''), '$calendar' => cal($y, $m, $links, ' eventcal'), '$events' => $events, '$upload' => t('Import'), '$submit' => t('Submit'), '$prev' => t('Previous'), '$next' => t('Next'), '$today' => t('Today'), '$form' => $form, '$expandform' => x($_GET, 'expandform') ? true : false, '$tabs' => $tabs));
         if (x($_GET, 'id')) {
             echo $o;
             killme();
         }
         return $o;
     }
 }
Example #24
0
function thing_content(&$a)
{
    // @FIXME one problem with things is we can't share them unless we provide the channel in the url
    // so we can definitively lookup the owner.
    if (argc() == 2) {
        $r = q("select obj_channel from obj where obj_type = %d and obj_obj = '%s' limit 1", intval(TERM_OBJ_THING), dbesc(argv(1)));
        if ($r) {
            $sql_extra = permissions_sql($r[0]['obj_channel']);
        }
        $r = q("select * from obj where obj_type = %d and obj_obj = '%s' {$sql_extra} limit 1", intval(TERM_OBJ_THING), dbesc(argv(1)));
        if ($r) {
            return replace_macros(get_markup_template('show_thing.tpl'), array('$header' => t('Show Thing'), '$edit' => t('Edit'), '$delete' => t('Delete'), '$canedit' => local_channel() && local_channel() == $r[0]['obj_channel'] ? true : false, '$thing' => $r[0]));
        } else {
            notice(t('item not found.') . EOL);
            return;
        }
    }
    $channel = App::get_channel();
    if (!(local_channel() && $channel)) {
        notice(t('Permission denied.') . EOL);
        return;
    }
    $acl = new Zotlabs\Access\AccessList($channel);
    $channel_acl = $acl->get();
    $lockstate = $acl->is_private() ? 'lock' : 'unlock';
    $thing_hash = '';
    if (argc() == 3 && argv(1) === 'edit') {
        $thing_hash = argv(2);
        $r = q("select * from obj where obj_type = %d and obj_obj = '%s' limit 1", intval(TERM_OBJ_THING), dbesc($thing_hash));
        if (!$r || $r[0]['obj_channel'] != local_channel()) {
            notice(t('Permission denied.') . EOL);
            return '';
        }
        $o .= replace_macros(get_markup_template('thing_edit.tpl'), array('$thing_hdr' => t('Edit Thing'), '$multiprof' => feature_enabled(local_channel(), 'multi_profiles'), '$profile_lbl' => t('Select a profile'), '$profile_select' => contact_profile_assign($r[0]['obj_page']), '$verb_lbl' => $channel['channel_name'], '$verb_select' => obj_verb_selector($r[0]['obj_verb']), '$activity' => array('activity', t('Post an activity'), true, t('Only sends to viewers of the applicable profile')), '$thing_hash' => $thing_hash, '$thing_lbl' => t('Name of thing e.g. something'), '$thething' => $r[0]['obj_term'], '$url_lbl' => t('URL of thing (optional)'), '$theurl' => $r[0]['obj_url'], '$img_lbl' => t('URL for photo of thing (optional)'), '$imgurl' => $r[0]['obj_imgurl'], '$permissions' => t('Permissions'), '$aclselect' => populate_acl($channel_acl, false), '$lockstate' => $lockstate, '$submit' => t('Submit')));
        return $o;
    }
    if (argc() == 3 && argv(1) === 'drop') {
        $thing_hash = argv(2);
        $r = q("select * from obj where obj_type = %d and obj_obj = '%s' limit 1", intval(TERM_OBJ_THING), dbesc($thing_hash));
        if (!$r || $r[0]['obj_channel'] != local_channel()) {
            notice(t('Permission denied.') . EOL);
            return '';
        }
        $x = q("delete from obj where obj_obj = '%s' and obj_type = %d and obj_channel = %d", dbesc($thing_hash), intval(TERM_OBJ_THING), intval(local_channel()));
        $r[0]['obj_deleted'] = 1;
        build_sync_packet(0, array('obj' => $r));
        return $o;
    }
    $o .= replace_macros(get_markup_template('thing_input.tpl'), array('$thing_hdr' => t('Add Thing to your Profile'), '$multiprof' => feature_enabled(local_channel(), 'multi_profiles'), '$profile_lbl' => t('Select a profile'), '$profile_select' => contact_profile_assign(''), '$verb_lbl' => $channel['channel_name'], '$activity' => array('activity', t('Post an activity'), array_key_exists('activity', $_REQUEST) ? $_REQUEST['activity'] : true, t('Only sends to viewers of the applicable profile')), '$verb_select' => obj_verb_selector(), '$thing_lbl' => t('Name of thing e.g. something'), '$url_lbl' => t('URL of thing (optional)'), '$img_lbl' => t('URL for photo of thing (optional)'), '$permissions' => t('Permissions'), '$aclselect' => populate_acl($channel_acl, false), '$lockstate' => $lockstate, '$submit' => t('Submit')));
    return $o;
}
Example #25
0
function photo_init(&$a)
{
    // To-Do:
    // - checking with realpath
    // - checking permissions
    /*
    	$cache = get_config('system','itemcache');
            if (($cache != '') and is_dir($cache)) {
    		$cachefile = $cache."/".$a->argc."-".$a->argv[1]."-".$a->argv[2]."-".$a->argv[3];
    		if (file_exists($cachefile)) {
    			$data = file_get_contents($cachefile);
    
    			if(function_exists('header_remove')) {
    				header_remove('Pragma');
    				header_remove('pragma');
    			}
    
    			header("Content-type: image/jpeg");
     			header("Expires: " . gmdate("D, d M Y H:i:s", time() + (3600*24)) . " GMT");
    			header("Cache-Control: max-age=" . (3600*24));
    			echo $data;
    			killme();
    			// NOTREACHED
    		}
    	}*/
    $prvcachecontrol = false;
    switch ($a->argc) {
        case 4:
            $person = $a->argv[3];
            $customres = intval($a->argv[2]);
            $type = $a->argv[1];
            break;
        case 3:
            $person = $a->argv[2];
            $type = $a->argv[1];
            break;
        case 2:
            $photo = $a->argv[1];
            break;
        case 1:
        default:
            killme();
            // NOTREACHED
    }
    $default = 'images/person-175.jpg';
    if (isset($type)) {
        /**
         * Profile photos
         */
        switch ($type) {
            case 'profile':
            case 'custom':
                $resolution = 4;
                break;
            case 'micro':
                $resolution = 6;
                $default = 'images/person-48.jpg';
                break;
            case 'avatar':
            default:
                $resolution = 5;
                $default = 'images/person-80.jpg';
                break;
        }
        $uid = str_replace('.jpg', '', $person);
        $r = q("SELECT * FROM `photo` WHERE `scale` = %d AND `uid` = %d AND `profile` = 1 LIMIT 1", intval($resolution), intval($uid));
        if (count($r)) {
            $data = $r[0]['data'];
        }
        if (!isset($data)) {
            $data = file_get_contents($default);
        }
    } else {
        /**
         * Other photos
         */
        $resolution = 0;
        $photo = str_replace('.jpg', '', $photo);
        if (substr($photo, -2, 1) == '-') {
            $resolution = intval(substr($photo, -1, 1));
            $photo = substr($photo, 0, -2);
        }
        $r = q("SELECT `uid` FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d LIMIT 1", dbesc($photo), intval($resolution));
        if (count($r)) {
            $sql_extra = permissions_sql($r[0]['uid']);
            // Now we'll see if we can access the photo
            $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d {$sql_extra} LIMIT 1", dbesc($photo), intval($resolution));
            if (count($r)) {
                $data = $r[0]['data'];
            } else {
                // Does the picture exist? It may be a remote person with no credentials,
                // but who should otherwise be able to view it. Show a default image to let
                // them know permissions was denied. It may be possible to view the image
                // through an authenticated profile visit.
                // There won't be many completely unauthorised people seeing this because
                // they won't have the photo link, so there's a reasonable chance that the person
                // might be able to obtain permission to view it.
                $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d LIMIT 1", dbesc($photo), intval($resolution));
                if (count($r)) {
                    $data = file_get_contents('images/nosign.jpg');
                    $prvcachecontrol = true;
                }
            }
        }
    }
    if (!isset($data)) {
        if (isset($resolution)) {
            switch ($resolution) {
                case 4:
                    $data = file_get_contents('images/person-175.jpg');
                    break;
                case 5:
                    $data = file_get_contents('images/person-80.jpg');
                    break;
                case 6:
                    $data = file_get_contents('images/person-48.jpg');
                    break;
                default:
                    killme();
                    // NOTREACHED
                    break;
            }
        }
    }
    if (isset($customres) && $customres > 0 && $customres < 500) {
        require_once 'include/Photo.php';
        $ph = new Photo($data);
        if ($ph->is_valid()) {
            $ph->scaleImageSquare($customres);
            $data = $ph->imageString();
        }
    }
    // Writing in cachefile
    if (isset($cachefile) && $cachefile != '') {
        file_put_contents($cachefile, $data);
    }
    if (function_exists('header_remove')) {
        header_remove('Pragma');
        header_remove('pragma');
    }
    header("Content-type: image/jpeg");
    if ($prvcachecontrol) {
        // it is a private photo that they have no permission to view.
        // tell the browser not to cache it, in case they authenticate
        // and subsequently have permission to see it
        header("Cache-Control: no-store, no-cache, must-revalidate");
    } else {
        header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600 * 24) . " GMT");
        header("Cache-Control: max-age=" . 3600 * 24);
    }
    echo $data;
    killme();
    // NOTREACHED
}
Example #26
0
// search term provided?
if ($search_term) {
    $wheres[] = "{$field['parent_caption']} like '%{$search_term}%'";
}
// any filterers specified?
if (is_array($field['filterers'])) {
    foreach ($field['filterers'] as $filterer => $filterer_parent) {
        $get = isset($_REQUEST["filterer_{$filterer}"]) ? $_REQUEST["filterer_{$filterer}"] : false;
        if ($get) {
            $wheres[] = "`{$field['parent_table']}`.`{$filterer_parent}`='" . makeSafe($get) . "'";
        }
    }
}
// inherit permissions?
if ($field['inherit_permissions']) {
    $inherit = permissions_sql($field['parent_table']);
    if ($inherit === false && !$search_id) {
        die($Translation['tableAccessDenied']);
    }
    if ($inherit['where']) {
        $wheres[] = $inherit['where'];
    }
    if ($inherit['from']) {
        $field['parent_from'] .= ", {$inherit['from']}";
    }
}
// single value?
if ($field['list_type'] != 2 && $search_id) {
    $wheres[] = "`{$field['parent_table']}`.`{$field['parent_pk_field']}`='{$search_id}'";
}
if (count($wheres)) {
Example #27
0
 function get()
 {
     if (local_channel()) {
         $channel = \App::get_channel();
     }
     $ob = \App::get_observer();
     $observer = get_observer_hash();
     if (!$observer) {
         notice(t('Permission denied.') . EOL);
         return;
     }
     if (!perm_is_allowed(\App::$profile['profile_uid'], $observer, 'chat')) {
         notice(t('Permission denied.') . EOL);
         return;
     }
     if (argc() > 3 && intval(argv(2)) && argv(3) === 'leave') {
         Zlib\Chatroom::leave($observer, argv(2), $_SERVER['REMOTE_ADDR']);
         goaway(z_root() . '/channel/' . argv(1));
     }
     if (argc() > 3 && intval(argv(2)) && argv(3) === 'status') {
         $ret = array('success' => false);
         $room_id = intval(argv(2));
         if (!$room_id || !$observer) {
             return;
         }
         $r = q("select * from chatroom where cr_id = %d limit 1", intval($room_id));
         if (!$r) {
             json_return_and_die($ret);
         }
         require_once 'include/security.php';
         $sql_extra = permissions_sql($r[0]['cr_uid']);
         $x = q("select * from chatroom where cr_id = %d and cr_uid = %d {$sql_extra} limit 1", intval($room_id), intval($r[0]['cr_uid']));
         if (!$x) {
             json_return_and_die($ret);
         }
         $y = q("select count(*) as total from chatpresence where cp_room = %d", intval($room_id));
         if ($y) {
             $ret['success'] = true;
             $ret['chatroom'] = $r[0]['cr_name'];
             $ret['inroom'] = $y[0]['total'];
         }
         // figure out how to present a timestamp of the last activity, since we don't know the observer's timezone.
         $z = q("select created from chat where chat_room = %d order by created desc limit 1", intval($room_id));
         if ($z) {
             $ret['last'] = $z[0]['created'];
         }
         json_return_and_die($ret);
     }
     if (argc() > 2 && intval(argv(2))) {
         $room_id = intval(argv(2));
         $bookmark_link = get_bookmark_link($ob);
         $x = Zlib\Chatroom::enter($observer, $room_id, 'online', $_SERVER['REMOTE_ADDR']);
         if (!$x) {
             return;
         }
         $x = q("select * from chatroom where cr_id = %d and cr_uid = %d {$sql_extra} limit 1", intval($room_id), intval(\App::$profile['profile_uid']));
         if ($x) {
             $acl = new \Zotlabs\Access\AccessList(false);
             $acl->set($x[0]);
             $private = $acl->is_private();
             $room_name = $x[0]['cr_name'];
             if ($bookmark_link) {
                 $bookmark_link .= '&url=' . z_root() . '/chat/' . argv(1) . '/' . argv(2) . '&title=' . urlencode($x[0]['cr_name']) . ($private ? '&private=1' : '') . '&ischat=1';
             }
         } else {
             notice(t('Room not found') . EOL);
             return;
         }
         $cipher = get_pconfig(local_channel(), 'system', 'default_cipher');
         if (!$cipher) {
             $cipher = 'aes256';
         }
         $o = replace_macros(get_markup_template('chat.tpl'), array('$is_owner' => local_channel() && local_channel() == $x[0]['cr_uid'] ? true : false, '$room_name' => $room_name, '$room_id' => $room_id, '$baseurl' => z_root(), '$nickname' => argv(1), '$submit' => t('Submit'), '$leave' => t('Leave Room'), '$drop' => t('Delete Room'), '$away' => t('I am away right now'), '$online' => t('I am online'), '$bookmark_link' => $bookmark_link, '$bookmark' => t('Bookmark this room'), '$feature_encrypt' => feature_enabled(local_channel(), 'content_encrypt') ? true : false, '$cipher' => $cipher, '$linkurl' => t('Please enter a link URL:'), '$encrypt' => t('Encrypt text'), '$insert' => t('Insert web link')));
         return $o;
     }
     require_once 'include/conversation.php';
     $o = profile_tabs($a, local_channel() && local_channel() == \App::$profile['profile_uid'] ? true : false, \App::$profile['channel_address']);
     if (!feature_enabled(\App::$profile['profile_uid'], 'ajaxchat')) {
         notice(t('Feature disabled.') . EOL);
         return $o;
     }
     $acl = new \Zotlabs\Access\AccessList($channel);
     $channel_acl = $acl->get();
     $lockstate = $channel_acl['allow_cid'] || $channel_acl['allow_gid'] || $channel_acl['deny_cid'] || $channel_acl['deny_gid'] ? 'lock' : 'unlock';
     require_once 'include/acl_selectors.php';
     $chatroom_new = '';
     if (local_channel()) {
         $chatroom_new = replace_macros(get_markup_template('chatroom_new.tpl'), array('$header' => t('New Chatroom'), '$name' => array('room_name', t('Chatroom name'), '', ''), '$chat_expire' => array('chat_expire', t('Expiration of chats (minutes)'), 120, ''), '$permissions' => t('Permissions'), '$acl' => populate_acl($channel_acl, false), '$lockstate' => $lockstate, '$submit' => t('Submit')));
     }
     $rooms = Zlib\Chatroom::roomlist(\App::$profile['profile_uid']);
     $o .= replace_macros(get_markup_template('chatrooms.tpl'), array('$header' => sprintf(t('%1$s\'s Chatrooms'), \App::$profile['fullname']), '$name' => t('Name'), '$baseurl' => z_root(), '$nickname' => \App::$profile['channel_address'], '$rooms' => $rooms, '$norooms' => t('No chatrooms available'), '$newroom' => t('Create New'), '$is_owner' => local_channel() && local_channel() == \App::$profile['profile_uid'] ? 1 : 0, '$chatroom_new' => $chatroom_new, '$expire' => t('Expiration'), '$expire_unit' => t('min')));
     return $o;
 }
Example #28
0
function photo_init(&$a)
{
    global $_SERVER;
    $prvcachecontrol = false;
    $file = "";
    switch ($a->argc) {
        case 4:
            $person = $a->argv[3];
            $customres = intval($a->argv[2]);
            $type = $a->argv[1];
            break;
        case 3:
            $person = $a->argv[2];
            $type = $a->argv[1];
            break;
        case 2:
            $photo = $a->argv[1];
            $file = $photo;
            break;
        case 1:
        default:
            killme();
            // NOTREACHED
    }
    //	strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($localFileName)) {
    if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
        header('HTTP/1.1 304 Not Modified');
        header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
        header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
        header("Expires: " . gmdate("D, d M Y H:i:s", time() + 31536000) . " GMT");
        header("Cache-Control: max-age=31536000");
        if (function_exists('header_remove')) {
            header_remove('Last-Modified');
            header_remove('Expires');
            header_remove('Cache-Control');
        }
        exit;
    }
    $default = 'images/person-175.jpg';
    if (isset($type)) {
        /**
         * Profile photos
         */
        switch ($type) {
            case 'profile':
            case 'custom':
                $resolution = 4;
                break;
            case 'micro':
                $resolution = 6;
                $default = 'images/person-48.jpg';
                break;
            case 'avatar':
            default:
                $resolution = 5;
                $default = 'images/person-80.jpg';
                break;
        }
        $uid = str_replace(array('.jpg', '.png'), array('', ''), $person);
        $r = q("SELECT * FROM `photo` WHERE `scale` = %d AND `uid` = %d AND `profile` = 1 LIMIT 1", intval($resolution), intval($uid));
        if (count($r)) {
            $data = $r[0]['data'];
            $mimetype = $r[0]['type'];
        }
        if (!isset($data)) {
            $data = file_get_contents($default);
            $mimetype = 'image/jpeg';
        }
    } else {
        /**
         * Other photos
         */
        $resolution = 0;
        foreach (Photo::supportedTypes() as $m => $e) {
            $photo = str_replace(".{$e}", '', $photo);
        }
        if (substr($photo, -2, 1) == '-') {
            $resolution = intval(substr($photo, -1, 1));
            $photo = substr($photo, 0, -2);
        }
        // check if the photo exists and get the owner of the photo
        $r = q("SELECT `uid` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1", dbesc($photo), intval($resolution));
        if (count($r)) {
            $sql_extra = permissions_sql($r[0]['uid']);
            // Now we'll see if we can access the photo
            $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` <= %d {$sql_extra} ORDER BY scale DESC LIMIT 1", dbesc($photo), intval($resolution));
            $public = $r[0]['allow_cid'] == '' and $r[0]['allow_gid'] == '' and $r[0]['deny_cid'] == '' and $r[0]['deny_gid'] == '';
            if (count($r)) {
                $resolution = $r[0]['scale'];
                $data = $r[0]['data'];
                $mimetype = $r[0]['type'];
            } else {
                // The picure exists. We already checked with the first query.
                // obviously, this is not an authorized viev!
                $data = file_get_contents('images/nosign.jpg');
                $mimetype = 'image/jpeg';
                $prvcachecontrol = true;
                $public = false;
            }
        }
    }
    if (!isset($data)) {
        if (isset($resolution)) {
            switch ($resolution) {
                case 4:
                    $data = file_get_contents('images/person-175.jpg');
                    $mimetype = 'image/jpeg';
                    break;
                case 5:
                    $data = file_get_contents('images/person-80.jpg');
                    $mimetype = 'image/jpeg';
                    break;
                case 6:
                    $data = file_get_contents('images/person-48.jpg');
                    $mimetype = 'image/jpeg';
                    break;
                default:
                    killme();
                    // NOTREACHED
                    break;
            }
        }
    }
    // Resize only if its not a GIF
    if ($mime != "image/gif") {
        $ph = new Photo($data, $mimetype);
        if ($ph->is_valid()) {
            if (isset($customres) && $customres > 0 && $customres < 500) {
                $ph->scaleImageSquare($customres);
            }
            $data = $ph->imageString();
            $mimetype = $ph->getType();
        }
    }
    if (function_exists('header_remove')) {
        header_remove('Pragma');
        header_remove('pragma');
    }
    header("Content-type: " . $mimetype);
    if ($prvcachecontrol) {
        // it is a private photo that they have no permission to view.
        // tell the browser not to cache it, in case they authenticate
        // and subsequently have permission to see it
        header("Cache-Control: no-store, no-cache, must-revalidate");
    } else {
        header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
        header('Etag: "' . md5($data) . '"');
        header("Expires: " . gmdate("D, d M Y H:i:s", time() + 31536000) . " GMT");
        header("Cache-Control: max-age=31536000");
    }
    echo $data;
    // If the photo is public and there is an existing photo directory store the photo there
    if ($public and $file != "") {
        // If the photo path isn't there, try to create it
        $basepath = $a->get_basepath();
        if (!is_dir($basepath . "/photo")) {
            if (is_writable($basepath)) {
                mkdir($basepath . "/photo");
            }
        }
        if (is_dir($basepath . "/photo")) {
            file_put_contents($basepath . "/photo/" . $file, $data);
        }
    }
    killme();
    // NOTREACHED
}
Example #29
0
function videos_content(&$a)
{
    // URLs (most aren't currently implemented):
    // videos/name
    // videos/name/upload
    // videos/name/upload/xxxxx (xxxxx is album name)
    // videos/name/album/xxxxx
    // videos/name/album/xxxxx/edit
    // videos/name/video/xxxxx
    // videos/name/video/xxxxx/edit
    if (get_config('system', 'block_public') && !local_user() && !remote_user()) {
        notice(t('Public access denied.') . EOL);
        return;
    }
    require_once 'include/bbcode.php';
    require_once 'include/security.php';
    require_once 'include/conversation.php';
    if (!x($a->data, 'user')) {
        notice(t('No videos selected') . EOL);
        return;
    }
    //$phototypes = Photo::supportedTypes();
    $_SESSION['video_return'] = $a->cmd;
    //
    // Parse arguments
    //
    if ($a->argc > 3) {
        $datatype = $a->argv[2];
        $datum = $a->argv[3];
    } elseif ($a->argc > 2 && $a->argv[2] === 'upload') {
        $datatype = 'upload';
    } else {
        $datatype = 'summary';
    }
    if ($a->argc > 4) {
        $cmd = $a->argv[4];
    } else {
        $cmd = 'view';
    }
    //
    // Setup permissions structures
    //
    $can_post = false;
    $visitor = 0;
    $contact = null;
    $remote_contact = false;
    $contact_id = 0;
    $owner_uid = $a->data['user']['uid'];
    $community_page = $a->data['user']['page-flags'] == PAGE_COMMUNITY ? true : false;
    if (local_user() && local_user() == $owner_uid) {
        $can_post = true;
    } else {
        if ($community_page && remote_user()) {
            if (is_array($_SESSION['remote'])) {
                foreach ($_SESSION['remote'] as $v) {
                    if ($v['uid'] == $owner_uid) {
                        $contact_id = $v['cid'];
                        break;
                    }
                }
            }
            if ($contact_id) {
                $r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1", intval($contact_id), intval($owner_uid));
                if (count($r)) {
                    $can_post = true;
                    $contact = $r[0];
                    $remote_contact = true;
                    $visitor = $cid;
                }
            }
        }
    }
    // perhaps they're visiting - but not a community page, so they wouldn't have write access
    if (remote_user() && !$visitor) {
        $contact_id = 0;
        if (is_array($_SESSION['remote'])) {
            foreach ($_SESSION['remote'] as $v) {
                if ($v['uid'] == $owner_uid) {
                    $contact_id = $v['cid'];
                    break;
                }
            }
        }
        if ($contact_id) {
            $groups = init_groups_visitor($contact_id);
            $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1", intval($contact_id), intval($owner_uid));
            if (count($r)) {
                $contact = $r[0];
                $remote_contact = true;
            }
        }
    }
    if (!$remote_contact) {
        if (local_user()) {
            $contact_id = $_SESSION['cid'];
            $contact = $a->contact;
        }
    }
    if ($a->data['user']['hidewall'] && local_user() != $owner_uid && !$remote_contact) {
        notice(t('Access to this item is restricted.') . EOL);
        return;
    }
    $sql_extra = permissions_sql($owner_uid, $remote_contact, $groups);
    $o = "";
    // tabs
    $_is_owner = local_user() && local_user() == $owner_uid;
    $o .= profile_tabs($a, $_is_owner, $a->data['user']['nickname']);
    //
    // dispatch request
    //
    if ($datatype === 'upload') {
        return;
        // no uploading for now
        // DELETED -- look at mod/photos.php if you want to implement
    }
    if ($datatype === 'album') {
        return;
        // no albums for now
        // DELETED -- look at mod/photos.php if you want to implement
    }
    if ($datatype === 'video') {
        return;
        // no single video view for now
        // DELETED -- look at mod/photos.php if you want to implement
    }
    // Default - show recent videos (no upload link for now)
    //$o = '';
    $r = q("SELECT hash FROM `attach` WHERE `uid` = %d AND filetype LIKE '%%video%%'\n\t\t{$sql_extra} GROUP BY hash", intval($a->data['user']['uid']));
    if (count($r)) {
        $a->set_pager_total(count($r));
        $a->set_pager_itemspage(20);
    }
    $r = q("SELECT hash, `id`, `filename`, filetype FROM `attach`\n\t\tWHERE `uid` = %d AND filetype LIKE '%%video%%'\n\t\t{$sql_extra} GROUP BY hash ORDER BY `created` DESC LIMIT %d , %d", intval($a->data['user']['uid']), intval($a->pager['start']), intval($a->pager['itemspage']));
    $videos = array();
    if (count($r)) {
        foreach ($r as $rr) {
            if ($a->theme['template_engine'] === 'internal') {
                $alt_e = template_escape($rr['filename']);
                $name_e = template_escape($rr['album']);
            } else {
                $alt_e = $rr['filename'];
                $name_e = $rr['album'];
            }
            $videos[] = array('id' => $rr['id'], 'link' => $a->get_baseurl() . '/videos/' . $a->data['user']['nickname'] . '/video/' . $rr['resource-id'], 'title' => t('View Video'), 'src' => $a->get_baseurl() . '/attach/' . $rr['id'] . '?attachment=0', 'alt' => $alt_e, 'mime' => $rr['filetype'], 'album' => array('link' => $a->get_baseurl() . '/videos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($rr['album']), 'name' => $name_e, 'alt' => t('View Album')));
        }
    }
    $tpl = get_markup_template('videos_recent.tpl');
    $o .= replace_macros($tpl, array('$title' => t('Recent Videos'), '$can_post' => $can_post, '$upload' => array(t('Upload New Videos'), $a->get_baseurl() . '/videos/' . $a->data['user']['nickname'] . '/upload'), '$videos' => $videos, '$delete_url' => $can_post ? $a->get_baseurl() . '/videos/' . $a->data['user']['nickname'] : False));
    $o .= paginate($a);
    return $o;
}