Exemple #1
0
 function init()
 {
     $starred = 0;
     if (!local_channel()) {
         killme();
     }
     if (argc() > 1) {
         $message_id = intval(argv(1));
     }
     if (!$message_id) {
         killme();
     }
     $r = q("SELECT item_flags FROM item WHERE uid = %d AND id = %d LIMIT 1", intval(local_channel()), intval($message_id));
     if (!count($r)) {
         killme();
     }
     $item_starred = intval($r[0]['item_starred']) ? 0 : 1;
     $r = q("UPDATE item SET item_starred = %d WHERE uid = %d and id = %d", intval($item_starred), intval(local_channel()), intval($message_id));
     $r = q("select * from item where id = %d", intval($message_id));
     if ($r) {
         xchan_query($r);
         $sync_item = fetch_post_tags($r);
         build_sync_packet(local_channel(), ['item' => [encode_item($sync_item[0], true)]]);
     }
     header('Content-type: application/json');
     echo json_encode(array('result' => $item_starred));
     killme();
 }
Exemple #2
0
function zot_feed($uid, $observer_hash, $arr)
{
    $result = array();
    $mindate = null;
    $message_id = null;
    require_once 'include/security.php';
    if (array_key_exists('mindate', $arr)) {
        $mindate = datetime_convert('UTC', 'UTC', $arr['mindate']);
    }
    if (array_key_exists('message_id', $arr)) {
        $message_id = $arr['message_id'];
    }
    if (!$mindate) {
        $mindate = NULL_DATE;
    }
    $mindate = dbesc($mindate);
    logger('zot_feed: requested for uid ' . $uid . ' from observer ' . $observer_hash, LOGGER_DEBUG);
    if ($message_id) {
        logger('message_id: ' . $message_id, LOGGER_DEBUG);
    }
    if (!perm_is_allowed($uid, $observer_hash, 'view_stream')) {
        logger('zot_feed: permission denied.');
        return $result;
    }
    if (!is_sys_channel($uid)) {
        $sql_extra = item_permissions_sql($uid, $observer_hash);
    }
    $limit = " LIMIT 100 ";
    if ($mindate != NULL_DATE) {
        $sql_extra .= " and ( created > '{$mindate}' or changed > '{$mindate}' ) ";
    }
    if ($message_id) {
        $sql_extra .= " and mid = '" . dbesc($message_id) . "' ";
        $limit = '';
    }
    $items = array();
    /** @FIXME re-unite these SQL statements. There is no need for them to be separate. The mySQL is convoluted with misuse of group by. As it stands, there is a slight difference where the postgres version doesn't remove the duplicate parents up to 100. In practice this doesn't matter. It could be made to match behavior by adding "distinct on (parent) " to the front of the selection list, at a not-worth-it performance penalty (page temp results to disk). duplicates are still ignored in the in() clause, you just get less than 100 parents if there are many children. */
    if (ACTIVE_DBTYPE == DBTYPE_POSTGRES) {
        $groupby = '';
    } else {
        $groupby = 'GROUP BY parent';
    }
    $item_normal = item_normal();
    if (is_sys_channel($uid)) {
        $r = q("SELECT parent, created, postopts from item\n\t\t\tWHERE uid != %d\n\t\t\t{$item_normal}\n\t\t\tAND item_wall = 1\n\t\t\tand item_private = 0 {$sql_extra} {$groupby} ORDER BY created ASC {$limit}", intval($uid));
    } else {
        $r = q("SELECT parent, created, postopts from item\n\t\t\tWHERE uid = %d {$item_normal}\n\t\t\tAND item_wall = 1\n\t\t\t{$sql_extra} {$groupby} ORDER BY created ASC {$limit}", intval($uid));
    }
    if ($r) {
        for ($x = 0; $x < count($r); $x++) {
            if (strpos($r[$x]['postopts'], 'nodeliver') !== false) {
                unset($r[$x]);
            }
        }
        $parents_str = ids_to_querystr($r, 'parent');
        $sys_query = is_sys_channel($uid) ? $sql_extra : '';
        $item_normal = item_normal();
        $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item`\n\t\t\tWHERE `item`.`parent` IN ( %s ) {$item_normal} {$sys_query} ", dbesc($parents_str));
    }
    if ($items) {
        xchan_query($items);
        $items = fetch_post_tags($items);
        require_once 'include/conversation.php';
        $items = conv_sort($items, 'ascending');
    } else {
        $items = array();
    }
    logger('zot_feed: number items: ' . count($items), LOGGER_DEBUG);
    foreach ($items as $item) {
        $result[] = encode_item($item);
    }
    return $result;
}
Exemple #3
0
function attach_export_data($channel, $resource_id, $deleted = false)
{
    $ret = array();
    $paths = array();
    $hash_ptr = $resource_id;
    $ret['fetch_url'] = z_root() . '/getfile';
    $ret['original_channel'] = $channel['channel_address'];
    if ($deleted) {
        $ret['attach'] = array(array('hash' => $resource_id, 'deleted' => 1));
        return $ret;
    }
    do {
        $r = q("select * from attach where hash = '%s' and uid = %d limit 1", dbesc($hash_ptr), intval($channel['channel_id']));
        if (!$r) {
            break;
        }
        if ($hash_ptr === $resource_id) {
            $attach_ptr = $r[0];
        }
        $hash_ptr = $r[0]['folder'];
        $paths[] = $r[0];
    } while ($hash_ptr);
    $paths = array_reverse($paths);
    $ret['attach'] = $paths;
    if ($attach_ptr['is_photo']) {
        $r = q("select * from photo where resource_id = '%s' and uid = %d order by imgscale asc", dbesc($resource_id), intval($channel['channel_id']));
        if ($r) {
            for ($x = 0; $x < count($r); $x++) {
                $r[$x]['content'] = base64_encode($r[$x]['content']);
            }
            $ret['photo'] = $r;
        }
        $r = q("select * from item where resource_id = '%s' and resource_type = 'photo' and uid = %d ", dbesc($resource_id), intval($channel['channel_id']));
        if ($r) {
            $ret['item'] = array();
            $items = q("select item.*, item.id as item_id from item where item.parent = %d ", intval($r[0]['id']));
            if ($items) {
                xchan_query($items);
                $items = fetch_post_tags($items, true);
                foreach ($items as $rr) {
                    $ret['item'][] = encode_item($rr, true);
                }
            }
        }
    }
    return $ret;
}
Exemple #4
0
function zot_feed($uid, $observer_xchan, $mindate)
{
    $result = array();
    $mindate = datetime_convert('UTC', 'UTC', $mindate);
    if (!$mindate) {
        $mindate = NULL_DATE;
    }
    $mindate = dbesc($mindate);
    logger('zot_feed: ' . $uid);
    if (!perm_is_allowed($uid, $observer_xchan, 'view_stream')) {
        logger('zot_feed: permission denied.');
        return $result;
    }
    if (!is_sys_channel($uid)) {
        require_once 'include/security.php';
        $sql_extra = item_permissions_sql($uid);
    }
    if ($mindate != NULL_DATE) {
        $sql_extra .= " and ( created > '{$mindate}' or edited > '{$mindate}' ) ";
        $limit = "";
    } else {
        $limit = " limit 0, 50 ";
    }
    $items = array();
    if (is_sys_channel($uid)) {
        require_once 'include/security.php';
        $r = q("SELECT distinct parent from item\n\t\t\tWHERE uid != %d\n\t\t\tand uid in (" . stream_perms_api_uids(PERMS_PUBLIC) . ") AND item_restrict = 0 \n\t\t\tAND (item_flags &  %d) \n\t\t\tand item_private = 0 {$sql_extra} ORDER BY created ASC {$limit}", intval($uid), intval(ITEM_WALL));
    } else {
        $r = q("SELECT distinct parent from item\n\t\t\tWHERE uid = %d AND item_restrict = 0\n\t\t\tAND (item_flags &  %d) \n\t\t\t{$sql_extra} ORDER BY created ASC {$limit}", intval($uid), intval(ITEM_WALL));
    }
    if ($r) {
        $parents_str = ids_to_querystr($r, 'parent');
        $sys_query = is_sys_channel($uid) ? $sql_extra : '';
        $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` \n\t\t\tWHERE `item`.`item_restrict` = 0\n\t\t\tAND `item`.`parent` IN ( %s ) {$sys_query} ", dbesc($parents_str));
    }
    if ($items) {
        xchan_query($items);
        $items = fetch_post_tags($items);
        require_once 'include/conversation.php';
        $items = conv_sort($items, 'ascending');
    } else {
        $items = array();
    }
    logger('zot_feed: number items: ' . count($items), LOGGER_DEBUG);
    foreach ($items as $item) {
        $result[] = encode_item($item);
    }
    return $result;
}
Exemple #5
0
function sync_an_item($channel_id, $item_id)
{
    $r = q("select * from item where id = %d", intval($item_id));
    if ($r) {
        xchan_query($r);
        $sync_item = fetch_post_tags($r);
        $rid = q("select * from item_id where iid = %d", intval($item_id));
        build_sync_packet($channel_d, array('item' => array(encode_item($sync_item[0], true)), 'item_id' => $rid));
    }
}
Exemple #6
0
 function get()
 {
     if (!local_channel() && !remote_channel()) {
         return;
     }
     $observer_hash = get_observer_hash();
     //strip html-tags
     $term = notags(trim($_GET['term']));
     //check if empty
     if (!$term) {
         return;
     }
     $item_id = argc() > 1 ? notags(trim(argv(1))) : 0;
     logger('tagger: tag ' . $term . ' item ' . $item_id);
     $r = q("SELECT * FROM item left join xchan on xchan_hash = author_xchan WHERE id = '%s' and uid = %d LIMIT 1", dbesc($item_id), intval(local_channel()));
     if (!$item_id || !$r) {
         logger('tagger: no item ' . $item_id);
         return;
     }
     $item = $r[0];
     $owner_uid = $item['uid'];
     switch ($item['resource_type']) {
         case 'photo':
             $targettype = ACTIVITY_OBJ_PHOTO;
             $post_type = t('photo');
             break;
         case 'event':
             $targgettype = ACTIVITY_OBJ_EVENT;
             $post_type = t('event');
             break;
         default:
             $targettype = ACTIVITY_OBJ_NOTE;
             $post_type = t('post');
             if ($item['mid'] != $item['parent_mid']) {
                 $post_type = t('comment');
             }
             break;
     }
     $links = array(array('rel' => 'alternate', 'type' => 'text/html', 'href' => z_root() . '/display/' . $item['mid']));
     $target = json_encode(array('type' => $targettype, 'id' => $item['mid'], 'link' => $links, 'title' => $item['title'], 'content' => $item['body'], 'created' => $item['created'], 'edited' => $item['edited'], 'author' => array('name' => $item['xchan_name'], 'address' => $item['xchan_addr'], 'guid' => $item['xchan_guid'], 'guid_sig' => $item['xchan_guid_sig'], 'link' => array(array('rel' => 'alternate', 'type' => 'text/html', 'href' => $item['xchan_url']), array('rel' => 'photo', 'type' => $item['xchan_photo_mimetype'], 'href' => $item['xchan_photo_m'])))));
     $link = xmlify('<link rel="alternate" type="text/html" href="' . z_root() . '/display/' . $owner['nickname'] . '/' . $item['id'] . '" />' . "\n");
     $tagid = z_root() . '/search?tag=' . $term;
     $objtype = ACTIVITY_OBJ_TAGTERM;
     $obj = json_encode(array('type' => $objtype, 'id' => $tagid, 'link' => array(array('rel' => 'alternate', 'type' => 'text/html', 'href' => $tagid)), 'title' => $term, 'content' => $term));
     $bodyverb = t('%1$s tagged %2$s\'s %3$s with %4$s');
     // saving here for reference
     // also check out x22d5 and x2317 and x0d6b and x0db8 and x24d0 and xff20 !!!
     $termlink = html_entity_decode('&#x22d5;') . '[zrl=' . z_root() . '/search?tag=' . urlencode($term) . ']' . $term . '[/zrl]';
     $channel = \App::get_channel();
     $arr = array();
     $arr['owner_xchan'] = $item['owner_xchan'];
     $arr['author_xchan'] = $channel['channel_hash'];
     $arr['item_origin'] = 1;
     $arr['item_wall'] = intval($item['item_wall']) ? 1 : 0;
     $ulink = '[zrl=' . $channel['xchan_url'] . ']' . $channel['channel_name'] . '[/zrl]';
     $alink = '[zrl=' . $item['xchan_url'] . ']' . $item['xchan_name'] . '[/zrl]';
     $plink = '[zrl=' . $item['plink'] . ']' . $post_type . '[/zrl]';
     $arr['body'] = sprintf($bodyverb, $ulink, $alink, $plink, $termlink);
     $arr['verb'] = ACTIVITY_TAG;
     $arr['tgt_type'] = $targettype;
     $arr['target'] = $target;
     $arr['obj_type'] = $objtype;
     $arr['obj'] = $obj;
     $arr['parent_mid'] = $item['mid'];
     store_item_tag($item['uid'], $item['id'], TERM_OBJ_POST, TERM_COMMUNITYTAG, $term, $tagid);
     $ret = post_activity_item($arr);
     if ($ret['success']) {
         build_sync_packet(local_channel(), ['item' => [encode_item($ret['activity'], true)]]);
     }
     killme();
 }
Exemple #7
0
function event_addtocal($item_id, $uid)
{
    $c = q("select * from channel where channel_id = %d limit 1", intval($uid));
    if (!$c) {
        return false;
    }
    $channel = $c[0];
    $r = q("select * from item where id = %d and uid = %d limit 1", intval($item_id), intval($channel['channel_id']));
    if (!$r || $r[0]['obj_type'] !== ACTIVITY_OBJ_EVENT) {
        return false;
    }
    $item = $r[0];
    $ev = bbtoevent($r[0]['body']);
    if (x($ev, 'summary') && x($ev, 'start')) {
        $ev['event_xchan'] = $item['author_xchan'];
        $ev['uid'] = $channel['channel_id'];
        $ev['account'] = $channel['channel_account_id'];
        $ev['edited'] = $item['edited'];
        $ev['mid'] = $item['mid'];
        $ev['private'] = $item['item_private'];
        // is this an edit?
        if ($item['resource_type'] === 'event') {
            $ev['event_hash'] = $item['resource_id'];
        }
        $event = event_store_event($ev);
        if ($event) {
            $r = q("update item set resource_id = '%s', resource_type = 'event' where id = %d and uid = %d", dbesc($event['event_hash']), intval($item['id']), intval($channel['channel_id']));
            $item['resource_id'] = $event['event_hash'];
            $item['resource_type'] = 'event';
            $i = array($item);
            xchan_query($i);
            $sync_item = fetch_post_tags($i);
            $z = q("select * from event where event_hash = '%s' and uid = %d limit 1", dbesc($event['event_hash']), intval($channel['channel_id']));
            if ($z) {
                build_sync_packet($channel['channel_id'], array('event_item' => array(encode_item($sync_item[0], true)), 'event' => $z));
            }
            return true;
        }
    }
    return false;
}
Exemple #8
0
function identity_export_year($channel_id, $year, $month = 0)
{
    if (!$year) {
        return array();
    }
    if ($month && $month <= 12) {
        $target_month = sprintf('%02d', $month);
        $target_month_plus = sprintf('%02d', $month + 1);
    } else {
        $target_month = '01';
    }
    $ret = array();
    $mindate = datetime_convert('UTC', 'UTC', $year . '-' . $target_month . '-01 00:00:00');
    if ($month && $month < 12) {
        $maxdate = datetime_convert('UTC', 'UTC', $year . '-' . $target_month_plus . '-01 00:00:00');
    } else {
        $maxdate = datetime_convert('UTC', 'UTC', $year + 1 . '-01-01 00:00:00');
    }
    $r = q("select * from item where item_wall = 1 and item_deleted = 0 and uid = %d and created >= '%s' and created < '%s'  and resource_type = '' order by created", intval($channel_id), dbesc($mindate), dbesc($maxdate));
    if ($r) {
        $ret['item'] = array();
        xchan_query($r);
        $r = fetch_post_tags($r, true);
        foreach ($r as $rr) {
            $ret['item'][] = encode_item($rr, true);
        }
    }
    $r = q("select item_id.*, item.mid from item_id left join item on item_id.iid = item.id where item_id.uid = %d \n\t\tand item.created >= '%s' and item.created < '%s' order by created ", intval($channel_id), dbesc($mindate), dbesc($maxdate));
    if ($r) {
        $ret['item_id'] = $r;
    }
    return $ret;
}
Exemple #9
0
function notifier_run($argv, $argc)
{
    cli_startup();
    $a = get_app();
    if ($argc < 3) {
        return;
    }
    logger('notifier: invoked: ' . print_r($argv, true), LOGGER_DEBUG);
    $cmd = $argv[1];
    $item_id = $argv[2];
    $extra = $argc > 3 ? $argv[3] : null;
    if (!$item_id) {
        return;
    }
    $sys = get_sys_channel();
    $deliveries = array();
    $dead_hubs = array();
    $dh = q("select site_url from site where site_dead = 1");
    if ($dh) {
        foreach ($dh as $dead) {
            $dead_hubs[] = $dead['site_url'];
        }
    }
    $request = false;
    $mail = false;
    $top_level = false;
    $location = false;
    $recipients = array();
    $url_recipients = array();
    $normal_mode = true;
    $packet_type = 'undefined';
    if ($cmd === 'mail') {
        $normal_mode = false;
        $mail = true;
        $private = true;
        $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1", intval($item_id));
        if (!$message) {
            return;
        }
        xchan_mail_query($message[0]);
        $uid = $message[0]['channel_id'];
        $recipients[] = $message[0]['from_xchan'];
        // include clones
        $recipients[] = $message[0]['to_xchan'];
        $item = $message[0];
        $encoded_item = encode_mail($item);
        $s = q("select * from channel where channel_id = %d limit 1", intval($item['channel_id']));
        if ($s) {
            $channel = $s[0];
        }
    } elseif ($cmd === 'request') {
        $channel_id = $item_id;
        $xchan = $argv[3];
        $request_message_id = $argv[4];
        $s = q("select * from channel where channel_id = %d limit 1", intval($channel_id));
        if ($s) {
            $channel = $s[0];
        }
        $private = true;
        $recipients[] = $xchan;
        $packet_type = 'request';
        $normal_mode = false;
    } elseif ($cmd == 'permission_update' || $cmd == 'permission_create') {
        // Get the (single) recipient
        $r = q("select * from abook left join xchan on abook_xchan = xchan_hash where abook_id = %d and abook_self = 0", intval($item_id));
        if ($r) {
            $uid = $r[0]['abook_channel'];
            // Get the sender
            $channel = channelx_by_n($uid);
            if ($channel) {
                $perm_update = array('sender' => $channel, 'recipient' => $r[0], 'success' => false, 'deliveries' => '');
                if ($cmd == 'permission_create') {
                    call_hooks('permissions_create', $perm_update);
                } else {
                    call_hooks('permissions_update', $perm_update);
                }
                if ($perm_update['success']) {
                    if ($perm_update['deliveries']) {
                        $deliveries[] = $perm_update['deliveries'];
                        do_delivery($deliveries);
                    }
                    return;
                } else {
                    $recipients[] = $r[0]['abook_xchan'];
                    $private = false;
                    $packet_type = 'refresh';
                    $packet_recips = array(array('guid' => $r[0]['xchan_guid'], 'guid_sig' => $r[0]['xchan_guid_sig'], 'hash' => $r[0]['xchan_hash']));
                }
            }
        }
    } elseif ($cmd === 'refresh_all') {
        logger('notifier: refresh_all: ' . $item_id);
        $uid = $item_id;
        $channel = channelx_by_n($item_id);
        $r = q("select abook_xchan from abook where abook_channel = %d", intval($item_id));
        if ($r) {
            foreach ($r as $rr) {
                $recipients[] = $rr['abook_xchan'];
            }
        }
        $private = false;
        $packet_type = 'refresh';
    } elseif ($cmd === 'location') {
        logger('notifier: location: ' . $item_id);
        $s = q("select * from channel where channel_id = %d limit 1", intval($item_id));
        if ($s) {
            $channel = $s[0];
        }
        $uid = $item_id;
        $recipients = array();
        $r = q("select abook_xchan from abook where abook_channel = %d", intval($item_id));
        if ($r) {
            foreach ($r as $rr) {
                $recipients[] = $rr['abook_xchan'];
            }
        }
        $encoded_item = array('locations' => zot_encode_locations($channel), 'type' => 'location', 'encoding' => 'zot');
        $target_item = array('aid' => $channel['channel_account_id'], 'uid' => $channel['channel_id']);
        $private = false;
        $packet_type = 'location';
        $location = true;
    } elseif ($cmd === 'purge_all') {
        logger('notifier: purge_all: ' . $item_id);
        $s = q("select * from channel where channel_id = %d limit 1", intval($item_id));
        if ($s) {
            $channel = $s[0];
        }
        $uid = $item_id;
        $recipients = array();
        $r = q("select abook_xchan from abook where abook_channel = %d", intval($item_id));
        if ($r) {
            foreach ($r as $rr) {
                $recipients[] = $rr['abook_xchan'];
            }
        }
        $private = false;
        $packet_type = 'purge';
    } else {
        // Normal items
        // Fetch the target item
        $r = q("SELECT * FROM item WHERE id = %d and parent != 0 LIMIT 1", intval($item_id));
        if (!$r) {
            return;
        }
        xchan_query($r);
        $r = fetch_post_tags($r);
        $target_item = $r[0];
        $deleted_item = false;
        if (intval($target_item['item_deleted'])) {
            logger('notifier: target item ITEM_DELETED', LOGGER_DEBUG);
            $deleted_item = true;
        }
        if (intval($target_item['item_type']) != ITEM_TYPE_POST) {
            logger('notifier: target item not forwardable: type ' . $target_item['item_type'], LOGGER_DEBUG);
            return;
        }
        if (intval($target_item['item_unpublished']) || intval($target_item['item_delayed'])) {
            logger('notifier: target item not published, so not forwardable', LOGGER_DEBUG);
            return;
        }
        if (strpos($target_item['postopts'], 'nodeliver') !== false) {
            logger('notifier: target item is undeliverable', LOGGER_DEBUG);
            return;
        }
        $s = q("select * from channel left join xchan on channel_hash = xchan_hash where channel_id = %d limit 1", intval($target_item['uid']));
        if ($s) {
            $channel = $s[0];
        }
        if ($channel['channel_hash'] !== $target_item['author_xchan'] && $channel['channel_hash'] !== $target_item['owner_xchan']) {
            logger("notifier: Sending channel {$channel['channel_hash']} is not owner {$target_item['owner_xchan']} or author {$target_item['author_xchan']}", LOGGER_NORMAL, LOG_WARNING);
            return;
        }
        if ($target_item['id'] == $target_item['parent']) {
            $parent_item = $target_item;
            $top_level_post = true;
        } else {
            // fetch the parent item
            $r = q("SELECT * from item where id = %d order by id asc", intval($target_item['parent']));
            if (!$r) {
                return;
            }
            if (strpos($r[0]['postopts'], 'nodeliver') !== false) {
                logger('notifier: target item is undeliverable', LOGGER_DEBUG, LOG_NOTICE);
                return;
            }
            xchan_query($r);
            $r = fetch_post_tags($r);
            $parent_item = $r[0];
            $top_level_post = false;
        }
        // avoid looping of discover items 12/4/2014
        if ($sys && $parent_item['uid'] == $sys['channel_id']) {
            return;
        }
        $encoded_item = encode_item($target_item);
        // Send comments to the owner to re-deliver to everybody in the conversation
        // We only do this if the item in question originated on this site. This prevents looping.
        // To clarify, a site accepting a new comment is responsible for sending it to the owner for relay.
        // Relaying should never be initiated on a post that arrived from elsewhere.
        // We should normally be able to rely on ITEM_ORIGIN, but start_delivery_chain() incorrectly set this
        // flag on comments for an extended period. So we'll also call comment_local_origin() which looks at
        // the hostname in the message_id and provides a second (fallback) opinion.
        $relay_to_owner = !$top_level_post && intval($target_item['item_origin']) && comment_local_origin($target_item) ? true : false;
        $uplink = false;
        // $cmd === 'relay' indicates the owner is sending it to the original recipients
        // don't allow the item in the relay command to relay to owner under any circumstances, it will loop
        logger('notifier: relay_to_owner: ' . ($relay_to_owner ? 'true' : 'false'), LOGGER_DATA, LOG_DEBUG);
        logger('notifier: top_level_post: ' . ($top_level_post ? 'true' : 'false'), LOGGER_DATA, LOG_DEBUG);
        // tag_deliver'd post which needs to be sent back to the original author
        if ($cmd === 'uplink' && intval($parent_item['item_uplink']) && !$top_level_post) {
            logger('notifier: uplink');
            $uplink = true;
        }
        if (($relay_to_owner || $uplink) && $cmd !== 'relay') {
            logger('notifier: followup relay', LOGGER_DEBUG);
            $recipients = array($uplink ? $parent_item['source_xchan'] : $parent_item['owner_xchan']);
            $private = true;
            if (!$encoded_item['flags']) {
                $encoded_item['flags'] = array();
            }
            $encoded_item['flags'][] = 'relay';
        } else {
            logger('notifier: normal distribution', LOGGER_DEBUG);
            if ($cmd === 'relay') {
                logger('notifier: owner relay');
            }
            // if our parent is a tag_delivery recipient, uplink to the original author causing
            // a delivery fork.
            if ($parent_item && intval($parent_item['item_uplink']) && !$top_level_post && $cmd !== 'uplink') {
                // don't uplink a relayed post to the relay owner
                if ($parent_item['source_xchan'] !== $parent_item['owner_xchan']) {
                    logger('notifier: uplinking this item');
                    proc_run('php', 'include/notifier.php', 'uplink', $item_id);
                }
            }
            $private = false;
            $recipients = collect_recipients($parent_item, $private);
            // FIXME add any additional recipients such as mentions, etc.
            // don't send deletions onward for other people's stuff
            // TODO verify this is needed - copied logic from same place in old code
            if (intval($target_item['item_deleted']) && !intval($target_item['item_wall'])) {
                logger('notifier: ignoring delete notification for non-wall item', LOGGER_NORMAL, LOG_NOTICE);
                return;
            }
        }
    }
    $walltowall = $top_level_post && $channel['xchan_hash'] === $target_item['author_xchan'] ? true : false;
    // Generic delivery section, we have an encoded item and recipients
    // Now start the delivery process
    $x = $encoded_item;
    $x['title'] = 'private';
    $x['body'] = 'private';
    logger('notifier: encoded item: ' . print_r($x, true), LOGGER_DATA, LOG_DEBUG);
    stringify_array_elms($recipients);
    if (!$recipients) {
        return;
    }
    //	logger('notifier: recipients: ' . print_r($recipients,true), LOGGER_NORMAL, LOG_DEBUG);
    $env_recips = $private ? array() : null;
    $details = q("select xchan_hash, xchan_instance_url, xchan_network, xchan_addr, xchan_guid, xchan_guid_sig from xchan where xchan_hash in (" . implode(',', $recipients) . ")");
    $recip_list = array();
    if ($details) {
        foreach ($details as $d) {
            $recip_list[] = $d['xchan_addr'] . ' (' . $d['xchan_hash'] . ')';
            if ($private) {
                $env_recips[] = array('guid' => $d['xchan_guid'], 'guid_sig' => $d['xchan_guid_sig'], 'hash' => $d['xchan_hash']);
            }
            if ($d['xchan_network'] === 'mail' && $normal_mode) {
                $delivery_options = get_xconfig($d['xchan_hash'], 'system', 'delivery_mode');
                if (!$delivery_options) {
                    format_and_send_email($channel, $d, $target_item);
                }
            }
        }
    }
    $narr = array('channel' => $channel, 'env_recips' => $env_recips, 'packet_recips' => $packet_recips, 'recipients' => $recipients, 'item' => $item, 'target_item' => $target_item, 'top_level_post' => $top_level_post, 'private' => $private, 'followup' => $followup, 'relay_to_owner' => $relay_to_owner, 'uplink' => $uplink, 'cmd' => $cmd, 'mail' => $mail, 'location' => $location, 'request' => $request, 'normal_mode' => $normal_mode, 'packet_type' => $packet_type, 'walltowall' => $walltowall, 'queued' => array());
    call_hooks('notifier_process', $narr);
    if ($narr['queued']) {
        foreach ($narr['queued'] as $pq) {
            $deliveries[] = $pq;
        }
    }
    if ($private && !$env_recips) {
        // shouldn't happen
        logger('notifier: private message with no envelope recipients.' . print_r($argv, true), LOGGER_NORMAL, LOG_NOTICE);
    }
    logger('notifier: recipients (may be delivered to more if public): ' . print_r($recip_list, true), LOGGER_DEBUG);
    // Now we have collected recipients (except for external mentions, FIXME)
    // Let's reduce this to a set of hubs.
    $r = q("select * from hubloc where hubloc_hash in (" . implode(',', $recipients) . ") \n\t\tand hubloc_error = 0 and hubloc_deleted = 0");
    if (!$r) {
        logger('notifier: no hubs', LOGGER_NORMAL, LOG_NOTICE);
        return;
    }
    $hubs = $r;
    /**
     * Reduce the hubs to those that are unique. For zot hubs, we need to verify uniqueness by the sitekey, since it may have been 
     * a re-install which has not yet been detected and pruned.
     * For other networks which don't have or require sitekeys, we'll have to use the URL
     */
    $hublist = array();
    // this provides an easily printable list for the logs
    $dhubs = array();
    // delivery hubs where we store our resulting unique array
    $keys = array();
    // array of keys to check uniquness for zot hubs
    $urls = array();
    // array of urls to check uniqueness of hubs from other networks
    foreach ($hubs as $hub) {
        if (in_array($hub['hubloc_url'], $dead_hubs)) {
            logger('skipping dead hub: ' . $hub['hubloc_url'], LOGGER_DEBUG, LOG_INFO);
            continue;
        }
        if ($hub['hubloc_network'] == 'zot') {
            if (!in_array($hub['hubloc_sitekey'], $keys)) {
                $hublist[] = $hub['hubloc_host'];
                $dhubs[] = $hub;
                $keys[] = $hub['hubloc_sitekey'];
            }
        } else {
            if (!in_array($hub['hubloc_url'], $urls)) {
                $hublist[] = $hub['hubloc_host'];
                $dhubs[] = $hub;
                $urls[] = $hub['hubloc_url'];
            }
        }
    }
    logger('notifier: will notify/deliver to these hubs: ' . print_r($hublist, true), LOGGER_DEBUG, LOG_DEBUG);
    foreach ($dhubs as $hub) {
        if ($hub['hubloc_network'] !== 'zot') {
            $narr = array('channel' => $channel, 'env_recips' => $env_recips, 'packet_recips' => $packet_recips, 'recipients' => $recipients, 'item' => $item, 'target_item' => $target_item, 'hub' => $hub, 'top_level_post' => $top_level_post, 'private' => $private, 'followup' => $followup, 'relay_to_owner' => $relay_to_owner, 'uplink' => $uplink, 'cmd' => $cmd, 'mail' => $mail, 'location' => $location, 'request' => $request, 'normal_mode' => $normal_mode, 'packet_type' => $packet_type, 'walltowall' => $walltowall, 'queued' => array());
            call_hooks('notifier_hub', $narr);
            if ($narr['queued']) {
                foreach ($narr['queued'] as $pq) {
                    $deliveries[] = $pq;
                }
            }
            continue;
        }
        // default: zot protocol
        $hash = random_string();
        $packet = null;
        if ($packet_type === 'refresh' || $packet_type === 'purge') {
            $packet = zot_build_packet($channel, $packet_type, $packet_recips ? $packet_recips : null);
        } elseif ($packet_type === 'request') {
            $packet = zot_build_packet($channel, $packet_type, $env_recips, $hub['hubloc_sitekey'], $hash, array('message_id' => $request_message_id));
        }
        if ($packet) {
            queue_insert(array('hash' => $hash, 'account_id' => $channel['channel_account_id'], 'channel_id' => $channel['channel_id'], 'posturl' => $hub['hubloc_callback'], 'notify' => $packet));
        } else {
            $packet = zot_build_packet($channel, 'notify', $env_recips, $private ? $hub['hubloc_sitekey'] : null, $hash);
            queue_insert(array('hash' => $hash, 'account_id' => $target_item['aid'], 'channel_id' => $target_item['uid'], 'posturl' => $hub['hubloc_callback'], 'notify' => $packet, 'msg' => json_encode($encoded_item)));
            // only create delivery reports for normal undeleted items
            if (is_array($target_item) && array_key_exists('postopts', $target_item) && !$target_item['item_deleted'] && !get_config('system', 'disable_dreport')) {
                q("insert into dreport ( dreport_mid, dreport_site, dreport_recip, dreport_result, dreport_time, dreport_xchan, dreport_queue ) values ( '%s','%s','%s','%s','%s','%s','%s' ) ", dbesc($target_item['mid']), dbesc($hub['hubloc_host']), dbesc($hub['hubloc_host']), dbesc('queued'), dbesc(datetime_convert()), dbesc($channel['channel_hash']), dbesc($hash));
            }
        }
        $deliveries[] = $hash;
    }
    if ($normal_mode) {
        $x = q("select * from hook where hook = 'notifier_normal'");
        if ($x) {
            proc_run('php', 'include/deliver_hooks.php', $target_item['id']);
        }
    }
    if ($deliveries) {
        do_delivery($deliveries);
    }
    logger('notifier: basic loop complete.', LOGGER_DEBUG);
    call_hooks('notifier_end', $target_item);
    logger('notifer: complete.');
    return;
}
Exemple #10
0
function item_post(&$a)
{
    // This will change. Figure out who the observer is and whether or not
    // they have permission to post here. Else ignore the post.
    if (!local_channel() && !remote_channel() && !x($_REQUEST, 'commenter')) {
        return;
    }
    require_once 'include/security.php';
    $uid = local_channel();
    $channel = null;
    $observer = null;
    /**
     * Is this a reply to something?
     */
    $parent = x($_REQUEST, 'parent') ? intval($_REQUEST['parent']) : 0;
    $parent_mid = x($_REQUEST, 'parent_mid') ? trim($_REQUEST['parent_mid']) : '';
    $remote_xchan = x($_REQUEST, 'remote_xchan') ? trim($_REQUEST['remote_xchan']) : false;
    $r = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($remote_xchan));
    if ($r) {
        $remote_observer = $r[0];
    } else {
        $remote_xchan = $remote_observer = false;
    }
    $profile_uid = x($_REQUEST, 'profile_uid') ? intval($_REQUEST['profile_uid']) : 0;
    require_once 'include/identity.php';
    $sys = get_sys_channel();
    if ($sys && $profile_uid && $sys['channel_id'] == $profile_uid && is_site_admin()) {
        $uid = intval($sys['channel_id']);
        $channel = $sys;
        $observer = $sys;
    }
    if (x($_REQUEST, 'dropitems')) {
        require_once 'include/items.php';
        $arr_drop = explode(',', $_REQUEST['dropitems']);
        drop_items($arr_drop);
        $json = array('success' => 1);
        echo json_encode($json);
        killme();
    }
    call_hooks('post_local_start', $_REQUEST);
    //	 logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
    $api_source = x($_REQUEST, 'api_source') && $_REQUEST['api_source'] ? true : false;
    $consensus = intval($_REQUEST['consensus']);
    // 'origin' (if non-zero) indicates that this network is where the message originated,
    // for the purpose of relaying comments to other conversation members.
    // If using the API from a device (leaf node) you must set origin to 1 (default) or leave unset.
    // If the API is used from another network with its own distribution
    // and deliveries, you may wish to set origin to 0 or false and allow the other
    // network to relay comments.
    // If you are unsure, it is prudent (and important) to leave it unset.
    $origin = $api_source && array_key_exists('origin', $_REQUEST) ? intval($_REQUEST['origin']) : 1;
    // To represent message-ids on other networks - this will create an item_id record
    $namespace = $api_source && array_key_exists('namespace', $_REQUEST) ? strip_tags($_REQUEST['namespace']) : '';
    $remote_id = $api_source && array_key_exists('remote_id', $_REQUEST) ? strip_tags($_REQUEST['remote_id']) : '';
    $owner_hash = null;
    $message_id = x($_REQUEST, 'message_id') && $api_source ? strip_tags($_REQUEST['message_id']) : '';
    $created = x($_REQUEST, 'created') ? datetime_convert('UTC', 'UTC', $_REQUEST['created']) : datetime_convert();
    $post_id = x($_REQUEST, 'post_id') ? intval($_REQUEST['post_id']) : 0;
    $app = x($_REQUEST, 'source') ? strip_tags($_REQUEST['source']) : '';
    $return_path = x($_REQUEST, 'return') ? $_REQUEST['return'] : '';
    $preview = x($_REQUEST, 'preview') ? intval($_REQUEST['preview']) : 0;
    $categories = x($_REQUEST, 'category') ? escape_tags($_REQUEST['category']) : '';
    $webpage = x($_REQUEST, 'webpage') ? intval($_REQUEST['webpage']) : 0;
    $pagetitle = x($_REQUEST, 'pagetitle') ? escape_tags(urlencode($_REQUEST['pagetitle'])) : '';
    $layout_mid = x($_REQUEST, 'layout_mid') ? escape_tags($_REQUEST['layout_mid']) : '';
    $plink = x($_REQUEST, 'permalink') ? escape_tags($_REQUEST['permalink']) : '';
    $obj_type = x($_REQUEST, 'obj_type') ? escape_tags($_REQUEST['obj_type']) : ACTIVITY_OBJ_NOTE;
    // allow API to bulk load a bunch of imported items with sending out a bunch of posts.
    $nopush = x($_REQUEST, 'nopush') ? intval($_REQUEST['nopush']) : 0;
    /*
     * Check service class limits
     */
    if ($uid && !x($_REQUEST, 'parent') && !x($_REQUEST, 'post_id')) {
        $ret = item_check_service_class($uid, $_REQUEST['webpage'] == ITEM_TYPE_WEBPAGE ? true : false);
        if (!$ret['success']) {
            notice(t($ret['message']) . EOL);
            if (x($_REQUEST, 'return')) {
                goaway($a->get_baseurl() . "/" . $return_path);
            }
            killme();
        }
    }
    if ($pagetitle) {
        require_once 'library/urlify/URLify.php';
        $pagetitle = strtolower(URLify::transliterate($pagetitle));
    }
    $item_flags = $item_restrict = 0;
    $route = '';
    $parent_item = null;
    $parent_contact = null;
    $thr_parent = '';
    $parid = 0;
    $r = false;
    if ($parent || $parent_mid) {
        if (!x($_REQUEST, 'type')) {
            $_REQUEST['type'] = 'net-comment';
        }
        if ($obj_type == ACTIVITY_OBJ_POST) {
            $obj_type = ACTIVITY_OBJ_COMMENT;
        }
        if ($parent) {
            $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($parent));
        } elseif ($parent_mid && $uid) {
            // This is coming from an API source, and we are logged in
            $r = q("SELECT * FROM `item` WHERE `mid` = '%s' AND `uid` = %d LIMIT 1", dbesc($parent_mid), intval($uid));
        }
        // if this isn't the real parent of the conversation, find it
        if ($r !== false && count($r)) {
            $parid = $r[0]['parent'];
            $parent_mid = $r[0]['mid'];
            if ($r[0]['id'] != $r[0]['parent']) {
                $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1", intval($parid));
            }
        }
        if ($r === false || !count($r)) {
            notice(t('Unable to locate original post.') . EOL);
            if (x($_REQUEST, 'return')) {
                goaway($a->get_baseurl() . "/" . $return_path);
            }
            killme();
        }
        // can_comment_on_post() needs info from the following xchan_query
        xchan_query($r);
        $parent_item = $r[0];
        $parent = $r[0]['id'];
        // multi-level threading - preserve the info but re-parent to our single level threading
        $thr_parent = $parent_mid;
        $route = $parent_item['route'];
    }
    if (!$observer) {
        $observer = $a->get_observer();
    }
    if ($parent) {
        logger('mod_item: item_post parent=' . $parent);
        $can_comment = false;
        if (array_key_exists('owner', $parent_item) && intval($parent_item['owner']['abook_self'])) {
            $can_comment = perm_is_allowed($profile_uid, $observer['xchan_hash'], 'post_comments');
        } else {
            $can_comment = can_comment_on_post($observer['xchan_hash'], $parent_item);
        }
        if (!$can_comment) {
            notice(t('Permission denied.') . EOL);
            if (x($_REQUEST, 'return')) {
                goaway($a->get_baseurl() . "/" . $return_path);
            }
            killme();
        }
    } else {
        if (!perm_is_allowed($profile_uid, $observer['xchan_hash'], 'post_wall')) {
            notice(t('Permission denied.') . EOL);
            if (x($_REQUEST, 'return')) {
                goaway($a->get_baseurl() . "/" . $return_path);
            }
            killme();
        }
    }
    // is this an edited post?
    $orig_post = null;
    if ($namespace && $remote_id) {
        // It wasn't an internally generated post - see if we've got an item matching this remote service id
        $i = q("select iid from item_id where service = '%s' and sid = '%s' limit 1", dbesc($namespace), dbesc($remote_id));
        if ($i) {
            $post_id = $i[0]['iid'];
        }
    }
    if ($post_id) {
        $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1", intval($profile_uid), intval($post_id));
        if (!count($i)) {
            killme();
        }
        $orig_post = $i[0];
    }
    if (!$channel) {
        if ($uid && $uid == $profile_uid) {
            $channel = $a->get_channel();
        } else {
            // posting as yourself but not necessarily to a channel you control
            $r = q("select * from channel left join account on channel_account_id = account_id where channel_id = %d LIMIT 1", intval($profile_uid));
            if ($r) {
                $channel = $r[0];
            }
        }
    }
    if (!$channel) {
        logger("mod_item: no channel.");
        if (x($_REQUEST, 'return')) {
            goaway($a->get_baseurl() . "/" . $return_path);
        }
        killme();
    }
    $owner_xchan = null;
    $r = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($channel['channel_hash']));
    if ($r && count($r)) {
        $owner_xchan = $r[0];
    } else {
        logger("mod_item: no owner.");
        if (x($_REQUEST, 'return')) {
            goaway($a->get_baseurl() . "/" . $return_path);
        }
        killme();
    }
    $walltowall = false;
    $walltowall_comment = false;
    if ($remote_xchan) {
        $observer = $remote_observer;
    }
    if ($observer) {
        logger('mod_item: post accepted from ' . $observer['xchan_name'] . ' for ' . $owner_xchan['xchan_name'], LOGGER_DEBUG);
        // wall-to-wall detection.
        // For top-level posts, if the author and owner are different it's a wall-to-wall
        // For comments, We need to additionally look at the parent and see if it's a wall post that originated locally.
        if ($observer['xchan_name'] != $owner_xchan['xchan_name']) {
            if ($parent_item && ($parent_item['item_wall'] && $parent_item['item_origin'])) {
                $walltowall_comment = true;
                $walltowall = true;
            }
            if (!$parent) {
                $walltowall = true;
            }
        }
    }
    $acl = new AccessList($channel);
    $public_policy = x($_REQUEST, 'public_policy') ? escape_tags($_REQUEST['public_policy']) : map_scope($channel['channel_r_stream'], true);
    if ($webpage) {
        $public_policy = '';
    }
    if ($public_policy) {
        $private = 1;
    }
    if ($orig_post) {
        $private = 0;
        // webpages are allowed to change ACLs after the fact. Normal conversation items aren't.
        if ($webpage) {
            $acl->set_from_array($_REQUEST);
        } else {
            $acl->set($orig_post);
            $public_policy = $orig_post['public_policy'];
            $private = $orig_post['item_private'];
        }
        if ($private || $public_policy || $acl->is_private()) {
            $private = 1;
        }
        $location = $orig_post['location'];
        $coord = $orig_post['coord'];
        $verb = $orig_post['verb'];
        $app = $orig_post['app'];
        $title = escape_tags(trim($_REQUEST['title']));
        $body = trim($_REQUEST['body']);
        $item_flags = $orig_post['item_flags'];
        $item_origin = $orig_post['item_origin'];
        $item_unseen = $orig_post['item_unseen'];
        $item_starred = $orig_post['item_starred'];
        $item_uplink = $orig_post['item_uplink'];
        $item_consensus = $orig_post['item_consensus'];
        $item_wall = $orig_post['item_wall'];
        $item_thread_top = $orig_post['item_thread_top'];
        $item_notshown = $orig_post['item_notshown'];
        $item_nsfw = $orig_post['item_nsfw'];
        $item_relay = $orig_post['item_relay'];
        $item_mentionsme = $orig_post['item_mentionsme'];
        $item_nocomment = $orig_post['item_nocomment'];
        $item_obscured = $orig_post['item_obscured'];
        $item_verified = $orig_post['item_verified'];
        $item_retained = $orig_post['item_retained'];
        $item_rss = $orig_post['item_rss'];
        $item_deleted = $orig_post['item_deleted'];
        $item_type = $orig_post['item_type'];
        $item_hidden = $orig_post['item_hidden'];
        $item_unpublished = $orig_post['item_unpublished'];
        $item_delayed = $orig_post['item_delayed'];
        $item_pending_remove = $orig_post['item_pending_remove'];
        $item_blocked = $orig_post['item_blocked'];
        $postopts = $orig_post['postopts'];
        $created = $orig_post['created'];
        $mid = $orig_post['mid'];
        $parent_mid = $orig_post['parent_mid'];
        $plink = $orig_post['plink'];
    } else {
        if (!$walltowall && (array_key_exists('contact_allow', $_REQUEST) || array_key_exists('group_allow', $_REQUEST) || array_key_exists('contact_deny', $_REQUEST) || array_key_exists('group_deny', $_REQUEST))) {
            $acl->set_from_array($_REQUEST);
        }
        $location = notags(trim($_REQUEST['location']));
        $coord = notags(trim($_REQUEST['coord']));
        $verb = notags(trim($_REQUEST['verb']));
        $title = escape_tags(trim($_REQUEST['title']));
        $body = trim($_REQUEST['body']);
        $body .= trim($_REQUEST['attachment']);
        $postopts = '';
        $private = intval($acl->is_private() || $public_policy);
        // If this is a comment, set the permissions from the parent.
        if ($parent_item) {
            $private = 0;
            $acl->set($parent_item);
            $private = intval($acl->is_private() || $parent_item['item_private']);
            $public_policy = $parent_item['public_policy'];
            $owner_hash = $parent_item['owner_xchan'];
        }
        if (!strlen($body)) {
            if ($preview) {
                killme();
            }
            info(t('Empty post discarded.') . EOL);
            if (x($_REQUEST, 'return')) {
                goaway($a->get_baseurl() . "/" . $return_path);
            }
            killme();
        }
    }
    $expires = NULL_DATE;
    if (feature_enabled($profile_uid, 'content_expire')) {
        if (x($_REQUEST, 'expire')) {
            $expires = datetime_convert(date_default_timezone_get(), 'UTC', $_REQUEST['expire']);
            if ($expires <= datetime_convert()) {
                $expires = NULL_DATE;
            }
        }
    }
    $mimetype = notags(trim($_REQUEST['mimetype']));
    if (!$mimetype) {
        $mimetype = 'text/bbcode';
    }
    if ($preview) {
        $body = z_input_filter($profile_uid, $body, $mimetype);
    }
    // Verify ability to use html or php!!!
    $execflag = false;
    if ($mimetype === 'application/x-php') {
        $z = q("select account_id, account_roles, channel_pageflags from account left join channel on channel_account_id = account_id where channel_id = %d limit 1", intval($profile_uid));
        if ($z && ($z[0]['account_roles'] & ACCOUNT_ROLE_ALLOWCODE || $z[0]['channel_pageflags'] & PAGE_ALLOWCODE)) {
            if ($uid && get_account_id() == $z[0]['account_id']) {
                $execflag = true;
            } else {
                notice(t('Executable content type not permitted to this channel.') . EOL);
                if (x($_REQUEST, 'return')) {
                    goaway($a->get_baseurl() . "/" . $return_path);
                }
                killme();
            }
        }
    }
    $gacl = $acl->get();
    $str_contact_allow = $gacl['allow_cid'];
    $str_group_allow = $gacl['allow_gid'];
    $str_contact_deny = $gacl['deny_cid'];
    $str_group_deny = $gacl['deny_gid'];
    if ($mimetype === 'text/bbcode') {
        require_once 'include/text.php';
        if ($uid && $uid == $profile_uid && feature_enabled($uid, 'markdown')) {
            require_once 'include/bb2diaspora.php';
            $body = escape_tags($body);
            $body = preg_replace_callback('/\\[share(.*?)\\]/ism', 'share_shield', $body);
            $body = diaspora2bb($body, true);
            $body = preg_replace_callback('/\\[share(.*?)\\]/ism', 'share_unshield', $body);
        }
        // BBCODE alert: the following functions assume bbcode input
        // and will require alternatives for alternative content-types (text/html, text/markdown, text/plain, etc.)
        // we may need virtual or template classes to implement the possible alternatives
        // Work around doubled linefeeds in Tinymce 3.5b2
        // First figure out if it's a status post that would've been
        // created using tinymce. Otherwise leave it alone.
        $plaintext = true;
        //		$plaintext = ((feature_enabled($profile_uid,'richtext')) ? false : true);
        //		if((! $parent) && (! $api_source) && (! $plaintext)) {
        //			$body = fix_mce_lf($body);
        //		}
        // If we're sending a private top-level message with a single @-taggable channel as a recipient, @-tag it, if our pconfig is set.
        if (!$parent && get_pconfig($profile_uid, 'system', 'tagifonlyrecip') && substr_count($str_contact_allow, '<') == 1 && $str_group_allow == '' && $str_contact_deny == '' && $str_group_deny == '') {
            $x = q("select abook_id, abook_their_perms from abook where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc(str_replace(array('<', '>'), array('', ''), $str_contact_allow)), intval($profile_uid));
            if ($x && $x[0]['abook_their_perms'] & PERMS_W_TAGWALL) {
                $body .= "\n\n@group+" . $x[0]['abook_id'] . "\n";
            }
        }
        /**
         * fix naked links by passing through a callback to see if this is a red site
         * (already known to us) which will get a zrl, otherwise link with url, add bookmark tag to both.
         * First protect any url inside certain bbcode tags so we don't double link it.
         */
        $body = preg_replace_callback('/\\[code(.*?)\\[\\/(code)\\]/ism', 'red_escape_codeblock', $body);
        $body = preg_replace_callback('/\\[url(.*?)\\[\\/(url)\\]/ism', 'red_escape_codeblock', $body);
        $body = preg_replace_callback('/\\[zrl(.*?)\\[\\/(zrl)\\]/ism', 'red_escape_codeblock', $body);
        $body = preg_replace_callback("/([^\\]\\='" . '"' . "\\/]|^|\\#\\^)(https?\\:\\/\\/[a-zA-Z0-9\\:\\/\\-\\?\\&\\;\\.\\=\\@\\_\\~\\#\\%\$\\!\\+\\,]+)/ism", 'red_zrl_callback', $body);
        $body = preg_replace_callback('/\\[\\$b64zrl(.*?)\\[\\/(zrl)\\]/ism', 'red_unescape_codeblock', $body);
        $body = preg_replace_callback('/\\[\\$b64url(.*?)\\[\\/(url)\\]/ism', 'red_unescape_codeblock', $body);
        $body = preg_replace_callback('/\\[\\$b64code(.*?)\\[\\/(code)\\]/ism', 'red_unescape_codeblock', $body);
        // fix any img tags that should be zmg
        $body = preg_replace_callback('/\\[img(.*?)\\](.*?)\\[\\/img\\]/ism', 'red_zrlify_img_callback', $body);
        $body = bb_translate_video($body);
        /**
         * Fold multi-line [code] sequences
         */
        $body = preg_replace('/\\[\\/code\\]\\s*\\[code\\]/ism', "\n", $body);
        $body = scale_external_images($body, false);
        // Look for tags and linkify them
        $results = linkify_tags($a, $body, $uid ? $uid : $profile_uid);
        if ($results) {
            // Set permissions based on tag replacements
            set_linkified_perms($results, $str_contact_allow, $str_group_allow, $profile_uid, $parent_item, $private);
            $post_tags = array();
            foreach ($results as $result) {
                $success = $result['success'];
                if ($success['replaced']) {
                    $post_tags[] = array('uid' => $profile_uid, 'type' => $success['termtype'], 'otype' => TERM_OBJ_POST, 'term' => $success['term'], 'url' => $success['url']);
                }
            }
        }
        /**
         *
         * When a photo was uploaded into the message using the (profile wall) ajax 
         * uploader, The permissions are initially set to disallow anybody but the
         * owner from seeing it. This is because the permissions may not yet have been
         * set for the post. If it's private, the photo permissions should be set
         * appropriately. But we didn't know the final permissions on the post until
         * now. So now we'll look for links of uploaded photos and attachments that are in the
         * post and set them to the same permissions as the post itself.
         *
         * If the post was end-to-end encrypted we can't find images and attachments in the body,
         * use our media_str input instead which only contains these elements - but only do this
         * when encrypted content exists because the photo/attachment may have been removed from 
         * the post and we should keep it private. If it's encrypted we have no way of knowing
         * so we'll set the permissions regardless and realise that the media may not be 
         * referenced in the post. 
         *
         * What is preventing us from being able to upload photos into comments is dealing with
         * the photo and attachment permissions, since we don't always know who was in the 
         * distribution for the top level post.
         * 
         * We might be able to provide this functionality with a lot of fiddling:
         * - if the top level post is public (make the photo public)
         * - if the top level post was written by us or a wall post that belongs to us (match the top level post)
         * - if the top level post has privacy mentions, add those to the permissions.
         * - otherwise disallow the photo *or* make the photo public. This is the part that gets messy. 
         */
        if (!$preview) {
            fix_attached_photo_permissions($profile_uid, $owner_xchan['xchan_hash'], strpos($body, '[/crypt]') ? $_POST['media_str'] : $body, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
            fix_attached_file_permissions($channel, $observer['xchan_hash'], strpos($body, '[/crypt]') ? $_POST['media_str'] : $body, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
        }
        $attachments = '';
        $match = false;
        if (preg_match_all('/(\\[attachment\\](.*?)\\[\\/attachment\\])/', $body, $match)) {
            $attachments = array();
            foreach ($match[2] as $mtch) {
                $attach_link = '';
                $hash = substr($mtch, 0, strpos($mtch, ','));
                $rev = intval(substr($mtch, strpos($mtch, ',')));
                $r = attach_by_hash_nodata($hash, $rev);
                if ($r['success']) {
                    $attachments[] = array('href' => $a->get_baseurl() . '/attach/' . $r['data']['hash'], 'length' => $r['data']['filesize'], 'type' => $r['data']['filetype'], 'title' => urlencode($r['data']['filename']), 'revision' => $r['data']['revision']);
                }
                $ext = substr($r['data']['filename'], strrpos($r['data']['filename'], '.'));
                if (strpos($r['data']['filetype'], 'audio/') !== false) {
                    $attach_link = '[audio]' . z_root() . '/attach/' . $r['data']['hash'] . '/' . $r['data']['revision'] . ($ext ? $ext : '') . '[/audio]';
                } elseif (strpos($r['data']['filetype'], 'video/') !== false) {
                    $attach_link = '[video]' . z_root() . '/attach/' . $r['data']['hash'] . '/' . $r['data']['revision'] . ($ext ? $ext : '') . '[/video]';
                }
                $body = str_replace($match[1], $attach_link, $body);
            }
        }
    }
    // BBCODE end alert
    if (strlen($categories)) {
        $cats = explode(',', $categories);
        foreach ($cats as $cat) {
            $post_tags[] = array('uid' => $profile_uid, 'type' => TERM_CATEGORY, 'otype' => TERM_OBJ_POST, 'term' => trim($cat), 'url' => $owner_xchan['xchan_url'] . '?f=&cat=' . urlencode(trim($cat)));
        }
    }
    $item_unseen = local_channel() != $profile_uid ? 1 : 0;
    $item_wall = $post_type === 'wall' || $post_type === 'wall-comment' ? 1 : 0;
    $item_origin = $origin ? 1 : 0;
    $item_consensus = $consensus ? 1 : 0;
    // determine if this is a wall post
    if ($parent) {
        $item_wall = $parent_item['item_wall'];
    } else {
        if (!$webpage) {
            $item_wall = 1;
        }
    }
    if ($moderated) {
        $item_blocked = ITEM_MODERATED;
    }
    if (!strlen($verb)) {
        $verb = ACTIVITY_POST;
    }
    $notify_type = $parent ? 'comment-new' : 'wall-new';
    if (!$mid) {
        $mid = $message_id ? $message_id : item_message_id();
    }
    if (!$parent_mid) {
        $parent_mid = $mid;
    }
    if ($parent_item) {
        $parent_mid = $parent_item['mid'];
    }
    // Fallback so that we alway have a thr_parent
    if (!$thr_parent) {
        $thr_parent = $mid;
    }
    $datarray = array();
    $item_thead_top = !$parent ? 1 : 0;
    if (!$plink && $item_thread_top) {
        $plink = z_root() . '/channel/' . $channel['channel_address'] . '/?f=&mid=' . $mid;
    }
    $datarray['aid'] = $channel['channel_account_id'];
    $datarray['uid'] = $profile_uid;
    $datarray['owner_xchan'] = $owner_hash ? $owner_hash : $owner_xchan['xchan_hash'];
    $datarray['author_xchan'] = $observer['xchan_hash'];
    $datarray['created'] = $created;
    $datarray['edited'] = $orig_post ? datetime_convert() : $created;
    $datarray['expires'] = $expires;
    $datarray['commented'] = $orig_post ? datetime_convert() : $created;
    $datarray['received'] = $orig_post ? datetime_convert() : $created;
    $datarray['changed'] = $orig_post ? datetime_convert() : $created;
    $datarray['mid'] = $mid;
    $datarray['parent_mid'] = $parent_mid;
    $datarray['mimetype'] = $mimetype;
    $datarray['title'] = $title;
    $datarray['body'] = $body;
    $datarray['app'] = $app;
    $datarray['location'] = $location;
    $datarray['coord'] = $coord;
    $datarray['verb'] = $verb;
    $datarray['obj_type'] = $obj_type;
    $datarray['allow_cid'] = $str_contact_allow;
    $datarray['allow_gid'] = $str_group_allow;
    $datarray['deny_cid'] = $str_contact_deny;
    $datarray['deny_gid'] = $str_group_deny;
    $datarray['item_private'] = $private;
    $datarray['item_wall'] = $item_wall;
    $datarray['attach'] = $attachments;
    $datarray['thr_parent'] = $thr_parent;
    $datarray['postopts'] = $postopts;
    $datarray['item_unseen'] = $item_unseen;
    $datarray['item_wall'] = $item_wall;
    $datarray['item_origin'] = $item_origin;
    $datarray['item_type'] = $webpage;
    $datarray['item_thread_top'] = $item_thread_top;
    $datarray['item_unseen'] = $item_unseen;
    $datarray['item_starred'] = $item_starred;
    $datarray['item_uplink'] = $item_uplink;
    $datarray['item_consensus'] = $item_consensus;
    $datarray['item_notshown'] = $item_notshown;
    $datarray['item_nsfw'] = $item_nsfw;
    $datarray['item_relay'] = $item_relay;
    $datarray['item_mentionsme'] = $item_mentionsme;
    $datarray['item_nocomment'] = $item_nocomment;
    $datarray['item_obscured'] = $item_obscured;
    $datarray['item_verified'] = $item_verified;
    $datarray['item_retained'] = $item_retained;
    $datarray['item_rss'] = $item_rss;
    $datarray['item_deleted'] = $item_deleted;
    $datarray['item_hidden'] = $item_hidden;
    $datarray['item_unpublished'] = $item_unpublished;
    $datarray['item_delayed'] = $item_delayed;
    $datarray['item_pending_remove'] = $item_pending_remove;
    $datarray['item_blocked'] = $item_blocked;
    $datarray['layout_mid'] = $layout_mid;
    $datarray['public_policy'] = $public_policy;
    $datarray['comment_policy'] = map_scope($channel['channel_w_comment']);
    $datarray['term'] = $post_tags;
    $datarray['plink'] = $plink;
    $datarray['route'] = $route;
    // preview mode - prepare the body for display and send it via json
    if ($preview) {
        require_once 'include/conversation.php';
        $datarray['owner'] = $owner_xchan;
        $datarray['author'] = $observer;
        $datarray['attach'] = json_encode($datarray['attach']);
        $o = conversation($a, array($datarray), 'search', false, 'preview');
        //		logger('preview: ' . $o, LOGGER_DEBUG);
        echo json_encode(array('preview' => $o));
        killme();
    }
    if ($orig_post) {
        $datarray['edit'] = true;
    }
    call_hooks('post_local', $datarray);
    if (x($datarray, 'cancel')) {
        logger('mod_item: post cancelled by plugin.');
        if ($return_path) {
            goaway($a->get_baseurl() . "/" . $return_path);
        }
        $json = array('cancel' => 1);
        if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
            $json['reload'] = $a->get_baseurl() . '/' . $_REQUEST['jsreload'];
        }
        echo json_encode($json);
        killme();
    }
    if (mb_strlen($datarray['title']) > 255) {
        $datarray['title'] = mb_substr($datarray['title'], 0, 255);
    }
    if (array_key_exists('item_private', $datarray) && $datarray['item_private']) {
        $datarray['body'] = trim(z_input_filter($datarray['uid'], $datarray['body'], $datarray['mimetype']));
        if ($uid) {
            if ($channel['channel_hash'] === $datarray['author_xchan']) {
                $datarray['sig'] = base64url_encode(rsa_sign($datarray['body'], $channel['channel_prvkey']));
                $datarray['item_verified'] = 1;
            }
        }
    }
    if ($orig_post) {
        $datarray['id'] = $post_id;
        item_store_update($datarray, $execflag);
        update_remote_id($channel, $post_id, $webpage, $pagetitle, $namespace, $remote_id, $mid);
        if (!$parent) {
            $r = q("select * from item where id = %d", intval($post_id));
            if ($r) {
                xchan_query($r);
                $sync_item = fetch_post_tags($r);
                $rid = q("select * from item_id where iid = %d", intval($post_id));
                build_sync_packet($uid, array('item' => array(encode_item($sync_item[0], true)), 'item_id' => $rid));
            }
        }
        if (!$nopush) {
            proc_run('php', "include/notifier.php", 'edit_post', $post_id);
        }
        if (x($_REQUEST, 'return') && strlen($return_path)) {
            logger('return: ' . $return_path);
            goaway($a->get_baseurl() . "/" . $return_path);
        }
        killme();
    } else {
        $post_id = 0;
    }
    $post = item_store($datarray, $execflag);
    $post_id = $post['item_id'];
    if ($post_id) {
        logger('mod_item: saved item ' . $post_id);
        if ($parent) {
            // only send comment notification if this is a wall-to-wall comment,
            // otherwise it will happen during delivery
            if ($datarray['owner_xchan'] != $datarray['author_xchan'] && intval($parent_item['item_wall'])) {
                notification(array('type' => NOTIFY_COMMENT, 'from_xchan' => $datarray['author_xchan'], 'to_xchan' => $datarray['owner_xchan'], 'item' => $datarray, 'link' => $a->get_baseurl() . '/display/' . $datarray['mid'], 'verb' => ACTIVITY_POST, 'otype' => 'item', 'parent' => $parent, 'parent_mid' => $parent_item['mid']));
            }
        } else {
            $parent = $post_id;
            if ($datarray['owner_xchan'] != $datarray['author_xchan']) {
                notification(array('type' => NOTIFY_WALL, 'from_xchan' => $datarray['author_xchan'], 'to_xchan' => $datarray['owner_xchan'], 'item' => $datarray, 'link' => $a->get_baseurl() . '/display/' . $datarray['mid'], 'verb' => ACTIVITY_POST, 'otype' => 'item'));
            }
            if ($uid && $uid == $profile_uid && is_item_normal($datarray)) {
                q("update channel set channel_lastpost = '%s' where channel_id = %d", dbesc(datetime_convert()), intval($uid));
            }
        }
        // photo comments turn the corresponding item visible to the profile wall
        // This way we don't see every picture in your new photo album posted to your wall at once.
        // They will show up as people comment on them.
        if (intval($parent_item['item_hidden'])) {
            $r = q("UPDATE item SET item_hidden = 0 WHERE id = %d", intval($parent_item['id']));
        }
    } else {
        logger('mod_item: unable to retrieve post that was just stored.');
        notice(t('System error. Post not saved.') . EOL);
        goaway($a->get_baseurl() . "/" . $return_path);
        // NOTREACHED
    }
    update_remote_id($channel, $post_id, $webpage, $pagetitle, $namespace, $remote_id, $mid);
    if ($parent && $parent != $post_id) {
        // Store the comment signature information in case we need to relay to Diaspora
        $ditem = $datarray;
        $ditem['author'] = $observer;
        store_diaspora_comment_sig($ditem, $channel, $parent_item, $post_id, $walltowall_comment ? 1 : 0);
    } else {
        $r = q("select * from item where id = %d", intval($post_id));
        if ($r) {
            xchan_query($r);
            $sync_item = fetch_post_tags($r);
            $rid = q("select * from item_id where iid = %d", intval($post_id));
            build_sync_packet($uid, array('item' => array(encode_item($sync_item[0], true)), 'item_id' => $rid));
        }
    }
    $datarray['id'] = $post_id;
    $datarray['llink'] = $a->get_baseurl() . '/display/' . $channel['channel_address'] . '/' . $post_id;
    call_hooks('post_local_end', $datarray);
    if (!$nopush) {
        proc_run('php', 'include/notifier.php', $notify_type, $post_id);
    }
    logger('post_complete');
    // figure out how to return, depending on from whence we came
    if ($api_source) {
        return $post;
    }
    if ($return_path) {
        goaway($a->get_baseurl() . "/" . $return_path);
    }
    $json = array('success' => 1);
    if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
        $json['reload'] = $a->get_baseurl() . '/' . $_REQUEST['jsreload'];
    }
    logger('post_json: ' . print_r($json, true), LOGGER_DEBUG);
    echo json_encode($json);
    killme();
    // NOTREACHED
}
Exemple #11
0
function notifier_run($argv, $argc)
{
    cli_startup();
    $a = get_app();
    require_once "session.php";
    require_once "datetime.php";
    require_once 'include/items.php';
    require_once 'include/bbcode.php';
    if ($argc < 3) {
        return;
    }
    logger('notifier: invoked: ' . print_r($argv, true), LOGGER_DEBUG);
    $cmd = $argv[1];
    $item_id = $argv[2];
    $extra = $argc > 3 ? $argv[3] : null;
    if (!$item_id) {
        return;
    }
    require_once 'include/identity.php';
    $sys = get_sys_channel();
    if ($cmd == 'permission_update') {
        // Get the recipient
        $r = q("select abook.*, hubloc.* from abook \n\t\t\tleft join hubloc on hubloc_hash = abook_xchan\n\t\t\twhere abook_id = %d and not ( abook_flags & %d ) > 0 \n\t\t\tand not (hubloc_flags & %d) > 0  and not (hubloc_status & %d) > 0 limit 1", intval($item_id), intval(ABOOK_FLAG_SELF), intval(HUBLOC_FLAGS_DELETED), intval(HUBLOC_OFFLINE));
        if ($r) {
            // Get the sender
            $s = q("select * from channel left join xchan on channel_hash = xchan_hash where channel_id = %d limit 1", intval($r[0]['abook_channel']));
            if ($s) {
                if ($r[0]['hubloc_network'] === 'diaspora' || $r[0]['hubloc_network'] === 'friendica-over-diaspora') {
                    require_once 'include/diaspora.php';
                    diaspora_share($s[0], $r[0]);
                } else {
                    // send a refresh message to each hub they have registered here
                    $h = q("select * from hubloc where hubloc_hash = '%s' \n\t\t\t\t\t\tand not (hubloc_flags & %d) > 0  and not (hubloc_status & %d) > 0", dbesc($r[0]['hubloc_hash']), intval(HUBLOC_FLAGS_DELETED), intval(HUBLOC_OFFLINE));
                    if ($h) {
                        foreach ($h as $hh) {
                            $data = zot_build_packet($s[0], 'refresh', array(array('guid' => $hh['hubloc_guid'], 'guid_sig' => $hh['hubloc_guid_sig'], 'url' => $hh['hubloc_url'])));
                            if ($data) {
                                $result = zot_zot($hh['hubloc_callback'], $data);
                                // if immediate delivery failed, stick it in the queue to try again later.
                                if (!$result['success']) {
                                    $hash = random_string();
                                    q("insert into outq ( outq_hash, outq_account, outq_channel, outq_driver, outq_posturl, outq_async, outq_created, outq_updated, outq_notify, outq_msg ) \n\t\t\t\t\t\t\t\t\t\tvalues ( '%s', %d, %d, '%s', '%s', %d, '%s', '%s', '%s', '%s' )", dbesc($hash), intval($s[0]['channel_account_id']), intval($s[0]['channel_id']), dbesc('zot'), dbesc($hh['hubloc_callback']), intval(1), dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc($data), dbesc(''));
                                }
                            }
                        }
                    }
                }
            }
        }
        return;
    }
    $expire = false;
    $request = false;
    $mail = false;
    $fsuggest = false;
    $top_level = false;
    $location = false;
    $recipients = array();
    $url_recipients = array();
    $normal_mode = true;
    $packet_type = 'undefined';
    if ($cmd === 'mail') {
        $normal_mode = false;
        $mail = true;
        $private = true;
        $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1", intval($item_id));
        if (!$message) {
            return;
        }
        xchan_mail_query($message[0]);
        $uid = $message[0]['channel_id'];
        $recipients[] = $message[0]['from_xchan'];
        // include clones
        $recipients[] = $message[0]['to_xchan'];
        $item = $message[0];
        $encoded_item = encode_mail($item);
        $s = q("select * from channel where channel_id = %d limit 1", intval($item['channel_id']));
        if ($s) {
            $channel = $s[0];
        }
    } elseif ($cmd === 'request') {
        $channel_id = $item_id;
        $xchan = $argv[3];
        $request_message_id = $argv[4];
        $s = q("select * from channel where channel_id = %d limit 1", intval($channel_id));
        if ($s) {
            $channel = $s[0];
        }
        $private = true;
        $recipients[] = $xchan;
        $packet_type = 'request';
        $normal_mode = false;
    } elseif ($cmd === 'expire') {
        // FIXME
        // This will require a special zot packet containing a list of item message_id's to be expired.
        // This packet will be public, since we cannot selectively deliver here.
        // We need the handling on this end to create the array, and the handling on the remote end
        // to verify permissions (for each item) and process it. Until this is complete, the expire feature will be disabled.
        return;
        $normal_mode = false;
        $expire = true;
        $items = q("SELECT * FROM item WHERE uid = %d AND ( item_flags & %d )>0\n\t\t\tAND ( item_restrict & %d )>0 AND `changed` > %s - INTERVAL %s", intval($item_id), intval(ITEM_WALL), intval(ITEM_DELETED), db_utcnow(), db_quoteinterval('10 MINUTE'));
        $uid = $item_id;
        $item_id = 0;
        if (!$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 === 'refresh_all') {
        logger('notifier: refresh_all: ' . $item_id);
        $s = q("select * from channel where channel_id = %d limit 1", intval($item_id));
        if ($s) {
            $channel = $s[0];
        }
        $uid = $item_id;
        $recipients = array();
        $r = q("select abook_xchan from abook where abook_channel = %d", intval($item_id));
        if ($r) {
            foreach ($r as $rr) {
                $recipients[] = $rr['abook_xchan'];
            }
        }
        $private = false;
        $packet_type = 'refresh';
    } elseif ($cmd === 'location') {
        logger('notifier: location: ' . $item_id);
        $s = q("select * from channel where channel_id = %d limit 1", intval($item_id));
        if ($s) {
            $channel = $s[0];
        }
        $uid = $item_id;
        $recipients = array();
        $r = q("select abook_xchan from abook where abook_channel = %d", intval($item_id));
        if ($r) {
            foreach ($r as $rr) {
                $recipients[] = $rr['abook_xchan'];
            }
        }
        $encoded_item = array('locations' => zot_encode_locations($channel), 'type' => 'location', 'encoding' => 'zot');
        $target_item = array('aid' => $channel['channel_account_id'], 'uid' => $channel['channel_id']);
        $private = false;
        $packet_type = 'location';
        $location = true;
    } elseif ($cmd === 'purge_all') {
        logger('notifier: purge_all: ' . $item_id);
        $s = q("select * from channel where channel_id = %d limit 1", intval($item_id));
        if ($s) {
            $channel = $s[0];
        }
        $uid = $item_id;
        $recipients = array();
        $r = q("select abook_xchan from abook where abook_channel = %d", intval($item_id));
        if ($r) {
            foreach ($r as $rr) {
                $recipients[] = $rr['abook_xchan'];
            }
        }
        $private = false;
        $packet_type = 'purge';
    } else {
        // Normal items
        // Fetch the target item
        $r = q("SELECT * FROM item WHERE id = %d and parent != 0 LIMIT 1", intval($item_id));
        if (!$r) {
            return;
        }
        xchan_query($r);
        $r = fetch_post_tags($r);
        $target_item = $r[0];
        $deleted_item = false;
        if ($target_item['item_restrict'] & ITEM_DELETED) {
            logger('notifier: target item ITEM_DELETED', LOGGER_DEBUG);
            $deleted_item = true;
        }
        $unforwardable = ITEM_UNPUBLISHED | ITEM_DELAYED_PUBLISH | ITEM_WEBPAGE | ITEM_BUILDBLOCK | ITEM_PDL;
        if ($target_item['item_restrict'] & $unforwardable) {
            logger('notifier: target item not forwardable: flags ' . $target_item['item_restrict'], LOGGER_DEBUG);
            return;
        }
        $s = q("select * from channel where channel_id = %d limit 1", intval($target_item['uid']));
        if ($s) {
            $channel = $s[0];
        }
        if ($channel['channel_hash'] !== $target_item['author_xchan'] && $channel['channel_hash'] !== $target_item['owner_xchan']) {
            logger("notifier: Sending channel {$channel['channel_hash']} is not owner {$target_item['owner_xchan']} or author {$target_item['author_xchan']}");
            return;
        }
        if ($target_item['id'] == $target_item['parent']) {
            $parent_item = $target_item;
            $top_level_post = true;
        } else {
            // fetch the parent item
            $r = q("SELECT * from item where id = %d order by id asc", intval($target_item['parent']));
            if (!$r) {
                return;
            }
            xchan_query($r);
            $r = fetch_post_tags($r);
            $parent_item = $r[0];
            $top_level_post = false;
        }
        // avoid looping of discover items 12/4/2014
        if ($sys && $parent_item['uid'] == $sys['channel_id']) {
            return;
        }
        $encoded_item = encode_item($target_item);
        // Send comments to the owner to re-deliver to everybody in the conversation
        // We only do this if the item in question originated on this site. This prevents looping.
        // To clarify, a site accepting a new comment is responsible for sending it to the owner for relay.
        // Relaying should never be initiated on a post that arrived from elsewhere.
        // We should normally be able to rely on ITEM_ORIGIN, but start_delivery_chain() incorrectly set this
        // flag on comments for an extended period. So we'll also call comment_local_origin() which looks at
        // the hostname in the message_id and provides a second (fallback) opinion.
        $relay_to_owner = !$top_level_post && $target_item['item_flags'] & ITEM_ORIGIN && comment_local_origin($target_item) ? true : false;
        $uplink = false;
        // $cmd === 'relay' indicates the owner is sending it to the original recipients
        // don't allow the item in the relay command to relay to owner under any circumstances, it will loop
        logger('notifier: relay_to_owner: ' . ($relay_to_owner ? 'true' : 'false'), LOGGER_DATA);
        logger('notifier: top_level_post: ' . ($top_level_post ? 'true' : 'false'), LOGGER_DATA);
        logger('notifier: target_item_flags: ' . $target_item['item_flags'] . ' ' . ($target_item['item_flags'] & ITEM_ORIGIN ? 'true' : 'false'), LOGGER_DATA);
        // tag_deliver'd post which needs to be sent back to the original author
        if ($cmd === 'uplink' && $parent_item['item_flags'] & ITEM_UPLINK && !$top_level_post) {
            logger('notifier: uplink');
            $uplink = true;
        }
        if (($relay_to_owner || $uplink) && $cmd !== 'relay') {
            logger('notifier: followup relay', LOGGER_DEBUG);
            $recipients = array($uplink ? $parent_item['source_xchan'] : $parent_item['owner_xchan']);
            $private = true;
            if (!$encoded_item['flags']) {
                $encoded_item['flags'] = array();
            }
            $encoded_item['flags'][] = 'relay';
        } else {
            logger('notifier: normal distribution', LOGGER_DEBUG);
            if ($cmd === 'relay') {
                logger('notifier: owner relay');
            }
            // if our parent is a tag_delivery recipient, uplink to the original author causing
            // a delivery fork.
            if ($parent_item['item_flags'] & ITEM_UPLINK && !$top_level_post && $cmd !== 'uplink') {
                logger('notifier: uplinking this item');
                proc_run('php', 'include/notifier.php', 'uplink', $item_id);
            }
            $private = false;
            $recipients = collect_recipients($parent_item, $private);
            // FIXME add any additional recipients such as mentions, etc.
            // don't send deletions onward for other people's stuff
            // TODO verify this is needed - copied logic from same place in old code
            if ($target_item['item_restrict'] & ITEM_DELETED && !($target_item['item_flags'] & ITEM_WALL)) {
                logger('notifier: ignoring delete notification for non-wall item');
                return;
            }
        }
    }
    $walltowall = $top_level_post && $channel['xchan_hash'] === $target_item['author_xchan'] ? true : false;
    // Generic delivery section, we have an encoded item and recipients
    // Now start the delivery process
    $x = $encoded_item;
    $x['title'] = 'private';
    $x['body'] = 'private';
    logger('notifier: encoded item: ' . print_r($x, true), LOGGER_DATA);
    stringify_array_elms($recipients);
    if (!$recipients) {
        return;
    }
    //	logger('notifier: recipients: ' . print_r($recipients,true));
    $env_recips = $private ? array() : null;
    $details = q("select xchan_hash, xchan_instance_url, xchan_network, xchan_addr, xchan_guid, xchan_guid_sig from xchan where xchan_hash in (" . implode(',', $recipients) . ")");
    $recip_list = array();
    if ($details) {
        foreach ($details as $d) {
            // If the recipient is federated from a traditional network they won't be able to
            // handle nomadic identity. If we're publishing from a site that they aren't
            // directly connected with, ignore them.
            // FIXME: make sure we run through a notifier loop on the hub they're connected
            // with if this post comes in from a different hub - so that we will deliver to them.
            // On the down side, these channels will stop working if the hub they connected with
            // goes down permanently, as they are (doh) not nomadic.
            if ($d['xchan_instance_url'] && $d['xchan_instance_url'] != z_root()) {
                continue;
            }
            $recip_list[] = $d['xchan_addr'] . ' (' . $d['xchan_hash'] . ')';
            if ($private) {
                $env_recips[] = array('guid' => $d['xchan_guid'], 'guid_sig' => $d['xchan_guid_sig'], 'hash' => $d['xchan_hash']);
            }
        }
    }
    if ($private && !$env_recips) {
        // shouldn't happen
        logger('notifier: private message with no envelope recipients.' . print_r($argv, true));
    }
    logger('notifier: recipients (may be delivered to more if public): ' . print_r($recip_list, true), LOGGER_DEBUG);
    // Now we have collected recipients (except for external mentions, FIXME)
    // Let's reduce this to a set of hubs.
    logger('notifier: hub choice: ' . intval($relay_to_owner) . ' ' . intval($private) . ' ' . $cmd, LOGGER_DEBUG);
    // FIXME: I think we need to remove the private bit or this clause will never execute. Needs more coffee to think it through.
    // We may in fact have to send it to clones in case the one we pick recently died.
    if ($relay_to_owner && !$private && $cmd !== 'relay') {
        // If sending a followup to the post owner, only send it to one channel clone - to avoid race conditions.
        // In this case we'll pick the most recently contacted hub, as their primary might be down and the most
        // recently contacted has the best chance of being alive.
        // For private posts or uplinks we have to do things differently as only the sending clone will have the recipient list.
        // We have to send to all clone channels of the owner to find out who has the definitive list. Posts with
        // item_private set (but no ACL list) will return empty recipients (except for the sender and owner) in
        // collect_recipients() above. The end result is we should get only one delivery per delivery chain if we
        // aren't the owner or author.
        $r = q("select hubloc_guid, hubloc_url, hubloc_sitekey, hubloc_network, hubloc_flags, hubloc_callback, hubloc_host from hubloc \n\t\t\twhere hubloc_hash in (" . implode(',', $recipients) . ") order by hubloc_connected desc limit 1");
    } else {
        $r = q("select hubloc_guid, hubloc_url, hubloc_sitekey, hubloc_network, hubloc_flags, hubloc_callback, hubloc_host from hubloc \n\t\t\twhere hubloc_hash in (" . implode(',', $recipients) . ") and not (hubloc_flags & %d) > 0  and not (hubloc_status & %d) > 0", intval(HUBLOC_FLAGS_DELETED), intval(HUBLOC_OFFLINE));
    }
    if (!$r) {
        logger('notifier: no hubs');
        return;
    }
    $hubs = $r;
    /**
     * Reduce the hubs to those that are unique. For zot hubs, we need to verify uniqueness by the sitekey, since it may have been 
     * a re-install which has not yet been detected and pruned.
     * For other networks which don't have or require sitekeys, we'll have to use the URL
     */
    $hublist = array();
    // this provides an easily printable list for the logs
    $dhubs = array();
    // delivery hubs where we store our resulting unique array
    $keys = array();
    // array of keys to check uniquness for zot hubs
    $urls = array();
    // array of urls to check uniqueness of hubs from other networks
    foreach ($hubs as $hub) {
        if ($hub['hubloc_network'] == 'zot') {
            if (!in_array($hub['hubloc_sitekey'], $keys)) {
                $hublist[] = $hub['hubloc_host'];
                $dhubs[] = $hub;
                $keys[] = $hub['hubloc_sitekey'];
            }
        } else {
            if (!in_array($hub['hubloc_url'], $urls)) {
                $hublist[] = $hub['hubloc_host'];
                $dhubs[] = $hub;
                $urls[] = $hub['hubloc_url'];
            }
        }
    }
    logger('notifier: will notify/deliver to these hubs: ' . print_r($hublist, true), LOGGER_DEBUG);
    $interval = get_config('system', 'delivery_interval') !== false ? intval(get_config('system', 'delivery_interval')) : 2;
    $deliveries_per_process = intval(get_config('system', 'delivery_batch_count'));
    if ($deliveries_per_process <= 0) {
        $deliveries_per_process = 1;
    }
    $deliver = array();
    foreach ($dhubs as $hub) {
        if (defined('DIASPORA_RELIABILITY_EMULATION')) {
            $cointoss = mt_rand(0, 2);
            if ($cointoss == 2) {
                continue;
            }
        }
        if ($hub['hubloc_network'] === 'diaspora' || $hub['hubloc_network'] === 'friendica-over-diaspora') {
            if (!get_config('system', 'diaspora_enabled')) {
                continue;
            }
            require_once 'include/diaspora.php';
            diaspora_process_outbound(array('channel' => $channel, 'env_recips' => $env_recips, 'recipients' => $recipients, 'item' => $item, 'target_item' => $target_item, 'hub' => $hub, 'top_level_post' => $top_level_post, 'private' => $private, 'followup' => $followup, 'relay_to_owner' => $relay_to_owner, 'uplink' => $uplink, 'cmd' => $cmd, 'expire' => $expire, 'mail' => $mail, 'location' => $location, 'fsuggest' => $fsuggest, 'request' => $request, 'normal_mode' => $normal_mode, 'packet_type' => $packet_type, 'walltowall' => $walltowall));
            continue;
        }
        // default: zot protocol
        $hash = random_string();
        if ($packet_type === 'refresh' || $packet_type === 'purge') {
            $n = zot_build_packet($channel, $packet_type);
            q("insert into outq ( outq_hash, outq_account, outq_channel, outq_driver, outq_posturl, outq_async, outq_created, outq_updated, outq_notify, outq_msg ) values ( '%s', %d, %d, '%s', '%s', %d, '%s', '%s', '%s', '%s' )", dbesc($hash), intval($channel['channel_account_id']), intval($channel['channel_id']), dbesc('zot'), dbesc($hub['hubloc_callback']), intval(1), dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc($n), dbesc(''));
        } elseif ($packet_type === 'request') {
            $n = zot_build_packet($channel, 'request', $env_recips, $hub['hubloc_sitekey'], $hash, array('message_id' => $request_message_id));
            q("insert into outq ( outq_hash, outq_account, outq_channel, outq_driver, outq_posturl, outq_async, outq_created, outq_updated, outq_notify, outq_msg ) values ( '%s', %d, %d, '%s', '%s', %d, '%s', '%s', '%s', '%s' )", dbesc($hash), intval($channel['channel_account_id']), intval($channel['channel_id']), dbesc('zot'), dbesc($hub['hubloc_callback']), intval(1), dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc($n), dbesc(''));
        } else {
            $n = zot_build_packet($channel, 'notify', $env_recips, $private ? $hub['hubloc_sitekey'] : null, $hash);
            q("insert into outq ( outq_hash, outq_account, outq_channel, outq_driver, outq_posturl, outq_async, outq_created, outq_updated, outq_notify, outq_msg ) values ( '%s', %d, %d, '%s', '%s', %d, '%s', '%s', '%s', '%s' )", dbesc($hash), intval($target_item['aid']), intval($target_item['uid']), dbesc('zot'), dbesc($hub['hubloc_callback']), intval(1), dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc($n), dbesc(json_encode($encoded_item)));
        }
        $deliver[] = $hash;
        if (count($deliver) >= $deliveries_per_process) {
            proc_run('php', 'include/deliver.php', $deliver);
            $deliver = array();
            if ($interval) {
                @time_sleep_until(microtime(true) + (double) $interval);
            }
        }
    }
    // catch any stragglers
    if (count($deliver)) {
        proc_run('php', 'include/deliver.php', $deliver);
    }
    logger('notifier: basic loop complete.', LOGGER_DEBUG);
    if ($normal_mode) {
        call_hooks('notifier_normal', $target_item);
    }
    call_hooks('notifier_end', $target_item);
    logger('notifer: complete.');
    return;
}
Exemple #12
0
function red_item($a, $type)
{
    if (api_user() === false) {
        logger('api_red_item_full: no user');
        return false;
    }
    if ($_REQUEST['mid']) {
        $arr = array('mid' => $_REQUEST['mid']);
    } elseif ($_REQUEST['item_id']) {
        $arr = array('item_id' => $_REQUEST['item_id']);
    } else {
        json_return_and_die(array());
    }
    $arr['start'] = 0;
    $arr['records'] = 999999;
    $arr['item_type'] = '*';
    $i = items_fetch($arr, App::get_channel(), get_observer_hash());
    if (!$i) {
        json_return_and_die(array());
    }
    $ret = array();
    $tmp = array();
    foreach ($i as $ii) {
        $tmp[] = encode_item($ii, true);
    }
    $ret['item'] = $tmp;
    json_return_and_die($ret);
}
Exemple #13
0
function api_photo_detail(&$a, $type)
{
    if (api_user() === false) {
        return false;
    }
    if (!$_REQUEST['photo_id']) {
        return false;
    }
    $scale = array_key_exists('scale', $_REQUEST) ? intval($_REQUEST['scale']) : 0;
    $r = q("select * from photo where uid = %d and resource_id = '%s' and scale = %d limit 1", intval(local_channel()), dbesc($_REQUEST['photo_id']), intval($scale));
    if ($r) {
        $data = dbunescbin($r[0]['data']);
        if (array_key_exists('os_storage', $r[0]) && intval($r[0]['os_storage'])) {
            $data = file_get_contents($data);
        }
        $r[0]['data'] = base64_encode($data);
        $ret = array('photo' => $r[0]);
        $i = q("select id from item where uid = %d and resource_type = 'photo' and resource_id = '%s' limit 1", intval(local_channel()), dbesc($_REQUEST['photo_id']));
        if ($i) {
            $ii = q("select * from item where parent = %d order by id", intval($i[0]['id']));
            if ($ii) {
                xchan_query($ii, true, 0);
                $ii = fetch_post_tags($ii, true);
                if ($ii) {
                    $ret['item'] = array();
                    foreach ($ii as $iii) {
                        $ret['item'][] = encode_item($iii, true);
                    }
                }
            }
        }
        json_return_and_die($ret);
    }
    killme();
}
Exemple #14
0
/**
 * @brief Create an array representing the important channel information
 * which would be necessary to create a nomadic identity clone. This includes
 * most channel resources and connection information with the exception of content.
 *
 * @param int $channel_id
 *     Channel_id to export
 * @param boolean $items
 *     Include channel posts (wall items), default false
 *
 * @returns array
 *     See function for details
 */
function identity_basic_export($channel_id, $items = false)
{
    /*
     * Red basic channel export
     */
    $ret = array();
    $ret['compatibility'] = array('project' => RED_PLATFORM, 'version' => RED_VERSION, 'database' => DB_UPDATE_VERSION);
    $r = q("select * from channel where channel_id = %d limit 1", intval($channel_id));
    if ($r) {
        $ret['channel'] = $r[0];
    }
    $r = q("select * from profile where uid = %d", intval($channel_id));
    if ($r) {
        $ret['profile'] = $r;
    }
    $xchans = array();
    $r = q("select * from abook where abook_channel = %d ", intval($channel_id));
    if ($r) {
        $ret['abook'] = $r;
        foreach ($r as $rr) {
            $xchans[] = $rr['abook_xchan'];
        }
        stringify_array_elms($xchans);
    }
    if ($xchans) {
        $r = q("select * from xchan where xchan_hash in ( " . implode(',', $xchans) . " ) ");
        if ($r) {
            $ret['xchan'] = $r;
        }
        $r = q("select * from hubloc where hubloc_hash in ( " . implode(',', $xchans) . " ) ");
        if ($r) {
            $ret['hubloc'] = $r;
        }
    }
    $r = q("select * from `groups` where uid = %d ", intval($channel_id));
    if ($r) {
        $ret['group'] = $r;
    }
    $r = q("select * from group_member where uid = %d ", intval($channel_id));
    if ($r) {
        $ret['group_member'] = $r;
    }
    $r = q("select * from pconfig where uid = %d", intval($channel_id));
    if ($r) {
        $ret['config'] = $r;
    }
    $r = q("select type, data from photo where scale = 4 and profile = 1 and uid = %d limit 1", intval($channel_id));
    if ($r) {
        $ret['photo'] = array('type' => $r[0]['type'], 'data' => base64url_encode($r[0]['data']));
    }
    // All other term types will be included in items, if requested.
    $r = q("select * from term where type in (%d,%d) and uid = %d", intval(TERM_SAVEDSEARCH), intval(TERM_THING), intval($channel_id));
    if ($r) {
        $ret['term'] = $r;
    }
    $r = q("select * from obj where obj_channel = %d", intval($channel_id));
    if ($r) {
        $ret['obj'] = $r;
    }
    if (!$items) {
        return $ret;
    }
    $r = q("select likes.*, item.mid from likes left join item on likes.iid = item.id where likes.channel_id = %d", intval($channel_id));
    if ($r) {
        $ret['likes'] = $r;
    }
    $r = q("select item_id.*, item.mid from item_id left join item on item_id.iid = item.id where item_id.uid = %d", intval($channel_id));
    if ($r) {
        $ret['item_id'] = $r;
    }
    //$key = get_config('system','prvkey');
    /** @warning this may run into memory limits on smaller systems */
    $r = q("select * from item where (item_flags & %d)>0 and not (item_restrict & %d)>0 and uid = %d", intval(ITEM_WALL), intval(ITEM_DELETED), intval($channel_id));
    if ($r) {
        $ret['item'] = array();
        xchan_query($r);
        $r = fetch_post_tags($r, true);
        foreach ($r as $rr) {
            $ret['item'][] = encode_item($rr, true);
        }
    }
    return $ret;
}
Exemple #15
0
function search_content(&$a, $update = 0, $load = false)
{
    if (get_config('system', 'block_public') || get_config('system', 'block_public_search')) {
        if (!local_channel() && !remote_channel()) {
            notice(t('Public access denied.') . EOL);
            return;
        }
    }
    if ($load) {
        $_SESSION['loadtime'] = datetime_convert();
    }
    nav_set_selected('search');
    require_once "include/bbcode.php";
    require_once 'include/security.php';
    require_once 'include/conversation.php';
    require_once 'include/items.php';
    $format = $_REQUEST['format'] ? $_REQUEST['format'] : '';
    if ($format !== '') {
        $update = $load = 1;
    }
    $observer = $a->get_observer();
    $observer_hash = $observer ? $observer['xchan_hash'] : '';
    $o = '<div id="live-search"></div>' . "\r\n";
    $o .= '<h3>' . t('Search') . '</h3>';
    if (x($a->data, 'search')) {
        $search = trim($a->data['search']);
    } else {
        $search = x($_GET, 'search') ? trim(rawurldecode($_GET['search'])) : '';
    }
    $tag = false;
    if (x($_GET, 'tag')) {
        $tag = true;
        $search = x($_GET, 'tag') ? trim(rawurldecode($_GET['tag'])) : '';
    }
    if (!local_channel() || !feature_enabled(local_channel(), 'savedsearch')) {
        $o .= search($search, 'search-box', '/search', local_channel() ? true : false);
    }
    if (strpos($search, '#') === 0) {
        $tag = true;
        $search = substr($search, 1);
    }
    if (strpos($search, '@') === 0) {
        $search = substr($search, 1);
        goaway(z_root() . '/directory' . '?f=1&search=' . $search);
    }
    // look for a naked webbie
    if (strpos($search, '@') !== false) {
        goaway(z_root() . '/directory' . '?f=1&search=' . $search);
    }
    if (!$search) {
        return $o;
    }
    if ($tag) {
        $sql_extra = sprintf(" AND `item`.`id` IN (select `oid` from term where otype = %d and type = %d and term = '%s') ", intval(TERM_OBJ_POST), intval(TERM_HASHTAG), dbesc(protect_sprintf($search)));
    } else {
        $regstr = db_getfunc('REGEXP');
        $sql_extra = sprintf(" AND `item`.`body` {$regstr} '%s' ", dbesc(protect_sprintf(preg_quote($search))));
    }
    // Here is the way permissions work in the search module...
    // Only public posts can be shown
    // OR your own posts if you are a logged in member
    // No items will be shown if the member has a blocked profile wall.
    if (!$update && !$load) {
        // This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
        // because browser prefetching might change it on us. We have to deliver it with the page.
        $o .= '<div id="live-search"></div>' . "\r\n";
        $o .= "<script> var profile_uid = " . (intval(local_channel()) ? local_channel() : -1) . "; var netargs = '?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
        $a->page['htmlhead'] .= replace_macros(get_markup_template("build_query.tpl"), array('$baseurl' => z_root(), '$pgtype' => 'search', '$uid' => $a->profile['profile_uid'] ? $a->profile['profile_uid'] : '0', '$gid' => '0', '$cid' => '0', '$cmin' => '0', '$cmax' => '0', '$star' => '0', '$liked' => '0', '$conv' => '0', '$spam' => '0', '$fh' => '0', '$nouveau' => '0', '$wall' => '0', '$list' => x($_REQUEST, 'list') ? intval($_REQUEST['list']) : 0, '$page' => $a->pager['page'] != 1 ? $a->pager['page'] : 1, '$search' => ($tag ? urlencode('#') : '') . $search, '$order' => '', '$file' => '', '$cats' => '', '$tags' => '', '$mid' => '', '$verb' => '', '$dend' => '', '$dbegin' => ''));
    }
    $pub_sql = public_permissions_sql($observer_hash);
    require_once 'include/identity.php';
    $sys = get_sys_channel();
    if ($update && $load) {
        $itemspage = get_pconfig(local_channel(), 'system', 'itemspage');
        $a->set_pager_itemspage(intval($itemspage) ? $itemspage : 20);
        $pager_sql = sprintf(" LIMIT %d OFFSET %d ", intval($a->pager['itemspage']), intval($a->pager['start']));
        // in case somebody turned off public access to sys channel content with permissions
        if (!perm_is_allowed($sys['channel_id'], $observer_hash, 'view_stream')) {
            $sys['xchan_hash'] .= 'disabled';
        }
        if ($load) {
            $r = null;
            if (ACTIVE_DBTYPE == DBTYPE_POSTGRES) {
                $prefix = 'distinct on (created, mid)';
                $suffix = 'ORDER BY created DESC, mid';
            } else {
                $prefix = 'distinct';
                $suffix = 'group by mid ORDER BY created DESC';
            }
            if (local_channel()) {
                $r = q("SELECT {$prefix} mid, item.id as item_id, item.* from item\n\t\t\t\t\tWHERE item_restrict = 0\n\t\t\t\t\tAND ((( `item`.`allow_cid` = ''  AND `item`.`allow_gid` = '' AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = '' AND item_private = 0 ) \n\t\t\t\t\tOR ( `item`.`uid` = %d )) OR item.owner_xchan = '%s' )\n\t\t\t\t\t{$sql_extra}\n\t\t\t\t\t{$suffix} {$pager_sql} ", intval(local_channel()), dbesc($sys['xchan_hash']));
            }
            if ($r === null) {
                $r = q("SELECT {$prefix} mid, item.id as item_id, item.* from item\n\t\t\t\t\tWHERE item_restrict = 0\n\t\t\t\t\tAND (((( `item`.`allow_cid` = ''  AND `item`.`allow_gid` = '' AND `item`.`deny_cid`  = ''\n\t\t\t\t\tAND `item`.`deny_gid`  = '' AND item_private = 0 )\n\t\t\t\t\tand owner_xchan in ( " . stream_perms_xchans($observer ? PERMS_NETWORK | PERMS_PUBLIC : PERMS_PUBLIC) . " ))\n\t\t\t\t\t\t{$pub_sql} ) OR owner_xchan = '%s')\n\t\t\t\t\t{$sql_extra} \n\t\t\t\t\t{$suffix} {$pager_sql}", dbesc($sys['xchan_hash']));
            }
        } else {
            $r = array();
        }
    }
    if ($r) {
        xchan_query($r);
        $items = fetch_post_tags($r, true);
    } else {
        $items = array();
    }
    if ($format == 'json') {
        $result = array();
        require_once 'include/conversation.php';
        foreach ($items as $item) {
            $item['html'] = bbcode($item['body']);
            $x = encode_item($item);
            $x['html'] = prepare_text($item['body'], $item['mimetype']);
            $result[] = $x;
        }
        json_return_and_die(array('success' => true, 'messages' => $result));
    }
    if ($tag) {
        $o .= '<h2>Items tagged with: ' . htmlspecialchars($search, ENT_COMPAT, 'UTF-8') . '</h2>';
    } else {
        $o .= '<h2>Search results for: ' . htmlspecialchars($search, ENT_COMPAT, 'UTF-8') . '</h2>';
    }
    $o .= conversation($a, $items, 'search', $update, 'client');
    return $o;
}
Exemple #16
0
 public static function run($argc, $argv)
 {
     $maxsysload = intval(get_config('system', 'maxloadavg'));
     if ($maxsysload < 1) {
         $maxsysload = 50;
     }
     if (function_exists('sys_getloadavg')) {
         $load = sys_getloadavg();
         if (intval($load[0]) > $maxsysload) {
             logger('system: load ' . $load . ' too high. Cron deferred to next scheduled run.');
             return;
         }
     }
     // Check for a lockfile.  If it exists, but is over an hour old, it's stale.  Ignore it.
     $lockfile = 'store/[data]/cron';
     if (file_exists($lockfile) && filemtime($lockfile) > time() - 3600 && !get_config('system', 'override_cron_lockfile')) {
         logger("cron: Already running");
         return;
     }
     // Create a lockfile.  Needs two vars, but $x doesn't need to contain anything.
     file_put_contents($lockfile, $x);
     logger('cron: start');
     // run queue delivery process in the background
     Master::Summon(array('Queue'));
     Master::Summon(array('Poller'));
     // maintenance for mod sharedwithme - check for updated items and remove them
     require_once 'include/sharedwithme.php';
     apply_updates();
     // expire any expired mail
     q("delete from mail where expires > '%s' and expires < %s ", dbesc(NULL_DATE), db_utcnow());
     // expire any expired items
     $r = q("select id from item where expires > '2001-01-01 00:00:00' and expires < %s \n\t\t\tand item_deleted = 0 ", db_utcnow());
     if ($r) {
         require_once 'include/items.php';
         foreach ($r as $rr) {
             drop_item($rr['id'], false);
         }
     }
     // delete expired access tokens
     $r = q("select atoken_id from atoken where atoken_expires > '%s' and atoken_expires < %s", dbesc(NULL_DATE), db_utcnow());
     if ($r) {
         require_once 'include/security.php';
         foreach ($r as $rr) {
             atoken_delete($rr['atoken_id']);
         }
     }
     // Ensure that every channel pings a directory server once a month. This way we can discover
     // channels and sites that quietly vanished and prevent the directory from accumulating stale
     // or dead entries.
     $r = q("select channel_id from channel where channel_dirdate < %s - INTERVAL %s", db_utcnow(), db_quoteinterval('30 DAY'));
     if ($r) {
         foreach ($r as $rr) {
             Master::Summon(array('Directory', $rr['channel_id'], 'force'));
             if ($interval) {
                 @time_sleep_until(microtime(true) + (double) $interval);
             }
         }
     }
     // publish any applicable items that were set to be published in the future
     // (time travel posts). Restrict to items that have come of age in the last
     // couple of days to limit the query to something reasonable.
     $r = q("select id from item where item_delayed = 1 and created <= %s  and created > '%s' ", db_utcnow(), dbesc(datetime_convert('UTC', 'UTC', 'now - 2 days')));
     if ($r) {
         foreach ($r as $rr) {
             $x = q("update item set item_delayed = 0 where id = %d", intval($rr['id']));
             if ($x) {
                 $z = q("select * from item where id = %d", intval($message_id));
                 if ($z) {
                     xchan_query($z);
                     $sync_item = fetch_post_tags($z);
                     build_sync_packet($sync_item[0]['uid'], ['item' => [encode_item($sync_item[0], true)]]);
                 }
                 Master::Summon(array('Notifier', 'wall-new', $rr['id']));
             }
         }
     }
     $abandon_days = intval(get_config('system', 'account_abandon_days'));
     if ($abandon_days < 1) {
         $abandon_days = 0;
     }
     // once daily run birthday_updates and then expire in background
     // FIXME: add birthday updates, both locally and for xprof for use
     // by directory servers
     $d1 = intval(get_config('system', 'last_expire_day'));
     $d2 = intval(datetime_convert('UTC', 'UTC', 'now', 'd'));
     // Allow somebody to staggger daily activities if they have more than one site on their server,
     // or if it happens at an inconvenient (busy) hour.
     $h1 = intval(get_config('system', 'cron_hour'));
     $h2 = intval(datetime_convert('UTC', 'UTC', 'now', 'G'));
     if ($d2 != $d1 && $h1 == $h2) {
         Master::Summon(array('Cron_daily'));
     }
     // update any photos which didn't get imported properly
     // This should be rare
     $r = q("select xchan_photo_l, xchan_hash from xchan where xchan_photo_l != '' and xchan_photo_m = '' \n\t\t\tand xchan_photo_date < %s - INTERVAL %s", db_utcnow(), db_quoteinterval('1 DAY'));
     if ($r) {
         require_once 'include/photo/photo_driver.php';
         foreach ($r as $rr) {
             $photos = import_xchan_photo($rr['xchan_photo_l'], $rr['xchan_hash']);
             $x = q("update xchan set xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s'\n\t\t\t\t\twhere xchan_hash = '%s'", dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), dbesc($photos[3]), dbesc($rr['xchan_hash']));
         }
     }
     // pull in some public posts
     if (!get_config('system', 'disable_discover_tab')) {
         Master::Summon(array('Externals'));
     }
     $generation = 0;
     $restart = false;
     if ($argc > 1 && $argv[1] == 'restart') {
         $restart = true;
         $generation = intval($argv[2]);
         if (!$generation) {
             killme();
         }
     }
     reload_plugins();
     $d = datetime_convert();
     // TODO check to see if there are any cronhooks before wasting a process
     if (!$restart) {
         Master::Summon(array('Cronhooks'));
     }
     set_config('system', 'lastcron', datetime_convert());
     //All done - clear the lockfile
     @unlink($lockfile);
     return;
 }
Exemple #17
0
function events_post(&$a)
{
    logger('post: ' . print_r($_REQUEST, true), LOGGER_DATA);
    if (!local_channel()) {
        return;
    }
    if ($_FILES && array_key_exists('userfile', $_FILES) && intval($_FILES['userfile']['size'])) {
        $src = $_FILES['userfile']['tmp_name'];
        if ($src) {
            $result = parse_ical_file($src, local_channel());
            if ($result) {
                info(t('Calendar entries imported.') . EOL);
            } else {
                notice(t('No calendar entries found.') . EOL);
            }
            @unlink($src);
        }
        goaway(z_root() . '/events');
    }
    $event_id = x($_POST, 'event_id') ? intval($_POST['event_id']) : 0;
    $event_hash = x($_POST, 'event_hash') ? $_POST['event_hash'] : '';
    $xchan = x($_POST, 'xchan') ? dbesc($_POST['xchan']) : '';
    $uid = local_channel();
    $start_text = escape_tags($_REQUEST['start_text']);
    $finish_text = escape_tags($_REQUEST['finish_text']);
    $adjust = intval($_POST['adjust']);
    $nofinish = intval($_POST['nofinish']);
    $categories = escape_tags(trim($_POST['category']));
    // only allow editing your own events.
    if ($xchan && $xchan !== get_observer_hash()) {
        return;
    }
    if ($start_text) {
        $start = $start_text;
    } else {
        $start = sprintf('%d-%d-%d %d:%d:0', $startyear, $startmonth, $startday, $starthour, $startminute);
    }
    if ($nofinish) {
        $finish = NULL_DATE;
    }
    if ($finish_text) {
        $finish = $finish_text;
    } else {
        $finish = sprintf('%d-%d-%d %d:%d:0', $finishyear, $finishmonth, $finishday, $finishhour, $finishminute);
    }
    if ($adjust) {
        $start = datetime_convert(date_default_timezone_get(), 'UTC', $start);
        if (!$nofinish) {
            $finish = datetime_convert(date_default_timezone_get(), 'UTC', $finish);
        }
    } else {
        $start = datetime_convert('UTC', 'UTC', $start);
        if (!$nofinish) {
            $finish = datetime_convert('UTC', 'UTC', $finish);
        }
    }
    // Don't allow the event to finish before it begins.
    // It won't hurt anything, but somebody will file a bug report
    // and we'll waste a bunch of time responding to it. Time that
    // could've been spent doing something else.
    $summary = escape_tags(trim($_POST['summary']));
    $desc = escape_tags(trim($_POST['desc']));
    $location = escape_tags(trim($_POST['location']));
    $type = escape_tags(trim($_POST['type']));
    require_once 'include/text.php';
    linkify_tags($a, $desc, local_channel());
    linkify_tags($a, $location, local_channel());
    //$action = ($event_hash == '') ? 'new' : "event/" . $event_hash;
    //fixme: this url gives a wsod if there is a linebreak detected in one of the variables ($desc or $location)
    //$onerror_url = $a->get_baseurl() . "/events/" . $action . "?summary=$summary&description=$desc&location=$location&start=$start_text&finish=$finish_text&adjust=$adjust&nofinish=$nofinish&type=$type";
    $onerror_url = $a->get_baseurl() . "/events";
    if (strcmp($finish, $start) < 0 && !$nofinish) {
        notice(t('Event can not end before it has started.') . EOL);
        if (intval($_REQUEST['preview'])) {
            echo t('Unable to generate preview.');
            killme();
        }
        goaway($onerror_url);
    }
    if (!$summary || !$start) {
        notice(t('Event title and start time are required.') . EOL);
        if (intval($_REQUEST['preview'])) {
            echo t('Unable to generate preview.');
            killme();
        }
        goaway($onerror_url);
    }
    $share = intval($_POST['share']) ? intval($_POST['share']) : 0;
    $channel = $a->get_channel();
    $acl = new AccessList(false);
    if ($event_id) {
        $x = q("select * from event where id = %d and uid = %d limit 1", intval($event_id), intval(local_channel()));
        if (!$x) {
            notice(t('Event not found.') . EOL);
            if (intval($_REQUEST['preview'])) {
                echo t('Unable to generate preview.');
                killme();
            }
            return;
        }
        $acl->set($x[0]);
        $created = $x[0]['created'];
        $edited = datetime_convert();
        if ($x[0]['allow_cid'] === '<' . $channel['channel_hash'] . '>' && $x[0]['allow_gid'] === '' && $x[0]['deny_cid'] === '' && $x[0]['deny_gid'] === '') {
            $share = false;
        } else {
            $share = true;
        }
    } else {
        $created = $edited = datetime_convert();
        if ($share) {
            $acl->set_from_array($_POST);
        } else {
            $acl->set(array('allow_cid' => '<' . $channel['channel_hash'] . '>', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''));
        }
    }
    $post_tags = array();
    $channel = $a->get_channel();
    $ac = $acl->get();
    if (strlen($categories)) {
        $cats = explode(',', $categories);
        foreach ($cats as $cat) {
            $post_tags[] = array('uid' => $profile_uid, 'type' => TERM_CATEGORY, 'otype' => TERM_OBJ_POST, 'term' => trim($cat), 'url' => $channel['xchan_url'] . '?f=&cat=' . urlencode(trim($cat)));
        }
    }
    $datarray = array();
    $datarray['start'] = $start;
    $datarray['finish'] = $finish;
    $datarray['summary'] = $summary;
    $datarray['description'] = $desc;
    $datarray['location'] = $location;
    $datarray['type'] = $type;
    $datarray['adjust'] = $adjust;
    $datarray['nofinish'] = $nofinish;
    $datarray['uid'] = local_channel();
    $datarray['account'] = get_account_id();
    $datarray['event_xchan'] = $channel['channel_hash'];
    $datarray['allow_cid'] = $ac['allow_cid'];
    $datarray['allow_gid'] = $ac['allow_gid'];
    $datarray['deny_cid'] = $ac['deny_cid'];
    $datarray['deny_gid'] = $ac['deny_gid'];
    $datarray['private'] = $acl->is_private() ? 1 : 0;
    $datarray['id'] = $event_id;
    $datarray['created'] = $created;
    $datarray['edited'] = $edited;
    if (intval($_REQUEST['preview'])) {
        $html = format_event_html($datarray);
        echo $html;
        killme();
    }
    $event = event_store_event($datarray);
    if ($post_tags) {
        $datarray['term'] = $post_tags;
    }
    $item_id = event_store_item($datarray, $event);
    if ($item_id) {
        $r = q("select * from item where id = %d", intval($item_id));
        if ($r) {
            xchan_query($r);
            $sync_item = fetch_post_tags($r);
            $z = q("select * from event where event_hash = '%s' and uid = %d limit 1", dbesc($r[0]['resource_id']), intval($channel['channel_id']));
            if ($z) {
                build_sync_packet($channel['channel_id'], array('event_item' => array(encode_item($sync_item[0], true)), 'event' => $z));
            }
        }
    }
    if ($share) {
        proc_run('php', "include/notifier.php", "event", "{$item_id}");
    }
}
Exemple #18
0
function zot_feed($uid, $observer_hash, $arr)
{
    $result = array();
    $mindate = null;
    $message_id = null;
    require_once 'include/security.php';
    if (array_key_exists('mindate', $arr)) {
        $mindate = datetime_convert('UTC', 'UTC', $arr['mindate']);
    }
    if (array_key_exists('message_id', $arr)) {
        $message_id = $arr['message_id'];
    }
    if (!$mindate) {
        $mindate = NULL_DATE;
    }
    $mindate = dbesc($mindate);
    logger('zot_feed: requested for uid ' . $uid . ' from observer ' . $observer_hash, LOGGER_DEBUG);
    if ($message_id) {
        logger('message_id: ' . $message_id, LOGGER_DEBUG);
    }
    if (!perm_is_allowed($uid, $observer_hash, 'view_stream')) {
        logger('zot_feed: permission denied.');
        return $result;
    }
    if (!is_sys_channel($uid)) {
        $sql_extra = item_permissions_sql($uid, $observer_hash);
    }
    $limit = " LIMIT 100 ";
    if ($mindate != NULL_DATE) {
        $sql_extra .= " and ( created > '{$mindate}' or changed > '{$mindate}' ) ";
    }
    if ($message_id) {
        $sql_extra .= " and mid = '" . dbesc($message_id) . "' ";
        $limit = '';
    }
    $items = array();
    /** @FIXME fix this part for PostgreSQL */
    if (ACTIVE_DBTYPE == DBTYPE_POSTGRES) {
        return array();
    }
    if (is_sys_channel($uid)) {
        $r = q("SELECT parent, created, postopts from item\n\t\t\tWHERE uid != %d\n\t\t\tAND item_private = 0 AND item_restrict = 0 AND uid in (" . stream_perms_api_uids(PERMS_PUBLIC, 10, 1) . ")\n\t\t\tAND (item_flags &  %d) > 0\n\t\t\t{$sql_extra} GROUP BY parent ORDER BY created ASC {$limit}", intval($uid), intval(ITEM_WALL));
    } else {
        $r = q("SELECT parent, created, postopts from item\n\t\t\tWHERE uid = %d AND item_restrict = 0\n\t\t\tAND (item_flags &  %d) > 0\n\t\t\t{$sql_extra} GROUP BY parent ORDER BY created ASC {$limit}", intval($uid), intval(ITEM_WALL));
    }
    if ($r) {
        for ($x = 0; $x < count($r); $x++) {
            if (strpos($r[$x]['postopts'], 'nodeliver') !== false) {
                unset($r[$x]);
            }
        }
        $parents_str = ids_to_querystr($r, 'parent');
        $sys_query = is_sys_channel($uid) ? $sql_extra : '';
        $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item`\n\t\t\tWHERE `item`.`item_restrict` = 0\n\t\t\tAND `item`.`parent` IN ( %s ) {$sys_query} ", dbesc($parents_str));
    }
    if ($items) {
        xchan_query($items);
        $items = fetch_post_tags($items);
        require_once 'include/conversation.php';
        $items = conv_sort($items, 'ascending');
    } else {
        $items = array();
    }
    logger('zot_feed: number items: ' . count($items), LOGGER_DEBUG);
    foreach ($items as $item) {
        $result[] = encode_item($item);
    }
    return $result;
}
Exemple #19
0
function channel_export_items($channel_id, $start, $finish)
{
    if (!$start) {
        return array();
    } else {
        $start = datetime_convert('UTC', 'UTC', $start);
    }
    $finish = datetime_convert('UTC', 'UTC', $finish ? $finish : 'now');
    if ($finish < $start) {
        return array();
    }
    $ret = array();
    $ch = channelx_by_n($channel_id);
    if ($ch) {
        $ret['relocate'] = ['channel_address' => $ch['channel_address'], 'url' => z_root()];
    }
    $r = q("select * from item where ( item_wall = 1 or item_type != %d ) and item_deleted = 0 and uid = %d and created >= '%s' and created < '%s'  and resource_type = '' order by created", intval(ITEM_TYPE_POST), intval($channel_id), dbesc($start), dbesc($finish));
    if ($r) {
        $ret['item'] = array();
        xchan_query($r);
        $r = fetch_post_tags($r, true);
        foreach ($r as $rr) {
            $ret['item'][] = encode_item($rr, true);
        }
    }
    return $ret;
}
Exemple #20
0
function red_item(&$a, $type)
{
    if (api_user() === false) {
        logger('api_red_item_full: no user');
        return false;
    }
    if ($_REQUEST['mid']) {
        $arr = array('mid' => $_REQUEST['mid']);
    } elseif ($_REQUEST['item_id']) {
        $arr = array('item_id' => $_REQUEST['item_id']);
    } else {
        json_return_and_die(array());
    }
    $arr['start'] = 0;
    $arr['records'] = 999999;
    $arr['item_type'] = '*';
    $i = items_fetch($arr, $a->get_channel(), get_observer_hash());
    if (!$i) {
        json_return_and_die(array());
    }
    $ret = array();
    $tmp = array();
    $str = '';
    foreach ($i as $ii) {
        $tmp[] = encode_item($ii, true);
        if ($str) {
            $str .= ',';
        }
        $str .= $ii['id'];
    }
    $ret['item'] = $tmp;
    if ($str) {
        $r = q("select item_id.*, item.mid from item_id left join item on item_id.iid = item.id where item.id in ( {$str} ) ");
        if ($r) {
            $ret['item_id'] = $r;
        }
    }
    json_return_and_die($ret);
}
Exemple #21
0
function identity_export_year($channel_id, $year)
{
    if (!$year) {
        return array();
    }
    $ret = array();
    $mindate = datetime_convert('UTC', 'UTC', $year . '-01-01 00:00:00');
    $maxdate = datetime_convert('UTC', 'UTC', $year + 1 . '-01-01 00:00:00');
    $r = q("select * from item where (item_flags & %d) > 0 and (item_restrict & %d) = 0 and uid = %d and created >= '%s' and created < '%s' order by created ", intval(ITEM_WALL), intval(ITEM_DELETED), intval($channel_id), dbesc($mindate), dbesc($maxdate));
    if ($r) {
        $ret['item'] = array();
        xchan_query($r);
        $r = fetch_post_tags($r, true);
        foreach ($r as $rr) {
            $ret['item'][] = encode_item($rr, true);
        }
    }
    return $ret;
}