Пример #1
0
function p_init(&$a)
{
    if (argc() < 2) {
        http_status_exit(401);
    }
    $mid = str_replace('.xml', '', argv(1));
    $r = q("select * from item where mid = '%s' and item_wall = 1 and item_private = 0 limit 1", dbesc($mid));
    if (!$r || !perm_is_allowed($r[0]['uid'], '', 'view_stream')) {
        http_status_exit(404);
    }
    $c = q("select * from channel where channel_id = %d limit 1", intval($r[0]['uid']));
    if (!$c) {
        http_status_exit(404);
    }
    $myaddr = $c[0]['channel_address'] . '@' . App::get_hostname();
    $item = $r[0];
    $title = $item['title'];
    $body = bb2diaspora_itembody($item);
    $created = datetime_convert('UTC', 'UTC', $item['created'], 'Y-m-d H:i:s \\U\\T\\C');
    $tpl = get_markup_template('diaspora_post.tpl', 'addon/diaspora');
    $msg = replace_macros($tpl, array('$body' => xmlify($body), '$guid' => $item['mid'], '$handle' => xmlify($myaddr), '$public' => 'true', '$created' => $created, '$provider' => $item['app'] ? $item['app'] : t('$projectname')));
    header('Content-type: text/xml');
    echo $msg;
    killme();
}
Пример #2
0
function pumpio_registerclient($a, $host)
{
    $url = 'https://' . $host . '/api/client/register';
    $params = array();
    $application_name = get_config('pumpio', 'application_name');
    if (!$application_name) {
        $application_name = App::get_hostname();
    }
    $params['type'] = 'client_associate';
    $params['contacts'] = get_config('system', 'admin_email');
    $params['application_type'] = 'native';
    $params['application_name'] = $application_name;
    $params['logo_uri'] = z_root() . '/images/rhash-32.png';
    $params['redirect_uris'] = z_root() . '/pumpio/connect';
    $res = z_post_url($url, $params);
    if ($res['success']) {
        logger('pumpio: registerclient: ' . $res['body'], LOGGER_DATA);
        $values = json_decode($res['body'], true);
        $pumpio = array();
        $pumpio["client_id"] = $values['client_id'];
        $pumpio["client_secret"] = $values['client_secret'];
        //print_r($values);
        return $values;
    }
    return false;
}
Пример #3
0
 public static function run($argc, $argv)
 {
     if ($argc != 2) {
         killme();
     }
     \App::$session->start();
     $_SESSION['authenticated'] = 1;
     $_SESSION['uid'] = $argv[1];
     $x = session_id();
     $f = 'store/[data]/cookie_' . $argv[1];
     $c = 'store/[data]/cookien_' . $argv[1];
     $e = file_exists($f);
     $output = '';
     if ($e) {
         $lines = file($f);
         if ($lines) {
             foreach ($lines as $line) {
                 if (strlen($line) > 0 && $line[0] != '#' && substr_count($line, "\t") == 6) {
                     $tokens = explode("\t", $line);
                     $tokens = array_map('trim', $tokens);
                     if ($tokens[4] > time()) {
                         $output .= $line . "\n";
                     }
                 } else {
                     $output .= $line;
                 }
             }
         }
     }
     $t = time() + 24 * 3600;
     file_put_contents($f, $output . 'HttpOnly_' . \App::get_hostname() . "\tFALSE\t/\tTRUE\t{$t}\tPHPSESSID\t" . $x, $e ? FILE_APPEND : 0);
     file_put_contents($c, $x);
     killme();
 }
Пример #4
0
 function init()
 {
     $uri = urldecode(notags(trim($_GET['uri'])));
     logger('xrd: ' . $uri, LOGGER_DEBUG);
     $resource = $uri;
     if (substr($uri, 0, 4) === 'http') {
         $uri = str_replace('~', '', $uri);
         $name = basename($uri);
     } else {
         $local = str_replace('acct:', '', $uri);
         if (substr($local, 0, 2) == '//') {
             $local = substr($local, 2);
         }
         $name = substr($local, 0, strpos($local, '@'));
     }
     $r = q("SELECT * FROM channel WHERE channel_address = '%s' LIMIT 1", dbesc($name));
     if (!$r) {
         killme();
     }
     $dspr = replace_macros(get_markup_template('xrd_diaspora.tpl'), array('$baseurl' => z_root(), '$dspr_guid' => $r[0]['channel_guid'] . str_replace('.', '', \App::get_hostname()), '$dspr_key' => base64_encode(pemtorsa($r[0]['channel_pubkey']))));
     $salmon_key = salmon_key($r[0]['channel_pubkey']);
     header('Access-Control-Allow-Origin: *');
     header("Content-type: application/xrd+xml");
     $aliases = array('acct:' . channel_reddress($r[0]), z_root() . '/channel/' . $r[0]['channel_address'], z_root() . '/~' . $r[0]['channel_address']);
     for ($x = 0; $x < count($aliases); $x++) {
         if ($aliases[$x] === $resource) {
             unset($aliases[$x]);
         }
     }
     $o = replace_macros(get_markup_template('xrd_person.tpl'), array('$nick' => $r[0]['channel_address'], '$accturi' => $resource, '$aliases' => $aliases, '$profile_url' => z_root() . '/channel/' . $r[0]['channel_address'], '$hcard_url' => z_root() . '/hcard/' . $r[0]['channel_address'], '$atom' => z_root() . '/feed/' . $r[0]['channel_address'], '$zot_post' => z_root() . '/post/' . $r[0]['channel_address'], '$poco_url' => z_root() . '/poco/' . $r[0]['channel_address'], '$photo' => z_root() . '/photo/profile/l/' . $r[0]['channel_id'], '$dspr' => $dspr, '$modexp' => 'data:application/magic-public-key,' . $salmon_key, '$subscribe' => z_root() . '/follow?url={uri}', '$bigkey' => salmon_key($r[0]['channel_pubkey'])));
     $arr = array('user' => $r[0], 'xml' => $o);
     call_hooks('personal_xrd', $arr);
     echo $arr['xml'];
     killme();
 }
Пример #5
0
function push_notifier_process(&$a, &$b)
{
    logger('push_notifier_process');
    if (!$b['normal_mode']) {
        return;
    }
    if ($b['private'] || $b['packet_type'] !== 'undefined' || $b['mail']) {
        return;
    }
    if (!$b['top_level_post']) {
        return;
    }
    // find push_subscribers following this $owner
    $channel = $b['channel'];
    // allow subscriptions either by http or https, as gnu-social has been known to subscribe
    // to the wrong one.
    $r = q("select * from push_subscriber where topic like '%s'", dbesc('%://' . App::get_hostname() . '/feed/' . $channel['channel_address']));
    if (!$r) {
        return;
    }
    foreach ($r as $rr) {
        $feed = get_feed_for($channel, '', array('begin' => $rr['last_update']));
        $hmac_sig = hash_hmac("sha1", $feed, $rr['secret']);
        $slap = array('sig' => $hmac_sig, 'topic' => $rr['topic'], 'body' => $feed);
        // Check for public post and create atom wrapper and stick in queue
        // also need queue driver for 'push' since we need to set some extra headers
        $hash = random_string();
        queue_insert(array('hash' => $hash, 'account_id' => $channel['channel_account_id'], 'channel_id' => $channel['channel_id'], 'driver' => 'push', 'posturl' => $rr['callback_url'], 'notify' => '', 'msg' => json_encode($slap)));
        $b['queued'][] = $hash;
    }
}
Пример #6
0
 function init()
 {
     $tpl = get_markup_template('opensearch.tpl');
     header("Content-type: application/opensearchdescription+xml");
     $o = replace_macros($tpl, array('$baseurl' => z_root(), '$nodename' => \App::get_hostname()));
     echo $o;
     killme();
 }
Пример #7
0
function hubwall_content(&$a)
{
    if (!is_site_admin()) {
        return;
    }
    $title = t('Send email to all hub members.');
    $senders = ['noreply@' . \App::get_hostname() => 'noreply@' . \App::get_hostname(), 'postmaster@' . \App::get_hostname() => 'postmaster@' . \App::get_hostname(), get_config('system', 'admin_email') => get_config('system', 'admin_email')];
    $o = replace_macros(get_markup_template('hubwall_form.tpl', 'addon/hubwall/'), array('$title' => $title, '$text' => htmlspecialchars($_REQUEST['text']), '$subject' => array('subject', t('Message subject'), $_REQUEST['subject'], ''), '$sender' => array('sender', t('Sender Email address'), $_REQUEST['sender'] ? $_REQUEST['sender'] : 'noreply@' . \App::get_hostname(), '', $senders), '$test' => array('test', t('Test mode (only send to hub administrator)'), array_key_exists('test', $_REQUEST) ? intval($_REQUEST['test']) : 0, ''), '$submit' => t('Submit')));
    return $o;
}
Пример #8
0
function dfedfix_personal_xrd(&$a, &$b)
{
    logger('dfedfix: ' . print_r($b, true));
    $x = $b['xml'];
    $x = str_replace('</Subject>', '</Subject>
<Alias>' . z_root() . '/channel/' . $b['user']['channel_address'] . '</Alias>', $x);
    $x = str_replace('.AQAB" />', '.AQAB "/>
<Link rel="salmon" href="' . z_root() . '/receive/users/' . $b['user']['channel_guid'] . str_replace('.', '', App::get_hostname()) . '"/>', $x);
    $b['xml'] = $x;
}
Пример #9
0
 function init()
 {
     header('Access-Control-Allow-Origin: *');
     header("Content-type: application/xrd+xml");
     logger('hostxrd', LOGGER_DEBUG);
     $tpl = get_markup_template('xrd_host.tpl');
     $x = replace_macros(get_markup_template('xrd_host.tpl'), array('$zhost' => \App::get_hostname(), '$zroot' => z_root()));
     $arr = array('xrd' => $x);
     call_hooks('hostxrd', $arr);
     echo $arr['xrd'];
     killme();
 }
Пример #10
0
function mailhost_addon_settings(&$a, &$s)
{
    if (!local_channel()) {
        return;
    }
    /* Add our stylesheet to the page so we can make our settings look nice */
    //head_add_css('/addon/mailhost/mailhost.css');
    $mailhost = get_pconfig(local_channel(), 'system', 'email_notify_host');
    if (!$mailhost) {
        $mailhost = App::get_hostname();
    }
    $sc .= replace_macros(get_markup_template('field_input.tpl'), array('$field' => array('mailhost-mailhost', t('Email notification hub'), $mailhost, t('Hostname'))));
    $s .= replace_macros(get_markup_template('generic_addon_settings.tpl'), array('$addon' => array('mailhost', t('Mailhost Settings'), '', t('Submit')), '$content' => $sc));
    return;
}
Пример #11
0
 function get()
 {
     if (!is_site_admin()) {
         return;
     }
     $o = '';
     $r = q("select * from channel where channel_removed = 0");
     $sitekey = get_config('system', 'pubkey');
     if ($r) {
         foreach ($r as $rr) {
             $found = false;
             $primary_address = '';
             $x = zot_get_hublocs($rr['channel_hash']);
             if ($x) {
                 foreach ($x as $xx) {
                     if ($xx['hubloc_url'] === z_root() && $xx['hubloc_sitekey'] === $sitekey) {
                         $found = true;
                         break;
                     }
                 }
                 if ($found) {
                     $o .= 'Hubloc exists for ' . $rr['channel_name'] . EOL;
                     continue;
                 }
             }
             $y = q("select xchan_addr from xchan where xchan_hash = '%s' limit 1", dbesc($rr['channel_hash']));
             if ($y) {
                 $primary_address = $y[0]['xchan_addr'];
             }
             $hub_address = $rr['channel']['channel_address'] . '@' . \App::get_hostname();
             $primary = $hub_address === $primary_address ? 1 : 0;
             if (!$y) {
                 $primary = 1;
             }
             $m = q("delete from hubloc where hubloc_hash = '%s' and hubloc_url = '%s' ", dbesc($rr['channel_hash']), dbesc(z_root()));
             // Create a verified hub location pointing to this site.
             $h = q("insert into hubloc ( hubloc_guid, hubloc_guid_sig, hubloc_hash, hubloc_addr, hubloc_primary, hubloc_url, hubloc_url_sig, hubloc_host, hubloc_callback, hubloc_sitekey, hubloc_network )\n\t\t\t\t\tvalues ( '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s' )", dbesc($rr['channel_guid']), dbesc($rr['channel_guid_sig']), dbesc($rr['channel_hash']), dbesc($rr['channel_address'] . '@' . \App::get_hostname()), intval($primary), dbesc(z_root()), dbesc(base64url_encode(rsa_sign(z_root(), $rr['channel_prvkey']))), dbesc(\App::get_hostname()), dbesc(z_root() . '/post'), dbesc($sitekey), dbesc('zot'));
             if ($h) {
                 $o . 'local hubloc created for ' . $rr['channel_name'] . EOL;
             } else {
                 $o .= 'DB update failed for ' . $rr['channel_name'] . EOL;
             }
         }
         return $o;
     }
 }
Пример #12
0
 function init()
 {
     $gc_probability = 50;
     ini_set('session.gc_probability', $gc_probability);
     ini_set('session.use_only_cookies', 1);
     ini_set('session.cookie_httponly', 1);
     /*
      * Set our session storage functions.
      */
     $handler = new \Zotlabs\Web\SessionHandler();
     self::$handler = $handler;
     $x = session_set_save_handler($handler, false);
     if (!$x) {
         logger('Session save handler initialisation failed.', LOGGER_NORMAL, LOG_ERR);
     }
     // Force cookies to be secure (https only) if this site is SSL enabled.
     // Must be done before session_start().
     $arr = session_get_cookie_params();
     session_set_cookie_params(isset($arr['lifetime']) ? $arr['lifetime'] : 0, isset($arr['path']) ? $arr['path'] : '/', isset($arr['domain']) ? $arr['domain'] : App::get_hostname(), isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? true : false, isset($arr['httponly']) ? $arr['httponly'] : true);
     register_shutdown_function('session_write_close');
 }
Пример #13
0
function diaspora_load()
{
    register_hook('notifier_hub', 'addon/diaspora/diaspora.php', 'diaspora_process_outbound');
    register_hook('notifier_process', 'addon/diaspora/diaspora.php', 'diaspora_notifier_process');
    register_hook('permissions_create', 'addon/diaspora/diaspora.php', 'diaspora_permissions_create');
    register_hook('permissions_update', 'addon/diaspora/diaspora.php', 'diaspora_permissions_update');
    register_hook('module_loaded', 'addon/diaspora/diaspora.php', 'diaspora_load_module');
    register_hook('follow_allow', 'addon/diaspora/diaspora.php', 'diaspora_follow_allow');
    register_hook('feature_settings_post', 'addon/diaspora/diaspora.php', 'diaspora_feature_settings_post');
    register_hook('feature_settings', 'addon/diaspora/diaspora.php', 'diaspora_feature_settings');
    register_hook('post_local', 'addon/diaspora/diaspora.php', 'diaspora_post_local');
    register_hook('well_known', 'addon/diaspora/diaspora.php', 'diaspora_well_known');
    register_hook('create_identity', 'addon/diaspora/diaspora.php', 'diaspora_create_identity');
    if (!get_config('diaspora', 'relay_handle')) {
        $x = import_author_diaspora(array('address' => '*****@*****.**'));
        if ($x) {
            set_config('diaspora', 'relay_handle', $x);
            // Now register
            $url = "http://the-federation.info/register/" . App::get_hostname();
            $ret = z_fetch_url($url);
        }
    }
}
Пример #14
0
function connect_post(&$a)
{
    if (!array_key_exists('channel', App::$data)) {
        return;
    }
    $edit = local_channel() && local_channel() == App::$data['channel']['channel_id'] ? true : false;
    if ($edit) {
        $has_premium = App::$data['channel']['channel_pageflags'] & PAGE_PREMIUM ? 1 : 0;
        $premium = $_POST['premium'] ? intval($_POST['premium']) : 0;
        $text = escape_tags($_POST['text']);
        if ($has_premium != $premium) {
            $r = q("update channel set channel_pageflags = ( channel_pageflags %s %d ) where channel_id = %d", db_getfunc('^'), intval(PAGE_PREMIUM), intval(local_channel()));
            proc_run('php', 'include/notifier.php', 'refresh_all', App::$data['channel']['channel_id']);
        }
        set_pconfig(App::$data['channel']['channel_id'], 'system', 'selltext', $text);
        // reload the page completely to get fresh data
        goaway(z_root() . '/' . App::$query_string);
    }
    $url = '';
    $observer = App::get_observer();
    if ($observer && $_POST['submit'] === t('Continue')) {
        if ($observer['xchan_follow']) {
            $url = sprintf($observer['xchan_follow'], urlencode(App::$data['channel']['channel_address'] . '@' . App::get_hostname()));
        }
        if (!$url) {
            $r = q("select * from hubloc where hubloc_hash = '%s' order by hubloc_id desc limit 1", dbesc($observer['xchan_hash']));
            if ($r) {
                $url = $r[0]['hubloc_url'] . '/follow?f=&url=' . urlencode(App::$data['channel']['channel_address'] . '@' . App::get_hostname());
            }
        }
    }
    if ($url) {
        goaway($url . '&confirm=1');
    } else {
        notice('Unable to connect to your home hub location.');
    }
}
Пример #15
0
function hubwall_post(&$a)
{
    if (!is_site_admin()) {
        return;
    }
    $text = trim($_REQUEST['text']);
    if (!$text) {
        return;
    }
    $sender_name = t('Hub Administrator');
    $sender_email = 'sys@' . App::get_hostname();
    $subject = $_REQUEST['subject'];
    $textversion = strip_tags(html_entity_decode(bbcode(stripslashes(str_replace(array("\\r", "\\n"), array("", "\n"), $text))), ENT_QUOTES, 'UTF-8'));
    $htmlversion = bbcode(stripslashes(str_replace(array("\\r", "\\n"), array("", "<br />\n"), $text)));
    $sql_extra = intval($_REQUEST['test']) ? sprintf(" and account_email = '%s' ", get_config('system', 'admin_email')) : '';
    $recips = q("select account_email from account where account_flags = %d {$sql_extra}", intval(ACCOUNT_OK));
    if (!$recips) {
        notice(t('No recipients found.') . EOL);
        return;
    }
    foreach ($recips as $recip) {
        \Zotlabs\Lib\Enotify::send(array('fromName' => $sender_name, 'fromEmail' => $sender_email, 'replyTo' => $sender_email, 'toEmail' => $recip['account_email'], 'messageSubject' => $subject, 'htmlVersion' => $htmlversion, 'textVersion' => $textversion));
    }
}
Пример #16
0
function channel_reddress($channel)
{
    if (!($channel && array_key_exists('channel_address', $channel))) {
        return '';
    }
    return strtolower($channel['channel_address'] . '@' . App::get_hostname());
}
Пример #17
0
 function get()
 {
     require_once 'include/acl_selectors.php';
     require_once 'include/permissions.php';
     $yes_no = array(t('No'), t('Yes'));
     $p = q("SELECT * FROM `profile` WHERE `is_default` = 1 AND `uid` = %d LIMIT 1", intval(local_channel()));
     if (count($p)) {
         $profile = $p[0];
     }
     load_pconfig(local_channel(), 'expire');
     $channel = \App::get_channel();
     $global_perms = \Zotlabs\Access\Permissions::Perms();
     $permiss = array();
     $perm_opts = array(array(t('Nobody except yourself'), 0), array(t('Only those you specifically allow'), PERMS_SPECIFIC), array(t('Approved connections'), PERMS_CONTACTS), array(t('Any connections'), PERMS_PENDING), array(t('Anybody on this website'), PERMS_SITE), array(t('Anybody in this network'), PERMS_NETWORK), array(t('Anybody authenticated'), PERMS_AUTHED), array(t('Anybody on the internet'), PERMS_PUBLIC));
     $limits = \Zotlabs\Access\PermissionLimits::Get(local_channel());
     foreach ($global_perms as $k => $perm) {
         $options = array();
         foreach ($perm_opts as $opt) {
             if (!strstr($k, 'view') && $opt[1] == PERMS_PUBLIC) {
                 continue;
             }
             $options[$opt[1]] = $opt[0];
         }
         $permiss[] = array($k, $perm, $limits[$k], '', $options);
     }
     $username = $channel['channel_name'];
     $nickname = $channel['channel_address'];
     $timezone = $channel['channel_timezone'];
     $notify = $channel['channel_notifyflags'];
     $defloc = $channel['channel_location'];
     $maxreq = $channel['channel_max_friend_req'];
     $expire = $channel['channel_expire_days'];
     $adult_flag = intval($channel['channel_pageflags'] & PAGE_ADULT);
     $sys_expire = get_config('system', 'default_expire_days');
     //		$unkmail    = \App::$user['unkmail'];
     //		$cntunkmail = \App::$user['cntunkmail'];
     $hide_presence = intval(get_pconfig(local_channel(), 'system', 'hide_online_status'));
     $expire_items = get_pconfig(local_channel(), 'expire', 'items');
     $expire_items = $expire_items === false ? '1' : $expire_items;
     // default if not set: 1
     $expire_notes = get_pconfig(local_channel(), 'expire', 'notes');
     $expire_notes = $expire_notes === false ? '1' : $expire_notes;
     // default if not set: 1
     $expire_starred = get_pconfig(local_channel(), 'expire', 'starred');
     $expire_starred = $expire_starred === false ? '1' : $expire_starred;
     // default if not set: 1
     $expire_photos = get_pconfig(local_channel(), 'expire', 'photos');
     $expire_photos = $expire_photos === false ? '0' : $expire_photos;
     // default if not set: 0
     $expire_network_only = get_pconfig(local_channel(), 'expire', 'network_only');
     $expire_network_only = $expire_network_only === false ? '0' : $expire_network_only;
     // default if not set: 0
     $suggestme = get_pconfig(local_channel(), 'system', 'suggestme');
     $suggestme = $suggestme === false ? '0' : $suggestme;
     // default if not set: 0
     $post_newfriend = get_pconfig(local_channel(), 'system', 'post_newfriend');
     $post_newfriend = $post_newfriend === false ? '0' : $post_newfriend;
     // default if not set: 0
     $post_joingroup = get_pconfig(local_channel(), 'system', 'post_joingroup');
     $post_joingroup = $post_joingroup === false ? '0' : $post_joingroup;
     // default if not set: 0
     $post_profilechange = get_pconfig(local_channel(), 'system', 'post_profilechange');
     $post_profilechange = $post_profilechange === false ? '0' : $post_profilechange;
     // default if not set: 0
     $blocktags = get_pconfig(local_channel(), 'system', 'blocktags');
     $blocktags = $blocktags === false ? '0' : $blocktags;
     $timezone = date_default_timezone_get();
     $opt_tpl = get_markup_template("field_checkbox.tpl");
     if (get_config('system', 'publish_all')) {
         $profile_in_dir = '<input type="hidden" name="profile_in_directory" value="1" />';
     } else {
         $profile_in_dir = replace_macros($opt_tpl, array('$field' => array('profile_in_directory', t('Publish your default profile in the network directory'), $profile['publish'], '', $yes_no)));
     }
     $suggestme = replace_macros($opt_tpl, array('$field' => array('suggestme', t('Allow us to suggest you as a potential friend to new members?'), $suggestme, '', $yes_no)));
     $subdir = strlen(\App::get_path()) ? '<br />' . t('or') . ' ' . z_root() . '/channel/' . $nickname : '';
     $tpl_addr = get_markup_template("settings_nick_set.tpl");
     $prof_addr = replace_macros($tpl_addr, array('$desc' => t('Your channel address is'), '$nickname' => $nickname, '$subdir' => $subdir, '$basepath' => \App::get_hostname()));
     $stpl = get_markup_template('settings.tpl');
     $acl = new \Zotlabs\Access\AccessList($channel);
     $perm_defaults = $acl->get();
     require_once 'include/group.php';
     $group_select = mini_group_select(local_channel(), $channel['channel_default_group']);
     require_once 'include/menu.php';
     $m1 = menu_list(local_channel());
     $menu = false;
     if ($m1) {
         $menu = array();
         $current = get_pconfig(local_channel(), 'system', 'channel_menu');
         $menu[] = array('name' => '', 'selected' => !$current ? true : false);
         foreach ($m1 as $m) {
             $menu[] = array('name' => htmlspecialchars($m['menu_name'], ENT_COMPAT, 'UTF-8'), 'selected' => $m['menu_name'] === $current ? ' selected="selected" ' : false);
         }
     }
     $evdays = get_pconfig(local_channel(), 'system', 'evdays');
     if (!$evdays) {
         $evdays = 3;
     }
     $permissions_role = get_pconfig(local_channel(), 'system', 'permissions_role');
     if (!$permissions_role) {
         $permissions_role = 'custom';
     }
     $permissions_set = $permissions_role != 'custom' ? true : false;
     $perm_roles = \Zotlabs\Access\PermissionRoles::roles();
     if (get_account_techlevel() < 4 && $permissions_role !== 'custom') {
         unset($perm_roles[t('Other')]);
     }
     $vnotify = get_pconfig(local_channel(), 'system', 'vnotify');
     $always_show_in_notices = get_pconfig(local_channel(), 'system', 'always_show_in_notices');
     if ($vnotify === false) {
         $vnotify = -1;
     }
     $o .= replace_macros($stpl, array('$ptitle' => t('Channel Settings'), '$submit' => t('Submit'), '$baseurl' => z_root(), '$uid' => local_channel(), '$form_security_token' => get_form_security_token("settings"), '$nickname_block' => $prof_addr, '$h_basic' => t('Basic Settings'), '$username' => array('username', t('Full Name:'), $username, ''), '$email' => array('email', t('Email Address:'), $email, ''), '$timezone' => array('timezone_select', t('Your Timezone:'), $timezone, '', get_timezones()), '$defloc' => array('defloc', t('Default Post Location:'), $defloc, t('Geographical location to display on your posts')), '$allowloc' => array('allow_location', t('Use Browser Location:'), get_pconfig(local_channel(), 'system', 'use_browser_location') ? 1 : '', '', $yes_no), '$adult' => array('adult', t('Adult Content'), $adult_flag, t('This channel frequently or regularly publishes adult content. (Please tag any adult material and/or nudity with #NSFW)'), $yes_no), '$h_prv' => t('Security and Privacy Settings'), '$permissions_set' => $permissions_set, '$server_role' => \Zotlabs\Lib\System::get_server_role(), '$perms_set_msg' => t('Your permissions are already configured. Click to view/adjust'), '$hide_presence' => array('hide_presence', t('Hide my online presence'), $hide_presence, t('Prevents displaying in your profile that you are online'), $yes_no), '$lbl_pmacro' => t('Simple Privacy Settings:'), '$pmacro3' => t('Very Public - <em>extremely permissive (should be used with caution)</em>'), '$pmacro2' => t('Typical - <em>default public, privacy when desired (similar to social network permissions but with improved privacy)</em>'), '$pmacro1' => t('Private - <em>default private, never open or public</em>'), '$pmacro0' => t('Blocked - <em>default blocked to/from everybody</em>'), '$permiss_arr' => $permiss, '$blocktags' => array('blocktags', t('Allow others to tag your posts'), 1 - $blocktags, t('Often used by the community to retro-actively flag inappropriate content'), $yes_no), '$lbl_p2macro' => t('Channel Permission Limits'), '$expire' => array('expire', t('Expire other channel content after this many days'), $expire, t('0 or blank to use the website limit.') . ' ' . (intval($sys_expire) ? sprintf(t('This website expires after %d days.'), intval($sys_expire)) : t('This website does not expire imported content.')) . ' ' . t('The website limit takes precedence if lower than your limit.')), '$maxreq' => array('maxreq', t('Maximum Friend Requests/Day:'), intval($channel['channel_max_friend_req']), t('May reduce spam activity')), '$permissions' => t('Default Access Control List (ACL)'), '$permdesc' => t("(click to open/close)"), '$aclselect' => populate_acl($perm_defaults, false, \Zotlabs\Lib\PermissionDescription::fromDescription(t('Use my default audience setting for the type of object published'))), '$allow_cid' => acl2json($perm_defaults['allow_cid']), '$allow_gid' => acl2json($perm_defaults['allow_gid']), '$deny_cid' => acl2json($perm_defaults['deny_cid']), '$deny_gid' => acl2json($perm_defaults['deny_gid']), '$suggestme' => $suggestme, '$group_select' => $group_select, '$role' => array('permissions_role', t('Channel permissions category:'), $permissions_role, '', $perm_roles), '$profile_in_dir' => $profile_in_dir, '$hide_friends' => $hide_friends, '$hide_wall' => $hide_wall, '$unkmail' => $unkmail, '$cntunkmail' => array('cntunkmail', t('Maximum private messages per day from unknown people:'), intval($channel['channel_max_anon_mail']), t("Useful to reduce spamming")), '$h_not' => t('Notification Settings'), '$activity_options' => t('By default post a status message when:'), '$post_newfriend' => array('post_newfriend', t('accepting a friend request'), $post_newfriend, '', $yes_no), '$post_joingroup' => array('post_joingroup', t('joining a forum/community'), $post_joingroup, '', $yes_no), '$post_profilechange' => array('post_profilechange', t('making an <em>interesting</em> profile change'), $post_profilechange, '', $yes_no), '$lbl_not' => t('Send a notification email when:'), '$notify1' => array('notify1', t('You receive a connection request'), $notify & NOTIFY_INTRO, NOTIFY_INTRO, '', $yes_no), '$notify2' => array('notify2', t('Your connections are confirmed'), $notify & NOTIFY_CONFIRM, NOTIFY_CONFIRM, '', $yes_no), '$notify3' => array('notify3', t('Someone writes on your profile wall'), $notify & NOTIFY_WALL, NOTIFY_WALL, '', $yes_no), '$notify4' => array('notify4', t('Someone writes a followup comment'), $notify & NOTIFY_COMMENT, NOTIFY_COMMENT, '', $yes_no), '$notify5' => array('notify5', t('You receive a private message'), $notify & NOTIFY_MAIL, NOTIFY_MAIL, '', $yes_no), '$notify6' => array('notify6', t('You receive a friend suggestion'), $notify & NOTIFY_SUGGEST, NOTIFY_SUGGEST, '', $yes_no), '$notify7' => array('notify7', t('You are tagged in a post'), $notify & NOTIFY_TAGSELF, NOTIFY_TAGSELF, '', $yes_no), '$notify8' => array('notify8', t('You are poked/prodded/etc. in a post'), $notify & NOTIFY_POKE, NOTIFY_POKE, '', $yes_no), '$lbl_vnot' => t('Show visual notifications including:'), '$vnotify1' => array('vnotify1', t('Unseen grid activity'), $vnotify & VNOTIFY_NETWORK, VNOTIFY_NETWORK, '', $yes_no), '$vnotify2' => array('vnotify2', t('Unseen channel activity'), $vnotify & VNOTIFY_CHANNEL, VNOTIFY_CHANNEL, '', $yes_no), '$vnotify3' => array('vnotify3', t('Unseen private messages'), $vnotify & VNOTIFY_MAIL, VNOTIFY_MAIL, t('Recommended'), $yes_no), '$vnotify4' => array('vnotify4', t('Upcoming events'), $vnotify & VNOTIFY_EVENT, VNOTIFY_EVENT, '', $yes_no), '$vnotify5' => array('vnotify5', t('Events today'), $vnotify & VNOTIFY_EVENTTODAY, VNOTIFY_EVENTTODAY, '', $yes_no), '$vnotify6' => array('vnotify6', t('Upcoming birthdays'), $vnotify & VNOTIFY_BIRTHDAY, VNOTIFY_BIRTHDAY, t('Not available in all themes'), $yes_no), '$vnotify7' => array('vnotify7', t('System (personal) notifications'), $vnotify & VNOTIFY_SYSTEM, VNOTIFY_SYSTEM, '', $yes_no), '$vnotify8' => array('vnotify8', t('System info messages'), $vnotify & VNOTIFY_INFO, VNOTIFY_INFO, t('Recommended'), $yes_no), '$vnotify9' => array('vnotify9', t('System critical alerts'), $vnotify & VNOTIFY_ALERT, VNOTIFY_ALERT, t('Recommended'), $yes_no), '$vnotify10' => array('vnotify10', t('New connections'), $vnotify & VNOTIFY_INTRO, VNOTIFY_INTRO, t('Recommended'), $yes_no), '$vnotify11' => array('vnotify11', t('System Registrations'), $vnotify & VNOTIFY_REGISTER, VNOTIFY_REGISTER, '', $yes_no), '$always_show_in_notices' => array('always_show_in_notices', t('Also show new wall posts, private messages and connections under Notices'), $always_show_in_notices, 1, '', $yes_no), '$evdays' => array('evdays', t('Notify me of events this many days in advance'), $evdays, t('Must be greater than 0')), '$h_advn' => t('Advanced Account/Page Type Settings'), '$h_descadvn' => t('Change the behaviour of this account for special situations'), '$pagetype' => $pagetype, '$lbl_misc' => t('Miscellaneous Settings'), '$photo_path' => array('photo_path', t('Default photo upload folder'), get_pconfig(local_channel(), 'system', 'photo_path'), t('%Y - current year, %m -  current month')), '$attach_path' => array('attach_path', t('Default file upload folder'), get_pconfig(local_channel(), 'system', 'attach_path'), t('%Y - current year, %m -  current month')), '$menus' => $menu, '$menu_desc' => t('Personal menu to display in your channel pages'), '$removeme' => t('Remove Channel'), '$removechannel' => t('Remove this channel.'), '$firefoxshare' => t('Firefox Share $Projectname provider'), '$cal_first_day' => array('first_day', t('Start calendar week on monday'), get_pconfig(local_channel(), 'system', 'cal_first_day') ? 1 : '', '', $yes_no)));
     call_hooks('settings_form', $o);
     //$o .= '</form>' . "\r\n";
     return $o;
 }
Пример #18
0
/**
 * @param  App $a
 * @return string
 */
function admin_page_site(&$a)
{
    /* Installed langs */
    $lang_choices = array();
    $langs = glob('view/*/strings.php');
    if (is_array($langs) && count($langs)) {
        if (!in_array('view/en/strings.php', $langs)) {
            $langs[] = 'view/en/';
        }
        asort($langs);
        foreach ($langs as $l) {
            $t = explode("/", $l);
            $lang_choices[$t[1]] = $t[1];
        }
    }
    /* Installed themes */
    $theme_choices = array();
    $theme_choices_mobile = array();
    $theme_choices_mobile["---"] = t("No special theme for mobile devices");
    $files = glob('view/theme/*');
    if ($files) {
        foreach ($files as $file) {
            $f = basename($file);
            $theme_name = file_exists($file . '/experimental') ? sprintf("%s - (Experimental)", $f) : $f;
            if (file_exists($file . '/mobile')) {
                $theme_choices_mobile[$f] = $theme_name;
            } else {
                $theme_choices[$f] = $theme_name;
            }
        }
    }
    /* Community page style */
    $community_page_style_choices = array(CP_NO_COMMUNITY_PAGE => t("No community page"), CP_USERS_ON_SERVER => t("Public postings from users of this site"), CP_GLOBAL_COMMUNITY => t("Global community page"));
    /* OStatus conversation poll choices */
    $ostatus_poll_choices = array("-2" => t("Never"), "-1" => t("At post arrival"), "0" => t("Frequently"), "60" => t("Hourly"), "720" => t("Twice daily"), "1440" => t("Daily"));
    /* get user names to make the install a personal install of X */
    $user_names = array();
    $user_names['---'] = t('Multi user instance');
    $users = q("SELECT username, nickname FROM `user`");
    foreach ($users as $user) {
        $user_names[$user['nickname']] = $user['username'];
    }
    /* Banner */
    $banner = get_config('system', 'banner');
    if ($banner == false) {
        $banner = '<a href="http://friendica.com"><img id="logo-img" src="images/friendica-32.png" alt="logo" /></a><span id="logo-text"><a href="http://friendica.com">Friendica</a></span>';
    }
    $banner = htmlspecialchars($banner);
    $info = get_config('config', 'info');
    $info = htmlspecialchars($info);
    // Automatically create temporary paths
    get_temppath();
    get_lockpath();
    get_itemcachepath();
    //echo "<pre>"; var_dump($lang_choices); die("</pre>");
    /* Register policy */
    $register_choices = array(REGISTER_CLOSED => t("Closed"), REGISTER_APPROVE => t("Requires approval"), REGISTER_OPEN => t("Open"));
    $ssl_choices = array(SSL_POLICY_NONE => t("No SSL policy, links will track page SSL state"), SSL_POLICY_FULL => t("Force all links to use SSL"), SSL_POLICY_SELFSIGN => t("Self-signed certificate, use SSL for local links only (discouraged)"));
    if ($a->config['hostname'] == "") {
        $a->config['hostname'] = $a->get_hostname();
    }
    $t = get_markup_template("admin_site.tpl");
    return replace_macros($t, array('$title' => t('Administration'), '$page' => t('Site'), '$submit' => t('Save Settings'), '$registration' => t('Registration'), '$upload' => t('File upload'), '$corporate' => t('Policies'), '$advanced' => t('Advanced'), '$performance' => t('Performance'), '$relocate' => t('Relocate - WARNING: advanced function. Could make this server unreachable.'), '$baseurl' => $a->get_baseurl(true), '$sitename' => array('sitename', t("Site name"), htmlentities($a->config['sitename'], ENT_QUOTES), 'UTF-8'), '$hostname' => array('hostname', t("Host name"), $a->config['hostname'], ""), '$sender_email' => array('sender_email', t("Sender Email"), $a->config['sender_email'], "The email address your server shall use to send notification emails from.", "", "", "email"), '$banner' => array('banner', t("Banner/Logo"), $banner, ""), '$shortcut_icon' => array('shortcut_icon', t("Shortcut icon"), get_config('system', 'shortcut_icon'), "Link to an icon that will be used for browsers."), '$touch_icon' => array('touch_icon', t("Touch icon"), get_config('system', 'touch_icon'), "Link to an icon that will be used for tablets and mobiles."), '$info' => array('info', t('Additional Info'), $info, t('For public servers: you can add additional information here that will be listed at dir.friendica.com/siteinfo.')), '$language' => array('language', t("System language"), get_config('system', 'language'), "", $lang_choices), '$theme' => array('theme', t("System theme"), get_config('system', 'theme'), t("Default system theme - may be over-ridden by user profiles - <a href='#' id='cnftheme'>change theme settings</a>"), $theme_choices), '$theme_mobile' => array('theme_mobile', t("Mobile system theme"), get_config('system', 'mobile-theme'), t("Theme for mobile devices"), $theme_choices_mobile), '$ssl_policy' => array('ssl_policy', t("SSL link policy"), (string) intval(get_config('system', 'ssl_policy')), t("Determines whether generated links should be forced to use SSL"), $ssl_choices), '$force_ssl' => array('force_ssl', t("Force SSL"), get_config('system', 'force_ssl'), t("Force all Non-SSL requests to SSL - Attention: on some systems it could lead to endless loops.")), '$old_share' => array('old_share', t("Old style 'Share'"), get_config('system', 'old_share'), t("Deactivates the bbcode element 'share' for repeating items.")), '$hide_help' => array('hide_help', t("Hide help entry from navigation menu"), get_config('system', 'hide_help'), t("Hides the menu entry for the Help pages from the navigation menu. You can still access it calling /help directly.")), '$singleuser' => array('singleuser', t("Single user instance"), get_config('system', 'singleuser'), t("Make this instance multi-user or single-user for the named user"), $user_names), '$maximagesize' => array('maximagesize', t("Maximum image size"), get_config('system', 'maximagesize'), t("Maximum size in bytes of uploaded images. Default is 0, which means no limits.")), '$maximagelength' => array('maximagelength', t("Maximum image length"), get_config('system', 'max_image_length'), t("Maximum length in pixels of the longest side of uploaded images. Default is -1, which means no limits.")), '$jpegimagequality' => array('jpegimagequality', t("JPEG image quality"), get_config('system', 'jpeg_quality'), t("Uploaded JPEGS will be saved at this quality setting [0-100]. Default is 100, which is full quality.")), '$register_policy' => array('register_policy', t("Register policy"), $a->config['register_policy'], "", $register_choices), '$daily_registrations' => array('max_daily_registrations', t("Maximum Daily Registrations"), get_config('system', 'max_daily_registrations'), t("If registration is permitted above, this sets the maximum number of new user registrations to accept per day.  If register is set to closed, this setting has no effect.")), '$register_text' => array('register_text', t("Register text"), htmlentities($a->config['register_text'], ENT_QUOTES, 'UTF-8'), t("Will be displayed prominently on the registration page.")), '$abandon_days' => array('abandon_days', t('Accounts abandoned after x days'), get_config('system', 'account_abandon_days'), t('Will not waste system resources polling external sites for abandonded accounts. Enter 0 for no time limit.')), '$allowed_sites' => array('allowed_sites', t("Allowed friend domains"), get_config('system', 'allowed_sites'), t("Comma separated list of domains which are allowed to establish friendships with this site. Wildcards are accepted. Empty to allow any domains")), '$allowed_email' => array('allowed_email', t("Allowed email domains"), get_config('system', 'allowed_email'), t("Comma separated list of domains which are allowed in email addresses for registrations to this site. Wildcards are accepted. Empty to allow any domains")), '$block_public' => array('block_public', t("Block public"), get_config('system', 'block_public'), t("Check to block public access to all otherwise public personal pages on this site unless you are currently logged in.")), '$force_publish' => array('publish_all', t("Force publish"), get_config('system', 'publish_all'), t("Check to force all profiles on this site to be listed in the site directory.")), '$global_directory' => array('directory_submit_url', t("Global directory update URL"), get_config('system', 'directory_submit_url'), t("URL to update the global directory. If this is not set, the global directory is completely unavailable to the application.")), '$thread_allow' => array('thread_allow', t("Allow threaded items"), get_config('system', 'thread_allow'), t("Allow infinite level threading for items on this site.")), '$newuser_private' => array('newuser_private', t("Private posts by default for new users"), get_config('system', 'newuser_private'), t("Set default post permissions for all new members to the default privacy group rather than public.")), '$enotify_no_content' => array('enotify_no_content', t("Don't include post content in email notifications"), get_config('system', 'enotify_no_content'), t("Don't include the content of a post/comment/private message/etc. in the email notifications that are sent out from this site, as a privacy measure.")), '$private_addons' => array('private_addons', t("Disallow public access to addons listed in the apps menu."), get_config('config', 'private_addons'), t("Checking this box will restrict addons listed in the apps menu to members only.")), '$disable_embedded' => array('disable_embedded', t("Don't embed private images in posts"), get_config('system', 'disable_embedded'), t("Don't replace locally-hosted private photos in posts with an embedded copy of the image. This means that contacts who receive posts containing private photos will have to authenticate and load each image, which may take a while.")), '$allow_users_remote_self' => array('allow_users_remote_self', t('Allow Users to set remote_self'), get_config('system', 'allow_users_remote_self'), t('With checking this, every user is allowed to mark every contact as a remote_self in the repair contact dialog. Setting this flag on a contact causes mirroring every posting of that contact in the users stream.')), '$no_multi_reg' => array('no_multi_reg', t("Block multiple registrations"), get_config('system', 'block_extended_register'), t("Disallow users to register additional accounts for use as pages.")), '$no_openid' => array('no_openid', t("OpenID support"), !get_config('system', 'no_openid'), t("OpenID support for registration and logins.")), '$no_regfullname' => array('no_regfullname', t("Fullname check"), !get_config('system', 'no_regfullname'), t("Force users to register with a space between firstname and lastname in Full name, as an antispam measure")), '$no_utf' => array('no_utf', t("UTF-8 Regular expressions"), !get_config('system', 'no_utf'), t("Use PHP UTF8 regular expressions")), '$community_page_style' => array('community_page_style', t("Community Page Style"), get_config('system', 'community_page_style'), t("Type of community page to show. 'Global community' shows every public posting from an open distributed network that arrived on this server."), $community_page_style_choices), '$max_author_posts_community_page' => array('max_author_posts_community_page', t("Posts per user on community page"), get_config('system', 'max_author_posts_community_page'), t("The maximum number of posts per user on the community page. (Not valid for 'Global Community')")), '$ostatus_disabled' => array('ostatus_disabled', t("Enable OStatus support"), !get_config('system', 'ostatus_disabled'), t("Provide built-in OStatus (StatusNet, GNU Social etc.) compatibility. All communications in OStatus are public, so privacy warnings will be occasionally displayed.")), '$ostatus_poll_interval' => array('ostatus_poll_interval', t("OStatus conversation completion interval"), (string) intval(get_config('system', 'ostatus_poll_interval')), t("How often shall the poller check for new entries in OStatus conversations? This can be a very ressource task."), $ostatus_poll_choices), '$diaspora_enabled' => array('diaspora_enabled', t("Enable Diaspora support"), get_config('system', 'diaspora_enabled'), t("Provide built-in Diaspora network compatibility.")), '$dfrn_only' => array('dfrn_only', t('Only allow Friendica contacts'), get_config('system', 'dfrn_only'), t("All contacts must use Friendica protocols. All other built-in communication protocols disabled.")), '$verifyssl' => array('verifyssl', t("Verify SSL"), get_config('system', 'verifyssl'), t("If you wish, you can turn on strict certificate checking. This will mean you cannot connect (at all) to self-signed SSL sites.")), '$proxyuser' => array('proxyuser', t("Proxy user"), get_config('system', 'proxyuser'), ""), '$proxy' => array('proxy', t("Proxy URL"), get_config('system', 'proxy'), ""), '$timeout' => array('timeout', t("Network timeout"), x(get_config('system', 'curl_timeout')) ? get_config('system', 'curl_timeout') : 60, t("Value is in seconds. Set to 0 for unlimited (not recommended).")), '$delivery_interval' => array('delivery_interval', t("Delivery interval"), x(get_config('system', 'delivery_interval')) ? get_config('system', 'delivery_interval') : 2, t("Delay background delivery processes by this many seconds to reduce system load. Recommend: 4-5 for shared hosts, 2-3 for virtual private servers. 0-1 for large dedicated servers.")), '$poll_interval' => array('poll_interval', t("Poll interval"), x(get_config('system', 'poll_interval')) ? get_config('system', 'poll_interval') : 2, t("Delay background polling processes by this many seconds to reduce system load. If 0, use delivery interval.")), '$maxloadavg' => array('maxloadavg', t("Maximum Load Average"), intval(get_config('system', 'maxloadavg')) > 0 ? get_config('system', 'maxloadavg') : 50, t("Maximum system load before delivery and poll processes are deferred - default 50.")), '$use_fulltext_engine' => array('use_fulltext_engine', t("Use MySQL full text engine"), get_config('system', 'use_fulltext_engine'), t("Activates the full text engine. Speeds up search - but can only search for four and more characters.")), '$suppress_language' => array('suppress_language', t("Suppress Language"), get_config('system', 'suppress_language'), t("Suppress language information in meta information about a posting.")), '$suppress_tags' => array('suppress_tags', t("Suppress Tags"), get_config('system', 'suppress_tags'), t("Suppress showing a list of hashtags at the end of the posting.")), '$itemcache' => array('itemcache', t("Path to item cache"), get_config('system', 'itemcache'), "The item caches buffers generated bbcode and external images."), '$itemcache_duration' => array('itemcache_duration', t("Cache duration in seconds"), get_config('system', 'itemcache_duration'), t("How long should the cache files be hold? Default value is 86400 seconds (One day). To disable the item cache, set the value to -1.")), '$max_comments' => array('max_comments', t("Maximum numbers of comments per post"), get_config('system', 'max_comments'), t("How much comments should be shown for each post? Default value is 100.")), '$lockpath' => array('lockpath', t("Path for lock file"), get_config('system', 'lockpath'), "The lock file is used to avoid multiple pollers at one time. Only define a folder here."), '$temppath' => array('temppath', t("Temp path"), get_config('system', 'temppath'), "If you have a restricted system where the webserver can't access the system temp path, enter another path here."), '$basepath' => array('basepath', t("Base path to installation"), get_config('system', 'basepath'), "If the system cannot detect the correct path to your installation, enter the correct path here. This setting should only be set if you are using a restricted system and symbolic links to your webroot."), '$proxy_disabled' => array('proxy_disabled', t("Disable picture proxy"), get_config('system', 'proxy_disabled'), t("The picture proxy increases performance and privacy. It shouldn't be used on systems with very low bandwith.")), '$old_pager' => array('old_pager', t("Enable old style pager"), get_config('system', 'old_pager'), t("The old style pager has page numbers but slows down massively the page speed.")), '$only_tag_search' => array('only_tag_search', t("Only search in tags"), get_config('system', 'only_tag_search'), t("On large systems the text search can slow down the system extremely.")), '$relocate_url' => array('relocate_url', t("New base url"), $a->get_baseurl(), "Change base url for this server. Sends relocate message to all DFRN contacts of all users."), '$form_security_token' => get_form_security_token("admin_site")));
}
Пример #19
0
 function get()
 {
     if (get_config('system', 'block_public') && !local_channel() && !remote_channel()) {
         notice(t('Public access denied.') . EOL);
         return;
     }
     $observer = get_observer_hash();
     $globaldir = get_directory_setting($observer, 'globaldir');
     // override your personal global search pref if we're doing a navbar search of the directory
     if (intval($_REQUEST['navsearch'])) {
         $globaldir = 1;
     }
     $safe_mode = get_directory_setting($observer, 'safemode');
     $pubforums = get_directory_setting($observer, 'pubforums');
     $o = '';
     nav_set_selected('directory');
     if (x($_POST, 'search')) {
         $search = notags(trim($_POST['search']));
     } else {
         $search = x($_GET, 'search') ? notags(trim(rawurldecode($_GET['search']))) : '';
     }
     if (strpos($search, '=') && local_channel() && get_pconfig(local_channel(), 'feature', 'expert')) {
         $advanced = $search;
     }
     $keywords = $_GET['keywords'] ? $_GET['keywords'] : '';
     // Suggest channels if no search terms or keywords are given
     $suggest = local_channel() && x($_REQUEST, 'suggest') ? $_REQUEST['suggest'] : '';
     if ($suggest) {
         $r = suggestion_query(local_channel(), get_observer_hash());
         // Remember in which order the suggestions were
         $addresses = array();
         $common = array();
         $index = 0;
         foreach ($r as $rr) {
             $common[$rr['xchan_addr']] = $rr['total'];
             $addresses[$rr['xchan_addr']] = $index++;
         }
         // Build query to get info about suggested people
         $advanced = '';
         foreach (array_keys($addresses) as $address) {
             $advanced .= "address=\"{$address}\" ";
         }
         // Remove last space in the advanced query
         $advanced = rtrim($advanced);
     }
     $tpl = get_markup_template('directory_header.tpl');
     $dirmode = intval(get_config('system', 'directory_mode'));
     if ($dirmode == DIRECTORY_MODE_PRIMARY || $dirmode == DIRECTORY_MODE_STANDALONE) {
         $url = z_root() . '/dirsearch';
     }
     if (!$url) {
         $directory = find_upstream_directory($dirmode);
         if (!$directory || !array_key_exists('url', $directory) || !$directory['url']) {
             logger('CRITICAL: No directory server URL');
         }
         $url = $directory['url'] . '/dirsearch';
     }
     $token = get_config('system', 'realm_token');
     logger('mod_directory: URL = ' . $url, LOGGER_DEBUG);
     $contacts = array();
     if (local_channel()) {
         $x = q("select abook_xchan from abook where abook_channel = %d", intval(local_channel()));
         if ($x) {
             foreach ($x as $xx) {
                 $contacts[] = $xx['abook_xchan'];
             }
         }
     }
     if ($url) {
         $numtags = get_config('system', 'directorytags');
         $kw = intval($numtags) > 0 ? intval($numtags) : 50;
         if (get_config('system', 'disable_directory_keywords')) {
             $kw = 0;
         }
         $query = $url . '?f=&kw=' . $kw . ($safe_mode != 1 ? '&safe=' . $safe_mode : '');
         if ($token) {
             $query .= '&t=' . $token;
         }
         if (!$globaldir) {
             $query .= '&hub=' . \App::get_hostname();
         }
         if ($search) {
             $query .= '&name=' . urlencode($search) . '&keywords=' . urlencode($search);
         }
         if (strpos($search, '@')) {
             $query .= '&address=' . urlencode($search);
         }
         if ($keywords) {
             $query .= '&keywords=' . urlencode($keywords);
         }
         if ($advanced) {
             $query .= '&query=' . urlencode($advanced);
         }
         if (!is_null($pubforums)) {
             $query .= '&pubforums=' . intval($pubforums);
         }
         $directory_sort_order = get_config('system', 'directory_sort_order');
         if (!$directory_sort_order) {
             $directory_sort_order = 'date';
         }
         $sort_order = x($_REQUEST, 'order') ? $_REQUEST['order'] : $directory_sort_order;
         if ($sort_order) {
             $query .= '&order=' . urlencode($sort_order);
         }
         if (\App::$pager['page'] != 1) {
             $query .= '&p=' . \App::$pager['page'];
         }
         logger('mod_directory: query: ' . $query);
         $x = z_fetch_url($query);
         logger('directory: return from upstream: ' . print_r($x, true), LOGGER_DATA);
         if ($x['success']) {
             $t = 0;
             $j = json_decode($x['body'], true);
             if ($j) {
                 if ($j['results']) {
                     $entries = array();
                     $photo = 'thumb';
                     foreach ($j['results'] as $rr) {
                         $profile_link = chanlink_url($rr['url']);
                         $pdesc = $rr['description'] ? $rr['description'] . '<br />' : '';
                         $connect_link = local_channel() ? z_root() . '/follow?f=&url=' . urlencode($rr['address']) : '';
                         // Checking status is disabled ATM until someone checks the performance impact more carefully
                         //$online = remote_online_status($rr['address']);
                         $online = '';
                         if (in_array($rr['hash'], $contacts)) {
                             $connect_link = '';
                         }
                         $location = '';
                         if (strlen($rr['locale'])) {
                             $location .= $rr['locale'];
                         }
                         if (strlen($rr['region'])) {
                             if (strlen($rr['locale'])) {
                                 $location .= ', ';
                             }
                             $location .= $rr['region'];
                         }
                         if (strlen($rr['country'])) {
                             if (strlen($location)) {
                                 $location .= ', ';
                             }
                             $location .= $rr['country'];
                         }
                         $age = '';
                         if (strlen($rr['birthday'])) {
                             if (($years = age($rr['birthday'], 'UTC', '')) != 0) {
                                 $age = $years;
                             }
                         }
                         $page_type = '';
                         if ($rr['total_ratings']) {
                             $total_ratings = sprintf(tt("%d rating", "%d ratings", $rr['total_ratings']), $rr['total_ratings']);
                         } else {
                             $total_ratings = '';
                         }
                         $profile = $rr;
                         if (x($profile, 'locale') == 1 || x($profile, 'region') == 1 || x($profile, 'postcode') == 1 || x($profile, 'country') == 1) {
                             $gender = x($profile, 'gender') == 1 ? t('Gender: ') . $profile['gender'] : False;
                         }
                         $marital = x($profile, 'marital') == 1 ? t('Status: ') . $profile['marital'] : False;
                         $homepage = x($profile, 'homepage') == 1 ? t('Homepage: ') : False;
                         $homepageurl = x($profile, 'homepage') == 1 ? $profile['homepage'] : '';
                         $hometown = x($profile, 'hometown') == 1 ? $profile['hometown'] : False;
                         $about = x($profile, 'about') == 1 ? bbcode($profile['about']) : False;
                         $keywords = x($profile, 'keywords') ? $profile['keywords'] : '';
                         $out = '';
                         if ($keywords) {
                             $keywords = str_replace(',', ' ', $keywords);
                             $keywords = str_replace('  ', ' ', $keywords);
                             $karr = explode(' ', $keywords);
                             if ($karr) {
                                 if (local_channel()) {
                                     $r = q("select keywords from profile where uid = %d and is_default = 1 limit 1", intval(local_channel()));
                                     if ($r) {
                                         $keywords = str_replace(',', ' ', $r[0]['keywords']);
                                         $keywords = str_replace('  ', ' ', $keywords);
                                         $marr = explode(' ', $keywords);
                                     }
                                 }
                                 foreach ($karr as $k) {
                                     if (strlen($out)) {
                                         $out .= ', ';
                                     }
                                     if ($marr && in_arrayi($k, $marr)) {
                                         $out .= '<strong>' . $k . '</strong>';
                                     } else {
                                         $out .= $k;
                                     }
                                 }
                             }
                         }
                         $entry = array('id' => ++$t, 'profile_link' => $profile_link, 'public_forum' => $rr['public_forum'], 'photo' => $rr['photo'], 'hash' => $rr['hash'], 'alttext' => $rr['name'] . (local_channel() || remote_channel() ? ' ' . $rr['address'] : ''), 'name' => $rr['name'], 'age' => $age, 'age_label' => t('Age:'), 'profile' => $profile, 'address' => $rr['address'], 'nickname' => substr($rr['address'], 0, strpos($rr['address'], '@')), 'location' => $location, 'location_label' => t('Location:'), 'gender' => $gender, 'total_ratings' => $total_ratings, 'viewrate' => true, 'canrate' => local_channel() ? true : false, 'pdesc' => $pdesc, 'pdesc_label' => t('Description:'), 'marital' => $marital, 'homepage' => $homepage, 'homepageurl' => linkify($homepageurl), 'hometown' => $hometown, 'hometown_label' => t('Hometown:'), 'about' => $about, 'about_label' => t('About:'), 'conn_label' => t('Connect'), 'forum_label' => t('Public Forum:'), 'connect' => $connect_link, 'online' => $online, 'kw' => $out ? t('Keywords: ') : '', 'keywords' => $out, 'ignlink' => $suggest ? z_root() . '/directory?ignore=' . $rr['hash'] : '', 'ignore_label' => t('Don\'t suggest'), 'common_friends' => $common[$rr['address']] ? intval($common[$rr['address']]) : '', 'common_label' => t('Common connections:'), 'common_count' => intval($common[$rr['address']]), 'safe' => $safe_mode);
                         $arr = array('contact' => $rr, 'entry' => $entry);
                         call_hooks('directory_item', $arr);
                         unset($profile);
                         unset($location);
                         if (!$arr['entry']) {
                             continue;
                         }
                         if ($sort_order == '' && $suggest) {
                             $entries[$addresses[$rr['address']]] = $arr['entry'];
                             // Use the same indexes as originally to get the best suggestion first
                         } else {
                             $entries[] = $arr['entry'];
                         }
                     }
                     ksort($entries);
                     // Sort array by key so that foreach-constructs work as expected
                     if ($j['keywords']) {
                         \App::$data['directory_keywords'] = $j['keywords'];
                     }
                     logger('mod_directory: entries: ' . print_r($entries, true), LOGGER_DATA);
                     if ($_REQUEST['aj']) {
                         if ($entries) {
                             $o = replace_macros(get_markup_template('directajax.tpl'), array('$entries' => $entries));
                         } else {
                             $o = '<div id="content-complete"></div>';
                         }
                         echo $o;
                         killme();
                     } else {
                         $maxheight = 94;
                         $dirtitle = $globaldir ? t('Global Directory') : t('Local Directory');
                         $o .= "<script> var page_query = '" . $_GET['q'] . "'; var extra_args = '" . extra_query_args() . "' ; divmore_height = " . intval($maxheight) . ";  </script>";
                         $o .= replace_macros($tpl, array('$search' => $search, '$desc' => t('Find'), '$finddsc' => t('Finding:'), '$safetxt' => htmlspecialchars($search, ENT_QUOTES, 'UTF-8'), '$entries' => $entries, '$dirlbl' => $suggest ? t('Channel Suggestions') : $dirtitle, '$submit' => t('Find'), '$next' => alt_pager($a, $j['records'], t('next page'), t('previous page')), '$sort' => t('Sort options'), '$normal' => t('Alphabetic'), '$reverse' => t('Reverse Alphabetic'), '$date' => t('Newest to Oldest'), '$reversedate' => t('Oldest to Newest'), '$suggest' => $suggest ? '&suggest=1' : ''));
                     }
                 } else {
                     if ($_REQUEST['aj']) {
                         $o = '<div id="content-complete"></div>';
                         echo $o;
                         killme();
                     }
                     if (\App::$pager['page'] == 1 && $j['records'] == 0 && strpos($search, '@')) {
                         goaway(z_root() . '/chanview/?f=&address=' . $search);
                     }
                     info(t("No entries (some entries may be hidden).") . EOL);
                 }
             }
         }
     }
     return $o;
 }
Пример #20
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;
}
Пример #21
0
    unset($db_host, $db_port, $db_user, $db_pass, $db_data, $db_type);
    /**
     * Load configs from db. Overwrite configs from .htconfig.php
     */
    load_config('config');
    load_config('system');
    load_config('feature');
    require_once 'include/session.php';
    load_hooks();
    call_hooks('init_1');
    $a->language = get_best_language();
    load_translation_table($a->language);
    // Force the cookie to be secure (https only) if this site is SSL enabled. Must be done before session_start().
    if (intval($a->config['system']['ssl_cookie_protection'])) {
        $arr = session_get_cookie_params();
        session_set_cookie_params(isset($arr['lifetime']) ? $arr['lifetime'] : 0, isset($arr['path']) ? $arr['path'] : '/', isset($arr['domain']) ? $arr['domain'] : $a->get_hostname(), isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? true : false, isset($arr['httponly']) ? $arr['httponly'] : true);
    }
} else {
    // load translations but do not check plugins as we have no database
    $a->language = get_best_language();
    load_translation_table($a->language, true);
}
/**
 *
 * Important stuff we always need to do.
 *
 * The order of these may be important so use caution if you think they're all
 * intertwingled with no logical order and decide to sort it out. Some of the
 * dependencies have changed, but at least at one time in the recent past - the
 * order was critical to everything working properly
 *
Пример #22
0
/**
 * @brief Send warnings every 3-5 days if cron is not running.
 */
function check_cron_broken()
{
    $d = get_config('system', 'lastcron');
    if (!$d || $d < datetime_convert('UTC', 'UTC', 'now - 4 hours')) {
        Zotlabs\Daemon\Master::Summon(array('Cron'));
    }
    $t = get_config('system', 'lastcroncheck');
    if (!$t) {
        // never checked before. Start the timer.
        set_config('system', 'lastcroncheck', datetime_convert());
        return;
    }
    if ($t > datetime_convert('UTC', 'UTC', 'now - 3 days')) {
        // Wait for 3 days before we do anything so as not to swamp the admin with messages
        return;
    }
    set_config('system', 'lastcroncheck', datetime_convert());
    if ($d && $d > datetime_convert('UTC', 'UTC', 'now - 3 days')) {
        // Scheduled tasks have run successfully in the last 3 days.
        return;
    }
    $email_tpl = get_intltext_template("cron_bad_eml.tpl");
    $email_msg = replace_macros($email_tpl, array('$sitename' => App::$config['system']['sitename'], '$siteurl' => z_root(), '$error' => t('Cron/Scheduled tasks not running.'), '$lastdate' => $d ? $d : t('never')));
    $subject = email_header_encode(sprintf(t('[hubzilla] Cron tasks not running on %s'), App::get_hostname()));
    mail(App::$config['system']['admin_email'], $subject, $email_msg, 'From: Administrator' . '@' . App::get_hostname() . "\n" . 'Content-type: text/plain; charset=UTF-8' . "\n" . 'Content-transfer-encoding: 8bit');
    return;
}
Пример #23
0
function get_zcard_embed($channel, $observer_hash = '', $args = array())
{
    logger('get_zcard_embed');
    $maxwidth = $args['width'] ? intval($args['width']) : 0;
    $maxheight = $args['height'] ? intval($args['height']) : 0;
    if ($maxwidth > 1200 || $maxwidth < 1) {
        $maxwidth = 1200;
    }
    if ($maxwidth <= 425) {
        $width = 425;
        $size = 'hz_small';
        $cover_size = PHOTO_RES_COVER_425;
        $pphoto = array('mimetype' => $channel['xchan_photo_mimetype'], 'width' => 80, 'height' => 80, 'href' => $channel['xchan_photo_m']);
    } elseif ($maxwidth <= 900) {
        $width = 900;
        $size = 'hz_medium';
        $cover_size = PHOTO_RES_COVER_850;
        $pphoto = array('mimetype' => $channel['xchan_photo_mimetype'], 'width' => 160, 'height' => 160, 'href' => $channel['xchan_photo_l']);
    } elseif ($maxwidth <= 1200) {
        $width = 1200;
        $size = 'hz_large';
        $cover_size = PHOTO_RES_COVER_1200;
        $pphoto = array('mimetype' => $channel['xchan_photo_mimetype'], 'width' => 300, 'height' => 300, 'href' => $channel['xchan_photo_l']);
    }
    $channel['channel_addr'] = $channel['channel_address'] . '@' . App::get_hostname();
    $zcard = array('chan' => $channel);
    $r = q("select height, width, resource_id, imgscale, mimetype from photo where uid = %d and imgscale = %d and photo_usage = %d", intval($channel['channel_id']), intval($cover_size), intval(PHOTO_COVER));
    if ($r) {
        $cover = $r[0];
        $cover['href'] = z_root() . '/photo/' . $r[0]['resource_id'] . '-' . $r[0]['imgscale'];
    } else {
        $cover = $pphoto;
    }
    $o .= replace_macros(get_markup_template('zcard_embed.tpl'), array('$maxwidth' => $maxwidth, '$scale' => $scale, '$translate' => $translate, '$size' => $size, '$cover' => $cover, '$pphoto' => $pphoto, '$zcard' => $zcard));
    return $o;
}
Пример #24
0
/**
 * @brief Push local channel updates to a local directory server.
 *
 * This is called from include/directory.php if a profile is to be pushed to the
 * directory and the local hub in this case is any kind of directory server.
 *
 * @param int $uid
 * @param boolean $force
 */
function local_dir_update($uid, $force)
{
    logger('local_dir_update: uid: ' . $uid, LOGGER_DEBUG);
    $p = q("select channel.channel_hash, channel_address, channel_timezone, profile.* from profile left join channel on channel_id = uid where uid = %d and is_default = 1", intval($uid));
    $profile = array();
    $profile['encoding'] = 'zot';
    if ($p) {
        $hash = $p[0]['channel_hash'];
        $profile['description'] = $p[0]['pdesc'];
        $profile['birthday'] = $p[0]['dob'];
        if ($age = age($p[0]['dob'], $p[0]['channel_timezone'], '')) {
            $profile['age'] = $age;
        }
        $profile['gender'] = $p[0]['gender'];
        $profile['marital'] = $p[0]['marital'];
        $profile['sexual'] = $p[0]['sexual'];
        $profile['locale'] = $p[0]['locality'];
        $profile['region'] = $p[0]['region'];
        $profile['postcode'] = $p[0]['postal_code'];
        $profile['country'] = $p[0]['country_name'];
        $profile['about'] = $p[0]['about'];
        $profile['homepage'] = $p[0]['homepage'];
        $profile['hometown'] = $p[0]['hometown'];
        if ($p[0]['keywords']) {
            $tags = array();
            $k = explode(' ', $p[0]['keywords']);
            if ($k) {
                foreach ($k as $kk) {
                    if (trim($kk)) {
                        $tags[] = trim($kk);
                    }
                }
            }
            if ($tags) {
                $profile['keywords'] = $tags;
            }
        }
        $hidden = 1 - intval($p[0]['publish']);
        logger('hidden: ' . $hidden);
        $r = q("select xchan_hidden from xchan where xchan_hash = '%s' limit 1", dbesc($p[0]['channel_hash']));
        if (intval($r[0]['xchan_hidden']) != $hidden) {
            $r = q("update xchan set xchan_hidden = %d where xchan_hash = '%s'", intval($hidden), dbesc($p[0]['channel_hash']));
        }
        $arr = array('channel_id' => $uid, 'hash' => $hash, 'profile' => $profile);
        call_hooks('local_dir_update', $arr);
        $address = $p[0]['channel_address'] . '@' . App::get_hostname();
        if (perm_is_allowed($uid, '', 'view_profile')) {
            import_directory_profile($hash, $arr['profile'], $address, 0);
        } else {
            // they may have made it private
            $r = q("delete from xprof where xprof_hash = '%s'", dbesc($hash));
            $r = q("delete from xtag where xtag_hash = '%s'", dbesc($hash));
        }
    }
    $ud_hash = random_string() . '@' . App::get_hostname();
    update_modtime($hash, $ud_hash, $p[0]['channel_address'] . '@' . App::get_hostname(), $force ? UPDATE_FLAGS_FORCED : UPDATE_FLAGS_UPDATED);
}
Пример #25
0
/**
 * @brief Returns an iframe from $match[1].
 *
 * @param array $match
 * @return string HTML iframe with content of $match[1]
 */
function bb_iframe($match)
{
    $sandbox = strpos($match[1], App::get_hostname()) ? ' sandbox="allow-scripts" ' : '';
    return '<iframe ' . $sandbox . ' src="' . $match[1] . '" width="' . App::$videowidth . '" height="' . App::$videoheight . '"><a href="' . $match[1] . '">' . $match[1] . '</a></iframe>';
}
Пример #26
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;
}
Пример #27
0
 function import_account($account_id)
 {
     if (!$account_id) {
         logger("import_account: No account ID supplied");
         return;
     }
     $max_identities = account_service_class_fetch($account_id, 'total_identities');
     $max_friends = account_service_class_fetch($account_id, 'total_channels');
     $max_feeds = account_service_class_fetch($account_id, 'total_feeds');
     if ($max_identities !== false) {
         $r = q("select channel_id from channel where channel_account_id = %d", intval($account_id));
         if ($r && count($r) > $max_identities) {
             notice(sprintf(t('Your service plan only allows %d channels.'), $max_identities) . EOL);
             return;
         }
     }
     $data = null;
     $seize = x($_REQUEST, 'make_primary') ? intval($_REQUEST['make_primary']) : 0;
     $import_posts = x($_REQUEST, 'import_posts') ? intval($_REQUEST['import_posts']) : 0;
     $src = $_FILES['filename']['tmp_name'];
     $filename = basename($_FILES['filename']['name']);
     $filesize = intval($_FILES['filename']['size']);
     $filetype = $_FILES['filename']['type'];
     $completed = array_key_exists('import_step', $_SESSION) ? intval($_SESSION['import_step']) : 0;
     if ($completed) {
         logger('saved import step: ' . $_SESSION['import_step']);
     }
     if ($src) {
         // This is OS specific and could also fail if your tmpdir isn't very large
         // mostly used for Diaspora which exports gzipped files.
         if (strpos($filename, '.gz')) {
             @rename($src, $src . '.gz');
             @system('gunzip ' . escapeshellarg($src . '.gz'));
         }
         if ($filesize) {
             $data = @file_get_contents($src);
         }
         unlink($src);
     }
     if (!$src) {
         $old_address = x($_REQUEST, 'old_address') ? $_REQUEST['old_address'] : '';
         if (!$old_address) {
             logger('mod_import: nothing to import.');
             notice(t('Nothing to import.') . EOL);
             return;
         }
         $email = x($_REQUEST, 'email') ? $_REQUEST['email'] : '';
         $password = x($_REQUEST, 'password') ? $_REQUEST['password'] : '';
         $channelname = substr($old_address, 0, strpos($old_address, '@'));
         $servername = substr($old_address, strpos($old_address, '@') + 1);
         $scheme = 'https://';
         $api_path = '/api/red/channel/export/basic?f=&channel=' . $channelname;
         if ($import_posts) {
             $api_path .= '&posts=1';
         }
         $binary = false;
         $redirects = 0;
         $opts = array('http_auth' => $email . ':' . $password);
         $url = $scheme . $servername . $api_path;
         $ret = z_fetch_url($url, $binary, $redirects, $opts);
         if (!$ret['success']) {
             $ret = z_fetch_url('http://' . $servername . $api_path, $binary, $redirects, $opts);
         }
         if ($ret['success']) {
             $data = $ret['body'];
         } else {
             notice(t('Unable to download data from old server') . EOL);
         }
     }
     if (!$data) {
         logger('mod_import: empty file.');
         notice(t('Imported file is empty.') . EOL);
         return;
     }
     $data = json_decode($data, true);
     //	logger('import: data: ' . print_r($data,true));
     //	print_r($data);
     if (array_key_exists('user', $data) && array_key_exists('version', $data)) {
         require_once 'include/Import/import_diaspora.php';
         import_diaspora($data);
         return;
     }
     $moving = false;
     if (array_key_exists('compatibility', $data) && array_key_exists('database', $data['compatibility'])) {
         $v1 = substr($data['compatibility']['database'], -4);
         $v2 = substr(DB_UPDATE_VERSION, -4);
         if ($v2 > $v1) {
             $t = sprintf(t('Warning: Database versions differ by %1$d updates.'), $v2 - $v1);
             notice($t);
         }
         if (array_key_exists('server_role', $data['compatibility']) && $data['compatibility']['server_role'] == 'basic') {
             $moving = true;
         }
     }
     if ($moving) {
         $seize = 1;
     }
     // import channel
     $relocate = array_key_exists('relocate', $data) ? $data['relocate'] : null;
     if (array_key_exists('channel', $data)) {
         if ($completed < 1) {
             $channel = import_channel($data['channel'], $account_id, $seize);
         } else {
             $r = q("select * from channel where channel_account_id = %d and channel_guid = '%s' limit 1", intval($account_id), dbesc($channel['channel_guid']));
             if ($r) {
                 $channel = $r[0];
             }
         }
         if (!$channel) {
             logger('mod_import: channel not found. ', print_r($channel, true));
             notice(t('Cloned channel not found. Import failed.') . EOL);
             return;
         }
     }
     if (!$channel) {
         $channel = \App::get_channel();
     }
     if (!$channel) {
         logger('mod_import: channel not found. ', print_r($channel, true));
         notice(t('No channel. Import failed.') . EOL);
         return;
     }
     if ($completed < 2) {
         if (is_array($data['config'])) {
             import_config($channel, $data['config']);
         }
         logger('import step 2');
         $_SESSION['import_step'] = 2;
     }
     if ($completed < 3) {
         if ($data['photo']) {
             require_once 'include/photo/photo_driver.php';
             import_channel_photo(base64url_decode($data['photo']['data']), $data['photo']['type'], $account_id, $channel['channel_id']);
         }
         if (is_array($data['profile'])) {
             import_profiles($channel, $data['profile']);
         }
         logger('import step 3');
         $_SESSION['import_step'] = 3;
     }
     if ($completed < 4) {
         if (is_array($data['hubloc']) && !$moving) {
             import_hublocs($channel, $data['hubloc'], $seize);
         }
         logger('import step 4');
         $_SESSION['import_step'] = 4;
     }
     if ($completed < 5) {
         // create new hubloc for the new channel at this site
         $r = q("insert into hubloc ( hubloc_guid, hubloc_guid_sig, hubloc_hash, hubloc_addr, hubloc_network, hubloc_primary, \n\t\t\t\thubloc_url, hubloc_url_sig, hubloc_host, hubloc_callback, hubloc_sitekey )\n\t\t\t\tvalues ( '%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s' )", dbesc($channel['channel_guid']), dbesc($channel['channel_guid_sig']), dbesc($channel['channel_hash']), dbesc(channel_reddress($channel)), dbesc('zot'), intval($seize ? 1 : 0), dbesc(z_root()), dbesc(base64url_encode(rsa_sign(z_root(), $channel['channel_prvkey']))), dbesc(\App::get_hostname()), dbesc(z_root() . '/post'), dbesc(get_config('system', 'pubkey')));
         // reset the original primary hubloc if it is being seized
         if ($seize) {
             $r = q("update hubloc set hubloc_primary = 0 where hubloc_primary = 1 and hubloc_hash = '%s' and hubloc_url != '%s' ", dbesc($channel['channel_hash']), dbesc(z_root()));
         }
         logger('import step 5');
         $_SESSION['import_step'] = 5;
     }
     if ($completed < 6) {
         // import xchans and contact photos
         if ($seize) {
             // replace any existing xchan we may have on this site if we're seizing control
             $r = q("delete from xchan where xchan_hash = '%s'", dbesc($channel['channel_hash']));
             $r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_guid_sig, xchan_pubkey, xchan_photo_l, xchan_photo_m, xchan_photo_s, xchan_addr, xchan_url, xchan_follow, xchan_connurl, xchan_name, xchan_network, xchan_photo_date, xchan_name_date, xchan_hidden, xchan_orphan, xchan_censored, xchan_selfcensored, xchan_system, xchan_pubforum, xchan_deleted ) values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d, %d, %d, %d )", dbesc($channel['channel_hash']), dbesc($channel['channel_guid']), dbesc($channel['channel_guid_sig']), dbesc($channel['channel_pubkey']), dbesc(z_root() . "/photo/profile/l/" . $channel['channel_id']), dbesc(z_root() . "/photo/profile/m/" . $channel['channel_id']), dbesc(z_root() . "/photo/profile/s/" . $channel['channel_id']), dbesc(channel_reddress($channel)), dbesc(z_root() . '/channel/' . $channel['channel_address']), dbesc(z_root() . '/follow?f=&url=%s'), dbesc(z_root() . '/poco/' . $channel['channel_address']), dbesc($channel['channel_name']), dbesc('zot'), dbesc(datetime_convert()), dbesc(datetime_convert()), 0, 0, 0, 0, 0, 0, 0);
         }
         logger('import step 6');
         $_SESSION['import_step'] = 6;
     }
     if ($completed < 7) {
         $xchans = $data['xchan'];
         if ($xchans) {
             foreach ($xchans as $xchan) {
                 $hash = make_xchan_hash($xchan['xchan_guid'], $xchan['xchan_guid_sig']);
                 if ($xchan['xchan_network'] === 'zot' && $hash !== $xchan['xchan_hash']) {
                     logger('forged xchan: ' . print_r($xchan, true));
                     continue;
                 }
                 if (!array_key_exists('xchan_hidden', $xchan)) {
                     $xchan['xchan_hidden'] = $xchan['xchan_flags'] & 0x1 ? 1 : 0;
                     $xchan['xchan_orphan'] = $xchan['xchan_flags'] & 0x2 ? 1 : 0;
                     $xchan['xchan_censored'] = $xchan['xchan_flags'] & 0x4 ? 1 : 0;
                     $xchan['xchan_selfcensored'] = $xchan['xchan_flags'] & 0x8 ? 1 : 0;
                     $xchan['xchan_system'] = $xchan['xchan_flags'] & 0x10 ? 1 : 0;
                     $xchan['xchan_pubforum'] = $xchan['xchan_flags'] & 0x20 ? 1 : 0;
                     $xchan['xchan_deleted'] = $xchan['xchan_flags'] & 0x1000 ? 1 : 0;
                 }
                 $r = q("select xchan_hash from xchan where xchan_hash = '%s' limit 1", dbesc($xchan['xchan_hash']));
                 if ($r) {
                     continue;
                 }
                 dbesc_array($xchan);
                 $r = dbq("INSERT INTO xchan (`" . implode("`, `", array_keys($xchan)) . "`) VALUES ('" . implode("', '", array_values($xchan)) . "')");
                 require_once 'include/photo/photo_driver.php';
                 $photos = import_xchan_photo($xchan['xchan_photo_l'], $xchan['xchan_hash']);
                 if ($photos[4]) {
                     $photodate = NULL_DATE;
                 } else {
                     $photodate = $xchan['xchan_photo_date'];
                 }
                 $r = q("update xchan set xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s', xchan_photo_date = '%s'\n\t\t\t\t\t\twhere xchan_hash = '%s'", dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), dbesc($photos[3]), dbesc($photodate), dbesc($xchan['xchan_hash']));
             }
         }
         logger('import step 7');
         $_SESSION['import_step'] = 7;
     }
     // FIXME - ensure we have an xchan if somebody is trying to pull a fast one
     if ($completed < 8) {
         $friends = 0;
         $feeds = 0;
         // import contacts
         $abooks = $data['abook'];
         if ($abooks) {
             foreach ($abooks as $abook) {
                 $abook_copy = $abook;
                 $abconfig = null;
                 if (array_key_exists('abconfig', $abook) && is_array($abook['abconfig']) && count($abook['abconfig'])) {
                     $abconfig = $abook['abconfig'];
                 }
                 unset($abook['abook_id']);
                 unset($abook['abook_rating']);
                 unset($abook['abook_rating_text']);
                 unset($abook['abconfig']);
                 unset($abook['abook_their_perms']);
                 unset($abook['abook_my_perms']);
                 $abook['abook_account'] = $account_id;
                 $abook['abook_channel'] = $channel['channel_id'];
                 if (!array_key_exists('abook_blocked', $abook)) {
                     $abook['abook_blocked'] = $abook['abook_flags'] & 0x1 ? 1 : 0;
                     $abook['abook_ignored'] = $abook['abook_flags'] & 0x2 ? 1 : 0;
                     $abook['abook_hidden'] = $abook['abook_flags'] & 0x4 ? 1 : 0;
                     $abook['abook_archived'] = $abook['abook_flags'] & 0x8 ? 1 : 0;
                     $abook['abook_pending'] = $abook['abook_flags'] & 0x10 ? 1 : 0;
                     $abook['abook_unconnected'] = $abook['abook_flags'] & 0x20 ? 1 : 0;
                     $abook['abook_self'] = $abook['abook_flags'] & 0x80 ? 1 : 0;
                     $abook['abook_feed'] = $abook['abook_flags'] & 0x100 ? 1 : 0;
                 }
                 if ($abook['abook_self']) {
                     $role = get_pconfig($channel['channel_id'], 'system', 'permissions_role');
                     if ($role === 'forum' || $abook['abook_my_perms'] & PERMS_W_TAGWALL) {
                         q("update xchan set xchan_pubforum = 1 where xchan_hash = '%s' ", dbesc($abook['abook_xchan']));
                     }
                 } else {
                     if ($max_friends !== false && $friends > $max_friends) {
                         continue;
                     }
                     if ($max_feeds !== false && intval($abook['abook_feed']) && $feeds > $max_feeds) {
                         continue;
                     }
                 }
                 dbesc_array($abook);
                 $r = dbq("INSERT INTO abook (`" . implode("`, `", array_keys($abook)) . "`) VALUES ('" . implode("', '", array_values($abook)) . "')");
                 $friends++;
                 if (intval($abook['abook_feed'])) {
                     $feeds++;
                 }
                 translate_abook_perms_inbound($channel, $abook_copy);
                 if ($abconfig) {
                     // @fixme does not handle sync of del_abconfig
                     foreach ($abconfig as $abc) {
                         set_abconfig($channel['channel_id'], $abc['xchan'], $abc['cat'], $abc['k'], $abc['v']);
                     }
                 }
             }
         }
         logger('import step 8');
         $_SESSION['import_step'] = 8;
     }
     if ($completed < 9) {
         $groups = $data['group'];
         if ($groups) {
             $saved = array();
             foreach ($groups as $group) {
                 $saved[$group['hash']] = array('old' => $group['id']);
                 if (array_key_exists('name', $group)) {
                     $group['gname'] = $group['name'];
                     unset($group['name']);
                 }
                 unset($group['id']);
                 $group['uid'] = $channel['channel_id'];
                 dbesc_array($group);
                 $r = dbq("INSERT INTO groups (`" . implode("`, `", array_keys($group)) . "`) VALUES ('" . implode("', '", array_values($group)) . "')");
             }
             $r = q("select * from `groups` where uid = %d", intval($channel['channel_id']));
             if ($r) {
                 foreach ($r as $rr) {
                     $saved[$rr['hash']]['new'] = $rr['id'];
                 }
             }
         }
         $group_members = $data['group_member'];
         if ($group_members) {
             foreach ($group_members as $group_member) {
                 unset($group_member['id']);
                 $group_member['uid'] = $channel['channel_id'];
                 foreach ($saved as $x) {
                     if ($x['old'] == $group_member['gid']) {
                         $group_member['gid'] = $x['new'];
                     }
                 }
                 dbesc_array($group_member);
                 $r = dbq("INSERT INTO group_member (`" . implode("`, `", array_keys($group_member)) . "`) VALUES ('" . implode("', '", array_values($group_member)) . "')");
             }
         }
         logger('import step 9');
         $_SESSION['import_step'] = 9;
     }
     if (is_array($data['obj'])) {
         import_objs($channel, $data['obj']);
     }
     if (is_array($data['likes'])) {
         import_likes($channel, $data['likes']);
     }
     if (is_array($data['app'])) {
         import_apps($channel, $data['app']);
     }
     if (is_array($data['chatroom'])) {
         import_chatrooms($channel, $data['chatroom']);
     }
     if (is_array($data['conv'])) {
         import_conv($channel, $data['conv']);
     }
     if (is_array($data['mail'])) {
         import_mail($channel, $data['mail']);
     }
     if (is_array($data['event'])) {
         import_events($channel, $data['event']);
     }
     if (is_array($data['event_item'])) {
         import_items($channel, $data['event_item'], false, $relocate);
     }
     if (is_array($data['menu'])) {
         import_menus($channel, $data['menu']);
     }
     $addon = array('channel' => $channel, 'data' => $data);
     call_hooks('import_channel', $addon);
     $saved_notification_flags = notifications_off($channel['channel_id']);
     if ($import_posts && array_key_exists('item', $data) && $data['item']) {
         import_items($channel, $data['item'], false, $relocate);
     }
     notifications_on($channel['channel_id'], $saved_notification_flags);
     if (array_key_exists('item_id', $data) && $data['item_id']) {
         import_item_ids($channel, $data['item_id']);
     }
     // FIXME - ensure we have a self entry if somebody is trying to pull a fast one
     // send out refresh requests
     // notify old server that it may no longer be primary.
     \Zotlabs\Daemon\Master::Summon(array('Notifier', 'location', $channel['channel_id']));
     // This will indirectly perform a refresh_all *and* update the directory
     \Zotlabs\Daemon\Master::Summon(array('Directory', $channel['channel_id']));
     notice(t('Import completed.') . EOL);
     change_channel($channel['channel_id']);
     unset($_SESSION['import_step']);
     goaway(z_root() . '/network');
 }
Пример #28
0
/**
 * @brief Generate a guaranteed unique (for this domain) item ID for ATOM.
 *
 * Safe from birthday paradox.
 *
 * @return string a unique id
 */
function item_message_id()
{
    do {
        $dups = false;
        $hash = random_string();
        $mid = $hash . '@' . App::get_hostname();
        $r = q("SELECT id FROM item WHERE mid = '%s' LIMIT 1", dbesc($mid));
        if (count($r)) {
            $dups = true;
        }
    } while ($dups == true);
    return $mid;
}
Пример #29
0
 /**
  * @brief
  *
  * @param array $params an assoziative array with:
  *  * \e string \b from_xchan sender xchan hash
  *  * \e string \b to_xchan recipient xchan hash
  *  * \e array \b item an assoziative array
  *  * \e int \b type one of the NOTIFY_* constants from boot.php
  *  * \e string \b link
  *  * \e string \b parent_mid
  *  * \e string \b otype
  *  * \e string \b verb
  *  * \e string \b activity
  */
 public static function submit($params)
 {
     logger('notification: entry', LOGGER_DEBUG);
     // throw a small amount of entropy into the system to breakup duplicates arriving at the same precise instant.
     usleep(mt_rand(0, 10000));
     if ($params['from_xchan']) {
         $x = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($params['from_xchan']));
     }
     if ($params['to_xchan']) {
         $y = q("select channel.*, account.* from channel left join account on channel_account_id = account_id\n\t\t\t\twhere channel_hash = '%s' and channel_removed = 0 limit 1", dbesc($params['to_xchan']));
     }
     if ($x & $y) {
         $sender = $x[0];
         $recip = $y[0];
     } else {
         logger('notification: no sender or recipient.');
         logger('sender: ' . $params['from_xchan']);
         logger('recip: ' . $params['to_xchan']);
         return;
     }
     // from here on everything is in the recipients language
     push_lang($recip['account_language']);
     // should probably have a channel language
     $banner = t('$Projectname Notification');
     $product = t('$projectname');
     // PLATFORM_NAME;
     $siteurl = z_root();
     $thanks = t('Thank You,');
     $sitename = get_config('system', 'sitename');
     $site_admin = sprintf(t('%s Administrator'), $sitename);
     $sender_name = $product;
     $hostname = \App::get_hostname();
     if (strpos($hostname, ':')) {
         $hostname = substr($hostname, 0, strpos($hostname, ':'));
     }
     // Do not translate 'noreply' as it must be a legal 7-bit email address
     $reply_email = get_config('system', 'reply_address');
     if (!$reply_email) {
         $reply_email = 'noreply' . '@' . $hostname;
     }
     $sender_email = get_config('system', 'from_email');
     if (!$sender_email) {
         $sender_email = 'Administrator' . '@' . \App::get_hostname();
     }
     $sender_name = get_config('system', 'from_email_name');
     if (!$sender_name) {
         $sender_name = \Zotlabs\Lib\System::get_site_name();
     }
     $additional_mail_header = "";
     if (array_key_exists('item', $params)) {
         require_once 'include/conversation.php';
         // if it's a normal item...
         if (array_key_exists('verb', $params['item'])) {
             // localize_item() alters the original item so make a copy first
             $i = $params['item'];
             logger('calling localize');
             localize_item($i);
             $title = $i['title'];
             $body = $i['body'];
             $private = $i['item_private'] || intval($i['item_obscured']);
         } else {
             $title = $params['item']['title'];
             $body = $params['item']['body'];
         }
     } else {
         $title = $body = '';
     }
     // e.g. "your post", "David's photo", etc.
     $possess_desc = t('%s <!item_type!>');
     if ($params['type'] == NOTIFY_MAIL) {
         logger('notification: mail');
         $subject = sprintf(t('[$Projectname:Notify] New mail received at %s'), $sitename);
         $preamble = sprintf(t('%1$s, %2$s sent you a new private message at %3$s.'), $recip['channel_name'], $sender['xchan_name'], $sitename);
         $epreamble = sprintf(t('%1$s sent you %2$s.'), '[zrl=' . $sender['xchan_url'] . ']' . $sender['xchan_name'] . '[/zrl]', '[zrl=$itemlink]' . t('a private message') . '[/zrl]');
         $sitelink = t('Please visit %s to view and/or reply to your private messages.');
         $tsitelink = sprintf($sitelink, $siteurl . '/mail/' . $params['item']['id']);
         $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '/mail/' . $params['item']['id'] . '">' . $sitename . '</a>');
         $itemlink = $siteurl . '/mail/' . $params['item']['id'];
     }
     if ($params['type'] == NOTIFY_COMMENT) {
         //		logger("notification: params = " . print_r($params, true), LOGGER_DEBUG);
         $itemlink = $params['link'];
         // ignore like/unlike activity on posts - they probably require a separate notification preference
         if (array_key_exists('item', $params) && !visible_activity($params['item'])) {
             logger('notification: not a visible activity. Ignoring.');
             pop_lang();
             return;
         }
         $parent_mid = $params['parent_mid'];
         // Check to see if there was already a notify for this post.
         // If so don't create a second notification
         $p = null;
         $p = q("select id from notify where link = '%s' and uid = %d limit 1", dbesc($params['link']), intval($recip['channel_id']));
         if ($p) {
             logger('notification: comment already notified');
             pop_lang();
             return;
         }
         // if it's a post figure out who's post it is.
         $p = null;
         if ($params['otype'] === 'item' && $parent_mid) {
             $p = q("select * from item where mid = '%s' and uid = %d limit 1", dbesc($parent_mid), intval($recip['channel_id']));
         }
         xchan_query($p);
         $item_post_type = item_post_type($p[0]);
         //		$private = $p[0]['item_private'];
         $parent_id = $p[0]['id'];
         $parent_item = $p[0];
         //$possess_desc = str_replace('<!item_type!>',$possess_desc);
         // "a post"
         $dest_str = sprintf(t('%1$s, %2$s commented on [zrl=%3$s]a %4$s[/zrl]'), $recip['channel_name'], '[zrl=' . $sender['xchan_url'] . ']' . $sender['xchan_name'] . '[/zrl]', $itemlink, $item_post_type);
         // "George Bull's post"
         if ($p) {
             $dest_str = sprintf(t('%1$s, %2$s commented on [zrl=%3$s]%4$s\'s %5$s[/zrl]'), $recip['channel_name'], '[zrl=' . $sender['xchan_url'] . ']' . $sender['xchan_name'] . '[/zrl]', $itemlink, $p[0]['author']['xchan_name'], $item_post_type);
         }
         // "your post"
         if ($p[0]['owner']['xchan_name'] == $p[0]['author']['xchan_name'] && intval($p[0]['item_wall'])) {
             $dest_str = sprintf(t('%1$s, %2$s commented on [zrl=%3$s]your %4$s[/zrl]'), $recip['channel_name'], '[zrl=' . $sender['xchan_url'] . ']' . $sender['xchan_name'] . '[/zrl]', $itemlink, $item_post_type);
         }
         // Some mail softwares relies on subject field for threading.
         // So, we cannot have different subjects for notifications of the same thread.
         // Before this we have the name of the replier on the subject rendering
         // differents subjects for messages on the same thread.
         $subject = sprintf(t('[$Projectname:Notify] Comment to conversation #%1$d by %2$s'), $parent_id, $sender['xchan_name']);
         $preamble = sprintf(t('%1$s, %2$s commented on an item/conversation you have been following.'), $recip['channel_name'], $sender['xchan_name']);
         $epreamble = $dest_str;
         $sitelink = t('Please visit %s to view and/or reply to the conversation.');
         $tsitelink = sprintf($sitelink, $siteurl);
         $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
     }
     if ($params['type'] == NOTIFY_WALL) {
         $subject = sprintf(t('[$Projectname:Notify] %s posted to your profile wall'), $sender['xchan_name']);
         $preamble = sprintf(t('%1$s, %2$s posted to your profile wall at %3$s'), $recip['channel_name'], $sender['xchan_name'], $sitename);
         $epreamble = sprintf(t('%1$s, %2$s posted to [zrl=%3$s]your wall[/zrl]'), $recip['channel_name'], '[zrl=' . $sender['xchan_url'] . ']' . $sender['xchan_name'] . '[/zrl]', $params['link']);
         $sitelink = t('Please visit %s to view and/or reply to the conversation.');
         $tsitelink = sprintf($sitelink, $siteurl);
         $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
         $itemlink = $params['link'];
     }
     if ($params['type'] == NOTIFY_TAGSELF) {
         $p = null;
         $p = q("select id from notify where link = '%s' and uid = %d limit 1", dbesc($params['link']), intval($recip['channel_id']));
         if ($p) {
             logger('enotify: tag: already notified about this post');
             pop_lang();
             return;
         }
         $subject = sprintf(t('[$Projectname:Notify] %s tagged you'), $sender['xchan_name']);
         $preamble = sprintf(t('%1$s, %2$s tagged you at %3$s'), $recip['channel_name'], $sender['xchan_name'], $sitename);
         $epreamble = sprintf(t('%1$s, %2$s [zrl=%3$s]tagged you[/zrl].'), $recip['channel_name'], '[zrl=' . $sender['xchan_url'] . ']' . $sender['xchan_name'] . '[/zrl]', $params['link']);
         $sitelink = t('Please visit %s to view and/or reply to the conversation.');
         $tsitelink = sprintf($sitelink, $siteurl);
         $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
         $itemlink = $params['link'];
     }
     if ($params['type'] == NOTIFY_POKE) {
         $subject = sprintf(t('[$Projectname:Notify] %1$s poked you'), $sender['xchan_name']);
         $preamble = sprintf(t('%1$s, %2$s poked you at %3$s'), $recip['channel_name'], $sender['xchan_name'], $sitename);
         $epreamble = sprintf(t('%1$s, %2$s [zrl=%2$s]poked you[/zrl].'), $recip['channel_name'], '[zrl=' . $sender['xchan_url'] . ']' . $sender['xchan_name'] . '[/zrl]', $params['link']);
         $subject = str_replace('poked', t($params['activity']), $subject);
         $preamble = str_replace('poked', t($params['activity']), $preamble);
         $epreamble = str_replace('poked', t($params['activity']), $epreamble);
         $sitelink = t('Please visit %s to view and/or reply to the conversation.');
         $tsitelink = sprintf($sitelink, $siteurl);
         $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
         $itemlink = $params['link'];
     }
     if ($params['type'] == NOTIFY_TAGSHARE) {
         $subject = sprintf(t('[$Projectname:Notify] %s tagged your post'), $sender['xchan_name']);
         $preamble = sprintf(t('%1$s, %2$s tagged your post at %3$s'), $recip['channel_name'], $sender['xchan_name'], $sitename);
         $epreamble = sprintf(t('%1$s, %2$s tagged [zrl=%3$s]your post[/zrl]'), $recip['channel_name'], '[zrl=' . $sender['xchan_url'] . ']' . $sender['xchan_name'] . '[/zrl]', $itemlink);
         $sitelink = t('Please visit %s to view and/or reply to the conversation.');
         $tsitelink = sprintf($sitelink, $siteurl);
         $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
         $itemlink = $params['link'];
     }
     if ($params['type'] == NOTIFY_INTRO) {
         $subject = sprintf(t('[$Projectname:Notify] Introduction received'));
         $preamble = sprintf(t('%1$s, you\'ve received an new connection request from \'%2$s\' at %3$s'), $recip['channel_name'], $sender['xchan_name'], $sitename);
         $epreamble = sprintf(t('%1$s, you\'ve received [zrl=%2$s]a new connection request[/zrl] from %3$s.'), $recip['channel_name'], $siteurl . '/connections/ifpending', '[zrl=' . $sender['xchan_url'] . ']' . $sender['xchan_name'] . '[/zrl]');
         $body = sprintf(t('You may visit their profile at %s'), $sender['xchan_url']);
         $sitelink = t('Please visit %s to approve or reject the connection request.');
         $tsitelink = sprintf($sitelink, $siteurl . '/connections/ifpending');
         $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '/connections/ifpending">' . $sitename . '</a>');
         $itemlink = $params['link'];
     }
     if ($params['type'] == NOTIFY_SUGGEST) {
         $subject = sprintf(t('[$Projectname:Notify] Friend suggestion received'));
         $preamble = sprintf(t('%1$s, you\'ve received a friend suggestion from \'%2$s\' at %3$s'), $recip['channel_name'], $sender['xchan_name'], $sitename);
         $epreamble = sprintf(t('%1$s, you\'ve received [zrl=%2$s]a friend suggestion[/zrl] for %3$s from %4$s.'), $recip['channel_name'], $itemlink, '[zrl=' . $params['item']['url'] . ']' . $params['item']['name'] . '[/zrl]', '[zrl=' . $sender['xchan_url'] . ']' . $sender['xchan_name'] . '[/zrl]');
         $body = t('Name:') . ' ' . $params['item']['name'] . "\n";
         $body .= t('Photo:') . ' ' . $params['item']['photo'] . "\n";
         $body .= sprintf(t('You may visit their profile at %s'), $params['item']['url']);
         $sitelink = t('Please visit %s to approve or reject the suggestion.');
         $tsitelink = sprintf($sitelink, $siteurl);
         $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
         $itemlink = $params['link'];
     }
     if ($params['type'] == NOTIFY_CONFIRM) {
         // ?
     }
     if ($params['type'] == NOTIFY_SYSTEM) {
         // ?
     }
     $h = array('params' => $params, 'subject' => $subject, 'preamble' => $preamble, 'epreamble' => $epreamble, 'body' => $body, 'sitelink' => $sitelink, 'sitename' => $sitename, 'tsitelink' => $tsitelink, 'hsitelink' => $hsitelink, 'itemlink' => $itemlink, 'sender' => $sender, 'recipient' => $recip);
     call_hooks('enotify', $h);
     $subject = $h['subject'];
     $preamble = $h['preamble'];
     $epreamble = $h['epreamble'];
     $body = $h['body'];
     $sitelink = $h['sitelink'];
     $tsitelink = $h['tsitelink'];
     $hsitelink = $h['hsitelink'];
     $itemlink = $h['itemlink'];
     require_once 'include/html2bbcode.php';
     do {
         $dups = false;
         $hash = random_string();
         $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1", dbesc($hash));
         if ($r) {
             $dups = true;
         }
     } while ($dups === true);
     $datarray = array();
     $datarray['hash'] = $hash;
     $datarray['sender_hash'] = $sender['xchan_hash'];
     $datarray['xname'] = $sender['xchan_name'];
     $datarray['url'] = $sender['xchan_url'];
     $datarray['photo'] = $sender['xchan_photo_s'];
     $datarray['created'] = datetime_convert();
     $datarray['aid'] = $recip['channel_account_id'];
     $datarray['uid'] = $recip['channel_id'];
     $datarray['link'] = $itemlink;
     $datarray['parent'] = $parent_mid;
     $datarray['parent_item'] = $parent_item;
     $datarray['ntype'] = $params['type'];
     $datarray['verb'] = $params['verb'];
     $datarray['otype'] = $params['otype'];
     $datarray['abort'] = false;
     $datarray['item'] = $params['item'];
     call_hooks('enotify_store', $datarray);
     if ($datarray['abort']) {
         pop_lang();
         return;
     }
     // create notification entry in DB
     $seen = 0;
     // Mark some notifications as seen right away
     // Note! The notification have to be created, because they are used to send emails
     // So easiest solution to hide them from Notices is to mark them as seen right away.
     // Another option would be to not add them to the DB, and change how emails are handled
     // (probably would be better that way)
     $always_show_in_notices = get_pconfig($recip['channel_id'], 'system', 'always_show_in_notices');
     if (!$always_show_in_notices) {
         if ($params['type'] == NOTIFY_WALL || $params['type'] == NOTIFY_MAIL || $params['type'] == NOTIFY_INTRO) {
             $seen = 1;
         }
     }
     $r = q("insert into notify (hash,xname,url,photo,created,aid,uid,link,parent,seen,ntype,verb,otype)\n\t\tvalues('%s','%s','%s','%s','%s',%d,%d,'%s','%s',%d,%d,'%s','%s')", dbesc($datarray['hash']), dbesc($datarray['xname']), dbesc($datarray['url']), dbesc($datarray['photo']), dbesc($datarray['created']), intval($datarray['aid']), intval($datarray['uid']), dbesc($datarray['link']), dbesc($datarray['parent']), intval($seen), intval($datarray['ntype']), dbesc($datarray['verb']), dbesc($datarray['otype']));
     $r = q("select id from notify where hash = '%s' and uid = %d limit 1", dbesc($hash), intval($recip['channel_id']));
     if ($r) {
         $notify_id = $r[0]['id'];
     } else {
         logger('notification not found.');
         pop_lang();
         return;
     }
     $itemlink = z_root() . '/notify/view/' . $notify_id;
     $msg = str_replace('$itemlink', $itemlink, $epreamble);
     // wretched hack, but we don't want to duplicate all the preamble variations and we also don't want to screw up a translation
     if ((\App::$language === 'en' || !\App::$language) && strpos($msg, ', ')) {
         $msg = substr($msg, strpos($msg, ', ') + 1);
     }
     $r = q("update notify set msg = '%s' where id = %d and uid = %d", dbesc($msg), intval($notify_id), intval($datarray['uid']));
     // send email notification if notification preferences permit
     require_once 'bbcode.php';
     if (intval($recip['channel_notifyflags']) & intval($params['type']) || $params['type'] == NOTIFY_SYSTEM) {
         logger('notification: sending notification email');
         $hn = get_pconfig($recip['channel_id'], 'system', 'email_notify_host');
         if ($hn && !stristr(\App::get_hostname(), $hn)) {
             // this isn't the email notification host
             pop_lang();
             return;
         }
         $textversion = strip_tags(html_entity_decode(bbcode(stripslashes(str_replace(array("\\r", "\\n"), array("", "\n"), $body))), ENT_QUOTES, 'UTF-8'));
         $htmlversion = bbcode(stripslashes(str_replace(array("\\r", "\\n"), array("", "<br />\n"), $body)));
         // use $_SESSION['zid_override'] to force zid() to use
         // the recipient address instead of the current observer
         $_SESSION['zid_override'] = channel_reddress($recip);
         $_SESSION['zrl_override'] = z_root() . '/channel/' . $recip['channel_address'];
         $textversion = zidify_links($textversion);
         $htmlversion = zidify_links($htmlversion);
         // unset when done to revert to normal behaviour
         unset($_SESSION['zid_override']);
         unset($_SESSION['zrl_override']);
         $datarray = array();
         $datarray['banner'] = $banner;
         $datarray['product'] = $product;
         $datarray['preamble'] = $preamble;
         $datarray['sitename'] = $sitename;
         $datarray['siteurl'] = $siteurl;
         $datarray['type'] = $params['type'];
         $datarray['parent'] = $params['parent_mid'];
         $datarray['source_name'] = $sender['xchan_name'];
         $datarray['source_link'] = $sender['xchan_url'];
         $datarray['source_photo'] = $sender['xchan_photo_s'];
         $datarray['uid'] = $recip['channel_id'];
         $datarray['username'] = $recip['channel_name'];
         $datarray['hsitelink'] = $hsitelink;
         $datarray['tsitelink'] = $tsitelink;
         $datarray['hitemlink'] = '<a href="' . $itemlink . '">' . $itemlink . '</a>';
         $datarray['titemlink'] = $itemlink;
         $datarray['thanks'] = $thanks;
         $datarray['site_admin'] = $site_admin;
         $datarray['title'] = stripslashes($title);
         $datarray['htmlversion'] = $htmlversion;
         $datarray['textversion'] = $textversion;
         $datarray['subject'] = $subject;
         $datarray['headers'] = $additional_mail_header;
         $datarray['email_secure'] = false;
         call_hooks('enotify_mail', $datarray);
         // Default to private - don't disclose message contents over insecure channels (such as email)
         // Might be interesting to use GPG,PGP,S/MIME encryption instead
         // but we'll save that for a clever plugin developer to implement
         $private_activity = false;
         if (!$datarray['email_secure']) {
             switch ($params['type']) {
                 case NOTIFY_WALL:
                 case NOTIFY_TAGSELF:
                 case NOTIFY_POKE:
                 case NOTIFY_COMMENT:
                     if (!$private) {
                         break;
                     }
                     $private_activity = true;
                 case NOTIFY_MAIL:
                     $datarray['textversion'] = $datarray['htmlversion'] = $datarray['title'] = '';
                     $datarray['subject'] = preg_replace('/' . preg_quote(t('[$Projectname:Notify]')) . '/', '$0*', $datarray['subject']);
                     break;
                 default:
                     break;
             }
         }
         if ($private_activity && intval(get_pconfig($datarray['uid'], 'system', 'ignore_private_notifications'))) {
             pop_lang();
             return;
         }
         // load the template for private message notifications
         $tpl = get_markup_template('email_notify_html.tpl');
         $email_html_body = replace_macros($tpl, array('$banner' => $datarray['banner'], '$notify_icon' => \Zotlabs\Lib\System::get_notify_icon(), '$product' => $datarray['product'], '$preamble' => $datarray['preamble'], '$sitename' => $datarray['sitename'], '$siteurl' => $datarray['siteurl'], '$source_name' => $datarray['source_name'], '$source_link' => $datarray['source_link'], '$source_photo' => $datarray['source_photo'], '$username' => $datarray['to_name'], '$hsitelink' => $datarray['hsitelink'], '$hitemlink' => $datarray['hitemlink'], '$thanks' => $datarray['thanks'], '$site_admin' => $datarray['site_admin'], '$title' => $datarray['title'], '$htmlversion' => $datarray['htmlversion']));
         // load the template for private message notifications
         $tpl = get_markup_template('email_notify_text.tpl');
         $email_text_body = replace_macros($tpl, array('$banner' => $datarray['banner'], '$product' => $datarray['product'], '$preamble' => $datarray['preamble'], '$sitename' => $datarray['sitename'], '$siteurl' => $datarray['siteurl'], '$source_name' => $datarray['source_name'], '$source_link' => $datarray['source_link'], '$source_photo' => $datarray['source_photo'], '$username' => $datarray['to_name'], '$tsitelink' => $datarray['tsitelink'], '$titemlink' => $datarray['titemlink'], '$thanks' => $datarray['thanks'], '$site_admin' => $datarray['site_admin'], '$title' => $datarray['title'], '$textversion' => $datarray['textversion']));
         //		logger('text: ' . $email_text_body);
         // use the EmailNotification library to send the message
         self::send(array('fromName' => $sender_name, 'fromEmail' => $sender_email, 'replyTo' => $reply_email, 'toEmail' => $recip['account_email'], 'messageSubject' => $datarray['subject'], 'htmlVersion' => $email_html_body, 'textVersion' => $email_text_body, 'additionalMailHeader' => $datarray['headers']));
     }
     pop_lang();
 }
Пример #30
0
/**
 * We can't trust ITEM_ORIGIN to tell us if this is a local comment
 * which needs to be relayed, because it was misconfigured at one point for several
 * months and set for some remote items (in alternate delivery chains). This could
 * cause looping, so use this hackish but accurate method.
 *
 * @param array $item
 * @return boolean
 */
function comment_local_origin($item)
{
    if (stripos($item['mid'], App::get_hostname()) && $item['parent'] != $item['id']) {
        return true;
    }
    return false;
}