Example #1
0
/**
 * @param App $a
 */
function fbrowser_content($a)
{
    if (!local_user()) {
        killme();
    }
    if ($a->argc == 1) {
        killme();
    }
    //echo "<pre>"; var_dump($a->argv); killme();
    switch ($a->argv[1]) {
        case "image":
            $path = array(array($a->get_baseurl() . "/fbrowser/image/", t("Photos")));
            $albums = false;
            $sql_extra = "";
            $sql_extra2 = " ORDER BY created DESC LIMIT 0, 10";
            if ($a->argc == 2) {
                $albums = q("SELECT distinct(`album`) AS `album` FROM `photo` WHERE `uid` = %d ", intval(local_user()));
                // anon functions only from 5.3.0... meglio tardi che mai..
                function folder1($el)
                {
                    return array(bin2hex($el['album']), $el['album']);
                }
                $albums = array_map("folder1", $albums);
            }
            $album = "";
            if ($a->argc == 3) {
                $album = hex2bin($a->argv[2]);
                $sql_extra = sprintf("AND `album` = '%s' ", dbesc($album));
                $sql_extra2 = "";
                $path[] = array($a->get_baseurl() . "/fbrowser/image/" . $a->argv[2] . "/", $album);
            }
            $r = q("SELECT `resource-id`, `id`, `filename`, min(`scale`) AS `hiq`,max(`scale`) AS `loq`, `desc`  \n\t\t\t\t\tFROM `photo` WHERE `uid` = %d {$sql_extra}\n\t\t\t\t\tGROUP BY `resource-id` {$sql_extra2}", intval(local_user()));
            function files1($rr)
            {
                global $a;
                return array($a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . $rr['hiq'] . '.jpg', template_escape($rr['filename']), $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . $rr['loq'] . '.jpg');
            }
            $files = array_map("files1", $r);
            $tpl = get_markup_template("filebrowser.tpl");
            echo replace_macros($tpl, array('$type' => 'image', '$baseurl' => $a->get_baseurl(), '$path' => $path, '$folders' => $albums, '$files' => $files));
            break;
        case "file":
            if ($a->argc == 2) {
                $files = q("SELECT id, filename, filetype FROM `attach` WHERE `uid` = %d ", intval(local_user()));
                function files2($rr)
                {
                    global $a;
                    list($m1, $m2) = explode("/", $rr['filetype']);
                    $filetype = file_exists("images/icons/{$m1}.png") ? $m1 : "zip";
                    return array($a->get_baseurl() . '/attach/' . $rr['id'], template_escape($rr['filename']), $a->get_baseurl() . '/images/icons/16/' . $filetype . '.png');
                }
                $files = array_map("files2", $files);
                //echo "<pre>"; var_dump($files); killme();
                $tpl = get_markup_template("filebrowser.tpl");
                echo replace_macros($tpl, array('$type' => 'file', '$baseurl' => $a->get_baseurl(), '$path' => array(array($a->get_baseurl() . "/fbrowser/image/", t("Files"))), '$folders' => false, '$files' => $files));
            }
            break;
    }
    killme();
}
Example #2
0
/**
 * @brief Returns the baseurl.
 *
 * @see App::get_baseurl()
 *
 * @return string
 */
function z_root()
{
    return App::get_baseurl();
}
Example #3
0
/**
 * @brief Logs admin page.
 *
 * @param App $a
 * @return string
 */
function admin_page_logs(&$a)
{
    $log_choices = array(LOGGER_NORMAL => 'Normal', LOGGER_TRACE => 'Trace', LOGGER_DEBUG => 'Debug', LOGGER_DATA => 'Data', LOGGER_ALL => 'All');
    $t = get_markup_template('admin_logs.tpl');
    $f = get_config('system', 'logfile');
    $data = '';
    if (!file_exists($f)) {
        $data = t("Error trying to open <strong>{$f}</strong> log file.\r\n<br/>Check to see if file {$f} exist and is \nreadable.");
    } else {
        $fp = fopen($f, 'r');
        if (!$fp) {
            $data = t("Couldn't open <strong>{$f}</strong> log file.\r\n<br/>Check to see if file {$f} is readable.");
        } else {
            $fstat = fstat($fp);
            $size = $fstat['size'];
            if ($size != 0) {
                if ($size > 5000000 || $size < 0) {
                    $size = 5000000;
                }
                $seek = fseek($fp, 0 - $size, SEEK_END);
                if ($seek === 0) {
                    $data = escape_tags(fread($fp, $size));
                    while (!feof($fp)) {
                        $data .= escape_tags(fread($fp, 4096));
                    }
                }
            }
            fclose($fp);
        }
    }
    return replace_macros($t, array('$title' => t('Administration'), '$page' => t('Logs'), '$submit' => t('Submit'), '$clear' => t('Clear'), '$data' => $data, '$baseurl' => $a->get_baseurl(true), '$logname' => get_config('system', 'logfile'), '$debugging' => array('debugging', t("Debugging"), get_config('system', 'debugging'), ""), '$logfile' => array('logfile', t("Log file"), get_config('system', 'logfile'), t("Must be writable by web server. Relative to your Red top-level directory.")), '$loglevel' => array('loglevel', t("Log level"), get_config('system', 'loglevel'), "", $log_choices), '$form_security_token' => get_form_security_token('admin_logs')));
}
Example #4
0
/**
 * @param App $a
 * @param object $b
 * @return mixed
 */
function fbpost_post_hook(&$a, &$b)
{
    logger('fbpost_post_hook: Facebook post invoked', LOGGER_DEBUG);
    if ($b['deleted'] || $b['created'] !== $b['edited']) {
        return;
    }
    logger('fbpost_post_hook: Facebook post first check successful', LOGGER_DEBUG);
    // if post comes from facebook don't send it back
    if ($b['extid'] == NETWORK_FACEBOOK) {
        return;
    }
    if ($b['app'] == "Facebook" and $b['verb'] != ACTIVITY_LIKE) {
        return;
    }
    logger('fbpost_post_hook: Facebook post accepted', LOGGER_DEBUG);
    /**
     * Post to Facebook stream
     */
    require_once 'include/group.php';
    require_once 'include/html2plain.php';
    $reply = false;
    $likes = false;
    $deny_arr = array();
    $allow_arr = array();
    $toplevel = $b['id'] == $b['parent'] ? true : false;
    $linking = get_pconfig($b['uid'], 'facebook', 'no_linking') ? 0 : 1;
    if (!$toplevel && $linking) {
        $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($b['parent']), intval($b['uid']));
        //$r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
        //	dbesc($b['parent-uri']),
        //	intval($b['uid'])
        //);
        // is it a reply to a facebook post?
        // A reply to a toplevel post is only allowed for "real" facebook posts
        if (count($r) && substr($r[0]['uri'], 0, 4) === 'fb::') {
            $reply = substr($r[0]['uri'], 4);
        } elseif (count($r) && substr($r[0]['extid'], 0, 4) === 'fb::' and $r[0]['id'] != $r[0]['parent']) {
            $reply = substr($r[0]['extid'], 4);
        } else {
            return;
        }
        $u = q("SELECT * FROM user where uid = %d limit 1", intval($b['uid']));
        if (!count($u)) {
            return;
        }
        // only accept comments from the item owner. Other contacts are unknown to FB.
        if (!link_compare($b['author-link'], $a->get_baseurl() . '/profile/' . $u[0]['nickname'])) {
            return;
        }
        logger('fbpost_post_hook: facebook reply id=' . $reply);
    }
    if (strstr($b['postopts'], 'facebook') || $b['private'] || $reply) {
        if ($b['private'] && $reply === false) {
            $allow_people = expand_acl($b['allow_cid']);
            $allow_groups = expand_groups(expand_acl($b['allow_gid']));
            $deny_people = expand_acl($b['deny_cid']);
            $deny_groups = expand_groups(expand_acl($b['deny_gid']));
            $recipients = array_unique(array_merge($allow_people, $allow_groups));
            $deny = array_unique(array_merge($deny_people, $deny_groups));
            $allow_str = dbesc(implode(', ', $recipients));
            if ($allow_str) {
                logger("fbpost_post_hook: private post to: " . $allow_str, LOGGER_DEBUG);
                $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( {$allow_str} ) AND `network` = 'face'");
                if (count($r)) {
                    foreach ($r as $rr) {
                        $allow_arr[] = $rr['notify'];
                    }
                }
            }
            $deny_str = dbesc(implode(', ', $deny));
            if ($deny_str) {
                $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( {$deny_str} ) AND `network` = 'face'");
                if (count($r)) {
                    foreach ($r as $rr) {
                        $deny_arr[] = $rr['notify'];
                    }
                }
            }
            if (count($deny_arr) && !count($allow_arr)) {
                // One or more FB folks were denied access but nobody on FB was specifically allowed access.
                // This might cause the post to be open to public on Facebook, but only to selected members
                // on another network. Since this could potentially leak a post to somebody who was denied,
                // we will skip posting it to Facebook with a slightly vague but relevant message that will
                // hopefully lead somebody to this code comment for a better explanation of what went wrong.
                notice(t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL);
                return;
            }
            // if it's a private message but no Facebook members are allowed or denied, skip Facebook post
            if (!count($allow_arr) && !count($deny_arr)) {
                return;
            }
        }
        if ($b['verb'] == ACTIVITY_LIKE) {
            $likes = true;
            logger('fbpost_post_hook: liking ' . print_r($b, true), LOGGER_DEBUG);
        }
        $appid = get_config('facebook', 'appid');
        $secret = get_config('facebook', 'appsecret');
        if ($appid && $secret) {
            logger('fbpost_post_hook: have appid+secret');
            $fb_token = get_pconfig($b['uid'], 'facebook', 'access_token');
            // post to facebook if it's a public post and we've ticked the 'post to Facebook' box,
            // or it's a private message with facebook participants
            // or it's a reply or likes action to an existing facebook post
            if ($fb_token && ($toplevel || $b['private'] || $reply)) {
                logger('fbpost_post_hook: able to post');
                require_once 'library/facebook.php';
                require_once 'include/bbcode.php';
                $msg = $b['body'];
                logger('fbpost_post_hook: original msg=' . $msg, LOGGER_DATA);
                if ($toplevel) {
                    require_once "include/plaintext.php";
                    $msgarr = plaintext($a, $b, 0, false, 9);
                    $msg = $msgarr["text"];
                    $link = $msgarr["url"];
                    $linkname = $msgarr["title"];
                    if ($msgarr["type"] != "video") {
                        $image = $msgarr["image"];
                    }
                    // Fallback - if message is empty
                    if (!strlen($msg)) {
                        $msg = $linkname;
                    }
                    if (!strlen($msg)) {
                        $msg = $link;
                    }
                    if (!strlen($msg)) {
                        $msg = $image;
                    }
                } else {
                    require_once "include/bbcode.php";
                    require_once "include/html2plain.php";
                    $msg = bb_CleanPictureLinks($msg);
                    $msg = bbcode($msg, false, false, 2, true);
                    $msg = trim(html2plain($msg, 0));
                    $link = "";
                    $image = "";
                    $linkname = "";
                }
                // If there is nothing to post then exit
                if (!strlen($msg)) {
                    return;
                }
                logger('fbpost_post_hook: msg=' . $msg, LOGGER_DATA);
                $video = "";
                if ($likes) {
                    $postvars = array('access_token' => $fb_token);
                } else {
                    // message, picture, link, name, caption, description, source, place, tags
                    //if(trim($link) != "")
                    //	if (@exif_imagetype($link) != 0) {
                    //		$image = $link;
                    //		$link = "";
                    //	}
                    $postvars = array('access_token' => $fb_token, 'message' => $msg);
                    if (trim($image) != "") {
                        $postvars['picture'] = $image;
                    }
                    if (trim($link) != "") {
                        $postvars['link'] = $link;
                        if (stristr($link, 'youtube') || stristr($link, 'youtu.be') || stristr($link, 'vimeo')) {
                            $video = $link;
                        }
                    }
                    if (trim($linkname) != "") {
                        $postvars['name'] = $linkname;
                    }
                }
                if ($b['private'] && $toplevel) {
                    $postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"';
                    if (count($allow_arr)) {
                        $postvars['privacy'] .= ',"allow": "' . implode(',', $allow_arr) . '"';
                    }
                    if (count($deny_arr)) {
                        $postvars['privacy'] .= ',"deny": "' . implode(',', $deny_arr) . '"';
                    }
                    $postvars['privacy'] .= '}';
                }
                $post_to_page = get_pconfig($b['uid'], 'facebook', 'post_to_page');
                $page_access_token = get_pconfig($b['uid'], 'facebook', 'page_access_token');
                if (intval($post_to_page) != 0 and $page_access_token != "") {
                    $target = $post_to_page;
                } else {
                    $target = "me";
                }
                if ($reply) {
                    $url = 'https://graph.facebook.com/' . $reply . '/' . ($likes ? 'likes' : 'comments');
                } else {
                    if ($video != "" or $image == "" and $link != "") {
                        // If it is a link to a video or a link without a preview picture then post it as a link
                        if ($video != "") {
                            $link = $video;
                        }
                        $postvars = array('access_token' => $fb_token, 'link' => $link);
                        if ($msg != $video) {
                            $postvars['message'] = $msg;
                        }
                        $url = 'https://graph.facebook.com/' . $target . '/links';
                    } else {
                        if ($link == "" and $image != "") {
                            // If it is only an image without a page link then post this image as a photo
                            $postvars = array('access_token' => $fb_token, 'url' => $image);
                            if ($msg != $image) {
                                $postvars['message'] = $msg;
                            }
                            $url = 'https://graph.facebook.com/' . $target . '/photos';
                            //} else if (($link != "") or ($image != "") or ($b['title'] == '') or (strlen($msg) < 500)) {
                        } else {
                            $url = 'https://graph.facebook.com/' . $target . '/feed';
                            if (!get_pconfig($b['uid'], 'facebook', 'suppress_view_on_friendica') and $b['plink']) {
                                $postvars['actions'] = '{"name": "' . t('View on Friendica') . '", "link": "' . $b['plink'] . '"}';
                            }
                        }
                    }
                }
                /*				} else {
                					// if its only a message and a subject and the message is larger than 500 characters then post it as note
                					$postvars = array(
                						'access_token' => $fb_token,
                						'message' => bbcode($b['body'], false, false),
                						'subject' => $b['title'],
                					);
                					$url = 'https://graph.facebook.com/'.$target.'/notes';
                				} */
                // Post to page?
                if (!$reply and $target != "me" and $page_access_token) {
                    $postvars['access_token'] = $page_access_token;
                }
                logger('fbpost_post_hook: post to ' . $url);
                logger('fbpost_post_hook: postvars: ' . print_r($postvars, true));
                // "test_mode" prevents anything from actually being posted.
                // Otherwise, let's do it.
                if (!get_config('facebook', 'test_mode')) {
                    $x = post_url($url, $postvars);
                    logger('fbpost_post_hook: post returns: ' . $x, LOGGER_DEBUG);
                    $retj = json_decode($x);
                    if ($retj->id) {
                        // Only set the extid when it isn't the toplevel post
                        q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d AND `parent` != %d", dbesc('fb::' . $retj->id), intval($b['id']), intval($b['id']));
                    } else {
                        // Sometimes posts are accepted from facebook although it telling an error
                        // This leads to endless comment flooding.
                        // If it is a special kind of failure the post was receiced
                        // Although facebook said it wasn't received ...
                        if (!$likes and ($retj->error->type != "OAuthException" or $retj->error->code != 2) and $x != "") {
                            $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($b['uid']));
                            if (count($r)) {
                                $a->contact = $r[0]["id"];
                            }
                            $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars));
                            require_once 'include/queue_fn.php';
                            add_to_queue($a->contact, NETWORK_FACEBOOK, $s);
                            logger('fbpost_post_hook: Post failed, requeued.', LOGGER_DEBUG);
                            notice(t('Facebook post failed. Queued for retry.') . EOL);
                        }
                        if (isset($retj->error) && $retj->error->type == "OAuthException" && $retj->error->code == 190) {
                            logger('fbpost_post_hook: Facebook session has expired due to changed password.', LOGGER_DEBUG);
                            $last_notification = get_pconfig($b['uid'], 'facebook', 'session_expired_mailsent');
                            if (!$last_notification || $last_notification < time() - FACEBOOK_SESSION_ERR_NOTIFICATION_INTERVAL) {
                                require_once 'include/enotify.php';
                                $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid']));
                                notification(array('uid' => $b['uid'], 'type' => NOTIFY_SYSTEM, 'system_type' => 'facebook_connection_invalid', 'language' => $r[0]['language'], 'to_name' => $r[0]['username'], 'to_email' => $r[0]['email'], 'source_name' => t('Administrator'), 'source_link' => $a->config["system"]["url"], 'source_photo' => $a->config["system"]["url"] . '/images/person-80.jpg'));
                                set_pconfig($b['uid'], 'facebook', 'session_expired_mailsent', time());
                            } else {
                                logger('fbpost_post_hook: No notification, as the last one was sent on ' . $last_notification, LOGGER_DEBUG);
                            }
                        }
                    }
                }
            }
        }
    }
}
Example #5
0
/**
 * @brief Returns the baseurl.
 *
 * @see App::get_baseurl()
 *
 * @return string
 */
function z_root()
{
    global $a;
    return App::get_baseurl();
}
Example #6
0
/**
 * @brief
 *
 * @param App $a
 * @param boolean $is_owner default false
 * @param string $nickname default null
 * @return void|string
 */
function profile_tabs($a, $is_owner = false, $nickname = null)
{
    // Don't provide any profile tabs if we're running as the sys channel
    if ($a->is_sys) {
        return;
    }
    $channel = $a->get_channel();
    if (is_null($nickname)) {
        $nickname = $channel['channel_address'];
    }
    $uid = $a->profile['profile_uid'] ? $a->profile['profile_uid'] : local_channel();
    if (get_pconfig($uid, 'system', 'noprofiletabs')) {
        return;
    }
    if (x($_GET, 'tab')) {
        $tab = notags(trim($_GET['tab']));
    }
    $url = $a->get_baseurl() . '/channel/' . $nickname;
    $pr = $a->get_baseurl() . '/profile/' . $nickname;
    $tabs = array(array('label' => t('Channel'), 'url' => $url, 'sel' => argv(0) == 'channel' ? 'active' : '', 'title' => t('Status Messages and Posts'), 'id' => 'status-tab'));
    $p = get_all_perms($uid, get_observer_hash());
    if ($p['view_profile']) {
        $tabs[] = array('label' => t('About'), 'url' => $pr, 'sel' => argv(0) == 'profile' ? 'active' : '', 'title' => t('Profile Details'), 'id' => 'profile-tab');
    }
    if ($p['view_photos']) {
        $tabs[] = array('label' => t('Photos'), 'url' => $a->get_baseurl() . '/photos/' . $nickname, 'sel' => argv(0) == 'photos' ? 'active' : '', 'title' => t('Photo Albums'), 'id' => 'photo-tab');
    }
    if ($p['view_storage']) {
        $tabs[] = array('label' => t('Files'), 'url' => $a->get_baseurl() . '/cloud/' . $nickname . (get_observer_hash() ? '' : '?f=&davguest=1'), 'sel' => argv(0) == 'cloud' || argv(0) == 'sharedwithme' ? 'active' : '', 'title' => t('Files and Storage'), 'id' => 'files-tab');
    }
    if ($p['chat']) {
        require_once 'include/chat.php';
        $has_chats = chatroom_list_count($uid);
        if ($has_chats) {
            $tabs[] = array('label' => t('Chatrooms'), 'url' => $a->get_baseurl() . '/chat/' . $nickname, 'sel' => argv(0) == 'chat' ? 'active' : '', 'title' => t('Chatrooms'), 'id' => 'chat-tab');
        }
    }
    require_once 'include/menu.php';
    $has_bookmarks = menu_list_count(local_channel(), '', MENU_BOOKMARK) + menu_list_count(local_channel(), '', MENU_SYSTEM | MENU_BOOKMARK);
    if ($is_owner && $has_bookmarks) {
        $tabs[] = array('label' => t('Bookmarks'), 'url' => $a->get_baseurl() . '/bookmarks', 'sel' => argv(0) == 'bookmarks' ? 'active' : '', 'title' => t('Saved Bookmarks'), 'id' => 'bookmarks-tab');
    }
    if ($is_owner && feature_enabled($uid, 'webpages')) {
        $tabs[] = array('label' => t('Webpages'), 'url' => $a->get_baseurl() . '/webpages/' . $nickname, 'sel' => argv(0) == 'webpages' ? 'active' : '', 'title' => t('Manage Webpages'), 'id' => 'webpages-tab');
    } else {
        /**
         * @FIXME we probably need a listing of events that were created by 
         * this channel and are visible to the observer
         */
    }
    $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $tab ? $tab : false, 'tabs' => $tabs);
    call_hooks('profile_tabs', $arr);
    $tpl = get_markup_template('common_tabs.tpl');
    return replace_macros($tpl, array('$tabs' => $arr['tabs']));
}
Example #7
0
/**
 * @brief This function removes the tag $tag from the text $body and replaces it
 * with the appropiate link.
 *
 * @param App $a
 * @param[in,out] string &$body the text to replace the tag in
 * @param[in,out] string &$access_tag used to return tag ACL exclusions e.g. @!foo
 * @param[in,out] string &$str_tags string to add the tag to
 * @param int $profile_uid
 * @param string $tag the tag to replace
 * @param boolean $diaspora default false
 * @return boolean true if replaced, false if not replaced
 */
function handle_tag($a, &$body, &$access_tag, &$str_tags, $profile_uid, $tag, $diaspora = false)
{
    $replaced = false;
    $r = null;
    $match = array();
    $termtype = strpos($tag, '#') === 0 ? TERM_HASHTAG : TERM_UNKNOWN;
    $termtype = strpos($tag, '@') === 0 ? TERM_MENTION : $termtype;
    $termtype = strpos($tag, '#^[') === 0 ? TERM_BOOKMARK : $termtype;
    //is it a hash tag?
    if (strpos($tag, '#') === 0) {
        if (strpos($tag, '#^[') === 0) {
            if (preg_match('/#\\^\\[(url|zrl)(.*?)\\](.*?)\\[\\/(url|zrl)\\]/', $tag, $match)) {
                $basetag = $match[3];
                $url = substr($match[2], 0, 1) === '=' ? substr($match[2], 1) : $match[3];
                $replaced = true;
            }
        } elseif (strpos($tag, '[zrl=') || strpos($tag, '[url=')) {
            //...do nothing
            return $replaced;
        }
        if ($tag == '#getzot') {
            $basetag = 'getzot';
            $url = 'http://hubzilla.org';
            $newtag = '#[zrl=' . $url . ']' . $basetag . '[/zrl]';
            $body = str_replace($tag, $newtag, $body);
            $replaced = true;
        }
        if (!$replaced) {
            //base tag has the tags name only
            if (substr($tag, 0, 7) === '#&quot;' && substr($tag, -6, 6) === '&quot;') {
                $basetag = substr($tag, 7);
                $basetag = substr($basetag, 0, -6);
            } else {
                $basetag = str_replace('_', ' ', substr($tag, 1));
            }
            //create text for link
            $url = $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag);
            $newtag = '#[zrl=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/zrl]';
            //replace tag by the link. Make sure to not replace something in the middle of a word
            // The '=' is needed to not replace color codes if the code is also used as a tag
            // Much better would be to somehow completely avoiding things in e.g. [color]-tags.
            // This would allow writing things like "my favourite tag=#foobar".
            $body = preg_replace('/(?<![a-zA-Z0-9=])' . preg_quote($tag, '/') . '/', $newtag, $body);
            $replaced = true;
        }
        //is the link already in str_tags?
        if (!stristr($str_tags, $newtag)) {
            //append or set str_tags
            if (strlen($str_tags)) {
                $str_tags .= ',';
            }
            $str_tags .= $newtag;
        }
        return array('replaced' => $replaced, 'termtype' => $termtype, 'term' => $basetag, 'url' => $url, 'contact' => $r[0]);
    }
    //is it a person tag?
    if (strpos($tag, '@') === 0) {
        // The @! tag will alter permissions
        $exclusive = strpos($tag, '!') === 1 && !$diaspora ? true : false;
        //is it already replaced?
        if (strpos($tag, '[zrl=')) {
            return $replaced;
        }
        //get the person's name
        $name = substr($tag, $exclusive ? 2 : 1);
        // The name or name fragment we are going to replace
        $newname = $name;
        // a copy that we can mess with
        $tagcid = 0;
        $r = null;
        // is it some generated name?
        $forum = false;
        $trailing_plus_name = false;
        // @channel+ is a forum or network delivery tag
        if (substr($newname, -1, 1) === '+') {
            $forum = true;
            $newname = substr($newname, 0, -1);
        }
        // Here we're looking for an address book entry as provided by the auto-completer
        // of the form something+nnn where nnn is an abook_id or the first chars of xchan_hash
        // If there's a +nnn in the string make sure there isn't a space preceding it
        $t1 = strpos($newname, ' ');
        $t2 = strrpos($newname, '+');
        if ($t1 && $t2 && $t1 < $t2) {
            $t2 = 0;
        }
        if ($t2 && !$diaspora) {
            //get the id
            $tagcid = substr($newname, $t2 + 1);
            if (strrpos($tagcid, ' ')) {
                $tagcid = substr($tagcid, 0, strrpos($tagcid, ' '));
            }
            if (strlen($tagcid) < 16) {
                $abook_id = intval($tagcid);
            }
            //remove the next word from tag's name
            if (strpos($name, ' ')) {
                $name = substr($name, 0, strpos($name, ' '));
            }
            if ($abook_id) {
                // if there was an id
                // select channel with that id from the logged in user's address book
                $r = q("SELECT * FROM abook left join xchan on abook_xchan = xchan_hash \n\t\t\t\t\tWHERE abook_id = %d AND abook_channel = %d LIMIT 1", intval($abook_id), intval($profile_uid));
            } else {
                $r = q("SELECT * FROM xchan \n\t\t\t\t\tWHERE xchan_hash like '%s%%' LIMIT 1", dbesc($tagcid));
            }
        }
        if (!$r) {
            // look for matching names in the address book
            // Two ways to deal with spaces - double quote the name or use underscores
            // we see this after input filtering so quotes have been html entity encoded
            if (substr($name, 0, 6) === '&quot;' && substr($name, -6, 6) === '&quot;') {
                $newname = substr($name, 6);
                $newname = substr($newname, 0, -6);
            } else {
                $newname = str_replace('_', ' ', $name);
            }
            // do this bit over since we started over with $name
            if (substr($newname, -1, 1) === '+') {
                $forum = true;
                $newname = substr($newname, 0, -1);
            }
            //select someone from this user's contacts by name
            $r = q("SELECT * FROM abook left join xchan on abook_xchan = xchan_hash  \n\t\t\t\tWHERE xchan_name = '%s' AND abook_channel = %d LIMIT 1", dbesc($newname), intval($profile_uid));
            if (!$r) {
                //select someone by attag or nick and the name passed in
                $r = q("SELECT * FROM abook left join xchan on abook_xchan = xchan_hash  \n\t\t\t\t\tWHERE xchan_addr like ('%s') AND abook_channel = %d LIMIT 1", dbesc(strpos($newname, '@') ? $newname : $newname . '@%'), intval($profile_uid));
            }
            if (!$r) {
                // it's possible somebody has a name ending with '+', which we stripped off as a forum indicator
                // This is very rare but we want to get it right.
                $r = q("SELECT * FROM abook left join xchan on abook_xchan = xchan_hash  \n\t\t\t\t\tWHERE xchan_name = '%s' AND abook_channel = %d LIMIT 1", dbesc($newname . '+'), intval($profile_uid));
                if ($r) {
                    $trailing_plus_name = true;
                }
            }
        }
        // $r is set if we found something
        $channel = get_app()->get_channel();
        if ($r) {
            $profile = $r[0]['xchan_url'];
            $newname = $r[0]['xchan_name'];
            // add the channel's xchan_hash to $access_tag if exclusive
            if ($exclusive) {
                $access_tag .= 'cid:' . $r[0]['xchan_hash'];
            }
        } else {
            // check for a group/collection exclusion tag
            // note that we aren't setting $replaced even though we're replacing text.
            // This tag isn't going to get a term attached to it. It's only used for
            // access control. The link points to out own channel just so it doesn't look
            // weird - as all the other tags are linked to something.
            if (local_channel() && local_channel() == $profile_uid) {
                require_once 'include/group.php';
                $grp = group_byname($profile_uid, $name);
                if ($grp) {
                    $g = q("select hash from groups where id = %d and visible = 1 limit 1", intval($grp));
                    if ($g && $exclusive) {
                        $access_tag .= 'gid:' . $g[0]['hash'];
                    }
                    $channel = get_app()->get_channel();
                    if ($channel) {
                        $newtag = '@' . ($exclusive ? '!' : '') . '[zrl=' . z_root() . '/channel/' . $channel['channel_address'] . ']' . $newname . '[/zrl]';
                        $body = str_replace('@' . ($exclusive ? '!' : '') . $name, $newtag, $body);
                    }
                }
            }
        }
        if ($exclusive && !$access_tag) {
            $access_tag .= 'cid:' . $channel['channel_hash'];
        }
        // if there is an url for this channel
        if (isset($profile)) {
            $replaced = true;
            //create profile link
            $profile = str_replace(',', '%2c', $profile);
            $url = $profile;
            $newtag = '@' . ($exclusive ? '!' : '') . '[zrl=' . $profile . ']' . $newname . ($forum && !$trailing_plus_name ? '+' : '') . '[/zrl]';
            $body = str_replace('@' . ($exclusive ? '!' : '') . $name, $newtag, $body);
            //append tag to str_tags
            if (!stristr($str_tags, $newtag)) {
                if (strlen($str_tags)) {
                    $str_tags .= ',';
                }
                $str_tags .= $newtag;
            }
        }
    }
    return array('replaced' => $replaced, 'termtype' => $termtype, 'term' => $newname, 'url' => $url, 'contact' => $r[0]);
}
Example #8
0
function map_content($a)
{
    if (argc() > 1 && argv(1) === 'import') {
        logger('map import launching');
        return map_import($a);
    }
    //$a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/map/map.css' . '" media="all" />' . "\r\n";
    head_add_css('/addon/map/view/css/map.css');
    //    $a->page['htmlhead'] .= replace_macros(get_markup_template('jot-header.tpl'), array(
    //        '$baseurl' => $a->get_baseurl(),
    //        '$editselect' => 'none',
    //        '$ispublic' => '&nbsp;', // t('Visible to <strong>everybody</strong>'),
    //        '$geotag' => '',
    //        '$nickname' => $channel['channel_address'],
    //        '$confirmdelete' => t('Delete webpage?')
    //    ));
    if ($_SESSION['data_cache'] !== null) {
        $data_cache = json_encode($_SESSION['data_cache']);
    } else {
        $data_cache = '';
    }
    $o .= replace_macros(get_markup_template('map.tpl', 'addon/map'), array('$header' => t('Map'), '$text' => $text, '$data_cache' => $data_cache, '$loginbox' => login()));
    $o .= '<script type="text/javascript" src="' . App::get_baseurl() . '/addon/map/view/js/underscore-min.js"></script>' . "\r\n";
    $o .= '<script type="text/javascript" src="' . App::get_baseurl() . '/addon/map/view/js/backbone-min.js"></script>' . "\r\n";
    $o .= '<script type="text/javascript" src="' . App::get_baseurl() . '/addon/map/view/js/ol.js"></script>' . "\r\n";
    $o .= '<script type="text/javascript" src="' . App::get_baseurl() . '/addon/map/view/js/map.js?version=' . map_get_version() . '"></script>' . "\r\n";
    return $o;
}
/**
 * @param App $a
 * @param string $o
 */
function privacy_image_cache_ping_xmlize_hook(&$a, &$o)
{
    if ($o["photo"] != "" && !privacy_image_cache_is_local_image($o["photo"])) {
        $o["photo"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["photo"])));
    }
}
Example #10
0
        $recipients = array_diff($recipients, $deny);
        $conversant_str = dbesc(implode(', ', $conversants));
    }
    $r = q("SELECT * FROM `contact` WHERE `id` IN ( {$conversant_str} ) AND `blocked` = 0 AND `pending` = 0");
    if (!count($r)) {
        killme();
    }
    $contacts = $r;
    $tomb_template = file_get_contents('view/atom_tomb.tpl');
    $item_template = file_get_contents('view/atom_item.tpl');
    $cmnt_template = file_get_contents('view/atom_cmnt.tpl');
}
$feed_template = file_get_contents('view/atom_feed.tpl');
$mail_template = file_get_contents('view/atom_mail.tpl');
$atom = '';
$atom .= replace_macros($feed_template, array('$feed_id' => xmlify($a->get_baseurl()), '$feed_title' => xmlify($owner['name']), '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00', 'Y-m-d\\TH:i:s\\Z')), '$name' => xmlify($owner['name']), '$profile_page' => xmlify($owner['url']), '$photo' => xmlify($owner['photo']), '$thumb' => xmlify($owner['thumb']), '$picdate' => xmlify(datetime_convert('UTC', 'UTC', $owner['avatar-date'] . '+00:00', 'Y-m-d\\TH:i:s\\Z')), '$uridate' => xmlify(datetime_convert('UTC', 'UTC', $owner['uri-date'] . '+00:00', 'Y-m-d\\TH:i:s\\Z')), '$namdate' => xmlify(datetime_convert('UTC', 'UTC', $owner['name-date'] . '+00:00', 'Y-m-d\\TH:i:s\\Z'))));
if ($cmd == 'mail') {
    $atom .= replace_macros($mail_template, array('$name' => xmlify($owner['name']), '$profile_page' => xmlify($owner['url']), '$thumb' => xmlify($owner['thumb']), '$item_id' => xmlify($item['uri']), '$subject' => xmlify($item['title']), '$created' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00', 'Y-m-d\\TH:i:s\\Z')), '$content' => xmlify($item['body']), '$parent_id' => xmlify($item['parent-uri'])));
} else {
    if ($followup) {
        foreach ($items as $item) {
            if ($item['id'] == $item_id) {
                $atom .= replace_macros($cmnt_template, array('$name' => xmlify($owner['name']), '$profile_page' => xmlify($owner['url']), '$thumb' => xmlify($owner['thumb']), '$item_id' => xmlify($item['uri']), '$title' => xmlify($item['title']), '$published' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00', 'Y-m-d\\TH:i:s\\Z')), '$updated' => xmlify(datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00', 'Y-m-d\\TH:i:s\\Z')), '$content' => xmlify($item['body']), '$parent_id' => xmlify($item['parent-uri']), '$comment_allow' => 0));
            }
        }
    } else {
        foreach ($items as $item) {
            if ($item['deleted']) {
                $atom .= replace_macros($tomb_template, array('$id' => xmlify($item['uri']), '$updated' => xmlify(datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00', 'Y-m-d\\TH:i:s\\Z'))));
            } else {
                foreach ($contacts as $contact) {
Example #11
0
/**
 * @param App $a
 */
function fbrowser_content($a)
{
    if (!local_user()) {
        killme();
    }
    if ($a->argc == 1) {
        killme();
    }
    $template_file = "filebrowser.tpl";
    $mode = "";
    if (x($_GET, 'mode')) {
        $template_file = "filebrowser_plain.tpl";
        $mode = "?mode=" . $_GET['mode'];
    }
    //echo "<pre>"; var_dump($a->argv); killme();
    switch ($a->argv[1]) {
        case "image":
            $path = array(array("", t("Photos")));
            $albums = false;
            $sql_extra = "";
            $sql_extra2 = " ORDER BY created DESC LIMIT 0, 10";
            if ($a->argc == 2) {
                $albums = q("SELECT distinct(`album`) AS `album` FROM `photo` WHERE `uid` = %d ", intval(local_user()));
                // anon functions only from 5.3.0... meglio tardi che mai..
                $folder1 = function ($el) use($mode) {
                    return array(bin2hex($el['album']), $el['album']);
                };
                $albums = array_map($folder1, $albums);
            }
            $album = "";
            if ($a->argc == 3) {
                $album = hex2bin($a->argv[2]);
                $sql_extra = sprintf("AND `album` = '%s' ", dbesc($album));
                $sql_extra2 = "";
                $path[] = array($a->argv[2], $album);
            }
            $r = q("SELECT `resource-id`, `id`, `filename`, type, min(`scale`) AS `hiq`,max(`scale`) AS `loq`, `desc`\n\t\t\t\t\tFROM `photo` WHERE `uid` = %d  {$sql_extra}\n\t\t\t\t\tGROUP BY `resource-id` {$sql_extra2}", intval(local_user()));
            function files1($rr)
            {
                global $a;
                $types = Photo::supportedTypes();
                $ext = $types[$rr['type']];
                if ($a->theme['template_engine'] === 'internal') {
                    $filename_e = template_escape($rr['filename']);
                } else {
                    $filename_e = $rr['filename'];
                }
                return array($a->get_baseurl() . '/photo/' . $rr['resource-id'] . '.' . $ext, $filename_e, $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . $rr['loq'] . '.' . $ext);
            }
            $files = array_map("files1", $r);
            $tpl = get_markup_template($template_file);
            $o = replace_macros($tpl, array('$type' => 'image', '$baseurl' => $a->get_baseurl(), '$path' => $path, '$folders' => $albums, '$files' => $files, '$cancel' => t('Cancel'), '$nickname' => $a->user['nickname']));
            break;
        case "file":
            if ($a->argc == 2) {
                $files = q("SELECT id, filename, filetype FROM `attach` WHERE `uid` = %d ", intval(local_user()));
                function files2($rr)
                {
                    global $a;
                    list($m1, $m2) = explode("/", $rr['filetype']);
                    $filetype = file_exists("images/icons/{$m1}.png") ? $m1 : "zip";
                    if ($a->theme['template_engine'] === 'internal') {
                        $filename_e = template_escape($rr['filename']);
                    } else {
                        $filename_e = $rr['filename'];
                    }
                    return array($a->get_baseurl() . '/attach/' . $rr['id'], $filename_e, $a->get_baseurl() . '/images/icons/16/' . $filetype . '.png');
                }
                $files = array_map("files2", $files);
                //echo "<pre>"; var_dump($files); killme();
                $tpl = get_markup_template($template_file);
                $o = replace_macros($tpl, array('$type' => 'file', '$baseurl' => $a->get_baseurl(), '$path' => array(array("", t("Files"))), '$folders' => false, '$files' => $files, '$cancel' => t('Cancel'), '$nickname' => $a->user['nickname']));
            }
            break;
    }
    if (x($_GET, 'mode')) {
        return $o;
    } else {
        echo $o;
        killme();
    }
}
Example #12
0
/**
 * @param App $a
 * @return string
 */
function wdcal_getSettingsPage(&$a)
{
    if (!local_user()) {
        notice(t('Permission denied.') . EOL);
        return '';
    }
    if (isset($_REQUEST["save"])) {
        check_form_security_token_redirectOnErr($a->get_baseurl() . '/dav/settings/', 'calprop');
        set_pconfig($a->user["uid"], "dav", "dateformat", $_REQUEST["wdcal_date_format"]);
        info(t('The new values have been saved.'));
    }
    $o = "";
    $o .= "<a href='" . $a->get_baseurl() . "/dav/wdcal/'>" . t("Go back to the calendar") . "</a><br><br>";
    $o .= '<h3>' . t('Calendar Settings') . '</h3>';
    $current_format = wdcal_local::getInstanceByUser($a->user["uid"]);
    $o .= '<form method="POST" action="' . $a->get_baseurl() . '/dav/settings/">';
    $o .= "<input type='hidden' name='form_security_token' value='" . get_form_security_token('calprop') . "'>\n";
    $o .= '<label for="wdcal_date_format">' . t('Date format') . ':</label><select name="wdcal_date_format" id="wdcal_date_format" size="1">';
    $classes = wdcal_local::getInstanceClasses();
    foreach ($classes as $c) {
        $o .= '<option value="' . $c::getID() . '" ';
        if ($c::getID() == $current_format::getID()) {
            $o .= 'selected';
        }
        $o .= '>' . escape_tags($c::getName()) . '</option>';
    }
    $o .= '</select><br>';
    $o .= '<label for="wdcal_time_zone">' . t('Time zone') . ':</label><input id="wdcal_time_zone" value="' . $a->timezone . '" disabled><br>';
    $o .= '<input type="submit" name="save" value="' . t('Save') . '">';
    $o .= '</form>';
    $o .= "<br><h3>" . t("Limitations") . "</h3>";
    $o .= "- The native friendica events are embedded as read-only, half-transparent in the calendar.<br>";
    $o .= "<br><h3>" . t("Warning") . "</h3>";
    $o .= "This plugin still is in a very early stage of development. Expect major bugs!<br>";
    $o .= "<br><h3>" . t("Synchronization (iPhone, Thunderbird Lightning, Android, ...)") . "</h3>";
    $o .= 'This plugin enables synchronization of your dates and contacts with CalDAV- and CardDAV-enabled programs or devices.<br>
		As an example, the instructions how to set up two-way synchronization with an iPhone/iPodTouch are provided below.<br>
		Unfortunately, Android does not have native support for CalDAV or CardDAV, so an app has to be installed.<br>
		On desktops, the Lightning-extension to Mozilla Thunderbird should be able to use this plugin as a backend.<br><br>';
    $o .= '<h4>' . t('Synchronizing this calendar with the iPhone') . '</h4>';
    $o .= "<ul>\n\t<li>Go to the settings</li>\n\t<li>Mail, contacts, settings</li>\n\t<li>Add a new account</li>\n\t<li>Other...</li>\n\t<li>Calendar -> CalDAV-Account</li>\n\t<li><b>Server:</b> " . $a->get_baseurl() . "/dav/ / <b>Username/Password:</b> <em>the same as your friendica-login</em></li>\n\t</ul>";
    $o .= '<h4>' . t('Synchronizing your Friendica-Contacts with the iPhone') . '</h4>';
    $o .= "<ul>\n\t<li>Go to the settings</li>\n\t<li>Mail, contacts, settings</li>\n\t<li>Add a new account</li>\n\t<li>Other...</li>\n\t<li>Contacts -> CardDAV-Account</li>\n\t<li><b>Server:</b> " . $a->get_baseurl() . "/dav/ / <b>Username/Password:</b> <em>the same as your friendica-login</em></li>\n\t</ul>";
    return $o;
}
Example #13
0
/**
 * @param App $a
 * @param array $user
 * @param array $self
 * @param string $fb_id
 * @param bool $wall
 * @param array $orig_post
 * @param object $likes
 */
function fb_consume_like(&$a, &$user, &$self, $fb_id, $wall, &$orig_post, &$likes)
{
    $top_item = $orig_post['id'];
    $uid = IntVal($user[0]['uid']);
    if (!$orig_post) {
        return;
    }
    // If we posted the like locally, it will be found with our url, not the FB url.
    $second_url = $likes->id == $fb_id ? $self[0]['url'] : 'http://facebook.com/profile.php?id=' . $likes->id;
    $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s'\n    \tAND ( `author-link` = '%s' OR `author-link` = '%s' ) LIMIT 1", dbesc($orig_post['uri']), intval($uid), dbesc(ACTIVITY_LIKE), dbesc('http://facebook.com/profile.php?id=' . $likes->id), dbesc($second_url));
    if (count($r)) {
        return;
    }
    $likedata = array();
    $likedata['parent'] = $top_item;
    $likedata['verb'] = ACTIVITY_LIKE;
    $likedata['gravity'] = 3;
    $likedata['uid'] = $uid;
    $likedata['wall'] = $wall ? 1 : 0;
    $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
    $likedata['parent-uri'] = $orig_post['uri'];
    if ($likes->id == $fb_id) {
        $likedata['contact-id'] = $self[0]['id'];
    } else {
        $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1", dbesc($likes->id), intval($uid));
        if (count($r)) {
            $likedata['contact-id'] = $r[0]['id'];
        }
    }
    if (!x($likedata, 'contact-id')) {
        $likedata['contact-id'] = $orig_post['contact-id'];
    }
    $likedata['app'] = 'facebook';
    $likedata['verb'] = ACTIVITY_LIKE;
    $likedata['author-name'] = $likes->name;
    $likedata['author-link'] = 'http://facebook.com/profile.php?id=' . $likes->id;
    $likedata['author-avatar'] = 'https://graph.facebook.com/' . $likes->id . '/picture';
    $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
    $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
    $post_type = t('status');
    $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
    $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
    $likedata['body'] = sprintf(t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
    $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' . '<id>' . $orig_post['uri'] . '</id><link>' . xmlify('<link rel="alternate" type="text/html" href="' . xmlify($orig_post['plink']) . '" />') . '</link><title>' . $orig_post['title'] . '</title><content>' . $orig_post['body'] . '</content></object>';
    item_store($likedata);
}
/**
 * @param App $a
 * @return string
 */
function wdcal_getSettingsPage(&$a)
{
    if (!local_user()) {
        notice(t('Permission denied.') . EOL);
        return '';
    }
    if (isset($_REQUEST["save"])) {
        check_form_security_token_redirectOnErr('/dav/settings/', 'calprop');
        set_pconfig($a->user["uid"], "dav", "dateformat", $_REQUEST["wdcal_date_format"]);
        info(t('The new values have been saved.'));
    }
    if (isset($_REQUEST["save_cals"])) {
        check_form_security_token_redirectOnErr('/dav/settings/', 'calprop');
        $r = q("SELECT * FROM %s%scalendars WHERE `namespace` = " . CALDAV_NAMESPACE_PRIVATE . " AND `namespace_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($a->user["uid"]));
        foreach ($r as $cal) {
            $backend = wdcal_calendar_factory($cal["namespace"], $cal["namespace_id"], $cal["uri"], $cal);
            $change_sql = "";
            $col = substr($_REQUEST["color"][$cal["id"]], 1);
            if (strtolower($col) != strtolower($cal["calendarcolor"])) {
                $change_sql .= ", `calendarcolor` = '" . dbesc($col) . "'";
            }
            if (!is_subclass_of($backend, "Sabre_CalDAV_Backend_Virtual")) {
                if ($_REQUEST["uri"][$cal["id"]] != $cal["uri"]) {
                    $change_sql .= ", `uri` = '" . dbesc($_REQUEST["uri"][$cal["id"]]) . "'";
                }
                if ($_REQUEST["name"][$cal["id"]] != $cal["displayname"]) {
                    $change_sql .= ", `displayname` = '" . dbesc($_REQUEST["name"][$cal["id"]]) . "'";
                }
            }
            if ($change_sql != "") {
                q("UPDATE %s%scalendars SET `ctag` = `ctag` + 1 {$change_sql} WHERE `id` = %d AND `namespace_id` = %d AND `namespace_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $cal["id"], CALDAV_NAMESPACE_PRIVATE, IntVal($a->user["uid"]));
                info(t('The calendar has been updated.'));
            }
        }
        if (isset($_REQUEST["uri"]["new"]) && $_REQUEST["uri"]["new"] != "" && $_REQUEST["name"]["new"] && $_REQUEST["name"]["new"] != "") {
            $order = q("SELECT MAX(`calendarorder`) ord FROM %s%scalendars WHERE `namespace_id` = %d AND `namespace_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CALDAV_NAMESPACE_PRIVATE, IntVal($a->user["uid"]));
            $neworder = $order[0]["ord"] + 1;
            q("INSERT INTO %s%scalendars (`namespace`, `namespace_id`, `calendarorder`, `calendarcolor`, `displayname`, `timezone`, `uri`, `has_vevent`, `ctag`)\n\t\t\t\tVALUES (%d, %d, %d, '%s', '%s', '%s', '%s', 1, 1)", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CALDAV_NAMESPACE_PRIVATE, IntVal($a->user["uid"]), $neworder, dbesc(strtolower(substr($_REQUEST["color"]["new"], 1))), dbesc($_REQUEST["name"]["new"]), dbesc($a->timezone), dbesc($_REQUEST["uri"]["new"]));
            info(t('The new calendar has been created.'));
        }
    }
    if (isset($_REQUEST["remove_cal"])) {
        check_form_security_token_redirectOnErr('/dav/settings/', 'del_cal', 't');
        $c = q("SELECT * FROM %s%scalendars WHERE `id` = %d AND `namespace_id` = %d AND `namespace_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($_REQUEST["remove_cal"]), CALDAV_NAMESPACE_PRIVATE, IntVal($a->user["uid"]));
        if (count($c) != 1) {
            killme();
        }
        $calobjs = q("SELECT `id` FROM %s%scalendarobjects WHERE `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($_REQUEST["remove_cal"]));
        $newcal = q("SELECT * FROM %s%scalendars WHERE `id` != %d AND `namespace_id` = %d AND `namespace_id` = %d ORDER BY `calendarcolor` LIMIT 0,1", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($_REQUEST["remove_cal"]), CALDAV_NAMESPACE_PRIVATE, IntVal($a->user["uid"]));
        if (count($newcal) != 1) {
            killme();
        }
        q("UPDATE %s%scalendarobjects SET `calendar_id` = %d WHERE `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($newcal[0]["id"]), IntVal($c[0]["id"]));
        foreach ($calobjs as $calobj) {
            renderCalDavEntry_calobj_id($calobj["id"]);
        }
        q("DELETE FROM %s%scalendars WHERE `id` = %s", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($_REQUEST["remove_cal"]));
        q("UPDATE %s%scalendars SET `ctag` = `ctag` + 1 WHERE `id` = " . CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $newcal[0]["id"]);
        info(t('The calendar has been deleted.'));
    }
    $o = "";
    $o .= "<a href='" . $a->get_baseurl() . "/dav/wdcal/'>" . t("Go back to the calendar") . "</a><br><br>";
    $o .= '<h3>' . t('Calendar Settings') . '</h3>';
    $current_format = wdcal_local::getInstanceByUser($a->user["uid"]);
    $o .= '<form method="POST" action="' . $a->get_baseurl() . '/dav/settings/">';
    $o .= "<input type='hidden' name='form_security_token' value='" . get_form_security_token('calprop') . "'>\n";
    $o .= '<label for="wdcal_date_format">' . t('Date format') . ':</label><select name="wdcal_date_format" id="wdcal_date_format" size="1">';
    $classes = wdcal_local::getInstanceClasses();
    foreach ($classes as $c) {
        $o .= '<option value="' . $c::getID() . '" ';
        if ($c::getID() == $current_format::getID()) {
            $o .= 'selected';
        }
        $o .= '>' . escape_tags($c::getName()) . '</option>';
    }
    $o .= '</select><br>';
    $o .= '<label for="wdcal_time_zone">' . t('Time zone') . ':</label><input id="wdcal_time_zone" value="' . $a->timezone . '" disabled><br>';
    $o .= '<input type="submit" name="save" value="' . t('Save') . '">';
    $o .= '</form>';
    $o .= '<br><br><h3>' . t('Calendars') . '</h3>';
    $o .= '<form method="POST" action="' . $a->get_baseurl() . '/dav/settings/">';
    $o .= "<input type='hidden' name='form_security_token' value='" . get_form_security_token('calprop') . "'>\n";
    $o .= "<table><tr><th>Type</th><th>Color</th><th>Name</th><th>URI (for CalDAV)</th><th>ICS</th></tr>";
    $r = q("SELECT * FROM %s%scalendars WHERE `namespace` = " . CALDAV_NAMESPACE_PRIVATE . " AND `namespace_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($a->user["uid"]));
    $private_max = 0;
    $num_non_virtual = 0;
    foreach ($r as $x) {
        $backend = wdcal_calendar_factory($x["namespace"], $x["namespace_id"], $x["uri"], $x);
        if (!is_subclass_of($backend, "Sabre_CalDAV_Backend_Virtual")) {
            $num_non_virtual++;
        }
    }
    foreach ($r as $x) {
        $p = explode("private-", $x["uri"]);
        if (count($p) == 2 && $p[1] > $private_max) {
            $private_max = $p[1];
        }
        $backend = wdcal_calendar_factory($x["namespace"], $x["namespace_id"], $x["uri"], $x);
        $disabled = is_subclass_of($backend, "Sabre_CalDAV_Backend_Virtual") ? "disabled" : "";
        $o .= "<tr>";
        $o .= "<td style='padding: 2px;'>" . escape_tags($backend->getBackendTypeName()) . "</td>";
        $o .= "<td style='padding: 2px; text-align: center;'><input style='margin-left: 10px; width: 70px;' class='cal_color' name='color[" . $x["id"] . "]' id='cal_color_" . $x["id"] . "' value='#" . (strlen($x["calendarcolor"]) != 6 ? "5858ff" : escape_tags($x["calendarcolor"])) . "'></td>";
        $o .= "<td style='padding: 2px;'><input style='margin-left: 10px;' name='name[" . $x["id"] . "]' value='" . escape_tags($x["displayname"]) . "' {$disabled}></td>";
        $o .= "<td style='padding: 2px;'><input style='margin-left: 10px; width: 150px;' name='uri[" . $x["id"] . "]' value='" . escape_tags($x["uri"]) . "' {$disabled}></td>";
        $o .= "<td style='padding: 2px;'><a href='" . $a->get_baseurl() . "/dav/wdcal/" . $x["id"] . "/ics-export/'>Export</a>";
        if (!is_subclass_of($backend, "Sabre_CalDAV_Backend_Virtual") && $num_non_virtual > 1) {
            $o .= " / <a href='" . $a->get_baseurl() . "/dav/wdcal/" . $x["id"] . "/ics-import/'>Import</a>";
        }
        $o .= "</td>";
        $o .= "<td style='padding: 2px; padding-left: 50px;'>";
        if (!is_subclass_of($backend, "Sabre_CalDAV_Backend_Virtual") && $num_non_virtual > 1) {
            $o .= "<a href='" . $a->get_baseurl() . "/dav/settings/?remove_cal=" . $x["id"] . "&amp;t=" . get_form_security_token("del_cal") . "' class='delete_cal'>Delete</a>";
        }
        $o .= "</td>\n";
        $o .= "</tr>\n";
    }
    $private_max++;
    $o .= "<tr class='cal_add_row' style='display: none;'>";
    $o .= "<td style='padding: 2px;'>" . escape_tags(Sabre_CalDAV_Backend_Private::getBackendTypeName()) . "</td>";
    $o .= "<td style='padding: 2px; text-align: center;'><input style='margin-left: 10px; width: 70px;' class='cal_color' name='color[new]' id='cal_color_new' value='#5858ff'></td>";
    $o .= "<td style='padding: 2px;'><input style='margin-left: 10px;' name='name[new]' value='Another calendar'></td>";
    $o .= "<td style='padding: 2px;'><input style='margin-left: 10px; width: 150px;' name='uri[new]' value='private-{$private_max}'></td>";
    $o .= "<td></td><td></td>";
    $o .= "</tr>\n";
    $o .= "</table>";
    $o .= "<div style='text-align: center;'>[<a href='#' class='calendar_add_caller'>" . t("Create a new calendar") . "</a>]</div>";
    $o .= '<input type="submit" name="save_cals" value="' . t('Save') . '">';
    $o .= '</form>';
    $baseurl = $a->get_baseurl();
    $o .= "<script>\$(function() {\n\t\twdcal_edit_calendars_start('" . $current_format->dateformat_datepicker_js() . "', '{$baseurl}/dav/');\n\t});</script>";
    $o .= "<br><h3>" . t("Limitations") . "</h3>";
    $o .= "- The native friendica events are embedded as read-only, half-transparent in the calendar.<br>";
    $o .= "<br><h3>" . t("Warning") . "</h3>";
    $o .= "This plugin still is in a very early stage of development. Expect major bugs!<br>";
    $o .= "<br><h3>" . t("Synchronization (iPhone, Thunderbird Lightning, Android, ...)") . "</h3>";
    $o .= 'This plugin enables synchronization of your dates and contacts with CalDAV- and CardDAV-enabled programs or devices.<br>
		As an example, the instructions how to set up two-way synchronization with an iPhone/iPodTouch are provided below.<br>
		Unfortunately, Android does not have native support for CalDAV or CardDAV, so an app has to be installed.<br>
		On desktops, the Lightning-extension to Mozilla Thunderbird should be able to use this plugin as a backend.<br><br>';
    $o .= '<h4>' . t('Synchronizing this calendar with the iPhone') . '</h4>';
    $o .= "<ul>\n\t<li>Go to the settings</li>\n\t<li>Mail, contacts, settings</li>\n\t<li>Add a new account</li>\n\t<li>Other...</li>\n\t<li>Calendar -> CalDAV-Account</li>\n\t<li><b>Server:</b> " . $a->get_baseurl() . "/dav/ / <b>Username/Password:</b> <em>the same as your friendica-login</em></li>\n\t</ul>";
    $o .= '<h4>' . t('Synchronizing your Friendica-Contacts with the iPhone') . '</h4>';
    $o .= "<ul>\n\t<li>Go to the settings</li>\n\t<li>Mail, contacts, settings</li>\n\t<li>Add a new account</li>\n\t<li>Other...</li>\n\t<li>Contacts -> CardDAV-Account</li>\n\t<li><b>Server:</b> " . $a->get_baseurl() . "/dav/ / <b>Username/Password:</b> <em>the same as your friendica-login</em></li>\n\t</ul>";
    return $o;
}
Example #15
0
function delivery_run(&$argv, &$argc)
{
    global $a, $db;
    if (is_null($a)) {
        $a = new App();
    }
    if (is_null($db)) {
        @(include ".htconfig.php");
        require_once "include/dba.php";
        $db = new dba($db_host, $db_user, $db_pass, $db_data);
        unset($db_host, $db_user, $db_pass, $db_data);
    }
    require_once "include/session.php";
    require_once "include/datetime.php";
    require_once 'include/items.php';
    require_once 'include/bbcode.php';
    require_once 'include/diaspora.php';
    require_once 'include/email.php';
    load_config('config');
    load_config('system');
    load_hooks();
    if ($argc < 3) {
        return;
    }
    $a->set_baseurl(get_config('system', 'url'));
    logger('delivery: invoked: ' . print_r($argv, true), LOGGER_DEBUG);
    $cmd = $argv[1];
    $item_id = intval($argv[2]);
    for ($x = 3; $x < $argc; $x++) {
        $contact_id = intval($argv[$x]);
        // Some other process may have delivered this item already.
        $r = q("select * from deliverq where cmd = '%s' and item = %d and contact = %d limit 1", dbesc($cmd), dbesc($item_id), dbesc($contact_id));
        if (!count($r)) {
            continue;
        }
        $maxsysload = intval(get_config('system', 'maxloadavg'));
        if ($maxsysload < 1) {
            $maxsysload = 50;
        }
        if (function_exists('sys_getloadavg')) {
            $load = sys_getloadavg();
            if (intval($load[0]) > $maxsysload) {
                logger('system: load ' . $load . ' too high. Delivery deferred to next queue run.');
                return;
            }
        }
        // It's ours to deliver. Remove it from the queue.
        q("delete from deliverq where cmd = '%s' and item = %d and contact = %d", dbesc($cmd), dbesc($item_id), dbesc($contact_id));
        if (!$item_id || !$contact_id) {
            continue;
        }
        $expire = false;
        $top_level = false;
        $recipients = array();
        $url_recipients = array();
        $normal_mode = true;
        $recipients[] = $contact_id;
        if ($cmd === 'expire') {
            $normal_mode = false;
            $expire = true;
            $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1 \n\t\t\t\tAND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 30 MINUTE", intval($item_id));
            $uid = $item_id;
            $item_id = 0;
            if (!count($items)) {
                continue;
            }
        } else {
            // find ancestors
            $r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1", intval($item_id));
            if (!count($r) || !intval($r[0]['parent'])) {
                continue;
            }
            $target_item = $r[0];
            $parent_id = intval($r[0]['parent']);
            $uid = $r[0]['uid'];
            $updated = $r[0]['edited'];
            // POSSIBLE CLEANUP --> The following seems superfluous. We've already checked for "if (! intval($r[0]['parent']))" a few lines up
            if (!$parent_id) {
                continue;
            }
            $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer` \n\t\t\t\tFROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC", intval($parent_id));
            if (!count($items)) {
                continue;
            }
            $icontacts = null;
            $contacts_arr = array();
            foreach ($items as $item) {
                if (!in_array($item['contact-id'], $contacts_arr)) {
                    $contacts_arr[] = intval($item['contact-id']);
                }
            }
            if (count($contacts_arr)) {
                $str_contacts = implode(',', $contacts_arr);
                $icontacts = q("SELECT * FROM `contact` \n\t\t\t\t\tWHERE `id` IN ( {$str_contacts} ) ");
            }
            if (!($icontacts && count($icontacts))) {
                continue;
            }
            // avoid race condition with deleting entries
            if ($items[0]['deleted']) {
                foreach ($items as $item) {
                    $item['deleted'] = 1;
                }
            }
            if (count($items) == 1 && $items[0]['uri'] === $items[0]['parent-uri']) {
                logger('delivery: top level post');
                $top_level = true;
            }
        }
        $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`, \n\t\t\t`user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`, \n\t\t\t`user`.`page-flags`, `user`.`prvnets`\n\t\t\tFROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid` \n\t\t\tWHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1", intval($uid));
        if (!count($r)) {
            continue;
        }
        $owner = $r[0];
        $walltowall = $top_level && $owner['id'] != $items[0]['contact-id'] ? true : false;
        $public_message = true;
        // fill this in with a single salmon slap if applicable
        $slap = '';
        require_once 'include/group.php';
        $parent = $items[0];
        // This is IMPORTANT!!!!
        // We will only send a "notify owner to relay" or followup message if the referenced post
        // originated on our system by virtue of having our hostname somewhere
        // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
        // if $parent['wall'] == 1 we will already have the parent message in our array
        // and we will relay the whole lot.
        // expire sends an entire group of expire messages and cannot be forwarded.
        // However the conversation owner will be a part of the conversation and will
        // be notified during this run.
        // Other DFRN conversation members will be alerted during polled updates.
        // Diaspora members currently are not notified of expirations, and other networks have
        // either limited or no ability to process deletions. We should at least fix Diaspora
        // by stringing togther an array of retractions and sending them onward.
        $localhost = $a->get_hostname();
        if (strpos($localhost, ':')) {
            $localhost = substr($localhost, 0, strpos($localhost, ':'));
        }
        /**
         *
         * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
         * have been known to cause runaway conditions which affected several servers, along with
         * permissions issues.
         *
         */
        if (!$top_level && $parent['wall'] == 0 && !$expire && stristr($target_item['uri'], $localhost)) {
            logger('relay denied for delivery agent.');
            /* no relay allowed for direct contact delivery */
            continue;
        }
        if (strlen($parent['allow_cid']) || strlen($parent['allow_gid']) || strlen($parent['deny_cid']) || strlen($parent['deny_gid'])) {
            $public_message = false;
            // private recipients, not public
        }
        $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0", intval($contact_id));
        if (count($r)) {
            $contact = $r[0];
        }
        $hubxml = feed_hublinks();
        logger('notifier: slaps: ' . print_r($slaps, true), LOGGER_DATA);
        require_once 'include/salmon.php';
        if ($contact['self']) {
            continue;
        }
        $deliver_status = 0;
        switch ($contact['network']) {
            case NETWORK_DFRN:
                logger('notifier: dfrndelivery: ' . $contact['name']);
                $feed_template = get_markup_template('atom_feed.tpl');
                $mail_template = get_markup_template('atom_mail.tpl');
                $atom = '';
                $birthday = feed_birthday($owner['uid'], $owner['timezone']);
                if (strlen($birthday)) {
                    $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
                }
                $atom .= replace_macros($feed_template, array('$version' => xmlify(FRIENDICA_VERSION), '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname']), '$feed_title' => xmlify($owner['name']), '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00', ATOM_TIME)), '$hub' => $hubxml, '$salmon' => '', '$name' => xmlify($owner['name']), '$profile_page' => xmlify($owner['url']), '$photo' => xmlify($owner['photo']), '$thumb' => xmlify($owner['thumb']), '$picdate' => xmlify(datetime_convert('UTC', 'UTC', $owner['avatar-date'] . '+00:00', ATOM_TIME)), '$uridate' => xmlify(datetime_convert('UTC', 'UTC', $owner['uri-date'] . '+00:00', ATOM_TIME)), '$namdate' => xmlify(datetime_convert('UTC', 'UTC', $owner['name-date'] . '+00:00', ATOM_TIME)), '$birthday' => $birthday, '$community' => $owner['page-flags'] == PAGE_COMMUNITY ? '<dfrn:community>1</dfrn:community>' : ''));
                foreach ($items as $item) {
                    if (!$item['parent']) {
                        continue;
                    }
                    // private emails may be in included in public conversations. Filter them.
                    if ($public_message && $item['private'] == 1) {
                        continue;
                    }
                    $item_contact = get_item_contact($item, $icontacts);
                    if (!$item_contact) {
                        continue;
                    }
                    if ($normal_mode) {
                        if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
                            $atom .= atom_entry($item, 'text', null, $owner, true, $top_level ? $contact['id'] : 0);
                        }
                    } else {
                        $atom .= atom_entry($item, 'text', null, $owner, true);
                    }
                }
                $atom .= '</feed>' . "\r\n";
                logger('notifier: ' . $atom, LOGGER_DATA);
                $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
                // perform local delivery if we are on the same site
                if (link_compare($basepath, $a->get_baseurl())) {
                    $nickname = basename($contact['url']);
                    if ($contact['issued-id']) {
                        $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
                    } else {
                        $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
                    }
                    $x = q("SELECT\t`contact`.*, `contact`.`uid` AS `importer_uid`,\n\t\t\t\t\t\t`contact`.`pubkey` AS `cpubkey`,\n\t\t\t\t\t\t`contact`.`prvkey` AS `cprvkey`,\n\t\t\t\t\t\t`contact`.`thumb` AS `thumb`,\n\t\t\t\t\t\t`contact`.`url` as `url`,\n\t\t\t\t\t\t`contact`.`name` as `senderName`,\n\t\t\t\t\t\t`user`.*\n\t\t\t\t\t\tFROM `contact`\n\t\t\t\t\t\tINNER JOIN `user` ON `contact`.`uid` = `user`.`uid`\n\t\t\t\t\t\tWHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\t\t\tAND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'\n\t\t\t\t\t\t{$sql_extra}\n\t\t\t\t\t\tAND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1", dbesc(NETWORK_DFRN), dbesc($nickname));
                    if ($x && count($x)) {
                        $write_flag = $x[0]['rel'] && $x[0]['rel'] != CONTACT_IS_SHARING ? true : false;
                        if (($owner['page-flags'] == PAGE_COMMUNITY || $write_flag) && !$x[0]['writable']) {
                            q("update contact set writable = 1 where id = %d", intval($x[0]['id']));
                            $x[0]['writable'] = 1;
                        }
                        $ssl_policy = get_config('system', 'ssl_policy');
                        fix_contact_ssl_policy($x[0], $ssl_policy);
                        // If we are setup as a soapbox we aren't accepting input from this person
                        if ($x[0]['page-flags'] == PAGE_SOAPBOX) {
                            break;
                        }
                        require_once 'library/simplepie/simplepie.inc';
                        logger('mod-delivery: local delivery');
                        local_delivery($x[0], $atom);
                        break;
                    }
                }
                if (!was_recently_delayed($contact['id'])) {
                    $deliver_status = dfrn_deliver($owner, $contact, $atom);
                } else {
                    $deliver_status = -1;
                }
                logger('notifier: dfrn_delivery returns ' . $deliver_status);
                if ($deliver_status == -1) {
                    logger('notifier: delivery failed: queuing message');
                    add_to_queue($contact['id'], NETWORK_DFRN, $atom);
                }
                break;
            case NETWORK_OSTATUS:
                // Do not send to otatus if we are not configured to send to public networks
                if ($owner['prvnets']) {
                    break;
                }
                if (get_config('system', 'ostatus_disabled') || get_config('system', 'dfrn_only')) {
                    break;
                }
                // only send salmon if public - e.g. if it's ok to notify
                // a public hub, it's ok to send a salmon
                if ($public_message && !$expire) {
                    $slaps = array();
                    foreach ($items as $item) {
                        if (!$item['parent']) {
                            continue;
                        }
                        // private emails may be in included in public conversations. Filter them.
                        if ($public_message && $item['private'] == 1) {
                            continue;
                        }
                        $item_contact = get_item_contact($item, $icontacts);
                        if (!$item_contact) {
                            continue;
                        }
                        if ($top_level && $public_message && $item['author-link'] === $item['owner-link'] && !$expire) {
                            $slaps[] = atom_entry($item, 'html', null, $owner, true);
                        }
                    }
                    logger('notifier: slapdelivery: ' . $contact['name']);
                    foreach ($slaps as $slappy) {
                        if ($contact['notify']) {
                            if (!was_recently_delayed($contact['id'])) {
                                $deliver_status = slapper($owner, $contact['notify'], $slappy);
                            } else {
                                $deliver_status = -1;
                            }
                            if ($deliver_status == -1) {
                                // queue message for redelivery
                                add_to_queue($contact['id'], NETWORK_OSTATUS, $slappy);
                            }
                        }
                    }
                }
                break;
            case NETWORK_MAIL:
            case NETWORK_MAIL2:
                if (get_config('system', 'dfrn_only')) {
                    break;
                }
                // WARNING: does not currently convert to RFC2047 header encodings, etc.
                $addr = $contact['addr'];
                if (!strlen($addr)) {
                    break;
                }
                if ($cmd === 'wall-new' || $cmd === 'comment-new') {
                    $it = null;
                    if ($cmd === 'wall-new') {
                        $it = $items[0];
                    } else {
                        $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($argv[2]), intval($uid));
                        if (count($r)) {
                            $it = $r[0];
                        }
                    }
                    if (!$it) {
                        break;
                    }
                    $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
                    if (!count($local_user)) {
                        break;
                    }
                    $reply_to = '';
                    $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1", intval($uid));
                    if ($r1 && $r1[0]['reply_to']) {
                        $reply_to = $r1[0]['reply_to'];
                    }
                    $subject = $it['title'] ? email_header_encode($it['title'], 'UTF-8') : t("(no subject)");
                    // only expose our real email address to true friends
                    if ($contact['rel'] == CONTACT_IS_FRIEND && !$contact['blocked']) {
                        if ($reply_to) {
                            $headers = 'From: ' . email_header_encode($local_user[0]['username'], 'UTF-8') . ' <' . $reply_to . '>' . "\n";
                            $headers .= 'Sender: ' . $local_user[0]['email'] . "\n";
                        } else {
                            $headers = 'From: ' . email_header_encode($local_user[0]['username'], 'UTF-8') . ' <' . $local_user[0]['email'] . '>' . "\n";
                        }
                    } else {
                        $headers = 'From: ' . email_header_encode($local_user[0]['username'], 'UTF-8') . ' <' . t('noreply') . '@' . $a->get_hostname() . '>' . "\n";
                    }
                    //if($reply_to)
                    //	$headers .= 'Reply-to: ' . $reply_to . "\n";
                    $headers .= 'Message-Id: <' . iri2msgid($it['uri']) . '>' . "\n";
                    //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
                    //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
                    //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
                    if ($it['uri'] !== $it['parent-uri']) {
                        $headers .= "References: <" . iri2msgid($it["parent-uri"]) . ">";
                        // If Threading is enabled, write down the correct parent
                        if ($it["thr-parent"] != "" and $it["thr-parent"] != $it["parent-uri"]) {
                            $headers .= " <" . iri2msgid($it["thr-parent"]) . ">";
                        }
                        $headers .= "\n";
                        if (!$it['title']) {
                            $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($it['parent-uri']), intval($uid));
                            if (count($r) and $r[0]['title'] != '') {
                                $subject = $r[0]['title'];
                            } else {
                                $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($it['parent-uri']), intval($uid));
                                if (count($r) and $r[0]['title'] != '') {
                                    $subject = $r[0]['title'];
                                }
                            }
                        }
                        if (strncasecmp($subject, 'RE:', 3)) {
                            $subject = 'Re: ' . $subject;
                        }
                    }
                    email_send($addr, $subject, $headers, $it);
                }
                break;
            case NETWORK_DIASPORA:
                if ($public_message) {
                    $loc = 'public batch ' . $contact['batch'];
                } else {
                    $loc = $contact['name'];
                }
                logger('delivery: diaspora batch deliver: ' . $loc);
                if (get_config('system', 'dfrn_only') || !get_config('system', 'diaspora_enabled') || !$normal_mode) {
                    break;
                }
                if (!$contact['pubkey'] && !$public_message) {
                    break;
                }
                if ($target_item['verb'] === ACTIVITY_DISLIKE) {
                    // unsupported
                    break;
                } elseif ($target_item['deleted'] && $target_item['uri'] === $target_item['parent-uri']) {
                    // top-level retraction
                    logger('delivery: diaspora retract: ' . $loc);
                    diaspora_send_retraction($target_item, $owner, $contact, $public_message);
                    break;
                } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
                    // we are the relay - send comments, likes and relayable_retractions to our conversants
                    logger('delivery: diaspora relay: ' . $loc);
                    diaspora_send_relay($target_item, $owner, $contact, $public_message);
                    break;
                } elseif ($top_level && !$walltowall) {
                    // currently no workable solution for sending walltowall
                    logger('delivery: diaspora status: ' . $loc);
                    diaspora_send_status($target_item, $owner, $contact, $public_message);
                    break;
                }
                logger('delivery: diaspora unknown mode: ' . $contact['name']);
                break;
            case NETWORK_FEED:
            case NETWORK_FACEBOOK:
                if (get_config('system', 'dfrn_only')) {
                    break;
                }
            case NETWORK_PUMPIO:
                if (get_config('system', 'dfrn_only')) {
                    break;
                }
            default:
                break;
        }
    }
    return;
}
Example #16
0
 /**
  * Find any non-embedded images in private items and add redir links to them
  *
  * @param App $a
  * @param array $item
  */
 function redir_private_images($a, &$item)
 {
     $matches = false;
     $cnt = preg_match_all('|\\[img\\](http[^\\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\\.[\\w]+?)?)\\[\\/img\\]|', $item['body'], $matches, PREG_SET_ORDER);
     if ($cnt) {
         //logger("redir_private_images: matches = " . print_r($matches, true));
         foreach ($matches as $mtch) {
             if (strpos($mtch[1], '/redir') !== false) {
                 continue;
             }
             if (local_user() == $item['uid'] && $item['private'] != 0 && $item['contact-id'] != $a->contact['id'] && $item['network'] == NETWORK_DFRN) {
                 //logger("redir_private_images: redir");
                 $img_url = $a->get_baseurl() . '/redir?f=1&quiet=1&url=' . $mtch[1] . '&conurl=' . $item['author-link'];
                 $item['body'] = str_replace($mtch[0], "[img]" . $img_url . "[/img]", $item['body']);
             }
         }
     }
 }
Example #17
0
 $my_url = $a->get_baseurl() . '/profile/' . $nickname;
 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
 if ($aes_allow && function_exists('openssl_encrypt')) {
     openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
     $params['public_key'] = openssl_encrypt($public_key, 'AES-256-CBC', $src_aes_key);
 }
 $res = post_url($dfrn_confirm, $params);
 $xml = simplexml_load_string($res);
 $status = (int) $xml->status;
 switch ($status) {
     case 0:
         break;
     case 1:
         // birthday paradox - generate new dfrn-id and fall through.
         $new_dfrn_id = random_string();
         $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d LIMIT 1", dbesc($new_dfrn_id), intval($contact_id));
     case 2:
         break;
     case 3:
     default:
         break;
 }
 if (($status == 0 || $status == 3) && $intro_id) {
     // delete the notification
     $r = q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1", intval($intro_id));
 }
 if ($status != 0) {
     killme();
 }
 require_once "Photo.php";
 $photo_failure = false;
 $filename = basename($intro['photo']);
 $img_str = fetch_url($intro['photo'], true);
 $img = new Photo($img_str);
 if ($img) {
     $img->scaleImageSquare(175);
     $hash = hash('md5', uniqid(mt_rand(), true));
     $r = $img->store($contact_id, $hash, $filename, t('Contact Photos'), 4);
     if ($r === false) {
         $photo_failure = true;
     }
     $img->scaleImage(80);
     $r = $img->store($contact_id, $hash, $filename, t('Contact Photos'), 5);
     if ($r === false) {
         $photo_failure = true;
     }
     $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.jpg';
Example #18
0
function notifier_run($argv, $argc)
{
    global $a, $db;
    if (is_null($a)) {
        $a = new App();
    }
    if (is_null($db)) {
        @(include ".htconfig.php");
        require_once "dba.php";
        $db = new dba($db_host, $db_user, $db_pass, $db_data);
        unset($db_host, $db_user, $db_pass, $db_data);
    }
    require_once "session.php";
    require_once "datetime.php";
    require_once 'include/items.php';
    require_once 'include/bbcode.php';
    load_config('config');
    load_config('system');
    load_hooks();
    if ($argc < 3) {
        return;
    }
    $a->set_baseurl(get_config('system', 'url'));
    logger('notifier: invoked: ' . print_r($argv, true));
    $cmd = $argv[1];
    switch ($cmd) {
        case 'mail':
        default:
            $item_id = intval($argv[2]);
            if (!$item_id) {
                return;
            }
            break;
    }
    $expire = false;
    $mail = false;
    $fsuggest = false;
    $top_level = false;
    $recipients = array();
    $url_recipients = array();
    $normal_mode = true;
    if ($cmd === 'mail') {
        $normal_mode = false;
        $mail = true;
        $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1", intval($item_id));
        if (!count($message)) {
            return;
        }
        $uid = $message[0]['uid'];
        $recipients[] = $message[0]['contact-id'];
        $item = $message[0];
    } elseif ($cmd === 'expire') {
        $normal_mode = false;
        $expire = true;
        $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1 \n\t\t\tAND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE", intval($item_id));
        $uid = $item_id;
        $item_id = 0;
        if (!count($items)) {
            return;
        }
    } elseif ($cmd === 'suggest') {
        $normal_mode = false;
        $fsuggest = true;
        $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item_id));
        if (!count($suggest)) {
            return;
        }
        $uid = $suggest[0]['uid'];
        $recipients[] = $suggest[0]['cid'];
        $item = $suggest[0];
    } else {
        // find ancestors
        $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($item_id));
        if (!count($r) || !intval($r[0]['parent'])) {
            return;
        }
        $target_item = $r[0];
        $parent_id = intval($r[0]['parent']);
        $uid = $r[0]['uid'];
        $updated = $r[0]['edited'];
        if (!$parent_id) {
            return;
        }
        $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer` \n\t\t\tFROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d ORDER BY `id` ASC", intval($parent_id));
        if (!count($items)) {
            return;
        }
        // avoid race condition with deleting entries
        if ($items[0]['deleted']) {
            foreach ($items as $item) {
                $item['deleted'] = 1;
            }
        }
        if (count($items) == 1 && $items[0]['id'] === $target_item['id'] && $items[0]['uri'] === $items[0]['parent-uri']) {
            logger('notifier: top level post');
            $top_level = true;
        }
    }
    $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`, \n\t\t`user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`, \n\t\t`user`.`page-flags`, `user`.`prvnets`\n\t\tFROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` \n\t\tWHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1", intval($uid));
    if (!count($r)) {
        return;
    }
    $owner = $r[0];
    $walltowall = $top_level && $owner['id'] != $items[0]['contact-id'] ? true : false;
    $hub = get_config('system', 'huburl');
    // If this is a public conversation, notify the feed hub
    $public_message = true;
    // fill this in with a single salmon slap if applicable
    $slap = '';
    if (!($mail || $fsuggest)) {
        require_once 'include/group.php';
        $parent = $items[0];
        // This is IMPORTANT!!!!
        // We will only send a "notify owner to relay" or followup message if the referenced post
        // originated on our system by virtue of having our hostname somewhere
        // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
        // if $parent['wall'] == 1 we will already have the parent message in our array
        // and we will relay the whole lot.
        // expire sends an entire group of expire messages and cannot be forwarded.
        // However the conversation owner will be a part of the conversation and will
        // be notified during this run.
        // Other DFRN conversation members will be alerted during polled updates.
        // Diaspora members currently are not notified of expirations, and other networks have
        // either limited or no ability to process deletions. We should at least fix Diaspora
        // by stringing togther an array of retractions and sending them onward.
        $localhost = $a->get_hostname();
        if (strpos($localhost, ':')) {
            $localhost = substr($localhost, 0, strpos($localhost, ':'));
        }
        /**
         *
         * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes 
         * have been known to cause runaway conditions which affected several servers, along with 
         * permissions issues. 
         *
         */
        $relay_to_owner = false;
        if (!$top_level && $parent['wall'] == 0 && !$expire && stristr($target_item['uri'], $localhost)) {
            $relay_to_owner = true;
        }
        if ($cmd === 'uplink' && intval($parent['forum_mode']) && !$top_level) {
            $relay_to_owner = true;
        }
        // until the 'origin' flag has been in use for several months
        // we will just use it as a fallback test
        // later we will be able to use it as the primary test of whether or not to relay.
        if (!$target_item['origin']) {
            $relay_to_owner = false;
        }
        if ($parent['origin']) {
            $relay_to_owner = false;
        }
        if ($relay_to_owner) {
            logger('notifier: followup', LOGGER_DEBUG);
            // local followup to remote post
            $followup = true;
            $public_message = false;
            // not public
            $conversant_str = dbesc($parent['contact-id']);
        } else {
            $followup = false;
            // don't send deletions onward for other people's stuff
            if ($target_item['deleted'] && !intval($target_item['wall'])) {
                logger('notifier: ignoring delete notification for non-wall item');
                return;
            }
            if (strlen($parent['allow_cid']) || strlen($parent['allow_gid']) || strlen($parent['deny_cid']) || strlen($parent['deny_gid'])) {
                $public_message = false;
                // private recipients, not public
            }
            $allow_people = expand_acl($parent['allow_cid']);
            $allow_groups = expand_groups(expand_acl($parent['allow_gid']));
            $deny_people = expand_acl($parent['deny_cid']);
            $deny_groups = expand_groups(expand_acl($parent['deny_gid']));
            // if our parent is a forum, uplink to the origonal author causing
            // a delivery fork
            if (intval($parent['forum_mode']) && !$top_level && $cmd !== 'uplink') {
                proc_run('php', 'include/notifier', 'uplink', $item_id);
            }
            $conversants = array();
            foreach ($items as $item) {
                $recipients[] = $item['contact-id'];
                $conversants[] = $item['contact-id'];
                // pull out additional tagged people to notify (if public message)
                if ($public_message && strlen($item['inform'])) {
                    $people = explode(',', $item['inform']);
                    foreach ($people as $person) {
                        if (substr($person, 0, 4) === 'cid:') {
                            $recipients[] = intval(substr($person, 4));
                            $conversants[] = intval(substr($person, 4));
                        } else {
                            $url_recipients[] = substr($person, 4);
                        }
                    }
                }
            }
            logger('notifier: url_recipients' . print_r($url_recipients, true));
            $conversants = array_unique($conversants);
            $recipients = array_unique(array_merge($recipients, $allow_people, $allow_groups));
            $deny = array_unique(array_merge($deny_people, $deny_groups));
            $recipients = array_diff($recipients, $deny);
            $conversant_str = dbesc(implode(', ', $conversants));
        }
        $r = q("SELECT * FROM `contact` WHERE `id` IN ( {$conversant_str} ) AND `blocked` = 0 AND `pending` = 0");
        if (count($r)) {
            $contacts = $r;
        }
    }
    $feed_template = get_markup_template('atom_feed.tpl');
    $mail_template = get_markup_template('atom_mail.tpl');
    $atom = '';
    $slaps = array();
    $hubxml = feed_hublinks();
    $birthday = feed_birthday($owner['uid'], $owner['timezone']);
    if (strlen($birthday)) {
        $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
    }
    $atom .= replace_macros($feed_template, array('$version' => xmlify(FRIENDICA_VERSION), '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname']), '$feed_title' => xmlify($owner['name']), '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00', ATOM_TIME)), '$hub' => $hubxml, '$salmon' => '', '$name' => xmlify($owner['name']), '$profile_page' => xmlify($owner['url']), '$photo' => xmlify($owner['photo']), '$thumb' => xmlify($owner['thumb']), '$picdate' => xmlify(datetime_convert('UTC', 'UTC', $owner['avatar-date'] . '+00:00', ATOM_TIME)), '$uridate' => xmlify(datetime_convert('UTC', 'UTC', $owner['uri-date'] . '+00:00', ATOM_TIME)), '$namdate' => xmlify(datetime_convert('UTC', 'UTC', $owner['name-date'] . '+00:00', ATOM_TIME)), '$birthday' => $birthday));
    if ($mail) {
        $public_message = false;
        // mail is  not public
        $body = fix_private_photos($item['body'], $owner['uid']);
        $atom .= replace_macros($mail_template, array('$name' => xmlify($owner['name']), '$profile_page' => xmlify($owner['url']), '$thumb' => xmlify($owner['thumb']), '$item_id' => xmlify($item['uri']), '$subject' => xmlify($item['title']), '$created' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00', ATOM_TIME)), '$content' => xmlify($body), '$parent_id' => xmlify($item['parent-uri'])));
    } elseif ($fsuggest) {
        $public_message = false;
        // suggestions are not public
        $sugg_template = get_markup_template('atom_suggest.tpl');
        $atom .= replace_macros($sugg_template, array('$name' => xmlify($item['name']), '$url' => xmlify($item['url']), '$photo' => xmlify($item['photo']), '$request' => xmlify($item['request']), '$note' => xmlify($item['note'])));
        // We don't need this any more
        q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
    } else {
        if ($followup) {
            foreach ($items as $item) {
                // there is only one item
                if (!$item['parent']) {
                    continue;
                }
                if ($item['id'] == $item_id) {
                    logger('notifier: followup: item: ' . print_r($item, true), LOGGER_DATA);
                    $slap = atom_entry($item, 'html', $owner, $owner, false);
                    $atom .= atom_entry($item, 'text', $owner, $owner, false);
                }
            }
        } else {
            foreach ($items as $item) {
                if (!$item['parent']) {
                    continue;
                }
                // private emails may be in included in public conversations. Filter them.
                if ($public_message && $item['private']) {
                    continue;
                }
                $contact = get_item_contact($item, $contacts);
                if (!$contact) {
                    continue;
                }
                if ($normal_mode) {
                    // we only need the current item, but include the parent because without it
                    // older sites without a corresponding dfrn_notify change may do the wrong thing.
                    if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
                        $atom .= atom_entry($item, 'text', $contact, $owner, true);
                    }
                } else {
                    $atom .= atom_entry($item, 'text', $contact, $owner, true);
                }
                if ($top_level && $public_message && $item['author-link'] === $item['owner-link'] && !$expire) {
                    $slaps[] = atom_entry($item, 'html', $contact, $owner, true);
                }
            }
        }
    }
    $atom .= '</feed>' . "\r\n";
    logger('notifier: ' . $atom, LOGGER_DATA);
    logger('notifier: slaps: ' . print_r($slaps, true), LOGGER_DATA);
    // If this is a public message and pubmail is set on the parent, include all your email contacts
    $mail_disabled = function_exists('imap_open') && !get_config('system', 'imap_disabled') ? 0 : 1;
    if (!$mail_disabled) {
        if (!strlen($target_item['allow_cid']) && !strlen($target_item['allow_gid']) && !strlen($target_item['deny_cid']) && !strlen($target_item['deny_gid']) && intval($target_item['pubmail'])) {
            $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `network` = '%s'", intval($uid), dbesc(NETWORK_MAIL));
            if (count($r)) {
                foreach ($r as $rr) {
                    $recipients[] = $rr['id'];
                }
            }
        }
    }
    if ($followup) {
        $recip_str = $parent['contact-id'];
    } else {
        $recip_str = implode(', ', $recipients);
    }
    $r = q("SELECT * FROM `contact` WHERE `id` IN ( %s ) AND `blocked` = 0 AND `pending` = 0 ", dbesc($recip_str));
    require_once 'include/salmon.php';
    $interval = get_config('system', 'delivery_interval') === false ? 2 : intval(get_config('system', 'delivery_interval'));
    // delivery loop
    if (count($r)) {
        foreach ($r as $contact) {
            if (!$mail && !$fsuggest && !$followup && !$contact['self']) {
                if ($contact['network'] === NETWORK_DIASPORA && $public_message) {
                    continue;
                }
                q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )", dbesc($cmd), intval($item_id), intval($contact['id']));
            }
        }
        foreach ($r as $contact) {
            if ($contact['self']) {
                continue;
            }
            // potentially more than one recipient. Start a new process and space them out a bit.
            // we will deliver single recipient types of message and email receipients here.
            if (!$mail && !$fsuggest && !$followup) {
                proc_run('php', 'include/delivery.php', $cmd, $item_id, $contact['id']);
                if ($interval) {
                    @time_sleep_until(microtime(true) + (double) $interval);
                }
                continue;
            }
            $deliver_status = 0;
            logger("main delivery by notifier: followup={$followup} mail={$mail} fsuggest={$fsuggest}");
            switch ($contact['network']) {
                case NETWORK_DFRN:
                    // perform local delivery if we are on the same site
                    $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
                    if (link_compare($basepath, $a->get_baseurl())) {
                        $nickname = basename($contact['url']);
                        if ($contact['issued-id']) {
                            $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
                        } else {
                            $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
                        }
                        $x = q("SELECT\t`contact`.*, `contact`.`uid` AS `importer_uid`, \n\t\t\t\t\t\t\t`contact`.`pubkey` AS `cpubkey`, \n\t\t\t\t\t\t\t`contact`.`prvkey` AS `cprvkey`, \n\t\t\t\t\t\t\t`contact`.`thumb` AS `thumb`, \n\t\t\t\t\t\t\t`contact`.`url` as `url`,\n\t\t\t\t\t\t\t`contact`.`name` as `senderName`,\n\t\t\t\t\t\t\t`user`.* \n\t\t\t\t\t\t\tFROM `contact` \n\t\t\t\t\t\t\tLEFT JOIN `user` ON `contact`.`uid` = `user`.`uid` \n\t\t\t\t\t\t\tWHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\t\t\t\tAND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'\n\t\t\t\t\t\t\t{$sql_extra}\n\t\t\t\t\t\t\tAND `user`.`account_expired` = 0 LIMIT 1", dbesc(NETWORK_DFRN), dbesc($nickname));
                        if (count($x)) {
                            require_once 'library/simplepie/simplepie.inc';
                            logger('mod-delivery: local delivery');
                            local_delivery($x[0], $atom);
                            break;
                        }
                    }
                    logger('notifier: dfrndelivery: ' . $contact['name']);
                    $deliver_status = dfrn_deliver($owner, $contact, $atom);
                    logger('notifier: dfrn_delivery returns ' . $deliver_status);
                    if ($deliver_status == -1) {
                        logger('notifier: delivery failed: queuing message');
                        // queue message for redelivery
                        add_to_queue($contact['id'], NETWORK_DFRN, $atom);
                    }
                    break;
                case NETWORK_OSTATUS:
                    // Do not send to otatus if we are not configured to send to public networks
                    if ($owner['prvnets']) {
                        break;
                    }
                    if (get_config('system', 'ostatus_disabled') || get_config('system', 'dfrn_only')) {
                        break;
                    }
                    if ($followup && $contact['notify']) {
                        logger('notifier: slapdelivery: ' . $contact['name']);
                        $deliver_status = slapper($owner, $contact['notify'], $slap);
                        if ($deliver_status == -1) {
                            // queue message for redelivery
                            add_to_queue($contact['id'], NETWORK_OSTATUS, $slap);
                        }
                    } else {
                        // only send salmon if public - e.g. if it's ok to notify
                        // a public hub, it's ok to send a salmon
                        if (count($slaps) && $public_message && !$expire) {
                            logger('notifier: slapdelivery: ' . $contact['name']);
                            foreach ($slaps as $slappy) {
                                if ($contact['notify']) {
                                    $deliver_status = slapper($owner, $contact['notify'], $slappy);
                                    if ($deliver_status == -1) {
                                        // queue message for redelivery
                                        add_to_queue($contact['id'], NETWORK_OSTATUS, $slappy);
                                    }
                                }
                            }
                        }
                    }
                    break;
                case NETWORK_MAIL:
                    if (get_config('system', 'dfrn_only')) {
                        break;
                    }
                    // WARNING: does not currently convert to RFC2047 header encodings, etc.
                    $addr = $contact['addr'];
                    if (!strlen($addr)) {
                        break;
                    }
                    if ($cmd === 'wall-new' || $cmd === 'comment-new') {
                        $it = null;
                        if ($cmd === 'wall-new') {
                            $it = $items[0];
                        } else {
                            $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($argv[2]), intval($uid));
                            if (count($r)) {
                                $it = $r[0];
                            }
                        }
                        if (!$it) {
                            break;
                        }
                        $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
                        if (!count($local_user)) {
                            break;
                        }
                        $reply_to = '';
                        $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1", intval($uid));
                        if ($r1 && $r1[0]['reply_to']) {
                            $reply_to = $r1[0]['reply_to'];
                        }
                        $subject = $it['title'] ? $it['title'] : t("(no subject)");
                        $headers = 'From: ' . $local_user[0]['username'] . ' <' . $local_user[0]['email'] . '>' . "\n";
                        if ($reply_to) {
                            $headers .= 'Reply-to: ' . $reply_to . "\n";
                        }
                        $headers .= 'Message-id: <' . $it['uri'] . '>' . "\n";
                        if ($it['uri'] !== $it['parent-uri']) {
                            $header .= 'References: <' . $it['parent-uri'] . '>' . "\n";
                            if (!strlen($it['title'])) {
                                $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' LIMIT 1", dbesc($it['parent-uri']));
                                if (count($r)) {
                                    $subtitle = $r[0]['title'];
                                    if ($subtitle) {
                                        if (strncasecmp($subtitle, 'RE:', 3)) {
                                            $subject = $subtitle;
                                        } else {
                                            $subject = 'Re: ' . $subtitle;
                                        }
                                    }
                                }
                            }
                        }
                        $headers .= 'MIME-Version: 1.0' . "\n";
                        $headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
                        $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
                        $html = prepare_body($it);
                        $message = '<html><body>' . $html . '</body></html>';
                        logger('notifier: email delivery to ' . $addr);
                        mail($addr, $subject, $message, $headers);
                    }
                    break;
                case NETWORK_DIASPORA:
                    require_once 'include/diaspora.php';
                    if (get_config('system', 'dfrn_only') || !get_config('system', 'diaspora_enabled')) {
                        break;
                    }
                    if ($mail) {
                        diaspora_send_mail($item, $owner, $contact);
                        break;
                    }
                    if (!$normal_mode) {
                        break;
                    }
                    // special handling for followup to public post
                    // all other public posts processed as public batches further below
                    if ($public_message) {
                        if ($followup) {
                            diaspora_send_followup($target_item, $owner, $contact, true);
                        }
                        break;
                    }
                    if (!$contact['pubkey']) {
                        break;
                    }
                    if ($target_item['verb'] === ACTIVITY_DISLIKE) {
                        // unsupported
                        break;
                    } elseif ($target_item['deleted'] && $target_item['verb'] !== ACTIVITY_LIKE) {
                        // diaspora delete,
                        diaspora_send_retraction($target_item, $owner, $contact);
                        break;
                    } elseif ($followup) {
                        // send comments, likes and retractions of likes to owner to relay
                        diaspora_send_followup($target_item, $owner, $contact);
                        break;
                    } elseif ($target_item['parent'] != $target_item['id']) {
                        // we are the relay - send comments, likes and unlikes to our conversants
                        diaspora_send_relay($target_item, $owner, $contact);
                        break;
                    } elseif ($top_level && !$walltowall) {
                        // currently no workable solution for sending walltowall
                        diaspora_send_status($target_item, $owner, $contact);
                        break;
                    }
                    break;
                case NETWORK_FEED:
                case NETWORK_FACEBOOK:
                    if (get_config('system', 'dfrn_only')) {
                        break;
                    }
                default:
                    break;
            }
        }
    }
    // send additional slaps to mentioned remote tags (@foo@example.com)
    if ($slap && count($url_recipients) && ($followup || $top_level) && $public_message && !$expire) {
        if (!get_config('system', 'dfrn_only')) {
            foreach ($url_recipients as $url) {
                if ($url) {
                    logger('notifier: urldelivery: ' . $url);
                    $deliver_status = slapper($owner, $url, $slap);
                    // TODO: redeliver/queue these items on failure, though there is no contact record
                }
            }
        }
    }
    if ($public_message) {
        $r1 = q("SELECT DISTINCT(`batch`), `id`, `name`,`network` FROM `contact` WHERE `network` = '%s' \n\t\t\tAND `uid` = %d AND `rel` != %d group by `batch` ORDER BY rand() ", dbesc(NETWORK_DIASPORA), intval($owner['uid']), intval(CONTACT_IS_SHARING));
        $r2 = q("SELECT `id`, `name`,`network` FROM `contact` \n\t\t\tWHERE `network` = '%s' AND `uid` = %d AND `blocked` = 0 AND `pending` = 0\n\t\t\tAND `rel` != %d order by rand() ", dbesc(NETWORK_DFRN), intval($owner['uid']), intval(CONTACT_IS_SHARING));
        $r = array_merge($r2, $r1);
        if (count($r)) {
            logger('pubdeliver: ' . print_r($r, true), LOGGER_DEBUG);
            // throw everything into the queue in case we get killed
            foreach ($r as $rr) {
                if (!$mail && !$fsuggest && !$followup) {
                    q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )", dbesc($cmd), intval($item_id), intval($rr['id']));
                }
            }
            foreach ($r as $rr) {
                // except for Diaspora batch jobs
                // Don't deliver to folks who have already been delivered to
                if ($rr['network'] !== NETWORK_DIASPORA && in_array($rr['id'], $conversants)) {
                    logger('notifier: already delivered id=' . $rr['id']);
                    continue;
                }
                if (!$mail && !$fsuggest && !$followup) {
                    logger('notifier: delivery agent: ' . $rr['name'] . ' ' . $rr['id']);
                    proc_run('php', 'include/delivery.php', $cmd, $item_id, $rr['id']);
                    if ($interval) {
                        @time_sleep_until(microtime(true) + (double) $interval);
                    }
                }
            }
        }
        if (strlen($hub)) {
            $hubs = explode(',', $hub);
            if (count($hubs)) {
                foreach ($hubs as $h) {
                    $h = trim($h);
                    if (!strlen($h)) {
                        continue;
                    }
                    $params = 'hub.mode=publish&hub.url=' . urlencode($a->get_baseurl() . '/dfrn_poll/' . $owner['nickname']);
                    post_url($h, $params);
                    logger('pubsub: publish: ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
                    if (count($hubs) > 1) {
                        sleep(7);
                    }
                    // try and avoid multiple hubs responding at precisely the same time
                }
            }
        }
    }
    if ($normal_mode) {
        call_hooks('notifier_normal', $target_item);
    }
    call_hooks('notifier_end', $target_item);
    return;
}
Example #19
0
/**
 * @param App $a
 * @param object $b
 */
function dav_cron(&$a, &$b)
{
    dav_include_files();
    $r = q("SELECT * FROM %s%snotifications WHERE `notified` = 0 AND `alert_date` <= NOW()", CALDAV_SQL_DB, CALDAV_SQL_PREFIX);
    if (is_array($r)) {
        foreach ($r as $not) {
            q("UPDATE %s%snotifications SET `notified` = 1 WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $not["id"]);
            $event = q("SELECT * FROM %s%sjqcalendar WHERE `calendarobject_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $not["calendarobject_id"]);
            $calendar = q("SELECT * FROM %s%scalendars WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $not["calendar_id"]);
            $users = array();
            if (count($calendar) != 1 || count($event) == 0) {
                continue;
            }
            switch ($calendar[0]["namespace"]) {
                case CALDAV_NAMESPACE_PRIVATE:
                    $user = q("SELECT * FROM user WHERE `uid` = %d AND `blocked` = 0", $calendar[0]["namespace_id"]);
                    if (count($user) != 1) {
                        continue;
                    }
                    $users[] = $user[0];
                    break;
            }
            switch ($not["action"]) {
                case "email":
                case "display":
                    // @TODO implement "Display"
                    foreach ($users as $user) {
                        $find = array("%to%", "%event%", "%url%");
                        $repl = array($user["username"], $event[0]["Summary"], $a->get_baseurl() . "/dav/wdcal/" . $calendar[0]["id"] . "/" . $not["calendarobject_id"] . "/");
                        $text_text = str_replace($find, $repl, "Hi %to%!\n\nThe event \"%event%\" is about to begin:\n%url%");
                        $text_html = str_replace($find, $repl, "Hi %to%!<br>\n<br>\nThe event \"%event%\" is about to begin:<br>\n<a href='" . "%url%" . "'>%url%</a>");
                        $params = array('fromName' => FRIENDICA_PLATFORM, 'fromEmail' => t('noreply') . '@' . $a->get_hostname(), 'replyTo' => t('noreply') . '@' . $a->get_hostname(), 'toEmail' => $user["email"], 'messageSubject' => t("Notification: " . $event[0]["Summary"]), 'htmlVersion' => $text_html, 'textVersion' => $text_text, 'additionalMailHeader' => "");
                        require_once 'include/Emailer.php';
                        Emailer::send($params);
                    }
                    break;
            }
        }
    }
}
Example #20
0
/**
 * @param App $a
 * @return string
 */
function admin_page_remoteupdate(&$a)
{
    if (!is_site_admin()) {
        return login(false);
    }
    $canwrite = canWeWrite();
    $canftp = function_exists('ftp_connect');
    $needupdate = true;
    $u = checkUpdate();
    if (!is_array($u)) {
        $needupdate = false;
        $u = array('', '', '');
    }
    $tpl = get_markup_template("admin_remoteupdate.tpl");
    return replace_macros($tpl, array('$baseurl' => $a->get_baseurl(true), '$submit' => t("Update now"), '$close' => t("Close"), '$localversion' => FRIENDICA_VERSION, '$remoteversion' => $u[1], '$needupdate' => $needupdate, '$canwrite' => $canwrite, '$canftp' => $canftp, '$ftphost' => array('ftphost', t("FTP Host"), '', ''), '$ftppath' => array('ftppath', t("FTP Path"), '/', ''), '$ftpuser' => array('ftpuser', t("FTP User"), '', ''), '$ftppwd' => array('ftppwd', t("FTP Password"), '', ''), '$remotefile' => array('remotefile', '', $u['2'], '')));
}
Example #21
0
function notifier_run(&$argv, &$argc)
{
    global $a, $db;
    if (is_null($a)) {
        $a = new App();
    }
    if (is_null($db)) {
        @(include ".htconfig.php");
        require_once "include/dba.php";
        $db = new dba($db_host, $db_user, $db_pass, $db_data);
        unset($db_host, $db_user, $db_pass, $db_data);
    }
    require_once "include/session.php";
    require_once "include/datetime.php";
    require_once 'include/items.php';
    require_once 'include/bbcode.php';
    require_once 'include/email.php';
    load_config('config');
    load_config('system');
    load_hooks();
    if ($argc < 3) {
        return;
    }
    $a->set_baseurl(get_config('system', 'url'));
    logger('notifier: invoked: ' . print_r($argv, true), LOGGER_DEBUG);
    $cmd = $argv[1];
    switch ($cmd) {
        case 'mail':
        default:
            $item_id = intval($argv[2]);
            if (!$item_id) {
                return;
            }
            break;
    }
    $expire = false;
    $mail = false;
    $fsuggest = false;
    $relocate = false;
    $top_level = false;
    $recipients = array();
    $url_recipients = array();
    $normal_mode = true;
    if ($cmd === 'mail') {
        $normal_mode = false;
        $mail = true;
        $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1", intval($item_id));
        if (!count($message)) {
            return;
        }
        $uid = $message[0]['uid'];
        $recipients[] = $message[0]['contact-id'];
        $item = $message[0];
    } elseif ($cmd === 'expire') {
        $normal_mode = false;
        $expire = true;
        $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1\n\t\t\tAND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE", intval($item_id));
        $uid = $item_id;
        $item_id = 0;
        if (!count($items)) {
            return;
        }
    } elseif ($cmd === 'suggest') {
        $normal_mode = false;
        $fsuggest = true;
        $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item_id));
        if (!count($suggest)) {
            return;
        }
        $uid = $suggest[0]['uid'];
        $recipients[] = $suggest[0]['cid'];
        $item = $suggest[0];
    } elseif ($cmd === 'removeme') {
        $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($item_id));
        if (!$r) {
            return;
        }
        $user = $r[0];
        $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1", intval($item_id));
        if (!$r) {
            return;
        }
        $self = $r[0];
        $r = q("SELECT * FROM `contact` WHERE `self` = 0 AND `uid` = %d", intval($item_id));
        if (!$r) {
            return;
        }
        require_once 'include/Contact.php';
        foreach ($r as $contact) {
            terminate_friendship($user, $self, $contact);
        }
        return;
    } elseif ($cmd === 'relocate') {
        $normal_mode = false;
        $relocate = true;
        $uid = $item_id;
    } else {
        // find ancestors
        $r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1", intval($item_id));
        if (!count($r) || !intval($r[0]['parent'])) {
            return;
        }
        $target_item = $r[0];
        $parent_id = intval($r[0]['parent']);
        $uid = $r[0]['uid'];
        $updated = $r[0]['edited'];
        // POSSIBLE CLEANUP --> The following seems superfluous. We've already checked for "if (! intval($r[0]['parent']))" a few lines up
        if (!$parent_id) {
            return;
        }
        $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`\n\t\t\tFROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC", intval($parent_id));
        if (!count($items)) {
            return;
        }
        // avoid race condition with deleting entries
        if ($items[0]['deleted']) {
            foreach ($items as $item) {
                $item['deleted'] = 1;
            }
        }
        if (count($items) == 1 && $items[0]['id'] === $target_item['id'] && $items[0]['uri'] === $items[0]['parent-uri']) {
            logger('notifier: top level post');
            $top_level = true;
        }
    }
    $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,\n\t\t`user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,\n\t\t`user`.`page-flags`, `user`.`prvnets`\n\t\tFROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`\n\t\tWHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1", intval($uid));
    if (!count($r)) {
        return;
    }
    $owner = $r[0];
    $walltowall = $top_level && $owner['id'] != $items[0]['contact-id'] ? true : false;
    $hub = get_config('system', 'huburl');
    // If this is a public conversation, notify the feed hub
    $public_message = true;
    // Do a PuSH
    $push_notify = false;
    // fill this in with a single salmon slap if applicable
    $slap = '';
    if (!($mail || $fsuggest || $relocate)) {
        require_once 'include/group.php';
        $parent = $items[0];
        $thr_parent = q("SELECT `network` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($target_item["thr-parent"]), intval($target_item["uid"]));
        logger('Parent is ' . $parent['network'] . '. Thread parent is ' . $thr_parent[0]['network'], LOGGER_DEBUG);
        // This is IMPORTANT!!!!
        // We will only send a "notify owner to relay" or followup message if the referenced post
        // originated on our system by virtue of having our hostname somewhere
        // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
        // if $parent['wall'] == 1 we will already have the parent message in our array
        // and we will relay the whole lot.
        // expire sends an entire group of expire messages and cannot be forwarded.
        // However the conversation owner will be a part of the conversation and will
        // be notified during this run.
        // Other DFRN conversation members will be alerted during polled updates.
        // Diaspora members currently are not notified of expirations, and other networks have
        // either limited or no ability to process deletions. We should at least fix Diaspora
        // by stringing togther an array of retractions and sending them onward.
        $localhost = str_replace('www.', '', $a->get_hostname());
        if (strpos($localhost, ':')) {
            $localhost = substr($localhost, 0, strpos($localhost, ':'));
        }
        /**
         *
         * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
         * have been known to cause runaway conditions which affected several servers, along with
         * permissions issues.
         *
         */
        $relay_to_owner = false;
        if (!$top_level && $parent['wall'] == 0 && !$expire && stristr($target_item['uri'], $localhost)) {
            $relay_to_owner = true;
        }
        if ($cmd === 'uplink' && intval($parent['forum_mode']) == 1 && !$top_level) {
            $relay_to_owner = true;
        }
        // until the 'origin' flag has been in use for several months
        // we will just use it as a fallback test
        // later we will be able to use it as the primary test of whether or not to relay.
        if (!$target_item['origin']) {
            $relay_to_owner = false;
        }
        if ($parent['origin']) {
            $relay_to_owner = false;
        }
        if ($relay_to_owner) {
            logger('notifier: followup ' . $target_item["guid"], LOGGER_DEBUG);
            // local followup to remote post
            $followup = true;
            $public_message = false;
            // not public
            $conversant_str = dbesc($parent['contact-id']);
            $recipients = array($parent['contact-id']);
            if (!$target_item['private'] and $target_item['wall'] and strlen($target_item['allow_cid'] . $target_item['allow_gid'] . $target_item['deny_cid'] . $target_item['deny_gid']) == 0) {
                $push_notify = true;
            }
            // We notify Friendica users in the thread when it is an OStatus thread.
            // Hopefully this transfers the messages to the other Friendica servers. (Untested)
            if ($thr_parent and $thr_parent[0]['network'] == NETWORK_OSTATUS or $parent['network'] == NETWORK_OSTATUS) {
                $push_notify = true;
                if ($parent["network"] == NETWORK_OSTATUS) {
                    $r = q("SELECT `author-link` FROM `item` WHERE `parent` = %d AND `author-link` != '%s'", intval($target_item["parent"]), dbesc($owner['url']));
                    foreach ($r as $parent_item) {
                        $probed_contact = probe_url($parent_item["author-link"]);
                        if ($probed_contact["notify"] != "" and $probed_contact["network"] == NETWORK_DFRN) {
                            logger('Notify Friendica user ' . $probed_contact["url"] . ': ' . $probed_contact["notify"]);
                            $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
                        }
                    }
                }
                if (count($url_recipients)) {
                    logger("url_recipients " . print_r($url_recipients, true));
                }
            }
        } else {
            $followup = false;
            logger('Distributing directly ' . $target_item["guid"], LOGGER_DEBUG);
            // don't send deletions onward for other people's stuff
            if ($target_item['deleted'] && !intval($target_item['wall'])) {
                logger('notifier: ignoring delete notification for non-wall item');
                return;
            }
            if (strlen($parent['allow_cid']) || strlen($parent['allow_gid']) || strlen($parent['deny_cid']) || strlen($parent['deny_gid'])) {
                $public_message = false;
                // private recipients, not public
            }
            $allow_people = expand_acl($parent['allow_cid']);
            $allow_groups = expand_groups(expand_acl($parent['allow_gid']), true);
            $deny_people = expand_acl($parent['deny_cid']);
            $deny_groups = expand_groups(expand_acl($parent['deny_gid']));
            // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
            // a delivery fork. private groups (forum_mode == 2) do not uplink
            if (intval($parent['forum_mode']) == 1 && !$top_level && $cmd !== 'uplink') {
                proc_run('php', 'include/notifier.php', 'uplink', $item_id);
            }
            $conversants = array();
            foreach ($items as $item) {
                $recipients[] = $item['contact-id'];
                $conversants[] = $item['contact-id'];
                // pull out additional tagged people to notify (if public message)
                if ($public_message && strlen($item['inform'])) {
                    $people = explode(',', $item['inform']);
                    foreach ($people as $person) {
                        if (substr($person, 0, 4) === 'cid:') {
                            $recipients[] = intval(substr($person, 4));
                            $conversants[] = intval(substr($person, 4));
                        } else {
                            $url_recipients[] = substr($person, 4);
                        }
                    }
                }
            }
            if (count($url_recipients)) {
                logger('notifier: ' . $target_item["guid"] . ' url_recipients ' . print_r($url_recipients, true));
            }
            $conversants = array_unique($conversants);
            $recipients = array_unique(array_merge($recipients, $allow_people, $allow_groups));
            $deny = array_unique(array_merge($deny_people, $deny_groups));
            $recipients = array_diff($recipients, $deny);
            $conversant_str = dbesc(implode(', ', $conversants));
        }
        // If the thread parent is OStatus then do some magic to distribute the messages.
        // We have not only to look at the parent, since it could be a Friendica thread.
        if ($thr_parent and $thr_parent[0]['network'] == NETWORK_OSTATUS or $parent['network'] == NETWORK_OSTATUS) {
            logger('Some parent is OStatus for ' . $target_item["guid"], LOGGER_DEBUG);
            // Send a salmon notification to every person we mentioned in the post
            $arr = explode(',', $target_item['tag']);
            foreach ($arr as $x) {
                //logger('Checking tag '.$x, LOGGER_DEBUG);
                $matches = null;
                if (preg_match('/@\\[url=([^\\]]*)\\]/', $x, $matches)) {
                    $probed_contact = probe_url($matches[1]);
                    if ($probed_contact["notify"] != "") {
                        logger('Notify mentioned user ' . $probed_contact["url"] . ': ' . $probed_contact["notify"]);
                        $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
                    }
                }
            }
            // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
            $sql_extra = " AND `network` IN ('" . NETWORK_OSTATUS . "', '" . NETWORK_DFRN . "')";
        } else {
            $sql_extra = "";
        }
        $r = q("SELECT * FROM `contact` WHERE `id` IN ({$conversant_str}) AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0" . $sql_extra);
        if (count($r)) {
            $contacts = $r;
        }
    }
    $feed_template = get_markup_template('atom_feed.tpl');
    $mail_template = get_markup_template('atom_mail.tpl');
    $atom = '';
    $slaps = array();
    $hubxml = feed_hublinks();
    $birthday = feed_birthday($owner['uid'], $owner['timezone']);
    if (strlen($birthday)) {
        $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
    }
    $atom .= replace_macros($feed_template, array('$version' => xmlify(FRIENDICA_VERSION), '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname']), '$feed_title' => xmlify($owner['name']), '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00', ATOM_TIME)), '$hub' => $hubxml, '$salmon' => '', '$name' => xmlify($owner['name']), '$profile_page' => xmlify($owner['url']), '$photo' => xmlify($owner['photo']), '$thumb' => xmlify($owner['thumb']), '$picdate' => xmlify(datetime_convert('UTC', 'UTC', $owner['avatar-date'] . '+00:00', ATOM_TIME)), '$uridate' => xmlify(datetime_convert('UTC', 'UTC', $owner['uri-date'] . '+00:00', ATOM_TIME)), '$namdate' => xmlify(datetime_convert('UTC', 'UTC', $owner['name-date'] . '+00:00', ATOM_TIME)), '$birthday' => $birthday, '$community' => $owner['page-flags'] == PAGE_COMMUNITY ? '<dfrn:community>1</dfrn:community>' : ''));
    if ($mail) {
        $public_message = false;
        // mail is  not public
        $body = fix_private_photos($item['body'], $owner['uid'], null, $message[0]['contact-id']);
        $atom .= replace_macros($mail_template, array('$name' => xmlify($owner['name']), '$profile_page' => xmlify($owner['url']), '$thumb' => xmlify($owner['thumb']), '$item_id' => xmlify($item['uri']), '$subject' => xmlify($item['title']), '$created' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00', ATOM_TIME)), '$content' => xmlify($body), '$parent_id' => xmlify($item['parent-uri'])));
    } elseif ($fsuggest) {
        $public_message = false;
        // suggestions are not public
        $sugg_template = get_markup_template('atom_suggest.tpl');
        $atom .= replace_macros($sugg_template, array('$name' => xmlify($item['name']), '$url' => xmlify($item['url']), '$photo' => xmlify($item['photo']), '$request' => xmlify($item['request']), '$note' => xmlify($item['note'])));
        // We don't need this any more
        q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
    } elseif ($relocate) {
        $public_message = false;
        // suggestions are not public
        $sugg_template = get_markup_template('atom_relocate.tpl');
        /* get site pubkey. this could be a new installation with no site keys*/
        $pubkey = get_config('system', 'site_pubkey');
        if (!$pubkey) {
            $res = new_keypair(1024);
            set_config('system', 'site_prvkey', $res['prvkey']);
            set_config('system', 'site_pubkey', $res['pubkey']);
        }
        $rp = q("SELECT `resource-id` , `scale`, type FROM `photo` \n\t\t\t\t\t\tWHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
        $photos = array();
        $ext = Photo::supportedTypes();
        foreach ($rp as $p) {
            $photos[$p['scale']] = $a->get_baseurl() . '/photo/' . $p['resource-id'] . '-' . $p['scale'] . '.' . $ext[$p['type']];
        }
        unset($rp, $ext);
        $atom .= replace_macros($sugg_template, array('$name' => xmlify($owner['name']), '$photo' => xmlify($photos[4]), '$thumb' => xmlify($photos[5]), '$micro' => xmlify($photos[6]), '$url' => xmlify($owner['url']), '$request' => xmlify($owner['request']), '$confirm' => xmlify($owner['confirm']), '$notify' => xmlify($owner['notify']), '$poll' => xmlify($owner['poll']), '$sitepubkey' => xmlify(get_config('system', 'site_pubkey'))));
        $recipients_relocate = q("SELECT * FROM contact WHERE uid = %d  AND self = 0 AND network = '%s'", intval($uid), NETWORK_DFRN);
        unset($photos);
    } else {
        $slap = ostatus_salmon($target_item, $owner);
        //$slap = atom_entry($target_item,'html',null,$owner,false);
        if ($followup) {
            foreach ($items as $item) {
                // there is only one item
                if (!$item['parent']) {
                    continue;
                }
                if ($item['id'] == $item_id) {
                    logger('notifier: followup: item: ' . print_r($item, true), LOGGER_DATA);
                    //$slap  = atom_entry($item,'html',null,$owner,false);
                    $atom .= atom_entry($item, 'text', null, $owner, false);
                }
            }
        } else {
            foreach ($items as $item) {
                if (!$item['parent']) {
                    continue;
                }
                // private emails may be in included in public conversations. Filter them.
                if ($public_message && $item['private'] == 1) {
                    continue;
                }
                $contact = get_item_contact($item, $contacts);
                if (!$contact) {
                    continue;
                }
                if ($normal_mode) {
                    // we only need the current item, but include the parent because without it
                    // older sites without a corresponding dfrn_notify change may do the wrong thing.
                    if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
                        $atom .= atom_entry($item, 'text', null, $owner, true);
                    }
                } else {
                    $atom .= atom_entry($item, 'text', null, $owner, true);
                }
                if ($top_level && $public_message && $item['author-link'] === $item['owner-link'] && !$expire) {
                    $slaps[] = ostatus_salmon($item, $owner);
                }
                //$slaps[] = atom_entry($item,'html',null,$owner,true);
            }
        }
    }
    $atom .= '</feed>' . "\r\n";
    logger('notifier: ' . $atom, LOGGER_DATA);
    logger('notifier: slaps: ' . print_r($slaps, true), LOGGER_DATA);
    // If this is a public message and pubmail is set on the parent, include all your email contacts
    $mail_disabled = function_exists('imap_open') && !get_config('system', 'imap_disabled') ? 0 : 1;
    if (!$mail_disabled) {
        if (!strlen($target_item['allow_cid']) && !strlen($target_item['allow_gid']) && !strlen($target_item['deny_cid']) && !strlen($target_item['deny_gid']) && intval($target_item['pubmail'])) {
            $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `network` = '%s'", intval($uid), dbesc(NETWORK_MAIL));
            if (count($r)) {
                foreach ($r as $rr) {
                    $recipients[] = $rr['id'];
                }
            }
        }
    }
    if ($followup) {
        $recip_str = $parent['contact-id'];
    } else {
        $recip_str = implode(', ', $recipients);
    }
    if ($relocate) {
        $r = $recipients_relocate;
    } else {
        $r = q("SELECT * FROM `contact` WHERE `id` IN ( %s ) AND `blocked` = 0 AND `pending` = 0 ", dbesc($recip_str));
    }
    require_once 'include/salmon.php';
    $interval = get_config('system', 'delivery_interval') === false ? 2 : intval(get_config('system', 'delivery_interval'));
    // If we are using the worker we don't need a delivery interval
    if (get_config("system", "worker")) {
        $interval = false;
    }
    // delivery loop
    if (count($r)) {
        foreach ($r as $contact) {
            if (!$mail && !$fsuggest && !$followup && !$relocate && !$contact['self']) {
                if ($contact['network'] === NETWORK_DIASPORA && $public_message) {
                    continue;
                }
                q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )", dbesc($cmd), intval($item_id), intval($contact['id']));
            }
        }
        // This controls the number of deliveries to execute with each separate delivery process.
        // By default we'll perform one delivery per process. Assuming a hostile shared hosting
        // provider, this provides the greatest chance of deliveries if processes start getting
        // killed. We can also space them out with the delivery_interval to also help avoid them
        // getting whacked.
        // If $deliveries_per_process > 1, we will chain this number of multiple deliveries
        // together into a single process. This will reduce the overall number of processes
        // spawned for each delivery, but they will run longer.
        // When using the workerqueue, we don't need this functionality.
        $deliveries_per_process = intval(get_config('system', 'delivery_batch_count'));
        if ($deliveries_per_process <= 0 or get_config("system", "worker")) {
            $deliveries_per_process = 1;
        }
        $this_batch = array();
        for ($x = 0; $x < count($r); $x++) {
            $contact = $r[$x];
            if ($contact['self']) {
                continue;
            }
            logger("Deliver " . $target_item["guid"] . " to " . $contact['url'], LOGGER_DEBUG);
            // potentially more than one recipient. Start a new process and space them out a bit.
            // we will deliver single recipient types of message and email recipients here.
            if (!$mail && !$fsuggest && !$relocate && !$followup) {
                $this_batch[] = $contact['id'];
                if (count($this_batch) == $deliveries_per_process) {
                    proc_run('php', 'include/delivery.php', $cmd, $item_id, $this_batch);
                    $this_batch = array();
                    if ($interval) {
                        @time_sleep_until(microtime(true) + (double) $interval);
                    }
                }
                continue;
            }
            // be sure to pick up any stragglers
            if (count($this_batch)) {
                proc_run('php', 'include/delivery.php', $cmd, $item_id, $this_batch);
            }
            $deliver_status = 0;
            logger("main delivery by notifier: followup={$followup} mail={$mail} fsuggest={$fsuggest} relocate={$relocate}");
            switch ($contact['network']) {
                case NETWORK_DFRN:
                    // perform local delivery if we are on the same site
                    $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
                    if (link_compare($basepath, $a->get_baseurl())) {
                        $nickname = basename($contact['url']);
                        if ($contact['issued-id']) {
                            $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
                        } else {
                            $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
                        }
                        $x = q("SELECT\t`contact`.*, `contact`.`uid` AS `importer_uid`,\n\t\t\t\t\t\t\t`contact`.`pubkey` AS `cpubkey`,\n\t\t\t\t\t\t\t`contact`.`prvkey` AS `cprvkey`,\n\t\t\t\t\t\t\t`contact`.`thumb` AS `thumb`,\n\t\t\t\t\t\t\t`contact`.`url` as `url`,\n\t\t\t\t\t\t\t`contact`.`name` as `senderName`,\n\t\t\t\t\t\t\t`user`.*\n\t\t\t\t\t\t\tFROM `contact`\n\t\t\t\t\t\t\tINNER JOIN `user` ON `contact`.`uid` = `user`.`uid`\n\t\t\t\t\t\t\tWHERE `contact`.`blocked` = 0 AND `contact`.`archive` = 0\n\t\t\t\t\t\t\tAND `contact`.`pending` = 0\n\t\t\t\t\t\t\tAND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'\n\t\t\t\t\t\t\t{$sql_extra}\n\t\t\t\t\t\t\tAND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1", dbesc(NETWORK_DFRN), dbesc($nickname));
                        if ($x && count($x)) {
                            $write_flag = $x[0]['rel'] && $x[0]['rel'] != CONTACT_IS_SHARING ? true : false;
                            if (($owner['page-flags'] == PAGE_COMMUNITY || $write_flag) && !$x[0]['writable']) {
                                q("update contact set writable = 1 where id = %d", intval($x[0]['id']));
                                $x[0]['writable'] = 1;
                            }
                            // if contact's ssl policy changed, which we just determined
                            // is on our own server, update our contact links
                            $ssl_policy = get_config('system', 'ssl_policy');
                            fix_contact_ssl_policy($x[0], $ssl_policy);
                            // If we are setup as a soapbox we aren't accepting top level posts from this person
                            if ($x[0]['page-flags'] == PAGE_SOAPBOX and $top_level) {
                                break;
                            }
                            require_once 'library/simplepie/simplepie.inc';
                            logger('mod-delivery: local delivery');
                            local_delivery($x[0], $atom);
                            break;
                        }
                    }
                    logger('notifier: dfrndelivery: ' . $contact['name']);
                    $deliver_status = dfrn_deliver($owner, $contact, $atom);
                    logger('notifier: dfrn_delivery returns ' . $deliver_status);
                    if ($deliver_status == -1) {
                        logger('notifier: delivery failed: queuing message');
                        // queue message for redelivery
                        add_to_queue($contact['id'], NETWORK_DFRN, $atom);
                    }
                    break;
                case NETWORK_OSTATUS:
                    // Do not send to ostatus if we are not configured to send to public networks
                    if ($owner['prvnets']) {
                        break;
                    }
                    if (get_config('system', 'ostatus_disabled') || get_config('system', 'dfrn_only')) {
                        break;
                    }
                    if ($followup && $contact['notify']) {
                        logger('slapdelivery followup item ' . $item_id . ' to ' . $contact['name']);
                        $deliver_status = slapper($owner, $contact['notify'], $slap);
                        if ($deliver_status == -1) {
                            // queue message for redelivery
                            add_to_queue($contact['id'], NETWORK_OSTATUS, $slap);
                        }
                    } else {
                        // only send salmon if public - e.g. if it's ok to notify
                        // a public hub, it's ok to send a salmon
                        if (count($slaps) && $public_message && !$expire) {
                            logger('slapdelivery item ' . $item_id . ' to ' . $contact['name']);
                            foreach ($slaps as $slappy) {
                                if ($contact['notify']) {
                                    $deliver_status = slapper($owner, $contact['notify'], $slappy);
                                    if ($deliver_status == -1) {
                                        // queue message for redelivery
                                        add_to_queue($contact['id'], NETWORK_OSTATUS, $slappy);
                                    }
                                }
                            }
                        }
                    }
                    break;
                case NETWORK_MAIL:
                case NETWORK_MAIL2:
                    if (get_config('system', 'dfrn_only')) {
                        break;
                    }
                    // WARNING: does not currently convert to RFC2047 header encodings, etc.
                    $addr = $contact['addr'];
                    if (!strlen($addr)) {
                        break;
                    }
                    if ($cmd === 'wall-new' || $cmd === 'comment-new') {
                        $it = null;
                        if ($cmd === 'wall-new') {
                            $it = $items[0];
                        } else {
                            $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($argv[2]), intval($uid));
                            if (count($r)) {
                                $it = $r[0];
                            }
                        }
                        if (!$it) {
                            break;
                        }
                        $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
                        if (!count($local_user)) {
                            break;
                        }
                        $reply_to = '';
                        $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1", intval($uid));
                        if ($r1 && $r1[0]['reply_to']) {
                            $reply_to = $r1[0]['reply_to'];
                        }
                        $subject = $it['title'] ? email_header_encode($it['title'], 'UTF-8') : t("(no subject)");
                        // only expose our real email address to true friends
                        if ($contact['rel'] == CONTACT_IS_FRIEND && !$contact['blocked']) {
                            if ($reply_to) {
                                $headers = 'From: ' . email_header_encode($local_user[0]['username'], 'UTF-8') . ' <' . $reply_to . '>' . "\n";
                                $headers .= 'Sender: ' . $local_user[0]['email'] . "\n";
                            } else {
                                $headers = 'From: ' . email_header_encode($local_user[0]['username'], 'UTF-8') . ' <' . $local_user[0]['email'] . '>' . "\n";
                            }
                        } else {
                            $headers = 'From: ' . email_header_encode($local_user[0]['username'], 'UTF-8') . ' <' . t('noreply') . '@' . $a->get_hostname() . '>' . "\n";
                        }
                        //if($reply_to)
                        //	$headers .= 'Reply-to: ' . $reply_to . "\n";
                        $headers .= 'Message-Id: <' . iri2msgid($it['uri']) . '>' . "\n";
                        if ($it['uri'] !== $it['parent-uri']) {
                            $headers .= "References: <" . iri2msgid($it["parent-uri"]) . ">";
                            // If Threading is enabled, write down the correct parent
                            if ($it["thr-parent"] != "" and $it["thr-parent"] != $it["parent-uri"]) {
                                $headers .= " <" . iri2msgid($it["thr-parent"]) . ">";
                            }
                            $headers .= "\n";
                            if (!$it['title']) {
                                $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($it['parent-uri']), intval($uid));
                                if (count($r) and $r[0]['title'] != '') {
                                    $subject = $r[0]['title'];
                                } else {
                                    $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($it['parent-uri']), intval($uid));
                                    if (count($r) and $r[0]['title'] != '') {
                                        $subject = $r[0]['title'];
                                    }
                                }
                            }
                            if (strncasecmp($subject, 'RE:', 3)) {
                                $subject = 'Re: ' . $subject;
                            }
                        }
                        email_send($addr, $subject, $headers, $it);
                    }
                    break;
                case NETWORK_DIASPORA:
                    if (get_config('system', 'dfrn_only') || !get_config('system', 'diaspora_enabled')) {
                        break;
                    }
                    if ($mail) {
                        diaspora_send_mail($item, $owner, $contact);
                        break;
                    }
                    if (!$normal_mode) {
                        break;
                    }
                    // special handling for followup to public post
                    // all other public posts processed as public batches further below
                    if ($public_message) {
                        if ($followup) {
                            diaspora_send_followup($target_item, $owner, $contact, true);
                        }
                        break;
                    }
                    if (!$contact['pubkey']) {
                        break;
                    }
                    $unsupported_activities = array(ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE);
                    //don't transmit activities which are not supported by diaspora
                    foreach ($unsupported_activities as $act) {
                        if (activity_match($target_item['verb'], $act)) {
                            break 2;
                        }
                    }
                    if ($target_item['deleted'] && ($target_item['uri'] === $target_item['parent-uri'] || $followup)) {
                        // send both top-level retractions and relayable retractions for owner to relay
                        diaspora_send_retraction($target_item, $owner, $contact);
                        break;
                    } elseif ($followup) {
                        // send comments and likes to owner to relay
                        diaspora_send_followup($target_item, $owner, $contact);
                        break;
                    } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
                        // we are the relay - send comments, likes and relayable_retractions
                        // (of comments and likes) to our conversants
                        diaspora_send_relay($target_item, $owner, $contact);
                        break;
                    } elseif ($top_level && !$walltowall) {
                        // currently no workable solution for sending walltowall
                        diaspora_send_status($target_item, $owner, $contact);
                        break;
                    }
                    break;
                case NETWORK_FEED:
                case NETWORK_FACEBOOK:
                    if (get_config('system', 'dfrn_only')) {
                        break;
                    }
                case NETWORK_PUMPIO:
                    if (get_config('system', 'dfrn_only')) {
                        break;
                    }
                default:
                    break;
            }
        }
    }
    // send additional slaps to mentioned remote tags (@foo@example.com)
    //if($slap && count($url_recipients) && ($followup || $top_level) && ($public_message || $push_notify) && (! $expire)) {
    if ($slap && count($url_recipients) && ($public_message || $push_notify) && !$expire) {
        if (!get_config('system', 'dfrn_only')) {
            foreach ($url_recipients as $url) {
                if ($url) {
                    logger('notifier: urldelivery: ' . $url);
                    $deliver_status = slapper($owner, $url, $slap);
                    // TODO: redeliver/queue these items on failure, though there is no contact record
                }
            }
        }
    }
    if ($public_message) {
        if (!$followup) {
            $r0 = diaspora_fetch_relay();
        } else {
            $r0 = array();
        }
        $r1 = q("SELECT DISTINCT(`batch`), `id`, `name`,`network` FROM `contact` WHERE `network` = '%s'\n\t\t\tAND `uid` = %d AND `rel` != %d group by `batch` ORDER BY rand() ", dbesc(NETWORK_DIASPORA), intval($owner['uid']), intval(CONTACT_IS_SHARING));
        $r2 = q("SELECT `id`, `name`,`network` FROM `contact`\n\t\t\tWHERE `network` in ( '%s', '%s')  AND `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0\n\t\t\tAND `rel` != %d order by rand() ", dbesc(NETWORK_DFRN), dbesc(NETWORK_MAIL2), intval($owner['uid']), intval(CONTACT_IS_SHARING));
        $r = array_merge($r2, $r1, $r0);
        if (count($r)) {
            logger('pubdeliver: ' . print_r($r, true), LOGGER_DEBUG);
            // throw everything into the queue in case we get killed
            foreach ($r as $rr) {
                if (!$mail && !$fsuggest && !$followup) {
                    q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )", dbesc($cmd), intval($item_id), intval($rr['id']));
                }
            }
            foreach ($r as $rr) {
                // except for Diaspora batch jobs
                // Don't deliver to folks who have already been delivered to
                if ($rr['network'] !== NETWORK_DIASPORA && in_array($rr['id'], $conversants)) {
                    logger('notifier: already delivered id=' . $rr['id']);
                    continue;
                }
                if (!$mail && !$fsuggest && !$followup) {
                    logger('notifier: delivery agent: ' . $rr['name'] . ' ' . $rr['id']);
                    proc_run('php', 'include/delivery.php', $cmd, $item_id, $rr['id']);
                    if ($interval) {
                        @time_sleep_until(microtime(true) + (double) $interval);
                    }
                }
            }
        }
        $push_notify = true;
    }
    if ($push_notify and strlen($hub)) {
        $hubs = explode(',', $hub);
        if (count($hubs)) {
            foreach ($hubs as $h) {
                $h = trim($h);
                if (!strlen($h)) {
                    continue;
                }
                if ($h === '[internal]') {
                    // Set push flag for PuSH subscribers to this topic,
                    // they will be notified in queue.php
                    q("UPDATE `push_subscriber` SET `push` = 1 " . "WHERE `nickname` = '%s'", dbesc($owner['nickname']));
                    logger('Activating internal PuSH for item ' . $item_id, LOGGER_DEBUG);
                } else {
                    $params = 'hub.mode=publish&hub.url=' . urlencode($a->get_baseurl() . '/dfrn_poll/' . $owner['nickname']);
                    post_url($h, $params);
                    logger('publish for item ' . $item_id . ' ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
                }
                if (count($hubs) > 1) {
                    sleep(7);
                }
                // try and avoid multiple hubs responding at precisely the same time
            }
        }
        // Handling the pubsubhubbub requests
        proc_run('php', 'include/pubsubpublish.php');
    }
    // If the item was deleted, clean up the `sign` table
    if ($target_item['deleted']) {
        $r = q("DELETE FROM sign where `retract_iid` = %d", intval($target_item['id']));
    }
    logger('notifier: calling hooks', LOGGER_DEBUG);
    if ($normal_mode) {
        call_hooks('notifier_normal', $target_item);
    }
    call_hooks('notifier_end', $target_item);
    return;
}
Example #22
0
/**
 * @param App $a
 * @param object $b
 */
function dav_profile_tabs_hook(&$a, &$b)
{
    $b["tabs"][] = array("label" => t('Calendar'), "url" => $a->get_baseurl() . "/dav/wdcal/", "sel" => "", "title" => t('Extended calendar with CalDAV-support'));
}
Example #23
0
if (x($_SESSION, 'authenticated') || x($_POST, 'auth-params') || $a->module === 'login') {
    require "auth.php";
}
$dreamhost_error_hack = 1;
if (x($_GET, 'zrl')) {
    $_SESSION['my_url'] = $_GET['zrl'];
    $a->query_string = preg_replace('/[\\?&]*zrl=(.*?)([\\?&]|$)/is', '', $a->query_string);
}
if (strlen($a->module)) {
    if (file_exists("mod/{$a->module}.php")) {
        include "mod/{$a->module}.php";
        $a->module_loaded = true;
    }
    if (!$a->module_loaded) {
        if (x($_SERVER, 'QUERY_STRING') && $_SERVER['QUERY_STRING'] === 'q=internal_error.html' && isset($dreamhost_error_hack)) {
            goaway($a->get_baseurl() . $_SERVER['REQUEST_URI']);
        }
        header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . t('Not Found'));
        notice(t('Page not found') . EOL);
    }
}
if ($a->module_loaded) {
    $a->page['page_title'] = $a->module;
    if (function_exists($a->module . '_init')) {
        $func = $a->module . '_init';
        $func($a);
    }
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$a->error && function_exists($a->module . '_post') && !x($_POST, 'auth-params')) {
        $func = $a->module . '_post';
        $func($a);
    }