Example #1
0
function vcard_from_xchan($xchan, $observer = null, $mode = '')
{
    $a = get_app();
    if (!$xchan) {
        if (App::$poi) {
            $xchan = App::$poi;
        } elseif (is_array(App::$profile) && App::$profile['channel_hash']) {
            $r = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc(App::$profile['channel_hash']));
            if ($r) {
                $xchan = $r[0];
            }
        }
    }
    if (!$xchan) {
        return;
    }
    // FIXME - show connect button to observer if appropriate
    $connect = false;
    if (local_channel()) {
        $r = q("select * from abook where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($xchan['xchan_hash']), intval(local_channel()));
        if (!$r) {
            $connect = t('Connect');
        }
    }
    if (array_key_exists('channel_id', $xchan)) {
        App::$profile_uid = $xchan['channel_id'];
    }
    $url = $observer ? z_root() . '/magic?f=&dest=' . $xchan['xchan_url'] . '&addr=' . $xchan['xchan_addr'] : $xchan['xchan_url'];
    return replace_macros(get_markup_template('xchan_vcard.tpl'), array('$name' => $xchan['xchan_name'], '$photo' => is_array(App::$profile) && array_key_exists('photo', App::$profile) ? App::$profile['photo'] : $xchan['xchan_photo_l'], '$follow' => $xchan['xchan_addr'], '$link' => zid($xchan['xchan_url']), '$connect' => $connect, '$newwin' => $mode === 'chanview' ? t('New window') : '', '$newtit' => t('Open the selected location in a different window or browser tab'), '$url' => $url));
}
Example #2
0
File: oembed.php Project: Mauru/red
function oembed_fetch_url($embedurl)
{
    $a = get_app();
    $txt = Cache::get($a->videowidth . $embedurl);
    if (strstr($txt, 'youtu')) {
        $txt = str_replace('http:', 'https:', $txt);
    }
    // These media files should now be caught in bbcode.php
    // left here as a fallback in case this is called from another source
    $noexts = array("mp3", "mp4", "ogg", "ogv", "oga", "ogm", "webm");
    $ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);
    if (is_null($txt)) {
        $txt = "";
        if (in_array($ext, $noexts)) {
            require_once 'include/hubloc.php';
            $zrl = is_matrix_url($embedurl);
            if ($zrl) {
                $embedurl = zid($embedurl);
            }
        } else {
            // try oembed autodiscovery
            $redirects = 0;
            $result = z_fetch_url($embedurl, false, $redirects, array('timeout' => 15, 'accept_content' => "text/*", 'novalidate' => true));
            if ($result['success']) {
                $html_text = $result['body'];
            }
            if ($html_text) {
                $dom = @DOMDocument::loadHTML($html_text);
                if ($dom) {
                    $xpath = new DOMXPath($dom);
                    $attr = "oembed";
                    $xattr = oe_build_xpath("class", "oembed");
                    $entries = $xpath->query("//link[@type='application/json+oembed']");
                    foreach ($entries as $e) {
                        $href = $e->getAttributeNode("href")->nodeValue;
                        $x = z_fetch_url($href . '&maxwidth=' . $a->videowidth);
                        $txt = $x['body'];
                        break;
                    }
                }
            }
        }
        if ($txt == false || $txt == "") {
            $x = array('url' => $embedurl, 'videowidth' => $a->videowidth);
            call_hooks('oembed_probe', $x);
            if (array_key_exists('embed', $x)) {
                $txt = $x['embed'];
            }
        }
        $txt = trim($txt);
        if ($txt[0] != "{") {
            $txt = '{"type":"error"}';
        }
        //save in cache
        Cache::set($a->videowidth . $embedurl, $txt);
    }
    $j = json_decode($txt);
    $j->embedurl = $embedurl;
    return $j;
}
Example #3
0
function menu_render($menu, $class = '', $edit = false, $var = array())
{
    if (!$menu) {
        return '';
    }
    $channel_id = is_array(App::$profile) ? App::$profile['profile_uid'] : 0;
    if (!$channel_id && local_channel()) {
        $channel_id = local_channel();
    }
    $menu_list = menu_list($channel_id);
    $menu_names = array();
    foreach ($menu_list as $menus) {
        if ($menus['menu_name'] != $menu['menu']['menu_name']) {
            $menu_names[] = $menus['menu_name'];
        }
    }
    for ($x = 0; $x < count($menu['items']); $x++) {
        if (in_array($menu['items'][$x]['mitem_link'], $menu_names)) {
            $m = menu_fetch($menu['items'][$x]['mitem_link'], $channel_id, get_observer_hash());
            $submenu = menu_render($m, 'dropdown-menu', $edit = false, array('wrap' => 'none'));
            $menu['items'][$x]['submenu'] = $submenu;
        }
        if ($menu['items'][$x]['mitem_flags'] & MENU_ITEM_ZID) {
            $menu['items'][$x]['mitem_link'] = zid($menu['items'][$x]['mitem_link']);
        }
        if ($menu['items'][$x]['mitem_flags'] & MENU_ITEM_NEWWIN) {
            $menu['items'][$x]['newwin'] = '1';
        }
        $menu['items'][$x]['mitem_desc'] = bbcode($menu['items'][$x]['mitem_desc']);
    }
    $wrap = $var['wrap'] === 'none' ? false : true;
    $ret = replace_macros(get_markup_template('usermenu.tpl'), array('$menu' => $menu['menu'], '$class' => $class, '$edit' => $edit ? t("Edit") : '', '$id' => $menu['menu']['menu_id'], '$items' => $menu['items'], '$wrap' => $wrap));
    return $ret;
}
Example #4
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);
 }
function custom_home_home(&$a, &$o)
{
    $x = get_config('system', 'custom_home');
    if ($x) {
        if ($x == "random") {
            $rand = db_getfunc('rand');
            $r = q("select channel_address from channel where channel_r_stream = 1 and channel_address != 'sys' order by {$rand} limit 1");
            $x = z_root() . '/channel/' . $r[0]['channel_address'];
        } else {
            $x = z_root() . '/' . $x;
        }
        goaway(zid($x));
    }
    //If nothing is set
    return $o;
}
Example #6
0
File: menu.php Project: Mauru/red
function menu_render($menu, $class = '', $edit = false)
{
    if (!$menu) {
        return '';
    }
    for ($x = 0; $x < count($menu['items']); $x++) {
        if ($menu['items'][$x]['mitem_flags'] & MENU_ITEM_ZID) {
            $menu['items'][$x]['mitem_link'] = zid($menu['items'][$x]['mitem_link']);
        }
        if ($menu['items'][$x]['mitem_flags'] & MENU_ITEM_NEWWIN) {
            $menu['items'][$x]['newwin'] = '1';
        }
        $menu['items'][$x]['mitem_desc'] = bbcode($menu['items'][$x]['mitem_desc']);
    }
    return replace_macros(get_markup_template('usermenu.tpl'), array('$menu' => $menu['menu'], '$class' => $class, '$edit' => $edit ? t("Edit") : '', '$items' => $menu['items']));
}
Example #7
0
function custom_home_home(&$a, &$o)
{
    $x = get_config('system', 'custom_home');
    if ($x) {
        if ($x == "random") {
            $rand = db_getfunc('rand');
            $r = q("select channel_address from channel left join pconfig on channel_id = pconfig.uid where pconfig.cat = 'perm_limits' and pconfig.k = 'view_stream' and pconfig.v = 1 and channel_address != 'sys' order by {$rand} limit 1");
            $x = z_root() . '/channel/' . $r[0]['channel_address'];
        } else {
            $x = z_root() . '/' . $x;
        }
        goaway(zid($x));
    }
    //If nothing is set
    return $o;
}
Example #8
0
/**
 * @brief Controller for /match.
 *
 * It takes keywords from your profile and queries the directory server for
 * matching keywords from other profiles.
 *
 * @FIXME this has never been properly ported from Friendica.
 *
 * @param App &$a
 * @return void|string
 */
function match_content(&$a)
{
    $o = '';
    if (!local_channel()) {
        return;
    }
    $_SESSION['return_url'] = z_root() . '/' . App::$cmd;
    $o .= '<h2>' . t('Profile Match') . '</h2>';
    $r = q("SELECT `keywords` FROM `profile` WHERE `is_default` = 1 AND `uid` = %d LIMIT 1", intval(local_channel()));
    if (!count($r)) {
        return;
    }
    if (!$r[0]['keywords']) {
        notice(t('No keywords to match. Please add keywords to your default profile.') . EOL);
        return;
    }
    $params = array();
    $tags = trim($r[0]['keywords']);
    if ($tags) {
        $params['s'] = $tags;
        if (App::$pager['page'] != 1) {
            $params['p'] = App::$pager['page'];
        }
        //		if(strlen(get_config('system','directory_submit_url')))
        //			$x = post_url('http://dir.friendica.com/msearch', $params);
        //		else
        //			$x = post_url(z_root() . '/msearch', $params);
        $j = json_decode($x);
        if ($j->total) {
            App::set_pager_total($j->total);
            App::set_pager_itemspage($j->items_page);
        }
        if (count($j->results)) {
            $tpl = get_markup_template('match.tpl');
            foreach ($j->results as $jj) {
                $connlnk = z_root() . '/follow/?url=' . $jj->url;
                $o .= replace_macros($tpl, array('$url' => zid($jj->url), '$name' => $jj->name, '$photo' => $jj->photo, '$inttxt' => ' ' . t('is interested in:'), '$conntxt' => t('Connect'), '$connlnk' => $connlnk, '$tags' => $jj->tags));
            }
        } else {
            info(t('No matches') . EOL);
        }
    }
    $o .= cleardiv();
    $o .= paginate($a);
    return $o;
}
Example #9
0
 function get($update = 0, $load = false)
 {
     if (!local_channel()) {
         $_SESSION['return_url'] = \App::$query_string;
         return login(false);
     }
     if ($load) {
         $_SESSION['loadtime'] = datetime_convert();
     }
     $arr = array('query' => \App::$query_string);
     call_hooks('network_content_init', $arr);
     $channel = \App::get_channel();
     $item_normal = item_normal();
     $datequery = $datequery2 = '';
     $group = 0;
     $nouveau = false;
     $datequery = x($_GET, 'dend') && is_a_date_arg($_GET['dend']) ? notags($_GET['dend']) : '';
     $datequery2 = x($_GET, 'dbegin') && is_a_date_arg($_GET['dbegin']) ? notags($_GET['dbegin']) : '';
     $nouveau = x($_GET, 'new') ? intval($_GET['new']) : 0;
     $gid = x($_GET, 'gid') ? intval($_GET['gid']) : 0;
     $category = x($_REQUEST, 'cat') ? $_REQUEST['cat'] : '';
     $hashtags = x($_REQUEST, 'tag') ? $_REQUEST['tag'] : '';
     $verb = x($_REQUEST, 'verb') ? $_REQUEST['verb'] : '';
     $search = $_GET['search'] ? $_GET['search'] : '';
     if ($search) {
         if (strpos($search, '@') === 0) {
             $r = q("select abook_id from abook left join xchan on abook_xchan = xchan_hash where xchan_name = '%s' and abook_channel = %d limit 1", dbesc(substr($search, 1)), intval(local_channel()));
             if ($r) {
                 $_GET['cid'] = $r[0]['abook_id'];
                 $search = $_GET['search'] = '';
             }
         } elseif (strpos($search, '#') === 0) {
             $hashtags = substr($search, 1);
             $search = $_GET['search'] = '';
         }
     }
     if ($datequery) {
         $_GET['order'] = 'post';
     }
     // filter by collection (e.g. group)
     if ($gid) {
         $r = q("SELECT * FROM groups WHERE id = %d AND uid = %d LIMIT 1", intval($gid), intval(local_channel()));
         if (!$r) {
             if ($update) {
                 killme();
             }
             notice(t('No such group') . EOL);
             goaway(z_root() . '/network');
             // NOTREACHED
         }
         $group = $gid;
         $group_hash = $r[0]['hash'];
         $def_acl = array('allow_gid' => '<' . $r[0]['hash'] . '>');
     }
     $o = '';
     // if no tabs are selected, defaults to comments
     $cid = x($_GET, 'cid') ? intval($_GET['cid']) : 0;
     $star = x($_GET, 'star') ? intval($_GET['star']) : 0;
     $order = x($_GET, 'order') ? notags($_GET['order']) : 'comment';
     $liked = x($_GET, 'liked') ? intval($_GET['liked']) : 0;
     $conv = x($_GET, 'conv') ? intval($_GET['conv']) : 0;
     $spam = x($_GET, 'spam') ? intval($_GET['spam']) : 0;
     $cmin = x($_GET, 'cmin') ? intval($_GET['cmin']) : 0;
     $cmax = x($_GET, 'cmax') ? intval($_GET['cmax']) : 99;
     $firehose = x($_GET, 'fh') ? intval($_GET['fh']) : 0;
     $file = x($_GET, 'file') ? $_GET['file'] : '';
     $deftag = '';
     if (x($_GET, 'search') || x($_GET, 'file')) {
         $nouveau = true;
     }
     if ($cid) {
         $r = q("SELECT abook_xchan FROM abook WHERE abook_id = %d AND abook_channel = %d LIMIT 1", intval($cid), intval(local_channel()));
         if (!$r) {
             if ($update) {
                 killme();
             }
             notice(t('No such channel') . EOL);
             goaway(z_root() . '/network');
             // NOTREACHED
         }
         if ($_GET['pf'] === '1') {
             $deftag = '@' . t('forum') . '+' . intval($cid) . '+';
         } else {
             $def_acl = array('allow_cid' => '<' . $r[0]['abook_xchan'] . '>');
         }
     }
     if (!$update) {
         $tabs = network_tabs();
         $o .= $tabs;
         // search terms header
         if ($search) {
             $o .= replace_macros(get_markup_template("section_title.tpl"), array('$title' => t('Search Results For:') . ' ' . htmlspecialchars($search, ENT_COMPAT, 'UTF-8')));
         }
         nav_set_selected('network');
         $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']);
         $private_editing = ($group || $cid) && !intval($_GET['pf']) ? true : false;
         $x = array('is_owner' => true, 'allow_location' => intval(get_pconfig($channel['channel_id'], 'system', 'use_browser_location')) ? '1' : '', 'default_location' => $channel['channel_location'], 'nickname' => $channel['channel_address'], 'lockstate' => $private_editing || $channel['channel_allow_cid'] || $channel['channel_allow_gid'] || $channel['channel_deny_cid'] || $channel['channel_deny_gid'] ? 'lock' : 'unlock', 'acl' => populate_acl($private_editing ? $def_acl : $channel_acl, true, \PermissionDescription::fromGlobalPermission('view_stream'), get_post_aclDialogDescription(), 'acl_dialog_post'), 'bang' => $private_editing ? '!' : '', 'visitor' => true, 'profile_uid' => local_channel(), 'editor_autocomplete' => true, 'bbco_autocomplete' => 'bbcode', 'bbcode' => true);
         if ($deftag) {
             $x['pretext'] = $deftag;
         }
         $status_editor = status_editor($a, $x);
         $o .= $status_editor;
     }
     // We don't have to deal with ACL's on this page. You're looking at everything
     // that belongs to you, hence you can see all of it. We will filter by group if
     // desired.
     $sql_options = $star ? " and item_starred = 1 " : '';
     $sql_nets = '';
     $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE item_thread_top = 1 {$sql_options} ) ";
     if ($group) {
         $contact_str = '';
         $contacts = group_get_members($group);
         if ($contacts) {
             foreach ($contacts as $c) {
                 if ($contact_str) {
                     $contact_str .= ',';
                 }
                 $contact_str .= "'" . $c['xchan'] . "'";
             }
         } else {
             $contact_str = ' 0 ';
             info(t('Privacy group is empty'));
         }
         $sql_extra = " AND item.parent IN ( SELECT DISTINCT parent FROM item WHERE true {$sql_options} AND (( author_xchan IN ( {$contact_str} ) OR owner_xchan in ( {$contact_str} )) or allow_gid like '" . protect_sprintf('%<' . dbesc($group_hash) . '>%') . "' ) and id = parent {$item_normal} ) ";
         $x = group_rec_byhash(local_channel(), $group_hash);
         if ($x) {
             $title = replace_macros(get_markup_template("section_title.tpl"), array('$title' => t('Privacy group: ') . $x['name']));
         }
         $o = $tabs;
         $o .= $title;
         $o .= $status_editor;
     } elseif ($cid) {
         $r = q("SELECT abook.*, xchan.* from abook left join xchan on abook_xchan = xchan_hash where abook_id = %d and abook_channel = %d and abook_blocked = 0 limit 1", intval($cid), intval(local_channel()));
         if ($r) {
             $sql_extra = " AND item.parent IN ( SELECT DISTINCT parent FROM item WHERE true {$sql_options} AND uid = " . intval(local_channel()) . " AND ( author_xchan = '" . dbesc($r[0]['abook_xchan']) . "' or owner_xchan = '" . dbesc($r[0]['abook_xchan']) . "' ) {$item_normal} ) ";
             $title = replace_macros(get_markup_template("section_title.tpl"), array('$title' => '<a href="' . zid($r[0]['xchan_url']) . '" ><img src="' . zid($r[0]['xchan_photo_s']) . '" alt="' . urlencode($r[0]['xchan_name']) . '" /></a> <a href="' . zid($r[0]['xchan_url']) . '" >' . $r[0]['xchan_name'] . '</a>'));
             $o = $tabs;
             $o .= $title;
             $o .= $status_editor;
         } else {
             notice(t('Invalid connection.') . EOL);
             goaway(z_root() . '/network');
         }
     }
     if (x($category)) {
         $sql_extra .= protect_sprintf(term_query('item', $category, TERM_CATEGORY));
     }
     if (x($hashtags)) {
         $sql_extra .= protect_sprintf(term_query('item', $hashtags, TERM_HASHTAG, TERM_COMMUNITYTAG));
     }
     if (!$update) {
         // The special div is needed for liveUpdate to kick in for this page.
         // We only launch liveUpdate if you aren't filtering in some incompatible
         // way and also you aren't writing a comment (discovered in javascript).
         if ($gid || $cid || $cmin || $cmax != 99 || $star || $liked || $conv || $spam || $nouveau || $list) {
             $firehose = 0;
         }
         $maxheight = get_pconfig(local_channel(), 'system', 'network_divmore_height');
         if (!$maxheight) {
             $maxheight = 400;
         }
         $o .= '<div id="live-network"></div>' . "\r\n";
         $o .= "<script> var profile_uid = " . local_channel() . "; var profile_page = " . \App::$pager['page'] . "; divmore_height = " . intval($maxheight) . "; </script>\r\n";
         \App::$page['htmlhead'] .= replace_macros(get_markup_template("build_query.tpl"), array('$baseurl' => z_root(), '$pgtype' => 'network', '$uid' => local_channel() ? local_channel() : '0', '$gid' => $gid ? $gid : '0', '$cid' => $cid ? $cid : '0', '$cmin' => $cmin ? $cmin : '0', '$cmax' => $cmax ? $cmax : '0', '$star' => $star ? $star : '0', '$liked' => $liked ? $liked : '0', '$conv' => $conv ? $conv : '0', '$spam' => $spam ? $spam : '0', '$fh' => $firehose ? $firehose : '0', '$nouveau' => $nouveau ? $nouveau : '0', '$wall' => '0', '$list' => x($_REQUEST, 'list') ? intval($_REQUEST['list']) : 0, '$page' => \App::$pager['page'] != 1 ? \App::$pager['page'] : 1, '$search' => $search ? $search : '', '$order' => $order, '$file' => $file, '$cats' => $category, '$tags' => $hashtags, '$dend' => $datequery, '$mid' => '', '$verb' => $verb, '$dbegin' => $datequery2));
     }
     $sql_extra3 = '';
     if ($datequery) {
         $sql_extra3 .= protect_sprintf(sprintf(" AND item.created <= '%s' ", dbesc(datetime_convert(date_default_timezone_get(), '', $datequery))));
     }
     if ($datequery2) {
         $sql_extra3 .= protect_sprintf(sprintf(" AND item.created >= '%s' ", dbesc(datetime_convert(date_default_timezone_get(), '', $datequery2))));
     }
     $sql_extra2 = $nouveau ? '' : " AND item.parent = item.id ";
     $sql_extra3 = $nouveau ? '' : $sql_extra3;
     if (x($_GET, 'search')) {
         $search = escape_tags($_GET['search']);
         if (strpos($search, '#') === 0) {
             $sql_extra .= term_query('item', substr($search, 1), TERM_HASHTAG, TERM_COMMUNITYTAG);
         } else {
             $sql_extra .= sprintf(" AND item.body like '%s' ", dbesc(protect_sprintf('%' . $search . '%')));
         }
     }
     if ($verb) {
         $sql_extra .= sprintf(" AND item.verb like '%s' ", dbesc(protect_sprintf('%' . $verb . '%')));
     }
     if (strlen($file)) {
         $sql_extra .= term_query('item', $file, TERM_FILE);
     }
     if ($conv) {
         $sql_extra .= sprintf(" AND parent IN (SELECT distinct(parent) from item where ( author_xchan like '%s' or item_mentionsme = 1 )) ", dbesc(protect_sprintf($channel['channel_hash'])));
     }
     if ($update && !$load) {
         // only setup pagination on initial page view
         $pager_sql = '';
     } else {
         $itemspage = get_pconfig(local_channel(), 'system', 'itemspage');
         \App::set_pager_itemspage(intval($itemspage) ? $itemspage : 20);
         $pager_sql = sprintf(" LIMIT %d OFFSET %d ", intval(\App::$pager['itemspage']), intval(\App::$pager['start']));
     }
     if ($cmin != 0 || $cmax != 99) {
         // Not everybody who shows up in the network stream will be in your address book.
         // By default those that aren't are assumed to have closeness = 99; but this isn't
         // recorded anywhere. So if cmax is 99, we'll open the search up to anybody in
         // the stream with a NULL address book entry.
         $sql_nets .= " AND ";
         if ($cmax == 99) {
             $sql_nets .= " ( ";
         }
         $sql_nets .= "( abook.abook_closeness >= " . intval($cmin) . " ";
         $sql_nets .= " AND abook.abook_closeness <= " . intval($cmax) . " ) ";
         if ($cmax == 99) {
             $sql_nets .= " OR abook.abook_closeness IS NULL ) ";
         }
     }
     $abook_uids = " and abook.abook_channel = " . local_channel() . " ";
     if ($firehose && !get_config('system', 'disable_discover_tab')) {
         require_once 'include/identity.php';
         $sys = get_sys_channel();
         $uids = " and item.uid  = " . intval($sys['channel_id']) . " ";
         \App::$data['firehose'] = intval($sys['channel_id']);
     } else {
         $uids = " and item.uid = " . local_channel() . " ";
     }
     if (get_pconfig(local_channel(), 'system', 'network_list_mode')) {
         $page_mode = 'list';
     } else {
         $page_mode = 'client';
     }
     $simple_update = $update ? " and item_unseen = 1 " : '';
     // This fixes a very subtle bug so I'd better explain it. You wake up in the morning or return after a day
     // or three and look at your matrix page - after opening up your browser. The first page loads just as it
     // should. All of a sudden a few seconds later, page 2 will get inserted at the beginning of the page
     // (before the page 1 content). The update code is actually doing just what it's supposed
     // to, it's fetching posts that have the ITEM_UNSEEN bit set. But the reason that page 2 content is being
     // returned in an UPDATE is because you hadn't gotten that far yet - you're still on page 1 and everything
     // that we loaded for page 1 is now marked as seen. But the stuff on page 2 hasn't been. So... it's being
     // treated as "new fresh" content because it is unseen. We need to distinguish it somehow from content
     // which "arrived as you were reading page 1". We're going to do this
     // by storing in your session the current UTC time whenever you LOAD a network page, and only UPDATE items
     // which are both ITEM_UNSEEN and have "changed" since that time. Cross fingers...
     if ($update && $_SESSION['loadtime']) {
         $simple_update = " AND (( item_unseen = 1 AND item.changed > '" . datetime_convert('UTC', 'UTC', $_SESSION['loadtime']) . "' )  OR item.changed > '" . datetime_convert('UTC', 'UTC', $_SESSION['loadtime']) . "' ) ";
     }
     if ($load) {
         $simple_update = '';
     }
     if ($nouveau && $load) {
         // "New Item View" - show all items unthreaded in reverse created date order
         $items = q("SELECT item.*, item.id AS item_id, received FROM item\n\t\t\t\tleft join abook on ( item.owner_xchan = abook.abook_xchan {$abook_uids} )\n\t\t\t\tWHERE true {$uids} {$item_normal}\n\t\t\t\tand (abook.abook_blocked = 0 or abook.abook_flags is null)\n\t\t\t\t{$simple_update}\n\t\t\t\t{$sql_extra} {$sql_nets}\n\t\t\t\tORDER BY item.received DESC {$pager_sql} ");
         require_once 'include/items.php';
         xchan_query($items);
         $items = fetch_post_tags($items, true);
     } elseif ($update) {
         // Normal conversation view
         if ($order === 'post') {
             $ordering = "created";
         } else {
             $ordering = "commented";
         }
         if ($load) {
             // Fetch a page full of parent items for this page
             $r = q("SELECT distinct item.id AS item_id, {$ordering} FROM item\n\t\t\t\t\tleft join abook on ( item.owner_xchan = abook.abook_xchan {$abook_uids} )\n\t\t\t\t\tWHERE true {$uids} {$item_normal}\n\t\t\t\t\tAND item.parent = item.id\n\t\t\t\t\tand (abook.abook_blocked = 0 or abook.abook_flags is null)\n\t\t\t\t\t{$sql_extra3} {$sql_extra} {$sql_nets}\n\t\t\t\t\tORDER BY {$ordering} DESC {$pager_sql} ");
         } else {
             // this is an update
             $r = q("SELECT item.parent AS item_id FROM item\n\t\t\t\t\tleft join abook on ( item.owner_xchan = abook.abook_xchan {$abook_uids} )\n\t\t\t\t\tWHERE true {$uids} {$item_normal} {$simple_update}\n\t\t\t\t\tand (abook.abook_blocked = 0 or abook.abook_flags is null)\n\t\t\t\t\t{$sql_extra3} {$sql_extra} {$sql_nets} ");
             $_SESSION['loadtime'] = datetime_convert();
         }
         // Then fetch all the children of the parents that are on this page
         $parents_str = '';
         $update_unseen = '';
         if ($r) {
             $parents_str = ids_to_querystr($r, 'item_id');
             $items = q("SELECT item.*, item.id AS item_id FROM item\n\t\t\t\t\tWHERE true {$uids} {$item_normal}\n\t\t\t\t\tAND item.parent IN ( %s )\n\t\t\t\t\t{$sql_extra} ", dbesc($parents_str));
             xchan_query($items, true, $firehose ? local_channel() : 0);
             $items = fetch_post_tags($items, true);
             $items = conv_sort($items, $ordering);
         } else {
             $items = array();
         }
         if ($page_mode === 'list') {
             /**
              * in "list mode", only mark the parent item and any like activities as "seen". 
              * We won't distinguish between comment likes and post likes. The important thing
              * is that the number of unseen comments will be accurate. The SQL to separate the
              * comment likes could also get somewhat hairy. 
              */
             if ($parents_str) {
                 $update_unseen = " AND ( id IN ( " . dbesc($parents_str) . " )";
                 $update_unseen .= " OR ( parent IN ( " . dbesc($parents_str) . " ) AND verb in ( '" . dbesc(ACTIVITY_LIKE) . "','" . dbesc(ACTIVITY_DISLIKE) . "' ))) ";
             }
         } else {
             if ($parents_str) {
                 $update_unseen = " AND parent IN ( " . dbesc($parents_str) . " )";
             }
         }
     }
     if ($update_unseen && !$firehose) {
         $r = q("UPDATE item SET item_unseen = 0 WHERE item_unseen = 1 AND uid = %d {$update_unseen} ", intval(local_channel()));
     }
     $mode = $nouveau ? 'network-new' : 'network';
     $o .= conversation($a, $items, $mode, $update, $page_mode);
     if ($items && !$update) {
         $o .= alt_pager($a, count($items));
     }
     return $o;
 }
Example #10
0
function get_plink($item, $conversation_mode = true)
{
    if ($conversation_mode) {
        $key = 'plink';
    } else {
        $key = 'llink';
    }
    if (x($item, $key)) {
        return array('href' => zid($item[$key]), 'title' => t('Link to Source'));
    } else {
        return false;
    }
}
Example #11
0
File: apps.php Project: Mauru/red
function app_render($papp, $mode = 'view')
{
    /**
     * modes:
     *    view: normal mode for viewing an app via bbcode from a conversation or page
     *       provides install/update button if you're logged in locally
     *    list: normal mode for viewing an app on the app page
     *       no buttons are shown
     *    edit: viewing the app page in editing mode provides a delete button
     */
    $installed = false;
    if (!$papp['photo']) {
        $papp['photo'] = z_root() . '/' . get_default_profile_photo(80);
    }
    if (!$papp) {
        return;
    }
    $papp['papp'] = papp_encode($papp);
    foreach ($papp as $k => $v) {
        if (strpos($v, 'http') === 0 && $k != 'papp') {
            $papp[$k] = zid($v);
        }
        if ($k === 'desc') {
            $papp['desc'] = str_replace(array('\'', '"'), array('&#39;', '&dquot;'), $papp['desc']);
        }
        if ($k === 'requires') {
            $require = trim(strtolower($v));
            switch ($require) {
                case 'nologin':
                    if (local_user()) {
                        return '';
                    }
                    break;
                case 'admin':
                    if (!is_site_admin()) {
                        return '';
                    }
                    break;
                case 'local_user':
                    if (!local_user()) {
                        return '';
                    }
                    break;
                case 'public_profile':
                    if (!is_public_profile()) {
                        return '';
                    }
                    break;
                case 'observer':
                    $observer = get_app()->get_observer();
                    if (!$observer) {
                        return '';
                    }
                    break;
                default:
                    if (!local_user() && feature_enabled(local_user(), $require)) {
                        return '';
                    }
                    break;
            }
        }
    }
    $hosturl = '';
    if (local_user()) {
        $installed = app_installed(local_user(), $papp);
        $hosturl = z_root() . '/';
    } elseif (remote_user()) {
        $observer = get_app()->get_observer();
        if ($observer && $observer['xchan_network'] === 'zot') {
            // some folks might have xchan_url redirected offsite, use the connurl
            $x = parse_url($observer['xchan_connurl']);
            if ($x) {
                $hosturl = $x['scheme'] . '://' . $x['host'] . '/';
            }
        }
    }
    $install_action = $installed ? t('Update') : t('Install');
    return replace_macros(get_markup_template('app.tpl'), array('$app' => $papp, '$hosturl' => $hosturl, '$purchase' => $papp['page'] && !$installed ? t('Purchase') : '', '$install' => $hosturl && $mode == 'view' ? $install_action : '', '$edit' => local_user() && $installed && $mode == 'edit' ? t('Edit') : '', '$delete' => local_user() && $installed && $mode == 'edit' ? t('Delete') : ''));
}
Example #12
0
function dirprofile_init(&$a)
{
    if (get_config('system', 'block_public') && !local_user() && !remote_user()) {
        notice(t('Public access denied.') . EOL);
        return;
    }
    $hash = $_REQUEST['hash'];
    if (!$hash) {
        return '';
    }
    $o = '';
    $dirmode = intval(get_config('system', 'directory_mode'));
    if ($dirmode == DIRECTORY_MODE_PRIMARY || $dirmode == DIRECTORY_MODE_STANDALONE) {
        $url = z_root() . '/dirsearch';
    }
    if (!$url) {
        $directory = find_upstream_directory($dirmode);
        $url = $directory['url'] . '/dirsearch';
    }
    logger('mod_directory: URL = ' . $url, LOGGER_DEBUG);
    $contacts = array();
    if (local_user()) {
        $x = q("select abook_xchan from abook where abook_channel = %d", intval(local_user()));
        if ($x) {
            foreach ($x as $xx) {
                $contacts[] = $xx['abook_xchan'];
            }
        }
    }
    if ($url) {
        $query = $url . '?f=&hash=' . $hash;
        $x = z_fetch_url($query);
        logger('dirprofile: return from upstream: ' . print_r($x, true), LOGGER_DATA);
        if ($x['success']) {
            $t = 0;
            $j = json_decode($x['body'], true);
            if ($j) {
                if ($j['results']) {
                    $entries = array();
                    $photo = 'thumb';
                    foreach ($j['results'] as $rr) {
                        $profile_link = chanlink_url($rr['url']);
                        $pdesc = $rr['description'] ? $rr['description'] . '<br />' : '';
                        $qrlink = zid($rr['url']);
                        $connect_link = local_user() ? z_root() . '/follow?f=&url=' . urlencode($rr['address']) : '';
                        $online = remote_online_status($rr['address']);
                        if (in_array($rr['hash'], $contacts)) {
                            $connect_link = '';
                        }
                        $details = '';
                        if (strlen($rr['locale'])) {
                            $details .= $rr['locale'];
                        }
                        if (strlen($rr['region'])) {
                            if (strlen($rr['locale'])) {
                                $details .= ', ';
                            }
                            $details .= $rr['region'];
                        }
                        if (strlen($rr['country'])) {
                            if (strlen($details)) {
                                $details .= ', ';
                            }
                            $details .= $rr['country'];
                        }
                        if (strlen($rr['birthday'])) {
                            if (($years = age($rr['birthday'], 'UTC', '')) != 0) {
                                $details .= '<br />' . t('Age: ') . $years;
                            }
                        }
                        if (strlen($rr['gender'])) {
                            $details .= '<br />' . t('Gender: ') . $rr['gender'];
                        }
                        $page_type = '';
                        $profile = $rr;
                        if (x($profile, 'locale') == 1 || x($profile, 'region') == 1 || x($profile, 'postcode') == 1 || x($profile, 'country') == 1) {
                            $location = t('Location:');
                        }
                        $marital = x($profile, 'marital') == 1 ? t('Status: ') . $profile['marital'] : False;
                        $sexual = x($profile, 'sexual') == 1 ? t('Sexual Preference: ') . $profile['sexual'] : False;
                        $homepage = x($profile, 'homepage') == 1 ? t('Homepage: ') . linkify($profile['homepage']) : False;
                        $hometown = x($profile, 'hometown') == 1 ? t('Hometown: ') . $profile['hometown'] : False;
                        $about = x($profile, 'about') == 1 ? t('About: ') . bbcode($profile['about']) : False;
                        $keywords = x($profile, 'keywords') ? $profile['keywords'] : '';
                        if ($keywords) {
                            $keywords = str_replace(',', ' ', $keywords);
                            $keywords = str_replace('  ', ' ', $keywords);
                            $karr = explode(' ', $keywords);
                            $out = '';
                            if ($karr) {
                                if (local_user()) {
                                    $r = q("select keywords from profile where uid = %d and is_default = 1 limit 1", intval(local_user()));
                                    if ($r) {
                                        $keywords = str_replace(',', ' ', $r[0]['keywords']);
                                        $keywords = str_replace('  ', ' ', $keywords);
                                        $marr = explode(' ', $keywords);
                                    }
                                }
                                foreach ($karr as $k) {
                                    if (strlen($out)) {
                                        $out .= ', ';
                                    }
                                    if ($marr && in_arrayi($k, $marr)) {
                                        $out .= '<strong>' . $k . '</strong>';
                                    } else {
                                        $out .= $k;
                                    }
                                }
                            }
                        }
                        $entry = replace_macros(get_markup_template('direntry_large.tpl'), array('$id' => ++$t, '$profile_link' => $profile_link, '$qrlink' => $qrlink, '$photo' => $rr['photo_l'], '$alttext' => $rr['name'] . ' ' . $rr['address'], '$name' => $rr['name'], '$online' => $online ? t('Online Now') : '', '$details' => $pdesc . $details, '$profile' => $profile, '$address' => $rr['address'], '$location' => $location, '$gender' => $gender, '$pdesc' => $pdesc, '$marital' => $marital, '$homepage' => $homepage, '$hometown' => $hometown, '$about' => $about, '$kw' => $out ? t('Keywords: ') : '', '$keywords' => $out, '$conn_label' => t('Connect'), '$connect' => $connect_link));
                        echo $entry;
                        killme();
                    }
                } else {
                    info(t("Not found.") . EOL);
                }
            }
        }
    }
}
Example #13
0
function new_contact($uid, $url, $channel, $interactive = false, $confirm = false)
{
    $result = array('success' => false, 'message' => '');
    $is_red = false;
    $is_http = strpos($url, '://') !== false ? true : false;
    if ($is_http && substr($url, -1, 1) === '/') {
        $url = substr($url, 0, -1);
    }
    if (!allowed_url($url)) {
        $result['message'] = t('Channel is blocked on this site.');
        return $result;
    }
    if (!$url) {
        $result['message'] = t('Channel location missing.');
        return $result;
    }
    // check service class limits
    $r = q("select count(*) as total from abook where abook_channel = %d and abook_self = 0 ", intval($uid));
    if ($r) {
        $total_channels = $r[0]['total'];
    }
    if (!service_class_allows($uid, 'total_channels', $total_channels)) {
        $result['message'] = upgrade_message();
        return $result;
    }
    $arr = array('url' => $url, 'channel' => array());
    call_hooks('follow', $arr);
    if ($arr['channel']['success']) {
        $ret = $arr['channel'];
    } elseif (!$is_http) {
        $ret = Zotlabs\Zot\Finger::run($url, $channel);
    }
    if ($ret && is_array($ret) && $ret['success']) {
        $is_red = true;
        $j = $ret;
    }
    $my_perms = get_channel_default_perms($uid);
    $role = get_pconfig($uid, 'system', 'permissions_role');
    if ($role) {
        $x = \Zotlabs\Access\PermissionRoles::role_perms($role);
        if ($x['perms_connect']) {
            $my_perms = $x['perms_connect'];
        }
    }
    if ($is_red && $j) {
        logger('follow: ' . $url . ' ' . print_r($j, true), LOGGER_DEBUG);
        if (!($j['success'] && $j['guid'])) {
            $result['message'] = t('Response from remote channel was incomplete.');
            logger('mod_follow: ' . $result['message']);
            return $result;
        }
        // Premium channel, set confirm before callback to avoid recursion
        if (array_key_exists('connect_url', $j) && $interactive && !$confirm) {
            goaway(zid($j['connect_url']));
        }
        // do we have an xchan and hubloc?
        // If not, create them.
        $x = import_xchan($j);
        if (array_key_exists('deleted', $j) && intval($j['deleted'])) {
            $result['message'] = t('Channel was deleted and no longer exists.');
            return $result;
        }
        if (!$x['success']) {
            return $x;
        }
        $xchan_hash = $x['hash'];
        if (array_key_exists('permissions', $j) && array_key_exists('data', $j['permissions'])) {
            $permissions = crypto_unencapsulate(array('data' => $j['permissions']['data'], 'key' => $j['permissions']['key'], 'iv' => $j['permissions']['iv']), $channel['channel_prvkey']);
            if ($permissions) {
                $permissions = json_decode($permissions, true);
            }
            logger('decrypted permissions: ' . print_r($permissions, true), LOGGER_DATA);
        } else {
            $permissions = $j['permissions'];
        }
        if (is_array($permissions) && $permissions) {
            foreach ($permissions as $k => $v) {
                set_abconfig($channel['channel_uid'], $xchan_hash, 'their_perms', $k, intval($v));
            }
        }
    } else {
        $xchan_hash = '';
        $r = q("select * from xchan where xchan_hash = '%s' or xchan_url = '%s' limit 1", dbesc($url), dbesc($url));
        if (!$r) {
            // attempt network auto-discovery
            $d = discover_by_webbie($url);
            if (!$d && $is_http) {
                // try RSS discovery
                if (get_config('system', 'feed_contacts')) {
                    $d = discover_by_url($url);
                } else {
                    $result['message'] = t('Protocol disabled.');
                    return $result;
                }
            }
            if ($d) {
                $r = q("select * from xchan where xchan_hash = '%s' or xchan_url = '%s' limit 1", dbesc($url), dbesc($url));
            }
        }
        // if discovery was a success we should have an xchan record in $r
        if ($r) {
            $xchan = $r[0];
            $xchan_hash = $r[0]['xchan_hash'];
            $their_perms = 0;
        }
    }
    if (!$xchan_hash) {
        $result['message'] = t('Channel discovery failed.');
        logger('follow: ' . $result['message']);
        return $result;
    }
    $allowed = $is_red || $r[0]['xchan_network'] === 'rss' ? 1 : 0;
    $x = array('channel_id' => $uid, 'follow_address' => $url, 'xchan' => $r[0], 'allowed' => $allowed, 'singleton' => 0);
    call_hooks('follow_allow', $x);
    if (!$x['allowed']) {
        $result['message'] = t('Protocol disabled.');
        return $result;
    }
    $singleton = intval($x['singleton']);
    $aid = $channel['channel_account_id'];
    $hash = get_observer_hash();
    $default_group = $channel['channel_default_group'];
    if ($xchan['xchan_network'] === 'rss') {
        // check service class feed limits
        $r = q("select count(*) as total from abook where abook_account = %d and abook_feed = 1 ", intval($aid));
        if ($r) {
            $total_feeds = $r[0]['total'];
        }
        if (!service_class_allows($uid, 'total_feeds', $total_feeds)) {
            $result['message'] = upgrade_message();
            return $result;
        }
    }
    if ($hash == $xchan_hash) {
        $result['message'] = t('Cannot connect to yourself.');
        return $result;
    }
    $r = q("select abook_xchan, abook_instance from abook where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($xchan_hash), intval($uid));
    if ($is_http) {
        // Always set these "remote" permissions for feeds since we cannot interact with them
        // to negotiate a suitable permission response
        set_abconfig($uid, $xchan_hash, 'their_perms', 'view_stream', 1);
        set_abconfig($uid, $xchan_hash, 'their_perms', 'republish', 1);
    }
    if ($r) {
        $abook_instance = $r[0]['abook_instance'];
        if ($singleton && strpos($abook_instance, z_root()) === false) {
            if ($abook_instance) {
                $abook_instance .= ',';
            }
            $abook_instance .= z_root();
        }
        $x = q("update abook set abook_instance = '%s' where abook_id = %d", dbesc($abook_instance), intval($r[0]['abook_id']));
    } else {
        $closeness = get_pconfig($uid, 'system', 'new_abook_closeness');
        if ($closeness === false) {
            $closeness = 80;
        }
        $r = q("insert into abook ( abook_account, abook_channel, abook_closeness, abook_xchan, abook_feed, abook_created, abook_updated, abook_instance )\n\t\t\tvalues( %d, %d, %d, '%s', %d, '%s', '%s', '%s' ) ", intval($aid), intval($uid), intval($closeness), dbesc($xchan_hash), intval($is_http ? 1 : 0), dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc($singleton ? z_root() : ''));
    }
    if (!$r) {
        logger('mod_follow: abook creation failed');
    }
    $all_perms = \Zotlabs\Access\Permissions::Perms();
    if ($all_perms) {
        foreach ($all_perms as $k => $v) {
            if (in_array($k, $my_perms)) {
                set_abconfig($uid, $xchan_hash, 'my_perms', $k, 1);
            } else {
                set_abconfig($uid, $xchan_hash, 'my_perms', $k, 0);
            }
        }
    }
    $r = q("select abook.*, xchan.* from abook left join xchan on abook_xchan = xchan_hash \n\t\twhere abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($xchan_hash), intval($uid));
    if ($r) {
        $result['abook'] = $r[0];
        Zotlabs\Daemon\Master::Summon(array('Notifier', 'permission_create', $result['abook']['abook_id']));
    }
    $arr = array('channel_id' => $uid, 'channel' => $channel, 'abook' => $result['abook']);
    call_hooks('follow', $arr);
    /** If there is a default group for this channel, add this connection to it */
    if ($default_group) {
        require_once 'include/group.php';
        $g = group_rec_byhash($uid, $default_group);
        if ($g) {
            group_add_member($uid, '', $xchan_hash, $g['id']);
        }
    }
    $result['success'] = true;
    return $result;
}
Example #14
0
function chanview_content(&$a)
{
    $observer = $a->get_observer();
    $xchan = null;
    $r = null;
    if ($_REQUEST['hash']) {
        $r = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($_REQUEST['hash']));
    }
    if ($_REQUEST['address']) {
        $r = q("select * from xchan where xchan_addr = '%s' limit 1", dbesc($_REQUEST['address']));
    } elseif (local_channel() && intval($_REQUEST['cid'])) {
        $r = q("SELECT abook.*, xchan.* \n\t\t\tFROM abook left join xchan on abook_xchan = xchan_hash\n\t\t\tWHERE abook_channel = %d and abook_id = %d LIMIT 1", intval(local_channel()), intval($_REQUEST['cid']));
    } elseif ($_REQUEST['url']) {
        // if somebody re-installed they will have more than one xchan, use the most recent name date as this is
        // the most useful consistently ascending table item we have.
        $r = q("select * from xchan where xchan_url = '%s' order by xchan_name_date desc limit 1", dbesc($_REQUEST['url']));
    }
    if ($r) {
        $a->poi = $r[0];
    }
    // Here, let's see if we have an xchan. If we don't, how we proceed is determined by what
    // info we do have. If it's a URL, we can offer to visit it directly. If it's a webbie or
    // address, we can and should try to import it. If it's just a hash, we can't continue, but we
    // probably wouldn't have a hash if we don't already have an xchan for this channel.
    if (!$a->poi) {
        logger('mod_chanview: fallback');
        // This is hackish - construct a zot address from the url
        if ($_REQUEST['url']) {
            if (preg_match('/https?\\:\\/\\/(.*?)(\\/channel\\/|\\/profile\\/)(.*?)$/ism', $_REQUEST['url'], $matches)) {
                $_REQUEST['address'] = $matches[3] . '@' . $matches[1];
            }
            logger('mod_chanview: constructed address ' . print_r($matches, true));
        }
        if ($_REQUEST['address']) {
            $ret = zot_finger($_REQUEST['address'], null);
            if ($ret['success']) {
                $j = json_decode($ret['body'], true);
                if ($j) {
                    import_xchan($j);
                }
                $r = q("select * from xchan where xchan_addr = '%s' limit 1", dbesc($_REQUEST['address']));
                if ($r) {
                    $a->poi = $r[0];
                }
            }
        }
    }
    if (!$a->poi) {
        //		We don't know who this is, and we can't figure it out from the URL
        //		On the plus side, there's a good chance we know somebody else at that
        //		hub so sending them there with a Zid will probably work anyway.
        $url = $_REQUEST['url'];
        if ($observer) {
            $url = zid($url);
        }
    }
    if ($a->poi) {
        $url = $a->poi['xchan_url'];
        if ($observer) {
            $url = zid($url);
        }
    }
    // let somebody over-ride the iframed viewport presentation
    // or let's just declare this a failed experiment.
    //	if((! local_channel()) || (get_pconfig(local_channel(),'system','chanview_full')))
    goaway($url);
    //	$o = replace_macros(get_markup_template('chanview.tpl'),array(
    //		'$url' => $url,
    //		'$full' => t('toggle full screen mode')
    //	));
    //	return $o;
}
Example #15
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 #16
0
function bb_ShareAttributes($match)
{
    $matches = array();
    $attributes = $match[1];
    $author = "";
    preg_match("/author='(.*?)'/ism", $attributes, $matches);
    if ($matches[1] != "") {
        $author = urldecode($matches[1]);
    }
    $link = "";
    preg_match("/link='(.*?)'/ism", $attributes, $matches);
    if ($matches[1] != "") {
        $link = $matches[1];
    }
    $avatar = "";
    preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
    if ($matches[1] != "") {
        $avatar = $matches[1];
    }
    $profile = "";
    preg_match("/profile='(.*?)'/ism", $attributes, $matches);
    if ($matches[1] != "") {
        $profile = $matches[1];
    }
    $posted = "";
    preg_match("/posted='(.*?)'/ism", $attributes, $matches);
    if ($matches[1] != "") {
        $posted = $matches[1];
    }
    // message_id is never used, do we still need it?
    $message_id = "";
    preg_match("/message_id='(.*?)'/ism", $attributes, $matches);
    if ($matches[1] != "") {
        $message_id = $matches[1];
    }
    /** @FIXME - this should really be a wall-item-ago so it will get updated on the client */
    $reldate = $posted ? relative_date($posted) : '';
    $headline = '<div class="shared_container"> <div class="shared_header">';
    if ($avatar != "") {
        $headline .= '<a href="' . zid($profile) . '" ><img src="' . $avatar . '" alt="' . $author . '" height="32" width="32" /></a>';
    }
    // Bob Smith wrote the following post 2 hours ago
    $fmt = sprintf(t('%1$s wrote the following %2$s %3$s'), '<a href="' . zid($profile) . '" >' . $author . '</a>', '<a href="' . zid($link) . '" >' . t('post') . '</a>', $reldate);
    $headline .= '<span>' . $fmt . '</span></div>';
    $text = $headline . '<div class="reshared-content">' . trim($match[2]) . '</div></div>';
    return $text;
}
Example #17
0
function oembed_format_object($j)
{
    $a = get_app();
    $embedurl = $j->embedurl;
    // logger('format: ' . print_r($j,true));
    $jhtml = oembed_iframe($j->embedurl, isset($j->width) ? $j->width : null, isset($j->height) ? $j->height : null);
    $ret = "<span class='oembed " . $j->type . "'>";
    switch ($j->type) {
        case "video":
            if (isset($j->thumbnail_url)) {
                $tw = isset($j->thumbnail_width) ? $j->thumbnail_width : 200;
                $th = isset($j->thumbnail_height) ? $j->thumbnail_height : 180;
                $tr = $tw / $th;
                $th = 120;
                $tw = $th * $tr;
                $tpl = get_markup_template('oembed_video.tpl');
                if (strstr($embedurl, 'youtu') && strstr(z_root(), 'https:')) {
                    $embedurl = str_replace('http:', 'https:', $embedurl);
                    $j->thumbnail_url = str_replace('http:', 'https:', $j->thumbnail_url);
                    $jhtml = str_replace('http:', 'https:', $jhtml);
                    $j->html = str_replace('http:', 'https:', $j->html);
                }
                $ret .= replace_macros($tpl, array('$baseurl' => $a->get_baseurl(), '$embedurl' => $embedurl, '$escapedhtml' => base64_encode($jhtml), '$tw' => $tw, '$th' => $th, '$turl' => $j->thumbnail_url));
            } else {
                $ret = $jhtml;
            }
            $ret .= "<br>";
            break;
        case "photo":
            $ret .= "<img width='" . $j->width . "' src='" . $j->url . "'>";
            $ret .= "<br>";
            break;
        case "link":
            if ($j->thumbnail_url) {
                if (is_matrix_url($embedurl)) {
                    $embedurl = zid($embedurl);
                    $j->thumbnail_url = zid($j->thumbnail_url);
                }
                $ret = '<a href="' . $embedurl . '" ><img src="' . $j->thumbnail_url . '" alt="thumbnail" /></a><br /><br />';
            }
            //$ret = "<a href='".$embedurl."'>".$j->title."</a>";
            break;
        case "rich":
            // not so safe..
            $ret .= $jhtml;
            break;
    }
    // add link to source if not present in "rich" type
    if ($j->type != 'rich' || !strpos($j->html, $embedurl)) {
        $embedlink = isset($j->title) ? $j->title : $embedurl;
        $ret .= '<br /><span class="bookmark-identifier">#^</span>' . "<a href='{$embedurl}' rel='oembed'>{$embedlink}</a>";
        $ret .= "<br />";
        if (isset($j->author_name)) {
            $ret .= " by " . $j->author_name;
        }
        if (isset($j->provider_name)) {
            $ret .= " on " . $j->provider_name;
        }
    } else {
        // add <a> for html2bbcode conversion
        $ret .= "<br /><a href='{$embedurl}' rel='oembed'>{$embedurl}</a>";
    }
    $ret .= "<br style='clear:left'></span>";
    return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
}
Example #18
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 #19
0
function prepare_page($item)
{
    $a = get_app();
    $naked = get_pconfig($item['uid'], 'system', 'nakedpage') ? 1 : 0;
    $observer = $a->get_observer();
    //240 chars is the longest we can have before we start hitting problems with suhosin sites
    $preview = substr(urlencode($item['body']), 0, 240);
    $link = z_root() . '/' . $a->cmd;
    if (array_key_exists('webpage', $a->layout) && array_key_exists('authored', $a->layout['webpage'])) {
        if ($a->layout['webpage']['authored'] === 'none') {
            $naked = 1;
        }
        // ... other possible options
    }
    // prepare_body calls unobscure() as a side effect. Do it here so that
    // the template will get passed an unobscured title.
    $body = prepare_body($item, true);
    $tpl = get_pconfig($item['uid'], 'system', 'pagetemplate');
    if (!$tpl) {
        $tpl = 'page_display.tpl';
    }
    return replace_macros(get_markup_template($tpl), array('$author' => $naked ? '' : $item['author']['xchan_name'], '$auth_url' => $naked ? '' : zid($item['author']['xchan_url']), '$date' => $naked ? '' : datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'Y-m-d H:i'), '$title' => smilies(bbcode($item['title'])), '$body' => $body, '$preview' => $preview, '$link' => $link));
}
Example #20
0
function widget_photo_rand($arr)
{
    require_once 'include/photos.php';
    $style = false;
    if (array_key_exists('album', $arr) && isset($arr['album'])) {
        $album = $arr['album'];
    } else {
        $album = '';
    }
    $channel_id = 0;
    if (array_key_exists('channel_id', $arr) && intval($arr['channel_id'])) {
        $channel_id = intval($arr['channel_id']);
    }
    if (!$channel_id) {
        $channel_id = get_app()->profile_uid;
    }
    if (!$channel_id) {
        return '';
    }
    $scale = array_key_exists('scale', $arr) ? intval($arr['scale']) : 0;
    $ret = photos_list_photos(array('channel_id' => $channel_id), get_app()->get_observer(), $album);
    $filtered = array();
    if ($ret['success'] && $ret['photos']) {
        foreach ($ret['photos'] as $p) {
            if ($p['scale'] == $scale) {
                $filtered[] = $p['src'];
            }
        }
    }
    if ($filtered) {
        $e = mt_rand(0, count($filtered) - 1);
        $url = $filtered[$e];
    }
    if (strpos($url, 'http') !== 0) {
        return '';
    }
    if (array_key_exists('style', $arr) && isset($arr['style'])) {
        $style = $arr['style'];
    }
    // ensure they can't sneak in an eval(js) function
    if (strpos($style, '(') !== false) {
        return '';
    }
    $url = zid($url);
    $o = '<div class="widget">';
    $o .= '<img class="zrl" ' . ($style ? ' style="' . $style . '"' : '') . ' src="' . $url . '" alt="' . t('photo/image') . '">';
    $o .= '</div>';
    return $o;
}
Example #21
0
 function exec()
 {
     $opts = $this->curlopts;
     $url = $this->url;
     if ($this->auth) {
         $opts['http_auth'] = $this->auth;
     }
     if ($this->magicauth) {
         $opts['cookiejar'] = 'store/[data]/cookie_' . $this->magicauth;
         $opts['cookiefile'] = 'store/[data]/cookie_' . $this->magicauth;
         $opts['cookie'] = 'PHPSESSID=' . trim(file_get_contents('store/[data]/cookien_' . $this->magicauth));
         $c = channelx_by_n($this->magicauth);
         if ($c) {
             $url = zid($this->url, channel_reddress($c));
         }
     }
     if ($this->custom) {
         $opts['custom'] = $this->custom;
     }
     if ($this->headers) {
         $opts['headers'] = $this->headers;
     }
     if ($this->upload) {
         $opts['upload'] = true;
         $opts['infile'] = $this->filehandle;
         $opts['infilesize'] = strlen($this->request_data);
         $opts['readfunc'] = [$this, 'curl_read'];
     }
     $recurse = 0;
     return z_fetch_url($this->url, true, $recurse, $opts ? $opts : null);
 }
Example #22
0
function new_contact($uid, $url, $channel, $interactive = false, $confirm = false)
{
    $result = array('success' => false, 'message' => '');
    $a = get_app();
    $is_red = false;
    $is_http = strpos($url, '://') !== false ? true : false;
    if ($is_http && substr($url, -1, 1) === '/') {
        $url = substr($url, 0, -1);
    }
    if (!allowed_url($url)) {
        $result['message'] = t('Channel is blocked on this site.');
        return $result;
    }
    if (!$url) {
        $result['message'] = t('Channel location missing.');
        return $result;
    }
    // check service class limits
    $r = q("select count(*) as total from abook where abook_channel = %d and abook_self = 0 ", intval($uid));
    if ($r) {
        $total_channels = $r[0]['total'];
    }
    if (!service_class_allows($uid, 'total_channels', $total_channels)) {
        $result['message'] = upgrade_message();
        return $result;
    }
    $arr = array('url' => $url, 'channel' => array());
    call_hooks('follow', $arr);
    if ($arr['channel']['success']) {
        $ret = $arr['channel'];
    } elseif (!$is_http) {
        $ret = zot_finger($url, $channel);
    }
    if ($ret && $ret['success']) {
        $is_red = true;
        $j = json_decode($ret['body'], true);
    }
    $my_perms = get_channel_default_perms($uid);
    $role = get_pconfig($uid, 'system', 'permissions_role');
    if ($role) {
        $x = get_role_perms($role);
        if ($x['perms_follow']) {
            $my_perms = $x['perms_follow'];
        }
    }
    if ($is_red && $j) {
        logger('follow: ' . $url . ' ' . print_r($j, true), LOGGER_DEBUG);
        if (!($j['success'] && $j['guid'])) {
            $result['message'] = t('Response from remote channel was incomplete.');
            logger('mod_follow: ' . $result['message']);
            return $result;
        }
        // Premium channel, set confirm before callback to avoid recursion
        if (array_key_exists('connect_url', $j) && $interactive && !$confirm) {
            goaway(zid($j['connect_url']));
        }
        // do we have an xchan and hubloc?
        // If not, create them.
        $x = import_xchan($j);
        if (array_key_exists('deleted', $j) && intval($j['deleted'])) {
            $result['message'] = t('Channel was deleted and no longer exists.');
            return $result;
        }
        if (!$x['success']) {
            return $x;
        }
        $xchan_hash = $x['hash'];
        $their_perms = 0;
        $global_perms = get_perms();
        if (array_key_exists('permissions', $j) && array_key_exists('data', $j['permissions'])) {
            $permissions = crypto_unencapsulate(array('data' => $j['permissions']['data'], 'key' => $j['permissions']['key'], 'iv' => $j['permissions']['iv']), $channel['channel_prvkey']);
            if ($permissions) {
                $permissions = json_decode($permissions, true);
            }
            logger('decrypted permissions: ' . print_r($permissions, true), LOGGER_DATA);
        } else {
            $permissions = $j['permissions'];
        }
        foreach ($permissions as $k => $v) {
            if ($v) {
                $their_perms = $their_perms | intval($global_perms[$k][1]);
            }
        }
    } else {
        $their_perms = 0;
        $xchan_hash = '';
        $r = q("select * from xchan where xchan_hash = '%s' or xchan_url = '%s' limit 1", dbesc($url), dbesc($url));
        if (!$r) {
            // attempt network auto-discovery
            if (strpos($url, '@') && !$is_http) {
                $r = discover_by_webbie($url);
            } elseif ($is_http) {
                $r = discover_by_url($url);
                $r['allowed'] = intval(get_config('system', 'feed_contacts'));
            }
            if ($r) {
                $r['channel_id'] = $uid;
                call_hooks('follow_allow', $r);
                if (!$r['allowed']) {
                    $result['message'] = t('Protocol disabled.');
                    return $result;
                }
                $r = q("select * from xchan where xchan_hash = '%s' or xchan_url = '%s' limit 1", dbesc($url), dbesc($url));
            }
        }
        if ($r) {
            $xchan_hash = $r[0]['xchan_hash'];
            $their_perms = 0;
        }
    }
    if (!$xchan_hash) {
        $result['message'] = t('Channel discovery failed.');
        logger('follow: ' . $result['message']);
        return $result;
    }
    if (local_channel() && $uid == local_channel()) {
        $aid = get_account_id();
        $hash = get_observer_hash();
        $ch = $a->get_channel();
        $default_group = $ch['channel_default_group'];
    } else {
        $r = q("select * from channel where channel_id = %d limit 1", intval($uid));
        if (!$r) {
            $result['message'] = t('local account not found.');
            return $result;
        }
        $aid = $r[0]['channel_account_id'];
        $hash = $r[0]['channel_hash'];
        $default_group = $r[0]['channel_default_group'];
    }
    if ($is_http) {
        $r = q("select count(*) as total from abook where abook_account = %d and abook_feed = 1 ", intval($aid));
        if ($r) {
            $total_feeds = $r[0]['total'];
        }
        if (!service_class_allows($uid, 'total_feeds', $total_feeds)) {
            $result['message'] = upgrade_message();
            return $result;
        }
    }
    if ($hash == $xchan_hash) {
        $result['message'] = t('Cannot connect to yourself.');
        return $result;
    }
    $r = q("select abook_xchan from abook where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($xchan_hash), intval($uid));
    if ($r) {
        $x = q("update abook set abook_their_perms = %d where abook_id = %d", intval($their_perms), intval($r[0]['abook_id']));
    } else {
        $closeness = get_pconfig($uid, 'system', 'new_abook_closeness');
        if ($closeness === false) {
            $closeness = 80;
        }
        $r = q("insert into abook ( abook_account, abook_channel, abook_closeness, abook_xchan, abook_feed, abook_their_perms, abook_my_perms, abook_created, abook_updated )\n\t\t\tvalues( %d, %d, %d, '%s', %d, %d, %d, '%s', '%s' ) ", intval($aid), intval($uid), intval($closeness), dbesc($xchan_hash), intval($is_http ? 1 : 0), intval($is_http ? $their_perms | PERMS_R_STREAM | PERMS_A_REPUBLISH : $their_perms), intval($my_perms), dbesc(datetime_convert()), dbesc(datetime_convert()));
    }
    if (!$r) {
        logger('mod_follow: abook creation failed');
    }
    $r = q("select abook.*, xchan.* from abook left join xchan on abook_xchan = xchan_hash \n\t\twhere abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($xchan_hash), intval($uid));
    if ($r) {
        $result['abook'] = $r[0];
        proc_run('php', 'include/notifier.php', 'permission_update', $result['abook']['abook_id']);
    }
    $arr = array('channel_id' => $uid, 'abook' => $result['abook']);
    call_hooks('follow', $arr);
    /** If there is a default group for this channel, add this member to it */
    if ($default_group) {
        require_once 'include/group.php';
        $g = group_rec_byhash($uid, $default_group);
        if ($g) {
            group_add_member($uid, '', $xchan_hash, $g['id']);
        }
    }
    $result['success'] = true;
    return $result;
}
Example #23
0
function advanced_profile(&$a)
{
    require_once 'include/text.php';
    if (!perm_is_allowed($a->profile['profile_uid'], get_observer_hash(), 'view_profile')) {
        return '';
    }
    $o = '';
    $o .= '<h2>' . t('Profile') . '</h2>';
    if ($a->profile['name']) {
        $tpl = get_markup_template('profile_advanced.tpl');
        $profile = array();
        $profile['fullname'] = array(t('Full Name:'), $a->profile['name']);
        if ($a->profile['gender']) {
            $profile['gender'] = array(t('Gender:'), $a->profile['gender']);
        }
        $ob_hash = get_observer_hash();
        if ($ob_hash && perm_is_allowed($a->profile['profile_uid'], $ob_hash, 'post_like')) {
            $profile['canlike'] = true;
            $profile['likethis'] = t('Like this channel');
            $profile['profile_guid'] = $a->profile['profile_guid'];
        }
        $likers = q("select liker, xchan.*  from likes left join xchan on liker = xchan_hash where channel_id = %d and target_type = '%s' and verb = '%s'", intval($a->profile['profile_uid']), dbesc(ACTIVITY_OBJ_PROFILE), dbesc(ACTIVITY_LIKE));
        $profile['likers'] = array();
        $profile['like_count'] = count($likers);
        $profile['like_button_label'] = tt('Like', 'Likes', $profile['like_count'], 'noun');
        if ($likers) {
            foreach ($likers as $l) {
                $profile['likers'][] = array('name' => $l['xchan_name'], 'url' => zid($l['xchan_url']));
            }
        }
        if ($a->profile['dob'] && $a->profile['dob'] != '0000-00-00') {
            $val = '';
            if (substr($a->profile['dob'], 5, 2) === '00' || substr($a->profile['dob'], 8, 2) === '00') {
                $val = substr($a->profile['dob'], 0, 4);
            }
            $year_bd_format = t('j F, Y');
            $short_bd_format = t('j F');
            if (!$val) {
                $val = intval($a->profile['dob']) ? day_translate(datetime_convert('UTC', 'UTC', $a->profile['dob'] . ' 00:00 +00:00', $year_bd_format)) : day_translate(datetime_convert('UTC', 'UTC', '2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format));
            }
            $profile['birthday'] = array(t('Birthday:'), $val);
        }
        if ($age = age($a->profile['dob'], $a->profile['timezone'], '')) {
            $profile['age'] = array(t('Age:'), $age);
        }
        if ($a->profile['marital']) {
            $profile['marital'] = array(t('Status:'), $a->profile['marital']);
        }
        if ($a->profile['with']) {
            $profile['marital']['with'] = bbcode($a->profile['with']);
        }
        if (strlen($a->profile['howlong']) && $a->profile['howlong'] !== NULL_DATE) {
            $profile['howlong'] = relative_date($a->profile['howlong'], t('for %1$d %2$s'));
        }
        if ($a->profile['sexual']) {
            $profile['sexual'] = array(t('Sexual Preference:'), $a->profile['sexual']);
        }
        if ($a->profile['homepage']) {
            $profile['homepage'] = array(t('Homepage:'), linkify($a->profile['homepage']));
        }
        if ($a->profile['hometown']) {
            $profile['hometown'] = array(t('Hometown:'), linkify($a->profile['hometown']));
        }
        if ($a->profile['keywords']) {
            $profile['keywords'] = array(t('Tags:'), $a->profile['keywords']);
        }
        if ($a->profile['politic']) {
            $profile['politic'] = array(t('Political Views:'), $a->profile['politic']);
        }
        if ($a->profile['religion']) {
            $profile['religion'] = array(t('Religion:'), $a->profile['religion']);
        }
        if ($txt = prepare_text($a->profile['about'])) {
            $profile['about'] = array(t('About:'), $txt);
        }
        if ($txt = prepare_text($a->profile['interest'])) {
            $profile['interest'] = array(t('Hobbies/Interests:'), $txt);
        }
        if ($txt = prepare_text($a->profile['likes'])) {
            $profile['likes'] = array(t('Likes:'), $txt);
        }
        if ($txt = prepare_text($a->profile['dislikes'])) {
            $profile['dislikes'] = array(t('Dislikes:'), $txt);
        }
        if ($txt = prepare_text($a->profile['contact'])) {
            $profile['contact'] = array(t('Contact information and Social Networks:'), $txt);
        }
        if ($txt = prepare_text($a->profile['channels'])) {
            $profile['channels'] = array(t('My other channels:'), $txt);
        }
        if ($txt = prepare_text($a->profile['music'])) {
            $profile['music'] = array(t('Musical interests:'), $txt);
        }
        if ($txt = prepare_text($a->profile['book'])) {
            $profile['book'] = array(t('Books, literature:'), $txt);
        }
        if ($txt = prepare_text($a->profile['tv'])) {
            $profile['tv'] = array(t('Television:'), $txt);
        }
        if ($txt = prepare_text($a->profile['film'])) {
            $profile['film'] = array(t('Film/dance/culture/entertainment:'), $txt);
        }
        if ($txt = prepare_text($a->profile['romance'])) {
            $profile['romance'] = array(t('Love/Romance:'), $txt);
        }
        if ($txt = prepare_text($a->profile['work'])) {
            $profile['work'] = array(t('Work/employment:'), $txt);
        }
        if ($txt = prepare_text($a->profile['education'])) {
            $profile['education'] = array(t('School/education:'), $txt);
        }
        if ($a->profile['extra_fields']) {
            foreach ($a->profile['extra_fields'] as $f) {
                $x = q("select * from profdef where field_name = '%s' limit 1", dbesc($f));
                if ($x && ($txt = prepare_text($a->profile[$f]))) {
                    $profile[$f] = array($x[0]['field_desc'] . ':', $txt);
                }
            }
            $profile['extra_fields'] = $a->profile['extra_fields'];
        }
        $things = get_things($a->profile['profile_guid'], $a->profile['profile_uid']);
        //		logger('mod_profile: things: ' . print_r($things,true), LOGGER_DATA);
        return replace_macros($tpl, array('$title' => t('Profile'), '$canlike' => $profile['canlike'] ? true : false, '$likethis' => t('Like this thing'), '$profile' => $profile, '$things' => $things));
    }
    return '';
}
Example #24
0
function get_things($profile_hash, $uid)
{
    $sql_extra = $profile_hash ? " and obj_page = '" . $profile_hash . "' " : '';
    $r = q("select * from obj where obj_channel = %d and obj_type = %d {$sql_extra} order by obj_verb, obj_term", intval($uid), intval(TERM_OBJ_THING));
    $things = $sorted_things = null;
    $profile_hashes = array();
    if ($r) {
        // if no profile_hash was specified (display on profile page mode), match each of the things to a profile name
        // (list all my things mode). This is harder than it sounds.
        foreach ($r as $rr) {
            $rr['profile_name'] = '';
            if (!in_array($rr['obj_obj'], $profile_hashes)) {
                $profile_hashes[] = $rr['obj_obj'];
            }
        }
        stringify_array_elms($profile_hashes);
        if (!$profile_hash) {
            $exp = explode(',', $profile_hashes);
            $p = q("select profile_guid as hash, profile_name as name from profile where profile_guid in ( {$exp} ) ");
            if ($p) {
                foreach ($r as $rr) {
                    foreach ($p as $pp) {
                        if ($rr['obj_page'] == $pp['hash']) {
                            $rr['profile_name'] == $pp['name'];
                        }
                    }
                }
            }
        }
        $things = array();
        // Use the system obj_verbs array as a sort key, since we don't really
        // want an alphabetic sort. To change the order, use a plugin to
        // alter the obj_verbs() array or alter it in code. Unknown verbs come
        // after the known ones - in no particular order.
        $v = obj_verbs();
        foreach ($v as $k => $foo) {
            $things[$k] = null;
        }
        foreach ($r as $rr) {
            $l = q("select xchan_name, xchan_url from likes left join xchan on likee = xchan_hash where\n\t\t\t\ttarget_type = '%s' and target_id = '%s' and channel_id = %d", dbesc(ACTIVITY_OBJ_THING), dbesc($rr['obj_obj']), intval($uid));
            for ($x = 0; $x < count($l); $x++) {
                $l[$x]['xchan_url'] = zid($l[$x]['xchan_url']);
            }
            if (!$things[$rr['obj_verb']]) {
                $things[$rr['obj_verb']] = array();
            }
            $things[$rr['obj_verb']][] = array('term' => $rr['obj_term'], 'url' => $rr['obj_url'], 'img' => $rr['obj_imgurl'], 'profile' => $rr['profile_name'], 'term_hash' => $rr['obj_obj'], 'likes' => $l, 'like_count' => count($l), 'like_label' => tt('Like', 'Likes', count($l), 'noun'));
        }
        $sorted_things = array();
        if ($things) {
            foreach ($things as $k => $v) {
                if (is_array($things[$k])) {
                    $sorted_things[$k] = $v;
                }
            }
        }
    }
    //logger('things: ' . print_r($sorted_things,true));
    return $sorted_things;
}
Example #25
0
/**
 * @function widget_photo($arr)
 *    widget to display a single photo.
 * @param array $arr;
 *    'src' => URL of photo
 *    'zrl' => true or false, use zid in url
 *    'style' => CSS string
 * URL must be an http or https URL
 */
function widget_photo($arr)
{
    $style = $zrl = false;
    $params = '';
    if (array_key_exists('src', $arr) && isset($arr['src'])) {
        $url = $arr['src'];
    }
    if (strpos($url, 'http') !== 0) {
        return '';
    }
    if (array_key_exists('style', $arr) && isset($arr['style'])) {
        $style = $arr['style'];
    }
    // ensure they can't sneak in an eval(js) function
    if (strpos($style, '(') !== false) {
        return '';
    }
    if (array_key_exists('zrl', $arr) && isset($arr['zrl'])) {
        $zrl = $arr['zrl'] ? true : false;
    }
    if ($zrl) {
        $url = zid($url);
    }
    $o = '<div class="widget">';
    $o .= '<img ' . ($zrl ? ' class="zrl" ' : '') . ($style ? ' style="' . $style . '"' : '') . ' src="' . $url . '" />';
    $o .= '</div>';
    return $o;
}
Example #26
0
function bb_ShareAttributes($match)
{
    $matches = array();
    $attributes = $match[1];
    $author = "";
    preg_match("/author='(.*?)'/ism", $attributes, $matches);
    if ($matches[1] != "") {
        $author = urldecode($matches[1]);
    }
    $link = "";
    preg_match("/link='(.*?)'/ism", $attributes, $matches);
    if ($matches[1] != "") {
        $link = $matches[1];
    }
    $avatar = "";
    preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
    if ($matches[1] != "") {
        $avatar = $matches[1];
    }
    $profile = "";
    preg_match("/profile='(.*?)'/ism", $attributes, $matches);
    if ($matches[1] != "") {
        $profile = $matches[1];
    }
    $posted = "";
    preg_match("/posted='(.*?)'/ism", $attributes, $matches);
    if ($matches[1] != "") {
        $posted = $matches[1];
    }
    // message_id is never used, do we still need it?
    $message_id = "";
    preg_match("/message_id='(.*?)'/ism", $attributes, $matches);
    if ($matches[1] != "") {
        $message_id = $matches[1];
    }
    $reldate = '<span class="autotime" title="' . datetime_convert('UTC', date_default_timezone_get(), $posted, 'c') . '" >' . datetime_convert('UTC', date_default_timezone_get(), $posted, 'r') . '</span>';
    $headline = '<div class="shared_container"> <div class="shared_header">';
    if ($avatar != "") {
        $headline .= '<a href="' . zid($profile) . '" ><img src="' . $avatar . '" alt="' . $author . '" height="32" width="32" /></a>';
    }
    // Bob Smith wrote the following post 2 hours ago
    $fmt = sprintf(t('%1$s wrote the following %2$s %3$s'), '<a href="' . zid($profile) . '" >' . $author . '</a>', '<a href="' . zid($link) . '" >' . t('post') . '</a>', $reldate);
    $headline .= '<span>' . $fmt . '</span></div>';
    $text = $headline . '<div class="reshared-content">' . trim($match[2]) . '</div></div>';
    return $text;
}