Esempio n. 1
2
function removeme_post(&$a)
{
    if (!local_channel()) {
        return;
    }
    if ($_SESSION['delegate']) {
        return;
    }
    if (!x($_POST, 'qxz_password') || !strlen(trim($_POST['qxz_password']))) {
        return;
    }
    if (!x($_POST, 'verify') || !strlen(trim($_POST['verify']))) {
        return;
    }
    if ($_POST['verify'] !== $_SESSION['remove_account_verify']) {
        return;
    }
    $account = App::get_account();
    if (!account_verify_password($account['account_email'], $_POST['qxz_password'])) {
        return;
    }
    if ($account['account_password_changed'] != NULL_DATE) {
        $d1 = datetime_convert('UTC', 'UTC', 'now - 48 hours');
        if ($account['account_password_changed'] > d1) {
            notice(t('Channel removals are not allowed within 48 hours of changing the account password.') . EOL);
            return;
        }
    }
    require_once 'include/Contact.php';
    $global_remove = intval($_POST['global']);
    channel_remove(local_channel(), 1 - $global_remove, true);
}
 private static function row2array($row, $timezone, $hostname, $uid, $namespace_id)
 {
     $v = new vcalendar();
     $v->setConfig('unique_id', $hostname);
     $v->setProperty('method', 'PUBLISH');
     $v->setProperty("x-wr-calname", "AnimexxCal");
     $v->setProperty("X-WR-CALDESC", "Animexx Calendar");
     $v->setProperty("X-WR-TIMEZONE", $timezone);
     if ($row["adjust"]) {
         $start = datetime_convert('UTC', date_default_timezone_get(), $row["start"]);
         $finish = datetime_convert('UTC', date_default_timezone_get(), $row["finish"]);
     } else {
         $start = $row["start"];
         $finish = $row["finish"];
     }
     $allday = strpos($start, "00:00:00") !== false && strpos($finish, "00:00:00") !== false;
     /*
     
     if ($allday) {
     	$dat = Datetime::createFromFormat("Y-m-d H:i:s", $finish_tmp);
     	$dat->sub(new DateInterval("P1D"));
     	$finish = datetime_convert("UTC", date_default_timezone_get(), $dat->format("Y-m-d H:i:s"));
     	var_dump($finish);
     }
     */
     $subject = substr(preg_replace("/\\[[^\\]]*\\]/", "", $row["desc"]), 0, 100);
     $description = preg_replace("/\\[[^\\]]*\\]/", "", $row["desc"]);
     $vevent = dav_create_vevent(wdcal_mySql2icalTime($row["start"]), wdcal_mySql2icalTime($row["finish"]), false);
     $vevent->setLocation(icalendar_sanitize_string($row["location"]));
     $vevent->setSummary(icalendar_sanitize_string($subject));
     $vevent->setDescription(icalendar_sanitize_string($description));
     $v->setComponent($vevent);
     $ical = $v->createCalendar();
     return array("uid" => $uid, "namespace" => CALDAV_NAMESPACE_FRIENDICA_NATIVE, "namespace_id" => $namespace_id, "date" => $row["edited"], "data_uri" => "friendica-" . $namespace_id . "-" . $row["id"] . "@" . $hostname, "data_subject" => $subject, "data_location" => $row["location"], "data_description" => $description, "data_start" => $start, "data_end" => $finish, "data_allday" => $allday, "data_type" => $row["type"], "ical" => $ical, "ical_size" => strlen($ical), "ical_etag" => md5($ical));
 }
Esempio n. 3
0
/**
 * @brief Log failed logins to a separate auth log.
 *
 * Can be used to reduce overhead for server side intrusion prevention, like
 * parse the authlog file with something like fail2ban, OSSEC, etc.
 *
 * @param string $errormsg
 *  Error message to display for failed login.
 */
function log_failed_login($errormsg)
{
    $authlog = get_config('system', 'authlog');
    if ($authlog) {
        @file_put_contents($authlog, datetime_convert() . ':' . session_id() . ' ' . $errormsg . PHP_EOL, FILE_APPEND);
    }
}
Esempio n. 4
0
 public static function run($argc, $argv)
 {
     logger('cronhooks: start');
     $d = datetime_convert();
     call_hooks('cron', $d);
     return;
 }
function privacy_image_cache_init()
{
    $urlhash = 'pic:' . sha1($_REQUEST['url']);
    $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' LIMIT 1", $urlhash);
    if (count($r)) {
        $img_str = $r[0]['data'];
        $mime = $r[0]["desc"];
        if ($mime == "") {
            $mime = "image/jpeg";
        }
    } else {
        require_once "Photo.php";
        $img_str = fetch_url($_REQUEST['url'], true);
        if (substr($img_str, 0, 6) == "GIF89a") {
            $mime = "image/gif";
            $image = @imagecreatefromstring($img_str);
            if ($image === FALSE) {
                die;
            }
            q("INSERT INTO `photo`\n\t\t\t( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `album`, `height`, `width`, `desc`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )\n\t\t\tVALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' )", 0, 0, get_guid(), dbesc($urlhash), dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc(basename(dbesc($_REQUEST["url"]))), dbesc(''), intval(imagesy($image)), intval(imagesx($image)), 'image/gif', dbesc($img_str), 100, intval(0), dbesc(''), dbesc(''), dbesc(''), dbesc(''));
        } else {
            $img = new Photo($img_str);
            if ($img->is_valid()) {
                $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
                $img_str = $img->imageString();
            }
            $mime = "image/jpeg";
        }
    }
    header("Content-type: {$mime}");
    header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600 * 24) . " GMT");
    header("Cache-Control: max-age=" . 3600 * 24);
    echo $img_str;
    killme();
}
Esempio n. 6
0
 public static function run($argc, $argv)
 {
     /**
      * Cron Weekly
      * 
      * Actions in the following block are executed once per day only on Sunday (once per week).
      *
      */
     call_hooks('cron_weekly', datetime_convert());
     z_check_cert();
     require_once 'include/hubloc.php';
     prune_hub_reinstalls();
     mark_orphan_hubsxchans();
     // get rid of really old poco records
     q("delete from xlink where xlink_updated < %s - INTERVAL %s and xlink_static = 0 ", db_utcnow(), db_quoteinterval('14 DAY'));
     $dirmode = intval(get_config('system', 'directory_mode'));
     if ($dirmode === DIRECTORY_MODE_SECONDARY || $dirmode === DIRECTORY_MODE_PRIMARY) {
         logger('regdir: ' . print_r(z_fetch_url(get_directory_primary() . '/regdir?f=&url=' . urlencode(z_root()) . '&realm=' . urlencode(get_directory_realm())), true));
     }
     // Check for dead sites
     Master::Summon(array('Checksites'));
     // update searchable doc indexes
     Master::Summon(array('Importdoc'));
     /**
      * End Cron Weekly
      */
 }
 function post()
 {
     if (!local_channel()) {
         return;
     }
     if ($_SESSION['delegate']) {
         return;
     }
     if (!x($_POST, 'qxz_password') || !strlen(trim($_POST['qxz_password']))) {
         return;
     }
     if (!x($_POST, 'verify') || !strlen(trim($_POST['verify']))) {
         return;
     }
     if ($_POST['verify'] !== $_SESSION['remove_account_verify']) {
         return;
     }
     $account = \App::get_account();
     $account_id = get_account_id();
     if (!account_verify_password($account['account_email'], $_POST['qxz_password'])) {
         return;
     }
     if ($account['account_password_changed'] != NULL_DATE) {
         $d1 = datetime_convert('UTC', 'UTC', 'now - 48 hours');
         if ($account['account_password_changed'] > d1) {
             notice(t('Account removals are not allowed within 48 hours of changing the account password.') . EOL);
             return;
         }
     }
     $global_remove = intval($_POST['global']);
     account_remove($account_id, 1 - $global_remove);
 }
Esempio n. 8
0
function find_diaspora_person_by_handle($handle)
{
    $person = false;
    $refresh = false;
    if (diaspora_is_blacklisted($handle)) {
        return false;
    }
    $r = q("select * from xchan where xchan_addr = '%s' limit 1", dbesc($handle));
    if ($r) {
        $person = $r[0];
        logger('find_diaspora_person_by handle: in cache ' . print_r($r, true), LOGGER_DATA, LOG_DEBUG);
        if ($person['xchan_name_date'] < datetime_convert('UTC', 'UTC', 'now - 1 month')) {
            logger('Updating Diaspora cached record for ' . $handle);
            $refresh = true;
        }
    }
    if (!$person || $refresh) {
        // try webfinger. Make sure to distinguish between diaspora,
        // hubzilla w/diaspora protocol and friendica w/diaspora protocol.
        $result = discover_by_webbie($handle);
        if ($result) {
            $r = q("select * from xchan where xchan_addr = '%s' limit 1", dbesc(str_replace('acct:', '', $handle)));
            if ($r) {
                $person = $r[0];
                logger('find_diaspora_person_by handle: discovered ' . print_r($r, true), LOGGER_DATA, LOG_DEBUG);
            }
        }
    }
    return $person;
}
Esempio n. 9
0
function testdrive_cron($a, $b)
{
    $r = q("select * from account where account_expires_on < %s + INTERVAL %s and\n\t\taccount_expire_notified = '%s' ", db_utcnow(), db_quoteinterval('5 DAY'), dbesc(NULL_DATE));
    if ($r) {
        foreach ($r as $rr) {
            $uid = $rr['account_default_channel'];
            if (!$uid) {
                continue;
            }
            $x = q("select * from channel where channel_id = %d limit 1", intval($uid));
            if (!$x) {
                continue;
            }
            \Zotlabs\Lib\Enotify::submit(array('type' => NOTIFY_SYSTEM, 'system_type' => 'testdrive_expire', 'from_xchan' => $x[0]['channel_hash'], 'to_xchan' => $x[0]['channel_hash']));
            q("update account set account_expire_notified = '%s' where account_id = %d", dbesc(datetime_convert()), intval($rr['account_id']));
        }
    }
    // give them a 5 day grace period. Then nuke the account.
    $r = q("select * from account where account_expired = 1 and account_expires < %s - INTERVAL %s", db_utcnow(), db_quoteinterval('5 DAY'));
    if ($r) {
        foreach ($r as $rr) {
            account_remove($rr['account_id']);
        }
    }
}
Esempio n. 10
0
 function q($sql)
 {
     if (!$this->db || !$this->connected) {
         return false;
     }
     $this->error = '';
     $result = @mysql_query($sql, $this->db);
     if (mysql_errno($this->db)) {
         $this->error = mysql_error($this->db);
     }
     if ($result === false || $this->error) {
         logger('dba_mysql: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
         if (file_exists('dbfail.out')) {
             file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
         }
     }
     if ($result === true || $result === false) {
         return $result;
     }
     $r = array();
     if (mysql_num_rows($result)) {
         while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
             $r[] = $x;
         }
         mysql_free_result($result);
         if ($this->debug) {
             logger('dba_mysql: ' . printable(print_r($r, true)));
         }
     }
     return $r;
 }
Esempio n. 11
0
function checksites_run($argv, $argc)
{
    cli_startup();
    $a = get_app();
    logger('checksites: start');
    if ($argc > 1 && $argv[1]) {
        $site_id = $argv[1];
    }
    if ($site_id) {
        $sql_options = " and site_url = '" . dbesc($argv[1]) . "' ";
    }
    $days = intval(get_config('system', 'sitecheckdays'));
    if ($days < 1) {
        $days = 30;
    }
    $r = q("select * from site where site_dead = 0 and site_update < %s - INTERVAL %s and site_type = %d {$sql_options} ", db_utcnow(), db_quoteinterval($days . ' DAY'), intval(SITE_TYPE_ZOT));
    if (!$r) {
        return;
    }
    foreach ($r as $rr) {
        if (!strcasecmp($rr['site_url'], z_root())) {
            continue;
        }
        $x = ping_site($rr['site_url']);
        if ($x['success']) {
            logger('checksites: ' . $rr['site_url']);
            q("update site set site_update = '%s' where site_url = '%s' ", dbesc(datetime_convert()), dbesc($rr['site_url']));
        } else {
            logger('marking dead site: ' . $x['message']);
            q("update site set site_dead = 1 where site_url = '%s' ", dbesc($rr['site_url']));
        }
    }
    return;
}
Esempio n. 12
0
 function lock_function($fn_name, $block = true, $wait_sec = 2, $timeout = 30)
 {
     if ($wait_sec == 0) {
         $wait_sec = 2;
     }
     // don't let the user pick a value that's likely to crash the system
     $got_lock = false;
     $start = time();
     do {
         q("LOCK TABLE `locks` WRITE");
         $r = q("SELECT `locked`, `created` FROM `locks` WHERE `name` = '%s' LIMIT 1", dbesc($fn_name));
         if (count($r) and (!$r[0]['locked'] or strtotime($r[0]['created']) < time() - 3600)) {
             q("UPDATE `locks` SET `locked` = 1, `created` = '%s' WHERE `name` = '%s'", dbesc(datetime_convert()), dbesc($fn_name));
             $got_lock = true;
         } elseif (!$r) {
             // the Boolean value for count($r) should be equivalent to the Boolean value of $r
             q("INSERT INTO `locks` (`name`, `created`, `locked`) VALUES ('%s', '%s', 1)", dbesc($fn_name), dbesc(datetime_convert()));
             $got_lock = true;
         }
         q("UNLOCK TABLES");
         if ($block && !$got_lock) {
             sleep($wait_sec);
         }
     } while ($block && !$got_lock && time() - $start < $timeout);
     logger('lock_function: function ' . $fn_name . ' with blocking = ' . $block . ' got_lock = ' . $got_lock . ' time = ' . (time() - $start), LOGGER_DEBUG);
     return $got_lock;
 }
Esempio n. 13
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();
}
Esempio n. 14
0
 public static function clear()
 {
     q("DELETE FROM `cache` WHERE `updated` < '%s' AND `expire_mode` = %d", dbesc(datetime_convert('UTC', 'UTC', "now - 30 days")), intval(CACHE_MONTH));
     q("DELETE FROM `cache` WHERE `updated` < '%s' AND `expire_mode` = %d", dbesc(datetime_convert('UTC', 'UTC', "now - 7 days")), intval(CACHE_WEEK));
     q("DELETE FROM `cache` WHERE `updated` < '%s' AND `expire_mode` = %d", dbesc(datetime_convert('UTC', 'UTC', "now - 1 days")), intval(CACHE_DAY));
     q("DELETE FROM `cache` WHERE `updated` < '%s' AND `expire_mode` = %d", dbesc(datetime_convert('UTC', 'UTC', "now - 1 hours")), intval(CACHE_HOUR));
 }
Esempio n. 15
0
function handle_pubsubhubbub()
{
    global $a, $db;
    logger('start');
    // We'll push to each subscriber that has push > 0,
    // i.e. there has been an update (set in notifier.php).
    $r = q("SELECT * FROM `push_subscriber` WHERE `push` > 0");
    foreach ($r as $rr) {
        $params = get_feed_for($a, '', $rr['nickname'], $rr['last_update'], 0, true);
        $hmac_sig = hash_hmac("sha1", $params, $rr['secret']);
        $headers = array("Content-type: application/atom+xml", sprintf("Link: <%s>;rel=hub," . "<%s>;rel=self", $a->get_baseurl() . '/pubsubhubbub', $rr['topic']), "X-Hub-Signature: sha1=" . $hmac_sig);
        logger('POST ' . print_r($headers, true) . "\n" . $params, LOGGER_DEBUG);
        post_url($rr['callback_url'], $params, $headers);
        $ret = $a->get_curl_code();
        if ($ret >= 200 && $ret <= 299) {
            logger('successfully pushed to ' . $rr['callback_url']);
            // set last_update to "now", and reset push=0
            $date_now = datetime_convert('UTC', 'UTC', 'now', 'Y-m-d H:i:s');
            q("UPDATE `push_subscriber` SET `push` = 0, last_update = '%s' WHERE id = %d", dbesc($date_now), intval($rr['id']));
        } else {
            logger('error when pushing to ' . $rr['callback_url'] . ' HTTP: ' . $ret);
            // we use the push variable also as a counter, if we failed we
            // increment this until some upper limit where we give up
            $new_push = intval($rr['push']) + 1;
            if ($new_push > 30) {
                // OK, let's give up
                $new_push = 0;
            }
            q("UPDATE `push_subscriber` SET `push` = %d WHERE id = %d", $new_push, intval($rr['id']));
        }
    }
    logger('done');
}
Esempio n. 16
0
function removeaccount_post(&$a)
{
    if (!local_user()) {
        return;
    }
    if (x($_SESSION, 'submanage') && intval($_SESSION['submanage'])) {
        return;
    }
    if (!x($_POST, 'qxz_password') || !strlen(trim($_POST['qxz_password']))) {
        return;
    }
    if (!x($_POST, 'verify') || !strlen(trim($_POST['verify']))) {
        return;
    }
    if ($_POST['verify'] !== $_SESSION['remove_account_verify']) {
        return;
    }
    $account = $a->get_account();
    $account_id = get_account_id();
    if (!account_verify_password($account['account_email'], $_POST['qxz_password'])) {
        return;
    }
    if ($account['account_password_changed'] != NULL_DATE) {
        $d1 = datetime_convert('UTC', 'UTC', 'now - 48 hours');
        if ($account['account_password_changed'] > d1) {
            notice(t('Account removals are not allowed within 48 hours of changing the account password.') . EOL);
            return;
        }
    }
    require_once 'include/Contact.php';
    $global_remove = intval($_POST['global']);
    account_remove($account_id, true);
}
Esempio n. 17
0
function crepair_post(&$a)
{
    if (!local_user()) {
        return;
    }
    $cid = $a->argc > 1 ? intval($a->argv[1]) : 0;
    if ($cid) {
        $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($cid), intval(local_user()));
    }
    if (!count($r)) {
        return;
    }
    $contact = $r[0];
    $nick = x($_POST, 'nick') ? $_POST['nick'] : '';
    $url = x($_POST, 'url') ? $_POST['url'] : '';
    $request = x($_POST, 'request') ? $_POST['request'] : '';
    $confirm = x($_POST, 'confirm') ? $_POST['confirm'] : '';
    $notify = x($_POST, 'notify') ? $_POST['notify'] : '';
    $poll = x($_POST, 'poll') ? $_POST['poll'] : '';
    $attag = x($_POST, 'attag') ? $_POST['attag'] : '';
    $photo = x($_POST, 'photo') ? $_POST['photo'] : '';
    $r = q("UPDATE `contact` SET `nick` = '%s', `url` = '%s', `request` = '%s', `confirm` = '%s', `notify` = '%s', `poll` = '%s', `attag` = '%s' \n\t\tWHERE `id` = %d AND `uid` = %d LIMIT 1", dbesc($nick), dbesc($url), dbesc($request), dbesc($confirm), dbesc($notify), dbesc($poll), dbesc($attag), intval($contact['id']), local_user());
    if ($photo) {
        logger('mod-crepair: updating photo from ' . $photo);
        require_once "Photo.php";
        $photos = import_profile_photo($photo, local_user(), $contact['id']);
        $x = q("UPDATE `contact` SET `photo` = '%s',\n\t\t\t`thumb` = '%s',\n\t\t\t`micro` = '%s',\n\t\t\t`name-date` = '%s',\n\t\t\t`uri-date` = '%s',\n\t\t\t`avatar-date` = '%s'\n\t\t\tWHERE `id` = %d LIMIT 1\n\t\t\t", dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc(datetime_convert()), intval($contact['id']));
    }
    if ($r) {
        info(t('Contact settings applied.') . EOL);
    } else {
        notice(t('Contact update failed.') . EOL);
    }
    return;
}
Esempio n. 18
0
 function post()
 {
     if (!local_channel()) {
         return;
     }
     if (\App::$argc != 2) {
         return;
     }
     $contact_id = intval(\App::$argv[1]);
     $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($contact_id), intval(local_channel()));
     if (!count($r)) {
         notice(t('Contact not found.') . EOL);
         return;
     }
     $contact = $r[0];
     $new_contact = intval($_POST['suggest']);
     $hash = random_string();
     $note = escape_tags(trim($_POST['note']));
     if ($new_contact) {
         $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($new_contact), intval(local_channel()));
         if (count($r)) {
             $x = q("INSERT INTO `fsuggest` ( `uid`,`cid`,`name`,`url`,`request`,`photo`,`note`,`created`)\n\t\t\t\t\tVALUES ( %d, %d, '%s','%s','%s','%s','%s','%s')", intval(local_channel()), intval($contact_id), dbesc($r[0]['name']), dbesc($r[0]['url']), dbesc($r[0]['request']), dbesc($r[0]['photo']), dbesc($hash), dbesc(datetime_convert()));
             $r = q("SELECT `id` FROM `fsuggest` WHERE `note` = '%s' AND `uid` = %d LIMIT 1", dbesc($hash), intval(local_channel()));
             if (count($r)) {
                 $fsuggest_id = $r[0]['id'];
                 q("UPDATE `fsuggest` SET `note` = '%s' WHERE `id` = %d AND `uid` = %d", dbesc($note), intval($fsuggest_id), intval(local_channel()));
                 proc_run('php', 'include/notifier.php', 'suggest', $fsuggest_id);
             }
             info(t('Friend suggestion sent.') . EOL);
         }
     }
 }
Esempio n. 19
0
 function init()
 {
     $result = array('success' => false);
     $mindate = $_REQUEST['mindate'] ? datetime_convert('UTC', 'UTC', $_REQUEST['mindate']) : '';
     if (!$mindate) {
         $mindate = datetime_convert('UTC', 'UTC', 'now - 14 days');
     }
     if (observer_prohibited()) {
         $result['message'] = 'Public access denied';
         json_return_and_die($result);
     }
     $observer = \App::get_observer();
     $channel_address = argc() > 1 ? argv(1) : '';
     if ($channel_address) {
         $r = q("select channel_id, channel_name from channel where channel_address = '%s' and channel_removed = 0 limit 1", dbesc(argv(1)));
     } else {
         $x = get_sys_channel();
         if ($x) {
             $r = array($x);
         }
         $mindate = datetime_convert('UTC', 'UTC', 'now - 14 days');
     }
     if (!$r) {
         $result['message'] = 'Channel not found.';
         json_return_and_die($result);
     }
     logger('zotfeed request: ' . $r[0]['channel_name'], LOGGER_DEBUG);
     $result['messages'] = zot_feed($r[0]['channel_id'], $observer['xchan_hash'], array('mindate' => $mindate));
     $result['success'] = true;
     json_return_and_die($result);
 }
Esempio n. 20
0
function zotfeed_init(&$a)
{
    $result = array('success' => false);
    $mindate = $_REQUEST['mindate'] ? datetime_convert('UTC', 'UTC', $_REQUEST['mindate']) : '';
    if (!$mindate) {
        $mindate = datetime_convert('UTC', 'UTC', 'now - 1 month');
    }
    if (get_config('system', 'block_public') && !get_account_id() && !remote_user()) {
        $result['message'] = 'Public access denied';
        json_return_and_die($result);
    }
    $observer = $a->get_observer();
    $channel_address = argc() > 1 ? argv(1) : '';
    if ($channel_address) {
        $r = q("select channel_id, channel_name from channel where channel_address = '%s' and not (channel_pageflags & %d) limit 1", dbesc(argv(1)), intval(PAGE_REMOVED));
    } else {
        $x = get_sys_channel();
        if ($x) {
            $r = array($x);
        }
    }
    if (!$r) {
        $result['message'] = 'Channel not found.';
        json_return_and_die($result);
    }
    logger('zotfeed request: ' . $r[0]['channel_name'], LOGGER_DEBUG);
    $result['messages'] = zot_feed($r[0]['channel_id'], $observer['xchan_hash'], $mindate);
    $result['success'] = true;
    json_return_and_die($result);
}
Esempio n. 21
0
function cronhooks_run($argv, $argc)
{
    cli_startup();
    logger('cronhooks: start');
    $d = datetime_convert();
    call_hooks('cron', $d);
    return;
}
Esempio n. 22
0
 function post()
 {
     $hash = $_POST['hash'];
     $time = $_POST['time'];
     $sig = $_POST['signature'];
     $resource = $_POST['resource'];
     $revision = intval($_POST['revision']);
     if (!$hash) {
         killme();
     }
     $channel = channelx_by_hash($hash);
     if (!$channel || !$time || !$sig) {
         killme();
     }
     $slop = intval(get_pconfig($channel['channel_id'], 'system', 'getfile_time_slop'));
     if ($slop < 1) {
         $slop = 3;
     }
     $d1 = datetime_convert('UTC', 'UTC', "now + {$slop} minutes");
     $d2 = datetime_convert('UTC', 'UTC', "now - {$slop} minutes");
     if ($time > $d1 || $time < $d2) {
         logger('time outside allowable range');
         killme();
     }
     if (!rsa_verify($hash . '.' . $time, base64url_decode($sig), $channel['channel_pubkey'])) {
         logger('verify failed.');
         killme();
     }
     $r = attach_by_hash($resource, $revision);
     if (!$r['success']) {
         notice($r['message'] . EOL);
         return;
     }
     $unsafe_types = array('text/html', 'text/css', 'application/javascript');
     if (in_array($r['data']['filetype'], $unsafe_types)) {
         header('Content-type: text/plain');
     } else {
         header('Content-type: ' . $r['data']['filetype']);
     }
     header('Content-disposition: attachment; filename="' . $r['data']['filename'] . '"');
     if (intval($r['data']['os_storage'])) {
         $fname = dbunescbin($r['data']['data']);
         if (strpos($fname, 'store') !== false) {
             $istream = fopen($fname, 'rb');
         } else {
             $istream = fopen('store/' . $channel['channel_address'] . '/' . $fname, 'rb');
         }
         $ostream = fopen('php://output', 'wb');
         if ($istream && $ostream) {
             pipe_streams($istream, $ostream);
             fclose($istream);
             fclose($ostream);
         }
     } else {
         echo dbunescbin($r['data']['data']);
     }
     killme();
 }
Esempio n. 23
0
/**
 * @brief
 *
 * @param array $argv
 * @param array $argc
 */
function directory_run($argv, $argc)
{
    cli_startup();
    if ($argc < 2) {
        return;
    }
    $force = false;
    $pushall = true;
    if ($argc > 2) {
        if ($argv[2] === 'force') {
            $force = true;
        }
        if ($argv[2] === 'nopush') {
            $pushall = false;
        }
    }
    logger('directory update', LOGGER_DEBUG);
    $dirmode = get_config('system', 'directory_mode');
    if ($dirmode === false) {
        $dirmode = DIRECTORY_MODE_NORMAL;
    }
    $x = q("select * from channel where channel_id = %d limit 1", intval($argv[1]));
    if (!$x) {
        return;
    }
    $channel = $x[0];
    if ($dirmode != DIRECTORY_MODE_NORMAL) {
        // this is an in-memory update and we don't need to send a network packet.
        local_dir_update($argv[1], $force);
        q("update channel set channel_dirdate = '%s' where channel_id = %d", dbesc(datetime_convert()), intval($channel['channel_id']));
        // Now update all the connections
        if ($pushall) {
            proc_run('php', 'include/notifier.php', 'refresh_all', $channel['channel_id']);
        }
        return;
    }
    // otherwise send the changes upstream
    $directory = find_upstream_directory($dirmode);
    $url = $directory['url'] . '/post';
    // ensure the upstream directory is updated
    $packet = zot_build_packet($channel, $force ? 'force_refresh' : 'refresh');
    $z = zot_zot($url, $packet);
    // re-queue if unsuccessful
    if (!$z['success']) {
        /** @FIXME we aren't updating channel_dirdate if we have to queue
         * the directory packet. That means we'll try again on the next poll run.
         */
        $hash = random_string();
        q("insert into outq ( outq_hash, outq_account, outq_channel, outq_driver, outq_posturl, outq_async, outq_created, outq_updated, outq_notify, outq_msg ) \n\t\t\tvalues ( '%s', %d, %d, '%s', '%s', %d, '%s', '%s', '%s', '%s' )", dbesc($hash), intval($channel['channel_account_id']), intval($channel['channel_id']), dbesc('zot'), dbesc($url), intval(1), dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc($packet), dbesc(''));
    } else {
        q("update channel set channel_dirdate = '%s' where channel_id = %d", dbesc(datetime_convert()), intval($channel['channel_id']));
    }
    // Now update all the connections
    if ($pushall) {
        proc_run('php', 'include/notifier.php', 'refresh_all', $channel['channel_id']);
    }
}
Esempio n. 24
0
function p_init($a)
{
    if ($a->argc != 2) {
        header($_SERVER["SERVER_PROTOCOL"] . ' 510 ' . t('Not Extended'));
        killme();
    }
    $guid = $a->argv[1];
    if (strtolower(substr($guid, -4)) != ".xml") {
        header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . t('Not Found'));
        killme();
    }
    $guid = strtolower(substr($guid, 0, -4));
    $item = q("SELECT `body`, `guid`, `contact-id`, `private`, `created`, `app` FROM `item` WHERE `uid` = 0 AND `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1", dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
    if (!$item) {
        header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . t('Not Found'));
        killme();
    }
    $post = array();
    $reshared = diaspora_is_reshare($item[0]["body"]);
    if ($reshared) {
        $nodename = "reshare";
        $post["root_diaspora_id"] = $reshared["root_handle"];
        $post["root_guid"] = $reshared["root_guid"];
        $post["guid"] = $item[0]["guid"];
        $post["diaspora_handle"] = diaspora_handle_from_contact($item[0]["contact-id"]);
        $post["public"] = !$item[0]["private"] ? 'true' : 'false';
        $post["created_at"] = datetime_convert('UTC', 'UTC', $item[0]["created"]);
    } else {
        $nodename = "status_message";
        $post["raw_message"] = str_replace("&", "&amp;", bb2diaspora($item[0]["body"]));
        $post["guid"] = $item[0]["guid"];
        $post["diaspora_handle"] = diaspora_handle_from_contact($item[0]["contact-id"]);
        $post["public"] = !$item[0]["private"] ? 'true' : 'false';
        $post["created_at"] = datetime_convert('UTC', 'UTC', $item[0]["created"]);
        $post["provider_display_name"] = $item[0]["app"];
    }
    $dom = new DOMDocument("1.0");
    $root = $dom->createElement("XML");
    $dom->appendChild($root);
    $postelement = $dom->createElement("post");
    $root->appendChild($postelement);
    $statuselement = $dom->createElement($nodename);
    $postelement->appendChild($statuselement);
    foreach ($post as $index => $value) {
        $postnode = $dom->createElement($index, $value);
        $statuselement->appendChild($postnode);
    }
    header("Content-Type: application/xml; charset=utf-8");
    $xml = $dom->saveXML();
    // Diaspora doesn't send the XML header, so we remove them as well.
    // So we avoid possible compatibility problems.
    if (substr($xml, 0, 21) == '<?xml version="1.0"?>') {
        $xml = trim(substr($xml, 21));
    }
    echo $xml;
    killme();
}
Esempio n. 25
0
function uexport_content(&$a)
{
    $y = datetime_convert('UTC', date_default_timezone_get(), 'now', 'Y');
    $yearurl = z_root() . '/uexport/' . $y;
    $janurl = z_root() . '/uexport/' . $y . '/1';
    $impurl = '/import_items';
    $o = replace_macros(get_markup_template('uexport.tpl'), array('$title' => t('Export Channel'), '$basictitle' => t('Export Channel'), '$basic' => t('Export your basic channel information to a file.  This acts as a backup of your connections, permissions, profile and basic data, which can be used to import your data to a new server hub, but does not contain your content.'), '$fulltitle' => t('Export Content'), '$full' => t('Export your channel information and recent content to a JSON backup that can be restored or imported to another server hub. This backs up all of your connections, permissions, profile data and several months of posts. This file may be VERY large.  Please be patient - it may take several minutes for this download to begin.'), '$by_year' => t('Export your posts from a given year.'), '$extra' => t('You may also export your posts and conversations for a particular year or month. Adjust the date in your browser location bar to select other dates. If the export fails (possibly due to memory exhaustion on your server hub), please try again selecting a more limited date range.'), '$extra2' => sprintf(t('To select all posts for a given year, such as this year, visit <a href="%1$s">%2$s</a>'), $yearurl, $yearurl), '$extra3' => sprintf(t('To select all posts for a given month, such as January of this year, visit <a href="%1$s">%2$s</a>'), $janurl, $janurl), '$extra4' => sprintf(t('These content files may be imported or restored by visiting <a href="%1$s">%2$s</a> on any site containing your channel. For best results please import or restore these in date order (oldest first).'), $impurl, $impurl)));
    return $o;
}
Esempio n. 26
0
 public static function run($argc, $argv)
 {
     if ($argc < 2) {
         return;
     }
     $force = false;
     $pushall = true;
     if ($argc > 2) {
         if ($argv[2] === 'force') {
             $force = true;
         }
         if ($argv[2] === 'nopush') {
             $pushall = false;
         }
     }
     logger('directory update', LOGGER_DEBUG);
     $dirmode = get_config('system', 'directory_mode');
     if ($dirmode === false) {
         $dirmode = DIRECTORY_MODE_NORMAL;
     }
     $x = q("select * from channel where channel_id = %d limit 1", intval($argv[1]));
     if (!$x) {
         return;
     }
     $channel = $x[0];
     if ($dirmode != DIRECTORY_MODE_NORMAL) {
         // this is an in-memory update and we don't need to send a network packet.
         local_dir_update($argv[1], $force);
         q("update channel set channel_dirdate = '%s' where channel_id = %d", dbesc(datetime_convert()), intval($channel['channel_id']));
         // Now update all the connections
         if ($pushall) {
             Master::Summon(array('Notifier', 'refresh_all', $channel['channel_id']));
         }
         return;
     }
     // otherwise send the changes upstream
     $directory = find_upstream_directory($dirmode);
     $url = $directory['url'] . '/post';
     // ensure the upstream directory is updated
     $packet = zot_build_packet($channel, $force ? 'force_refresh' : 'refresh');
     $z = zot_zot($url, $packet);
     // re-queue if unsuccessful
     if (!$z['success']) {
         /** @FIXME we aren't updating channel_dirdate if we have to queue
          * the directory packet. That means we'll try again on the next poll run.
          */
         $hash = random_string();
         queue_insert(array('hash' => $hash, 'account_id' => $channel['channel_account_id'], 'channel_id' => $channel['channel_id'], 'posturl' => $url, 'notify' => $packet));
     } else {
         q("update channel set channel_dirdate = '%s' where channel_id = %d", dbesc(datetime_convert()), intval($channel['channel_id']));
     }
     // Now update all the connections
     if ($pushall) {
         Master::Summon(array('Notifier', 'refresh_all', $channel['channel_id']));
     }
 }
Esempio n. 27
0
function tasks_post(&$a)
{
    //	logger('post: ' . print_r($_POST,true));
    if (!local_channel()) {
        return;
    }
    $channel = App::get_channel();
    if (argc() > 2 && argv(1) === 'complete' && intval(argv(2))) {
        $ret = array('success' => false);
        $r = q("select * from event where `type` = 'task' and uid = %d and id = %d limit 1", intval(local_channel()), intval(argv(2)));
        if ($r) {
            $event = $r[0];
            if ($event['event_status'] === 'COMPLETED') {
                $event['event_status'] = 'IN-PROCESS';
                $event['event_status_date'] = NULL_DATE;
                $event['event_percent'] = 0;
                $event['event_sequence'] = $event['event_sequence'] + 1;
                $event['edited'] = datetime_convert();
            } else {
                $event['event_status'] = 'COMPLETED';
                $event['event_status_date'] = datetime_convert();
                $event['event_percent'] = 100;
                $event['event_sequence'] = $event['event_sequence'] + 1;
                $event['edited'] = datetime_convert();
            }
            $x = event_store_event($event);
            if ($x) {
                $ret['success'] = true;
            }
        }
        json_return_and_die($ret);
    }
    if (argc() == 2 && argv(1) === 'new') {
        $text = escape_tags(trim($_REQUEST['summary']));
        if (!$text) {
            return array('success' => false);
        }
        $event = array();
        $event['account'] = $channel['channel_account_id'];
        $event['uid'] = $channel['channel_id'];
        $event['event_xchan'] = $channel['channel_hash'];
        $event['type'] = 'task';
        $event['nofinish'] = true;
        $event['created'] = $event['edited'] = $event['start'] = datetime_convert();
        $event['adjust'] = 1;
        $event['allow_cid'] = '<' . $channel['channel_hash'] . '>';
        $event['summary'] = escape_tags($_REQUEST['summary']);
        $x = event_store_event($event);
        if ($x) {
            $x['success'] = true;
        } else {
            $x = array('success' => false);
        }
        json_return_and_die($x);
    }
}
Esempio n. 28
0
 public static function run($argc, $argv)
 {
     logger('cron_daily: start');
     /**
      * Cron Daily
      *
      */
     require_once 'include/dir_fns.php';
     check_upstream_directory();
     // Fire off the Cron_weekly process if it's the correct day.
     $d3 = intval(datetime_convert('UTC', 'UTC', 'now', 'N'));
     if ($d3 == 7) {
         Master::Summon(array('Cron_weekly'));
     }
     // once daily run birthday_updates and then expire in background
     // FIXME: add birthday updates, both locally and for xprof for use
     // by directory servers
     update_birthdays();
     // expire any read notifications over a month old
     q("delete from notify where seen = 1 and created < %s - INTERVAL %s", db_utcnow(), db_quoteinterval('30 DAY'));
     //update statistics in config
     require_once 'include/statistics_fns.php';
     update_channels_total_stat();
     update_channels_active_halfyear_stat();
     update_channels_active_monthly_stat();
     update_local_posts_stat();
     // expire old delivery reports
     $keep_reports = intval(get_config('system', 'expire_delivery_reports'));
     if ($keep_reports === 0) {
         $keep_reports = 10;
     }
     q("delete from dreport where dreport_time < %s - INTERVAL %s", db_utcnow(), db_quoteinterval($keep_reports . ' DAY'));
     // expire any expired accounts
     downgrade_accounts();
     // If this is a directory server, request a sync with an upstream
     // directory at least once a day, up to once every poll interval.
     // Pull remote changes and push local changes.
     // potential issue: how do we keep from creating an endless update loop?
     $dirmode = get_config('system', 'directory_mode');
     if ($dirmode == DIRECTORY_MODE_SECONDARY || $dirmode == DIRECTORY_MODE_PRIMARY) {
         require_once 'include/dir_fns.php';
         sync_directories($dirmode);
     }
     Master::Summon(array('Expire'));
     Master::Summon(array('Cli_suggest'));
     require_once 'include/hubloc.php';
     remove_obsolete_hublocs();
     call_hooks('cron_daily', datetime_convert());
     set_config('system', 'last_expire_day', $d2);
     /**
      * End Cron Daily
      */
 }
Esempio n. 29
0
 function mark_for_death($contact)
 {
     if ($contact['term-date'] == '0000-00-00 00:00:00') {
         q("UPDATE `contact` SET `term-date` = '%s' WHERE `id` = %d LIMIT 1", dbesc(datetime_convert()), intval($contact['id']));
     } else {
         $expiry = $contact['term-date'] . ' + 32 days ';
         if (datetime_convert() > datetime_convert('UTC', 'UTC', $expiry)) {
             // relationship is really truly dead.
             contact_remove($contact['id']);
         }
     }
 }
Esempio n. 30
0
 function q($sql)
 {
     if (!$this->db || !$this->connected) {
         return false;
     }
     if (!strpos($sql, ';')) {
         $sql .= ';';
     }
     if (strpos($sql, '`')) {
         // this is a hack. quoted identifiers should be replaced everywhere in the code with dbesc_identifier(), remove this once it is
         $sql = str_replace('`', '"', $sql);
     }
     $this->error = '';
     $result = @pg_query($this->db, $sql);
     if (file_exists('db-allqueries.out')) {
         $bt = debug_backtrace();
         $trace = array();
         foreach ($bt as $frame) {
             if (!empty($frame['file']) && @strstr($frame['file'], $_SERVER['DOCUMENT_ROOT'])) {
                 $frame['file'] = substr($frame['file'], strlen($_SERVER['DOCUMENT_ROOT']) + 1);
             }
             $trace[] = $frame['file'] . ':' . $frame['function'] . '():' . $frame['line'];
         }
         $compact = join(', ', $trace);
         file_put_contents('db-allqueries.out', datetime_convert() . ": " . $sql . ' is_resource: ' . var_export(is_resource($result), true) . ', backtrace: ' . $compact . "\n\n", FILE_APPEND);
     }
     if ($result === false) {
         $this->error = pg_last_error($this->db);
     }
     if ($result === false || $this->error) {
         //logger('dba_postgres: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
         if (file_exists('dbfail.out')) {
             file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
         }
     }
     if ($result === true || $result === false) {
         return $result;
     }
     if (pg_result_status($result) == PGSQL_COMMAND_OK) {
         return true;
     }
     $r = array();
     if (pg_num_rows($result)) {
         while ($x = pg_fetch_array($result, null, PGSQL_ASSOC)) {
             $r[] = $x;
         }
         pg_free_result($result);
         if ($this->debug) {
             logger('dba_postgres: ' . printable(print_r($r, true)));
         }
     }
     return $r;
 }