Example #1
0
/**
 * @brief Returns an array of contact-ids that are allowed to see this object.
 *
 * @param object $obj
 * @return array
 */
function enumerate_permissions($obj)
{
    require_once 'include/group.php';
    $allow_people = expand_acl($obj['allow_cid']);
    $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
    $deny_people = expand_acl($obj['deny_cid']);
    $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
    $recipients = array_unique(array_merge($allow_people, $allow_groups));
    $deny = array_unique(array_merge($deny_people, $deny_groups));
    $recipients = array_diff($recipients, $deny);
    return $recipients;
}
Example #2
0
function network_content(&$a, $update = 0)
{
    require_once 'include/conversation.php';
    if (!local_user()) {
        $_SESSION['return_url'] = $a->query_string;
        return login(false);
    }
    // TODO:is this really necessary? $a is already available to hooks
    $arr = array('query' => $a->query_string);
    call_hooks('network_content_init', $arr);
    $datequery = $datequery2 = '';
    $group = 0;
    $nouveau = false;
    if ($a->argc > 1) {
        for ($x = 1; $x < $a->argc; $x++) {
            if (is_a_date_arg($a->argv[$x])) {
                if ($datequery) {
                    $datequery2 = escape_tags($a->argv[$x]);
                } else {
                    $datequery = escape_tags($a->argv[$x]);
                    $_GET['order'] = 'post';
                }
            } elseif ($a->argv[$x] === 'new') {
                $nouveau = true;
            } elseif (intval($a->argv[$x])) {
                $group = intval($a->argv[$x]);
                $def_acl = array('allow_gid' => '<' . $group . '>');
            }
        }
    }
    $o = '';
    // item filter tabs
    // TODO: fix this logic, reduce duplication
    //$a->page['content'] .= '<div class="tabs-wrapper">';
    list($no_active, $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active, $spam_active) = network_query_get_sel_tab($a);
    // if no tabs are selected, defaults to comments
    if ($no_active == 'active') {
        $all_active = 'active';
    }
    $cmd = $datequery ? '' : $a->cmd;
    $len_naked_cmd = strlen(str_replace('/new', '', $cmd));
    // tabs
    $tabs = array(array('label' => t('Commented Order'), 'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $cmd) . '?f=&order=comment' . (x($_GET, 'cid') ? '&cid=' . $_GET['cid'] : ''), 'sel' => $all_active, 'title' => t('Sort by Comment Date')), array('label' => t('Posted Order'), 'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $cmd) . '?f=&order=post' . (x($_GET, 'cid') ? '&cid=' . $_GET['cid'] : ''), 'sel' => $postord_active, 'title' => t('Sort by Post Date')));
    if (feature_enabled(local_user(), 'personal_tab')) {
        $tabs[] = array('label' => t('Personal'), 'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $cmd) . (x($_GET, 'cid') ? '/?f=&cid=' . $_GET['cid'] : '/?f=') . '&conv=1', 'sel' => $conv_active, 'title' => t('Posts that mention or involve you'));
    }
    if (feature_enabled(local_user(), 'new_tab')) {
        $tabs[] = array('label' => t('New'), 'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $cmd) . ($len_naked_cmd ? '/' : '') . 'new' . (x($_GET, 'cid') ? '/?f=&cid=' . $_GET['cid'] : ''), 'sel' => $new_active, 'title' => t('Activity Stream - by date'));
    }
    if (feature_enabled(local_user(), 'link_tab')) {
        $tabs[] = array('label' => t('Shared Links'), 'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $cmd) . (x($_GET, 'cid') ? '/?f=&cid=' . $_GET['cid'] : '/?f=') . '&bmark=1', 'sel' => $bookmarked_active, 'title' => t('Interesting Links'));
    }
    if (feature_enabled(local_user(), 'star_posts')) {
        $tabs[] = array('label' => t('Starred'), 'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $cmd) . (x($_GET, 'cid') ? '/?f=&cid=' . $_GET['cid'] : '/?f=') . '&star=1', 'sel' => $starred_active, 'title' => t('Favourite Posts'));
    }
    // save selected tab, but only if not in search or file mode
    if (!x($_GET, 'search') && !x($_GET, 'file')) {
        set_pconfig(local_user(), 'network.view', 'tab.selected', array($all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active, $spam_active));
    }
    $arr = array('tabs' => $tabs);
    call_hooks('network_tabs', $arr);
    $o .= replace_macros(get_markup_template('common_tabs.tpl'), array('$tabs' => $arr['tabs']));
    // --- end item filter tabs
    $contact_id = $a->cid;
    require_once 'include/acl_selectors.php';
    $cid = x($_GET, 'cid') ? intval($_GET['cid']) : 0;
    $star = x($_GET, 'star') ? intval($_GET['star']) : 0;
    $bmark = x($_GET, 'bmark') ? intval($_GET['bmark']) : 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;
    $nets = x($_GET, 'nets') ? $_GET['nets'] : '';
    $cmin = x($_GET, 'cmin') ? intval($_GET['cmin']) : 0;
    $cmax = x($_GET, 'cmax') ? intval($_GET['cmax']) : 99;
    $file = x($_GET, 'file') ? $_GET['file'] : '';
    if (x($_GET, 'search') || x($_GET, 'file')) {
        $nouveau = true;
    }
    if ($cid) {
        $def_acl = array('allow_cid' => '<' . intval($cid) . '>');
    }
    if ($nets) {
        $r = q("select id from contact where uid = %d and network = '%s' and self = 0", intval(local_user()), dbesc($nets));
        $str = '';
        if (count($r)) {
            foreach ($r as $rr) {
                $str .= '<' . $rr['id'] . '>';
            }
        }
        if (strlen($str)) {
            $def_acl = array('allow_cid' => $str);
        }
    }
    set_pconfig(local_user(), 'network.view', 'net.selected', $nets ? $nets : 'all');
    if (!$update) {
        if ($group) {
            if (($t = group_public_members($group)) && !get_pconfig(local_user(), 'system', 'nowarn_insecure')) {
                notice(sprintf(tt('Warning: This group contains %s member from an insecure network.', 'Warning: This group contains %s members from an insecure network.', $t), $t) . EOL);
                notice(t('Private messages to this group are at risk of public disclosure.') . EOL);
            }
        }
        nav_set_selected('network');
        $content = "";
        if ($cid) {
            $contact = q("SELECT `nick` FROM `contact` WHERE `id` = %d AND `uid` = %d AND `forum`", intval($cid), intval(local_user()));
            if ($contact) {
                $content = "@" . $contact[0]["nick"] . "+" . $cid;
            }
        }
        $x = array('is_owner' => true, 'allow_location' => $a->user['allow_location'], 'default_location' => $a->user['default-location'], 'nickname' => $a->user['nickname'], 'lockstate' => $group || $cid || $nets || is_array($a->user) && (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) || strlen($a->user['deny_cid']) || strlen($a->user['deny_gid'])) ? 'lock' : 'unlock', 'default_perms' => get_acl_permissions($a->user), 'acl' => populate_acl($group || $cid || $nets ? $def_acl : $a->user, true), 'bang' => $group || $cid || $nets ? '!' : '', 'visitor' => 'block', 'profile_uid' => local_user(), 'acl_data' => construct_acl_data($a, $a->user), 'content' => $content);
        $o .= status_editor($a, $x);
    }
    // We don't have to deal with ACLs 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_post_table = "";
    $sql_options = $star ? " and starred = 1 " : '';
    $sql_options .= $bmark ? " and bookmark = 1 " : '';
    $sql_extra = $sql_options;
    $sql_extra2 = "";
    $sql_extra3 = "";
    $sql_table = "`thread`";
    $sql_parent = "`iid`";
    if ($nouveau or strlen($file) or $update) {
        $sql_table = "`item`";
        $sql_parent = "`parent`";
    }
    $sql_nets = $nets ? sprintf(" and {$sql_table}.`network` = '%s' ", dbesc($nets)) : '';
    if ($group) {
        $r = q("SELECT `name`, `id` FROM `group` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($group), intval($_SESSION['uid']));
        if (!count($r)) {
            if ($update) {
                killme();
            }
            notice(t('No such group') . EOL);
            goaway($a->get_baseurl(true) . '/network/0');
            // NOTREACHED
        }
        $contacts = expand_groups(array($group));
        $contact_str_self = "";
        if (is_array($contacts) && count($contacts)) {
            $contact_str = implode(',', $contacts);
            $self = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($_SESSION['uid']));
            if (count($self)) {
                $contact_str_self = "," . $self[0]["id"];
            }
        } else {
            $contact_str = ' 0 ';
            info(t('Group is empty'));
        }
        //$sql_post_table = " INNER JOIN (SELECT DISTINCT(`parent`) FROM `item` WHERE (`contact-id` IN ($contact_str) OR `allow_gid` like '".protect_sprintf('%<'.intval($group).'>%')."') and deleted = 0 ORDER BY `created` DESC) AS `temp1` ON $sql_table.$sql_parent = `temp1`.`parent` ";
        $sql_extra3 .= " AND `contact-id` IN ({$contact_str}{$contact_str_self}) ";
        $sql_extra3 .= " AND EXISTS (SELECT id FROM `item` WHERE (`contact-id` IN ({$contact_str}) \n\t\t\t\tOR `allow_gid` like '" . protect_sprintf('%<' . intval($group) . '>%') . "') and deleted = 0 \n\t\t\t\tAND parent = {$sql_table}.{$sql_parent}) ";
        $o = replace_macros(get_markup_template("section_title.tpl"), array('$title' => sprintf(t('Group: %s'), $r[0]['name']))) . $o;
    } elseif ($cid) {
        $r = q("SELECT `id`,`name`,`network`,`writable`,`nurl` FROM `contact` WHERE `id` = %d\n\t\t\t\tAND `blocked` = 0 AND `pending` = 0 LIMIT 1", intval($cid));
        if (count($r)) {
            $sql_post_table = " INNER JOIN (SELECT DISTINCT(`parent`) FROM `item` \n\t\t\t\t\t    WHERE 1 {$sql_options} AND `contact-id` = " . intval($cid) . " and deleted = 0 \n\t\t\t\t\t    ORDER BY `item`.`received` DESC) AS `temp1` \n\t\t\t\t\t    ON {$sql_table}.{$sql_parent} = `temp1`.`parent` ";
            $sql_extra = "";
            $o = replace_macros(get_markup_template("section_title.tpl"), array('$title' => sprintf(t('Contact: %s'), $r[0]['name']))) . $o;
            if ($r[0]['network'] === NETWORK_OSTATUS && $r[0]['writable'] && !get_pconfig(local_user(), 'system', 'nowarn_insecure')) {
                notice(t('Private messages to this person are at risk of public disclosure.') . EOL);
            }
        } else {
            notice(t('Invalid contact.') . EOL);
            goaway($a->get_baseurl(true) . '/network');
            // NOTREACHED
        }
    }
    if (!$group && !$cid && !$update && !get_config('theme', 'hide_eventlist')) {
        $o .= get_birthdays();
        $o .= get_events();
    }
    if ($datequery) {
        $sql_extra3 .= protect_sprintf(sprintf(" AND {$sql_table}.created <= '%s' ", dbesc(datetime_convert(date_default_timezone_get(), '', $datequery))));
    }
    if ($datequery2) {
        $sql_extra3 .= protect_sprintf(sprintf(" AND {$sql_table}.created >= '%s' ", dbesc(datetime_convert(date_default_timezone_get(), '', $datequery2))));
    }
    //$sql_extra2 = (($nouveau) ? '' : " AND `item`.`parent` = `item`.`id` ");
    $sql_extra2 = $nouveau ? '' : $sql_extra2;
    $sql_extra3 = $nouveau ? '' : $sql_extra3;
    $sql_order = "";
    $order_mode = "received";
    $tag = false;
    if (x($_GET, 'search')) {
        $search = escape_tags($_GET['search']);
        if (strpos($search, '#') === 0) {
            $tag = true;
            $search = substr($search, 1);
        }
        if (get_config('system', 'only_tag_search')) {
            $tag = true;
        }
        if ($tag) {
            $sql_extra = "";
            $sql_post_table = sprintf("INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ", dbesc(protect_sprintf($search)), intval(TERM_OBJ_POST), intval(TERM_HASHTAG), intval(local_user()));
            $sql_order = "`item`.`id`";
            $order_mode = "id";
        } else {
            if (get_config('system', 'use_fulltext_engine')) {
                $sql_extra = sprintf(" AND MATCH (`item`.`body`, `item`.`title`) AGAINST ('%s' in boolean mode) ", dbesc(protect_sprintf($search)));
            } else {
                $sql_extra = sprintf(" AND `item`.`body` REGEXP '%s' ", dbesc(protect_sprintf(preg_quote($search))));
            }
            $sql_order = "`item`.`received`";
            $order_mode = "received";
        }
    }
    if (strlen($file)) {
        $sql_post_table = sprintf("INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ", dbesc(protect_sprintf($file)), intval(TERM_OBJ_POST), intval(TERM_FILE), intval(local_user()));
        $sql_order = "`item`.`id`";
        $order_mode = "id";
    }
    if ($conv) {
        $sql_extra3 .= " AND `mention`";
    }
    if ($update) {
        // only setup pagination on initial page view
        $pager_sql = '';
    } else {
        if (get_config('system', 'old_pager')) {
            $r = q("SELECT COUNT(*) AS `total`\n\t\t\t        FROM {$sql_table} {$sql_post_table} INNER JOIN `contact` ON `contact`.`id` = {$sql_table}.`contact-id`\n\t\t\t        AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t        WHERE {$sql_table}.`uid` = %d AND {$sql_table}.`visible` = 1 AND {$sql_table}.`deleted` = 0\n\t\t\t        {$sql_extra2} {$sql_extra3}\n\t\t\t        {$sql_extra} {$sql_nets} ", intval($_SESSION['uid']));
            if (count($r)) {
                $a->set_pager_total($r[0]['total']);
            }
        }
        //  check if we serve a mobile device and get the user settings
        //  accordingly
        if ($a->is_mobile) {
            $itemspage_network = get_pconfig(local_user(), 'system', 'itemspage_mobile_network');
            $itemspage_network = intval($itemspage_network) ? $itemspage_network : 20;
        } else {
            $itemspage_network = get_pconfig(local_user(), 'system', 'itemspage_network');
            $itemspage_network = intval($itemspage_network) ? $itemspage_network : 40;
        }
        //  now that we have the user settings, see if the theme forces
        //  a maximum item number which is lower then the user choice
        if ($a->force_max_items > 0 && $a->force_max_items < $itemspage_network) {
            $itemspage_network = $a->force_max_items;
        }
        $a->set_pager_itemspage($itemspage_network);
        $pager_sql = sprintf(" LIMIT %d, %d ", intval($a->pager['start']), intval($a->pager['itemspage']));
    }
    if ($nouveau) {
        $simple_update = $update ? " and `item`.`unseen` = 1 " : '';
        if ($sql_order == "") {
            $sql_order = "`item`.`received`";
        }
        // "New Item View" - show all items unthreaded in reverse created date order
        $items = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,\n\t\t\t`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`, `contact`.`writable`,\n\t\t\t`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,\n\t\t\t`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`\n\t\t\tFROM {$sql_table} {$sql_post_table} INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1\n\t\t\tAND `item`.`deleted` = 0 and `item`.`moderated` = 0\n\t\t\t{$simple_update}\n\t\t\t{$sql_extra} {$sql_nets}\n\t\t\tORDER BY {$sql_order} DESC {$pager_sql} ", intval($_SESSION['uid']));
        $update_unseen = ' WHERE uid = ' . intval($_SESSION['uid']) . " AND unseen = 1 {$sql_extra} {$sql_nets}";
    } else {
        // Normal conversation view
        if ($order === 'post') {
            $ordering = "`created`";
            if ($sql_order == "") {
                $order_mode = "created";
            }
        } else {
            $ordering = "`commented`";
            if ($sql_order == "") {
                $order_mode = "commented";
            }
        }
        if ($sql_order == "") {
            $sql_order = "{$sql_table}.{$ordering}";
        }
        if ($_GET["offset"] != "") {
            $sql_extra3 .= sprintf(" AND {$sql_order} <= '%s'", dbesc($_GET["offset"]));
        }
        // Fetch a page full of parent items for this page
        if ($update) {
            if (!get_config("system", "like_no_comment")) {
                $sql_extra4 = "(`item`.`deleted` = 0 OR `item`.`verb` = '" . ACTIVITY_LIKE . "' OR `item`.`verb` = '" . ACTIVITY_DISLIKE . "')";
            } else {
                $sql_extra4 = "`item`.`deleted` = 0 AND `item`.`verb` = '" . ACTIVITY_POST . "'";
            }
            $r = q("SELECT `item`.`parent` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`uid` AS `contact_uid`\n\t\t\t\tFROM {$sql_table} {$sql_post_table} INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND {$sql_extra4}\n\t\t\t\tAND `item`.`moderated` = 0 AND `item`.`unseen` = 1\n\t\t\t\t{$sql_extra3} {$sql_extra} {$sql_nets} ORDER BY `item_id` DESC LIMIT 100", intval(local_user()));
        } else {
            $r = q("SELECT `thread`.`iid` AS `item_id`, `thread`.`network` AS `item_network`, `contact`.`uid` AS `contact_uid`\n\t\t\t\tFROM {$sql_table} {$sql_post_table} STRAIGHT_JOIN `contact` ON `contact`.`id` = `thread`.`contact-id`\n\t\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\tWHERE `thread`.`uid` = %d AND `thread`.`visible` = 1 AND `thread`.`deleted` = 0\n\t\t\t\tAND `thread`.`moderated` = 0\n\t\t\t\t{$sql_extra2} {$sql_extra3} {$sql_extra} {$sql_nets}\n\t\t\t\tORDER BY {$sql_order} DESC {$pager_sql} ", intval(local_user()));
        }
        // Then fetch all the children of the parents that are on this page
        $parents_arr = array();
        $parents_str = '';
        $date_offset = "";
        if (count($r)) {
            foreach ($r as $rr) {
                if (!in_array($rr['item_id'], $parents_arr)) {
                    $parents_arr[] = $rr['item_id'];
                }
            }
            $parents_str = implode(", ", $parents_arr);
            // splitted into separate queries to avoid the problem with very long threads
            // so always the last X comments are loaded
            // This problem can occur expecially with imported facebook posts
            $max_comments = get_config("system", "max_comments");
            if ($max_comments == 0) {
                $max_comments = 100;
            }
            $items = array();
            foreach ($parents_arr as $parents) {
                //					$sql_extra ORDER BY `item`.`commented` DESC LIMIT %d",
                $thread_items = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,\n\t\t\t\t\t`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`alias`, `contact`.`rel`, `contact`.`writable`,\n\t\t\t\t\t`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,\n\t\t\t\t\t`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`\n\t\t\t\t\tFROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\t\t\t\tAND `item`.`moderated` = 0\n\t\t\t\t\tAND `item`.`parent` = %d\n\t\t\t\t\tORDER BY `item`.`commented` DESC LIMIT %d", intval(local_user()), intval($parents), intval($max_comments + 1));
                $items = array_merge($items, $thread_items);
            }
            $items = conv_sort($items, $ordering);
        } else {
            $items = array();
        }
        if ($_GET["offset"] == "") {
            $date_offset = $items[0][$order_mode];
        } else {
            $date_offset = $_GET["offset"];
        }
        $a->page_offset = $date_offset;
        if ($parents_str) {
            $update_unseen = ' WHERE uid = ' . intval(local_user()) . ' AND unseen = 1 AND parent IN ( ' . dbesc($parents_str) . ' )';
        }
    }
    // We aren't going to try and figure out at the item, group, and page
    // level which items you've seen and which you haven't. If you're looking
    // at the top level network page just mark everything seen.
    // The $update_unseen is a bit unreliable if you have stuff coming into your stream from a new contact -
    // and other feeds that bring in stuff from the past. One can't find it all.
    // I'm reviving this block to mark everything seen on page 1 of the network as a temporary measure.
    // The correct solution is to implement a network notifications box just like the system notifications popup
    // with the ability in the popup to "mark all seen".
    // Several people are complaining because there are unseen messages they can't find and as time goes
    // on they just get buried deeper. It has happened to me a couple of times also.
    if (!$group && !$cid && !$star) {
        $r = q("UPDATE `item` SET `unseen` = 0\n\t\t\tWHERE `unseen` = 1 AND `uid` = %d", intval(local_user()));
    } else {
        if ($update_unseen) {
            $r = q("UPDATE `item` SET `unseen` = 0 {$update_unseen}");
        }
    }
    // Set this so that the conversation function can find out contact info for our wall-wall items
    $a->page_contact = $a->contact;
    $mode = $nouveau ? 'network-new' : 'network';
    $o .= conversation($a, $items, $mode, $update);
    if (!$update) {
        if (get_pconfig(local_user(), 'system', 'infinite_scroll')) {
            $o .= scroll_loader();
        } elseif (!get_config('system', 'old_pager')) {
            $o .= alt_pager($a, count($items));
        } else {
            $o .= paginate($a);
        }
    }
    return $o;
}
Example #3
0
function notifier_run($argv, $argc)
{
    global $a, $db;
    if (is_null($a)) {
        $a = new App();
    }
    if (is_null($db)) {
        @(include ".htconfig.php");
        require_once "dba.php";
        $db = new dba($db_host, $db_user, $db_pass, $db_data);
        unset($db_host, $db_user, $db_pass, $db_data);
    }
    require_once "session.php";
    require_once "datetime.php";
    require_once 'include/items.php';
    require_once 'include/bbcode.php';
    load_config('config');
    load_config('system');
    load_hooks();
    if ($argc < 3) {
        return;
    }
    $a->set_baseurl(get_config('system', 'url'));
    logger('notifier: invoked: ' . print_r($argv, true));
    $cmd = $argv[1];
    switch ($cmd) {
        case 'mail':
        default:
            $item_id = intval($argv[2]);
            if (!$item_id) {
                return;
            }
            break;
    }
    $expire = false;
    $mail = false;
    $fsuggest = false;
    $top_level = false;
    $recipients = array();
    $url_recipients = array();
    $normal_mode = true;
    if ($cmd === 'mail') {
        $normal_mode = false;
        $mail = true;
        $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1", intval($item_id));
        if (!count($message)) {
            return;
        }
        $uid = $message[0]['uid'];
        $recipients[] = $message[0]['contact-id'];
        $item = $message[0];
    } elseif ($cmd === 'expire') {
        $normal_mode = false;
        $expire = true;
        $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1 \n\t\t\tAND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE", intval($item_id));
        $uid = $item_id;
        $item_id = 0;
        if (!count($items)) {
            return;
        }
    } elseif ($cmd === 'suggest') {
        $normal_mode = false;
        $fsuggest = true;
        $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item_id));
        if (!count($suggest)) {
            return;
        }
        $uid = $suggest[0]['uid'];
        $recipients[] = $suggest[0]['cid'];
        $item = $suggest[0];
    } else {
        // find ancestors
        $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($item_id));
        if (!count($r) || !intval($r[0]['parent'])) {
            return;
        }
        $target_item = $r[0];
        $parent_id = intval($r[0]['parent']);
        $uid = $r[0]['uid'];
        $updated = $r[0]['edited'];
        if (!$parent_id) {
            return;
        }
        $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer` \n\t\t\tFROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d ORDER BY `id` ASC", intval($parent_id));
        if (!count($items)) {
            return;
        }
        // avoid race condition with deleting entries
        if ($items[0]['deleted']) {
            foreach ($items as $item) {
                $item['deleted'] = 1;
            }
        }
        if (count($items) == 1 && $items[0]['id'] === $target_item['id'] && $items[0]['uri'] === $items[0]['parent-uri']) {
            logger('notifier: top level post');
            $top_level = true;
        }
    }
    $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`, \n\t\t`user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`, \n\t\t`user`.`page-flags`, `user`.`prvnets`\n\t\tFROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` \n\t\tWHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1", intval($uid));
    if (!count($r)) {
        return;
    }
    $owner = $r[0];
    $walltowall = $top_level && $owner['id'] != $items[0]['contact-id'] ? true : false;
    $hub = get_config('system', 'huburl');
    // If this is a public conversation, notify the feed hub
    $public_message = true;
    // fill this in with a single salmon slap if applicable
    $slap = '';
    if (!($mail || $fsuggest)) {
        require_once 'include/group.php';
        $parent = $items[0];
        // This is IMPORTANT!!!!
        // We will only send a "notify owner to relay" or followup message if the referenced post
        // originated on our system by virtue of having our hostname somewhere
        // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
        // if $parent['wall'] == 1 we will already have the parent message in our array
        // and we will relay the whole lot.
        // expire sends an entire group of expire messages and cannot be forwarded.
        // However the conversation owner will be a part of the conversation and will
        // be notified during this run.
        // Other DFRN conversation members will be alerted during polled updates.
        // Diaspora members currently are not notified of expirations, and other networks have
        // either limited or no ability to process deletions. We should at least fix Diaspora
        // by stringing togther an array of retractions and sending them onward.
        $localhost = $a->get_hostname();
        if (strpos($localhost, ':')) {
            $localhost = substr($localhost, 0, strpos($localhost, ':'));
        }
        /**
         *
         * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes 
         * have been known to cause runaway conditions which affected several servers, along with 
         * permissions issues. 
         *
         */
        $relay_to_owner = false;
        if (!$top_level && $parent['wall'] == 0 && !$expire && stristr($target_item['uri'], $localhost)) {
            $relay_to_owner = true;
        }
        if ($cmd === 'uplink' && intval($parent['forum_mode']) && !$top_level) {
            $relay_to_owner = true;
        }
        // until the 'origin' flag has been in use for several months
        // we will just use it as a fallback test
        // later we will be able to use it as the primary test of whether or not to relay.
        if (!$target_item['origin']) {
            $relay_to_owner = false;
        }
        if ($parent['origin']) {
            $relay_to_owner = false;
        }
        if ($relay_to_owner) {
            logger('notifier: followup', LOGGER_DEBUG);
            // local followup to remote post
            $followup = true;
            $public_message = false;
            // not public
            $conversant_str = dbesc($parent['contact-id']);
        } else {
            $followup = false;
            // don't send deletions onward for other people's stuff
            if ($target_item['deleted'] && !intval($target_item['wall'])) {
                logger('notifier: ignoring delete notification for non-wall item');
                return;
            }
            if (strlen($parent['allow_cid']) || strlen($parent['allow_gid']) || strlen($parent['deny_cid']) || strlen($parent['deny_gid'])) {
                $public_message = false;
                // private recipients, not public
            }
            $allow_people = expand_acl($parent['allow_cid']);
            $allow_groups = expand_groups(expand_acl($parent['allow_gid']));
            $deny_people = expand_acl($parent['deny_cid']);
            $deny_groups = expand_groups(expand_acl($parent['deny_gid']));
            // if our parent is a forum, uplink to the origonal author causing
            // a delivery fork
            if (intval($parent['forum_mode']) && !$top_level && $cmd !== 'uplink') {
                proc_run('php', 'include/notifier', 'uplink', $item_id);
            }
            $conversants = array();
            foreach ($items as $item) {
                $recipients[] = $item['contact-id'];
                $conversants[] = $item['contact-id'];
                // pull out additional tagged people to notify (if public message)
                if ($public_message && strlen($item['inform'])) {
                    $people = explode(',', $item['inform']);
                    foreach ($people as $person) {
                        if (substr($person, 0, 4) === 'cid:') {
                            $recipients[] = intval(substr($person, 4));
                            $conversants[] = intval(substr($person, 4));
                        } else {
                            $url_recipients[] = substr($person, 4);
                        }
                    }
                }
            }
            logger('notifier: url_recipients' . print_r($url_recipients, true));
            $conversants = array_unique($conversants);
            $recipients = array_unique(array_merge($recipients, $allow_people, $allow_groups));
            $deny = array_unique(array_merge($deny_people, $deny_groups));
            $recipients = array_diff($recipients, $deny);
            $conversant_str = dbesc(implode(', ', $conversants));
        }
        $r = q("SELECT * FROM `contact` WHERE `id` IN ( {$conversant_str} ) AND `blocked` = 0 AND `pending` = 0");
        if (count($r)) {
            $contacts = $r;
        }
    }
    $feed_template = get_markup_template('atom_feed.tpl');
    $mail_template = get_markup_template('atom_mail.tpl');
    $atom = '';
    $slaps = array();
    $hubxml = feed_hublinks();
    $birthday = feed_birthday($owner['uid'], $owner['timezone']);
    if (strlen($birthday)) {
        $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
    }
    $atom .= replace_macros($feed_template, array('$version' => xmlify(FRIENDICA_VERSION), '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname']), '$feed_title' => xmlify($owner['name']), '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00', ATOM_TIME)), '$hub' => $hubxml, '$salmon' => '', '$name' => xmlify($owner['name']), '$profile_page' => xmlify($owner['url']), '$photo' => xmlify($owner['photo']), '$thumb' => xmlify($owner['thumb']), '$picdate' => xmlify(datetime_convert('UTC', 'UTC', $owner['avatar-date'] . '+00:00', ATOM_TIME)), '$uridate' => xmlify(datetime_convert('UTC', 'UTC', $owner['uri-date'] . '+00:00', ATOM_TIME)), '$namdate' => xmlify(datetime_convert('UTC', 'UTC', $owner['name-date'] . '+00:00', ATOM_TIME)), '$birthday' => $birthday));
    if ($mail) {
        $public_message = false;
        // mail is  not public
        $body = fix_private_photos($item['body'], $owner['uid']);
        $atom .= replace_macros($mail_template, array('$name' => xmlify($owner['name']), '$profile_page' => xmlify($owner['url']), '$thumb' => xmlify($owner['thumb']), '$item_id' => xmlify($item['uri']), '$subject' => xmlify($item['title']), '$created' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00', ATOM_TIME)), '$content' => xmlify($body), '$parent_id' => xmlify($item['parent-uri'])));
    } elseif ($fsuggest) {
        $public_message = false;
        // suggestions are not public
        $sugg_template = get_markup_template('atom_suggest.tpl');
        $atom .= replace_macros($sugg_template, array('$name' => xmlify($item['name']), '$url' => xmlify($item['url']), '$photo' => xmlify($item['photo']), '$request' => xmlify($item['request']), '$note' => xmlify($item['note'])));
        // We don't need this any more
        q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
    } else {
        if ($followup) {
            foreach ($items as $item) {
                // there is only one item
                if (!$item['parent']) {
                    continue;
                }
                if ($item['id'] == $item_id) {
                    logger('notifier: followup: item: ' . print_r($item, true), LOGGER_DATA);
                    $slap = atom_entry($item, 'html', $owner, $owner, false);
                    $atom .= atom_entry($item, 'text', $owner, $owner, false);
                }
            }
        } else {
            foreach ($items as $item) {
                if (!$item['parent']) {
                    continue;
                }
                // private emails may be in included in public conversations. Filter them.
                if ($public_message && $item['private']) {
                    continue;
                }
                $contact = get_item_contact($item, $contacts);
                if (!$contact) {
                    continue;
                }
                if ($normal_mode) {
                    // we only need the current item, but include the parent because without it
                    // older sites without a corresponding dfrn_notify change may do the wrong thing.
                    if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
                        $atom .= atom_entry($item, 'text', $contact, $owner, true);
                    }
                } else {
                    $atom .= atom_entry($item, 'text', $contact, $owner, true);
                }
                if ($top_level && $public_message && $item['author-link'] === $item['owner-link'] && !$expire) {
                    $slaps[] = atom_entry($item, 'html', $contact, $owner, true);
                }
            }
        }
    }
    $atom .= '</feed>' . "\r\n";
    logger('notifier: ' . $atom, LOGGER_DATA);
    logger('notifier: slaps: ' . print_r($slaps, true), LOGGER_DATA);
    // If this is a public message and pubmail is set on the parent, include all your email contacts
    $mail_disabled = function_exists('imap_open') && !get_config('system', 'imap_disabled') ? 0 : 1;
    if (!$mail_disabled) {
        if (!strlen($target_item['allow_cid']) && !strlen($target_item['allow_gid']) && !strlen($target_item['deny_cid']) && !strlen($target_item['deny_gid']) && intval($target_item['pubmail'])) {
            $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `network` = '%s'", intval($uid), dbesc(NETWORK_MAIL));
            if (count($r)) {
                foreach ($r as $rr) {
                    $recipients[] = $rr['id'];
                }
            }
        }
    }
    if ($followup) {
        $recip_str = $parent['contact-id'];
    } else {
        $recip_str = implode(', ', $recipients);
    }
    $r = q("SELECT * FROM `contact` WHERE `id` IN ( %s ) AND `blocked` = 0 AND `pending` = 0 ", dbesc($recip_str));
    require_once 'include/salmon.php';
    $interval = get_config('system', 'delivery_interval') === false ? 2 : intval(get_config('system', 'delivery_interval'));
    // delivery loop
    if (count($r)) {
        foreach ($r as $contact) {
            if (!$mail && !$fsuggest && !$followup && !$contact['self']) {
                if ($contact['network'] === NETWORK_DIASPORA && $public_message) {
                    continue;
                }
                q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )", dbesc($cmd), intval($item_id), intval($contact['id']));
            }
        }
        foreach ($r as $contact) {
            if ($contact['self']) {
                continue;
            }
            // potentially more than one recipient. Start a new process and space them out a bit.
            // we will deliver single recipient types of message and email receipients here.
            if (!$mail && !$fsuggest && !$followup) {
                proc_run('php', 'include/delivery.php', $cmd, $item_id, $contact['id']);
                if ($interval) {
                    @time_sleep_until(microtime(true) + (double) $interval);
                }
                continue;
            }
            $deliver_status = 0;
            logger("main delivery by notifier: followup={$followup} mail={$mail} fsuggest={$fsuggest}");
            switch ($contact['network']) {
                case NETWORK_DFRN:
                    // perform local delivery if we are on the same site
                    $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
                    if (link_compare($basepath, $a->get_baseurl())) {
                        $nickname = basename($contact['url']);
                        if ($contact['issued-id']) {
                            $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
                        } else {
                            $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
                        }
                        $x = q("SELECT\t`contact`.*, `contact`.`uid` AS `importer_uid`, \n\t\t\t\t\t\t\t`contact`.`pubkey` AS `cpubkey`, \n\t\t\t\t\t\t\t`contact`.`prvkey` AS `cprvkey`, \n\t\t\t\t\t\t\t`contact`.`thumb` AS `thumb`, \n\t\t\t\t\t\t\t`contact`.`url` as `url`,\n\t\t\t\t\t\t\t`contact`.`name` as `senderName`,\n\t\t\t\t\t\t\t`user`.* \n\t\t\t\t\t\t\tFROM `contact` \n\t\t\t\t\t\t\tLEFT JOIN `user` ON `contact`.`uid` = `user`.`uid` \n\t\t\t\t\t\t\tWHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\t\t\t\tAND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'\n\t\t\t\t\t\t\t{$sql_extra}\n\t\t\t\t\t\t\tAND `user`.`account_expired` = 0 LIMIT 1", dbesc(NETWORK_DFRN), dbesc($nickname));
                        if (count($x)) {
                            require_once 'library/simplepie/simplepie.inc';
                            logger('mod-delivery: local delivery');
                            local_delivery($x[0], $atom);
                            break;
                        }
                    }
                    logger('notifier: dfrndelivery: ' . $contact['name']);
                    $deliver_status = dfrn_deliver($owner, $contact, $atom);
                    logger('notifier: dfrn_delivery returns ' . $deliver_status);
                    if ($deliver_status == -1) {
                        logger('notifier: delivery failed: queuing message');
                        // queue message for redelivery
                        add_to_queue($contact['id'], NETWORK_DFRN, $atom);
                    }
                    break;
                case NETWORK_OSTATUS:
                    // Do not send to otatus if we are not configured to send to public networks
                    if ($owner['prvnets']) {
                        break;
                    }
                    if (get_config('system', 'ostatus_disabled') || get_config('system', 'dfrn_only')) {
                        break;
                    }
                    if ($followup && $contact['notify']) {
                        logger('notifier: slapdelivery: ' . $contact['name']);
                        $deliver_status = slapper($owner, $contact['notify'], $slap);
                        if ($deliver_status == -1) {
                            // queue message for redelivery
                            add_to_queue($contact['id'], NETWORK_OSTATUS, $slap);
                        }
                    } else {
                        // only send salmon if public - e.g. if it's ok to notify
                        // a public hub, it's ok to send a salmon
                        if (count($slaps) && $public_message && !$expire) {
                            logger('notifier: slapdelivery: ' . $contact['name']);
                            foreach ($slaps as $slappy) {
                                if ($contact['notify']) {
                                    $deliver_status = slapper($owner, $contact['notify'], $slappy);
                                    if ($deliver_status == -1) {
                                        // queue message for redelivery
                                        add_to_queue($contact['id'], NETWORK_OSTATUS, $slappy);
                                    }
                                }
                            }
                        }
                    }
                    break;
                case NETWORK_MAIL:
                    if (get_config('system', 'dfrn_only')) {
                        break;
                    }
                    // WARNING: does not currently convert to RFC2047 header encodings, etc.
                    $addr = $contact['addr'];
                    if (!strlen($addr)) {
                        break;
                    }
                    if ($cmd === 'wall-new' || $cmd === 'comment-new') {
                        $it = null;
                        if ($cmd === 'wall-new') {
                            $it = $items[0];
                        } else {
                            $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($argv[2]), intval($uid));
                            if (count($r)) {
                                $it = $r[0];
                            }
                        }
                        if (!$it) {
                            break;
                        }
                        $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
                        if (!count($local_user)) {
                            break;
                        }
                        $reply_to = '';
                        $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1", intval($uid));
                        if ($r1 && $r1[0]['reply_to']) {
                            $reply_to = $r1[0]['reply_to'];
                        }
                        $subject = $it['title'] ? $it['title'] : t("(no subject)");
                        $headers = 'From: ' . $local_user[0]['username'] . ' <' . $local_user[0]['email'] . '>' . "\n";
                        if ($reply_to) {
                            $headers .= 'Reply-to: ' . $reply_to . "\n";
                        }
                        $headers .= 'Message-id: <' . $it['uri'] . '>' . "\n";
                        if ($it['uri'] !== $it['parent-uri']) {
                            $header .= 'References: <' . $it['parent-uri'] . '>' . "\n";
                            if (!strlen($it['title'])) {
                                $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' LIMIT 1", dbesc($it['parent-uri']));
                                if (count($r)) {
                                    $subtitle = $r[0]['title'];
                                    if ($subtitle) {
                                        if (strncasecmp($subtitle, 'RE:', 3)) {
                                            $subject = $subtitle;
                                        } else {
                                            $subject = 'Re: ' . $subtitle;
                                        }
                                    }
                                }
                            }
                        }
                        $headers .= 'MIME-Version: 1.0' . "\n";
                        $headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
                        $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
                        $html = prepare_body($it);
                        $message = '<html><body>' . $html . '</body></html>';
                        logger('notifier: email delivery to ' . $addr);
                        mail($addr, $subject, $message, $headers);
                    }
                    break;
                case NETWORK_DIASPORA:
                    require_once 'include/diaspora.php';
                    if (get_config('system', 'dfrn_only') || !get_config('system', 'diaspora_enabled')) {
                        break;
                    }
                    if ($mail) {
                        diaspora_send_mail($item, $owner, $contact);
                        break;
                    }
                    if (!$normal_mode) {
                        break;
                    }
                    // special handling for followup to public post
                    // all other public posts processed as public batches further below
                    if ($public_message) {
                        if ($followup) {
                            diaspora_send_followup($target_item, $owner, $contact, true);
                        }
                        break;
                    }
                    if (!$contact['pubkey']) {
                        break;
                    }
                    if ($target_item['verb'] === ACTIVITY_DISLIKE) {
                        // unsupported
                        break;
                    } elseif ($target_item['deleted'] && $target_item['verb'] !== ACTIVITY_LIKE) {
                        // diaspora delete,
                        diaspora_send_retraction($target_item, $owner, $contact);
                        break;
                    } elseif ($followup) {
                        // send comments, likes and retractions of likes to owner to relay
                        diaspora_send_followup($target_item, $owner, $contact);
                        break;
                    } elseif ($target_item['parent'] != $target_item['id']) {
                        // we are the relay - send comments, likes and unlikes to our conversants
                        diaspora_send_relay($target_item, $owner, $contact);
                        break;
                    } elseif ($top_level && !$walltowall) {
                        // currently no workable solution for sending walltowall
                        diaspora_send_status($target_item, $owner, $contact);
                        break;
                    }
                    break;
                case NETWORK_FEED:
                case NETWORK_FACEBOOK:
                    if (get_config('system', 'dfrn_only')) {
                        break;
                    }
                default:
                    break;
            }
        }
    }
    // send additional slaps to mentioned remote tags (@foo@example.com)
    if ($slap && count($url_recipients) && ($followup || $top_level) && $public_message && !$expire) {
        if (!get_config('system', 'dfrn_only')) {
            foreach ($url_recipients as $url) {
                if ($url) {
                    logger('notifier: urldelivery: ' . $url);
                    $deliver_status = slapper($owner, $url, $slap);
                    // TODO: redeliver/queue these items on failure, though there is no contact record
                }
            }
        }
    }
    if ($public_message) {
        $r1 = q("SELECT DISTINCT(`batch`), `id`, `name`,`network` FROM `contact` WHERE `network` = '%s' \n\t\t\tAND `uid` = %d AND `rel` != %d group by `batch` ORDER BY rand() ", dbesc(NETWORK_DIASPORA), intval($owner['uid']), intval(CONTACT_IS_SHARING));
        $r2 = q("SELECT `id`, `name`,`network` FROM `contact` \n\t\t\tWHERE `network` = '%s' AND `uid` = %d AND `blocked` = 0 AND `pending` = 0\n\t\t\tAND `rel` != %d order by rand() ", dbesc(NETWORK_DFRN), intval($owner['uid']), intval(CONTACT_IS_SHARING));
        $r = array_merge($r2, $r1);
        if (count($r)) {
            logger('pubdeliver: ' . print_r($r, true), LOGGER_DEBUG);
            // throw everything into the queue in case we get killed
            foreach ($r as $rr) {
                if (!$mail && !$fsuggest && !$followup) {
                    q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )", dbesc($cmd), intval($item_id), intval($rr['id']));
                }
            }
            foreach ($r as $rr) {
                // except for Diaspora batch jobs
                // Don't deliver to folks who have already been delivered to
                if ($rr['network'] !== NETWORK_DIASPORA && in_array($rr['id'], $conversants)) {
                    logger('notifier: already delivered id=' . $rr['id']);
                    continue;
                }
                if (!$mail && !$fsuggest && !$followup) {
                    logger('notifier: delivery agent: ' . $rr['name'] . ' ' . $rr['id']);
                    proc_run('php', 'include/delivery.php', $cmd, $item_id, $rr['id']);
                    if ($interval) {
                        @time_sleep_until(microtime(true) + (double) $interval);
                    }
                }
            }
        }
        if (strlen($hub)) {
            $hubs = explode(',', $hub);
            if (count($hubs)) {
                foreach ($hubs as $h) {
                    $h = trim($h);
                    if (!strlen($h)) {
                        continue;
                    }
                    $params = 'hub.mode=publish&hub.url=' . urlencode($a->get_baseurl() . '/dfrn_poll/' . $owner['nickname']);
                    post_url($h, $params);
                    logger('pubsub: publish: ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
                    if (count($hubs) > 1) {
                        sleep(7);
                    }
                    // try and avoid multiple hubs responding at precisely the same time
                }
            }
        }
    }
    if ($normal_mode) {
        call_hooks('notifier_normal', $target_item);
    }
    call_hooks('notifier_end', $target_item);
    return;
}
Example #4
0
/**
 * @param App $a
 * @param object $b
 * @return mixed
 */
function fbpost_post_hook(&$a, &$b)
{
    logger('fbpost_post_hook: Facebook post invoked', LOGGER_DEBUG);
    if ($b['deleted'] || $b['created'] !== $b['edited']) {
        return;
    }
    logger('fbpost_post_hook: Facebook post first check successful', LOGGER_DEBUG);
    // if post comes from facebook don't send it back
    if ($b['extid'] == NETWORK_FACEBOOK) {
        return;
    }
    if ($b['app'] == "Facebook" and $b['verb'] != ACTIVITY_LIKE) {
        return;
    }
    logger('fbpost_post_hook: Facebook post accepted', LOGGER_DEBUG);
    /**
     * Post to Facebook stream
     */
    require_once 'include/group.php';
    require_once 'include/html2plain.php';
    $reply = false;
    $likes = false;
    $deny_arr = array();
    $allow_arr = array();
    $toplevel = $b['id'] == $b['parent'] ? true : false;
    $linking = get_pconfig($b['uid'], 'facebook', 'no_linking') ? 0 : 1;
    if (!$toplevel && $linking) {
        $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($b['parent']), intval($b['uid']));
        //$r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
        //	dbesc($b['parent-uri']),
        //	intval($b['uid'])
        //);
        // is it a reply to a facebook post?
        // A reply to a toplevel post is only allowed for "real" facebook posts
        if (count($r) && substr($r[0]['uri'], 0, 4) === 'fb::') {
            $reply = substr($r[0]['uri'], 4);
        } elseif (count($r) && substr($r[0]['extid'], 0, 4) === 'fb::' and $r[0]['id'] != $r[0]['parent']) {
            $reply = substr($r[0]['extid'], 4);
        } else {
            return;
        }
        $u = q("SELECT * FROM user where uid = %d limit 1", intval($b['uid']));
        if (!count($u)) {
            return;
        }
        // only accept comments from the item owner. Other contacts are unknown to FB.
        if (!link_compare($b['author-link'], $a->get_baseurl() . '/profile/' . $u[0]['nickname'])) {
            return;
        }
        logger('fbpost_post_hook: facebook reply id=' . $reply);
    }
    if (strstr($b['postopts'], 'facebook') || $b['private'] || $reply) {
        if ($b['private'] && $reply === false) {
            $allow_people = expand_acl($b['allow_cid']);
            $allow_groups = expand_groups(expand_acl($b['allow_gid']));
            $deny_people = expand_acl($b['deny_cid']);
            $deny_groups = expand_groups(expand_acl($b['deny_gid']));
            $recipients = array_unique(array_merge($allow_people, $allow_groups));
            $deny = array_unique(array_merge($deny_people, $deny_groups));
            $allow_str = dbesc(implode(', ', $recipients));
            if ($allow_str) {
                logger("fbpost_post_hook: private post to: " . $allow_str, LOGGER_DEBUG);
                $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( {$allow_str} ) AND `network` = 'face'");
                if (count($r)) {
                    foreach ($r as $rr) {
                        $allow_arr[] = $rr['notify'];
                    }
                }
            }
            $deny_str = dbesc(implode(', ', $deny));
            if ($deny_str) {
                $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( {$deny_str} ) AND `network` = 'face'");
                if (count($r)) {
                    foreach ($r as $rr) {
                        $deny_arr[] = $rr['notify'];
                    }
                }
            }
            if (count($deny_arr) && !count($allow_arr)) {
                // One or more FB folks were denied access but nobody on FB was specifically allowed access.
                // This might cause the post to be open to public on Facebook, but only to selected members
                // on another network. Since this could potentially leak a post to somebody who was denied,
                // we will skip posting it to Facebook with a slightly vague but relevant message that will
                // hopefully lead somebody to this code comment for a better explanation of what went wrong.
                notice(t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL);
                return;
            }
            // if it's a private message but no Facebook members are allowed or denied, skip Facebook post
            if (!count($allow_arr) && !count($deny_arr)) {
                return;
            }
        }
        if ($b['verb'] == ACTIVITY_LIKE) {
            $likes = true;
            logger('fbpost_post_hook: liking ' . print_r($b, true), LOGGER_DEBUG);
        }
        $appid = get_config('facebook', 'appid');
        $secret = get_config('facebook', 'appsecret');
        if ($appid && $secret) {
            logger('fbpost_post_hook: have appid+secret');
            $fb_token = get_pconfig($b['uid'], 'facebook', 'access_token');
            // post to facebook if it's a public post and we've ticked the 'post to Facebook' box,
            // or it's a private message with facebook participants
            // or it's a reply or likes action to an existing facebook post
            if ($fb_token && ($toplevel || $b['private'] || $reply)) {
                logger('fbpost_post_hook: able to post');
                require_once 'library/facebook.php';
                require_once 'include/bbcode.php';
                $msg = $b['body'];
                logger('fbpost_post_hook: original msg=' . $msg, LOGGER_DATA);
                if ($toplevel) {
                    require_once "include/plaintext.php";
                    $msgarr = plaintext($a, $b, 0, false, 9);
                    $msg = $msgarr["text"];
                    $link = $msgarr["url"];
                    $linkname = $msgarr["title"];
                    if ($msgarr["type"] != "video") {
                        $image = $msgarr["image"];
                    }
                    // Fallback - if message is empty
                    if (!strlen($msg)) {
                        $msg = $linkname;
                    }
                    if (!strlen($msg)) {
                        $msg = $link;
                    }
                    if (!strlen($msg)) {
                        $msg = $image;
                    }
                } else {
                    require_once "include/bbcode.php";
                    require_once "include/html2plain.php";
                    $msg = bb_CleanPictureLinks($msg);
                    $msg = bbcode($msg, false, false, 2, true);
                    $msg = trim(html2plain($msg, 0));
                    $link = "";
                    $image = "";
                    $linkname = "";
                }
                // If there is nothing to post then exit
                if (!strlen($msg)) {
                    return;
                }
                logger('fbpost_post_hook: msg=' . $msg, LOGGER_DATA);
                $video = "";
                if ($likes) {
                    $postvars = array('access_token' => $fb_token);
                } else {
                    // message, picture, link, name, caption, description, source, place, tags
                    //if(trim($link) != "")
                    //	if (@exif_imagetype($link) != 0) {
                    //		$image = $link;
                    //		$link = "";
                    //	}
                    $postvars = array('access_token' => $fb_token, 'message' => $msg);
                    if (trim($image) != "") {
                        $postvars['picture'] = $image;
                    }
                    if (trim($link) != "") {
                        $postvars['link'] = $link;
                        if (stristr($link, 'youtube') || stristr($link, 'youtu.be') || stristr($link, 'vimeo')) {
                            $video = $link;
                        }
                    }
                    if (trim($linkname) != "") {
                        $postvars['name'] = $linkname;
                    }
                }
                if ($b['private'] && $toplevel) {
                    $postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"';
                    if (count($allow_arr)) {
                        $postvars['privacy'] .= ',"allow": "' . implode(',', $allow_arr) . '"';
                    }
                    if (count($deny_arr)) {
                        $postvars['privacy'] .= ',"deny": "' . implode(',', $deny_arr) . '"';
                    }
                    $postvars['privacy'] .= '}';
                }
                $post_to_page = get_pconfig($b['uid'], 'facebook', 'post_to_page');
                $page_access_token = get_pconfig($b['uid'], 'facebook', 'page_access_token');
                if (intval($post_to_page) != 0 and $page_access_token != "") {
                    $target = $post_to_page;
                } else {
                    $target = "me";
                }
                if ($reply) {
                    $url = 'https://graph.facebook.com/' . $reply . '/' . ($likes ? 'likes' : 'comments');
                } else {
                    if ($video != "" or $image == "" and $link != "") {
                        // If it is a link to a video or a link without a preview picture then post it as a link
                        if ($video != "") {
                            $link = $video;
                        }
                        $postvars = array('access_token' => $fb_token, 'link' => $link);
                        if ($msg != $video) {
                            $postvars['message'] = $msg;
                        }
                        $url = 'https://graph.facebook.com/' . $target . '/links';
                    } else {
                        if ($link == "" and $image != "") {
                            // If it is only an image without a page link then post this image as a photo
                            $postvars = array('access_token' => $fb_token, 'url' => $image);
                            if ($msg != $image) {
                                $postvars['message'] = $msg;
                            }
                            $url = 'https://graph.facebook.com/' . $target . '/photos';
                            //} else if (($link != "") or ($image != "") or ($b['title'] == '') or (strlen($msg) < 500)) {
                        } else {
                            $url = 'https://graph.facebook.com/' . $target . '/feed';
                            if (!get_pconfig($b['uid'], 'facebook', 'suppress_view_on_friendica') and $b['plink']) {
                                $postvars['actions'] = '{"name": "' . t('View on Friendica') . '", "link": "' . $b['plink'] . '"}';
                            }
                        }
                    }
                }
                /*				} else {
                					// if its only a message and a subject and the message is larger than 500 characters then post it as note
                					$postvars = array(
                						'access_token' => $fb_token,
                						'message' => bbcode($b['body'], false, false),
                						'subject' => $b['title'],
                					);
                					$url = 'https://graph.facebook.com/'.$target.'/notes';
                				} */
                // Post to page?
                if (!$reply and $target != "me" and $page_access_token) {
                    $postvars['access_token'] = $page_access_token;
                }
                logger('fbpost_post_hook: post to ' . $url);
                logger('fbpost_post_hook: postvars: ' . print_r($postvars, true));
                // "test_mode" prevents anything from actually being posted.
                // Otherwise, let's do it.
                if (!get_config('facebook', 'test_mode')) {
                    $x = post_url($url, $postvars);
                    logger('fbpost_post_hook: post returns: ' . $x, LOGGER_DEBUG);
                    $retj = json_decode($x);
                    if ($retj->id) {
                        // Only set the extid when it isn't the toplevel post
                        q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d AND `parent` != %d", dbesc('fb::' . $retj->id), intval($b['id']), intval($b['id']));
                    } else {
                        // Sometimes posts are accepted from facebook although it telling an error
                        // This leads to endless comment flooding.
                        // If it is a special kind of failure the post was receiced
                        // Although facebook said it wasn't received ...
                        if (!$likes and ($retj->error->type != "OAuthException" or $retj->error->code != 2) and $x != "") {
                            $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($b['uid']));
                            if (count($r)) {
                                $a->contact = $r[0]["id"];
                            }
                            $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars));
                            require_once 'include/queue_fn.php';
                            add_to_queue($a->contact, NETWORK_FACEBOOK, $s);
                            logger('fbpost_post_hook: Post failed, requeued.', LOGGER_DEBUG);
                            notice(t('Facebook post failed. Queued for retry.') . EOL);
                        }
                        if (isset($retj->error) && $retj->error->type == "OAuthException" && $retj->error->code == 190) {
                            logger('fbpost_post_hook: Facebook session has expired due to changed password.', LOGGER_DEBUG);
                            $last_notification = get_pconfig($b['uid'], 'facebook', 'session_expired_mailsent');
                            if (!$last_notification || $last_notification < time() - FACEBOOK_SESSION_ERR_NOTIFICATION_INTERVAL) {
                                require_once 'include/enotify.php';
                                $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid']));
                                notification(array('uid' => $b['uid'], 'type' => NOTIFY_SYSTEM, 'system_type' => 'facebook_connection_invalid', 'language' => $r[0]['language'], 'to_name' => $r[0]['username'], 'to_email' => $r[0]['email'], 'source_name' => t('Administrator'), 'source_link' => $a->config["system"]["url"], 'source_photo' => $a->config["system"]["url"] . '/images/person-80.jpg'));
                                set_pconfig($b['uid'], 'facebook', 'session_expired_mailsent', time());
                            } else {
                                logger('fbpost_post_hook: No notification, as the last one was sent on ' . $last_notification, LOGGER_DEBUG);
                            }
                        }
                    }
                }
            }
        }
    }
}
Example #5
0
function network_content(&$a, $update = 0)
{
    require_once 'include/conversation.php';
    if (!local_user()) {
        return login(false);
    }
    $o = '';
    // item filter tabs
    // TODO: fix this logic, reduce duplication
    //$a->page['content'] .= '<div class="tabs-wrapper">';
    $starred_active = '';
    $new_active = '';
    $bookmarked_active = '';
    $all_active = '';
    $search_active = '';
    $conv_active = '';
    if ($a->argc > 1 && $a->argv[1] === 'new' || $a->argc > 2 && $a->argv[2] === 'new') {
        $new_active = 'active';
    }
    if (x($_GET, 'search')) {
        $search_active = 'active';
    }
    if (x($_GET, 'star')) {
        $starred_active = 'active';
    }
    if ($_GET['bmark']) {
        $bookmarked_active = 'active';
    }
    if ($_GET['conv']) {
        $conv_active = 'active';
    }
    if ($new_active == '' && $starred_active == '' && $bookmarked_active == '' && $conv_active == '' && $search_active == '') {
        $all_active = 'active';
    }
    $postord_active = '';
    if ($all_active && x($_GET, 'order') && $_GET['order'] !== 'comment') {
        $all_active = '';
        $postord_active = 'active';
    }
    // tabs
    $tabs = array(array('label' => t('Commented Order'), 'url' => $a->get_baseurl() . '/' . str_replace('/new', '', $a->cmd) . (x($_GET, 'cid') ? '?cid=' . $_GET['cid'] : ''), 'sel' => $all_active), array('label' => t('Posted Order'), 'url' => $a->get_baseurl() . '/' . str_replace('/new', '', $a->cmd) . '?order=post' . (x($_GET, 'cid') ? '&cid=' . $_GET['cid'] : ''), 'sel' => $postord_active), array('label' => t('Personal'), 'url' => $a->get_baseurl() . '/' . str_replace('/new', '', $a->cmd) . (x($_GET, 'cid') ? '/?cid=' . $_GET['cid'] : '') . '&conv=1', 'sel' => $conv_active), array('label' => t('New'), 'url' => $a->get_baseurl() . '/' . str_replace('/new', '', $a->cmd) . '/new' . (x($_GET, 'cid') ? '/?cid=' . $_GET['cid'] : ''), 'sel' => $new_active), array('label' => t('Starred'), 'url' => $a->get_baseurl() . '/' . str_replace('/new', '', $a->cmd) . (x($_GET, 'cid') ? '/?cid=' . $_GET['cid'] : '') . '&star=1', 'sel' => $starred_active), array('label' => t('Bookmarks'), 'url' => $a->get_baseurl() . '/' . str_replace('/new', '', $a->cmd) . (x($_GET, 'cid') ? '/?cid=' . $_GET['cid'] : '') . '&bmark=1', 'sel' => $bookmarked_active));
    $tpl = get_markup_template('common_tabs.tpl');
    $o .= replace_macros($tpl, array('$tabs' => $tabs));
    // --- end item filter tabs
    $contact_id = $a->cid;
    $group = 0;
    $nouveau = false;
    require_once 'include/acl_selectors.php';
    $cid = x($_GET, 'cid') ? intval($_GET['cid']) : 0;
    $star = x($_GET, 'star') ? intval($_GET['star']) : 0;
    $bmark = x($_GET, 'bmark') ? intval($_GET['bmark']) : 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;
    if ($a->argc > 2 && $a->argv[2] === 'new') {
        $nouveau = true;
    }
    if ($a->argc > 1) {
        if ($a->argv[1] === 'new') {
            $nouveau = true;
        } else {
            $group = intval($a->argv[1]);
            $def_acl = array('allow_gid' => '<' . $group . '>');
        }
    }
    if (x($_GET, 'search')) {
        $nouveau = true;
    }
    if ($cid) {
        $def_acl = array('allow_cid' => '<' . intval($cid) . '>');
    }
    if (!$update) {
        if (group) {
            if (($t = group_public_members($group)) && !get_pconfig(local_user(), 'system', 'nowarn_insecure')) {
                notice(sprintf(tt('Warning: This group contains %s member from an insecure network.', 'Warning: This group contains %s members from an insecure network.', $t), $t) . EOL);
                notice(t('Private messages to this group are at risk of public disclosure.') . EOL);
            }
        }
        nav_set_selected('network');
        $_SESSION['return_url'] = $a->cmd;
        $celeb = $a->user['page-flags'] == PAGE_SOAPBOX || $a->user['page-flags'] == PAGE_COMMUNITY ? true : false;
        $x = array('is_owner' => true, 'allow_location' => $a->user['allow_location'], 'default_location' => $a->user['default_location'], 'nickname' => $a->user['nickname'], 'lockstate' => $group || is_array($a->user) && (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) || strlen($a->user['deny_cid']) || strlen($a->user['deny_gid'])) ? 'lock' : 'unlock', 'acl' => populate_acl($group || $cid ? $def_acl : $a->user, $celeb), 'bang' => $group || $cid ? '!' : '', 'visitor' => 'block', 'profile_uid' => local_user());
        $o .= status_editor($a, $x);
    }
    // We aren't going to try and figure out at the item, group, and page
    // level which items you've seen and which you haven't. If you're looking
    // at the top level network page just mark everything seen.
    if (!$group && !$cid && !$star) {
        $r = q("UPDATE `item` SET `unseen` = 0 \n\t\t\tWHERE `unseen` = 1 AND `uid` = %d", intval($_SESSION['uid']));
    }
    // 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.
    $star_sql = $star ? " AND `starred` = 1 " : '';
    if ($bmark) {
        $star_sql .= " AND `bookmark` = 1 ";
    }
    $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` {$star_sql} ) ";
    if ($group) {
        $r = q("SELECT `name`, `id` FROM `group` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($group), intval($_SESSION['uid']));
        if (!count($r)) {
            if ($update) {
                killme();
            }
            notice(t('No such group') . EOL);
            goaway($a->get_baseurl() . '/network');
            // NOTREACHED
        }
        $contacts = expand_groups(array($group));
        if (is_array($contacts) && count($contacts)) {
            $contact_str = implode(',', $contacts);
        } else {
            $contact_str = ' 0 ';
            info(t('Group is empty'));
        }
        $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` {$star_sql} AND ( `contact-id` IN ( {$contact_str} ) OR `allow_gid` REGEXP '<" . intval($group) . ">' )) ";
        $o = '<h2>' . t('Group: ') . $r[0]['name'] . '</h2>' . $o;
    } elseif ($cid) {
        $r = q("SELECT `id`,`name`,`network`,`writable` FROM `contact` WHERE `id` = %d \n\t\t\t\tAND `blocked` = 0 AND `pending` = 0 LIMIT 1", intval($cid));
        if (count($r)) {
            $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` {$star_sql} AND `contact-id` IN ( " . intval($cid) . " )) ";
            $o = '<h2>' . t('Contact: ') . $r[0]['name'] . '</h2>' . $o;
            if ($r[0]['network'] !== NETWORK_MAIL && $r[0]['network'] !== NETWORK_DFRN && $r[0]['network'] !== NETWORK_FACEBOOK && $r[0]['network'] !== NETWORK_DIASPORA && $r[0]['writable'] && !get_pconfig(local_user(), 'system', 'nowarn_insecure')) {
                notice(t('Private messages to this person are at risk of public disclosure.') . EOL);
            }
        } else {
            notice(t('Invalid contact.') . EOL);
            goaway($a->get_baseurl() . '/network');
            // NOTREACHED
        }
    }
    if (!$group && !$cid && !$update) {
        $o .= get_birthdays();
        $o .= get_events();
    }
    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).
        $o .= '<div id="live-network"></div>' . "\r\n";
        $o .= "<script> var profile_uid = " . $_SESSION['uid'] . "; var netargs = '" . substr($a->cmd, 8) . '?f=' . (x($_GET, 'cid') ? '&cid=' . $_GET['cid'] : '') . (x($_GET, 'search') ? '&search=' . $_GET['search'] : '') . (x($_GET, 'star') ? '&star=' . $_GET['star'] : '') . (x($_GET, 'order') ? '&order=' . $_GET['order'] : '') . (x($_GET, 'bmark') ? '&bmark=' . $_GET['bmark'] : '') . (x($_GET, 'liked') ? '&liked=' . $_GET['liked'] : '') . (x($_GET, 'conv') ? '&conv=' . $_GET['conv'] : '') . "'; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
    }
    $sql_extra2 = $nouveau ? '' : " AND `item`.`parent` = `item`.`id` ";
    if (x($_GET, 'search')) {
        $search = escape_tags($_GET['search']);
        $sql_extra .= sprintf(" AND ( `item`.`body` REGEXP '%s' OR `item`.`tag` REGEXP '%s' ) ", dbesc(preg_quote($search)), dbesc('\\]' . preg_quote($search) . '\\['));
    }
    if ($conv) {
        $myurl = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
        $myurl = substr($myurl, strpos($myurl, '://') + 3);
        $myurl = str_replace(array('www.', '.'), array('', '\\.'), $myurl);
        $diasp_url = str_replace('/profile/', '/u/', $myurl);
        $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where ( `author-link` regexp '%s' or `tag` regexp '%s' or tag regexp '%s' )) ", dbesc($myurl . '$'), dbesc($myurl . '\\]'), dbesc($diasp_url . '\\]'));
    }
    $r = q("SELECT COUNT(*) AS `total`\n\t\tFROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t{$sql_extra2}\n\t\t{$sql_extra} ", intval($_SESSION['uid']));
    if (count($r)) {
        $a->set_pager_total($r[0]['total']);
        $a->set_pager_itemspage(40);
    }
    if ($nouveau) {
        // "New Item View" - show all items unthreaded in reverse created date order
        $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, \n\t\t\t`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`, `contact`.`writable`,\n\t\t\t`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,\n\t\t\t`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`\n\t\t\tFROM `item`, `contact`\n\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\t\tAND `contact`.`id` = `item`.`contact-id`\n\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t{$sql_extra}\n\t\t\tORDER BY `item`.`received` DESC LIMIT %d ,%d ", intval($_SESSION['uid']), intval($a->pager['start']), intval($a->pager['itemspage']));
    } else {
        // Normal conversation view
        if ($order === 'post') {
            $ordering = "`created`";
        } else {
            $ordering = "`commented`";
        }
        // Fetch a page full of parent items for this page
        $r = q("SELECT `item`.`id` AS `item_id`, `contact`.`uid` AS `contact_uid`\n\t\t\tFROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\tAND `item`.`parent` = `item`.`id`\n\t\t\t{$sql_extra}\n\t\t\tORDER BY `item`.{$ordering} DESC LIMIT %d ,%d ", intval(local_user()), intval($a->pager['start']), intval($a->pager['itemspage']));
        // Then fetch all the children of the parents that are on this page
        $parents_arr = array();
        $parents_str = '';
        if (count($r)) {
            foreach ($r as $rr) {
                $parents_arr[] = $rr['item_id'];
            }
            $parents_str = implode(', ', $parents_arr);
            $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,\n\t\t\t\t`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`, `contact`.`writable`,\n\t\t\t\t`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,\n\t\t\t\t`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`\n\t\t\t\tFROM `item`, (SELECT `p`.`id`,`p`.`created`,`p`.`commented` FROM `item` AS `p` WHERE `p`.`parent`=`p`.`id`) as `parentitem`, `contact`\n\t\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\t\t\tAND `contact`.`id` = `item`.`contact-id`\n\t\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\tAND `item`.`parent` = `parentitem`.`id` AND `item`.`parent` IN ( %s )\n\t\t\t\t{$sql_extra}\n\t\t\t\tORDER BY `parentitem`.{$ordering} DESC, `parentitem`.`id` ASC, `item`.`gravity` ASC, `item`.`created` ASC ", intval(local_user()), dbesc($parents_str));
        }
    }
    // Set this so that the conversation function can find out contact info for our wall-wall items
    $a->page_contact = $a->contact;
    $mode = $nouveau ? 'network-new' : 'network';
    $o .= conversation($a, $r, $mode, $update);
    if (!$update) {
        $o .= paginate($a);
    }
    return $o;
}
Example #6
0
function content_content(&$a, $update = 0)
{
    require_once 'include/conversation.php';
    // Currently security is based on the logged in user
    if (!local_user()) {
        return;
    }
    $arr = array('query' => $a->query_string);
    call_hooks('content_content_init', $arr);
    $datequery = $datequery2 = '';
    $group = 0;
    $nouveau = false;
    if ($a->argc > 1) {
        for ($x = 1; $x < $a->argc; $x++) {
            if (is_a_date_arg($a->argv[$x])) {
                if ($datequery) {
                    $datequery2 = escape_tags($a->argv[$x]);
                } else {
                    $datequery = escape_tags($a->argv[$x]);
                    $_GET['order'] = 'post';
                }
            } elseif ($a->argv[$x] === 'new') {
                $nouveau = true;
            } elseif (intval($a->argv[$x])) {
                $group = intval($a->argv[$x]);
                $def_acl = array('allow_gid' => '<' . $group . '>');
            }
        }
    }
    $o = '';
    $contact_id = $a->cid;
    require_once 'include/acl_selectors.php';
    $cid = x($_GET, 'cid') ? intval($_GET['cid']) : 0;
    $star = x($_GET, 'star') ? intval($_GET['star']) : 0;
    $bmark = x($_GET, 'bmark') ? intval($_GET['bmark']) : 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;
    $nets = x($_GET, 'nets') ? $_GET['nets'] : '';
    $cmin = x($_GET, 'cmin') ? intval($_GET['cmin']) : 0;
    $cmax = x($_GET, 'cmax') ? intval($_GET['cmax']) : 99;
    $file = x($_GET, 'file') ? $_GET['file'] : '';
    if (x($_GET, 'search') || x($_GET, 'file')) {
        $nouveau = true;
    }
    if ($cid) {
        $def_acl = array('allow_cid' => '<' . intval($cid) . '>');
    }
    if ($nets) {
        $r = q("select id from contact where uid = %d and network = '%s' and self = 0", intval(local_user()), dbesc($nets));
        $str = '';
        if (count($r)) {
            foreach ($r as $rr) {
                $str .= '<' . $rr['id'] . '>';
            }
        }
        if (strlen($str)) {
            $def_acl = array('allow_cid' => $str);
        }
    }
    $sql_options = $star ? " and starred = 1 " : '';
    $sql_options .= $bmark ? " and bookmark = 1 " : '';
    $sql_nets = $nets ? sprintf(" and `contact`.`network` = '%s' ", dbesc($nets)) : '';
    $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` {$sql_options} ) ";
    if ($group) {
        $r = q("SELECT `name`, `id` FROM `group` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($group), intval($_SESSION['uid']));
        if (!count($r)) {
            if ($update) {
                killme();
            }
            notice(t('No such group') . EOL);
            goaway($a->get_baseurl(true) . '/network');
            // NOTREACHED
        }
        $contacts = expand_groups(array($group));
        if (is_array($contacts) && count($contacts)) {
            $contact_str = implode(',', $contacts);
        } else {
            $contact_str = ' 0 ';
            info(t('Group is empty'));
        }
        $sql_extra = " AND `item`.`parent` IN ( SELECT DISTINCT(`parent`) FROM `item` WHERE 1 {$sql_options} AND ( `contact-id` IN ( {$contact_str} ) OR `allow_gid` like '" . protect_sprintf('%<' . intval($group) . '>%') . "' ) and deleted = 0 ) ";
        $o = replace_macros(get_markup_template("section_title.tpl"), array('$title' => sprintf(t('Group: %s'), $r[0]['name']))) . $o;
    } elseif ($cid) {
        $r = q("SELECT `id`,`name`,`network`,`writable`,`nurl` FROM `contact` WHERE `id` = %d \n\t\t\t\tAND `blocked` = 0 AND `pending` = 0 LIMIT 1", intval($cid));
        if (count($r)) {
            $sql_extra = " AND `item`.`parent` IN ( SELECT DISTINCT(`parent`) FROM `item` WHERE 1 {$sql_options} AND `contact-id` = " . intval($cid) . " and deleted = 0 ) ";
        } else {
            killme();
        }
    }
    $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;
    $sql_table = "`item`";
    if (x($_GET, 'search')) {
        $search = escape_tags($_GET['search']);
        if (strpos($search, '#') === 0) {
            $tag = true;
            $search = substr($search, 1);
        }
        if (get_config('system', 'only_tag_search')) {
            $tag = true;
        }
        if ($tag) {
            //$sql_extra = sprintf(" AND `term`.`term` = '%s' AND `term`.`otype` = %d AND `term`.`type` = %d ",
            //	dbesc(protect_sprintf($search)), intval(TERM_OBJ_POST), intval(TERM_HASHTAG));
            //$sql_table = "`term` INNER JOIN `item` ON `item`.`id` = `term`.`oid` AND `item`.`uid` = `term`.`uid` ";
            $sql_extra = "";
            $sql_table = sprintf("`item` INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ", dbesc(protect_sprintf($search)), intval(TERM_OBJ_POST), intval(TERM_HASHTAG), intval(local_user()));
        } else {
            if (get_config('system', 'use_fulltext_engine')) {
                $sql_extra = sprintf(" AND MATCH (`item`.`body`, `item`.`title`) AGAINST ('%s' in boolean mode) ", dbesc(protect_sprintf($search)));
            } else {
                $sql_extra = sprintf(" AND `item`.`body` REGEXP '%s' ", dbesc(protect_sprintf(preg_quote($search))));
            }
        }
    }
    if (strlen($file)) {
        $sql_extra .= file_tag_file_query('item', unxmlify($file));
    }
    if ($conv) {
        $myurl = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
        $myurl = substr($myurl, strpos($myurl, '://') + 3);
        $myurl = str_replace('www.', '', $myurl);
        $diasp_url = str_replace('/profile/', '/u/', $myurl);
        $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where `author-link` IN ('https://%s', 'http://%s') OR `mention`)", dbesc(protect_sprintf($myurl)), dbesc(protect_sprintf($myurl)));
    }
    $pager_sql = sprintf(" LIMIT %d, %d ", intval($a->pager['start']), intval($a->pager['itemspage']));
    if ($nouveau) {
        // "New Item View" - show all items unthreaded in reverse created date order
        $items = q("SELECT `item`.*, `item`.`id` AS `item_id`,\n\t\t\t`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`, `contact`.`writable`,\n\t\t\t`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,\n\t\t\t`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`\n\t\t\tFROM {$sql_table} INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1\n\t\t\tAND `item`.`deleted` = 0 and `item`.`moderated` = 0\n\t\t\t{$simple_update}\n\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t{$sql_extra} {$sql_nets}\n\t\t\tORDER BY `item`.`received` DESC {$pager_sql} ", intval($_SESSION['uid']));
    } else {
        // Normal conversation view
        if ($order === 'post') {
            $ordering = "`created`";
        } else {
            $ordering = "`commented`";
        }
        $start = dba_timer();
        $r = q("SELECT `item`.`id` AS `item_id`, `contact`.`uid` AS `contact_uid`\n\t\t\tFROM {$sql_table} INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\t\tAND `item`.`moderated` = 0 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\tAND `item`.`parent` = `item`.`id`\n\t\t\t{$sql_extra3} {$sql_extra} {$sql_nets}\n\t\t\tORDER BY `item`.{$ordering} DESC {$pager_sql} ", intval(local_user()));
        $first = dba_timer();
        // Then fetch all the children of the parents that are on this page
        $parents_arr = array();
        $parents_str = '';
        if (count($r)) {
            foreach ($r as $rr) {
                if (!in_array($rr['item_id'], $parents_arr)) {
                    $parents_arr[] = $rr['item_id'];
                }
            }
            $parents_str = implode(', ', $parents_arr);
            $items = q("SELECT `item`.*, `item`.`id` AS `item_id`,\n\t\t\t\t`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`alias`, `contact`.`rel`, `contact`.`writable`,\n\t\t\t\t`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,\n\t\t\t\t`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`\n\t\t\t\tFROM {$sql_table} INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\t\t\tAND `item`.`moderated` = 0\n\t\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\tAND `item`.`parent` IN ( %s )\n\t\t\t\t{$sql_extra} ", intval(local_user()), dbesc($parents_str));
            $second = dba_timer();
            $items = conv_sort($items, $ordering);
        } else {
            $items = array();
        }
    }
    logger('parent dba_timer: ' . sprintf('%01.4f', $first - $start));
    logger('child  dba_timer: ' . sprintf('%01.4f', $second - $first));
    // Set this so that the conversation function can find out contact info for our wall-wall items
    $a->page_contact = $a->contact;
    $mode = $nouveau ? 'network-new' : 'network';
    $o = render_content($a, $items, $mode, false);
    header('Content-type: application/json');
    echo json_encode($o);
    killme();
}
Example #7
0
function notifier_run(&$argv, &$argc)
{
    global $a, $db;
    if (is_null($a)) {
        $a = new App();
    }
    if (is_null($db)) {
        @(include ".htconfig.php");
        require_once "include/dba.php";
        $db = new dba($db_host, $db_user, $db_pass, $db_data);
        unset($db_host, $db_user, $db_pass, $db_data);
    }
    require_once "include/session.php";
    require_once "include/datetime.php";
    require_once 'include/items.php';
    require_once 'include/bbcode.php';
    require_once 'include/email.php';
    load_config('config');
    load_config('system');
    load_hooks();
    if ($argc < 3) {
        return;
    }
    $a->set_baseurl(get_config('system', 'url'));
    logger('notifier: invoked: ' . print_r($argv, true), LOGGER_DEBUG);
    $cmd = $argv[1];
    switch ($cmd) {
        case 'mail':
        default:
            $item_id = intval($argv[2]);
            if (!$item_id) {
                return;
            }
            break;
    }
    $expire = false;
    $mail = false;
    $fsuggest = false;
    $relocate = false;
    $top_level = false;
    $recipients = array();
    $url_recipients = array();
    $normal_mode = true;
    if ($cmd === 'mail') {
        $normal_mode = false;
        $mail = true;
        $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1", intval($item_id));
        if (!count($message)) {
            return;
        }
        $uid = $message[0]['uid'];
        $recipients[] = $message[0]['contact-id'];
        $item = $message[0];
    } elseif ($cmd === 'expire') {
        $normal_mode = false;
        $expire = true;
        $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1\n\t\t\tAND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE", intval($item_id));
        $uid = $item_id;
        $item_id = 0;
        if (!count($items)) {
            return;
        }
    } elseif ($cmd === 'suggest') {
        $normal_mode = false;
        $fsuggest = true;
        $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item_id));
        if (!count($suggest)) {
            return;
        }
        $uid = $suggest[0]['uid'];
        $recipients[] = $suggest[0]['cid'];
        $item = $suggest[0];
    } elseif ($cmd === 'removeme') {
        $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($item_id));
        if (!$r) {
            return;
        }
        $user = $r[0];
        $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1", intval($item_id));
        if (!$r) {
            return;
        }
        $self = $r[0];
        $r = q("SELECT * FROM `contact` WHERE `self` = 0 AND `uid` = %d", intval($item_id));
        if (!$r) {
            return;
        }
        require_once 'include/Contact.php';
        foreach ($r as $contact) {
            terminate_friendship($user, $self, $contact);
        }
        return;
    } elseif ($cmd === 'relocate') {
        $normal_mode = false;
        $relocate = true;
        $uid = $item_id;
    } else {
        // find ancestors
        $r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1", intval($item_id));
        if (!count($r) || !intval($r[0]['parent'])) {
            return;
        }
        $target_item = $r[0];
        $parent_id = intval($r[0]['parent']);
        $uid = $r[0]['uid'];
        $updated = $r[0]['edited'];
        // POSSIBLE CLEANUP --> The following seems superfluous. We've already checked for "if (! intval($r[0]['parent']))" a few lines up
        if (!$parent_id) {
            return;
        }
        $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`\n\t\t\tFROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC", intval($parent_id));
        if (!count($items)) {
            return;
        }
        // avoid race condition with deleting entries
        if ($items[0]['deleted']) {
            foreach ($items as $item) {
                $item['deleted'] = 1;
            }
        }
        if (count($items) == 1 && $items[0]['id'] === $target_item['id'] && $items[0]['uri'] === $items[0]['parent-uri']) {
            logger('notifier: top level post');
            $top_level = true;
        }
    }
    $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,\n\t\t`user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,\n\t\t`user`.`page-flags`, `user`.`prvnets`\n\t\tFROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`\n\t\tWHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1", intval($uid));
    if (!count($r)) {
        return;
    }
    $owner = $r[0];
    $walltowall = $top_level && $owner['id'] != $items[0]['contact-id'] ? true : false;
    $hub = get_config('system', 'huburl');
    // If this is a public conversation, notify the feed hub
    $public_message = true;
    // Do a PuSH
    $push_notify = false;
    // fill this in with a single salmon slap if applicable
    $slap = '';
    if (!($mail || $fsuggest || $relocate)) {
        require_once 'include/group.php';
        $parent = $items[0];
        $thr_parent = q("SELECT `network` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($target_item["thr-parent"]), intval($target_item["uid"]));
        logger('Parent is ' . $parent['network'] . '. Thread parent is ' . $thr_parent[0]['network'], LOGGER_DEBUG);
        // This is IMPORTANT!!!!
        // We will only send a "notify owner to relay" or followup message if the referenced post
        // originated on our system by virtue of having our hostname somewhere
        // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
        // if $parent['wall'] == 1 we will already have the parent message in our array
        // and we will relay the whole lot.
        // expire sends an entire group of expire messages and cannot be forwarded.
        // However the conversation owner will be a part of the conversation and will
        // be notified during this run.
        // Other DFRN conversation members will be alerted during polled updates.
        // Diaspora members currently are not notified of expirations, and other networks have
        // either limited or no ability to process deletions. We should at least fix Diaspora
        // by stringing togther an array of retractions and sending them onward.
        $localhost = str_replace('www.', '', $a->get_hostname());
        if (strpos($localhost, ':')) {
            $localhost = substr($localhost, 0, strpos($localhost, ':'));
        }
        /**
         *
         * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
         * have been known to cause runaway conditions which affected several servers, along with
         * permissions issues.
         *
         */
        $relay_to_owner = false;
        if (!$top_level && $parent['wall'] == 0 && !$expire && stristr($target_item['uri'], $localhost)) {
            $relay_to_owner = true;
        }
        if ($cmd === 'uplink' && intval($parent['forum_mode']) == 1 && !$top_level) {
            $relay_to_owner = true;
        }
        // until the 'origin' flag has been in use for several months
        // we will just use it as a fallback test
        // later we will be able to use it as the primary test of whether or not to relay.
        if (!$target_item['origin']) {
            $relay_to_owner = false;
        }
        if ($parent['origin']) {
            $relay_to_owner = false;
        }
        if ($relay_to_owner) {
            logger('notifier: followup ' . $target_item["guid"], LOGGER_DEBUG);
            // local followup to remote post
            $followup = true;
            $public_message = false;
            // not public
            $conversant_str = dbesc($parent['contact-id']);
            $recipients = array($parent['contact-id']);
            if (!$target_item['private'] and $target_item['wall'] and strlen($target_item['allow_cid'] . $target_item['allow_gid'] . $target_item['deny_cid'] . $target_item['deny_gid']) == 0) {
                $push_notify = true;
            }
            // We notify Friendica users in the thread when it is an OStatus thread.
            // Hopefully this transfers the messages to the other Friendica servers. (Untested)
            if ($thr_parent and $thr_parent[0]['network'] == NETWORK_OSTATUS or $parent['network'] == NETWORK_OSTATUS) {
                $push_notify = true;
                if ($parent["network"] == NETWORK_OSTATUS) {
                    $r = q("SELECT `author-link` FROM `item` WHERE `parent` = %d AND `author-link` != '%s'", intval($target_item["parent"]), dbesc($owner['url']));
                    foreach ($r as $parent_item) {
                        $probed_contact = probe_url($parent_item["author-link"]);
                        if ($probed_contact["notify"] != "" and $probed_contact["network"] == NETWORK_DFRN) {
                            logger('Notify Friendica user ' . $probed_contact["url"] . ': ' . $probed_contact["notify"]);
                            $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
                        }
                    }
                }
                if (count($url_recipients)) {
                    logger("url_recipients " . print_r($url_recipients, true));
                }
            }
        } else {
            $followup = false;
            logger('Distributing directly ' . $target_item["guid"], LOGGER_DEBUG);
            // don't send deletions onward for other people's stuff
            if ($target_item['deleted'] && !intval($target_item['wall'])) {
                logger('notifier: ignoring delete notification for non-wall item');
                return;
            }
            if (strlen($parent['allow_cid']) || strlen($parent['allow_gid']) || strlen($parent['deny_cid']) || strlen($parent['deny_gid'])) {
                $public_message = false;
                // private recipients, not public
            }
            $allow_people = expand_acl($parent['allow_cid']);
            $allow_groups = expand_groups(expand_acl($parent['allow_gid']), true);
            $deny_people = expand_acl($parent['deny_cid']);
            $deny_groups = expand_groups(expand_acl($parent['deny_gid']));
            // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
            // a delivery fork. private groups (forum_mode == 2) do not uplink
            if (intval($parent['forum_mode']) == 1 && !$top_level && $cmd !== 'uplink') {
                proc_run('php', 'include/notifier.php', 'uplink', $item_id);
            }
            $conversants = array();
            foreach ($items as $item) {
                $recipients[] = $item['contact-id'];
                $conversants[] = $item['contact-id'];
                // pull out additional tagged people to notify (if public message)
                if ($public_message && strlen($item['inform'])) {
                    $people = explode(',', $item['inform']);
                    foreach ($people as $person) {
                        if (substr($person, 0, 4) === 'cid:') {
                            $recipients[] = intval(substr($person, 4));
                            $conversants[] = intval(substr($person, 4));
                        } else {
                            $url_recipients[] = substr($person, 4);
                        }
                    }
                }
            }
            if (count($url_recipients)) {
                logger('notifier: ' . $target_item["guid"] . ' url_recipients ' . print_r($url_recipients, true));
            }
            $conversants = array_unique($conversants);
            $recipients = array_unique(array_merge($recipients, $allow_people, $allow_groups));
            $deny = array_unique(array_merge($deny_people, $deny_groups));
            $recipients = array_diff($recipients, $deny);
            $conversant_str = dbesc(implode(', ', $conversants));
        }
        // If the thread parent is OStatus then do some magic to distribute the messages.
        // We have not only to look at the parent, since it could be a Friendica thread.
        if ($thr_parent and $thr_parent[0]['network'] == NETWORK_OSTATUS or $parent['network'] == NETWORK_OSTATUS) {
            logger('Some parent is OStatus for ' . $target_item["guid"], LOGGER_DEBUG);
            // Send a salmon notification to every person we mentioned in the post
            $arr = explode(',', $target_item['tag']);
            foreach ($arr as $x) {
                //logger('Checking tag '.$x, LOGGER_DEBUG);
                $matches = null;
                if (preg_match('/@\\[url=([^\\]]*)\\]/', $x, $matches)) {
                    $probed_contact = probe_url($matches[1]);
                    if ($probed_contact["notify"] != "") {
                        logger('Notify mentioned user ' . $probed_contact["url"] . ': ' . $probed_contact["notify"]);
                        $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
                    }
                }
            }
            // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
            $sql_extra = " AND `network` IN ('" . NETWORK_OSTATUS . "', '" . NETWORK_DFRN . "')";
        } else {
            $sql_extra = "";
        }
        $r = q("SELECT * FROM `contact` WHERE `id` IN ({$conversant_str}) AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0" . $sql_extra);
        if (count($r)) {
            $contacts = $r;
        }
    }
    $feed_template = get_markup_template('atom_feed.tpl');
    $mail_template = get_markup_template('atom_mail.tpl');
    $atom = '';
    $slaps = array();
    $hubxml = feed_hublinks();
    $birthday = feed_birthday($owner['uid'], $owner['timezone']);
    if (strlen($birthday)) {
        $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
    }
    $atom .= replace_macros($feed_template, array('$version' => xmlify(FRIENDICA_VERSION), '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname']), '$feed_title' => xmlify($owner['name']), '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00', ATOM_TIME)), '$hub' => $hubxml, '$salmon' => '', '$name' => xmlify($owner['name']), '$profile_page' => xmlify($owner['url']), '$photo' => xmlify($owner['photo']), '$thumb' => xmlify($owner['thumb']), '$picdate' => xmlify(datetime_convert('UTC', 'UTC', $owner['avatar-date'] . '+00:00', ATOM_TIME)), '$uridate' => xmlify(datetime_convert('UTC', 'UTC', $owner['uri-date'] . '+00:00', ATOM_TIME)), '$namdate' => xmlify(datetime_convert('UTC', 'UTC', $owner['name-date'] . '+00:00', ATOM_TIME)), '$birthday' => $birthday, '$community' => $owner['page-flags'] == PAGE_COMMUNITY ? '<dfrn:community>1</dfrn:community>' : ''));
    if ($mail) {
        $public_message = false;
        // mail is  not public
        $body = fix_private_photos($item['body'], $owner['uid'], null, $message[0]['contact-id']);
        $atom .= replace_macros($mail_template, array('$name' => xmlify($owner['name']), '$profile_page' => xmlify($owner['url']), '$thumb' => xmlify($owner['thumb']), '$item_id' => xmlify($item['uri']), '$subject' => xmlify($item['title']), '$created' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00', ATOM_TIME)), '$content' => xmlify($body), '$parent_id' => xmlify($item['parent-uri'])));
    } elseif ($fsuggest) {
        $public_message = false;
        // suggestions are not public
        $sugg_template = get_markup_template('atom_suggest.tpl');
        $atom .= replace_macros($sugg_template, array('$name' => xmlify($item['name']), '$url' => xmlify($item['url']), '$photo' => xmlify($item['photo']), '$request' => xmlify($item['request']), '$note' => xmlify($item['note'])));
        // We don't need this any more
        q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
    } elseif ($relocate) {
        $public_message = false;
        // suggestions are not public
        $sugg_template = get_markup_template('atom_relocate.tpl');
        /* get site pubkey. this could be a new installation with no site keys*/
        $pubkey = get_config('system', 'site_pubkey');
        if (!$pubkey) {
            $res = new_keypair(1024);
            set_config('system', 'site_prvkey', $res['prvkey']);
            set_config('system', 'site_pubkey', $res['pubkey']);
        }
        $rp = q("SELECT `resource-id` , `scale`, type FROM `photo` \n\t\t\t\t\t\tWHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
        $photos = array();
        $ext = Photo::supportedTypes();
        foreach ($rp as $p) {
            $photos[$p['scale']] = $a->get_baseurl() . '/photo/' . $p['resource-id'] . '-' . $p['scale'] . '.' . $ext[$p['type']];
        }
        unset($rp, $ext);
        $atom .= replace_macros($sugg_template, array('$name' => xmlify($owner['name']), '$photo' => xmlify($photos[4]), '$thumb' => xmlify($photos[5]), '$micro' => xmlify($photos[6]), '$url' => xmlify($owner['url']), '$request' => xmlify($owner['request']), '$confirm' => xmlify($owner['confirm']), '$notify' => xmlify($owner['notify']), '$poll' => xmlify($owner['poll']), '$sitepubkey' => xmlify(get_config('system', 'site_pubkey'))));
        $recipients_relocate = q("SELECT * FROM contact WHERE uid = %d  AND self = 0 AND network = '%s'", intval($uid), NETWORK_DFRN);
        unset($photos);
    } else {
        $slap = ostatus_salmon($target_item, $owner);
        //$slap = atom_entry($target_item,'html',null,$owner,false);
        if ($followup) {
            foreach ($items as $item) {
                // there is only one item
                if (!$item['parent']) {
                    continue;
                }
                if ($item['id'] == $item_id) {
                    logger('notifier: followup: item: ' . print_r($item, true), LOGGER_DATA);
                    //$slap  = atom_entry($item,'html',null,$owner,false);
                    $atom .= atom_entry($item, 'text', null, $owner, false);
                }
            }
        } else {
            foreach ($items as $item) {
                if (!$item['parent']) {
                    continue;
                }
                // private emails may be in included in public conversations. Filter them.
                if ($public_message && $item['private'] == 1) {
                    continue;
                }
                $contact = get_item_contact($item, $contacts);
                if (!$contact) {
                    continue;
                }
                if ($normal_mode) {
                    // we only need the current item, but include the parent because without it
                    // older sites without a corresponding dfrn_notify change may do the wrong thing.
                    if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
                        $atom .= atom_entry($item, 'text', null, $owner, true);
                    }
                } else {
                    $atom .= atom_entry($item, 'text', null, $owner, true);
                }
                if ($top_level && $public_message && $item['author-link'] === $item['owner-link'] && !$expire) {
                    $slaps[] = ostatus_salmon($item, $owner);
                }
                //$slaps[] = atom_entry($item,'html',null,$owner,true);
            }
        }
    }
    $atom .= '</feed>' . "\r\n";
    logger('notifier: ' . $atom, LOGGER_DATA);
    logger('notifier: slaps: ' . print_r($slaps, true), LOGGER_DATA);
    // If this is a public message and pubmail is set on the parent, include all your email contacts
    $mail_disabled = function_exists('imap_open') && !get_config('system', 'imap_disabled') ? 0 : 1;
    if (!$mail_disabled) {
        if (!strlen($target_item['allow_cid']) && !strlen($target_item['allow_gid']) && !strlen($target_item['deny_cid']) && !strlen($target_item['deny_gid']) && intval($target_item['pubmail'])) {
            $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `network` = '%s'", intval($uid), dbesc(NETWORK_MAIL));
            if (count($r)) {
                foreach ($r as $rr) {
                    $recipients[] = $rr['id'];
                }
            }
        }
    }
    if ($followup) {
        $recip_str = $parent['contact-id'];
    } else {
        $recip_str = implode(', ', $recipients);
    }
    if ($relocate) {
        $r = $recipients_relocate;
    } else {
        $r = q("SELECT * FROM `contact` WHERE `id` IN ( %s ) AND `blocked` = 0 AND `pending` = 0 ", dbesc($recip_str));
    }
    require_once 'include/salmon.php';
    $interval = get_config('system', 'delivery_interval') === false ? 2 : intval(get_config('system', 'delivery_interval'));
    // If we are using the worker we don't need a delivery interval
    if (get_config("system", "worker")) {
        $interval = false;
    }
    // delivery loop
    if (count($r)) {
        foreach ($r as $contact) {
            if (!$mail && !$fsuggest && !$followup && !$relocate && !$contact['self']) {
                if ($contact['network'] === NETWORK_DIASPORA && $public_message) {
                    continue;
                }
                q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )", dbesc($cmd), intval($item_id), intval($contact['id']));
            }
        }
        // This controls the number of deliveries to execute with each separate delivery process.
        // By default we'll perform one delivery per process. Assuming a hostile shared hosting
        // provider, this provides the greatest chance of deliveries if processes start getting
        // killed. We can also space them out with the delivery_interval to also help avoid them
        // getting whacked.
        // If $deliveries_per_process > 1, we will chain this number of multiple deliveries
        // together into a single process. This will reduce the overall number of processes
        // spawned for each delivery, but they will run longer.
        // When using the workerqueue, we don't need this functionality.
        $deliveries_per_process = intval(get_config('system', 'delivery_batch_count'));
        if ($deliveries_per_process <= 0 or get_config("system", "worker")) {
            $deliveries_per_process = 1;
        }
        $this_batch = array();
        for ($x = 0; $x < count($r); $x++) {
            $contact = $r[$x];
            if ($contact['self']) {
                continue;
            }
            logger("Deliver " . $target_item["guid"] . " to " . $contact['url'], LOGGER_DEBUG);
            // potentially more than one recipient. Start a new process and space them out a bit.
            // we will deliver single recipient types of message and email recipients here.
            if (!$mail && !$fsuggest && !$relocate && !$followup) {
                $this_batch[] = $contact['id'];
                if (count($this_batch) == $deliveries_per_process) {
                    proc_run('php', 'include/delivery.php', $cmd, $item_id, $this_batch);
                    $this_batch = array();
                    if ($interval) {
                        @time_sleep_until(microtime(true) + (double) $interval);
                    }
                }
                continue;
            }
            // be sure to pick up any stragglers
            if (count($this_batch)) {
                proc_run('php', 'include/delivery.php', $cmd, $item_id, $this_batch);
            }
            $deliver_status = 0;
            logger("main delivery by notifier: followup={$followup} mail={$mail} fsuggest={$fsuggest} relocate={$relocate}");
            switch ($contact['network']) {
                case NETWORK_DFRN:
                    // perform local delivery if we are on the same site
                    $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
                    if (link_compare($basepath, $a->get_baseurl())) {
                        $nickname = basename($contact['url']);
                        if ($contact['issued-id']) {
                            $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
                        } else {
                            $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
                        }
                        $x = q("SELECT\t`contact`.*, `contact`.`uid` AS `importer_uid`,\n\t\t\t\t\t\t\t`contact`.`pubkey` AS `cpubkey`,\n\t\t\t\t\t\t\t`contact`.`prvkey` AS `cprvkey`,\n\t\t\t\t\t\t\t`contact`.`thumb` AS `thumb`,\n\t\t\t\t\t\t\t`contact`.`url` as `url`,\n\t\t\t\t\t\t\t`contact`.`name` as `senderName`,\n\t\t\t\t\t\t\t`user`.*\n\t\t\t\t\t\t\tFROM `contact`\n\t\t\t\t\t\t\tINNER JOIN `user` ON `contact`.`uid` = `user`.`uid`\n\t\t\t\t\t\t\tWHERE `contact`.`blocked` = 0 AND `contact`.`archive` = 0\n\t\t\t\t\t\t\tAND `contact`.`pending` = 0\n\t\t\t\t\t\t\tAND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'\n\t\t\t\t\t\t\t{$sql_extra}\n\t\t\t\t\t\t\tAND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1", dbesc(NETWORK_DFRN), dbesc($nickname));
                        if ($x && count($x)) {
                            $write_flag = $x[0]['rel'] && $x[0]['rel'] != CONTACT_IS_SHARING ? true : false;
                            if (($owner['page-flags'] == PAGE_COMMUNITY || $write_flag) && !$x[0]['writable']) {
                                q("update contact set writable = 1 where id = %d", intval($x[0]['id']));
                                $x[0]['writable'] = 1;
                            }
                            // if contact's ssl policy changed, which we just determined
                            // is on our own server, update our contact links
                            $ssl_policy = get_config('system', 'ssl_policy');
                            fix_contact_ssl_policy($x[0], $ssl_policy);
                            // If we are setup as a soapbox we aren't accepting top level posts from this person
                            if ($x[0]['page-flags'] == PAGE_SOAPBOX and $top_level) {
                                break;
                            }
                            require_once 'library/simplepie/simplepie.inc';
                            logger('mod-delivery: local delivery');
                            local_delivery($x[0], $atom);
                            break;
                        }
                    }
                    logger('notifier: dfrndelivery: ' . $contact['name']);
                    $deliver_status = dfrn_deliver($owner, $contact, $atom);
                    logger('notifier: dfrn_delivery returns ' . $deliver_status);
                    if ($deliver_status == -1) {
                        logger('notifier: delivery failed: queuing message');
                        // queue message for redelivery
                        add_to_queue($contact['id'], NETWORK_DFRN, $atom);
                    }
                    break;
                case NETWORK_OSTATUS:
                    // Do not send to ostatus if we are not configured to send to public networks
                    if ($owner['prvnets']) {
                        break;
                    }
                    if (get_config('system', 'ostatus_disabled') || get_config('system', 'dfrn_only')) {
                        break;
                    }
                    if ($followup && $contact['notify']) {
                        logger('slapdelivery followup item ' . $item_id . ' to ' . $contact['name']);
                        $deliver_status = slapper($owner, $contact['notify'], $slap);
                        if ($deliver_status == -1) {
                            // queue message for redelivery
                            add_to_queue($contact['id'], NETWORK_OSTATUS, $slap);
                        }
                    } else {
                        // only send salmon if public - e.g. if it's ok to notify
                        // a public hub, it's ok to send a salmon
                        if (count($slaps) && $public_message && !$expire) {
                            logger('slapdelivery item ' . $item_id . ' to ' . $contact['name']);
                            foreach ($slaps as $slappy) {
                                if ($contact['notify']) {
                                    $deliver_status = slapper($owner, $contact['notify'], $slappy);
                                    if ($deliver_status == -1) {
                                        // queue message for redelivery
                                        add_to_queue($contact['id'], NETWORK_OSTATUS, $slappy);
                                    }
                                }
                            }
                        }
                    }
                    break;
                case NETWORK_MAIL:
                case NETWORK_MAIL2:
                    if (get_config('system', 'dfrn_only')) {
                        break;
                    }
                    // WARNING: does not currently convert to RFC2047 header encodings, etc.
                    $addr = $contact['addr'];
                    if (!strlen($addr)) {
                        break;
                    }
                    if ($cmd === 'wall-new' || $cmd === 'comment-new') {
                        $it = null;
                        if ($cmd === 'wall-new') {
                            $it = $items[0];
                        } else {
                            $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($argv[2]), intval($uid));
                            if (count($r)) {
                                $it = $r[0];
                            }
                        }
                        if (!$it) {
                            break;
                        }
                        $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
                        if (!count($local_user)) {
                            break;
                        }
                        $reply_to = '';
                        $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1", intval($uid));
                        if ($r1 && $r1[0]['reply_to']) {
                            $reply_to = $r1[0]['reply_to'];
                        }
                        $subject = $it['title'] ? email_header_encode($it['title'], 'UTF-8') : t("(no subject)");
                        // only expose our real email address to true friends
                        if ($contact['rel'] == CONTACT_IS_FRIEND && !$contact['blocked']) {
                            if ($reply_to) {
                                $headers = 'From: ' . email_header_encode($local_user[0]['username'], 'UTF-8') . ' <' . $reply_to . '>' . "\n";
                                $headers .= 'Sender: ' . $local_user[0]['email'] . "\n";
                            } else {
                                $headers = 'From: ' . email_header_encode($local_user[0]['username'], 'UTF-8') . ' <' . $local_user[0]['email'] . '>' . "\n";
                            }
                        } else {
                            $headers = 'From: ' . email_header_encode($local_user[0]['username'], 'UTF-8') . ' <' . t('noreply') . '@' . $a->get_hostname() . '>' . "\n";
                        }
                        //if($reply_to)
                        //	$headers .= 'Reply-to: ' . $reply_to . "\n";
                        $headers .= 'Message-Id: <' . iri2msgid($it['uri']) . '>' . "\n";
                        if ($it['uri'] !== $it['parent-uri']) {
                            $headers .= "References: <" . iri2msgid($it["parent-uri"]) . ">";
                            // If Threading is enabled, write down the correct parent
                            if ($it["thr-parent"] != "" and $it["thr-parent"] != $it["parent-uri"]) {
                                $headers .= " <" . iri2msgid($it["thr-parent"]) . ">";
                            }
                            $headers .= "\n";
                            if (!$it['title']) {
                                $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($it['parent-uri']), intval($uid));
                                if (count($r) and $r[0]['title'] != '') {
                                    $subject = $r[0]['title'];
                                } else {
                                    $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($it['parent-uri']), intval($uid));
                                    if (count($r) and $r[0]['title'] != '') {
                                        $subject = $r[0]['title'];
                                    }
                                }
                            }
                            if (strncasecmp($subject, 'RE:', 3)) {
                                $subject = 'Re: ' . $subject;
                            }
                        }
                        email_send($addr, $subject, $headers, $it);
                    }
                    break;
                case NETWORK_DIASPORA:
                    if (get_config('system', 'dfrn_only') || !get_config('system', 'diaspora_enabled')) {
                        break;
                    }
                    if ($mail) {
                        diaspora_send_mail($item, $owner, $contact);
                        break;
                    }
                    if (!$normal_mode) {
                        break;
                    }
                    // special handling for followup to public post
                    // all other public posts processed as public batches further below
                    if ($public_message) {
                        if ($followup) {
                            diaspora_send_followup($target_item, $owner, $contact, true);
                        }
                        break;
                    }
                    if (!$contact['pubkey']) {
                        break;
                    }
                    $unsupported_activities = array(ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE);
                    //don't transmit activities which are not supported by diaspora
                    foreach ($unsupported_activities as $act) {
                        if (activity_match($target_item['verb'], $act)) {
                            break 2;
                        }
                    }
                    if ($target_item['deleted'] && ($target_item['uri'] === $target_item['parent-uri'] || $followup)) {
                        // send both top-level retractions and relayable retractions for owner to relay
                        diaspora_send_retraction($target_item, $owner, $contact);
                        break;
                    } elseif ($followup) {
                        // send comments and likes to owner to relay
                        diaspora_send_followup($target_item, $owner, $contact);
                        break;
                    } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
                        // we are the relay - send comments, likes and relayable_retractions
                        // (of comments and likes) to our conversants
                        diaspora_send_relay($target_item, $owner, $contact);
                        break;
                    } elseif ($top_level && !$walltowall) {
                        // currently no workable solution for sending walltowall
                        diaspora_send_status($target_item, $owner, $contact);
                        break;
                    }
                    break;
                case NETWORK_FEED:
                case NETWORK_FACEBOOK:
                    if (get_config('system', 'dfrn_only')) {
                        break;
                    }
                case NETWORK_PUMPIO:
                    if (get_config('system', 'dfrn_only')) {
                        break;
                    }
                default:
                    break;
            }
        }
    }
    // send additional slaps to mentioned remote tags (@foo@example.com)
    //if($slap && count($url_recipients) && ($followup || $top_level) && ($public_message || $push_notify) && (! $expire)) {
    if ($slap && count($url_recipients) && ($public_message || $push_notify) && !$expire) {
        if (!get_config('system', 'dfrn_only')) {
            foreach ($url_recipients as $url) {
                if ($url) {
                    logger('notifier: urldelivery: ' . $url);
                    $deliver_status = slapper($owner, $url, $slap);
                    // TODO: redeliver/queue these items on failure, though there is no contact record
                }
            }
        }
    }
    if ($public_message) {
        if (!$followup) {
            $r0 = diaspora_fetch_relay();
        } else {
            $r0 = array();
        }
        $r1 = q("SELECT DISTINCT(`batch`), `id`, `name`,`network` FROM `contact` WHERE `network` = '%s'\n\t\t\tAND `uid` = %d AND `rel` != %d group by `batch` ORDER BY rand() ", dbesc(NETWORK_DIASPORA), intval($owner['uid']), intval(CONTACT_IS_SHARING));
        $r2 = q("SELECT `id`, `name`,`network` FROM `contact`\n\t\t\tWHERE `network` in ( '%s', '%s')  AND `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0\n\t\t\tAND `rel` != %d order by rand() ", dbesc(NETWORK_DFRN), dbesc(NETWORK_MAIL2), intval($owner['uid']), intval(CONTACT_IS_SHARING));
        $r = array_merge($r2, $r1, $r0);
        if (count($r)) {
            logger('pubdeliver: ' . print_r($r, true), LOGGER_DEBUG);
            // throw everything into the queue in case we get killed
            foreach ($r as $rr) {
                if (!$mail && !$fsuggest && !$followup) {
                    q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )", dbesc($cmd), intval($item_id), intval($rr['id']));
                }
            }
            foreach ($r as $rr) {
                // except for Diaspora batch jobs
                // Don't deliver to folks who have already been delivered to
                if ($rr['network'] !== NETWORK_DIASPORA && in_array($rr['id'], $conversants)) {
                    logger('notifier: already delivered id=' . $rr['id']);
                    continue;
                }
                if (!$mail && !$fsuggest && !$followup) {
                    logger('notifier: delivery agent: ' . $rr['name'] . ' ' . $rr['id']);
                    proc_run('php', 'include/delivery.php', $cmd, $item_id, $rr['id']);
                    if ($interval) {
                        @time_sleep_until(microtime(true) + (double) $interval);
                    }
                }
            }
        }
        $push_notify = true;
    }
    if ($push_notify and strlen($hub)) {
        $hubs = explode(',', $hub);
        if (count($hubs)) {
            foreach ($hubs as $h) {
                $h = trim($h);
                if (!strlen($h)) {
                    continue;
                }
                if ($h === '[internal]') {
                    // Set push flag for PuSH subscribers to this topic,
                    // they will be notified in queue.php
                    q("UPDATE `push_subscriber` SET `push` = 1 " . "WHERE `nickname` = '%s'", dbesc($owner['nickname']));
                    logger('Activating internal PuSH for item ' . $item_id, LOGGER_DEBUG);
                } else {
                    $params = 'hub.mode=publish&hub.url=' . urlencode($a->get_baseurl() . '/dfrn_poll/' . $owner['nickname']);
                    post_url($h, $params);
                    logger('publish for item ' . $item_id . ' ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
                }
                if (count($hubs) > 1) {
                    sleep(7);
                }
                // try and avoid multiple hubs responding at precisely the same time
            }
        }
        // Handling the pubsubhubbub requests
        proc_run('php', 'include/pubsubpublish.php');
    }
    // If the item was deleted, clean up the `sign` table
    if ($target_item['deleted']) {
        $r = q("DELETE FROM sign where `retract_iid` = %d", intval($target_item['id']));
    }
    logger('notifier: calling hooks', LOGGER_DEBUG);
    if ($normal_mode) {
        call_hooks('notifier_normal', $target_item);
    }
    call_hooks('notifier_end', $target_item);
    return;
}
Example #8
0
function network_content(&$a, $update = false)
{
    if (!local_user()) {
        return;
    }
    require_once "include/bbcode.php";
    $contact_id = $a->cid;
    $group = 0;
    if (!$update) {
        // pull out the group here because the updater might have different args
        if ($a->argc > 1) {
            $group = intval($a->argv[1]);
        }
        $_SESSION['return_url'] = $a->cmd;
        $tpl = file_get_contents('view/jot-header.tpl');
        $a->page['htmlhead'] .= replace_macros($tpl, array('$baseurl' => $a->get_baseurl()));
        require_once 'view/acl_selectors.php';
        $tpl = file_get_contents("view/jot.tpl");
        $o .= replace_macros($tpl, array('$return_path' => $a->cmd, '$baseurl' => $a->get_baseurl(), '$defloc' => $a->user['default-location'], '$visitor' => 'block', '$lockstate' => 'unlock', '$acl' => populate_acl($a->user), '$profile_uid' => $_SESSION['uid']));
        // The special div is needed for liveUpdate to kick in for this page.
        // We only launch liveUpdate if you are on the front page, you aren't
        // filtering by group and also you aren't writing a comment (the last
        // criteria is discovered in javascript).
        if ($a->pager['start'] == 0 && $a->argc == 1) {
            $o .= '<div id="live-network"></div>' . "\r\n";
        }
    }
    // We aren't going to try and figure out at the item, group, and page level
    // which items you've seen and which you haven't. You're looking at some
    // subset of items, so just mark everything seen.
    $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` = 1 ");
    // 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_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` AND `type` IN ('wall', 'photo', 'remote' )) ";
    $sql_extra = '';
    if ($group) {
        $r = q("SELECT `name`, `id` FROM `group` WHERE `id` = %d LIMIT 1", intval($group));
        if (!count($r)) {
            notice(t('No such group') . EOL);
            goaway($a->get_baseurl() . '/network');
            return;
            // NOTREACHED
        }
        $contacts = expand_groups(array($group));
        $contact_str = implode(',', $contacts);
        $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` AND `type` IN ('wall', 'photo', 'remote') AND `contact-id` IN ( {$contact_str} )) ";
        $o = '<h4>' . t('Group: ') . $r[0]['name'] . '</h4>' . $o;
    }
    $r = q("SELECT COUNT(*) AS `total`\n\t\tFROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\tWHERE `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t{$sql_extra} ");
    if (count($r)) {
        $a->set_pager_total($r[0]['total']);
    }
    $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, \n\t\t`contact`.`name`, `contact`.`photo`, `contact`.`url`, \n\t\t`contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`, \n\t\t`contact`.`id` AS `cid`\n\t\tFROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\tWHERE `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t{$sql_extra}\n\t\tORDER BY `parent` DESC, `created` ASC LIMIT %d ,%d ", intval($a->pager['start']), intval($a->pager['itemspage']));
    $cmnt_tpl = file_get_contents('view/comment_item.tpl');
    $tpl = file_get_contents('view/wall_item.tpl');
    $wallwall = file_get_contents('view/wallwall_item.tpl');
    if (count($r)) {
        foreach ($r as $item) {
            $comment = '';
            $template = $tpl;
            $commentww = '';
            $profile_url = $item['url'];
            $redirect_url = $a->get_baseurl() . '/redir/' . $item['cid'];
            // Top-level wall post not written by the wall owner (wall-to-wall)
            // First figure out who owns it.
            if ($item['parent'] == $item['item_id'] && !$item['self']) {
                if ($item['type'] == 'wall') {
                    // I do. Put me on the left of the wall-to-wall notice.
                    $owner_url = $a->contact['url'];
                    $owner_photo = $a->contact['thumb'];
                    $owner_name = $a->contact['name'];
                    $template = $wallwall;
                    $commentww = 'ww';
                }
                if ($item['type'] == 'remote' && $item['owner-link'] != $item['author-link']) {
                    // Could be anybody.
                    $owner_url = $item['owner-link'];
                    $owner_photo = $item['owner-avatar'];
                    $owner_name = $item['owner-name'];
                    $template = $wallwall;
                    $commentww = 'ww';
                    // If it is our contact, use a friendly redirect link
                    if ($item['owner-link'] == $item['url'] && ($item['rel'] == DIRECTION_IN || $item['rel'] == DIRECTION_BOTH)) {
                        $owner_url = $redirect_url;
                    }
                }
            }
            if ($update) {
                $return_url = $_SESSION['return_url'];
            } else {
                $return_url = $_SESSION['return_url'] = $a->cmd;
            }
            if ($item['last-child']) {
                $comment = replace_macros($cmnt_tpl, array('$return_path' => $_SESSION['return_url'], '$type' => 'net-comment', '$id' => $item['item_id'], '$parent' => $item['parent'], '$profile_uid' => $_SESSION['uid'], '$mylink' => $a->contact['url'], '$mytitle' => t('Me'), '$myphoto' => $a->contact['thumb'], '$ww' => $commentww));
            }
            $drop = replace_macros(file_get_contents('view/wall_item_drop.tpl'), array('$id' => $item['id']));
            if (strlen($item['dfrn-id']) && !$item['self']) {
                $profile_url = $redirect_url;
            }
            $photo = $item['photo'];
            $thumb = $item['thumb'];
            // Post was remotely authored.
            $profile_name = strlen($item['author-name']) ? $item['author-name'] : $item['name'];
            $profile_avatar = strlen($item['author-avatar']) ? $item['author-avatar'] : $thumb;
            $profile_link = $profile_url;
            // Can we use our special contact URL for this author?
            if (strlen($item['author-link'])) {
                if ($item['author-link'] == $item['url'] && ($item['rel'] == DIRECTION_IN || $item['rel'] == DIRECTION_BOTH)) {
                    $profile_link = $redirect_url;
                } else {
                    $profile_link = $item['author-link'];
                }
            }
            // Build the HTML
            $o .= replace_macros($template, array('$id' => $item['item_id'], '$profile_url' => $profile_link, '$name' => $profile_name, '$thumb' => $profile_avatar, '$title' => $item['title'], '$body' => bbcode($item['body']), '$ago' => relative_date($item['created']), '$location' => $item['location'] ? '<a target="map" href="http://maps.google.com/?q=' . urlencode($item['location']) . '">' . $item['location'] . '</a>' : '', '$indent' => $item['parent'] != $item['item_id'] ? ' comment' : '', '$owner_url' => $owner_url, '$owner_photo' => $owner_photo, '$owner_name' => $owner_name, '$drop' => $drop, '$comment' => $comment));
        }
    }
    if (!$update) {
        $o .= paginate($a);
    }
    return $o;
}
Example #9
0
} else {
    killme();
}
if ($cmd != 'mail') {
    require_once 'include/group.php';
    $parent = $items[0];
    if ($parent['type'] == 'remote') {
        // local followup to remote post
        $followup = true;
        $conversant_str = dbesc($parent['contact-id']);
    } else {
        $followup = false;
        $allow_people = expand_acl($parent['allow_cid']);
        $allow_groups = expand_groups(expand_acl($parent['allow_gid']));
        $deny_people = expand_acl($parent['deny_cid']);
        $deny_groups = expand_groups(expand_acl($parent['deny_gid']));
        $conversants = array();
        foreach ($items as $item) {
            $recipients[] = $item['contact-id'];
            $conversants[] = $item['contact-id'];
        }
        $conversants = array_unique($conversants, SORT_NUMERIC);
        $recipients = array_unique(array_merge($recipients, $allow_people, $allow_groups), SORT_NUMERIC);
        $deny = array_unique(array_merge($deny_people, $deny_groups), SORT_NUMERIC);
        $recipients = array_diff($recipients, $deny);
        $conversant_str = dbesc(implode(', ', $conversants));
    }
    $r = q("SELECT * FROM `contact` WHERE `id` IN ( {$conversant_str} ) AND `blocked` = 0 AND `pending` = 0");
    if (!count($r)) {
        killme();
    }
Example #10
0
/**
 * @param App $a
 * @param object $b
 * @return mixed
 */
function facebook_post_hook(&$a, &$b)
{
    if ($b['deleted'] || $b['created'] !== $b['edited']) {
        return;
    }
    /**
     * Post to Facebook stream
     */
    require_once 'include/group.php';
    require_once 'include/html2plain.php';
    logger('Facebook post');
    $reply = false;
    $likes = false;
    $deny_arr = array();
    $allow_arr = array();
    $toplevel = $b['id'] == $b['parent'] ? true : false;
    $linking = get_pconfig($b['uid'], 'facebook', 'no_linking') ? 0 : 1;
    if (!$toplevel && $linking) {
        $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($b['parent']), intval($b['uid']));
        if (count($r) && substr($r[0]['uri'], 0, 4) === 'fb::') {
            $reply = substr($r[0]['uri'], 4);
        } elseif (count($r) && substr($r[0]['extid'], 0, 4) === 'fb::') {
            $reply = substr($r[0]['extid'], 4);
        } else {
            return;
        }
        $u = q("SELECT * FROM user where uid = %d limit 1", intval($b['uid']));
        if (!count($u)) {
            return;
        }
        // only accept comments from the item owner. Other contacts are unknown to FB.
        if (!link_compare($b['author-link'], $a->get_baseurl() . '/profile/' . $u[0]['nickname'])) {
            return;
        }
        logger('facebook reply id=' . $reply);
    }
    if (strstr($b['postopts'], 'facebook') || $b['private'] || $reply) {
        if ($b['private'] && $reply === false) {
            $allow_people = expand_acl($b['allow_cid']);
            $allow_groups = expand_groups(expand_acl($b['allow_gid']));
            $deny_people = expand_acl($b['deny_cid']);
            $deny_groups = expand_groups(expand_acl($b['deny_gid']));
            $recipients = array_unique(array_merge($allow_people, $allow_groups));
            $deny = array_unique(array_merge($deny_people, $deny_groups));
            $allow_str = dbesc(implode(', ', $recipients));
            if ($allow_str) {
                $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( {$allow_str} ) AND `network` = 'face'");
                if (count($r)) {
                    foreach ($r as $rr) {
                        $allow_arr[] = $rr['notify'];
                    }
                }
            }
            $deny_str = dbesc(implode(', ', $deny));
            if ($deny_str) {
                $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( {$deny_str} ) AND `network` = 'face'");
                if (count($r)) {
                    foreach ($r as $rr) {
                        $deny_arr[] = $rr['notify'];
                    }
                }
            }
            if (count($deny_arr) && !count($allow_arr)) {
                // One or more FB folks were denied access but nobody on FB was specifically allowed access.
                // This might cause the post to be open to public on Facebook, but only to selected members
                // on another network. Since this could potentially leak a post to somebody who was denied,
                // we will skip posting it to Facebook with a slightly vague but relevant message that will
                // hopefully lead somebody to this code comment for a better explanation of what went wrong.
                notice(t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL);
                return;
            }
            // if it's a private message but no Facebook members are allowed or denied, skip Facebook post
            if (!count($allow_arr) && !count($deny_arr)) {
                return;
            }
        }
        if ($b['verb'] == ACTIVITY_LIKE) {
            $likes = true;
        }
        $appid = get_config('facebook', 'appid');
        $secret = get_config('facebook', 'appsecret');
        if ($appid && $secret) {
            logger('facebook: have appid+secret');
            $fb_token = get_pconfig($b['uid'], 'facebook', 'access_token');
            // post to facebook if it's a public post and we've ticked the 'post to Facebook' box,
            // or it's a private message with facebook participants
            // or it's a reply or likes action to an existing facebook post
            if ($fb_token && ($toplevel || $b['private'] || $reply)) {
                logger('facebook: able to post');
                require_once 'library/facebook.php';
                require_once 'include/bbcode.php';
                $msg = $b['body'];
                logger('Facebook post: original msg=' . $msg, LOGGER_DATA);
                // make links readable before we strip the code
                // unless it's a dislike - just send the text as a comment
                // if($b['verb'] == ACTIVITY_DISLIKE)
                //	$msg = trim(strip_tags(bbcode($msg)));
                // Old code
                /*$search_str = $a->get_baseurl() . '/search';
                
                				if(preg_match("/\[url=(.*?)\](.*?)\[\/url\]/is",$msg,$matches)) {
                
                					// don't use hashtags for message link
                
                					if(strpos($matches[2],$search_str) === false) {
                						$link = $matches[1];
                						if(substr($matches[2],0,5) != '[img]')
                							$linkname = $matches[2];
                					}
                				}
                
                				// strip tag links to avoid link clutter, this really should be 
                				// configurable because we're losing information
                
                				$msg = preg_replace("/\#\[url=(.*?)\](.*?)\[\/url\]/is",'#$2',$msg);
                
                				// provide the link separately for normal links
                				$msg = preg_replace("/\[url=(.*?)\](.*?)\[\/url\]/is",'$2 $1',$msg);
                
                				if(preg_match("/\[img\](.*?)\[\/img\]/is",$msg,$matches))
                					$image = $matches[1];
                
                				$msg = preg_replace("/\[img\](.*?)\[\/img\]/is", t('Image: ') . '$1', $msg);
                
                				if((strpos($link,z_root()) !== false) && (! $image))
                					$image = $a->get_baseurl() . '/images/friendica-64.jpg';
                
                				$msg = trim(strip_tags(bbcode($msg)));*/
                // New code
                // Looking for the first image
                $image = '';
                if (preg_match("/\\[img\\=([0-9]*)x([0-9]*)\\](.*?)\\[\\/img\\]/is", $b['body'], $matches)) {
                    $image = $matches[3];
                }
                if ($image == '') {
                    if (preg_match("/\\[img\\](.*?)\\[\\/img\\]/is", $b['body'], $matches)) {
                        $image = $matches[1];
                    }
                }
                // Checking for a bookmark element
                $body = $b['body'];
                if (strpos($body, "[bookmark") !== false) {
                    // splitting the text in two parts:
                    // before and after the bookmark
                    $pos = strpos($body, "[bookmark");
                    $body1 = substr($body, 0, $pos);
                    $body2 = substr($body, $pos);
                    // Removing the bookmark and all quotes after the bookmark
                    // they are mostly only the content after the bookmark.
                    $body2 = preg_replace("/\\[bookmark\\=([^\\]]*)\\](.*?)\\[\\/bookmark\\]/ism", '', $body2);
                    $body2 = preg_replace("/\\[quote\\=([^\\]]*)\\](.*?)\\[\\/quote\\]/ism", '', $body2);
                    $body2 = preg_replace("/\\[quote\\](.*?)\\[\\/quote\\]/ism", '', $body2);
                    $body = $body1 . $body2;
                }
                // At first convert the text to html
                $html = bbcode($body);
                // Then convert it to plain text
                $msg = trim($b['title'] . " \n\n" . html2plain($html, 0, true));
                $msg = html_entity_decode($msg, ENT_QUOTES, 'UTF-8');
                // Removing multiple newlines
                while (strpos($msg, "\n\n\n") !== false) {
                    $msg = str_replace("\n\n\n", "\n\n", $msg);
                }
                // add any attachments as text urls
                $arr = explode(',', $b['attach']);
                if (count($arr)) {
                    $msg .= "\n";
                    foreach ($arr as $r) {
                        $matches = false;
                        $cnt = preg_match('|\\[attach\\]href=\\"(.*?)\\" size=\\"(.*?)\\" type=\\"(.*?)\\" title=\\"(.*?)\\"\\[\\/attach\\]|', $r, $matches);
                        if ($cnt) {
                            $msg .= "\n" . $matches[1];
                        }
                    }
                }
                $link = '';
                $linkname = '';
                // look for bookmark-bbcode and handle it with priority
                if (preg_match("/\\[bookmark\\=([^\\]]*)\\](.*?)\\[\\/bookmark\\]/is", $b['body'], $matches)) {
                    $link = $matches[1];
                    $linkname = $matches[2];
                }
                // If there is no bookmark element then take the first link
                if ($link == '') {
                    $links = collecturls($html);
                    if (sizeof($links) > 0) {
                        reset($links);
                        $link = current($links);
                    }
                }
                // Remove trailing and leading spaces
                $msg = trim($msg);
                // Since facebook increased the maxpostlen massively this never should happen again :)
                if (strlen($msg) > FACEBOOK_MAXPOSTLEN) {
                    require_once 'library/slinky.php';
                    $display_url = $b['plink'];
                    $slinky = new Slinky($display_url);
                    // setup a cascade of shortening services
                    // try to get a short link from these services
                    // in the order ur1.ca, trim, id.gd, tinyurl
                    $slinky->set_cascade(array(new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
                    $shortlink = $slinky->short();
                    // the new message will be shortened such that "... $shortlink"
                    // will fit into the character limit
                    $msg = substr($msg, 0, FACEBOOK_MAXPOSTLEN - strlen($shortlink) - 4);
                    $msg .= '... ' . $shortlink;
                }
                // Fallback - if message is empty
                if (!strlen($msg)) {
                    $msg = $link;
                }
                if (!strlen($msg)) {
                    $msg = $image;
                }
                if (!strlen($msg)) {
                    $msg = $linkname;
                }
                // If there is nothing to post then exit
                if (!strlen($msg)) {
                    return;
                }
                logger('Facebook post: msg=' . $msg, LOGGER_DATA);
                if ($likes) {
                    $postvars = array('access_token' => $fb_token);
                } else {
                    $postvars = array('access_token' => $fb_token, 'message' => $msg);
                    if (isset($image)) {
                        $postvars['picture'] = $image;
                        //$postvars['type'] = "photo";
                    }
                    if (isset($link)) {
                        $postvars['link'] = $link;
                        //$postvars['type'] = "link";
                    }
                    if (isset($linkname)) {
                        $postvars['name'] = $linkname;
                    }
                }
                if ($b['private'] && $toplevel) {
                    $postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"';
                    if (count($allow_arr)) {
                        $postvars['privacy'] .= ',"allow": "' . implode(',', $allow_arr) . '"';
                    }
                    if (count($deny_arr)) {
                        $postvars['privacy'] .= ',"deny": "' . implode(',', $deny_arr) . '"';
                    }
                    $postvars['privacy'] .= '}';
                }
                if ($reply) {
                    $url = 'https://graph.facebook.com/' . $reply . '/' . ($likes ? 'likes' : 'comments');
                } else {
                    if ($link != "" or $image != "" or $b['title'] == '' or strlen($msg) < 500) {
                        $url = 'https://graph.facebook.com/me/feed';
                        if ($b['plink']) {
                            $postvars['actions'] = '{"name": "' . t('View on Friendica') . '", "link": "' . $b['plink'] . '"}';
                        }
                    } else {
                        // if its only a message and a subject and the message is larger than 500 characters then post it as note
                        $postvars = array('access_token' => $fb_token, 'message' => bbcode($b['body']), 'subject' => $b['title']);
                        $url = 'https://graph.facebook.com/me/notes';
                    }
                }
                logger('facebook: post to ' . $url);
                logger('facebook: postvars: ' . print_r($postvars, true));
                // "test_mode" prevents anything from actually being posted.
                // Otherwise, let's do it.
                if (!get_config('facebook', 'test_mode')) {
                    $x = post_url($url, $postvars);
                    logger('Facebook post returns: ' . $x, LOGGER_DEBUG);
                    $retj = json_decode($x);
                    if ($retj->id) {
                        q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1", dbesc('fb::' . $retj->id), intval($b['id']));
                    } else {
                        if (!$likes) {
                            $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars));
                            require_once 'include/queue_fn.php';
                            add_to_queue($a->contact, NETWORK_FACEBOOK, $s);
                            notice(t('Facebook post failed. Queued for retry.') . EOL);
                        }
                        if (isset($retj->error) && $retj->error->type == "OAuthException" && $retj->error->code == 190) {
                            logger('Facebook session has expired due to changed password.', LOGGER_DEBUG);
                            $last_notification = get_pconfig($b['uid'], 'facebook', 'session_expired_mailsent');
                            if (!$last_notification || $last_notification < time() - FACEBOOK_SESSION_ERR_NOTIFICATION_INTERVAL) {
                                require_once 'include/enotify.php';
                                $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid']));
                                notification(array('uid' => $b['uid'], 'type' => NOTIFY_SYSTEM, 'system_type' => 'facebook_connection_invalid', 'language' => $r[0]['language'], 'to_name' => $r[0]['username'], 'to_email' => $r[0]['email'], 'source_name' => t('Administrator'), 'source_link' => $a->config["system"]["url"], 'source_photo' => $a->config["system"]["url"] . '/images/person-80.jpg'));
                                set_pconfig($b['uid'], 'facebook', 'session_expired_mailsent', time());
                            } else {
                                logger('Facebook: No notification, as the last one was sent on ' . $last_notification, LOGGER_DEBUG);
                            }
                        }
                    }
                }
            }
        }
    }
}
Example #11
0
function network_content(&$a, $update = 0)
{
    require_once 'include/conversation.php';
    if (!local_user()) {
        $_SESSION['return_url'] = $a->query_string;
        return login(false);
    }
    $arr = array('query' => $a->query_string);
    call_hooks('network_content_init', $arr);
    $o = '';
    // item filter tabs
    // TODO: fix this logic, reduce duplication
    //$a->page['content'] .= '<div class="tabs-wrapper">';
    $starred_active = '';
    $new_active = '';
    $bookmarked_active = '';
    $all_active = '';
    $search_active = '';
    $conv_active = '';
    $spam_active = '';
    if ($a->argc > 1 && $a->argv[1] === 'new' || $a->argc > 2 && $a->argv[2] === 'new') {
        $new_active = 'active';
    }
    if (x($_GET, 'search')) {
        $search_active = 'active';
    }
    if (x($_GET, 'star')) {
        $starred_active = 'active';
    }
    if (x($_GET, 'bmark')) {
        $bookmarked_active = 'active';
    }
    if (x($_GET, 'conv')) {
        $conv_active = 'active';
    }
    if (x($_GET, 'spam')) {
        $spam_active = 'active';
    }
    if ($new_active == '' && $starred_active == '' && $bookmarked_active == '' && $conv_active == '' && $search_active == '' && $spam_active == '') {
        $all_active = 'active';
    }
    $postord_active = '';
    if ($all_active && x($_GET, 'order') && $_GET['order'] !== 'comment') {
        $all_active = '';
        $postord_active = 'active';
    }
    // tabs
    $tabs = array(array('label' => t('Commented Order'), 'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $a->cmd) . (x($_GET, 'cid') ? '?f=&cid=' . $_GET['cid'] : ''), 'sel' => $all_active, 'title' => t('Sort by Comment Date')), array('label' => t('Posted Order'), 'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $a->cmd) . '?f=&order=post' . (x($_GET, 'cid') ? '&cid=' . $_GET['cid'] : ''), 'sel' => $postord_active, 'title' => t('Sort by Post Date')), array('label' => t('Personal'), 'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $a->cmd) . (x($_GET, 'cid') ? '/?f=&cid=' . $_GET['cid'] : '') . '&conv=1', 'sel' => $conv_active, 'title' => t('Posts that mention or involve you')), array('label' => t('New'), 'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $a->cmd) . '/new' . (x($_GET, 'cid') ? '/?f=&cid=' . $_GET['cid'] : ''), 'sel' => $new_active, 'title' => t('Activity Stream - by date')), array('label' => t('Starred'), 'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $a->cmd) . (x($_GET, 'cid') ? '/?f=&cid=' . $_GET['cid'] : '') . '&star=1', 'sel' => $starred_active, 'title' => t('Favourite Posts')), array('label' => t('Shared Links'), 'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $a->cmd) . (x($_GET, 'cid') ? '/?f=&cid=' . $_GET['cid'] : '') . '&bmark=1', 'sel' => $bookmarked_active, 'title' => t('Interesting Links')));
    $arr = array('tabs' => $tabs);
    call_hooks('network_tabs', $arr);
    $o .= replace_macros(get_markup_template('common_tabs.tpl'), array('$tabs' => $arr['tabs']));
    // --- end item filter tabs
    $contact_id = $a->cid;
    $group = 0;
    $nouveau = false;
    require_once 'include/acl_selectors.php';
    $cid = x($_GET, 'cid') ? intval($_GET['cid']) : 0;
    $star = x($_GET, 'star') ? intval($_GET['star']) : 0;
    $bmark = x($_GET, 'bmark') ? intval($_GET['bmark']) : 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;
    $nets = x($_GET, 'nets') ? $_GET['nets'] : '';
    $cmin = x($_GET, 'cmin') ? intval($_GET['cmin']) : 0;
    $cmax = x($_GET, 'cmax') ? intval($_GET['cmax']) : 99;
    $file = x($_GET, 'file') ? $_GET['file'] : '';
    if ($a->argc > 2 && $a->argv[2] === 'new') {
        $nouveau = true;
    }
    if ($a->argc > 1) {
        if ($a->argv[1] === 'new') {
            $nouveau = true;
        } else {
            $group = intval($a->argv[1]);
            $def_acl = array('allow_gid' => '<' . $group . '>');
        }
    }
    if (x($_GET, 'search') || x($_GET, 'file')) {
        $nouveau = true;
    }
    if ($cid) {
        $def_acl = array('allow_cid' => '<' . intval($cid) . '>');
    }
    if ($nets) {
        $r = q("select id from contact where uid = %d and network = '%s' and self = 0", intval(local_user()), dbesc($nets));
        $str = '';
        if (count($r)) {
            foreach ($r as $rr) {
                $str .= '<' . $rr['id'] . '>';
            }
        }
        if (strlen($str)) {
            $def_acl = array('allow_cid' => $str);
        }
    }
    if (!$update) {
        if ($group) {
            if (($t = group_public_members($group)) && !get_pconfig(local_user(), 'system', 'nowarn_insecure')) {
                notice(sprintf(tt('Warning: This group contains %s member from an insecure network.', 'Warning: This group contains %s members from an insecure network.', $t), $t) . EOL);
                notice(t('Private messages to this group are at risk of public disclosure.') . EOL);
            }
        }
        nav_set_selected('network');
        $celeb = $a->user['page-flags'] == PAGE_SOAPBOX || $a->user['page-flags'] == PAGE_COMMUNITY ? true : false;
        $x = array('is_owner' => true, 'allow_location' => $a->user['allow_location'], 'default_location' => $a->user['default-location'], 'nickname' => $a->user['nickname'], 'lockstate' => $group || $cid || $nets || is_array($a->user) && (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) || strlen($a->user['deny_cid']) || strlen($a->user['deny_gid'])) ? 'lock' : 'unlock', 'acl' => populate_acl($group || $cid || $nets ? $def_acl : $a->user, $celeb), 'bang' => $group || $cid || $nets ? '!' : '', 'visitor' => 'block', 'profile_uid' => local_user());
        $o .= status_editor($a, $x);
    }
    // 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 starred = 1 " : '';
    $sql_options .= $bmark ? " and bookmark = 1 " : '';
    $sql_nets = $nets ? sprintf(" and `contact`.`network` = '%s' ", dbesc($nets)) : '';
    $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` {$sql_options} ) ";
    if ($group) {
        $r = q("SELECT `name`, `id` FROM `group` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($group), intval($_SESSION['uid']));
        if (!count($r)) {
            if ($update) {
                killme();
            }
            notice(t('No such group') . EOL);
            goaway($a->get_baseurl(true) . '/network');
            // NOTREACHED
        }
        $contacts = expand_groups(array($group));
        if (is_array($contacts) && count($contacts)) {
            $contact_str = implode(',', $contacts);
        } else {
            $contact_str = ' 0 ';
            info(t('Group is empty'));
        }
        $sql_extra = " AND `item`.`parent` IN ( SELECT DISTINCT(`parent`) FROM `item` WHERE 1 {$sql_options} AND ( `contact-id` IN ( {$contact_str} ) OR `allow_gid` like '" . protect_sprintf('%<' . intval($group) . '>%') . "' ) and deleted = 0 ) ";
        $o = '<h2>' . t('Group: ') . $r[0]['name'] . '</h2>' . $o;
    } elseif ($cid) {
        $r = q("SELECT `id`,`name`,`network`,`writable`,`nurl` FROM `contact` WHERE `id` = %d \n\t\t\t\tAND `blocked` = 0 AND `pending` = 0 LIMIT 1", intval($cid));
        if (count($r)) {
            $sql_extra = " AND `item`.`parent` IN ( SELECT DISTINCT(`parent`) FROM `item` WHERE 1 {$sql_options} AND `contact-id` = " . intval($cid) . " and deleted = 0 ) ";
            $o = '<h2>' . t('Contact: ') . $r[0]['name'] . '</h2>' . $o;
            if ($r[0]['network'] === NETWORK_OSTATUS && $r[0]['writable'] && !get_pconfig(local_user(), 'system', 'nowarn_insecure')) {
                notice(t('Private messages to this person are at risk of public disclosure.') . EOL);
            }
        } else {
            notice(t('Invalid contact.') . EOL);
            goaway($a->get_baseurl(true) . '/network');
            // NOTREACHED
        }
    }
    if (!$group && !$cid && !$update) {
        $o .= get_birthdays();
        $o .= get_events();
    }
    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).
        $o .= '<div id="live-network"></div>' . "\r\n";
        $o .= "<script> var profile_uid = " . $_SESSION['uid'] . "; var netargs = '" . substr($a->cmd, 8) . '?f=' . (x($_GET, 'cid') ? '&cid=' . $_GET['cid'] : '') . (x($_GET, 'search') ? '&search=' . $_GET['search'] : '') . (x($_GET, 'star') ? '&star=' . $_GET['star'] : '') . (x($_GET, 'order') ? '&order=' . $_GET['order'] : '') . (x($_GET, 'bmark') ? '&bmark=' . $_GET['bmark'] : '') . (x($_GET, 'liked') ? '&liked=' . $_GET['liked'] : '') . (x($_GET, 'conv') ? '&conv=' . $_GET['conv'] : '') . (x($_GET, 'spam') ? '&spam=' . $_GET['spam'] : '') . (x($_GET, 'nets') ? '&nets=' . $_GET['nets'] : '') . (x($_GET, 'cmin') ? '&cmin=' . $_GET['cmin'] : '') . (x($_GET, 'cmax') ? '&cmax=' . $_GET['cmax'] : '') . (x($_GET, 'file') ? '&file=' . $_GET['file'] : '') . "'; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
    }
    $sql_extra2 = $nouveau ? '' : " AND `item`.`parent` = `item`.`id` ";
    if (x($_GET, 'search')) {
        $search = escape_tags($_GET['search']);
        if (get_config('system', 'use_fulltext_engine')) {
            if (strpos($search, '#') === 0) {
                $sql_extra .= sprintf(" AND (MATCH(tag) AGAINST ('" . '"%s"' . "' in boolean mode)) ", dbesc(protect_sprintf($search)));
            } else {
                $sql_extra .= sprintf(" AND (MATCH(`item`.`body`) AGAINST ('" . '"%s"' . "' in boolean mode) or MATCH(tag) AGAINST ('" . '"%s"' . "' in boolean mode)) ", dbesc(protect_sprintf($search)), dbesc(protect_sprintf($search)));
            }
        } else {
            $sql_extra .= sprintf(" AND ( `item`.`body` like '%s' OR `item`.`tag` like '%s' ) ", dbesc(protect_sprintf('%' . $search . '%')), dbesc(protect_sprintf('%]' . $search . '[%')));
        }
    }
    if (strlen($file)) {
        $sql_extra .= file_tag_file_query('item', unxmlify($file));
    }
    if ($conv) {
        $myurl = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
        $myurl = substr($myurl, strpos($myurl, '://') + 3);
        $myurl = str_replace('www.', '', $myurl);
        $diasp_url = str_replace('/profile/', '/u/', $myurl);
        if (get_config('system', 'use_fulltext_engine')) {
            $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where (MATCH(`author-link`) AGAINST ('" . '"%s"' . "' in boolean mode) or MATCH(`tag`) AGAINST ('" . '"%s"' . "' in boolean mode) or MATCH(tag) AGAINST ('" . '"%s"' . "' in boolean mode))) ", dbesc(protect_sprintf($myurl)), dbesc(protect_sprintf($myurl)), dbesc(protect_sprintf($diasp_url)));
        } else {
            $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where ( `author-link` like '%s' or `tag` like '%s' or tag like '%s' )) ", dbesc(protect_sprintf('%' . $myurl)), dbesc(protect_sprintf('%' . $myurl . ']%')), dbesc(protect_sprintf('%' . $diasp_url . ']%')));
        }
    }
    if ($update) {
        // only setup pagination on initial page view
        $pager_sql = '';
    } else {
        $r = q("SELECT COUNT(*) AS `total`\n\t\t\tFROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t{$sql_extra2}\n\t\t\t{$sql_extra} {$sql_nets} ", intval($_SESSION['uid']));
        if (count($r)) {
            $a->set_pager_total($r[0]['total']);
            $itemspage_network = get_pconfig(local_user(), 'system', 'itemspage_network');
            $a->set_pager_itemspage(intval($itemspage_network) ? $itemspage_network : 40);
        }
        $pager_sql = sprintf(" LIMIT %d, %d ", intval($a->pager['start']), intval($a->pager['itemspage']));
    }
    $simple_update = $update ? " and `item`.`unseen` = 1 " : '';
    if ($nouveau) {
        // "New Item View" - show all items unthreaded in reverse created date order
        $items = q("SELECT `item`.*, `item`.`id` AS `item_id`, \n\t\t\t`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`, `contact`.`writable`,\n\t\t\t`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,\n\t\t\t`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`\n\t\t\tFROM `item`, `contact`\n\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 \n\t\t\tAND `item`.`deleted` = 0 and `item`.`moderated` = 0\n\t\t\t{$simple_update}\n\t\t\tAND `contact`.`id` = `item`.`contact-id`\n\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t{$sql_extra} {$sql_nets}\n\t\t\tORDER BY `item`.`received` DESC {$pager_sql} ", intval($_SESSION['uid']));
    } else {
        // Normal conversation view
        if ($order === 'post') {
            $ordering = "`created`";
        } else {
            $ordering = "`commented`";
        }
        // Fetch a page full of parent items for this page
        if ($update) {
            $r = q("SELECT `parent` AS `item_id`, `contact`.`uid` AS `contact_uid`\n\t\t\t\tFROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\t\t\tand `item`.`moderated` = 0 and `item`.`unseen` = 1\n\t\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\t{$sql_extra} {$sql_nets} ", intval(local_user()));
        } else {
            $r = q("SELECT `item`.`id` AS `item_id`, `contact`.`uid` AS `contact_uid`\n\t\t\t\tFROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\t\t\tAND `item`.`moderated` = 0 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\tAND `item`.`parent` = `item`.`id`\n\t\t\t\t{$sql_extra} {$sql_nets}\n\t\t\t\tORDER BY `item`.{$ordering} DESC {$pager_sql} ", intval(local_user()));
        }
        // Then fetch all the children of the parents that are on this page
        $parents_arr = array();
        $parents_str = '';
        if (count($r)) {
            foreach ($r as $rr) {
                if (!in_array($rr['item_id'], $parents_arr)) {
                    $parents_arr[] = $rr['item_id'];
                }
            }
            $parents_str = implode(', ', $parents_arr);
            $items = q("SELECT `item`.*, `item`.`id` AS `item_id`,\n\t\t\t\t`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`alias`, `contact`.`rel`, `contact`.`writable`,\n\t\t\t\t`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,\n\t\t\t\t`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`\n\t\t\t\tFROM `item`, `contact`\n\t\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\t\t\tAND `item`.`moderated` = 0 AND `contact`.`id` = `item`.`contact-id`\n\t\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\tAND `item`.`parent` IN ( %s )\n\t\t\t\t{$sql_extra} ", intval(local_user()), dbesc($parents_str));
            $items = conv_sort($items, $ordering);
        } else {
            $items = array();
        }
    }
    // We aren't going to try and figure out at the item, group, and page
    // level which items you've seen and which you haven't. If you're looking
    // at the top level network page just mark everything seen.
    if (!$group && !$cid && !$star) {
        $r = q("UPDATE `item` SET `unseen` = 0 \n\t\t\tWHERE `unseen` = 1 AND `uid` = %d", intval(local_user()));
    }
    // Set this so that the conversation function can find out contact info for our wall-wall items
    $a->page_contact = $a->contact;
    $mode = $nouveau ? 'network-new' : 'network';
    $o .= conversation($a, $items, $mode, $update);
    if (!$update) {
        $o .= paginate($a);
    }
    return $o;
}
Example #12
0
function network_content(&$a, $update = 0)
{
    require_once 'include/conversation.php';
    if (!local_user()) {
        $_SESSION['return_url'] = $a->query_string;
        return login(false);
    }
    $arr = array('query' => $a->query_string);
    call_hooks('network_content_init', $arr);
    $datequery = $datequery2 = '';
    $group = 0;
    $nouveau = false;
    if ($a->argc > 1) {
        for ($x = 1; $x < $a->argc; $x++) {
            if (is_a_date_arg($a->argv[$x])) {
                if ($datequery) {
                    $datequery2 = escape_tags($a->argv[$x]);
                } else {
                    $datequery = escape_tags($a->argv[$x]);
                    $_GET['order'] = 'post';
                }
            } elseif ($a->argv[$x] === 'new') {
                $nouveau = true;
            } elseif (intval($a->argv[$x])) {
                $group = intval($a->argv[$x]);
                $def_acl = array('allow_gid' => '<' . $group . '>');
            }
        }
    }
    $o = '';
    // item filter tabs
    // TODO: fix this logic, reduce duplication
    //$a->page['content'] .= '<div class="tabs-wrapper">';
    list($no_active, $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active, $spam_active) = network_query_get_sel_tab($a);
    // if no tabs are selected, defaults to comments
    if ($no_active == 'active') {
        $all_active = 'active';
    }
    //echo "<pre>"; var_dump($no_active, $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active, $spam_active); killme();
    $cmd = $datequery ? '' : $a->cmd;
    $len_naked_cmd = strlen(str_replace('/new', '', $cmd));
    // tabs
    $tabs = array(array('label' => t('Commented Order'), 'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $cmd) . '?f=&order=comment' . (x($_GET, 'cid') ? '&cid=' . $_GET['cid'] : ''), 'sel' => $all_active, 'title' => t('Sort by Comment Date')), array('label' => t('Posted Order'), 'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $cmd) . '?f=&order=post' . (x($_GET, 'cid') ? '&cid=' . $_GET['cid'] : ''), 'sel' => $postord_active, 'title' => t('Sort by Post Date')));
    if (feature_enabled(local_user(), 'personal_tab')) {
        $tabs[] = array('label' => t('Personal'), 'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $cmd) . (x($_GET, 'cid') ? '/?f=&cid=' . $_GET['cid'] : '') . '&conv=1', 'sel' => $conv_active, 'title' => t('Posts that mention or involve you'));
    }
    if (feature_enabled(local_user(), 'new_tab')) {
        $tabs[] = array('label' => t('New'), 'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $cmd) . ($len_naked_cmd ? '/' : '') . 'new' . (x($_GET, 'cid') ? '/?f=&cid=' . $_GET['cid'] : ''), 'sel' => $new_active, 'title' => t('Activity Stream - by date'));
    }
    if (feature_enabled(local_user(), 'link_tab')) {
        $tabs[] = array('label' => t('Shared Links'), 'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $cmd) . (x($_GET, 'cid') ? '/?f=&cid=' . $_GET['cid'] : '') . '&bmark=1', 'sel' => $bookmarked_active, 'title' => t('Interesting Links'));
    }
    if (feature_enabled(local_user(), 'star_posts')) {
        $tabs[] = array('label' => t('Starred'), 'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $cmd) . (x($_GET, 'cid') ? '/?f=&cid=' . $_GET['cid'] : '') . '&star=1', 'sel' => $starred_active, 'title' => t('Favourite Posts'));
    }
    // Not yet implemented
    /*	if(feature_enabled(local_user(),'spam_filter'))  {
    		$tabs[] = array(
    			'label' => t('Spam'),
    			'url'=>$a->get_baseurl(true) . '/network?f=&spam=1',
    			'sel'=> $spam_active,
    			'title' => t('Posts flagged as SPAM'),
    		);
    	}*/
    // save selected tab, but only if not in search or file mode
    if (!x($_GET, 'search') && !x($_GET, 'file')) {
        set_pconfig(local_user(), 'network.view', 'tab.selected', array($all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active, $spam_active));
    }
    $arr = array('tabs' => $tabs);
    call_hooks('network_tabs', $arr);
    $o .= replace_macros(get_markup_template('common_tabs.tpl'), array('$tabs' => $arr['tabs']));
    // --- end item filter tabs
    $contact_id = $a->cid;
    require_once 'include/acl_selectors.php';
    $cid = x($_GET, 'cid') ? intval($_GET['cid']) : 0;
    $star = x($_GET, 'star') ? intval($_GET['star']) : 0;
    $bmark = x($_GET, 'bmark') ? intval($_GET['bmark']) : 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;
    $nets = x($_GET, 'nets') ? $_GET['nets'] : '';
    $cmin = x($_GET, 'cmin') ? intval($_GET['cmin']) : 0;
    $cmax = x($_GET, 'cmax') ? intval($_GET['cmax']) : 99;
    $file = x($_GET, 'file') ? $_GET['file'] : '';
    if (x($_GET, 'search') || x($_GET, 'file')) {
        $nouveau = true;
    }
    if ($cid) {
        $def_acl = array('allow_cid' => '<' . intval($cid) . '>');
    }
    if ($nets) {
        $r = q("select id from contact where uid = %d and network = '%s' and self = 0", intval(local_user()), dbesc($nets));
        $str = '';
        if (count($r)) {
            foreach ($r as $rr) {
                $str .= '<' . $rr['id'] . '>';
            }
        }
        if (strlen($str)) {
            $def_acl = array('allow_cid' => $str);
        }
    }
    set_pconfig(local_user(), 'network.view', 'net.selected', $nets ? $nets : 'all');
    if (!$update) {
        if ($group) {
            if (($t = group_public_members($group)) && !get_pconfig(local_user(), 'system', 'nowarn_insecure')) {
                notice(sprintf(tt('Warning: This group contains %s member from an insecure network.', 'Warning: This group contains %s members from an insecure network.', $t), $t) . EOL);
                notice(t('Private messages to this group are at risk of public disclosure.') . EOL);
            }
        }
        nav_set_selected('network');
        $celeb = $a->user['page-flags'] == PAGE_SOAPBOX || $a->user['page-flags'] == PAGE_COMMUNITY ? true : false;
        $x = array('is_owner' => true, 'allow_location' => $a->user['allow_location'], 'default_location' => $a->user['default-location'], 'nickname' => $a->user['nickname'], 'lockstate' => $group || $cid || $nets || is_array($a->user) && (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) || strlen($a->user['deny_cid']) || strlen($a->user['deny_gid'])) ? 'lock' : 'unlock', 'default_perms' => get_acl_permissions($a->user), 'acl' => populate_acl($group || $cid || $nets ? $def_acl : $a->user, $celeb), 'bang' => $group || $cid || $nets ? '!' : '', 'visitor' => 'block', 'profile_uid' => local_user(), 'acl_data' => construct_acl_data($a, $a->user));
        $o .= status_editor($a, $x);
    }
    // We don't have to deal with ACLs 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 starred = 1 " : '';
    $sql_options .= $bmark ? " and bookmark = 1 " : '';
    $sql_nets = $nets ? sprintf(" and `contact`.`network` = '%s' ", dbesc($nets)) : '';
    $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` {$sql_options} ) ";
    if ($group) {
        $r = q("SELECT `name`, `id` FROM `group` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($group), intval($_SESSION['uid']));
        if (!count($r)) {
            if ($update) {
                killme();
            }
            notice(t('No such group') . EOL);
            goaway($a->get_baseurl(true) . '/network/0');
            // NOTREACHED
        }
        $contacts = expand_groups(array($group));
        if (is_array($contacts) && count($contacts)) {
            $contact_str = implode(',', $contacts);
        } else {
            $contact_str = ' 0 ';
            info(t('Group is empty'));
        }
        $sql_extra = " AND `item`.`parent` IN ( SELECT DISTINCT(`parent`) FROM `item` WHERE 1 {$sql_options} AND ( `contact-id` IN ( {$contact_str} ) OR `allow_gid` like '" . protect_sprintf('%<' . intval($group) . '>%') . "' ) and deleted = 0 ) ";
        $o = '<h2>' . t('Group: ') . $r[0]['name'] . '</h2>' . $o;
    } elseif ($cid) {
        $r = q("SELECT `id`,`name`,`network`,`writable`,`nurl` FROM `contact` WHERE `id` = %d \n\t\t\t\tAND `blocked` = 0 AND `pending` = 0 LIMIT 1", intval($cid));
        if (count($r)) {
            $sql_extra = " AND `item`.`parent` IN ( SELECT DISTINCT(`parent`) FROM `item` WHERE 1 {$sql_options} AND `contact-id` = " . intval($cid) . " and deleted = 0 ) ";
            $o = '<h2>' . t('Contact: ') . $r[0]['name'] . '</h2>' . $o;
            if ($r[0]['network'] === NETWORK_OSTATUS && $r[0]['writable'] && !get_pconfig(local_user(), 'system', 'nowarn_insecure')) {
                notice(t('Private messages to this person are at risk of public disclosure.') . EOL);
            }
        } else {
            notice(t('Invalid contact.') . EOL);
            goaway($a->get_baseurl(true) . '/network');
            // NOTREACHED
        }
    }
    if (!$group && !$cid && !$update && !get_config('theme', 'hide_eventlist')) {
        $o .= get_birthdays();
        $o .= get_events();
    }
    $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;
    $sql_table = "`item`";
    if (x($_GET, 'search')) {
        $search = escape_tags($_GET['search']);
        if (strpos($search, '#') === 0) {
            $tag = true;
            $search = substr($search, 1);
        }
        if (get_config('system', 'only_tag_search')) {
            $tag = true;
        }
        /*if (get_config('system','use_fulltext_engine')) {
        			if(strpos($search,'#') === 0)
        				$sql_extra .= sprintf(" AND (MATCH(tag) AGAINST ('".'"%s"'."' in boolean mode)) ",
        					dbesc(protect_sprintf($search))
        				);
        			else
        				$sql_extra .= sprintf(" AND (MATCH(`item`.`body`, `item`.`title`) AGAINST ('%s' in boolean mode)) ",
        					dbesc(protect_sprintf($search)),
        					dbesc(protect_sprintf($search))
        				);
        		} else {
        			$sql_extra .= sprintf(" AND ( `item`.`body` like '%s' OR `item`.`tag` like '%s' ) ",
        					dbesc(protect_sprintf('%' . $search . '%')),
        					dbesc(protect_sprintf('%]' . $search . '[%'))
        			);
        		}*/
        if ($tag) {
            $sql_extra = sprintf(" AND `term`.`term` = '%s' AND `term`.`otype` = %d AND `term`.`type` = %d ", dbesc(protect_sprintf($search)), intval(TERM_OBJ_POST), intval(TERM_HASHTAG));
            $sql_table = "`term` LEFT JOIN `item` ON `item`.`id` = `term`.`oid` AND `item`.`uid` = `term`.`uid` ";
        } else {
            if (get_config('system', 'use_fulltext_engine')) {
                $sql_extra = sprintf(" AND MATCH (`item`.`body`, `item`.`title`) AGAINST ('%s' in boolean mode) ", dbesc(protect_sprintf($search)));
            } else {
                $sql_extra = sprintf(" AND `item`.`body` REGEXP '%s' ", dbesc(protect_sprintf(preg_quote($search))));
            }
        }
    }
    if (strlen($file)) {
        $sql_extra .= file_tag_file_query('item', unxmlify($file));
    }
    if ($conv) {
        $myurl = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
        $myurl = substr($myurl, strpos($myurl, '://') + 3);
        $myurl = str_replace('www.', '', $myurl);
        $diasp_url = str_replace('/profile/', '/u/', $myurl);
        /*if (get_config('system','use_fulltext_engine'))
        			$sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where (MATCH(`author-link`) AGAINST ('".'"%s"'."' in boolean mode) or MATCH(`tag`) AGAINST ('".'"%s"'."' in boolean mode) or MATCH(tag) AGAINST ('".'"%s"'."' in boolean mode))) ",
        			//$sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where (`author-link` IN ('https://%s', 'http://%s') OR MATCH(`tag`) AGAINST ('".'"%s"'."' in boolean mode) or MATCH(tag) AGAINST ('".'"%s"'."' in boolean mode))) ",
        			//$sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where `author-link` IN ('https://%s', 'http://%s') OR `mention`)",
        				dbesc(protect_sprintf($myurl)),
        				dbesc(protect_sprintf($myurl)),
        				dbesc(protect_sprintf($diasp_url))
        			);
        		else
        			$sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where ( `author-link` like '%s' or `tag` like '%s' or tag like '%s' )) ",
        				dbesc(protect_sprintf('%' . $myurl)),
        				dbesc(protect_sprintf('%' . $myurl . ']%')),
        				dbesc(protect_sprintf('%' . $diasp_url . ']%'))
        			);*/
        $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where `author-link` IN ('https://%s', 'http://%s') OR `mention`)", dbesc(protect_sprintf($myurl)), dbesc(protect_sprintf($myurl)));
    }
    if ($update) {
        // only setup pagination on initial page view
        $pager_sql = '';
    } else {
        if (!get_config('alt_pager', 'global') && !get_pconfig(local_user(), 'system', 'alt_pager')) {
            $r = q("SELECT COUNT(*) AS `total`\n\t\t\t        FROM {$sql_table} LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\t        WHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\t\t        AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t        {$sql_extra2} {$sql_extra3}\n\t\t\t        {$sql_extra} {$sql_nets} ", intval($_SESSION['uid']));
            if (count($r)) {
                $a->set_pager_total($r[0]['total']);
            }
        }
        $itemspage_network = get_pconfig(local_user(), 'system', 'itemspage_network');
        $itemspage_network = intval($itemspage_network) ? $itemspage_network : 40;
        if ($a->force_max_items > 0 && $a->force_max_items < $itemspage_network) {
            $itemspage_network = $a->force_max_items;
        }
        $a->set_pager_itemspage($itemspage_network);
        $pager_sql = sprintf(" LIMIT %d, %d ", intval($a->pager['start']), intval($a->pager['itemspage']));
    }
    $simple_update = $update ? " and `item`.`unseen` = 1 " : '';
    if ($nouveau) {
        // "New Item View" - show all items unthreaded in reverse created date order
        $items = q("SELECT `item`.*, `item`.`id` AS `item_id`, \n\t\t\t`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`, `contact`.`writable`,\n\t\t\t`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,\n\t\t\t`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`\n\t\t\tFROM {$sql_table} LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 \n\t\t\tAND `item`.`deleted` = 0 and `item`.`moderated` = 0\n\t\t\t{$simple_update}\n\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t{$sql_extra} {$sql_nets}\n\t\t\tORDER BY `item`.`received` DESC {$pager_sql} ", intval($_SESSION['uid']));
        $update_unseen = ' WHERE uid = ' . intval($_SESSION['uid']) . " AND unseen = 1 {$sql_extra} {$sql_nets}";
    } else {
        // Normal conversation view
        if ($order === 'post') {
            $ordering = "`created`";
        } else {
            $ordering = "`commented`";
        }
        // Fetch a page full of parent items for this page
        if ($update) {
            $r = q("SELECT `parent` AS `item_id`, `contact`.`uid` AS `contact_uid`\n\t\t\t\tFROM {$sql_table} LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND\n\t\t\t\t(`item`.`deleted` = 0 OR item.verb = '" . ACTIVITY_LIKE . "' OR item.verb = '" . ACTIVITY_DISLIKE . "')\n\t\t\t\tand `item`.`moderated` = 0 and `item`.`unseen` = 1\n\t\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\t{$sql_extra3} {$sql_extra} {$sql_nets} ", intval(local_user()));
        } else {
            $r = q("SELECT `item`.`id` AS `item_id`, `contact`.`uid` AS `contact_uid`\n\t\t\t\tFROM {$sql_table} LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\t\t\tAND `item`.`moderated` = 0 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\tAND `item`.`parent` = `item`.`id`\n\t\t\t\t{$sql_extra3} {$sql_extra} {$sql_nets}\n\t\t\t\tORDER BY `item`.{$ordering} DESC {$pager_sql} ", intval(local_user()));
        }
        // Then fetch all the children of the parents that are on this page
        $parents_arr = array();
        $parents_str = '';
        if (count($r)) {
            foreach ($r as $rr) {
                if (!in_array($rr['item_id'], $parents_arr)) {
                    $parents_arr[] = $rr['item_id'];
                }
            }
            $parents_str = implode(', ', $parents_arr);
            $items = q("SELECT `item`.*, `item`.`id` AS `item_id`,\n\t\t\t\t`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`alias`, `contact`.`rel`, `contact`.`writable`,\n\t\t\t\t`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,\n\t\t\t\t`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`\n\t\t\t\tFROM {$sql_table} LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\t\t\tAND `item`.`moderated` = 0\n\t\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\tAND `item`.`parent` IN ( %s )\n\t\t\t\t{$sql_extra} ", intval(local_user()), dbesc($parents_str));
            $items = conv_sort($items, $ordering);
        } else {
            $items = array();
        }
        if ($parents_str) {
            $update_unseen = ' WHERE uid = ' . intval(local_user()) . ' AND unseen = 1 AND parent IN ( ' . dbesc($parents_str) . ' )';
        }
    }
    // We aren't going to try and figure out at the item, group, and page
    // level which items you've seen and which you haven't. If you're looking
    // at the top level network page just mark everything seen.
    // The $update_unseen is a bit unreliable if you have stuff coming into your stream from a new contact -
    // and other feeds that bring in stuff from the past. One can't find it all.
    // I'm reviving this block to mark everything seen on page 1 of the network as a temporary measure.
    // The correct solution is to implement a network notifications box just like the system notifications popup
    // with the ability in the popup to "mark all seen".
    // Several people are complaining because there are unseen messages they can't find and as time goes
    // on they just get buried deeper. It has happened to me a couple of times also.
    if (!$group && !$cid && !$star) {
        $r = q("UPDATE `item` SET `unseen` = 0 \n\t\t\tWHERE `unseen` = 1 AND `uid` = %d", intval(local_user()));
    } else {
        if ($update_unseen) {
            $r = q("UPDATE `item` SET `unseen` = 0 {$update_unseen}");
        }
    }
    // Set this so that the conversation function can find out contact info for our wall-wall items
    $a->page_contact = $a->contact;
    $mode = $nouveau ? 'network-new' : 'network';
    $o .= conversation($a, $items, $mode, $update);
    if (!$update) {
        if (get_config('alt_pager', 'global') || get_pconfig(local_user(), 'system', 'alt_pager')) {
            $o .= alt_pager($a, count($items));
        } else {
            $o .= paginate($a);
        }
    }
    return $o;
}