public static function run($argc, $argv)
 {
     /**
      * Cron Weekly
      * 
      * Actions in the following block are executed once per day only on Sunday (once per week).
      *
      */
     call_hooks('cron_weekly', datetime_convert());
     z_check_cert();
     require_once 'include/hubloc.php';
     prune_hub_reinstalls();
     mark_orphan_hubsxchans();
     // get rid of really old poco records
     q("delete from xlink where xlink_updated < %s - INTERVAL %s and xlink_static = 0 ", db_utcnow(), db_quoteinterval('14 DAY'));
     $dirmode = intval(get_config('system', 'directory_mode'));
     if ($dirmode === DIRECTORY_MODE_SECONDARY || $dirmode === DIRECTORY_MODE_PRIMARY) {
         logger('regdir: ' . print_r(z_fetch_url(get_directory_primary() . '/regdir?f=&url=' . urlencode(z_root()) . '&realm=' . urlencode(get_directory_realm())), true));
     }
     // Check for dead sites
     Master::Summon(array('Checksites'));
     // update searchable doc indexes
     Master::Summon(array('Importdoc'));
     /**
      * End Cron Weekly
      */
 }
Example #2
0
function pubsites_content(&$a)
{
    require_once 'include/dir_fns.php';
    $dirmode = intval(get_config('system', 'directory_mode'));
    if ($dirmode == DIRECTORY_MODE_PRIMARY || $dirmode == DIRECTORY_MODE_STANDALONE) {
        $url = z_root() . '/dirsearch';
    }
    if (!$url) {
        $directory = find_upstream_directory($dirmode);
        $url = $directory['url'] . '/dirsearch';
    }
    $url .= '/sites';
    $o .= '<h1>' . t('Public Sites') . '</h1>';
    $o .= '<div class="descriptive-text">' . t('The listed sites allow public registration into the Red Matrix. All sites in the matrix are interlinked so membership on any of them conveys membership in the matrix as a whole. Some sites may require subscription or provide tiered service plans. The provider links <strong>may</strong> provide additional details.') . '</div>' . EOL;
    $ret = z_fetch_url($url);
    if ($ret['success']) {
        $j = json_decode($ret['body'], true);
        if ($j) {
            $rate_meta = local_channel() ? '<td>' . t('Rate this hub') . '</td>' : '';
            $o .= '<table border="1"><tr><td>' . t('Site URL') . '</td><td>' . t('Access Type') . '</td><td>' . t('Registration Policy') . '</td><td>' . t('Location') . '</td><td>' . t('View hub ratings') . '</td>' . $rate_meta . '</tr>';
            if ($j['sites']) {
                foreach ($j['sites'] as $jj) {
                    $host = strtolower(substr($jj['url'], strpos($jj['url'], '://') + 3));
                    $rate_links = local_channel() ? '<td><a href="rate?f=&target=' . $host . '" class="btn-btn-default"><i class="icon-check"></i> ' . t('Rate') . '</a></td>' : '';
                    $o .= '<tr><td>' . '<a href="' . ($jj['sellpage'] ? $jj['sellpage'] : $jj['url'] . '/register') . '" >' . $jj['url'] . '</a>' . '</td><td>' . $jj['access'] . '</td><td>' . $jj['register'] . '</td><td>' . $jj['location'] . '</td><td><a href="ratings/' . $host . '" class="btn-btn-default"><i class="icon-eye-open"></i> ' . t('View ratings') . '</a></td>' . $rate_links . '</tr>';
                }
            }
            $o .= '</table>';
        }
    }
    return $o;
}
Example #3
0
File: oembed.php Project: Mauru/red
function oembed_fetch_url($embedurl)
{
    $a = get_app();
    $txt = Cache::get($a->videowidth . $embedurl);
    if (strstr($txt, 'youtu')) {
        $txt = str_replace('http:', 'https:', $txt);
    }
    // These media files should now be caught in bbcode.php
    // left here as a fallback in case this is called from another source
    $noexts = array("mp3", "mp4", "ogg", "ogv", "oga", "ogm", "webm");
    $ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);
    if (is_null($txt)) {
        $txt = "";
        if (in_array($ext, $noexts)) {
            require_once 'include/hubloc.php';
            $zrl = is_matrix_url($embedurl);
            if ($zrl) {
                $embedurl = zid($embedurl);
            }
        } else {
            // try oembed autodiscovery
            $redirects = 0;
            $result = z_fetch_url($embedurl, false, $redirects, array('timeout' => 15, 'accept_content' => "text/*", 'novalidate' => true));
            if ($result['success']) {
                $html_text = $result['body'];
            }
            if ($html_text) {
                $dom = @DOMDocument::loadHTML($html_text);
                if ($dom) {
                    $xpath = new DOMXPath($dom);
                    $attr = "oembed";
                    $xattr = oe_build_xpath("class", "oembed");
                    $entries = $xpath->query("//link[@type='application/json+oembed']");
                    foreach ($entries as $e) {
                        $href = $e->getAttributeNode("href")->nodeValue;
                        $x = z_fetch_url($href . '&maxwidth=' . $a->videowidth);
                        $txt = $x['body'];
                        break;
                    }
                }
            }
        }
        if ($txt == false || $txt == "") {
            $x = array('url' => $embedurl, 'videowidth' => $a->videowidth);
            call_hooks('oembed_probe', $x);
            if (array_key_exists('embed', $x)) {
                $txt = $x['embed'];
            }
        }
        $txt = trim($txt);
        if ($txt[0] != "{") {
            $txt = '{"type":"error"}';
        }
        //save in cache
        Cache::set($a->videowidth . $embedurl, $txt);
    }
    $j = json_decode($txt);
    $j->embedurl = $embedurl;
    return $j;
}
Example #4
0
 function get()
 {
     require_once 'include/dir_fns.php';
     $dirmode = intval(get_config('system', 'directory_mode'));
     if ($dirmode == DIRECTORY_MODE_PRIMARY || $dirmode == DIRECTORY_MODE_STANDALONE) {
         $url = z_root() . '/dirsearch';
     }
     if (!$url) {
         $directory = find_upstream_directory($dirmode);
         $url = $directory['url'] . '/dirsearch';
     }
     $url .= '/sites';
     $rating_enabled = get_config('system', 'rating_enabled');
     $o .= '<div class="generic-content-wrapper">';
     $o .= '<div class="section-title-wrapper"><h2>' . t('Public Hubs') . '</h2></div>';
     $o .= '<div class="section-content-tools-wrapper"><div class="descriptive-text">' . t('The listed hubs allow public registration for the $Projectname network. All hubs in the network are interlinked so membership on any of them conveys membership in the network as a whole. Some hubs may require subscription or provide tiered service plans. The hub itself <strong>may</strong> provide additional details.') . '</div>' . EOL;
     $ret = z_fetch_url($url);
     if ($ret['success']) {
         $j = json_decode($ret['body'], true);
         if ($j) {
             $o .= '<table class="table table-striped table-hover"><tr><td>' . t('Hub URL') . '</td><td>' . t('Access Type') . '</td><td>' . t('Registration Policy') . '</td><td>' . t('Stats') . '</td><td>' . t('Software') . '</td>';
             if ($rating_enabled) {
                 $o .= '<td colspan="2">' . t('Ratings') . '</td>';
             }
             $o .= '</tr>';
             if ($j['sites']) {
                 foreach ($j['sites'] as $jj) {
                     if (!$jj['project']) {
                         continue;
                     }
                     if (strpos($jj['version'], ' ')) {
                         $x = explode(' ', $jj['version']);
                         if ($x[1]) {
                             $jj['version'] = $x[1];
                         }
                     }
                     $m = parse_url($jj['url']);
                     $host = strtolower(substr($jj['url'], strpos($jj['url'], '://') + 3));
                     $rate_links = local_channel() ? '<td><a href="rate?f=&target=' . $host . '" class="btn-btn-default"><i class="fa fa-check-square-o"></i> ' . t('Rate') . '</a></td>' : '';
                     $location = '';
                     if (!empty($jj['location'])) {
                         $location = '<p title="' . t('Location') . '" style="margin: 5px 5px 0 0; text-align: right"><i class="fa fa-globe"></i> ' . $jj['location'] . '</p>';
                     } else {
                         $location = '<br />&nbsp;';
                     }
                     $urltext = str_replace(array('https://'), '', $jj['url']);
                     $o .= '<tr><td><a href="' . ($jj['sellpage'] ? $jj['sellpage'] : $jj['url'] . '/register') . '" ><i class="fa fa-link"></i> ' . $urltext . '</a>' . $location . '</td><td>' . $jj['access'] . '</td><td>' . $jj['register'] . '</td><td>' . '<a target="stats" href="https://hubchart-tarine.rhcloud.com/hub.jsp?hubFqdn=' . $m['host'] . '"><i class="fa fa-area-chart"></i></a></td><td>' . ucwords($jj['project']) . ($jj['version'] ? ' ' . $jj['version'] : '') . '</td>';
                     if ($rating_enabled) {
                         $o .= '<td><a href="ratings/' . $host . '" class="btn-btn-default"><i class="fa fa-eye"></i> ' . t('View') . '</a></td>' . $rate_links;
                     }
                     $o .= '</tr>';
                 }
             }
             $o .= '</table>';
             $o .= '</div></div>';
         }
     }
     return $o;
 }
Example #5
0
 function init()
 {
     if (get_config('system', 'block_public') && !local_channel() && !remote_channel()) {
         return;
     }
     if (local_channel()) {
         load_contact_links(local_channel());
     }
     $dirmode = intval(get_config('system', 'directory_mode'));
     $x = find_upstream_directory($dirmode);
     if ($x) {
         $url = $x['url'];
     }
     $poco_rating = get_config('system', 'poco_rating_enable');
     // if unset default to enabled
     if ($poco_rating === false) {
         $poco_rating = true;
     }
     if (!$poco_rating) {
         return;
     }
     if (argc() > 1) {
         $hash = argv(1);
     }
     if (!$hash) {
         notice('Must supply a channel identififier.');
         return;
     }
     $results = false;
     $x = z_fetch_url($url . '/ratingsearch/' . urlencode($hash));
     if ($x['success']) {
         $results = json_decode($x['body'], true);
     }
     if (!$results || !$results['success']) {
         notice('No results.');
         return;
     }
     if (array_key_exists('xchan_hash', $results['target'])) {
         \App::$poi = $results['target'];
     }
     $friends = array();
     $others = array();
     if ($results['ratings']) {
         foreach ($results['ratings'] as $n) {
             if (is_array(\App::$contacts) && array_key_exists($n['xchan_hash'], \App::$contacts)) {
                 $friends[] = $n;
             } else {
                 $others[] = $n;
             }
         }
     }
     \App::$data = array('target' => $results['target'], 'results' => array_merge($friends, $others));
     if (!\App::$data['results']) {
         notice(t('No ratings') . EOL);
     }
     return;
 }
Example #6
0
function embedly_oembed_probe($a, $b)
{
    // try oohembed service
    $ourl = "http://oohembed.com/oohembed/?url=" . $b['url'] . '&maxwidth=' . $b['videowidth'];
    $result = z_fetch_url($ourl);
    if ($result['success']) {
        $b['embed'] = $result['body'];
    }
}
Example #7
0
function noembed_oembed_probe(&$a, &$b)
{
    // try noembed service
    $ourl = 'https://noembed.com/embed?url=' . urlencode($b['url']);
    $result = z_fetch_url($ourl);
    if ($result['success']) {
        $b['embed'] = $result['body'];
    }
}
function ostatus_subscribe_content(&$a)
{
    if (!local_user()) {
        notice(t('Permission denied.') . EOL);
        goaway($_SESSION['return_url']);
        // NOTREACHED
    }
    $o = "<h2>" . t("Subsribing to OStatus contacts") . "</h2>";
    $uid = local_user();
    $a = get_app();
    $counter = intval($_REQUEST['counter']);
    if (get_pconfig($uid, "ostatus", "legacy_friends") == "") {
        if ($_REQUEST["url"] == "") {
            return $o . t("No contact provided.");
        }
        $contact = probe_url($_REQUEST["url"]);
        if (!$contact) {
            return $o . t("Couldn't fetch information for contact.");
        }
        $api = $contact["baseurl"] . "/api/";
        // Fetching friends
        $data = z_fetch_url($api . "statuses/friends.json?screen_name=" . $contact["nick"]);
        if (!$data["success"]) {
            return $o . t("Couldn't fetch friends for contact.");
        }
        set_pconfig($uid, "ostatus", "legacy_friends", $data["body"]);
    }
    $friends = json_decode(get_pconfig($uid, "ostatus", "legacy_friends"));
    $total = sizeof($friends);
    if ($counter >= $total) {
        $a->page['htmlhead'] = '<meta http-equiv="refresh" content="0; URL=' . $a->get_baseurl() . '/settings/connectors">';
        del_pconfig($uid, "ostatus", "legacy_friends");
        del_pconfig($uid, "ostatus", "legacy_contact");
        $o .= t("Done");
        return $o;
    }
    $friend = $friends[$counter++];
    $url = $friend->statusnet_profile_url;
    $o .= "<p>" . $counter . "/" . $total . ": " . $url;
    $data = probe_url($url);
    if ($data["network"] == NETWORK_OSTATUS) {
        $result = new_contact($uid, $url, true);
        if ($result["success"]) {
            $o .= " - " . t("success");
        } else {
            $o .= " - " . t("failed");
        }
    } else {
        $o .= " - " . t("ignored");
    }
    $o .= "</p>";
    $o .= "<p>" . t("Keep this window open until done.") . "</p>";
    $a->page['htmlhead'] = '<meta http-equiv="refresh" content="0; URL=' . $a->get_baseurl() . '/ostatus_subscribe?counter=' . $counter . '">';
    return $o;
}
function fortunate_fetch(&$a, &$b)
{
    $fort_server = get_config('fortunate', 'server');
    if (!$fort_server) {
        return;
    }
    $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/fortunate/fortunate.css' . '" media="all" />' . "\r\n";
    $s = z_fetch_url('http://' . $fort_server . '/cookie.php?numlines=4&equal=1&rand=' . mt_rand());
    if ($s['success']) {
        $b .= '<div class="fortunate">' . $s['body'] . '</div>';
    }
}
Example #10
0
function oexchange_content(&$a)
{
    if (!local_channel()) {
        if (remote_channel()) {
            $observer = $a->get_observer();
            if ($observer && $observer['xchan_url']) {
                $parsed = @parse_url($observer['xchan_url']);
                if (!$parsed) {
                    notice(t('Unable to find your hub.') . EOL);
                    return;
                }
                $url = $parsed['scheme'] . '://' . $parsed['host'] . ($parsed['port'] ? ':' . $parsed['port'] : '');
                $url .= '/oexchange';
                $result = z_post_url($url, $_REQUEST);
                json_return_and_die($result);
            }
        }
        return login(false);
    }
    if (argc() > 1 && argv(1) === 'done') {
        info(t('Post successful.') . EOL);
        return;
    }
    $url = x($_REQUEST, 'url') && strlen($_REQUEST['url']) ? urlencode(notags(trim($_REQUEST['url']))) : '';
    $title = x($_REQUEST, 'title') && strlen($_REQUEST['title']) ? '&title=' . urlencode(notags(trim($_REQUEST['title']))) : '';
    $description = x($_REQUEST, 'description') && strlen($_REQUEST['description']) ? '&description=' . urlencode(notags(trim($_REQUEST['description']))) : '';
    $tags = x($_REQUEST, 'tags') && strlen($_REQUEST['tags']) ? '&tags=' . urlencode(notags(trim($_REQUEST['tags']))) : '';
    $ret = z_fetch_url($a->get_baseurl() . '/urlinfo?f=&url=' . $url . $title . $description . $tags);
    if ($ret['success']) {
        $s = $ret['body'];
    }
    if (!strlen($s)) {
        return;
    }
    $post = array();
    $post['profile_uid'] = local_channel();
    $post['return'] = '/oexchange/done';
    $post['body'] = $s;
    $post['type'] = 'wall';
    $_REQUEST = $post;
    require_once 'mod/item.php';
    item_post($a);
}
Example #11
0
 function get()
 {
     $auth_success = false;
     $o .= '<h3>Magic-Auth Diagnostic</h3>';
     if (!local_channel()) {
         notice(t('Permission denied.') . EOL);
         return $o;
     }
     $o .= '<form action="authtest" method="get">';
     $o .= 'Target URL: <input type="text" style="width: 250px;" name="dest" value="' . $_GET['dest'] . '" />';
     $o .= '<input type="submit" name="submit" value="Submit" /></form>';
     $o .= '<br /><br />';
     if (x($_GET, 'dest')) {
         if (strpos($_GET['dest'], '@')) {
             $_GET['dest'] = $_REQUEST['dest'] = 'https://' . substr($_GET['dest'], strpos($_GET['dest'], '@') + 1) . '/channel/' . substr($_GET['dest'], 0, strpos($_GET['dest'], '@'));
         }
         $_REQUEST['test'] = 1;
         $mod = new Magic();
         $x = $mod->init($a);
         $o .= 'Local Setup returns: ' . print_r($x, true);
         if ($x['url']) {
             $z = z_fetch_url($x['url'] . '&test=1');
             if ($z['success']) {
                 $j = json_decode($z['body'], true);
                 if (!$j) {
                     $o .= 'json_decode failure from remote site. ' . print_r($z['body'], true);
                 }
                 $o .= 'Remote site responded: ' . print_r($j, true);
                 if ($j['success'] && strpos($j['message'], 'Authentication Success')) {
                     $auth_success = true;
                 }
             } else {
                 $o .= 'fetch url failure.' . print_r($z, true);
             }
         }
         if (!$auth_success) {
             $o .= 'Authentication Failed!' . EOL;
         }
     }
     return str_replace("\n", '<br />', $o);
 }
Example #12
0
function sslify_init(&$a)
{
    $x = z_fetch_url($_REQUEST['url']);
    if ($x['success']) {
        $h = explode("\n", $x['header']);
        foreach ($h as $l) {
            list($k, $v) = array_map("trim", explode(":", trim($l), 2));
            $hdrs[$k] = $v;
        }
        if (array_key_exists('Content-Type', $hdrs)) {
            $type = $hdrs['Content-Type'];
        }
        header('Content-Type: ' . $type);
        echo $x['body'];
        killme();
    }
    killme();
    // for some reason when this fallback is in place - it gets triggered
    // often, (creating mixed content exceptions) even though there is
    // nothing obvious missing on the page when we bypass it.
    goaway($_REQUEST['url']);
}
Example #13
0
function diaspora_load()
{
    register_hook('notifier_hub', 'addon/diaspora/diaspora.php', 'diaspora_process_outbound');
    register_hook('notifier_process', 'addon/diaspora/diaspora.php', 'diaspora_notifier_process');
    register_hook('permissions_create', 'addon/diaspora/diaspora.php', 'diaspora_permissions_create');
    register_hook('permissions_update', 'addon/diaspora/diaspora.php', 'diaspora_permissions_update');
    register_hook('module_loaded', 'addon/diaspora/diaspora.php', 'diaspora_load_module');
    register_hook('follow_allow', 'addon/diaspora/diaspora.php', 'diaspora_follow_allow');
    register_hook('feature_settings_post', 'addon/diaspora/diaspora.php', 'diaspora_feature_settings_post');
    register_hook('feature_settings', 'addon/diaspora/diaspora.php', 'diaspora_feature_settings');
    register_hook('post_local', 'addon/diaspora/diaspora.php', 'diaspora_post_local');
    register_hook('well_known', 'addon/diaspora/diaspora.php', 'diaspora_well_known');
    if (!get_config('diaspora', 'relay_handle')) {
        $x = import_author_diaspora(array('address' => '*****@*****.**'));
        if ($x) {
            set_config('diaspora', 'relay_handle', $x);
            // Now register
            $url = "http://the-federation.info/register/" . App::get_hostname();
            $ret = z_fetch_url($url);
        }
    }
}
Example #14
0
 function import_account($account_id)
 {
     if (!$account_id) {
         logger("import_account: No account ID supplied");
         return;
     }
     $max_identities = account_service_class_fetch($account_id, 'total_identities');
     $max_friends = account_service_class_fetch($account_id, 'total_channels');
     $max_feeds = account_service_class_fetch($account_id, 'total_feeds');
     if ($max_identities !== false) {
         $r = q("select channel_id from channel where channel_account_id = %d", intval($account_id));
         if ($r && count($r) > $max_identities) {
             notice(sprintf(t('Your service plan only allows %d channels.'), $max_identities) . EOL);
             return;
         }
     }
     $data = null;
     $seize = x($_REQUEST, 'make_primary') ? intval($_REQUEST['make_primary']) : 0;
     $import_posts = x($_REQUEST, 'import_posts') ? intval($_REQUEST['import_posts']) : 0;
     $src = $_FILES['filename']['tmp_name'];
     $filename = basename($_FILES['filename']['name']);
     $filesize = intval($_FILES['filename']['size']);
     $filetype = $_FILES['filename']['type'];
     $completed = array_key_exists('import_step', $_SESSION) ? intval($_SESSION['import_step']) : 0;
     if ($completed) {
         logger('saved import step: ' . $_SESSION['import_step']);
     }
     if ($src) {
         // This is OS specific and could also fail if your tmpdir isn't very large
         // mostly used for Diaspora which exports gzipped files.
         if (strpos($filename, '.gz')) {
             @rename($src, $src . '.gz');
             @system('gunzip ' . escapeshellarg($src . '.gz'));
         }
         if ($filesize) {
             $data = @file_get_contents($src);
         }
         unlink($src);
     }
     if (!$src) {
         $old_address = x($_REQUEST, 'old_address') ? $_REQUEST['old_address'] : '';
         if (!$old_address) {
             logger('mod_import: nothing to import.');
             notice(t('Nothing to import.') . EOL);
             return;
         }
         $email = x($_REQUEST, 'email') ? $_REQUEST['email'] : '';
         $password = x($_REQUEST, 'password') ? $_REQUEST['password'] : '';
         $channelname = substr($old_address, 0, strpos($old_address, '@'));
         $servername = substr($old_address, strpos($old_address, '@') + 1);
         $scheme = 'https://';
         $api_path = '/api/red/channel/export/basic?f=&channel=' . $channelname;
         if ($import_posts) {
             $api_path .= '&posts=1';
         }
         $binary = false;
         $redirects = 0;
         $opts = array('http_auth' => $email . ':' . $password);
         $url = $scheme . $servername . $api_path;
         $ret = z_fetch_url($url, $binary, $redirects, $opts);
         if (!$ret['success']) {
             $ret = z_fetch_url('http://' . $servername . $api_path, $binary, $redirects, $opts);
         }
         if ($ret['success']) {
             $data = $ret['body'];
         } else {
             notice(t('Unable to download data from old server') . EOL);
         }
     }
     if (!$data) {
         logger('mod_import: empty file.');
         notice(t('Imported file is empty.') . EOL);
         return;
     }
     $data = json_decode($data, true);
     //	logger('import: data: ' . print_r($data,true));
     //	print_r($data);
     if (array_key_exists('user', $data) && array_key_exists('version', $data)) {
         require_once 'include/Import/import_diaspora.php';
         import_diaspora($data);
         return;
     }
     $moving = false;
     if (array_key_exists('compatibility', $data) && array_key_exists('database', $data['compatibility'])) {
         $v1 = substr($data['compatibility']['database'], -4);
         $v2 = substr(DB_UPDATE_VERSION, -4);
         if ($v2 > $v1) {
             $t = sprintf(t('Warning: Database versions differ by %1$d updates.'), $v2 - $v1);
             notice($t);
         }
         if (array_key_exists('server_role', $data['compatibility']) && $data['compatibility']['server_role'] == 'basic') {
             $moving = true;
         }
     }
     if ($moving) {
         $seize = 1;
     }
     // import channel
     $relocate = array_key_exists('relocate', $data) ? $data['relocate'] : null;
     if (array_key_exists('channel', $data)) {
         if ($completed < 1) {
             $channel = import_channel($data['channel'], $account_id, $seize);
         } else {
             $r = q("select * from channel where channel_account_id = %d and channel_guid = '%s' limit 1", intval($account_id), dbesc($channel['channel_guid']));
             if ($r) {
                 $channel = $r[0];
             }
         }
         if (!$channel) {
             logger('mod_import: channel not found. ', print_r($channel, true));
             notice(t('Cloned channel not found. Import failed.') . EOL);
             return;
         }
     }
     if (!$channel) {
         $channel = \App::get_channel();
     }
     if (!$channel) {
         logger('mod_import: channel not found. ', print_r($channel, true));
         notice(t('No channel. Import failed.') . EOL);
         return;
     }
     if ($completed < 2) {
         if (is_array($data['config'])) {
             import_config($channel, $data['config']);
         }
         logger('import step 2');
         $_SESSION['import_step'] = 2;
     }
     if ($completed < 3) {
         if ($data['photo']) {
             require_once 'include/photo/photo_driver.php';
             import_channel_photo(base64url_decode($data['photo']['data']), $data['photo']['type'], $account_id, $channel['channel_id']);
         }
         if (is_array($data['profile'])) {
             import_profiles($channel, $data['profile']);
         }
         logger('import step 3');
         $_SESSION['import_step'] = 3;
     }
     if ($completed < 4) {
         if (is_array($data['hubloc']) && !$moving) {
             import_hublocs($channel, $data['hubloc'], $seize);
         }
         logger('import step 4');
         $_SESSION['import_step'] = 4;
     }
     if ($completed < 5) {
         // create new hubloc for the new channel at this site
         $r = q("insert into hubloc ( hubloc_guid, hubloc_guid_sig, hubloc_hash, hubloc_addr, hubloc_network, hubloc_primary, \n\t\t\t\thubloc_url, hubloc_url_sig, hubloc_host, hubloc_callback, hubloc_sitekey )\n\t\t\t\tvalues ( '%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s' )", dbesc($channel['channel_guid']), dbesc($channel['channel_guid_sig']), dbesc($channel['channel_hash']), dbesc(channel_reddress($channel)), dbesc('zot'), intval($seize ? 1 : 0), dbesc(z_root()), dbesc(base64url_encode(rsa_sign(z_root(), $channel['channel_prvkey']))), dbesc(\App::get_hostname()), dbesc(z_root() . '/post'), dbesc(get_config('system', 'pubkey')));
         // reset the original primary hubloc if it is being seized
         if ($seize) {
             $r = q("update hubloc set hubloc_primary = 0 where hubloc_primary = 1 and hubloc_hash = '%s' and hubloc_url != '%s' ", dbesc($channel['channel_hash']), dbesc(z_root()));
         }
         logger('import step 5');
         $_SESSION['import_step'] = 5;
     }
     if ($completed < 6) {
         // import xchans and contact photos
         if ($seize) {
             // replace any existing xchan we may have on this site if we're seizing control
             $r = q("delete from xchan where xchan_hash = '%s'", dbesc($channel['channel_hash']));
             $r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_guid_sig, xchan_pubkey, xchan_photo_l, xchan_photo_m, xchan_photo_s, xchan_addr, xchan_url, xchan_follow, xchan_connurl, xchan_name, xchan_network, xchan_photo_date, xchan_name_date, xchan_hidden, xchan_orphan, xchan_censored, xchan_selfcensored, xchan_system, xchan_pubforum, xchan_deleted ) values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d, %d, %d, %d )", dbesc($channel['channel_hash']), dbesc($channel['channel_guid']), dbesc($channel['channel_guid_sig']), dbesc($channel['channel_pubkey']), dbesc(z_root() . "/photo/profile/l/" . $channel['channel_id']), dbesc(z_root() . "/photo/profile/m/" . $channel['channel_id']), dbesc(z_root() . "/photo/profile/s/" . $channel['channel_id']), dbesc(channel_reddress($channel)), dbesc(z_root() . '/channel/' . $channel['channel_address']), dbesc(z_root() . '/follow?f=&url=%s'), dbesc(z_root() . '/poco/' . $channel['channel_address']), dbesc($channel['channel_name']), dbesc('zot'), dbesc(datetime_convert()), dbesc(datetime_convert()), 0, 0, 0, 0, 0, 0, 0);
         }
         logger('import step 6');
         $_SESSION['import_step'] = 6;
     }
     if ($completed < 7) {
         $xchans = $data['xchan'];
         if ($xchans) {
             foreach ($xchans as $xchan) {
                 $hash = make_xchan_hash($xchan['xchan_guid'], $xchan['xchan_guid_sig']);
                 if ($xchan['xchan_network'] === 'zot' && $hash !== $xchan['xchan_hash']) {
                     logger('forged xchan: ' . print_r($xchan, true));
                     continue;
                 }
                 if (!array_key_exists('xchan_hidden', $xchan)) {
                     $xchan['xchan_hidden'] = $xchan['xchan_flags'] & 0x1 ? 1 : 0;
                     $xchan['xchan_orphan'] = $xchan['xchan_flags'] & 0x2 ? 1 : 0;
                     $xchan['xchan_censored'] = $xchan['xchan_flags'] & 0x4 ? 1 : 0;
                     $xchan['xchan_selfcensored'] = $xchan['xchan_flags'] & 0x8 ? 1 : 0;
                     $xchan['xchan_system'] = $xchan['xchan_flags'] & 0x10 ? 1 : 0;
                     $xchan['xchan_pubforum'] = $xchan['xchan_flags'] & 0x20 ? 1 : 0;
                     $xchan['xchan_deleted'] = $xchan['xchan_flags'] & 0x1000 ? 1 : 0;
                 }
                 $r = q("select xchan_hash from xchan where xchan_hash = '%s' limit 1", dbesc($xchan['xchan_hash']));
                 if ($r) {
                     continue;
                 }
                 dbesc_array($xchan);
                 $r = dbq("INSERT INTO xchan (`" . implode("`, `", array_keys($xchan)) . "`) VALUES ('" . implode("', '", array_values($xchan)) . "')");
                 require_once 'include/photo/photo_driver.php';
                 $photos = import_xchan_photo($xchan['xchan_photo_l'], $xchan['xchan_hash']);
                 if ($photos[4]) {
                     $photodate = NULL_DATE;
                 } else {
                     $photodate = $xchan['xchan_photo_date'];
                 }
                 $r = q("update xchan set xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s', xchan_photo_date = '%s'\n\t\t\t\t\t\twhere xchan_hash = '%s'", dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), dbesc($photos[3]), dbesc($photodate), dbesc($xchan['xchan_hash']));
             }
         }
         logger('import step 7');
         $_SESSION['import_step'] = 7;
     }
     // FIXME - ensure we have an xchan if somebody is trying to pull a fast one
     if ($completed < 8) {
         $friends = 0;
         $feeds = 0;
         // import contacts
         $abooks = $data['abook'];
         if ($abooks) {
             foreach ($abooks as $abook) {
                 $abook_copy = $abook;
                 $abconfig = null;
                 if (array_key_exists('abconfig', $abook) && is_array($abook['abconfig']) && count($abook['abconfig'])) {
                     $abconfig = $abook['abconfig'];
                 }
                 unset($abook['abook_id']);
                 unset($abook['abook_rating']);
                 unset($abook['abook_rating_text']);
                 unset($abook['abconfig']);
                 unset($abook['abook_their_perms']);
                 unset($abook['abook_my_perms']);
                 $abook['abook_account'] = $account_id;
                 $abook['abook_channel'] = $channel['channel_id'];
                 if (!array_key_exists('abook_blocked', $abook)) {
                     $abook['abook_blocked'] = $abook['abook_flags'] & 0x1 ? 1 : 0;
                     $abook['abook_ignored'] = $abook['abook_flags'] & 0x2 ? 1 : 0;
                     $abook['abook_hidden'] = $abook['abook_flags'] & 0x4 ? 1 : 0;
                     $abook['abook_archived'] = $abook['abook_flags'] & 0x8 ? 1 : 0;
                     $abook['abook_pending'] = $abook['abook_flags'] & 0x10 ? 1 : 0;
                     $abook['abook_unconnected'] = $abook['abook_flags'] & 0x20 ? 1 : 0;
                     $abook['abook_self'] = $abook['abook_flags'] & 0x80 ? 1 : 0;
                     $abook['abook_feed'] = $abook['abook_flags'] & 0x100 ? 1 : 0;
                 }
                 if ($abook['abook_self']) {
                     $role = get_pconfig($channel['channel_id'], 'system', 'permissions_role');
                     if ($role === 'forum' || $abook['abook_my_perms'] & PERMS_W_TAGWALL) {
                         q("update xchan set xchan_pubforum = 1 where xchan_hash = '%s' ", dbesc($abook['abook_xchan']));
                     }
                 } else {
                     if ($max_friends !== false && $friends > $max_friends) {
                         continue;
                     }
                     if ($max_feeds !== false && intval($abook['abook_feed']) && $feeds > $max_feeds) {
                         continue;
                     }
                 }
                 dbesc_array($abook);
                 $r = dbq("INSERT INTO abook (`" . implode("`, `", array_keys($abook)) . "`) VALUES ('" . implode("', '", array_values($abook)) . "')");
                 $friends++;
                 if (intval($abook['abook_feed'])) {
                     $feeds++;
                 }
                 translate_abook_perms_inbound($channel, $abook_copy);
                 if ($abconfig) {
                     // @fixme does not handle sync of del_abconfig
                     foreach ($abconfig as $abc) {
                         set_abconfig($channel['channel_id'], $abc['xchan'], $abc['cat'], $abc['k'], $abc['v']);
                     }
                 }
             }
         }
         logger('import step 8');
         $_SESSION['import_step'] = 8;
     }
     if ($completed < 9) {
         $groups = $data['group'];
         if ($groups) {
             $saved = array();
             foreach ($groups as $group) {
                 $saved[$group['hash']] = array('old' => $group['id']);
                 if (array_key_exists('name', $group)) {
                     $group['gname'] = $group['name'];
                     unset($group['name']);
                 }
                 unset($group['id']);
                 $group['uid'] = $channel['channel_id'];
                 dbesc_array($group);
                 $r = dbq("INSERT INTO groups (`" . implode("`, `", array_keys($group)) . "`) VALUES ('" . implode("', '", array_values($group)) . "')");
             }
             $r = q("select * from `groups` where uid = %d", intval($channel['channel_id']));
             if ($r) {
                 foreach ($r as $rr) {
                     $saved[$rr['hash']]['new'] = $rr['id'];
                 }
             }
         }
         $group_members = $data['group_member'];
         if ($group_members) {
             foreach ($group_members as $group_member) {
                 unset($group_member['id']);
                 $group_member['uid'] = $channel['channel_id'];
                 foreach ($saved as $x) {
                     if ($x['old'] == $group_member['gid']) {
                         $group_member['gid'] = $x['new'];
                     }
                 }
                 dbesc_array($group_member);
                 $r = dbq("INSERT INTO group_member (`" . implode("`, `", array_keys($group_member)) . "`) VALUES ('" . implode("', '", array_values($group_member)) . "')");
             }
         }
         logger('import step 9');
         $_SESSION['import_step'] = 9;
     }
     if (is_array($data['obj'])) {
         import_objs($channel, $data['obj']);
     }
     if (is_array($data['likes'])) {
         import_likes($channel, $data['likes']);
     }
     if (is_array($data['app'])) {
         import_apps($channel, $data['app']);
     }
     if (is_array($data['chatroom'])) {
         import_chatrooms($channel, $data['chatroom']);
     }
     if (is_array($data['conv'])) {
         import_conv($channel, $data['conv']);
     }
     if (is_array($data['mail'])) {
         import_mail($channel, $data['mail']);
     }
     if (is_array($data['event'])) {
         import_events($channel, $data['event']);
     }
     if (is_array($data['event_item'])) {
         import_items($channel, $data['event_item'], false, $relocate);
     }
     if (is_array($data['menu'])) {
         import_menus($channel, $data['menu']);
     }
     $addon = array('channel' => $channel, 'data' => $data);
     call_hooks('import_channel', $addon);
     $saved_notification_flags = notifications_off($channel['channel_id']);
     if ($import_posts && array_key_exists('item', $data) && $data['item']) {
         import_items($channel, $data['item'], false, $relocate);
     }
     notifications_on($channel['channel_id'], $saved_notification_flags);
     if (array_key_exists('item_id', $data) && $data['item_id']) {
         import_item_ids($channel, $data['item_id']);
     }
     // FIXME - ensure we have a self entry if somebody is trying to pull a fast one
     // send out refresh requests
     // notify old server that it may no longer be primary.
     \Zotlabs\Daemon\Master::Summon(array('Notifier', 'location', $channel['channel_id']));
     // This will indirectly perform a refresh_all *and* update the directory
     \Zotlabs\Daemon\Master::Summon(array('Directory', $channel['channel_id']));
     notice(t('Import completed.') . EOL);
     change_channel($channel['channel_id']);
     unset($_SESSION['import_step']);
     goaway(z_root() . '/network');
 }
Example #15
0
function remote_online_status($webbie)
{
    $result = false;
    $r = q("select * from hubloc where hubloc_addr = '%s' limit 1", dbesc($webbie));
    if (!$r) {
        return $result;
    }
    $url = $r[0]['hubloc_url'] . '/online/' . substr($webbie, 0, strpos($webbie, '@'));
    $x = z_fetch_url($url);
    if ($x['success']) {
        $j = json_decode($x['body'], true);
        if ($j) {
            $result = $j['result'] ? $j['result'] : false;
        }
    }
    return $result;
}
Example #16
0
 function exec()
 {
     $opts = $this->curlopts;
     $url = $this->url;
     if ($this->auth) {
         $opts['http_auth'] = $this->auth;
     }
     if ($this->magicauth) {
         $opts['cookiejar'] = 'store/[data]/cookie_' . $this->magicauth;
         $opts['cookiefile'] = 'store/[data]/cookie_' . $this->magicauth;
         $opts['cookie'] = 'PHPSESSID=' . trim(file_get_contents('store/[data]/cookien_' . $this->magicauth));
         $c = channelx_by_n($this->magicauth);
         if ($c) {
             $url = zid($this->url, channel_reddress($c));
         }
     }
     if ($this->custom) {
         $opts['custom'] = $this->custom;
     }
     if ($this->headers) {
         $opts['headers'] = $this->headers;
     }
     if ($this->upload) {
         $opts['upload'] = true;
         $opts['infile'] = $this->filehandle;
         $opts['infilesize'] = strlen($this->request_data);
         $opts['readfunc'] = [$this, 'curl_read'];
     }
     $recurse = 0;
     return z_fetch_url($this->url, true, $recurse, $opts ? $opts : null);
 }
Example #17
0
function import_xchan_photo($photo, $xchan, $thing = false)
{
    $flags = $thing ? PHOTO_THING : PHOTO_XCHAN;
    $album = $thing ? 'Things' : 'Contact Photos';
    logger('import_xchan_photo: updating channel photo from ' . $photo . ' for ' . $xchan, LOGGER_DEBUG);
    if ($thing) {
        $hash = photo_new_resource();
    } else {
        $r = q("select resource_id from photo where xchan = '%s' and photo_usage = %d and imgscale = 4 limit 1", dbesc($xchan), intval(PHOTO_XCHAN));
        if ($r) {
            $hash = $r[0]['resource_id'];
        } else {
            $hash = photo_new_resource();
        }
    }
    $photo_failure = false;
    $img_str = '';
    if ($photo) {
        $filename = basename($photo);
        $result = z_fetch_url($photo, true);
        if ($result['success']) {
            $img_str = $result['body'];
            $type = guess_image_type($photo, $result['header']);
            $h = explode("\n", $result['header']);
            if ($h) {
                foreach ($h as $hl) {
                    if (stristr($hl, 'content-type:')) {
                        if (!stristr($hl, 'image/')) {
                            $photo_failure = true;
                        }
                    }
                }
            }
        }
    } else {
        $photo_failure = true;
    }
    if (!$photo_failure) {
        $img = photo_factory($img_str, $type);
        if ($img->is_valid()) {
            $width = $img->getWidth();
            $height = $img->getHeight();
            if ($width && $height) {
                if ($width / $height > 1.2) {
                    // crop out the sides
                    $margin = $width - $height;
                    $img->cropImage(300, $margin / 2, 0, $height, $height);
                } elseif ($height / $width > 1.2) {
                    // crop out the bottom
                    $margin = $height - $width;
                    $img->cropImage(300, 0, 0, $width, $width);
                } else {
                    $img->scaleImageSquare(300);
                }
            } else {
                $photo_failure = true;
            }
            $p = array('xchan' => $xchan, 'resource_id' => $hash, 'filename' => basename($photo), 'album' => $album, 'photo_usage' => $flags, 'imgscale' => 4);
            $r = $img->save($p);
            if ($r === false) {
                $photo_failure = true;
            }
            $img->scaleImage(80);
            $p['imgscale'] = 5;
            $r = $img->save($p);
            if ($r === false) {
                $photo_failure = true;
            }
            $img->scaleImage(48);
            $p['imgscale'] = 6;
            $r = $img->save($p);
            if ($r === false) {
                $photo_failure = true;
            }
            $photo = z_root() . '/photo/' . $hash . '-4';
            $thumb = z_root() . '/photo/' . $hash . '-5';
            $micro = z_root() . '/photo/' . $hash . '-6';
        } else {
            logger('import_xchan_photo: invalid image from ' . $photo);
            $photo_failure = true;
        }
    }
    if ($photo_failure) {
        $photo = z_root() . '/' . get_default_profile_photo();
        $thumb = z_root() . '/' . get_default_profile_photo(80);
        $micro = z_root() . '/' . get_default_profile_photo(48);
        $type = 'image/png';
    }
    return array($photo, $thumb, $micro, $type, $photo_failure);
}
Example #18
0
function random_profile()
{
    $randfunc = db_getfunc('rand');
    $checkrandom = get_config('randprofile', 'check');
    // False by default
    $retryrandom = intval(get_config('randprofile', 'retry'));
    if ($retryrandom == 0) {
        $retryrandom = 5;
    }
    for ($i = 0; $i < $retryrandom; $i++) {
        $r = q("select xchan_url from xchan left join hubloc on hubloc_hash = xchan_hash where hubloc_connected > %s - interval %s order by {$randfunc} limit 1", db_utcnow(), db_quoteinterval('30 day'));
        if (!$r) {
            return '';
        }
        // Couldn't get a random channel
        if ($checkrandom) {
            $x = z_fetch_url($r[0]['xchan_url']);
            if ($x['success']) {
                return $r[0]['xchan_url'];
            } else {
                logger('Random channel turned out to be bad.');
            }
        } else {
            return $r[0]['xchan_url'];
        }
    }
    return '';
}
Example #19
0
function diaspora_reshare($importer, $xml, $msg)
{
    logger('diaspora_reshare: init: ' . print_r($xml, true));
    $a = get_app();
    $guid = notags(unxmlify($xml->guid));
    $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
    if ($diaspora_handle != $msg['author']) {
        logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
        return 202;
    }
    $contact = diaspora_get_contact_by_handle($importer['channel_id'], $diaspora_handle);
    if (!$contact) {
        return;
    }
    if (!perm_is_allowed($importer['channel_id'], $contact['xchan_hash'], 'send_stream')) {
        logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml, true));
        return 202;
    }
    $search_guid = strlen($guid) == 64 ? $guid . '%' : $guid;
    $r = q("SELECT id FROM item WHERE uid = %d AND mid like '%s' LIMIT 1", intval($importer['channel_id']), dbesc($search_guid));
    if ($r) {
        logger('diaspora_reshare: message exists: ' . $guid);
        return;
    }
    $orig_author = notags(unxmlify($xml->root_diaspora_id));
    $orig_guid = notags(unxmlify($xml->root_guid));
    $source_url = 'https://' . substr($orig_author, strpos($orig_author, '@') + 1) . '/p/' . $orig_guid . '.xml';
    $orig_url = 'https://' . substr($orig_author, strpos($orig_author, '@') + 1) . '/posts/' . $orig_guid;
    $x = z_fetch_url($source_url);
    if (!$x['success']) {
        $x = z_fetch_url(str_replace('https://', 'http://', $source_url));
    }
    if (!$x['success']) {
        logger('diaspora_reshare: unable to fetch source url ' . $source_url);
        return;
    }
    logger('diaspora_reshare: source: ' . $x['body']);
    $source_xml = parse_xml_string($x['body'], false);
    if ($source_xml->post->status_message) {
        $body = diaspora2bb($source_xml->post->status_message->raw_message);
        // Checking for embedded pictures
        if ($source_xml->post->status_message->photo->remote_photo_path && $source_xml->post->status_message->photo->remote_photo_name) {
            $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
            $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
            $body = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n" . $body;
            logger('diaspora_reshare: embedded picture link found: ' . $body, LOGGER_DEBUG);
        }
        $body = scale_external_images($body);
        // Add OEmbed and other information to the body
        //		$body = add_page_info_to_body($body, false, true);
    } else {
        // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
        logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml, true));
        $body = "";
        //return;
    }
    //if(! $body) {
    //	logger('diaspora_reshare: empty body: source= ' . $x);
    //	return;
    //}
    $person = find_diaspora_person_by_handle($orig_author);
    if ($person) {
        $orig_author_name = $person['xchan_name'];
        $orig_author_link = $person['xchan_url'];
        $orig_author_photo = $person['xchan_photo_m'];
    }
    $newbody = "[share author='" . urlencode($orig_author_name) . "' profile='" . $orig_author_link . "' avatar='" . $orig_author_photo . "' link='" . $orig_url . "' posted='" . datetime_convert('UTC', 'UTC', unxmlify($sourcexml->post->status_message->created_at)) . "' message_id='" . unxmlify($source_xml->post->status_message->guid) . "]" . $body . "[/share]";
    $created = unxmlify($xml->created_at);
    $private = unxmlify($xml->public) == 'false' ? 1 : 0;
    $datarray = array();
    $str_tags = '';
    $tags = get_tags($newbody);
    if (count($tags)) {
        $datarray['term'] = array();
        foreach ($tags as $tag) {
            if (strpos($tag, '#') === 0) {
                if (strpos($tag, '[url=')) {
                    continue;
                }
                // don't link tags that are already embedded in links
                if (preg_match('/\\[(.*?)' . preg_quote($tag, '/') . '(.*?)\\]/', $newbody)) {
                    continue;
                }
                if (preg_match('/\\[(.*?)\\]\\((.*?)' . preg_quote($tag, '/') . '(.*?)\\)/', $newbody)) {
                    continue;
                }
                $basetag = str_replace('_', ' ', substr($tag, 1));
                $newbody = str_replace($tag, '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]', $newbody);
                $datarray['term'][] = array('uid' => $importer['channel_id'], 'type' => TERM_HASHTAG, 'otype' => TERM_OBJ_POST, 'term' => $basetag, 'url' => z_root() . '/search?tag=' . rawurlencode($basetag));
            }
        }
    }
    $cnt = preg_match_all('/@\\[url=(.*?)\\](.*?)\\[\\/url\\]/ism', $newbody, $matches, PREG_SET_ORDER);
    if ($cnt) {
        foreach ($matches as $mtch) {
            $datarray['term'][] = array('uid' => $importer['channel_id'], 'type' => TERM_MENTION, 'otype' => TERM_OBJ_POST, 'term' => $mtch[2], 'url' => $mtch[1]);
        }
    }
    // This won't work
    $plink = 'https://' . substr($diaspora_handle, strpos($diaspora_handle, '@') + 1) . '/posts/' . $guid;
    $datarray['uid'] = $importer['channel_id'];
    $datarray['mid'] = $datarray['parent_mid'] = $guid;
    $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC', 'UTC', $created);
    $datarray['item_private'] = $private;
    $datarray['plink'] = $plink;
    $datarray['owner_xchan'] = $contact['xchan_hash'];
    $datarray['author_xchan'] = $contact['xchan_hash'];
    $datarray['body'] = $newbody;
    $datarray['app'] = 'Diaspora';
    $result = item_store($datarray);
    return;
}
Example #20
0
 function get()
 {
     if (get_config('system', 'block_public') && !local_channel() && !remote_channel()) {
         notice(t('Public access denied.') . EOL);
         return;
     }
     $observer = get_observer_hash();
     $globaldir = get_directory_setting($observer, 'globaldir');
     // override your personal global search pref if we're doing a navbar search of the directory
     if (intval($_REQUEST['navsearch'])) {
         $globaldir = 1;
     }
     $safe_mode = get_directory_setting($observer, 'safemode');
     $pubforums = get_directory_setting($observer, 'pubforums');
     $o = '';
     nav_set_selected('directory');
     if (x($_POST, 'search')) {
         $search = notags(trim($_POST['search']));
     } else {
         $search = x($_GET, 'search') ? notags(trim(rawurldecode($_GET['search']))) : '';
     }
     if (strpos($search, '=') && local_channel() && get_pconfig(local_channel(), 'feature', 'expert')) {
         $advanced = $search;
     }
     $keywords = $_GET['keywords'] ? $_GET['keywords'] : '';
     // Suggest channels if no search terms or keywords are given
     $suggest = local_channel() && x($_REQUEST, 'suggest') ? $_REQUEST['suggest'] : '';
     if ($suggest) {
         $r = suggestion_query(local_channel(), get_observer_hash());
         // Remember in which order the suggestions were
         $addresses = array();
         $common = array();
         $index = 0;
         foreach ($r as $rr) {
             $common[$rr['xchan_addr']] = $rr['total'];
             $addresses[$rr['xchan_addr']] = $index++;
         }
         // Build query to get info about suggested people
         $advanced = '';
         foreach (array_keys($addresses) as $address) {
             $advanced .= "address=\"{$address}\" ";
         }
         // Remove last space in the advanced query
         $advanced = rtrim($advanced);
     }
     $tpl = get_markup_template('directory_header.tpl');
     $dirmode = intval(get_config('system', 'directory_mode'));
     if ($dirmode == DIRECTORY_MODE_PRIMARY || $dirmode == DIRECTORY_MODE_STANDALONE) {
         $url = z_root() . '/dirsearch';
     }
     if (!$url) {
         $directory = find_upstream_directory($dirmode);
         if (!$directory || !array_key_exists('url', $directory) || !$directory['url']) {
             logger('CRITICAL: No directory server URL');
         }
         $url = $directory['url'] . '/dirsearch';
     }
     $token = get_config('system', 'realm_token');
     logger('mod_directory: URL = ' . $url, LOGGER_DEBUG);
     $contacts = array();
     if (local_channel()) {
         $x = q("select abook_xchan from abook where abook_channel = %d", intval(local_channel()));
         if ($x) {
             foreach ($x as $xx) {
                 $contacts[] = $xx['abook_xchan'];
             }
         }
     }
     if ($url) {
         $numtags = get_config('system', 'directorytags');
         $kw = intval($numtags) > 0 ? intval($numtags) : 50;
         if (get_config('system', 'disable_directory_keywords')) {
             $kw = 0;
         }
         $query = $url . '?f=&kw=' . $kw . ($safe_mode != 1 ? '&safe=' . $safe_mode : '');
         if ($token) {
             $query .= '&t=' . $token;
         }
         if (!$globaldir) {
             $query .= '&hub=' . \App::get_hostname();
         }
         if ($search) {
             $query .= '&name=' . urlencode($search) . '&keywords=' . urlencode($search);
         }
         if (strpos($search, '@')) {
             $query .= '&address=' . urlencode($search);
         }
         if ($keywords) {
             $query .= '&keywords=' . urlencode($keywords);
         }
         if ($advanced) {
             $query .= '&query=' . urlencode($advanced);
         }
         if (!is_null($pubforums)) {
             $query .= '&pubforums=' . intval($pubforums);
         }
         $directory_sort_order = get_config('system', 'directory_sort_order');
         if (!$directory_sort_order) {
             $directory_sort_order = 'date';
         }
         $sort_order = x($_REQUEST, 'order') ? $_REQUEST['order'] : $directory_sort_order;
         if ($sort_order) {
             $query .= '&order=' . urlencode($sort_order);
         }
         if (\App::$pager['page'] != 1) {
             $query .= '&p=' . \App::$pager['page'];
         }
         logger('mod_directory: query: ' . $query);
         $x = z_fetch_url($query);
         logger('directory: return from upstream: ' . print_r($x, true), LOGGER_DATA);
         if ($x['success']) {
             $t = 0;
             $j = json_decode($x['body'], true);
             if ($j) {
                 if ($j['results']) {
                     $entries = array();
                     $photo = 'thumb';
                     foreach ($j['results'] as $rr) {
                         $profile_link = chanlink_url($rr['url']);
                         $pdesc = $rr['description'] ? $rr['description'] . '<br />' : '';
                         $connect_link = local_channel() ? z_root() . '/follow?f=&url=' . urlencode($rr['address']) : '';
                         // Checking status is disabled ATM until someone checks the performance impact more carefully
                         //$online = remote_online_status($rr['address']);
                         $online = '';
                         if (in_array($rr['hash'], $contacts)) {
                             $connect_link = '';
                         }
                         $location = '';
                         if (strlen($rr['locale'])) {
                             $location .= $rr['locale'];
                         }
                         if (strlen($rr['region'])) {
                             if (strlen($rr['locale'])) {
                                 $location .= ', ';
                             }
                             $location .= $rr['region'];
                         }
                         if (strlen($rr['country'])) {
                             if (strlen($location)) {
                                 $location .= ', ';
                             }
                             $location .= $rr['country'];
                         }
                         $age = '';
                         if (strlen($rr['birthday'])) {
                             if (($years = age($rr['birthday'], 'UTC', '')) != 0) {
                                 $age = $years;
                             }
                         }
                         $page_type = '';
                         if ($rr['total_ratings']) {
                             $total_ratings = sprintf(tt("%d rating", "%d ratings", $rr['total_ratings']), $rr['total_ratings']);
                         } else {
                             $total_ratings = '';
                         }
                         $profile = $rr;
                         if (x($profile, 'locale') == 1 || x($profile, 'region') == 1 || x($profile, 'postcode') == 1 || x($profile, 'country') == 1) {
                             $gender = x($profile, 'gender') == 1 ? t('Gender: ') . $profile['gender'] : False;
                         }
                         $marital = x($profile, 'marital') == 1 ? t('Status: ') . $profile['marital'] : False;
                         $homepage = x($profile, 'homepage') == 1 ? t('Homepage: ') : False;
                         $homepageurl = x($profile, 'homepage') == 1 ? $profile['homepage'] : '';
                         $hometown = x($profile, 'hometown') == 1 ? $profile['hometown'] : False;
                         $about = x($profile, 'about') == 1 ? bbcode($profile['about']) : False;
                         $keywords = x($profile, 'keywords') ? $profile['keywords'] : '';
                         $out = '';
                         if ($keywords) {
                             $keywords = str_replace(',', ' ', $keywords);
                             $keywords = str_replace('  ', ' ', $keywords);
                             $karr = explode(' ', $keywords);
                             if ($karr) {
                                 if (local_channel()) {
                                     $r = q("select keywords from profile where uid = %d and is_default = 1 limit 1", intval(local_channel()));
                                     if ($r) {
                                         $keywords = str_replace(',', ' ', $r[0]['keywords']);
                                         $keywords = str_replace('  ', ' ', $keywords);
                                         $marr = explode(' ', $keywords);
                                     }
                                 }
                                 foreach ($karr as $k) {
                                     if (strlen($out)) {
                                         $out .= ', ';
                                     }
                                     if ($marr && in_arrayi($k, $marr)) {
                                         $out .= '<strong>' . $k . '</strong>';
                                     } else {
                                         $out .= $k;
                                     }
                                 }
                             }
                         }
                         $entry = array('id' => ++$t, 'profile_link' => $profile_link, 'public_forum' => $rr['public_forum'], 'photo' => $rr['photo'], 'hash' => $rr['hash'], 'alttext' => $rr['name'] . (local_channel() || remote_channel() ? ' ' . $rr['address'] : ''), 'name' => $rr['name'], 'age' => $age, 'age_label' => t('Age:'), 'profile' => $profile, 'address' => $rr['address'], 'nickname' => substr($rr['address'], 0, strpos($rr['address'], '@')), 'location' => $location, 'location_label' => t('Location:'), 'gender' => $gender, 'total_ratings' => $total_ratings, 'viewrate' => true, 'canrate' => local_channel() ? true : false, 'pdesc' => $pdesc, 'pdesc_label' => t('Description:'), 'marital' => $marital, 'homepage' => $homepage, 'homepageurl' => linkify($homepageurl), 'hometown' => $hometown, 'hometown_label' => t('Hometown:'), 'about' => $about, 'about_label' => t('About:'), 'conn_label' => t('Connect'), 'forum_label' => t('Public Forum:'), 'connect' => $connect_link, 'online' => $online, 'kw' => $out ? t('Keywords: ') : '', 'keywords' => $out, 'ignlink' => $suggest ? z_root() . '/directory?ignore=' . $rr['hash'] : '', 'ignore_label' => t('Don\'t suggest'), 'common_friends' => $common[$rr['address']] ? intval($common[$rr['address']]) : '', 'common_label' => t('Common connections:'), 'common_count' => intval($common[$rr['address']]), 'safe' => $safe_mode);
                         $arr = array('contact' => $rr, 'entry' => $entry);
                         call_hooks('directory_item', $arr);
                         unset($profile);
                         unset($location);
                         if (!$arr['entry']) {
                             continue;
                         }
                         if ($sort_order == '' && $suggest) {
                             $entries[$addresses[$rr['address']]] = $arr['entry'];
                             // Use the same indexes as originally to get the best suggestion first
                         } else {
                             $entries[] = $arr['entry'];
                         }
                     }
                     ksort($entries);
                     // Sort array by key so that foreach-constructs work as expected
                     if ($j['keywords']) {
                         \App::$data['directory_keywords'] = $j['keywords'];
                     }
                     logger('mod_directory: entries: ' . print_r($entries, true), LOGGER_DATA);
                     if ($_REQUEST['aj']) {
                         if ($entries) {
                             $o = replace_macros(get_markup_template('directajax.tpl'), array('$entries' => $entries));
                         } else {
                             $o = '<div id="content-complete"></div>';
                         }
                         echo $o;
                         killme();
                     } else {
                         $maxheight = 94;
                         $dirtitle = $globaldir ? t('Global Directory') : t('Local Directory');
                         $o .= "<script> var page_query = '" . $_GET['q'] . "'; var extra_args = '" . extra_query_args() . "' ; divmore_height = " . intval($maxheight) . ";  </script>";
                         $o .= replace_macros($tpl, array('$search' => $search, '$desc' => t('Find'), '$finddsc' => t('Finding:'), '$safetxt' => htmlspecialchars($search, ENT_QUOTES, 'UTF-8'), '$entries' => $entries, '$dirlbl' => $suggest ? t('Channel Suggestions') : $dirtitle, '$submit' => t('Find'), '$next' => alt_pager($a, $j['records'], t('next page'), t('previous page')), '$sort' => t('Sort options'), '$normal' => t('Alphabetic'), '$reverse' => t('Reverse Alphabetic'), '$date' => t('Newest to Oldest'), '$reversedate' => t('Oldest to Newest'), '$suggest' => $suggest ? '&suggest=1' : ''));
                     }
                 } else {
                     if ($_REQUEST['aj']) {
                         $o = '<div id="content-complete"></div>';
                         echo $o;
                         killme();
                     }
                     if (\App::$pager['page'] == 1 && $j['records'] == 0 && strpos($search, '@')) {
                         goaway(z_root() . '/chanview/?f=&address=' . $search);
                     }
                     info(t("No entries (some entries may be hidden).") . EOL);
                 }
             }
         }
     }
     return $o;
 }
Example #21
0
File: zot.php Project: 23n/hubzilla
/**
 * @brief
 *
 * @param array $arr
 * @param string $pubkey
 * @return boolean true if updated or inserted
 */
function import_site($arr, $pubkey)
{
    if (!is_array($arr) || !$arr['url'] || !$arr['url_sig']) {
        return false;
    }
    if (!rsa_verify($arr['url'], base64url_decode($arr['url_sig']), $pubkey)) {
        logger('import_site: bad url_sig');
        return false;
    }
    $update = false;
    $exists = false;
    $r = q("select * from site where site_url = '%s' limit 1", dbesc($arr['url']));
    if ($r) {
        $exists = true;
        $siterecord = $r[0];
    }
    $site_directory = 0;
    if ($arr['directory_mode'] == 'normal') {
        $site_directory = DIRECTORY_MODE_NORMAL;
    }
    if ($arr['directory_mode'] == 'primary') {
        $site_directory = DIRECTORY_MODE_PRIMARY;
    }
    if ($arr['directory_mode'] == 'secondary') {
        $site_directory = DIRECTORY_MODE_SECONDARY;
    }
    if ($arr['directory_mode'] == 'standalone') {
        $site_directory = DIRECTORY_MODE_STANDALONE;
    }
    $register_policy = 0;
    if ($arr['register_policy'] == 'closed') {
        $register_policy = REGISTER_CLOSED;
    }
    if ($arr['register_policy'] == 'open') {
        $register_policy = REGISTER_OPEN;
    }
    if ($arr['register_policy'] == 'approve') {
        $register_policy = REGISTER_APPROVE;
    }
    $access_policy = 0;
    if (array_key_exists('access_policy', $arr)) {
        if ($arr['access_policy'] === 'private') {
            $access_policy = ACCESS_PRIVATE;
        }
        if ($arr['access_policy'] === 'paid') {
            $access_policy = ACCESS_PAID;
        }
        if ($arr['access_policy'] === 'free') {
            $access_policy = ACCESS_FREE;
        }
        if ($arr['access_policy'] === 'tiered') {
            $access_policy = ACCESS_TIERED;
        }
    }
    // don't let insecure sites register as public hubs
    if (strpos($arr['url'], 'https://') === false) {
        $access_policy = ACCESS_PRIVATE;
    }
    if ($access_policy != ACCESS_PRIVATE) {
        $x = z_fetch_url($arr['url'] . '/siteinfo/json');
        if (!$x['success']) {
            $access_policy = ACCESS_PRIVATE;
        }
    }
    $directory_url = htmlspecialchars($arr['directory_url'], ENT_COMPAT, 'UTF-8', false);
    $url = htmlspecialchars(strtolower($arr['url']), ENT_COMPAT, 'UTF-8', false);
    $sellpage = htmlspecialchars($arr['sellpage'], ENT_COMPAT, 'UTF-8', false);
    $site_location = htmlspecialchars($arr['location'], ENT_COMPAT, 'UTF-8', false);
    $site_realm = htmlspecialchars($arr['realm'], ENT_COMPAT, 'UTF-8', false);
    $site_project = htmlspecialchars($arr['project'], ENT_COMPAT, 'UTF-8', false);
    // You can have one and only one primary directory per realm.
    // Downgrade any others claiming to be primary. As they have
    // flubbed up this badly already, don't let them be directory servers at all.
    if ($site_directory === DIRECTORY_MODE_PRIMARY && $site_realm === get_directory_realm() && $arr['url'] != get_directory_primary()) {
        $site_directory = DIRECTORY_MODE_NORMAL;
    }
    if ($exists) {
        if ($siterecord['site_flags'] != $site_directory || $siterecord['site_access'] != $access_policy || $siterecord['site_directory'] != $directory_url || $siterecord['site_sellpage'] != $sellpage || $siterecord['site_location'] != $site_location || $siterecord['site_register'] != $register_policy || $siterecord['site_project'] != $site_project || $siterecord['site_realm'] != $site_realm) {
            $update = true;
            //			logger('import_site: input: ' . print_r($arr,true));
            //			logger('import_site: stored: ' . print_r($siterecord,true));
            $r = q("update site set site_dead = 0, site_location = '%s', site_flags = %d, site_access = %d, site_directory = '%s', site_register = %d, site_update = '%s', site_sellpage = '%s', site_realm = '%s', site_type = %d, site_project = '%s'\n\t\t\t\twhere site_url = '%s'", dbesc($site_location), intval($site_directory), intval($access_policy), dbesc($directory_url), intval($register_policy), dbesc(datetime_convert()), dbesc($sellpage), dbesc($site_realm), intval(SITE_TYPE_ZOT), dbesc($site_project), dbesc($url));
            if (!$r) {
                logger('import_site: update failed. ' . print_r($arr, true));
            }
        } else {
            // update the timestamp to indicate we communicated with this site
            q("update site set site_dead = 0, site_update = '%s' where site_url = '%s'", dbesc(datetime_convert()), dbesc($url));
        }
    } else {
        $update = true;
        $r = q("insert into site ( site_location, site_url, site_access, site_flags, site_update, site_directory, site_register, site_sellpage, site_realm, site_type, site_project )\n\t\t\tvalues ( '%s', '%s', %d, %d, '%s', '%s', %d, '%s', '%s', %d, '%s' )", dbesc($site_location), dbesc($url), intval($access_policy), intval($site_directory), dbesc(datetime_convert()), dbesc($directory_url), intval($register_policy), dbesc($sellpage), dbesc($site_realm), intval(SITE_TYPE_ZOT), dbesc($site_project));
        if (!$r) {
            logger('import_site: record create failed. ' . print_r($arr, true));
        }
    }
    return $update;
}
Example #22
0
function poco_discover_server_users($data, $server)
{
    if (!isset($data->entry)) {
        return;
    }
    foreach ($data->entry as $entry) {
        $username = "";
        if (isset($entry->urls)) {
            foreach ($entry->urls as $url) {
                if ($url->type == 'profile') {
                    $profile_url = $url->value;
                    $urlparts = parse_url($profile_url);
                    $username = end(explode("/", $urlparts["path"]));
                }
            }
        }
        if ($username != "") {
            logger("Fetch contacts for the user " . $username . " from the server " . $server["nurl"], LOGGER_DEBUG);
            // Fetch all contacts from a given user from the other server
            $url = $server["poco"] . "/" . $username . "/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
            $retdata = z_fetch_url($url);
            if ($retdata["success"]) {
                poco_discover_server(json_decode($retdata["body"]), 3);
            }
        }
    }
}
Example #23
0
/**
 * @brief Check URL rewrite und SSL certificate.
 *
 * @param[out] array &$checks
 */
function check_htaccess(&$checks)
{
    $a = get_app();
    $status = true;
    $help = '';
    $ssl_error = false;
    $url = $a->get_baseurl() . '/setup/testrewrite';
    if (function_exists('curl_init')) {
        $test = z_fetch_url($url);
        if (!$test['success']) {
            if (strstr($url, 'https://')) {
                $test = z_fetch_url($url, false, 0, array('novalidate' => true));
                if ($test['success']) {
                    $ssl_error = true;
                }
            } else {
                $test = z_fetch_url(str_replace('http://', 'https://', $url), false, 0, array('novalidate' => true));
                if ($test['success']) {
                    $ssl_error = true;
                }
            }
            if ($ssl_error) {
                $help = t('SSL certificate cannot be validated. Fix certificate or disable https access to this site.') . EOL;
                $help .= t('If you have https access to your website or allow connections to TCP port 443 (the https: port), you MUST use a browser-valid certificate. You MUST NOT use self-signed certificates!') . EOL;
                $help .= t('This restriction is incorporated because public posts from you may for example contain references to images on your own hub.') . EOL;
                $help .= t('If your certificate is not recognized, members of other sites (who may themselves have valid certificates) will get a warning message on their own site complaining about security issues.') . EOL;
                $help .= t('This can cause usability issues elsewhere (not just on your own site) so we must insist on this requirement.') . EOL;
                $help .= t('Providers are available that issue free certificates which are browser-valid.') . EOL;
                check_add($checks, t('SSL certificate validation'), false, true, $help);
            }
        }
        if (!$test['success'] || $test['body'] != "ok") {
            $status = false;
            $help = t('Url rewrite in .htaccess is not working. Check your server configuration.' . 'Test: ' . var_export($test, true));
        }
        check_add($checks, t('Url rewrite is working'), $status, true, $help);
    } else {
        // cannot check modrewrite if libcurl is not installed
    }
}
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookies);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookies);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'RedMatrix');
$output = curl_exec($ch);
curl_close($ch);
$j = json_decode($output, true);
logger('received: ' . print_r($j, true));
if (!($j['photo'] && $j['photo']['src'])) {
    logger('redphotohelper: no data');
    killme();
}
$filep = fopen($photo_tmp, 'w');
$redirects = 0;
$x = z_fetch_url($fr_server . '/api/red/getphoto?f=&photo_id=' . $photo_id, true, $redirects, array('filep' => $filep, 'cookiejar' => $cookies, 'cookiefile' => $cookies));
fclose($filep);
if (!$x['success']) {
    logger('photo download failed');
    @unlink($photo_tmp);
    killme();
}
$args = array();
$args['src'] = $photo_tmp;
$args['nosync'] = true;
$args['filename'] = $j['photo']['filename'];
if (!$args['filename']) {
    $args['filename'] = t('photo');
}
$args['hash'] = array_key_exists($j['photo']['hash']) ? $j['photo']['hash'] : $j['photo']['resource_id'];
$args['imgscale'] = array_key_exists('imgscale', $j['photo']) ? $j['photo']['imgscale'] : $j['photo']['scale'];
Example #25
0
function handle_feed($uid, $abook_id, $url)
{
    require_once 'include/Contact.php';
    $channel = channelx_by_n($uid);
    if (!$channel) {
        return;
    }
    $x = q("select * from abook left join xchan on abook_xchan = xchan_hash where abook_id = %d and abook_channel = %d limit 1", dbesc($abook_id), intval($uid));
    $recurse = 0;
    $z = z_fetch_url($url, false, $recurse, array('novalidate' => true));
    //logger('handle_feed:' . print_r($z,true));
    if ($z['success']) {
        consume_feed($z['body'], $channel, $x[0], 0);
        consume_feed($z['body'], $channel, $x[0], 1);
    }
}
Example #26
0
function scrape_feed($url)
{
    $a = get_app();
    $ret = array();
    $level = 0;
    $x = z_fetch_url($url, false, $level, array('novalidate' => true));
    if (!$x['success']) {
        return $ret;
    }
    $headers = $x['header'];
    $code = $x['return_code'];
    $s = $x['body'];
    logger('scrape_feed: returns: ' . $code . ' headers=' . $headers, LOGGER_DEBUG);
    if (!$s) {
        logger('scrape_feed: no data returned for ' . $url);
        return $ret;
    }
    $lines = explode("\n", $headers);
    if (count($lines)) {
        foreach ($lines as $line) {
            if (stristr($line, 'content-type:')) {
                if (stristr($line, 'application/atom+xml') || stristr($s, '<feed')) {
                    $ret['feed_atom'] = $url;
                    return $ret;
                }
                if (stristr($line, 'application/rss+xml') || stristr($s, '<rss')) {
                    $ret['feed_rss'] = $url;
                    return $ret;
                }
            }
        }
        // perhaps an RSS version 1 feed with a generic or incorrect content-type?
        if (stristr($s, '</item>')) {
            $ret['feed_rss'] = $url;
            return $ret;
        }
    }
    try {
        $dom = HTML5_Parser::parse($s);
    } catch (DOMException $e) {
        logger('scrape_feed: parse error: ' . $e);
    }
    if (!$dom) {
        logger('scrape_feed: failed to parse.');
        return $ret;
    }
    $head = $dom->getElementsByTagName('base');
    if ($head) {
        foreach ($head as $head0) {
            $basename = $head0->getAttribute('href');
            break;
        }
    }
    if (!$basename) {
        $basename = implode('/', array_slice(explode('/', $url), 0, 3)) . '/';
    }
    $items = $dom->getElementsByTagName('link');
    // get Atom/RSS link elements, take the first one of either.
    if ($items) {
        foreach ($items as $item) {
            $x = $item->getAttribute('rel');
            if ($x === 'alternate' && $item->getAttribute('type') === 'application/atom+xml') {
                if (!x($ret, 'feed_atom')) {
                    $ret['feed_atom'] = $item->getAttribute('href');
                }
            }
            if ($x === 'alternate' && $item->getAttribute('type') === 'application/rss+xml') {
                if (!x($ret, 'feed_rss')) {
                    $ret['feed_rss'] = $item->getAttribute('href');
                }
            }
        }
    }
    // Drupal and perhaps others only provide relative URL's. Turn them into absolute.
    if (x($ret, 'feed_atom') && !strstr($ret['feed_atom'], '://')) {
        $ret['feed_atom'] = $basename . $ret['feed_atom'];
    }
    if (x($ret, 'feed_rss') && !strstr($ret['feed_rss'], '://')) {
        $ret['feed_rss'] = $basename . $ret['feed_rss'];
    }
    return $ret;
}
Example #27
0
/**
 * remote post
 * 
 * https://yoursite/rpost?f=&title=&body=&remote_return=
 *
 * This can be called via either GET or POST, use POST for long body content as suhosin often limits GET parameter length
 *
 * f= placeholder, often required
 * title= Title of post
 * body= Body of post
 * url= URL which will be parsed and the results appended to the body
 * source= Source application
 * remote_return= absolute URL to return after posting is finished
 * type= choices are 'html' or 'bbcode', default is 'bbcode'
 *
 */
function rpost_content(&$a)
{
    $o = '';
    if (!local_channel()) {
        if (remote_channel()) {
            // redirect to your own site.
            // We can only do this with a GET request so you'll need to keep the text short or risk getting truncated
            // by the wretched beast called 'suhosin'. All the browsers now allow long GET requests, but suhosin
            // blocks them.
            $url = get_rpost_path($a->get_observer());
            // make sure we're not looping to our own hub
            if ($url && !stristr($url, $a->get_hostname())) {
                foreach ($_REQUEST as $key => $arg) {
                    $url .= '&' . $key . '=' . $arg;
                }
                goaway($url);
            }
        }
        // The login procedure is going to bugger our $_REQUEST variables
        // so save them in the session.
        if (array_key_exists('body', $_REQUEST)) {
            $_SESSION['rpost'] = $_REQUEST;
        }
        return login();
    }
    // If we have saved rpost session variables, but nothing in the current $_REQUEST, recover the saved variables
    if (!array_key_exists('body', $_REQUEST) && array_key_exists('rpost', $_SESSION)) {
        $_REQUEST = $_SESSION['rpost'];
        unset($_SESSION['rpost']);
    }
    if (array_key_exists('channel', $_REQUEST)) {
        $r = q("select channel_id from channel where channel_account_id = %d and channel_address = '%s' limit 1", intval(get_account_id()), dbesc($_REQUEST['channel']));
        if ($r) {
            require_once 'include/security.php';
            $change = change_channel($r[0]['channel_id']);
        }
    }
    if ($_REQUEST['remote_return']) {
        $_SESSION['remote_return'] = $_REQUEST['remote_return'];
    }
    if (argc() > 1 && argv(1) === 'return') {
        if ($_SESSION['remote_return']) {
            goaway($_SESSION['remote_return']);
        }
        goaway(z_root() . '/network');
    }
    $plaintext = true;
    //	if(feature_enabled(local_channel(),'richtext'))
    //		$plaintext = false;
    if (array_key_exists('type', $_REQUEST) && $_REQUEST['type'] === 'html') {
        require_once 'include/html2bbcode.php';
        $_REQUEST['body'] = html2bbcode($_REQUEST['body']);
    }
    $channel = $a->get_channel();
    $channel_acl = array('allow_cid' => $channel['channel_allow_cid'], 'allow_gid' => $channel['channel_allow_gid'], 'deny_cid' => $channel['channel_deny_cid'], 'deny_gid' => $channel['channel_deny_gid']);
    if ($_REQUEST['url']) {
        $x = z_fetch_url(z_root() . '/parse_url?f=&url=' . urlencode($_REQUEST['url']));
        if ($x['success']) {
            $_REQUEST['body'] = $_REQUEST['body'] . $x['body'];
        }
    }
    $x = array('is_owner' => true, 'allow_location' => intval(get_pconfig($channel['channel_id'], 'system', 'use_browser_location')) ? '1' : '', 'default_location' => $channel['channel_location'], 'nickname' => $channel['channel_address'], 'lockstate' => $channel['channel_allow_cid'] || $channel['channel_allow_gid'] || $channel['channel_deny_cid'] || $channel['channel_deny_gid'] ? 'lock' : 'unlock', 'acl' => populate_acl($channel_acl), 'bang' => '', 'visitor' => true, 'profile_uid' => local_channel(), 'title' => $_REQUEST['title'], 'body' => $_REQUEST['body'], 'attachment' => $_REQUEST['attachment'], 'source' => x($_REQUEST, 'source') ? strip_tags($_REQUEST['source']) : '', 'return_path' => 'rpost/return');
    $editor = status_editor($a, $x);
    $o .= replace_macros(get_markup_template('edpost_head.tpl'), array('$title' => t('Edit post'), '$editor' => $editor));
    return $o;
}
Example #28
0
function z_check_cert()
{
    $a = get_app();
    if (strpos(z_root(), 'https://') !== false) {
        $x = z_fetch_url(z_root() . '/siteinfo/json');
        if (!$x['success']) {
            $recurse = 0;
            $y = z_fetch_url(z_root() . '/siteinfo/json', false, $recurse, array('novalidate' => true));
            if ($y['success']) {
                cert_bad_email();
            }
        }
    }
}
Example #29
0
function randpost_fetch(&$a, &$b)
{
    $fort_server = get_config('fortunate', 'server');
    if (!$fort_server) {
        return;
    }
    $r = q("select * from pconfig where cat = 'randpost' and k = 'enable'");
    if ($r) {
        foreach ($r as $rr) {
            if (!$rr['v']) {
                continue;
            }
            //			logger('randpost');
            // cronhooks run every 10-15 minutes typically
            // try to keep from posting frequently.
            $test = mt_rand(0, 100);
            if ($test == 25) {
                $c = q("select * from channel where channel_id = %d limit 1", intval($rr['uid']));
                if (!$c) {
                    continue;
                }
                $mention = '';
                require_once 'include/html2bbcode.php';
                $s = z_fetch_url('http://' . $fort_server . '/cookie.php?numlines=2&equal=1&rand=' . mt_rand());
                if (!$s['success']) {
                    continue;
                }
                $x = array();
                $x['uid'] = $c[0]['channel_id'];
                $x['aid'] = $c[0]['channel_account_id'];
                $x['mid'] = $x['parent_mid'] = item_message_id();
                $x['author_xchan'] = $x['owner_xchan'] = $c[0]['channel_hash'];
                $x['item_thread_top'] = 1;
                $x['item_origin'] = 1;
                $x['item_verified'] = 1;
                $x['item_wall'] = 1;
                // if it might be a quote make it a quote
                if (strpos($s['body'], '--')) {
                    $x['body'] = $mention . '[quote]' . html2bbcode($s['body']) . '[/quote]';
                } else {
                    $x['body'] = $mention . html2bbcode($s['body']);
                }
                $x['sig'] = base64url_encode(rsa_sign($x['body'], $c[0]['channel_prvkey']));
                $post = item_store($x);
                $post_id = $post['item_id'];
                $x['id'] = $post_id;
                call_hooks('post_local_end', $x);
                Zotlabs\Daemon\Master::Summon(array('Notifier', 'wall-new', $post_id));
            }
        }
    }
}
Example #30
0
 public static function run($argc, $argv)
 {
     logger('onepoll: start');
     if ($argc > 1 && intval($argv[1])) {
         $contact_id = intval($argv[1]);
     }
     if (!$contact_id) {
         logger('onepoll: no contact');
         return;
     }
     $d = datetime_convert();
     $contacts = q("SELECT abook.*, xchan.*, account.*\n\t\t\tFROM abook LEFT JOIN account on abook_account = account_id left join xchan on xchan_hash = abook_xchan \n\t\t\twhere abook_id = %d\n\t\t\tand abook_pending = 0 and abook_archived = 0 and abook_blocked = 0 and abook_ignored = 0\n\t\t\tAND (( account_flags = %d ) OR ( account_flags = %d )) limit 1", intval($contact_id), intval(ACCOUNT_OK), intval(ACCOUNT_UNVERIFIED));
     if (!$contacts) {
         logger('onepoll: abook_id not found: ' . $contact_id);
         return;
     }
     $contact = $contacts[0];
     $t = $contact['abook_updated'];
     $importer_uid = $contact['abook_channel'];
     $r = q("SELECT * from channel left join xchan on channel_hash = xchan_hash where channel_id = %d limit 1", intval($importer_uid));
     if (!$r) {
         return;
     }
     $importer = $r[0];
     logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['xchan_name']}, CONTACT: {$contact['xchan_name']}");
     $last_update = $contact['abook_updated'] === $contact['abook_created'] || $contact['abook_updated'] <= NULL_DATE ? datetime_convert('UTC', 'UTC', 'now - 7 days') : datetime_convert('UTC', 'UTC', $contact['abook_updated'] . ' - 2 days');
     if ($contact['xchan_network'] === 'rss') {
         logger('onepoll: processing feed ' . $contact['xchan_name'], LOGGER_DEBUG);
         handle_feed($importer['channel_id'], $contact_id, $contact['xchan_hash']);
         q("update abook set abook_connected = '%s' where abook_id = %d", dbesc(datetime_convert()), intval($contact['abook_id']));
         return;
     }
     if ($contact['xchan_network'] !== 'zot') {
         return;
     }
     // update permissions
     $x = zot_refresh($contact, $importer);
     $responded = false;
     $updated = datetime_convert();
     $connected = datetime_convert();
     if (!$x) {
         // mark for death by not updating abook_connected, this is caught in include/poller.php
         q("update abook set abook_updated = '%s' where abook_id = %d", dbesc($updated), intval($contact['abook_id']));
     } else {
         q("update abook set abook_updated = '%s', abook_connected = '%s' where abook_id = %d", dbesc($updated), dbesc($connected), intval($contact['abook_id']));
         $responded = true;
     }
     if (!$responded) {
         return;
     }
     if ($contact['xchan_connurl']) {
         $fetch_feed = true;
         $x = null;
         // They haven't given us permission to see their stream
         $can_view_stream = intval(get_abconfig($importer_uid, $contact['abook_xchan'], 'their_perms', 'view_stream'));
         if (!$can_view_stream) {
             $fetch_feed = false;
         }
         // we haven't given them permission to send us their stream
         $can_send_stream = intval(get_abconfig($importer_uid, $contact['abook_xchan'], 'my_perms', 'send_stream'));
         if (!$can_send_stream) {
             $fetch_feed = false;
         }
         if ($fetch_feed) {
             $feedurl = str_replace('/poco/', '/zotfeed/', $contact['xchan_connurl']);
             $feedurl .= '?f=&mindate=' . urlencode($last_update);
             $x = z_fetch_url($feedurl);
             logger('feed_update: ' . print_r($x, true), LOGGER_DATA);
         }
         if ($x && $x['success']) {
             $total = 0;
             logger('onepoll: feed update ' . $contact['xchan_name'] . ' ' . $feedurl);
             $j = json_decode($x['body'], true);
             if ($j['success'] && $j['messages']) {
                 foreach ($j['messages'] as $message) {
                     $results = process_delivery(array('hash' => $contact['xchan_hash']), get_item_elements($message), array(array('hash' => $importer['xchan_hash'])), false);
                     logger('onepoll: feed_update: process_delivery: ' . print_r($results, true), LOGGER_DATA);
                     $total++;
                 }
                 logger("onepoll: {$total} messages processed");
             }
         }
     }
     // update the poco details for this connection
     if ($contact['xchan_connurl']) {
         $r = q("SELECT xlink_id from xlink \n\t\t\t\twhere xlink_xchan = '%s' and xlink_updated > %s - INTERVAL %s and xlink_static = 0 limit 1", intval($contact['xchan_hash']), db_utcnow(), db_quoteinterval('1 DAY'));
         if (!$r) {
             poco_load($contact['xchan_hash'], $contact['xchan_connurl']);
         }
     }
     return;
 }