Beispiel #1
1
function directory_run(&$argv, &$argc)
{
    global $a, $db;
    if (is_null($a)) {
        $a = new App();
    }
    if (is_null($db)) {
        @(include ".htconfig.php");
        require_once "include/dba.php";
        $db = new dba($db_host, $db_user, $db_pass, $db_data);
        unset($db_host, $db_user, $db_pass, $db_data);
    }
    load_config('config');
    load_config('system');
    if ($argc != 2) {
        return;
    }
    load_config('system');
    load_hooks();
    $a->set_baseurl(get_config('system', 'url'));
    $dir = get_config('system', 'directory_submit_url');
    if (!strlen($dir)) {
        return;
    }
    $arr = array('url' => $argv[1]);
    call_hooks('globaldir_update', $arr);
    logger('Updating directory: ' . $arr['url'], LOGGER_DEBUG);
    if (strlen($arr['url'])) {
        fetch_url($dir . '?url=' . bin2hex($arr['url']));
    }
    return;
}
Beispiel #2
1
function directory_run($argv, $argc)
{
    global $a, $db;
    if (is_null($a)) {
        $a = new App();
    }
    if (is_null($db)) {
        @(include ".htconfig.php");
        require_once "dba.php";
        $db = new dba($db_host, $db_user, $db_pass, $db_data);
        unset($db_host, $db_user, $db_pass, $db_data);
    }
    load_config('config');
    load_config('system');
    if ($argc != 2) {
        return;
    }
    load_config('system');
    $a->set_baseurl(get_config('system', 'url'));
    $dir = get_config('system', 'directory_submit_url');
    if (!strlen($dir)) {
        return;
    }
    fetch_url($dir . '?url=' . bin2hex($argv[1]));
    return;
}
function privacy_image_cache_init()
{
    $urlhash = 'pic:' . sha1($_REQUEST['url']);
    $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' LIMIT 1", $urlhash);
    if (count($r)) {
        $img_str = $r[0]['data'];
        $mime = $r[0]["desc"];
        if ($mime == "") {
            $mime = "image/jpeg";
        }
    } else {
        require_once "Photo.php";
        $img_str = fetch_url($_REQUEST['url'], true);
        if (substr($img_str, 0, 6) == "GIF89a") {
            $mime = "image/gif";
            $image = @imagecreatefromstring($img_str);
            if ($image === FALSE) {
                die;
            }
            q("INSERT INTO `photo`\n\t\t\t( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `album`, `height`, `width`, `desc`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )\n\t\t\tVALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' )", 0, 0, get_guid(), dbesc($urlhash), dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc(basename(dbesc($_REQUEST["url"]))), dbesc(''), intval(imagesy($image)), intval(imagesx($image)), 'image/gif', dbesc($img_str), 100, intval(0), dbesc(''), dbesc(''), dbesc(''), dbesc(''));
        } else {
            $img = new Photo($img_str);
            if ($img->is_valid()) {
                $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
                $img_str = $img->imageString();
            }
            $mime = "image/jpeg";
        }
    }
    header("Content-type: {$mime}");
    header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600 * 24) . " GMT");
    header("Cache-Control: max-age=" . 3600 * 24);
    echo $img_str;
    killme();
}
function leistungsschutzrecht_fetchsites()
{
    require_once "include/network.php";
    $sites = array();
    $url = "http://www.vg-media.de/lizenzen/digitale-verlegerische-angebote/wahrnehmungsberechtigte-digitale-verlegerische-angebote.html";
    $site = fetch_url($url);
    $doc = new DOMDocument();
    @$doc->loadHTML($site);
    $xpath = new DomXPath($doc);
    $list = $xpath->query("//td/a");
    foreach ($list as $node) {
        $attr = array();
        if ($node->attributes->length) {
            foreach ($node->attributes as $attribute) {
                $attr[$attribute->name] = $attribute->value;
            }
        }
        if (isset($attr["href"])) {
            $urldata = parse_url($attr["href"]);
            if (isset($urldata["host"]) and !isset($urldata["path"])) {
                $cleanedurlpart = explode("%", $urldata["host"]);
                $hostname = explode(".", $cleanedurlpart[0]);
                $site = $hostname[sizeof($hostname) - 2] . "." . $hostname[sizeof($hostname) - 1];
                $sites[$site] = $site;
            }
        }
    }
    if (sizeof($sites)) {
        set_config('leistungsschutzrecht', 'sites', $sites);
    }
}
Beispiel #5
0
function oexchange_content(&$a)
{
    if (!local_user()) {
        $o = login(false);
        return $o;
    }
    if ($a->argc > 1 && $a->argv[1] === 'done') {
        info(t('Post successful.') . EOL);
        return;
    }
    $url = x($_GET, 'url') && strlen($_GET['url']) ? urlencode(notags(trim($_GET['url']))) : '';
    $title = x($_GET, 'title') && strlen($_GET['title']) ? '&title=' . urlencode(notags(trim($_GET['title']))) : '';
    $description = x($_GET, 'description') && strlen($_GET['description']) ? '&description=' . urlencode(notags(trim($_GET['description']))) : '';
    $tags = x($_GET, 'tags') && strlen($_GET['tags']) ? '&tags=' . urlencode(notags(trim($_GET['tags']))) : '';
    $s = fetch_url($a->get_baseurl() . '/parse_url?f=&url=' . $url . $title . $description . $tags);
    if (!strlen($s)) {
        return;
    }
    require_once 'include/html2bbcode.php';
    $post = array();
    $post['profile_uid'] = local_user();
    $post['return'] = '/oexchange/done';
    $post['body'] = html2bbcode($s);
    $post['type'] = 'wall';
    $_POST = $post;
    require_once 'mod/item.php';
    item_post($a);
}
Beispiel #6
0
function dirfind_content(&$a)
{
    $search = notags(trim($_REQUEST['search']));
    if (strpos($search, '@') === 0) {
        $search = substr($search, 1);
    }
    $o = '';
    $o .= '<h2>' . t('People Search') . ' - ' . $search . '</h2>';
    if ($search) {
        $p = $a->pager['page'] != 1 ? '&p=' . $a->pager['page'] : '';
        if (strlen(get_config('system', 'directory_submit_url'))) {
            $x = fetch_url('http://dir.friendica.com/lsearch?f=' . $p . '&search=' . urlencode($search));
        }
        //TODO fallback local search if global dir not available.
        //		else
        //			$x = post_url($a->get_baseurl() . '/lsearch', $params);
        $j = json_decode($x);
        if ($j->total) {
            $a->set_pager_total($j->total);
            $a->set_pager_itemspage($j->items_page);
        }
        if (count($j->results)) {
            $tpl = get_markup_template('match.tpl');
            foreach ($j->results as $jj) {
                $o .= replace_macros($tpl, array('$url' => zrl($jj->url), '$name' => $jj->name, '$photo' => $jj->photo, '$tags' => $jj->tags));
            }
        } else {
            info(t('No matches') . EOL);
        }
    }
    $o .= '<div class="clear"></div>';
    $o .= paginate($a);
    return $o;
}
function getWeather($loc, $units = 'metric', $lang = 'en', $appid = '', $cachetime = 0)
{
    $url = "http://api.openweathermap.org/data/2.5/weather?q=" . $loc . "&appid=" . $appid . "&lang=" . $lang . "&units=" . $units . "&mode=xml";
    $cached = Cache::get('curweather' . md5($url));
    $now = new DateTime();
    if (!is_null($cached)) {
        $cdate = get_pconfig(local_user(), 'curweather', 'last');
        $cached = unserialize($cached);
        if ($cdate + $cachetime > $now->getTimestamp()) {
            return $cached;
        }
    }
    try {
        $res = new SimpleXMLElement(fetch_url($url));
    } catch (Exception $e) {
        info(t('Error fetching weather data.\\nError was: ' . $e->getMessage()));
        return false;
    }
    if ((string) $res->temperature['unit'] === 'metric') {
        $tunit = '°C';
        $wunit = 'm/s';
    } else {
        $tunit = '°F';
        $wunit = 'mph';
    }
    if (trim((string) $res->weather['value']) == trim((string) $res->clouds['name'])) {
        $desc = (string) $res->clouds['name'];
    } else {
        $desc = (string) $res->weather['value'] . ', ' . (string) $res->clouds['name'];
    }
    $r = array('city' => (string) $res->city['name'][0], 'country' => (string) $res->city->country[0], 'lat' => (string) $res->city->coord['lat'], 'lon' => (string) $res->city->coord['lon'], 'temperature' => (string) $res->temperature['value'][0] . $tunit, 'pressure' => (string) $res->pressure['value'] . (string) $res->pressure['unit'], 'humidity' => (string) $res->humidity['value'] . (string) $res->humidity['unit'], 'descripion' => $desc, 'wind' => (string) $res->wind->speed['name'] . ' (' . (string) $res->wind->speed['value'] . $wunit . ')', 'update' => (string) $res->lastupdate['value'], 'icon' => (string) $res->weather['icon']);
    set_pconfig(local_user(), 'curweather', 'last', $now->getTimestamp());
    Cache::set('curweather' . md5($url), serialize($r), CACHE_HOUR);
    return $r;
}
Beispiel #8
0
function checkUpdate()
{
    $r = fetch_url(APIBASE . "json/repos/show/" . F9KREPO . "/tags");
    $tags = json_decode($r);
    $tag = 0.0;
    foreach ($tags->tags as $i => $v) {
        $i = (double) $i;
        if ($i > $tag) {
            $tag = $i;
        }
    }
    if ($tag == 0.0) {
        return false;
    }
    $f = fetch_url("https://raw.github.com/" . F9KREPO . "/" . $tag . "/boot.php", "r");
    preg_match("|'FRIENDICA_VERSION', *'([^']*)'|", $f, $m);
    $version = $m[1];
    $lv = explode(".", FRIENDICA_VERSION);
    $rv = explode(".", $version);
    foreach ($lv as $i => $v) {
        if ((int) $lv[$i] < (int) $rv[$i]) {
            return array($tag, $version, "https://github.com/friendica/friendica/zipball/" . $tag);
            break;
        }
    }
    return false;
}
Beispiel #9
0
function scale_diaspora_images($s, $include_link = true)
{
    $matches = null;
    $c = preg_match_all('/\\[img\\](.*?)\\[\\/img\\]/ism', $s, $matches, PREG_SET_ORDER);
    if ($c) {
        require_once 'include/Photo.php';
        foreach ($matches as $mtch) {
            logger('scale_diaspora_image: ' . $mtch[1]);
            $i = fetch_url($mtch[1]);
            if ($i) {
                $ph = new Photo($i);
                if ($ph->is_valid()) {
                    if ($ph->getWidth() > 600 || $ph->getHeight() > 600) {
                        $ph->scaleImage(600);
                        $new_width = $ph->getWidth();
                        $new_height = $ph->getHeight();
                        logger('scale_diaspora_image: ' . $new_width . 'w ' . $new_height . 'h' . 'match: ' . $mtch[0], LOGGER_DEBUG);
                        $s = str_replace($mtch[0], '[img=' . $new_width . 'x' . $new_height . ']' . $mtch[1] . '[/img]' . "\n" . ($include_link ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n" : ''), $s);
                        logger('scale_diaspora_image: new string: ' . $s, LOGGER_DEBUG);
                    }
                }
            }
        }
    }
    return $s;
}
function fortunate_fetch(&$a, &$b)
{
    $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/fortunate/fortunate.css' . '" media="all" />' . "\r\n";
    if (FORTUNATE_SERVER != 'hostname.com') {
        $s = fetch_url('http://' . FORTUNATE_SERVER . '/cookie.php?numlines=2&equal=1&rand=' . mt_rand());
        $b .= '<div class="fortunate">' . $s . '</div>';
    }
}
function getCryptsyTicker($marketid)
{
    $res = fetch_url("http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid={$marketid}");
    if (!$res) {
        return null;
    }
    $ticker = json_decode($res);
    return $ticker;
}
Beispiel #12
0
function dfrn_poll_init(&$a)
{
    $dfrn_id = '';
    if (x($_GET, 'dfrn_id')) {
        $dfrn_id = $a->config['dfrn_poll_dfrn_id'] = $_GET['dfrn_id'];
    }
    if (x($_GET, 'type')) {
        $type = $a->config['dfrn_poll_type'] = $_GET['type'];
    }
    if (x($_GET, 'last_update')) {
        $last_update = $a->config['dfrn_poll_last_update'] = $_GET['last_update'];
    }
    $dfrn_version = x($_GET, 'dfrn_version') ? $_GET['dfrn_version'] : '1.0';
    $destination_url = x($_GET, 'destination_url') ? $_GET['destination_url'] : '';
    if ($dfrn_id == '' && !x($_POST, 'dfrn_id') && $a->argc > 1) {
        $o = get_feed_for($a, '*', $a->argv[1], $last_update);
        echo $o;
        killme();
    }
    if (x($type) && $type == 'profile') {
        $r = q("SELECT `contact`.*, `user`.`nickname` \n\t\t\tFROM `contact` LEFT JOIN `user` ON `user`.`uid` = 1\n\t\t\tWHERE ( `dfrn-id` = '%s' OR ( `issued-id` = '%s' AND `duplex` = 1 )) LIMIT 1", dbesc($dfrn_id), dbesc($dfrn_id));
        if (count($r)) {
            $s = fetch_url($r[0]['poll'] . '?dfrn_id=' . $dfrn_id . '&type=profile-check');
            if (strlen($s)) {
                $xml = simplexml_load_string($s);
                if ((int) $xml->status == 1) {
                    $_SESSION['authenticated'] = 1;
                    $_SESSION['visitor_id'] = $r[0]['id'];
                    notice(t('Hi ') . $r[0]['name'] . EOL);
                    // Visitors get 1 day session.
                    $session_id = session_id();
                    $expire = time() + 86400;
                    q("UPDATE `session` SET `expire` = '%s' WHERE `sid` = '%s' LIMIT 1", dbesc($expire), dbesc($session_id));
                }
            }
            $profile = $r[0]['nickname'];
            goaway(strlen($destination_url) ? $destination_url : $a->get_baseurl() . '/profile/' . $profile);
        }
        goaway($a->get_baseurl());
    }
    if (x($type) && $type == 'profile-check') {
        q("DELETE FROM `profile_check` WHERE `expire` < " . intval(time()));
        $r = q("SELECT * FROM `profile_check` WHERE `dfrn_id` = '%s' ORDER BY `expire` DESC", dbesc($dfrn_id));
        if (count($r)) {
            xml_status(1);
            return;
            // NOTREACHED
        }
        xml_status(0);
        return;
        // NOTREACHED
    }
}
Beispiel #13
0
function get_salmon_key($uri, $keyhash)
{
    $ret = array();
    logger('Fetching salmon key for ' . $uri);
    $arr = lrdd($uri);
    if (is_array($arr)) {
        foreach ($arr as $a) {
            if ($a['@attributes']['rel'] === 'magic-public-key') {
                $ret[] = $a['@attributes']['href'];
            }
        }
    } else {
        return '';
    }
    // We have found at least one key URL
    // If it's inline, parse it - otherwise get the key
    if (count($ret)) {
        for ($x = 0; $x < count($ret); $x++) {
            if (substr($ret[$x], 0, 5) === 'data:') {
                if (strstr($ret[$x], ',')) {
                    $ret[$x] = substr($ret[$x], strpos($ret[$x], ',') + 1);
                } else {
                    $ret[$x] = substr($ret[$x], 5);
                }
            } else {
                $ret[$x] = fetch_url($ret[$x]);
            }
        }
    }
    logger('Key located: ' . print_r($ret, true));
    if (count($ret) == 1) {
        // We only found one one key so we don't care if the hash matches.
        // If it's the wrong key we'll find out soon enough because
        // message verification will fail. This also covers some older
        // software which don't supply a keyhash. As long as they only
        // have one key we'll be right.
        return $ret[0];
    } else {
        foreach ($ret as $a) {
            $hash = base64url_encode(hash('sha256', $a));
            if ($hash == $keyhash) {
                return $a;
            }
        }
    }
    return '';
}
Beispiel #14
0
function oembed_fetch_url($embedurl)
{
    $a = get_app();
    $txt = Cache::get($a->videowidth . $embedurl);
    // 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)) {
            // try oembed autodiscovery
            $redirects = 0;
            $html_text = fetch_url($embedurl, false, $redirects, 15, "text/*");
            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;
                        $txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
                        break;
                    }
                }
            }
        }
        if ($txt == false || $txt == "") {
            // try oohembed service
            $ourl = "http://oohembed.com/oohembed/?url=" . urlencode($embedurl) . '&maxwidth=' . $a->videowidth;
            $txt = fetch_url($ourl);
        }
        $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;
}
function geocoordinates_resolve_item(&$item)
{
    if (!$item["coord"] || $item["location"]) {
        return;
    }
    $key = get_config("geocoordinates", "api_key");
    if ($key == "") {
        return;
    }
    $language = get_config("geocoordinates", "language");
    if ($language == "") {
        $language = "de";
    }
    $coords = explode(' ', $item["coord"]);
    if (count($coords) < 2) {
        return;
    }
    $coords[0] = round($coords[0], 5);
    $coords[1] = round($coords[1], 5);
    $result = Cache::get("geocoordinates:" . $language . ":" . $coords[0] . "-" . $coords[1]);
    if (!is_null($result)) {
        $item["location"] = $result;
        return;
    }
    $s = fetch_url("https://api.opencagedata.com/geocode/v1/json?q=" . $coords[0] . "," . $coords[1] . "&key=" . $key . "&language=" . $language);
    if (!$s) {
        logger("API could not be queried", LOGGER_DEBUG);
        return;
    }
    $data = json_decode($s);
    if ($data->status->code != "200") {
        logger("API returned error " . $data->status->code . " " . $data->status->message, LOGGER_DEBUG);
        return;
    }
    if ($data->total_results == 0 or count($data->results) == 0) {
        logger("No results found for coordinates " . $item["coord"], LOGGER_DEBUG);
        return;
    }
    $item["location"] = $data->results[0]->formatted;
    logger("Got location for coordinates " . $coords[0] . "-" . $coords[1] . ": " . $item["location"], LOGGER_DEBUG);
    if ($item["location"] != "") {
        Cache::set("geocoordinates:" . $language . ":" . $coords[0] . "-" . $coords[1], $item["location"]);
    }
}
Beispiel #16
0
function parse_url_content(&$a)
{
    $url = trim($_GET['url']);
    $template = "<a href=\"%s\" >%s</a>%s";
    if ($url) {
        $s = fetch_url($url);
    } else {
        echo '';
        killme();
    }
    if (!$s) {
        echo sprintf($template, $url, $url, '');
        killme();
    }
    $dom = HTML5_Parser::parse($s);
    if (!$dom) {
        return $ret;
    }
    $items = $dom->getElementsByTagName('title');
    if ($items) {
        foreach ($items as $item) {
            $title = $item->textContent;
            break;
        }
    }
    $items = $dom->getElementsByTagName('p');
    if ($items) {
        foreach ($items as $item) {
            $text = $item->textContent;
            $text = strip_tags($text);
            if (strlen($text) < 100) {
                continue;
            }
            $text = substr($text, 0, 250) . '...';
            break;
        }
    }
    if (strlen($text)) {
        $text = '<br />' . $text;
    }
    echo sprintf($template, $url, $title, $text);
    killme();
}
Beispiel #17
0
function fetch_page($page_url)
{
    $html = fetch_url($page_url);
    // echo $html;
    if (!preg_match_all('%<img src="([^"]+.douban.com/view/group_topic/large/public/p\\d+.jpg)"%i', $html, $matches)) {
        echo "no image in this page\n";
        return false;
    }
    foreach ($matches[1] as $image_url) {
        $file_name = substr($image_url, strrpos($image_url, '/') + 1);
        $file_name = __DIR__ . '/images/' . $file_name;
        if (is_file($file_name)) {
            echo "skip {$file_name}\n";
            continue;
        }
        echo "save {$file_name} \n";
        image_save($file_name, $image_url);
    }
    return count($matches[1]);
}
Beispiel #18
0
function oembed_fetch_url($embedurl)
{
    $txt = Cache::get($embedurl);
    $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)) {
            // try oembed autodiscovery
            $redirects = 0;
            $html_text = fetch_url($embedurl, false, $redirects, 15, "text/*");
            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;
                        $txt = fetch_url($href);
                    }
                }
            }
        }
        if ($txt == false || $txt == "") {
            // try oohembed service
            $ourl = "http://oohembed.com/oohembed/?url=" . urlencode($embedurl);
            $txt = fetch_url($ourl);
        }
        $txt = trim($txt);
        if ($txt[0] != "{") {
            $txt = '{"type":"error"}';
        }
        //save in cache
        Cache::set($embedurl, $txt);
    }
    $j = json_decode($txt);
    $j->embedurl = $embedurl;
    return $j;
}
Beispiel #19
0
 /**
  * Fetches an update file and verifies its authenticity before returning
  * the file contents. Returns false on failure.
  */
 public static function fetch($path)
 {
     self::$error = false;
     $file_url = self::$updates . $path;
     $sha_url = self::$checksums . $path . '.sha';
     $file = fetch_url($file_url);
     if (!$file) {
         self::$error = 'Unable to fetch file.';
         return false;
     }
     $sha = fetch_url($sha_url);
     if (!$sha) {
         self::$error = 'Unable to fetch checksum file.';
         return false;
     }
     if (!self::test_checksum($file, $sha)) {
         self::$error = 'Checksum failed!';
         return false;
     }
     return $file;
 }
Beispiel #20
0
 function scrape_meta($url)
 {
     $ret = array();
     $s = fetch_url($url);
     if (!$s) {
         return $ret;
     }
     $dom = HTML5_Parser::parse($s);
     if (!$dom) {
         return $ret;
     }
     $items = $dom->getElementsByTagName('meta');
     // get DFRN link elements
     foreach ($items as $item) {
         $x = $item->getAttribute('name');
         if (substr($x, 0, 5) == "dfrn-") {
             $ret[$x] = $item->getAttribute('content');
         }
     }
     return $ret;
 }
Beispiel #21
0
function updatesites_content(&$a)
{
    $r = q("select * from site where url != '' order by name asc");
    if (count($r)) {
        foreach ($r as $rr) {
            $s = '';
            $s = fetch_url($rr['url'] . '/friendica/json');
            if ($s) {
                $j = json_decode($s);
            } else {
                continue;
            }
            if ($j) {
                $plugs = (array) $j->plugins;
                if (in_array('testdrive', $plugs)) {
                    $j->site_name = '!!! Test/Demo ONLY. !!! ' . $j->site_name;
                    $j->info = 'Accounts are temporary, expiration is enabled. ' . $j->info;
                }
                asort($plugs);
                q("UPDATE site set\n\t\t\t\t\tname = '%s',\n\t\t\t\t\turl = '%s', \n\t\t\t\t\tversion = '%s',\n\t\t\t\t\tplugins = '%s',\n\t\t\t\t\treg_policy = '%s',\n\t\t\t\t\tinfo = '%s',\n\t\t\t\t\tadmin_name = '%s',\n\t\t\t\t\tadmin_profile = '%s',\n\t\t\t\t\tupdated = '%s'\n\t\t\t\t\twhere id = %d limit 1", dbesc($j->site_name), dbesc($j->url), dbesc($j->version), dbesc(implode(',', $plugs)), dbesc($j->register_policy), dbesc($j->info ? $j->info : ''), dbesc($j->admin->name), dbesc($j->admin->profile), dbesc(datetime_convert()), intval($rr['id']));
            }
        }
    }
}
Beispiel #22
0
function diaspora_fetch_message($guid, $server, $level = 0)
{
    if ($level > 5) {
        return false;
    }
    $a = get_app();
    // This will not work if the server is not a Diaspora server
    $source_url = $server . '/p/' . $guid . '.xml';
    $x = fetch_url($source_url);
    if (!$x) {
        return false;
    }
    $x = str_replace(array('<activity_streams-photo>', '</activity_streams-photo>'), array('<asphoto>', '</asphoto>'), $x);
    $source_xml = parse_xml_string($x, false);
    $item = array();
    $item["app"] = 'Diaspora';
    $item["guid"] = $guid;
    $body = "";
    if ($source_xml->post->status_message->created_at) {
        $item["created"] = unxmlify($source_xml->post->status_message->created_at);
    }
    if ($source_xml->post->status_message->provider_display_name) {
        $item["app"] = unxmlify($source_xml->post->status_message->provider_display_name);
    }
    if ($source_xml->post->status_message->diaspora_handle) {
        $item["author"] = unxmlify($source_xml->post->status_message->diaspora_handle);
    }
    if ($source_xml->post->status_message->guid) {
        $item["guid"] = unxmlify($source_xml->post->status_message->guid);
    }
    $item["private"] = unxmlify($source_xml->post->status_message->public) == 'false';
    $item["object"] = json_encode($source_xml->post);
    if (strlen($source_xml->post->asphoto->objectId) && $source_xml->post->asphoto->objectId != 0 && $source_xml->post->asphoto->image_url) {
        $item["object-type"] = ACTIVITY_OBJ_PHOTO;
        $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
        $body = scale_external_images($body, false);
    } elseif ($source_xml->post->asphoto->image_url) {
        $item["object-type"] = ACTIVITY_OBJ_PHOTO;
        $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
        $body = scale_external_images($body);
    } elseif ($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 and $source_xml->post->status_message->photo->remote_photo_name) {
            $item["object-type"] = ACTIVITY_OBJ_PHOTO;
            $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('embedded picture link found: ' . $body, LOGGER_DEBUG);
        } else {
            $item["object-type"] = ACTIVITY_OBJ_NOTE;
        }
        $body = scale_external_images($body);
        // Add OEmbed and other information to the body
        // To-Do: It could be a repeated redmatrix item
        // Then we shouldn't add further data to it
        if ($item["object-type"] == ACTIVITY_OBJ_NOTE) {
            $body = add_page_info_to_body($body, false, true);
        }
    } elseif ($source_xml->post->reshare) {
        // Reshare of a reshare
        return diaspora_fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
    } else {
        // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
        logger('no content found: ' . print_r($source_xml, true));
        return false;
    }
    if (trim($body) == "") {
        return false;
    }
    $item["tag"] = '';
    $item["body"] = $body;
    return $item;
}
Beispiel #23
0
function dfrn_poll_content(&$a)
{
    $dfrn_id = x($_GET, 'dfrn_id') ? $_GET['dfrn_id'] : '';
    $type = x($_GET, 'type') ? $_GET['type'] : 'data';
    $last_update = x($_GET, 'last_update') ? $_GET['last_update'] : '';
    $destination_url = x($_GET, 'destination_url') ? $_GET['destination_url'] : '';
    $sec = x($_GET, 'sec') ? $_GET['sec'] : '';
    $dfrn_version = x($_GET, 'dfrn_version') ? (double) $_GET['dfrn_version'] : 2.0;
    $perm = x($_GET, 'perm') ? $_GET['perm'] : 'r';
    $direction = -1;
    if (strpos($dfrn_id, ':') == 1) {
        $direction = intval(substr($dfrn_id, 0, 1));
        $dfrn_id = substr($dfrn_id, 2);
    }
    if ($dfrn_id != '') {
        // initial communication from external contact
        $hash = random_string();
        $status = 0;
        $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
        if ($type !== 'profile') {
            $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` , `type`, `last_update` )\n\t\t\t\tVALUES( '%s', '%s', '%s', '%s', '%s' ) ", dbesc($hash), dbesc($dfrn_id), intval(time() + 60), dbesc($type), dbesc($last_update));
        }
        $sql_extra = '';
        switch ($direction) {
            case -1:
                if ($type === 'profile') {
                    $sql_extra = sprintf(" AND ( `dfrn-id` = '%s' OR `issued-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
                } else {
                    $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
                }
                $my_id = $dfrn_id;
                break;
            case 0:
                $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
                $my_id = '1:' . $dfrn_id;
                break;
            case 1:
                $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
                $my_id = '0:' . $dfrn_id;
                break;
            default:
                goaway(z_root());
                break;
                // NOTREACHED
        }
        $r = q("SELECT `contact`.*, `user`.`username`, `user`.`nickname` \n\t\t\tFROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`\n\t\t\tWHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 \n\t\t\tAND `user`.`nickname` = '%s' {$sql_extra} LIMIT 1", dbesc($a->argv[1]));
        if (count($r)) {
            $challenge = '';
            $encrypted_id = '';
            $id_str = $my_id . '.' . mt_rand(1000, 9999);
            if ($r[0]['duplex'] && strlen($r[0]['pubkey'])) {
                openssl_public_encrypt($hash, $challenge, $r[0]['pubkey']);
                openssl_public_encrypt($id_str, $encrypted_id, $r[0]['pubkey']);
            } else {
                openssl_private_encrypt($hash, $challenge, $r[0]['prvkey']);
                openssl_private_encrypt($id_str, $encrypted_id, $r[0]['prvkey']);
            }
            $challenge = bin2hex($challenge);
            $encrypted_id = bin2hex($encrypted_id);
        } else {
            $status = 1;
            $challenge = '';
            $encrypted_id = '';
        }
        if ($type === 'profile' && strlen($sec)) {
            // URL reply
            if ($dfrn_version < 2.2) {
                $s = fetch_url($r[0]['poll'] . '?dfrn_id=' . $encrypted_id . '&type=profile-check' . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&challenge=' . $challenge . '&sec=' . $sec);
            } else {
                $s = post_url($r[0]['poll'], array('dfrn_id' => $encrypted_id, 'type' => 'profile-check', 'dfrn_version' => DFRN_PROTOCOL_VERSION, 'challenge' => $challenge, 'sec' => $sec));
            }
            $profile = $r[0]['nickname'];
            switch ($destination_url) {
                case 'profile':
                    $dest = $a->get_baseurl() . '/profile/' . $profile . '?tab=profile';
                    break;
                case 'photos':
                    $dest = $a->get_baseurl() . '/photos/' . $profile;
                    break;
                case 'status':
                case '':
                    $dest = $a->get_baseurl() . '/profile/' . $profile;
                    break;
                default:
                    $dest = $destination_url;
                    break;
            }
            logger("dfrn_poll: sec profile: " . $s, LOGGER_DATA);
            if (strlen($s) && strstr($s, '<?xml')) {
                $xml = parse_xml_string($s);
                logger('dfrn_poll: profile: parsed xml: ' . print_r($xml, true), LOGGER_DATA);
                logger('dfrn_poll: secure profile: challenge: ' . $xml->challenge . ' expecting ' . $hash);
                logger('dfrn_poll: secure profile: sec: ' . $xml->sec . ' expecting ' . $sec);
                if ((int) $xml->status == 0 && $xml->challenge == $hash && $xml->sec == $sec) {
                    $_SESSION['authenticated'] = 1;
                    $_SESSION['visitor_id'] = $r[0]['id'];
                    $_SESSION['visitor_home'] = $r[0]['url'];
                    $_SESSION['visitor_visiting'] = $r[0]['uid'];
                    info(sprintf(t('%s welcomes %s'), $r[0]['username'], $r[0]['name']) . EOL);
                    // Visitors get 1 day session.
                    $session_id = session_id();
                    $expire = time() + 86400;
                    q("UPDATE `session` SET `expire` = '%s' WHERE `sid` = '%s' LIMIT 1", dbesc($expire), dbesc($session_id));
                }
                goaway($dest);
            }
            goaway($dest);
            // NOTREACHED
        } else {
            // XML reply
            header("Content-type: text/xml");
            echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<dfrn_poll>' . "\r\n" . "\t" . '<status>' . $status . '</status>' . "\r\n" . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n" . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n" . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n" . '</dfrn_poll>' . "\r\n";
            killme();
            // NOTREACHED
        }
    }
}
Beispiel #24
0
function poco_discover_federation()
{
    $last = get_config('poco', 'last_federation_discovery');
    if ($last) {
        $next = $last + 24 * 60 * 60;
        if ($next > time()) {
            return;
        }
    }
    $serverdata = fetch_url("http://the-federation.info/pods.json");
    if (!$serverdata) {
        return;
    }
    $servers = json_decode($serverdata);
    foreach ($servers->pods as $server) {
        poco_check_server("https://" . $server->host);
    }
    set_config('poco', 'last_federation_discovery', time());
}
Beispiel #25
0
function check_htaccess(&$checks)
{
    $a = get_app();
    $status = true;
    $help = "";
    if (function_exists('curl_init')) {
        $test = fetch_url($a->get_baseurl() . "/install/testrewrite");
        if ($test != "ok") {
            $status = false;
            $help = t('Url rewrite in .htaccess is not working. Check your server configuration.');
        }
        check_add($checks, t('Url rewrite is working'), $status, true, $help);
    } else {
        // cannot check modrewrite if libcurl is not installed
    }
}
Beispiel #26
0
function bb_CleanPictureLinksSub($match)
{
    $text = Cache::get($match[1]);
    if (is_null($text)) {
        $a = get_app();
        $stamp1 = microtime(true);
        $ch = @curl_init($match[1]);
        @curl_setopt($ch, CURLOPT_NOBODY, true);
        @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
        @curl_exec($ch);
        $curl_info = @curl_getinfo($ch);
        $a->save_timestamp($stamp1, "network");
        // if its a link to a picture then embed this picture
        if (substr($curl_info["content_type"], 0, 6) == "image/") {
            $text = "[img]" . $match[1] . "[/img]";
        } else {
            $text = "[img]" . $match[2] . "[/img]";
            // if its not a picture then look if its a page that contains a picture link
            require_once "include/network.php";
            $body = fetch_url($match[1]);
            $doc = new DOMDocument();
            @$doc->loadHTML($body);
            $xpath = new DomXPath($doc);
            $list = $xpath->query("//meta[@name]");
            foreach ($list as $node) {
                $attr = array();
                if ($node->attributes->length) {
                    foreach ($node->attributes as $attribute) {
                        $attr[$attribute->name] = $attribute->value;
                    }
                }
                if (strtolower($attr["name"]) == "twitter:image") {
                    $text = "[img]" . $attr["content"] . "[/img]";
                }
            }
        }
        Cache::set($match[1], $text);
    }
    return $text;
}
Beispiel #27
0
 function webfinger($s)
 {
     if (!strstr($s, '@')) {
         return $s;
     }
     $host = substr($s, strpos($s, '@') + 1);
     $url = 'http://' . $host . '/.well-known/host-meta';
     $xml = fetch_url($url);
     if (!$xml) {
         return '';
     }
     $h = simplexml_load_string($xml);
     $arr = convert_xml_element_to_array($h);
     if (!isset($arr['xrd']['link'])) {
         return '';
     }
     $link = $arr['xrd']['link'];
     if (!isset($link[0])) {
         $links = array($link);
     } else {
         $links = $link;
     }
     foreach ($links as $link) {
         if ($link['@attributes']['rel'] && $link['@attributes']['rel'] == 'lrdd') {
             $tpl = $link['@attributes']['template'];
         }
     }
     if (empty($tpl) || !strpos($tpl, '{uri}')) {
         return '';
     }
     $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
     $xml = fetch_url($pxrd);
     if (!$xml) {
         return '';
     }
     $h = simplexml_load_string($xml);
     $arr = convert_xml_element_to_array($h);
     if (!isset($arr['xrd']['link'])) {
         return '';
     }
     $link = $arr['xrd']['link'];
     if (!isset($link[0])) {
         $links = array($link);
     } else {
         $links = $link;
     }
     foreach ($links as $link) {
         if ($link['@attributes']['rel'] == NAMESPACE_DFRN) {
             return $link['@attributes']['href'];
         }
     }
     return '';
 }
Beispiel #28
0
             msg($do->errmsg);
         }
     } else {
         foreach ($do->fields as $v) {
             isset(${$v}) or ${$v} = '';
         }
         $content = '';
         $status = 3;
         $addtime = timetodate($DT_TIME);
         $totime = '';
         $username = $_username;
         $item = array();
         $menuid = 0;
         isset($url) or $url = '';
         if ($url) {
             $tmp = fetch_url($url);
             if ($tmp) {
                 extract($tmp);
             }
         }
         include tpl('edit', $module);
     }
     break;
 case 'edit':
     $itemid or msg();
     $do->itemid = $itemid;
     if ($submit) {
         if ($do->pass($post)) {
             if ($FD) {
                 fields_check($post_fields);
             }
Beispiel #29
0
/**
 * check_config
 * This checks the script configuration... Like upload limit, thumbs, etc. 
 */
function check_config()
{
    global $config, $install_errors;
    if (!defined('HTTP_HOST')) {
        $install_errors[] = 'Can\'t resolve <code>HTTP_HOST</code>. Please check at the bottom of <code>config.php</code>';
    }
    // Upload limit vs php.ini value -> http://php.net/manual/ini.php
    $ini_upload_bytes = return_bytes(trim(ini_get('upload_max_filesize')) . 'B');
    $max_size_bytes = return_bytes($config['max_filesize']);
    if (!is_numeric($max_size_bytes)) {
        $install_errors[] = 'Invalid numeric value in <code>$config[\'max_filesize\']</code>';
    } else {
        if ($ini_upload_bytes < $max_size_bytes) {
            $install_errors[] = 'Max. image size (' . $config['max_filesize'] . ') is greater than the value in <code>php.ini</code> (' . format_bytes($ini_upload_bytes) . ')';
        }
    }
    if (!is_int($config['thumb_width'])) {
        $install_errors[] = 'Invalid thumb size width in <code>$config[\'thumb_width\']</code>';
    }
    if (!is_int($config['thumb_height'])) {
        $install_errors[] = 'Invalid thumb size height in <code>$config[\'thumb_height\']</code>';
    }
    if (!is_int($config['min_resize_size']) || $config['min_resize_size'] < 0) {
        $install_errors[] = 'Invalid minimum resize size in <code>$config[\'min_resize_size\']</code>';
    }
    if (!is_int($config['max_resize_size']) || $config['max_resize_size'] < 0) {
        $install_errors[] = 'Invalid maximum resize size in <code>$config[\'max_resize_size\']</code>';
    }
    if (is_int($config['min_resize_size']) && is_int($config['max_resize_size']) && $config['min_resize_size'] > $config['max_resize_size']) {
        $install_errors[] = 'Minimum resize size can\'t be larger than maximum resize size. Please check <code>$config[\'min_resize_size\']</code> and <code>$config[\'max_resize_size\']</code>';
    }
    if (!conditional_config('multiupload')) {
        $config['multiupload_limit'] = 1;
    } else {
        if ($config['multiupload_limit'] <= 0 || $config['multiupload_limit'] == '') {
            $config['multiupload_limit'] = 0;
        }
    }
    if (!check_value(chevereto_config('file_naming')) || !in_array(chevereto_config('file_naming'), array('original', 'random', 'mixed'))) {
        $config['file_naming'] = 'original';
    }
    if (!is_numeric($config['multiupload_limit']) && !is_bool($config['multiupload_limit'])) {
        $install_errors[] = 'Invalid multiupload limit value in <code>$config[\'multiupload_limit\']</code>';
    }
    if ($config['multiupload_limit'] > 100) {
        $install_errors[] = 'Multiupload limit value can\'t be higher than 100 in <code>$config[\'multiupload_limit\']</code>';
    }
    if ($config['short_url_service'] == 'bitly') {
        $bitly_status = fetch_url('http://api.bit.ly/v3/validate?x_login='******'short_url_user'] . '&x_apiKey=' . $config['short_url_keypass'] . '&apiKey=' . $config['short_url_keypass'] . '&login='******'short_url_user'] . '&format=json');
        $bitly_json = json_decode($bitly_status);
        if ($bitly_json->data->valid !== 1) {
            $install_errors[] = 'The <a href="http://bit.ly/" target="_blank">bit.ly</a> user/api is invalid. bitly server says <code>' . $bitly_json->status_txt . '</code>. Please double check your data.';
        }
    }
    // Facebook comments
    if (use_facebook_comments() && !check_value($config['facebook_app_id'])) {
        $install_errors[] = 'You are are trying to use Facebook comments but <code>$config[\'facebook_app_id\']</code> is not setted.';
    }
    // Virtual folders
    foreach (array('virtual_folder_image', 'virtual_folder_uploaded') as $value) {
        if (!check_value($config[$value])) {
            $install_errors[] = '<code>$config[\'' . $value . '\']</code> is not setted.';
        }
    }
    // Passwords
    if ($config['user_password'] == $config['admin_password']) {
        $install_errors[] = 'Admin and user passwords must be different. Please check <code>$config[\'admin_password\']</code> and <code>$config[\'user_password\']</code>';
    }
    // Flood report email?
    if (check_value($config['flood_report_email']) && !check_email_address($config['flood_report_email'])) {
        $install_errors[] = 'It appears that <code>$config[\'flood_report_email\']</code> has a invalid email address';
    }
    // Watermark
    if (conditional_config('watermark_enable')) {
        define('__CHV_WATERMARK_FILE__', __CHV_ROOT_DIR__ . ltrim($config['watermark_image'], '/'));
        if (!is_int($config['watermark_margin'])) {
            $install_errors[] = 'Watermark margin must be integer in <code>$config[\'watermark_margin\']</code>';
        }
        if (!is_int($config['watermark_opacity'])) {
            $install_errors[] = 'Watermark opacity must be integer in <code>$config[\'watermark_opacity\']</code>';
        }
        if ($config['watermark_opacity'] > 100 or $config['watermark_opacity'] < 0) {
            $install_errors[] = 'Watermark opacity value out of limis (' . $config['watermark_opacity'] . '). <code>$config[\'watermark_opacity\']</code> must be in the range 0 to 100';
        }
        // Watermark position
        if (!check_value($config['watermark_position'])) {
            $config['watermark_position'] = 'center center';
        }
        $watermark_position = explode(' ', strtolower($config['watermark_position']));
        if (!isset($watermark_position[1])) {
            $watermark_position[1] = 'center';
        }
        if (preg_match('/^left|center|right$/', $watermark_position[0])) {
            $config['watermark_x_position'] = $watermark_position[0];
        } else {
            $install_errors[] = 'Invalid watermark horizontal position in <code>$config[\'watermark_position\']</code>';
        }
        if (preg_match('/^top|center|bottom$/', $watermark_position[1])) {
            $config['watermark_y_position'] = $watermark_position[1];
        } else {
            $install_errors[] = 'Invalid watermark vertical position in <code>$config[\'watermark_position\']</code>';
        }
        if (!file_exists(__CHV_WATERMARK_FILE__)) {
            $install_errors[] = 'Watermark image file doesn\'t exists. Please check the path in <code>$config[\'watermark_image\']</code>';
        } else {
            $watermark_image_info = get_info(__CHV_WATERMARK_FILE__);
            if ($watermark_image_info['mime'] !== 'image/png') {
                $install_errors[] = 'Watermark image file must be a PNG image in <code>$config[\'watermark_image\']</code>';
            }
        }
    }
    // Flood limits
    $flood_limits = array('minute', 'hour', 'day', 'week', 'month');
    $flood_value_error = false;
    foreach ($flood_limits as $value) {
        if (!check_value($config['max_uploads_per_' . $value]) || !is_numeric($config['max_uploads_per_' . $value])) {
            $install_errors[] = 'Invalid config value in <code>$config[\'' . $value . '\']</code>';
            $flood_value_error = true;
        }
    }
    if ($flood_value_error == false) {
        $flood_lower_than = array('minute' => array('hour', 'day', 'week', 'month'), 'hour' => array('day', 'week', 'month'), 'day' => array('week', 'month'), 'week' => array('month'));
        foreach ($flood_lower_than as $period => $lower_than) {
            foreach ($lower_than as $value) {
                if ($config['max_uploads_per_' . $period] >= $config['max_uploads_per_' . $value]) {
                    $install_errors[] = '<code>max_uploads_per_' . $period . '</code> must be lower than <code>max_uploads_per_' . $value . '</code>';
                }
            }
        }
    }
    // dB settings
    foreach (array('db_host', 'db_name', 'db_user') as $value) {
        if (!check_value($config[$value])) {
            $install_errors[] = '<code>$config[\'' . $value . '\']</code>';
        }
    }
    if (count($install_errors) == 0) {
        require_once __CHV_PATH_CLASSES__ . 'class.db.php';
        $dB = new dB();
        if ($dB->dead) {
            chevereto_die('<code>' . $dB->error . '</code>', 'Database error', array('The system has encountered a error when it try to connect to the database server.', 'Please note this error and if you need help go to <a href="http://chevereto.com/support/">Chevereto support</a>.'));
        } else {
            // Check maintenance mode
            if ($dB->get_option('maintenance') && !defined('SKIP_MAINTENANCE')) {
                $config['maintenance'] = true;
            }
        }
    }
    return count($install_errors) == 0 ? true : false;
}
Beispiel #30
0
function api_get_nick($profile)
{
    /* To-Do:
     - remove trailing jung from profile url
     - pump.io check has to check the website
    */
    $nick = "";
    $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "\$2", $profile);
    if ($friendica != $profile) {
        $nick = $friendica;
    }
    if (!$nick == "") {
        $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "\$2", $profile);
        if ($diaspora != $profile) {
            $nick = $diaspora;
        }
    }
    if (!$nick == "") {
        $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "\$1", $profile);
        if ($twitter != $profile) {
            $nick = $twitter;
        }
    }
    if (!$nick == "") {
        $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "\$1", $profile);
        if ($StatusnetHost != $profile) {
            $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "\$2", $profile);
            if ($StatusnetUser != $profile) {
                $UserData = fetch_url("http://" . $StatusnetHost . "/api/users/show.json?user_id=" . $StatusnetUser);
                $user = json_decode($UserData);
                if ($user) {
                    $nick = $user->screen_name;
                }
            }
        }
    }
    // To-Do: look at the page if its really a pumpio site
    //if (!$nick == "") {
    //	$pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
    //	if ($pumpio != $profile)
    //		$nick = $pumpio;
    //      <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
    //}
    if ($nick != "") {
        q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'", dbesc($nick), dbesc(normalise_link($profile)));
        return $nick;
    }
    return false;
}