function update_rss_feed($feed, $ignore_daemon = false, $no_cache = false) { $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']; _debug("start", $debug_enabled); $result = db_query("SELECT id,update_interval,auth_login,\n\t\t\tfeed_url,auth_pass,cache_images,last_updated,\n\t\t\tmark_unread_on_update, owner_uid,\n\t\t\tpubsub_state, auth_pass_encrypted,\n\t\t\t(SELECT max(date_entered) FROM\n\t\t\t\tttrss_entries, ttrss_user_entries where ref_id = id AND feed_id = '{$feed}') AS last_article_timestamp\n\t\t\tFROM ttrss_feeds WHERE id = '{$feed}'"); if (db_num_rows($result) == 0) { _debug("feed {$feed} NOT FOUND/SKIPPED", $debug_enabled); return false; } $last_updated = db_fetch_result($result, 0, "last_updated"); $last_article_timestamp = @strtotime(db_fetch_result($result, 0, "last_article_timestamp")); if (defined('_DISABLE_HTTP_304')) { $last_article_timestamp = 0; } $owner_uid = db_fetch_result($result, 0, "owner_uid"); $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result, 0, "mark_unread_on_update")); $pubsub_state = db_fetch_result($result, 0, "pubsub_state"); $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result, 0, "auth_pass_encrypted")); db_query("UPDATE ttrss_feeds SET last_update_started = NOW()\n\t\t\tWHERE id = '{$feed}'"); $auth_login = db_fetch_result($result, 0, "auth_login"); $auth_pass = db_fetch_result($result, 0, "auth_pass"); if ($auth_pass_encrypted) { require_once "crypt.php"; $auth_pass = decrypt_string($auth_pass); } $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images")); $fetch_url = db_fetch_result($result, 0, "feed_url"); $feed = db_escape_string($feed); $date_feed_processed = date('Y-m-d H:i'); $cache_filename = CACHE_DIR . "/simplepie/" . sha1($fetch_url) . ".xml"; $pluginhost = new PluginHost(); $pluginhost->set_debug($debug_enabled); $user_plugins = get_pref("_ENABLED_PLUGINS", $owner_uid); $pluginhost->load(PLUGINS, PluginHost::KIND_ALL); $pluginhost->load($user_plugins, PluginHost::KIND_USER, $owner_uid); $pluginhost->load_data(); $rss = false; $rss_hash = false; $force_refetch = isset($_REQUEST["force_refetch"]); if (file_exists($cache_filename) && is_readable($cache_filename) && !$auth_login && !$auth_pass && filemtime($cache_filename) > time() - 30) { _debug("using local cache.", $debug_enabled); @($feed_data = file_get_contents($cache_filename)); if ($feed_data) { $rss_hash = sha1($feed_data); } } else { _debug("local cache will not be used for this feed", $debug_enabled); } if (!$rss) { foreach ($pluginhost->get_hooks(PluginHost::HOOK_FETCH_FEED) as $plugin) { $feed_data = $plugin->hook_fetch_feed($feed_data, $fetch_url, $owner_uid, $feed); } if (!$feed_data) { _debug("fetching [{$fetch_url}]...", $debug_enabled); _debug("If-Modified-Since: " . gmdate('D, d M Y H:i:s \\G\\M\\T', $last_article_timestamp), $debug_enabled); $feed_data = fetch_file_contents($fetch_url, false, $auth_login, $auth_pass, false, $no_cache ? FEED_FETCH_NO_CACHE_TIMEOUT : FEED_FETCH_TIMEOUT, $force_refetch ? 0 : $last_article_timestamp); global $fetch_curl_used; if (!$fetch_curl_used) { $tmp = @gzdecode($feed_data); if ($tmp) { $feed_data = $tmp; } } $feed_data = trim($feed_data); _debug("fetch done.", $debug_enabled); /* if ($feed_data) { $error = verify_feed_xml($feed_data); if ($error) { _debug("error verifying XML, code: " . $error->code, $debug_enabled); if ($error->code == 26) { _debug("got error 26, trying to decode entities...", $debug_enabled); $feed_data = html_entity_decode($feed_data, ENT_COMPAT, 'UTF-8'); $error = verify_feed_xml($feed_data); if ($error) $feed_data = ''; } } } */ } if (!$feed_data) { global $fetch_last_error; global $fetch_last_error_code; _debug("unable to fetch: {$fetch_last_error} [{$fetch_last_error_code}]", $debug_enabled); $error_escaped = ''; // If-Modified-Since if ($fetch_last_error_code != 304) { $error_escaped = db_escape_string($fetch_last_error); } else { _debug("source claims data not modified, nothing to do.", $debug_enabled); } db_query("UPDATE ttrss_feeds SET last_error = '{$error_escaped}',\n\t\t\t\t\t\tlast_updated = NOW() WHERE id = '{$feed}'"); return; } } foreach ($pluginhost->get_hooks(PluginHost::HOOK_FEED_FETCHED) as $plugin) { $feed_data = $plugin->hook_feed_fetched($feed_data, $fetch_url, $owner_uid, $feed); } // set last update to now so if anything *simplepie* crashes later we won't be // continuously failing on the same feed //db_query("UPDATE ttrss_feeds SET last_updated = NOW() WHERE id = '$feed'"); if (!$rss) { $rss = new FeedParser($feed_data); $rss->init(); } // print_r($rss); $feed = db_escape_string($feed); if (!$rss->error()) { // cache data for later if (!$auth_pass && !$auth_login && is_writable(CACHE_DIR . "/simplepie")) { $new_rss_hash = sha1($rss_data); if ($new_rss_hash != $rss_hash && count($rss->get_items()) > 0) { _debug("saving {$cache_filename}", $debug_enabled); @file_put_contents($cache_filename, $feed_data); } } // We use local pluginhost here because we need to load different per-user feed plugins $pluginhost->run_hooks(PluginHost::HOOK_FEED_PARSED, "hook_feed_parsed", $rss); _debug("processing feed data...", $debug_enabled); // db_query("BEGIN"); if (DB_TYPE == "pgsql") { $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'"; } else { $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)"; } $result = db_query("SELECT title,site_url,owner_uid,favicon_avg_color,\n\t\t\t\t(favicon_last_checked IS NULL OR {$favicon_interval_qpart}) AS\n\t\t\t\t\t\tfavicon_needs_check\n\t\t\t\tFROM ttrss_feeds WHERE id = '{$feed}'"); $registered_title = db_fetch_result($result, 0, "title"); $orig_site_url = db_fetch_result($result, 0, "site_url"); $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0, "favicon_needs_check")); $favicon_avg_color = db_fetch_result($result, 0, "favicon_avg_color"); $owner_uid = db_fetch_result($result, 0, "owner_uid"); $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245)); _debug("site_url: {$site_url}", $debug_enabled); _debug("feed_title: " . $rss->get_title(), $debug_enabled); if ($favicon_needs_check || $force_refetch) { /* terrible hack: if we crash on floicon shit here, we won't check * the icon avgcolor again (unless the icon got updated) */ $favicon_file = ICONS_DIR . "/{$feed}.ico"; $favicon_modified = @filemtime($favicon_file); _debug("checking favicon...", $debug_enabled); check_feed_favicon($site_url, $feed); $favicon_modified_new = @filemtime($favicon_file); if ($favicon_modified_new > $favicon_modified) { $favicon_avg_color = ''; } if (file_exists($favicon_file) && function_exists("imagecreatefromstring") && $favicon_avg_color == '') { require_once "colors.php"; db_query("UPDATE ttrss_feeds SET favicon_avg_color = 'fail' WHERE\n\t\t\t\t\t\t\tid = '{$feed}'"); $favicon_color = db_escape_string(calculate_avg_color($favicon_file)); $favicon_colorstring = ",favicon_avg_color = '" . $favicon_color . "'"; } else { if ($favicon_avg_color == 'fail') { _debug("floicon failed on this file, not trying to recalculate avg color", $debug_enabled); } } db_query("UPDATE ttrss_feeds SET favicon_last_checked = NOW()\n\t\t\t\t\t{$favicon_colorstring}\n\t\t\t\t\tWHERE id = '{$feed}'"); } if (!$registered_title || $registered_title == "[Unknown]") { $feed_title = db_escape_string($rss->get_title()); if ($feed_title) { _debug("registering title: {$feed_title}", $debug_enabled); db_query("UPDATE ttrss_feeds SET\n\t\t\t\t\t\ttitle = '{$feed_title}' WHERE id = '{$feed}'"); } } if ($site_url && $orig_site_url != $site_url) { db_query("UPDATE ttrss_feeds SET\n\t\t\t\t\tsite_url = '{$site_url}' WHERE id = '{$feed}'"); } _debug("loading filters & labels...", $debug_enabled); $filters = load_filters($feed, $owner_uid); $labels = get_all_labels($owner_uid); _debug("" . count($filters) . " filters loaded.", $debug_enabled); $items = $rss->get_items(); if (!is_array($items)) { _debug("no articles found.", $debug_enabled); db_query("UPDATE ttrss_feeds\n\t\t\t\t\tSET last_updated = NOW(), last_error = '' WHERE id = '{$feed}'"); return; // no articles } if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) { _debug("checking for PUSH hub...", $debug_enabled); $feed_hub_url = false; $links = $rss->get_links('hub'); if ($links && is_array($links)) { foreach ($links as $l) { $feed_hub_url = $l; break; } } _debug("feed hub url: {$feed_hub_url}", $debug_enabled); if ($feed_hub_url && function_exists('curl_init') && !ini_get("open_basedir")) { require_once 'lib/pubsubhubbub/subscriber.php'; $callback_url = get_self_url_prefix() . "/public.php?op=pubsub&id={$feed}"; $s = new Subscriber($feed_hub_url, $callback_url); $rc = $s->subscribe($fetch_url); _debug("feed hub url found, subscribe request sent.", $debug_enabled); db_query("UPDATE ttrss_feeds SET pubsub_state = 1\n\t\t\t\t\t\tWHERE id = '{$feed}'"); } } _debug("processing articles...", $debug_enabled); foreach ($items as $item) { if ($_REQUEST['xdebug'] == 3) { print_r($item); } $entry_guid = $item->get_id(); if (!$entry_guid) { $entry_guid = $item->get_link(); } if (!$entry_guid) { $entry_guid = make_guid_from_title($item->get_title()); } _debug("f_guid {$entry_guid}", $debug_enabled); if (!$entry_guid) { continue; } $entry_guid = "{$owner_uid},{$entry_guid}"; $entry_guid_hashed = db_escape_string('SHA1:' . sha1($entry_guid)); _debug("guid {$entry_guid} / {$entry_guid_hashed}", $debug_enabled); $entry_timestamp = ""; $entry_timestamp = $item->get_date(); _debug("orig date: " . $item->get_date(), $debug_enabled); if ($entry_timestamp == -1 || !$entry_timestamp || $entry_timestamp > time()) { $entry_timestamp = time(); $no_orig_date = 'true'; } else { $no_orig_date = 'false'; } $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp); _debug("date {$entry_timestamp} [{$entry_timestamp_fmt}]", $debug_enabled); // $entry_title = html_entity_decode($item->get_title(), ENT_COMPAT, 'UTF-8'); // $entry_title = decode_numeric_entities($entry_title); $entry_title = $item->get_title(); $entry_link = rewrite_relative_url($site_url, $item->get_link()); _debug("title {$entry_title}", $debug_enabled); _debug("link {$entry_link}", $debug_enabled); if (!$entry_title) { $entry_title = date("Y-m-d H:i:s", $entry_timestamp); } $entry_content = $item->get_content(); if (!$entry_content) { $entry_content = $item->get_description(); } if ($_REQUEST["xdebug"] == 2) { print "content: "; print $entry_content; print "\n"; } $entry_comments = $item->get_comments_url(); $entry_author = $item->get_author(); $entry_guid = db_escape_string(mb_substr($entry_guid, 0, 245)); $entry_comments = db_escape_string(mb_substr(trim($entry_comments), 0, 245)); $entry_author = db_escape_string(mb_substr(trim($entry_author), 0, 245)); $num_comments = (int) $item->get_comments_count(); _debug("author {$entry_author}", $debug_enabled); _debug("num_comments: {$num_comments}", $debug_enabled); _debug("looking for tags...", $debug_enabled); // parse <category> entries into tags $additional_tags = array(); $additional_tags_src = $item->get_categories(); if (is_array($additional_tags_src)) { foreach ($additional_tags_src as $tobj) { array_push($additional_tags, $tobj); } } $entry_tags = array_unique($additional_tags); for ($i = 0; $i < count($entry_tags); $i++) { $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8'); } _debug("tags found: " . join(",", $entry_tags), $debug_enabled); _debug("done collecting data.", $debug_enabled); // TODO: less memory-hungry implementation _debug("applying plugin filters..", $debug_enabled); // FIXME not sure if owner_uid is a good idea here, we may have a base entry without user entry (?) $result = db_query("SELECT plugin_data,title,content,link,tag_cache,author FROM ttrss_entries, ttrss_user_entries\n\t\t\t\t\tWHERE ref_id = id AND (guid = '" . db_escape_string($entry_guid) . "' OR guid = '{$entry_guid_hashed}') AND owner_uid = {$owner_uid}"); if (db_num_rows($result) != 0) { $entry_plugin_data = db_fetch_result($result, 0, "plugin_data"); $stored_article = array("title" => db_fetch_result($result, 0, "title"), "content" => db_fetch_result($result, 0, "content"), "link" => db_fetch_result($result, 0, "link"), "tags" => explode(",", db_fetch_result($result, 0, "tag_cache")), "author" => db_fetch_result($result, 0, "author")); } else { $entry_plugin_data = ""; $stored_article = array(); } $article = array("owner_uid" => $owner_uid, "guid" => $entry_guid, "title" => $entry_title, "content" => $entry_content, "link" => $entry_link, "tags" => $entry_tags, "plugin_data" => $entry_plugin_data, "author" => $entry_author, "stored" => $stored_article); foreach ($pluginhost->get_hooks(PluginHost::HOOK_ARTICLE_FILTER) as $plugin) { $article = $plugin->hook_article_filter($article); } $entry_tags = $article["tags"]; $entry_guid = db_escape_string($entry_guid); $entry_title = db_escape_string($article["title"]); $entry_author = db_escape_string($article["author"]); $entry_link = db_escape_string($article["link"]); $entry_plugin_data = db_escape_string($article["plugin_data"]); $entry_content = $article["content"]; // escaped below _debug("plugin data: {$entry_plugin_data}", $debug_enabled); if ($cache_images && is_writable(CACHE_DIR . '/images')) { cache_images($entry_content, $site_url, $debug_enabled); } $entry_content = db_escape_string($entry_content, false); $content_hash = "SHA1:" . sha1($entry_content); db_query("BEGIN"); $result = db_query("SELECT id FROM\tttrss_entries\n\t\t\t\t\tWHERE (guid = '{$entry_guid}' OR guid = '{$entry_guid_hashed}')"); if (db_num_rows($result) == 0) { _debug("base guid [{$entry_guid}] not found", $debug_enabled); // base post entry does not exist, create it $result = db_query("INSERT INTO ttrss_entries\n\t\t\t\t\t\t\t(title,\n\t\t\t\t\t\t\tguid,\n\t\t\t\t\t\t\tlink,\n\t\t\t\t\t\t\tupdated,\n\t\t\t\t\t\t\tcontent,\n\t\t\t\t\t\t\tcontent_hash,\n\t\t\t\t\t\t\tno_orig_date,\n\t\t\t\t\t\t\tdate_updated,\n\t\t\t\t\t\t\tdate_entered,\n\t\t\t\t\t\t\tcomments,\n\t\t\t\t\t\t\tnum_comments,\n\t\t\t\t\t\t\tplugin_data,\n\t\t\t\t\t\t\tauthor)\n\t\t\t\t\t\tVALUES\n\t\t\t\t\t\t\t('{$entry_title}',\n\t\t\t\t\t\t\t'{$entry_guid_hashed}',\n\t\t\t\t\t\t\t'{$entry_link}',\n\t\t\t\t\t\t\t'{$entry_timestamp_fmt}',\n\t\t\t\t\t\t\t'{$entry_content}',\n\t\t\t\t\t\t\t'{$content_hash}',\n\t\t\t\t\t\t\t{$no_orig_date},\n\t\t\t\t\t\t\tNOW(),\n\t\t\t\t\t\t\t'{$date_feed_processed}',\n\t\t\t\t\t\t\t'{$entry_comments}',\n\t\t\t\t\t\t\t'{$num_comments}',\n\t\t\t\t\t\t\t'{$entry_plugin_data}',\n\t\t\t\t\t\t\t'{$entry_author}')"); $article_labels = array(); } else { // we keep encountering the entry in feeds, so we need to // update date_updated column so that we don't get horrible // dupes when the entry gets purged and reinserted again e.g. // in the case of SLOW SLOW OMG SLOW updating feeds $base_entry_id = db_fetch_result($result, 0, "id"); db_query("UPDATE ttrss_entries SET date_updated = NOW()\n\t\t\t\t\t\tWHERE id = '{$base_entry_id}'"); $article_labels = get_article_labels($base_entry_id, $owner_uid); } // now it should exist, if not - bad luck then $result = db_query("SELECT\n\t\t\t\t\t\tid,content_hash,no_orig_date,title,plugin_data,guid,\n\t\t\t\t\t\t" . SUBSTRING_FOR_DATE . "(date_updated,1,19) as date_updated,\n\t\t\t\t\t\t" . SUBSTRING_FOR_DATE . "(updated,1,19) as updated,\n\t\t\t\t\t\tnum_comments\n\t\t\t\t\tFROM\n\t\t\t\t\t\tttrss_entries\n\t\t\t\t\tWHERE guid = '{$entry_guid}' OR guid = '{$entry_guid_hashed}'"); $entry_ref_id = 0; $entry_int_id = 0; if (db_num_rows($result) == 1) { _debug("base guid found, checking for user record", $debug_enabled); // this will be used below in update handler $orig_content_hash = db_fetch_result($result, 0, "content_hash"); $orig_title = db_fetch_result($result, 0, "title"); $orig_num_comments = db_fetch_result($result, 0, "num_comments"); $orig_date_updated = strtotime(db_fetch_result($result, 0, "date_updated")); $orig_plugin_data = db_fetch_result($result, 0, "plugin_data"); $ref_id = db_fetch_result($result, 0, "id"); $entry_ref_id = $ref_id; /* $stored_guid = db_fetch_result($result, 0, "guid"); if ($stored_guid != $entry_guid_hashed) { if ($debug_enabled) _debug("upgrading compat guid to hashed one", $debug_enabled); db_query("UPDATE ttrss_entries SET guid = '$entry_guid_hashed' WHERE id = '$ref_id'"); } */ // check for user post link to main table // do we allow duplicate posts with same GUID in different feeds? if (get_pref("ALLOW_DUPLICATE_POSTS", $owner_uid, false)) { $dupcheck_qpart = "AND (feed_id = '{$feed}' OR feed_id IS NULL)"; } else { $dupcheck_qpart = ""; } /* Collect article tags here so we could filter by them: */ $article_filters = get_article_filters($filters, $entry_title, $entry_content, $entry_link, $entry_timestamp, $entry_author, $entry_tags); if ($debug_enabled) { _debug("article filters: ", $debug_enabled); if (count($article_filters) != 0) { print_r($article_filters); } } if (find_article_filter($article_filters, "filter")) { db_query("COMMIT"); // close transaction in progress continue; } $score = calculate_article_score($article_filters); _debug("initial score: {$score}", $debug_enabled); $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE\n\t\t\t\t\t\t\tref_id = '{$ref_id}' AND owner_uid = '{$owner_uid}'\n\t\t\t\t\t\t\t{$dupcheck_qpart}"; // if ($_REQUEST["xdebug"]) print "$query\n"; $result = db_query($query); // okay it doesn't exist - create user entry if (db_num_rows($result) == 0) { _debug("user record not found, creating...", $debug_enabled); if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) { $unread = 'true'; $last_read_qpart = 'NULL'; } else { $unread = 'false'; $last_read_qpart = 'NOW()'; } if (find_article_filter($article_filters, 'mark') || $score > 1000) { $marked = 'true'; } else { $marked = 'false'; } if (find_article_filter($article_filters, 'publish')) { $published = 'true'; } else { $published = 'false'; } // N-grams if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) { $result = db_query("SELECT COUNT(*) AS similar FROM\n\t\t\t\t\t\t\t\t\tttrss_entries,ttrss_user_entries\n\t\t\t\t\t\t\t\tWHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'\n\t\t\t\t\t\t\t\t\tAND similarity(title, '{$entry_title}') >= " . _NGRAM_TITLE_DUPLICATE_THRESHOLD . "\n\t\t\t\t\t\t\t\t\tAND owner_uid = {$owner_uid}"); $ngram_similar = db_fetch_result($result, 0, "similar"); _debug("N-gram similar results: {$ngram_similar}", $debug_enabled); if ($ngram_similar > 0) { $unread = 'false'; } } $last_marked = $marked == 'true' ? 'NOW()' : 'NULL'; $last_published = $published == 'true' ? 'NOW()' : 'NULL'; $result = db_query("INSERT INTO ttrss_user_entries\n\t\t\t\t\t\t\t\t(ref_id, owner_uid, feed_id, unread, last_read, marked,\n\t\t\t\t\t\t\t\tpublished, score, tag_cache, label_cache, uuid,\n\t\t\t\t\t\t\t\tlast_marked, last_published)\n\t\t\t\t\t\t\tVALUES ('{$ref_id}', '{$owner_uid}', '{$feed}', {$unread},\n\t\t\t\t\t\t\t\t{$last_read_qpart}, {$marked}, {$published}, '{$score}', '', '',\n\t\t\t\t\t\t\t\t'', {$last_marked}, {$last_published})"); if (PUBSUBHUBBUB_HUB && $published == 'true') { $rss_link = get_self_url_prefix() . "/public.php?op=rss&id=-2&key=" . get_feed_access_key(-2, false, $owner_uid); $p = new Publisher(PUBSUBHUBBUB_HUB); $pubsub_result = $p->publish_update($rss_link); } $result = db_query("SELECT int_id FROM ttrss_user_entries WHERE\n\t\t\t\t\t\t\t\tref_id = '{$ref_id}' AND owner_uid = '{$owner_uid}' AND\n\t\t\t\t\t\t\t\tfeed_id = '{$feed}' LIMIT 1"); if (db_num_rows($result) == 1) { $entry_int_id = db_fetch_result($result, 0, "int_id"); } } else { _debug("user record FOUND", $debug_enabled); $entry_ref_id = db_fetch_result($result, 0, "ref_id"); $entry_int_id = db_fetch_result($result, 0, "int_id"); } _debug("RID: {$entry_ref_id}, IID: {$entry_int_id}", $debug_enabled); $post_needs_update = false; $update_insignificant = false; if ($orig_num_comments != $num_comments) { $post_needs_update = true; $update_insignificant = true; } if ($entry_plugin_data != $orig_plugin_data) { $post_needs_update = true; $update_insignificant = true; } if ($content_hash != $orig_content_hash) { $post_needs_update = true; $update_insignificant = false; } if (db_escape_string($orig_title) != $entry_title) { $post_needs_update = true; $update_insignificant = false; } // if post needs update, update it and mark all user entries // linking to this post as updated if ($post_needs_update) { if (defined('DAEMON_EXTENDED_DEBUG')) { _debug("post {$entry_guid_hashed} needs update...", $debug_enabled); } // print "<!-- post $orig_title needs update : $post_needs_update -->"; db_query("UPDATE ttrss_entries\n\t\t\t\t\t\t\tSET title = '{$entry_title}', content = '{$entry_content}',\n\t\t\t\t\t\t\t\tcontent_hash = '{$content_hash}',\n\t\t\t\t\t\t\t\tupdated = '{$entry_timestamp_fmt}',\n\t\t\t\t\t\t\t\tnum_comments = '{$num_comments}',\n\t\t\t\t\t\t\t\tplugin_data = '{$entry_plugin_data}'\n\t\t\t\t\t\t\tWHERE id = '{$ref_id}'"); if (!$update_insignificant) { if ($mark_unread_on_update) { db_query("UPDATE ttrss_user_entries\n\t\t\t\t\t\t\t\t\tSET last_read = null, unread = true WHERE ref_id = '{$ref_id}'"); } } } } db_query("COMMIT"); _debug("assigning labels...", $debug_enabled); assign_article_to_label_filters($entry_ref_id, $article_filters, $owner_uid, $article_labels); _debug("looking for enclosures...", $debug_enabled); // enclosures $enclosures = array(); $encs = $item->get_enclosures(); if (is_array($encs)) { foreach ($encs as $e) { $e_item = array($e->link, $e->type, $e->length); array_push($enclosures, $e_item); } } if ($debug_enabled) { _debug("article enclosures:", $debug_enabled); print_r($enclosures); } db_query("BEGIN"); foreach ($enclosures as $enc) { $enc_url = db_escape_string($enc[0]); $enc_type = db_escape_string($enc[1]); $enc_dur = db_escape_string($enc[2]); $result = db_query("SELECT id FROM ttrss_enclosures\n\t\t\t\t\t\tWHERE content_url = '{$enc_url}' AND post_id = '{$entry_ref_id}'"); if (db_num_rows($result) == 0) { db_query("INSERT INTO ttrss_enclosures\n\t\t\t\t\t\t\t(content_url, content_type, title, duration, post_id) VALUES\n\t\t\t\t\t\t\t('{$enc_url}', '{$enc_type}', '', '{$enc_dur}', '{$entry_ref_id}')"); } } db_query("COMMIT"); // check for manual tags (we have to do it here since they're loaded from filters) foreach ($article_filters as $f) { if ($f["type"] == "tag") { $manual_tags = trim_array(explode(",", $f["param"])); foreach ($manual_tags as $tag) { if (tag_is_valid($tag)) { array_push($entry_tags, $tag); } } } } // Skip boring tags $boring_tags = trim_array(explode(",", mb_strtolower(get_pref('BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8'))); $filtered_tags = array(); $tags_to_cache = array(); if ($entry_tags && is_array($entry_tags)) { foreach ($entry_tags as $tag) { if (array_search($tag, $boring_tags) === false) { array_push($filtered_tags, $tag); } } } $filtered_tags = array_unique($filtered_tags); if ($debug_enabled) { _debug("filtered article tags:", $debug_enabled); print_r($filtered_tags); } // Save article tags in the database if (count($filtered_tags) > 0) { db_query("BEGIN"); foreach ($filtered_tags as $tag) { $tag = sanitize_tag($tag); $tag = db_escape_string($tag); if (!tag_is_valid($tag)) { continue; } $result = db_query("SELECT id FROM ttrss_tags\n\t\t\t\t\t\t\tWHERE tag_name = '{$tag}' AND post_int_id = '{$entry_int_id}' AND\n\t\t\t\t\t\t\towner_uid = '{$owner_uid}' LIMIT 1"); if ($result && db_num_rows($result) == 0) { db_query("INSERT INTO ttrss_tags\n\t\t\t\t\t\t\t\t\t(owner_uid,tag_name,post_int_id)\n\t\t\t\t\t\t\t\t\tVALUES ('{$owner_uid}','{$tag}', '{$entry_int_id}')"); } array_push($tags_to_cache, $tag); } /* update the cache */ $tags_to_cache = array_unique($tags_to_cache); $tags_str = db_escape_string(join(",", $tags_to_cache)); db_query("UPDATE ttrss_user_entries\n\t\t\t\t\t\tSET tag_cache = '{$tags_str}' WHERE ref_id = '{$entry_ref_id}'\n\t\t\t\t\t\tAND owner_uid = {$owner_uid}"); db_query("COMMIT"); } if (get_pref("AUTO_ASSIGN_LABELS", $owner_uid, false)) { _debug("auto-assigning labels...", $debug_enabled); foreach ($labels as $label) { $caption = preg_quote($label["caption"]); if ($caption && preg_match("/\\b{$caption}\\b/i", "{$tags_str} " . strip_tags($entry_content) . " {$entry_title}")) { if (!labels_contains_caption($article_labels, $caption)) { label_add_article($entry_ref_id, $caption, $owner_uid); } } } } _debug("article processed", $debug_enabled); } _debug("purging feed...", $debug_enabled); purge_feed($feed, 0, $debug_enabled); db_query("UPDATE ttrss_feeds\n\t\t\t\tSET last_updated = NOW(), last_error = '' WHERE id = '{$feed}'"); // db_query("COMMIT"); } else { $error_msg = db_escape_string(mb_substr($rss->error(), 0, 245)); _debug("error fetching feed: {$error_msg}", $debug_enabled); db_query("UPDATE ttrss_feeds SET last_error = '{$error_msg}',\n\t\t\t\t\tlast_updated = NOW() WHERE id = '{$feed}'"); } unset($rss); _debug("done", $debug_enabled); }
function index() { global $access_level_names; $prefs_blacklist = array("STRIP_UNSAFE_TAGS", "REVERSE_HEADLINES", "SORT_HEADLINES_BY_FEED_DATE", "DEFAULT_ARTICLE_LIMIT", "FEEDS_SORT_BY_UNREAD"); /* "FEEDS_SORT_BY_UNREAD", "HIDE_READ_FEEDS", "REVERSE_HEADLINES" */ $profile_blacklist = array("ALLOW_DUPLICATE_POSTS", "PURGE_OLD_DAYS", "PURGE_UNREAD_ARTICLES", "DIGEST_ENABLE", "DIGEST_CATCHUP", "BLACKLISTED_TAGS", "ENABLE_API_ACCESS", "UPDATE_POST_ON_CHECKSUM_CHANGE", "DEFAULT_UPDATE_INTERVAL", "USER_TIMEZONE", "SORT_HEADLINES_BY_FEED_DATE", "SSL_CERT_SERIAL", "DIGEST_PREFERRED_TIME"); $_SESSION["prefs_op_result"] = ""; print "<div dojoType=\"dijit.layout.AccordionContainer\" region=\"center\">"; print "<div dojoType=\"dijit.layout.AccordionPane\" title=\"" . __('Personal data / Authentication') . "\">"; print "<form dojoType=\"dijit.form.Form\" id=\"changeUserdataForm\">"; print "<script type=\"dojo/method\" event=\"onSubmit\" args=\"evt\">\n\t\tevt.preventDefault();\n\t\tif (this.validate()) {\n\t\t\tnotify_progress('Saving data...', true);\n\n\t\t\tnew Ajax.Request('backend.php', {\n\t\t\t\tparameters: dojo.objectToQuery(this.getValues()),\n\t\t\t\tonComplete: function(transport) {\n\t\t\t\t\tnotify_callback2(transport);\n\t\t\t} });\n\n\t\t}\n\t\t</script>"; print "<table width=\"100%\" class=\"prefPrefsList\">"; print "<h2>" . __("Personal data") . "</h2>"; $result = $this->dbh->query("SELECT email,full_name,otp_enabled,\n\t\t\taccess_level FROM ttrss_users\n\t\t\tWHERE id = " . $_SESSION["uid"]); $email = htmlspecialchars($this->dbh->fetch_result($result, 0, "email")); $full_name = htmlspecialchars($this->dbh->fetch_result($result, 0, "full_name")); $otp_enabled = sql_bool_to_bool($this->dbh->fetch_result($result, 0, "otp_enabled")); print "<tr><td width=\"40%\">" . __('Full name') . "</td>"; print "<td class=\"prefValue\"><input dojoType=\"dijit.form.ValidationTextBox\" name=\"full_name\" required=\"1\"\n\t\t\tvalue=\"{$full_name}\"></td></tr>"; print "<tr><td width=\"40%\">" . __('E-mail') . "</td>"; print "<td class=\"prefValue\"><input dojoType=\"dijit.form.ValidationTextBox\" name=\"email\" required=\"1\" value=\"{$email}\"></td></tr>"; if (!SINGLE_USER_MODE && !$_SESSION["hide_hello"]) { $access_level = $this->dbh->fetch_result($result, 0, "access_level"); print "<tr><td width=\"40%\">" . __('Access level') . "</td>"; print "<td>" . $access_level_names[$access_level] . "</td></tr>"; } print "</table>"; print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"op\" value=\"pref-prefs\">"; print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"method\" value=\"changeemail\">"; print "<p><button dojoType=\"dijit.form.Button\" type=\"submit\">" . __("Save data") . "</button>"; print "</form>"; if ($_SESSION["auth_module"]) { $authenticator = PluginHost::getInstance()->get_plugin($_SESSION["auth_module"]); } else { $authenticator = false; } if ($authenticator && method_exists($authenticator, "change_password")) { print "<h2>" . __("Password") . "</h2>"; $result = $this->dbh->query("SELECT id FROM ttrss_users\n\t\t\t\tWHERE id = " . $_SESSION["uid"] . " AND pwd_hash\n\t\t\t\t= 'SHA1:5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8'"); if ($this->dbh->num_rows($result) != 0) { print format_warning(__("Your password is at default value, please change it."), "default_pass_warning"); } print "<form dojoType=\"dijit.form.Form\">"; print "<script type=\"dojo/method\" event=\"onSubmit\" args=\"evt\">\n\t\t\tevt.preventDefault();\n\t\t\tif (this.validate()) {\n\t\t\t\tnotify_progress('Changing password...', true);\n\n\t\t\t\tnew Ajax.Request('backend.php', {\n\t\t\t\t\tparameters: dojo.objectToQuery(this.getValues()),\n\t\t\t\t\tonComplete: function(transport) {\n\t\t\t\t\t\tnotify('');\n\t\t\t\t\t\tif (transport.responseText.indexOf('ERROR: ') == 0) {\n\t\t\t\t\t\t\tnotify_error(transport.responseText.replace('ERROR: ', ''));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tnotify_info(transport.responseText);\n\t\t\t\t\t\t\tvar warn = \$('default_pass_warning');\n\t\t\t\t\t\t\tif (warn) Element.hide(warn);\n\t\t\t\t\t\t}\n\t\t\t\t}});\n\t\t\t\tthis.reset();\n\t\t\t}\n\t\t\t</script>"; if ($otp_enabled) { print_notice(__("Changing your current password will disable OTP.")); } print "<table width=\"100%\" class=\"prefPrefsList\">"; print "<tr><td width=\"40%\">" . __("Old password") . "</td>"; print "<td class=\"prefValue\"><input dojoType=\"dijit.form.ValidationTextBox\" type=\"password\" required=\"1\" name=\"old_password\"></td></tr>"; print "<tr><td width=\"40%\">" . __("New password") . "</td>"; print "<td class=\"prefValue\"><input dojoType=\"dijit.form.ValidationTextBox\" type=\"password\" required=\"1\"\n\t\t\t\tname=\"new_password\"></td></tr>"; print "<tr><td width=\"40%\">" . __("Confirm password") . "</td>"; print "<td class=\"prefValue\"><input dojoType=\"dijit.form.ValidationTextBox\" type=\"password\" required=\"1\" name=\"confirm_password\"></td></tr>"; print "</table>"; print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"op\" value=\"pref-prefs\">"; print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"method\" value=\"changepassword\">"; print "<p><button dojoType=\"dijit.form.Button\" type=\"submit\">" . __("Change password") . "</button>"; print "</form>"; if ($_SESSION["auth_module"] == "auth_internal") { print "<h2>" . __("One time passwords / Authenticator") . "</h2>"; if ($otp_enabled) { print_notice(__("One time passwords are currently enabled. Enter your current password below to disable.")); print "<form dojoType=\"dijit.form.Form\">"; print "<script type=\"dojo/method\" event=\"onSubmit\" args=\"evt\">\n\t\t\t\tevt.preventDefault();\n\t\t\t\tif (this.validate()) {\n\t\t\t\t\tnotify_progress('Disabling OTP', true);\n\n\t\t\t\t\tnew Ajax.Request('backend.php', {\n\t\t\t\t\t\tparameters: dojo.objectToQuery(this.getValues()),\n\t\t\t\t\t\tonComplete: function(transport) {\n\t\t\t\t\t\t\tnotify('');\n\t\t\t\t\t\t\tif (transport.responseText.indexOf('ERROR: ') == 0) {\n\t\t\t\t\t\t\t\tnotify_error(transport.responseText.replace('ERROR: ', ''));\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\twindow.location.reload();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}});\n\t\t\t\t\tthis.reset();\n\t\t\t\t}\n\t\t\t\t</script>"; print "<table width=\"100%\" class=\"prefPrefsList\">"; print "<tr><td width=\"40%\">" . __("Enter your password") . "</td>"; print "<td class=\"prefValue\"><input dojoType=\"dijit.form.ValidationTextBox\" type=\"password\" required=\"1\"\n\t\t\t\t\tname=\"password\"></td></tr>"; print "</table>"; print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"op\" value=\"pref-prefs\">"; print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"method\" value=\"otpdisable\">"; print "<p><button dojoType=\"dijit.form.Button\" type=\"submit\">" . __("Disable OTP") . "</button>"; print "</form>"; } else { if (function_exists("imagecreatefromstring")) { print_warning(__("You will need a compatible Authenticator to use this. Changing your password would automatically disable OTP.")); print "<p>" . __("Scan the following code by the Authenticator application:") . "</p>"; $csrf_token = $_SESSION["csrf_token"]; print "<img src=\"backend.php?op=pref-prefs&method=otpqrcode&csrf_token={$csrf_token}\">"; print "<form dojoType=\"dijit.form.Form\" id=\"changeOtpForm\">"; print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"op\" value=\"pref-prefs\">"; print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"method\" value=\"otpenable\">"; print "<script type=\"dojo/method\" event=\"onSubmit\" args=\"evt\">\n\t\t\t\t\tevt.preventDefault();\n\t\t\t\t\tif (this.validate()) {\n\t\t\t\t\t\tnotify_progress('Saving data...', true);\n\n\t\t\t\t\t\tnew Ajax.Request('backend.php', {\n\t\t\t\t\t\t\tparameters: dojo.objectToQuery(this.getValues()),\n\t\t\t\t\t\t\tonComplete: function(transport) {\n\t\t\t\t\t\t\t\tnotify('');\n\t\t\t\t\t\t\t\tif (transport.responseText.indexOf('ERROR:') == 0) {\n\t\t\t\t\t\t\t\t\tnotify_error(transport.responseText.replace('ERROR:', ''));\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\twindow.location.reload();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} });\n\n\t\t\t\t\t}\n\t\t\t\t\t</script>"; print "<table width=\"100%\" class=\"prefPrefsList\">"; print "<tr><td width=\"40%\">" . __("Enter your password") . "</td>"; print "<td class=\"prefValue\"><input dojoType=\"dijit.form.ValidationTextBox\" type=\"password\" required=\"1\"\n\t\t\t\t\t\tname=\"password\"></td></tr>"; print "<tr><td width=\"40%\">" . __("Enter the generated one time password") . "</td>"; print "<td class=\"prefValue\"><input dojoType=\"dijit.form.ValidationTextBox\" autocomplete=\"off\"\n\t\t\t\t\t\trequired=\"1\"\n\t\t\t\t\t\tname=\"otp\"></td></tr>"; print "<tr><td colspan=\"2\">"; print "</td></tr><tr><td colspan=\"2\">"; print "</td></tr>"; print "</table>"; print "<p><button dojoType=\"dijit.form.Button\" type=\"submit\">" . __("Enable OTP") . "</button>"; print "</form>"; } else { print_notice(__("PHP GD functions are required for OTP support.")); } } } } PluginHost::getInstance()->run_hooks(PluginHost::HOOK_PREFS_TAB_SECTION, "hook_prefs_tab_section", "prefPrefsAuth"); print "</div>"; #pane print "<div dojoType=\"dijit.layout.AccordionPane\" selected=\"true\" title=\"" . __('Preferences') . "\">"; print "<form dojoType=\"dijit.form.Form\" id=\"changeSettingsForm\">"; print "<script type=\"dojo/method\" event=\"onSubmit\" args=\"evt, quit\">\n\t\tif (evt) evt.preventDefault();\n\t\tif (this.validate()) {\n\t\t\tconsole.log(dojo.objectToQuery(this.getValues()));\n\n\t\t\tnew Ajax.Request('backend.php', {\n\t\t\t\tparameters: dojo.objectToQuery(this.getValues()),\n\t\t\t\tonComplete: function(transport) {\n\t\t\t\t\tvar msg = transport.responseText;\n\t\t\t\t\tif (quit) {\n\t\t\t\t\t\tgotoMain();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (msg == 'PREFS_NEED_RELOAD') {\n\t\t\t\t\t\t\twindow.location.reload();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tnotify_info(msg);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t} });\n\t\t}\n\t\t</script>"; print '<div dojoType="dijit.layout.BorderContainer" gutters="false">'; print '<div dojoType="dijit.layout.ContentPane" region="center" style="overflow-y : auto">'; if ($_SESSION["profile"]) { print_notice(__("Some preferences are only available in default profile.")); } if ($_SESSION["profile"]) { initialize_user_prefs($_SESSION["uid"], $_SESSION["profile"]); $profile_qpart = "profile = '" . $_SESSION["profile"] . "'"; } else { initialize_user_prefs($_SESSION["uid"]); $profile_qpart = "profile IS NULL"; } /* if ($_SESSION["prefs_show_advanced"]) $access_query = "true"; else $access_query = "(access_level = 0 AND section_id != 3)"; */ $access_query = 'true'; $result = $this->dbh->query("SELECT DISTINCT\n\t\t\tttrss_user_prefs.pref_name,value,type_name,\n\t\t\tttrss_prefs_sections.order_id,\n\t\t\tdef_value,section_id\n\t\t\tFROM ttrss_prefs,ttrss_prefs_types,ttrss_prefs_sections,ttrss_user_prefs\n\t\t\tWHERE type_id = ttrss_prefs_types.id AND\n\t\t\t\t{$profile_qpart} AND\n\t\t\t\tsection_id = ttrss_prefs_sections.id AND\n\t\t\t\tttrss_user_prefs.pref_name = ttrss_prefs.pref_name AND\n\t\t\t\t{$access_query} AND\n\t\t\t\towner_uid = " . $_SESSION["uid"] . "\n\t\t\tORDER BY ttrss_prefs_sections.order_id,pref_name"); $lnum = 0; $active_section = ""; $listed_boolean_prefs = array(); while ($line = $this->dbh->fetch_assoc($result)) { if (in_array($line["pref_name"], $prefs_blacklist)) { continue; } $type_name = $line["type_name"]; $pref_name = $line["pref_name"]; $section_name = $this->getSectionName($line["section_id"]); $value = $line["value"]; $short_desc = $this->getShortDesc($pref_name); $help_text = $this->getHelpText($pref_name); if (!$short_desc) { continue; } if ($_SESSION["profile"] && in_array($line["pref_name"], $profile_blacklist)) { continue; } if ($active_section != $line["section_id"]) { if ($active_section != "") { print "</table>"; } print "<table width=\"100%\" class=\"prefPrefsList\">"; $active_section = $line["section_id"]; print "<tr><td colspan=\"3\"><h3>" . $section_name . "</h3></td></tr>"; $lnum = 0; } print "<tr>"; print "<td width=\"40%\" class=\"prefName\" id=\"{$pref_name}\">"; print "<label for='CB_{$pref_name}'>"; print $short_desc; print "</label>"; if ($help_text) { print "<div class=\"prefHelp\">" . __($help_text) . "</div>"; } print "</td>"; print "<td class=\"prefValue\">"; if ($pref_name == "USER_LANGUAGE") { print_select_hash($pref_name, $value, get_translations(), "style='width : 220px; margin : 0px' dojoType='dijit.form.Select'"); } else { if ($pref_name == "USER_TIMEZONE") { $timezones = explode("\n", file_get_contents("lib/timezones.txt")); print_select($pref_name, $value, $timezones, 'dojoType="dijit.form.FilteringSelect"'); } else { if ($pref_name == "USER_STYLESHEET") { print "<button dojoType=\"dijit.form.Button\"\n\t\t\t\t\tonclick=\"customizeCSS()\">" . __('Customize') . "</button>"; } else { if ($pref_name == "USER_CSS_THEME") { $themes = array_map("basename", glob("themes/*.css")); print_select($pref_name, $value, $themes, 'dojoType="dijit.form.Select"'); } else { if ($pref_name == "DEFAULT_UPDATE_INTERVAL") { global $update_intervals_nodefault; print_select_hash($pref_name, $value, $update_intervals_nodefault, 'dojoType="dijit.form.Select"'); } else { if ($type_name == "bool") { array_push($listed_boolean_prefs, $pref_name); $checked = $value == "true" ? "checked=\"checked\"" : ""; if ($pref_name == "PURGE_UNREAD_ARTICLES" && FORCE_ARTICLE_PURGE != 0) { $disabled = "disabled=\"1\""; $checked = "checked=\"checked\""; } else { $disabled = ""; } print "<input type='checkbox' name='{$pref_name}' {$checked} {$disabled}\n\t\t\t\t\tdojoType='dijit.form.CheckBox' id='CB_{$pref_name}' value='1'>"; } else { if (array_search($pref_name, array('FRESH_ARTICLE_MAX_AGE', 'PURGE_OLD_DAYS', 'LONG_DATE_FORMAT', 'SHORT_DATE_FORMAT')) !== false) { $regexp = $type_name == 'integer' ? 'regexp="^\\d*$"' : ''; if ($pref_name == "PURGE_OLD_DAYS" && FORCE_ARTICLE_PURGE != 0) { $disabled = "disabled=\"1\""; $value = FORCE_ARTICLE_PURGE; } else { $disabled = ""; } print "<input dojoType=\"dijit.form.ValidationTextBox\"\n\t\t\t\t\trequired=\"1\" {$regexp} {$disabled}\n\t\t\t\t\tname=\"{$pref_name}\" value=\"{$value}\">"; } else { if ($pref_name == "SSL_CERT_SERIAL") { print "<input dojoType=\"dijit.form.ValidationTextBox\"\n\t\t\t\t\tid=\"SSL_CERT_SERIAL\" readonly=\"1\"\n\t\t\t\t\tname=\"{$pref_name}\" value=\"{$value}\">"; $cert_serial = htmlspecialchars(get_ssl_certificate_id()); $has_serial = $cert_serial ? "false" : "true"; print " <button dojoType=\"dijit.form.Button\" disabled=\"{$has_serial}\"\n\t\t\t\t\tonclick=\"insertSSLserial('{$cert_serial}')\">" . __('Register') . "</button>"; print " <button dojoType=\"dijit.form.Button\"\n\t\t\t\t\tonclick=\"insertSSLserial('')\">" . __('Clear') . "</button>"; } else { if ($pref_name == 'DIGEST_PREFERRED_TIME') { print "<input dojoType=\"dijit.form.ValidationTextBox\"\n\t\t\t\t\tid=\"{$pref_name}\" regexp=\"[012]?\\d:\\d\\d\" placeHolder=\"12:00\"\n\t\t\t\t\tname=\"{$pref_name}\" value=\"{$value}\"><div class=\"insensitive\">" . T_sprintf("Current server time: %s (UTC)", date("H:i")) . "</div>"; } else { $regexp = $type_name == 'integer' ? 'regexp="^\\d*$"' : ''; print "<input dojoType=\"dijit.form.ValidationTextBox\"\n\t\t\t\t\t{$regexp}\n\t\t\t\t\tname=\"{$pref_name}\" value=\"{$value}\">"; } } } } } } } } } print "</td>"; print "</tr>"; $lnum++; } print "</table>"; $listed_boolean_prefs = htmlspecialchars(join(",", $listed_boolean_prefs)); print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"boolean_prefs\" value=\"{$listed_boolean_prefs}\">"; PluginHost::getInstance()->run_hooks(PluginHost::HOOK_PREFS_TAB_SECTION, "hook_prefs_tab_section", "prefPrefsPrefsInside"); print '</div>'; # inside pane print '<div dojoType="dijit.layout.ContentPane" region="bottom">'; print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"op\" value=\"pref-prefs\">"; print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"method\" value=\"saveconfig\">"; print "<div dojoType=\"dijit.form.ComboButton\" type=\"submit\">\n\t\t\t<span>" . __('Save configuration') . "</span>\n\t\t\t<div dojoType=\"dijit.DropDownMenu\">\n\t\t\t\t<div dojoType=\"dijit.MenuItem\"\n\t\t\t\t\tonclick=\"dijit.byId('changeSettingsForm').onSubmit(null, true)\">" . __("Save and exit preferences") . "</div>\n\t\t\t</div>\n\t\t\t</div>"; print "<button dojoType=\"dijit.form.Button\" onclick=\"return editProfiles()\">" . __('Manage profiles') . "</button> "; print "<button dojoType=\"dijit.form.Button\" onclick=\"return validatePrefsReset()\">" . __('Reset to defaults') . "</button>"; print " "; /* $checked = $_SESSION["prefs_show_advanced"] ? "checked='1'" : ""; print "<input onclick='toggleAdvancedPrefs()' id='prefs_show_advanced' dojoType=\"dijit.form.CheckBox\" $checked type=\"checkbox\"></input> <label for='prefs_show_advanced'>" . __("Show additional preferences") . "</label>"; */ PluginHost::getInstance()->run_hooks(PluginHost::HOOK_PREFS_TAB_SECTION, "hook_prefs_tab_section", "prefPrefsPrefsOutside"); print "</form>"; print '</div>'; # inner pane print '</div>'; # border container print "</div>"; #pane print "<div dojoType=\"dijit.layout.AccordionPane\" title=\"" . __('Plugins') . "\">"; print "<p>" . __("You will need to reload Tiny Tiny RSS for plugin changes to take effect.") . "</p>"; print_notice(__("Download more plugins at tt-rss.org <a class=\"visibleLink\" target=\"_blank\" href=\"http://tt-rss.org/forum/viewforum.php?f=22\">forums</a> or <a target=\"_blank\" class=\"visibleLink\" href=\"http://tt-rss.org/wiki/Plugins\">wiki</a>.")); print "<form dojoType=\"dijit.form.Form\" id=\"changePluginsForm\">"; print "<script type=\"dojo/method\" event=\"onSubmit\" args=\"evt\">\n\t\tevt.preventDefault();\n\t\tif (this.validate()) {\n\t\t\tnotify_progress('Saving data...', true);\n\n\t\t\tnew Ajax.Request('backend.php', {\n\t\t\t\tparameters: dojo.objectToQuery(this.getValues()),\n\t\t\t\tonComplete: function(transport) {\n\t\t\t\t\tnotify('');\n\t\t\t\t\tif (confirm(__('Selected plugins have been enabled. Reload?'))) {\n\t\t\t\t\t\twindow.location.reload();\n\t\t\t\t\t}\n\t\t\t} });\n\n\t\t}\n\t\t</script>"; print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"op\" value=\"pref-prefs\">"; print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"method\" value=\"setplugins\">"; print "<table width='100%' class='prefPluginsList'>"; print "<tr><td colspan='4'><h3>" . __("System plugins") . "</h3></td></tr>"; print "<tr class=\"title\">\n\t\t\t\t<td width=\"5%\"> </td>\n\t\t\t\t<td width='10%'>" . __('Plugin') . "</td>\n\t\t\t\t<td width=''>" . __('Description') . "</td>\n\t\t\t\t<td width='5%'>" . __('Version') . "</td>\n\t\t\t\t<td width='10%'>" . __('Author') . "</td></tr>"; $system_enabled = array_map("trim", explode(",", PLUGINS)); $user_enabled = array_map("trim", explode(",", get_pref("_ENABLED_PLUGINS"))); $tmppluginhost = new PluginHost(); $tmppluginhost->load_all($tmppluginhost::KIND_ALL, $_SESSION["uid"]); $tmppluginhost->load_data(true); foreach ($tmppluginhost->get_plugins() as $name => $plugin) { $about = $plugin->about(); if ($about[3] && strpos($name, "example") === FALSE) { if (in_array($name, $system_enabled)) { $checked = "checked='1'"; } else { $checked = ""; } print "<tr>"; print "<td align='center'><input disabled='1'\n\t\t\t\t\t\tdojoType=\"dijit.form.CheckBox\" {$checked}\n\t\t\t\t\t\ttype=\"checkbox\"></td>"; $plugin_icon = $checked ? "plugin.png" : "plugin_disabled.png"; print "<td><label><img src='images/{$plugin_icon}' alt=''> {$name}</label></td>"; print "<td>" . htmlspecialchars($about[1]); if (@$about[4]) { print " — <a target=\"_blank\" class=\"visibleLink\"\n\t\t\t\t\t\thref=\"" . htmlspecialchars($about[4]) . "\">" . __("more info") . "</a>"; } print "</td>"; print "<td>" . htmlspecialchars(sprintf("%.2f", $about[0])) . "</td>"; print "<td>" . htmlspecialchars($about[2]) . "</td>"; if (count($tmppluginhost->get_all($plugin)) > 0) { if (in_array($name, $system_enabled)) { print "<td><a href='#' onclick=\"clearPluginData('{$name}')\"\n\t\t\t\t\t\t\tclass='visibleLink'>" . __("Clear data") . "</a></td>"; } } print "</tr>"; } } print "<tr><td colspan='4'><h3>" . __("User plugins") . "</h3></td></tr>"; print "<tr class=\"title\">\n\t\t\t\t<td width=\"5%\"> </td>\n\t\t\t\t<td width='10%'>" . __('Plugin') . "</td>\n\t\t\t\t<td width=''>" . __('Description') . "</td>\n\t\t\t\t<td width='5%'>" . __('Version') . "</td>\n\t\t\t\t<td width='10%'>" . __('Author') . "</td></tr>"; foreach ($tmppluginhost->get_plugins() as $name => $plugin) { $about = $plugin->about(); if (!$about[3] && strpos($name, "example") === FALSE) { if (in_array($name, $system_enabled)) { $checked = "checked='1'"; $disabled = "disabled='1'"; $rowclass = ''; } else { if (in_array($name, $user_enabled)) { $checked = "checked='1'"; $disabled = ""; $rowclass = "Selected"; } else { $checked = ""; $disabled = ""; $rowclass = ''; } } print "<tr class='{$rowclass}'>"; $plugin_icon = $checked ? "plugin.png" : "plugin_disabled.png"; print "<td align='center'><input id='FPCHK-{$name}' name='plugins[]' value='{$name}' onclick='toggleSelectRow2(this);'\n\t\t\t\t\tdojoType=\"dijit.form.CheckBox\" {$checked} {$disabled}\n\t\t\t\t\ttype=\"checkbox\"></td>"; print "<td><label for='FPCHK-{$name}'><img src='images/{$plugin_icon}' alt=''> {$name}</label></td>"; print "<td><label for='FPCHK-{$name}'>" . htmlspecialchars($about[1]) . "</label>"; if (@$about[4]) { print " — <a target=\"_blank\" class=\"visibleLink\"\n\t\t\t\t\t\thref=\"" . htmlspecialchars($about[4]) . "\">" . __("more info") . "</a>"; } print "</td>"; print "<td>" . htmlspecialchars(sprintf("%.2f", $about[0])) . "</td>"; print "<td>" . htmlspecialchars($about[2]) . "</td>"; if (count($tmppluginhost->get_all($plugin)) > 0) { if (in_array($name, $system_enabled) || in_array($name, $user_enabled)) { print "<td><a href='#' onclick=\"clearPluginData('{$name}')\" class='visibleLink'>" . __("Clear data") . "</a></td>"; } } print "</tr>"; } } print "</table>"; print "<p><button dojoType=\"dijit.form.Button\" type=\"submit\">" . __("Enable selected plugins") . "</button></p>"; print "</form>"; print "</div>"; #pane PluginHost::getInstance()->run_hooks(PluginHost::HOOK_PREFS_TAB, "hook_prefs_tab", "prefPrefs"); print "</div>"; #container }
function update_rss_feed($feed, $ignore_daemon = false, $no_cache = false, $rss = false) { $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']; _debug_suppress(!$debug_enabled); _debug("start", $debug_enabled); $result = db_query("SELECT title FROM ttrss_feeds\n\t\t\tWHERE id = '{$feed}'"); $title = db_fetch_result($result, 0, "title"); // feed was batch-subscribed or something, we need to get basic info // this is not optimal currently as it fetches stuff separately TODO: optimize if ($title == "[Unknown]") { _debug("setting basic feed info for {$feed}..."); set_basic_feed_info($feed); } $result = db_query("SELECT id,update_interval,auth_login,\n\t\t\tfeed_url,auth_pass,cache_images,\n\t\t\tmark_unread_on_update, owner_uid,\n\t\t\tpubsub_state, auth_pass_encrypted,\n\t\t\tfeed_language,\n\t\t\t(SELECT max(date_entered) FROM\n\t\t\t\tttrss_entries, ttrss_user_entries where ref_id = id AND feed_id = '{$feed}') AS last_article_timestamp\n\t\t\tFROM ttrss_feeds WHERE id = '{$feed}'"); if (db_num_rows($result) == 0) { _debug("feed {$feed} NOT FOUND/SKIPPED", $debug_enabled); return false; } $last_article_timestamp = @strtotime(db_fetch_result($result, 0, "last_article_timestamp")); if (defined('_DISABLE_HTTP_304')) { $last_article_timestamp = 0; } $owner_uid = db_fetch_result($result, 0, "owner_uid"); $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result, 0, "mark_unread_on_update")); $pubsub_state = db_fetch_result($result, 0, "pubsub_state"); $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result, 0, "auth_pass_encrypted")); db_query("UPDATE ttrss_feeds SET last_update_started = NOW()\n\t\t\tWHERE id = '{$feed}'"); $auth_login = db_fetch_result($result, 0, "auth_login"); $auth_pass = db_fetch_result($result, 0, "auth_pass"); if ($auth_pass_encrypted) { require_once "crypt.php"; $auth_pass = decrypt_string($auth_pass); } $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images")); $fetch_url = db_fetch_result($result, 0, "feed_url"); $feed_language = db_escape_string(mb_strtolower(db_fetch_result($result, 0, "feed_language"))); if (!$feed_language) { $feed_language = 'english'; } $feed = db_escape_string($feed); $date_feed_processed = date('Y-m-d H:i'); $cache_filename = CACHE_DIR . "/simplepie/" . sha1($fetch_url) . ".xml"; $pluginhost = new PluginHost(); $pluginhost->set_debug($debug_enabled); $user_plugins = get_pref("_ENABLED_PLUGINS", $owner_uid); $pluginhost->load(PLUGINS, PluginHost::KIND_ALL); $pluginhost->load($user_plugins, PluginHost::KIND_USER, $owner_uid); $pluginhost->load_data(); if ($rss && is_object($rss) && get_class($rss) == "FeedParser") { _debug("using previously initialized parser object"); } else { $rss_hash = false; $force_refetch = isset($_REQUEST["force_refetch"]); foreach ($pluginhost->get_hooks(PluginHost::HOOK_FETCH_FEED) as $plugin) { $feed_data = $plugin->hook_fetch_feed($feed_data, $fetch_url, $owner_uid, $feed, $last_article_timestamp, $auth_login, $auth_pass); } // try cache if (!$feed_data && file_exists($cache_filename) && is_readable($cache_filename) && !$auth_login && !$auth_pass && filemtime($cache_filename) > time() - 30) { _debug("using local cache [{$cache_filename}].", $debug_enabled); @($feed_data = file_get_contents($cache_filename)); if ($feed_data) { $rss_hash = sha1($feed_data); } } else { _debug("local cache will not be used for this feed", $debug_enabled); } // fetch feed from source if (!$feed_data) { _debug("fetching [{$fetch_url}]...", $debug_enabled); _debug("If-Modified-Since: " . gmdate('D, d M Y H:i:s \\G\\M\\T', $last_article_timestamp), $debug_enabled); $feed_data = fetch_file_contents($fetch_url, false, $auth_login, $auth_pass, false, $no_cache ? FEED_FETCH_NO_CACHE_TIMEOUT : FEED_FETCH_TIMEOUT, $force_refetch ? 0 : $last_article_timestamp); global $fetch_curl_used; if (!$fetch_curl_used) { $tmp = @gzdecode($feed_data); if ($tmp) { $feed_data = $tmp; } } $feed_data = trim($feed_data); _debug("fetch done.", $debug_enabled); // cache vanilla feed data for re-use if ($feed_data && !$auth_pass && !$auth_login && is_writable(CACHE_DIR . "/simplepie")) { $new_rss_hash = sha1($feed_data); if ($new_rss_hash != $rss_hash) { _debug("saving {$cache_filename}", $debug_enabled); @file_put_contents($cache_filename, $feed_data); } } } if (!$feed_data) { global $fetch_last_error; global $fetch_last_error_code; _debug("unable to fetch: {$fetch_last_error} [{$fetch_last_error_code}]", $debug_enabled); $error_escaped = ''; // If-Modified-Since if ($fetch_last_error_code != 304) { $error_escaped = db_escape_string($fetch_last_error); } else { _debug("source claims data not modified, nothing to do.", $debug_enabled); } db_query("UPDATE ttrss_feeds SET last_error = '{$error_escaped}',\n\t\t\t\t\t\tlast_updated = NOW() WHERE id = '{$feed}'"); return; } } foreach ($pluginhost->get_hooks(PluginHost::HOOK_FEED_FETCHED) as $plugin) { $feed_data = $plugin->hook_feed_fetched($feed_data, $fetch_url, $owner_uid, $feed); } // set last update to now so if anything *simplepie* crashes later we won't be // continuously failing on the same feed //db_query("UPDATE ttrss_feeds SET last_updated = NOW() WHERE id = '$feed'"); if (!$rss) { $rss = new FeedParser($feed_data); $rss->init(); } // print_r($rss); $feed = db_escape_string($feed); if (!$rss->error()) { // We use local pluginhost here because we need to load different per-user feed plugins $pluginhost->run_hooks(PluginHost::HOOK_FEED_PARSED, "hook_feed_parsed", $rss); _debug("language: {$feed_language}", $debug_enabled); _debug("processing feed data...", $debug_enabled); // db_query("BEGIN"); if (DB_TYPE == "pgsql") { $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'"; } else { $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)"; } $result = db_query("SELECT owner_uid,favicon_avg_color,\n\t\t\t\t(favicon_last_checked IS NULL OR {$favicon_interval_qpart}) AS\n\t\t\t\t\t\tfavicon_needs_check\n\t\t\t\tFROM ttrss_feeds WHERE id = '{$feed}'"); $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0, "favicon_needs_check")); $favicon_avg_color = db_fetch_result($result, 0, "favicon_avg_color"); $owner_uid = db_fetch_result($result, 0, "owner_uid"); $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245)); _debug("site_url: {$site_url}", $debug_enabled); _debug("feed_title: " . $rss->get_title(), $debug_enabled); if ($favicon_needs_check || $force_refetch) { /* terrible hack: if we crash on floicon shit here, we won't check * the icon avgcolor again (unless the icon got updated) */ $favicon_file = ICONS_DIR . "/{$feed}.ico"; $favicon_modified = @filemtime($favicon_file); _debug("checking favicon...", $debug_enabled); check_feed_favicon($site_url, $feed); $favicon_modified_new = @filemtime($favicon_file); if ($favicon_modified_new > $favicon_modified) { $favicon_avg_color = ''; } if (file_exists($favicon_file) && function_exists("imagecreatefromstring") && $favicon_avg_color == '') { require_once "colors.php"; db_query("UPDATE ttrss_feeds SET favicon_avg_color = 'fail' WHERE\n\t\t\t\t\t\t\tid = '{$feed}'"); $favicon_color = db_escape_string(calculate_avg_color($favicon_file)); $favicon_colorstring = ",favicon_avg_color = '" . $favicon_color . "'"; } else { if ($favicon_avg_color == 'fail') { _debug("floicon failed on this file, not trying to recalculate avg color", $debug_enabled); } } db_query("UPDATE ttrss_feeds SET favicon_last_checked = NOW()\n\t\t\t\t\t{$favicon_colorstring}\n\t\t\t\t\tWHERE id = '{$feed}'"); } _debug("loading filters & labels...", $debug_enabled); $filters = load_filters($feed, $owner_uid); _debug("" . count($filters) . " filters loaded.", $debug_enabled); $items = $rss->get_items(); if (!is_array($items)) { _debug("no articles found.", $debug_enabled); db_query("UPDATE ttrss_feeds\n\t\t\t\t\tSET last_updated = NOW(), last_error = '' WHERE id = '{$feed}'"); return; // no articles } if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) { _debug("checking for PUSH hub...", $debug_enabled); $feed_hub_url = false; $links = $rss->get_links('hub'); if ($links && is_array($links)) { foreach ($links as $l) { $feed_hub_url = $l; break; } } _debug("feed hub url: {$feed_hub_url}", $debug_enabled); $feed_self_url = $fetch_url; $links = $rss->get_links('self'); if ($links && is_array($links)) { foreach ($links as $l) { $feed_self_url = $l; break; } } _debug("feed self url = {$feed_self_url}"); if ($feed_hub_url && $feed_self_url && function_exists('curl_init') && !ini_get("open_basedir")) { require_once 'lib/pubsubhubbub/subscriber.php'; $callback_url = get_self_url_prefix() . "/public.php?op=pubsub&id={$feed}"; $s = new Subscriber($feed_hub_url, $callback_url); $rc = $s->subscribe($feed_self_url); _debug("feed hub url found, subscribe request sent. [rc={$rc}]", $debug_enabled); db_query("UPDATE ttrss_feeds SET pubsub_state = 1\n\t\t\t\t\t\tWHERE id = '{$feed}'"); } } _debug("processing articles...", $debug_enabled); $tstart = time(); foreach ($items as $item) { if ($_REQUEST['xdebug'] == 3) { print_r($item); } if (ini_get("max_execution_time") > 0 && time() - $tstart >= ini_get("max_execution_time") * 0.7) { _debug("looks like there's too many articles to process at once, breaking out", $debug_enabled); break; } $entry_guid = $item->get_id(); if (!$entry_guid) { $entry_guid = $item->get_link(); } if (!$entry_guid) { $entry_guid = make_guid_from_title($item->get_title()); } if (!$entry_guid) { continue; } $entry_guid = "{$owner_uid},{$entry_guid}"; $entry_guid_hashed = db_escape_string('SHA1:' . sha1($entry_guid)); _debug("guid {$entry_guid} / {$entry_guid_hashed}", $debug_enabled); $entry_timestamp = ""; $entry_timestamp = $item->get_date(); _debug("orig date: " . $item->get_date(), $debug_enabled); if ($entry_timestamp == -1 || !$entry_timestamp || $entry_timestamp > time()) { $entry_timestamp = time(); } $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp); _debug("date {$entry_timestamp} [{$entry_timestamp_fmt}]", $debug_enabled); // $entry_title = html_entity_decode($item->get_title(), ENT_COMPAT, 'UTF-8'); // $entry_title = decode_numeric_entities($entry_title); $entry_title = $item->get_title(); $entry_link = rewrite_relative_url($site_url, $item->get_link()); _debug("title {$entry_title}", $debug_enabled); _debug("link {$entry_link}", $debug_enabled); if (!$entry_title) { $entry_title = date("Y-m-d H:i:s", $entry_timestamp); } $entry_content = $item->get_content(); if (!$entry_content) { $entry_content = $item->get_description(); } if ($_REQUEST["xdebug"] == 2) { print "content: "; print $entry_content; print "\n"; } $entry_comments = $item->get_comments_url(); $entry_author = $item->get_author(); $entry_guid = db_escape_string(mb_substr($entry_guid, 0, 245)); $entry_comments = db_escape_string(mb_substr(trim($entry_comments), 0, 245)); $entry_author = db_escape_string(mb_substr(trim($entry_author), 0, 245)); $num_comments = (int) $item->get_comments_count(); _debug("author {$entry_author}", $debug_enabled); _debug("num_comments: {$num_comments}", $debug_enabled); _debug("looking for tags...", $debug_enabled); // parse <category> entries into tags $additional_tags = array(); $additional_tags_src = $item->get_categories(); if (is_array($additional_tags_src)) { foreach ($additional_tags_src as $tobj) { array_push($additional_tags, $tobj); } } $entry_tags = array_unique($additional_tags); for ($i = 0; $i < count($entry_tags); $i++) { $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8'); } _debug("tags found: " . join(",", $entry_tags), $debug_enabled); _debug("done collecting data.", $debug_enabled); $result = db_query("SELECT id, content_hash, lang FROM ttrss_entries\n\t\t\t\t\tWHERE guid = '" . db_escape_string($entry_guid) . "' OR guid = '{$entry_guid_hashed}'"); if (db_num_rows($result) != 0) { $base_entry_id = db_fetch_result($result, 0, "id"); $entry_stored_hash = db_fetch_result($result, 0, "content_hash"); $article_labels = get_article_labels($base_entry_id, $owner_uid); $entry_language = db_fetch_result($result, 0, "lang"); } else { $base_entry_id = false; $entry_stored_hash = ""; $article_labels = array(); $entry_language = ""; } $article = array("owner_uid" => $owner_uid, "guid" => $entry_guid, "guid_hashed" => $entry_guid_hashed, "title" => $entry_title, "content" => $entry_content, "link" => $entry_link, "labels" => $article_labels, "tags" => $entry_tags, "author" => $entry_author, "force_catchup" => false, "score_modifier" => 0, "language" => $entry_language, "feed" => array("id" => $feed, "fetch_url" => $fetch_url, "site_url" => $site_url)); $entry_plugin_data = ""; $entry_current_hash = calculate_article_hash($article, $pluginhost); _debug("article hash: {$entry_current_hash} [stored={$entry_stored_hash}]", $debug_enabled); if ($entry_current_hash == $entry_stored_hash && !isset($_REQUEST["force_rehash"])) { _debug("stored article seems up to date [IID: {$base_entry_id}], updating timestamp only", $debug_enabled); // we keep encountering the entry in feeds, so we need to // update date_updated column so that we don't get horrible // dupes when the entry gets purged and reinserted again e.g. // in the case of SLOW SLOW OMG SLOW updating feeds $base_entry_id = db_fetch_result($result, 0, "id"); db_query("UPDATE ttrss_entries SET date_updated = NOW()\n\t\t\t\t\t\tWHERE id = '{$base_entry_id}'"); // if we allow duplicate posts, we have to continue to // create the user entries for this feed if (!get_pref("ALLOW_DUPLICATE_POSTS", $owner_uid, false)) { continue; } } _debug("hash differs, applying plugin filters:", $debug_enabled); foreach ($pluginhost->get_hooks(PluginHost::HOOK_ARTICLE_FILTER) as $plugin) { _debug("... " . get_class($plugin), $debug_enabled); $start = microtime(true); $article = $plugin->hook_article_filter($article); _debug("=== " . sprintf("%.4f (sec)", microtime(true) - $start), $debug_enabled); $entry_plugin_data .= mb_strtolower(get_class($plugin)) . ","; } $entry_plugin_data = db_escape_string($entry_plugin_data); _debug("plugin data: {$entry_plugin_data}", $debug_enabled); // Workaround: 4-byte unicode requires utf8mb4 in MySQL. See https://tt-rss.org/forum/viewtopic.php?f=1&t=3377&p=20077#p20077 if (DB_TYPE == "mysql") { foreach ($article as $k => $v) { // i guess we'll have to take the risk of 4byte unicode labels & tags here if (!is_array($article[$k])) { $article[$k] = preg_replace('/[\\x{10000}-\\x{10FFFF}]/u', "�", $v); } } } $entry_tags = $article["tags"]; $entry_guid = db_escape_string($entry_guid); $entry_title = db_escape_string($article["title"]); $entry_author = db_escape_string($article["author"]); $entry_link = db_escape_string($article["link"]); $entry_content = $article["content"]; // escaped below $entry_force_catchup = $article["force_catchup"]; $article_labels = $article["labels"]; $entry_score_modifier = (int) $article["score_modifier"]; $entry_language = db_escape_string($article["language"]); if ($debug_enabled) { _debug("article labels:", $debug_enabled); print_r($article_labels); } _debug("force catchup: {$entry_force_catchup}"); if ($cache_images && is_writable(CACHE_DIR . '/images')) { cache_images($entry_content, $site_url, $debug_enabled); } $entry_content = db_escape_string($entry_content, false); db_query("BEGIN"); $result = db_query("SELECT id FROM\tttrss_entries\n\t\t\t\t\tWHERE (guid = '{$entry_guid}' OR guid = '{$entry_guid_hashed}')"); if (db_num_rows($result) == 0) { _debug("base guid [{$entry_guid}] not found", $debug_enabled); // base post entry does not exist, create it $result = db_query("INSERT INTO ttrss_entries\n\t\t\t\t\t\t\t(title,\n\t\t\t\t\t\t\tguid,\n\t\t\t\t\t\t\tlink,\n\t\t\t\t\t\t\tupdated,\n\t\t\t\t\t\t\tcontent,\n\t\t\t\t\t\t\tcontent_hash,\n\t\t\t\t\t\t\tno_orig_date,\n\t\t\t\t\t\t\tdate_updated,\n\t\t\t\t\t\t\tdate_entered,\n\t\t\t\t\t\t\tcomments,\n\t\t\t\t\t\t\tnum_comments,\n\t\t\t\t\t\t\tplugin_data,\n\t\t\t\t\t\t\tlang,\n\t\t\t\t\t\t\tauthor)\n\t\t\t\t\t\tVALUES\n\t\t\t\t\t\t\t('{$entry_title}',\n\t\t\t\t\t\t\t'{$entry_guid_hashed}',\n\t\t\t\t\t\t\t'{$entry_link}',\n\t\t\t\t\t\t\t'{$entry_timestamp_fmt}',\n\t\t\t\t\t\t\t'{$entry_content}',\n\t\t\t\t\t\t\t'{$entry_current_hash}',\n\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t\tNOW(),\n\t\t\t\t\t\t\t'{$date_feed_processed}',\n\t\t\t\t\t\t\t'{$entry_comments}',\n\t\t\t\t\t\t\t'{$num_comments}',\n\t\t\t\t\t\t\t'{$entry_plugin_data}',\n\t\t\t\t\t\t\t'{$entry_language}',\n\t\t\t\t\t\t\t'{$entry_author}')"); } else { $base_entry_id = db_fetch_result($result, 0, "id"); } // now it should exist, if not - bad luck then $result = db_query("SELECT id FROM ttrss_entries\n\t\t\t\t\tWHERE guid = '{$entry_guid}' OR guid = '{$entry_guid_hashed}'"); $entry_ref_id = 0; $entry_int_id = 0; if (db_num_rows($result) == 1) { _debug("base guid found, checking for user record", $debug_enabled); $ref_id = db_fetch_result($result, 0, "id"); $entry_ref_id = $ref_id; /* $stored_guid = db_fetch_result($result, 0, "guid"); if ($stored_guid != $entry_guid_hashed) { if ($debug_enabled) _debug("upgrading compat guid to hashed one", $debug_enabled); db_query("UPDATE ttrss_entries SET guid = '$entry_guid_hashed' WHERE id = '$ref_id'"); } */ // check for user post link to main table // do we allow duplicate posts with same GUID in different feeds? if (get_pref("ALLOW_DUPLICATE_POSTS", $owner_uid, false)) { $dupcheck_qpart = "AND (feed_id = '{$feed}' OR feed_id IS NULL)"; } else { $dupcheck_qpart = ""; } /* Collect article tags here so we could filter by them: */ $article_filters = get_article_filters($filters, $entry_title, $entry_content, $entry_link, $entry_timestamp, $entry_author, $entry_tags); if ($debug_enabled) { _debug("article filters: ", $debug_enabled); if (count($article_filters) != 0) { print_r($article_filters); } } if (find_article_filter($article_filters, "filter")) { db_query("COMMIT"); // close transaction in progress continue; } $score = calculate_article_score($article_filters) + $entry_score_modifier; _debug("initial score: {$score} [including plugin modifier: {$entry_score_modifier}]", $debug_enabled); $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE\n\t\t\t\t\t\t\tref_id = '{$ref_id}' AND owner_uid = '{$owner_uid}'\n\t\t\t\t\t\t\t{$dupcheck_qpart}"; // if ($_REQUEST["xdebug"]) print "$query\n"; $result = db_query($query); // okay it doesn't exist - create user entry if (db_num_rows($result) == 0) { _debug("user record not found, creating...", $debug_enabled); if ($score >= -500 && !find_article_filter($article_filters, 'catchup') && !$entry_force_catchup) { $unread = 'true'; $last_read_qpart = 'NULL'; } else { $unread = 'false'; $last_read_qpart = 'NOW()'; } if (find_article_filter($article_filters, 'mark') || $score > 1000) { $marked = 'true'; } else { $marked = 'false'; } if (find_article_filter($article_filters, 'publish')) { $published = 'true'; } else { $published = 'false'; } // N-grams /* if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) { $result = db_query("SELECT COUNT(*) AS similar FROM ttrss_entries,ttrss_user_entries WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day' AND similarity(title, '$entry_title') >= "._NGRAM_TITLE_DUPLICATE_THRESHOLD." AND owner_uid = $owner_uid"); $ngram_similar = db_fetch_result($result, 0, "similar"); _debug("N-gram similar results: $ngram_similar", $debug_enabled); if ($ngram_similar > 0) { $unread = 'false'; } } */ $last_marked = $marked == 'true' ? 'NOW()' : 'NULL'; $last_published = $published == 'true' ? 'NOW()' : 'NULL'; $result = db_query("INSERT INTO ttrss_user_entries\n\t\t\t\t\t\t\t\t(ref_id, owner_uid, feed_id, unread, last_read, marked,\n\t\t\t\t\t\t\t\tpublished, score, tag_cache, label_cache, uuid,\n\t\t\t\t\t\t\t\tlast_marked, last_published)\n\t\t\t\t\t\t\tVALUES ('{$ref_id}', '{$owner_uid}', '{$feed}', {$unread},\n\t\t\t\t\t\t\t\t{$last_read_qpart}, {$marked}, {$published}, '{$score}', '', '',\n\t\t\t\t\t\t\t\t'', {$last_marked}, {$last_published})"); if (PUBSUBHUBBUB_HUB && $published == 'true') { $rss_link = get_self_url_prefix() . "/public.php?op=rss&id=-2&key=" . get_feed_access_key(-2, false, $owner_uid); $p = new Publisher(PUBSUBHUBBUB_HUB); /* $pubsub_result = */ $p->publish_update($rss_link); } $result = db_query("SELECT int_id FROM ttrss_user_entries WHERE\n\t\t\t\t\t\t\t\tref_id = '{$ref_id}' AND owner_uid = '{$owner_uid}' AND\n\t\t\t\t\t\t\t\tfeed_id = '{$feed}' LIMIT 1"); if (db_num_rows($result) == 1) { $entry_int_id = db_fetch_result($result, 0, "int_id"); } } else { _debug("user record FOUND", $debug_enabled); $entry_ref_id = db_fetch_result($result, 0, "ref_id"); $entry_int_id = db_fetch_result($result, 0, "int_id"); } _debug("RID: {$entry_ref_id}, IID: {$entry_int_id}", $debug_enabled); if (DB_TYPE == "pgsql") { $tsvector_combined = db_escape_string(mb_substr($entry_title . ' ' . strip_tags($entry_content), 0, 1000000)); $tsvector_qpart = "tsvector_combined = to_tsvector('{$feed_language}', '{$tsvector_combined}'),"; } else { $tsvector_qpart = ""; } db_query("UPDATE ttrss_entries\n\t\t\t\t\t\tSET title = '{$entry_title}',\n\t\t\t\t\t\t\tcontent = '{$entry_content}',\n\t\t\t\t\t\t\tcontent_hash = '{$entry_current_hash}',\n\t\t\t\t\t\t\tupdated = '{$entry_timestamp_fmt}',\n\t\t\t\t\t\t\t{$tsvector_qpart}\n\t\t\t\t\t\t\tnum_comments = '{$num_comments}',\n\t\t\t\t\t\t\tplugin_data = '{$entry_plugin_data}',\n\t\t\t\t\t\t\tauthor = '{$entry_author}',\n\t\t\t\t\t\t\tlang = '{$entry_language}'\n\t\t\t\t\t\tWHERE id = '{$ref_id}'"); // update aux data db_query("UPDATE ttrss_user_entries\n\t\t\t\t\t\t\tSET score = '{$score}' WHERE ref_id = '{$ref_id}'"); if ($mark_unread_on_update) { db_query("UPDATE ttrss_user_entries\n\t\t\t\t\t\t\tSET last_read = null, unread = true WHERE ref_id = '{$ref_id}'"); } } db_query("COMMIT"); _debug("assigning labels [other]...", $debug_enabled); foreach ($article_labels as $label) { label_add_article($entry_ref_id, $label[1], $owner_uid); } _debug("assigning labels [filters]...", $debug_enabled); assign_article_to_label_filters($entry_ref_id, $article_filters, $owner_uid, $article_labels); _debug("looking for enclosures...", $debug_enabled); // enclosures $enclosures = array(); $encs = $item->get_enclosures(); if (is_array($encs)) { foreach ($encs as $e) { $e_item = array($e->link, $e->type, $e->length, $e->title, $e->width, $e->height); array_push($enclosures, $e_item); } } if ($debug_enabled) { _debug("article enclosures:", $debug_enabled); print_r($enclosures); } db_query("BEGIN"); // debugging // db_query("DELETE FROM ttrss_enclosures WHERE post_id = '$entry_ref_id'"); foreach ($enclosures as $enc) { $enc_url = db_escape_string($enc[0]); $enc_type = db_escape_string($enc[1]); $enc_dur = db_escape_string($enc[2]); $enc_title = db_escape_string($enc[3]); $enc_width = intval($enc[4]); $enc_height = intval($enc[5]); $result = db_query("SELECT id FROM ttrss_enclosures\n\t\t\t\t\t\tWHERE content_url = '{$enc_url}' AND post_id = '{$entry_ref_id}'"); if (db_num_rows($result) == 0) { db_query("INSERT INTO ttrss_enclosures\n\t\t\t\t\t\t\t(content_url, content_type, title, duration, post_id, width, height) VALUES\n\t\t\t\t\t\t\t('{$enc_url}', '{$enc_type}', '{$enc_title}', '{$enc_dur}', '{$entry_ref_id}', {$enc_width}, {$enc_height})"); } } db_query("COMMIT"); // check for manual tags (we have to do it here since they're loaded from filters) foreach ($article_filters as $f) { if ($f["type"] == "tag") { $manual_tags = trim_array(explode(",", $f["param"])); foreach ($manual_tags as $tag) { if (tag_is_valid($tag)) { array_push($entry_tags, $tag); } } } } // Skip boring tags $boring_tags = trim_array(explode(",", mb_strtolower(get_pref('BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8'))); $filtered_tags = array(); $tags_to_cache = array(); if ($entry_tags && is_array($entry_tags)) { foreach ($entry_tags as $tag) { if (array_search($tag, $boring_tags) === false) { array_push($filtered_tags, $tag); } } } $filtered_tags = array_unique($filtered_tags); if ($debug_enabled) { _debug("filtered article tags:", $debug_enabled); print_r($filtered_tags); } // Save article tags in the database if (count($filtered_tags) > 0) { db_query("BEGIN"); foreach ($filtered_tags as $tag) { $tag = sanitize_tag($tag); $tag = db_escape_string($tag); if (!tag_is_valid($tag)) { continue; } $result = db_query("SELECT id FROM ttrss_tags\n\t\t\t\t\t\t\tWHERE tag_name = '{$tag}' AND post_int_id = '{$entry_int_id}' AND\n\t\t\t\t\t\t\towner_uid = '{$owner_uid}' LIMIT 1"); if ($result && db_num_rows($result) == 0) { db_query("INSERT INTO ttrss_tags\n\t\t\t\t\t\t\t\t\t(owner_uid,tag_name,post_int_id)\n\t\t\t\t\t\t\t\t\tVALUES ('{$owner_uid}','{$tag}', '{$entry_int_id}')"); } array_push($tags_to_cache, $tag); } /* update the cache */ $tags_to_cache = array_unique($tags_to_cache); $tags_str = db_escape_string(join(",", $tags_to_cache)); db_query("UPDATE ttrss_user_entries\n\t\t\t\t\t\tSET tag_cache = '{$tags_str}' WHERE ref_id = '{$entry_ref_id}'\n\t\t\t\t\t\tAND owner_uid = {$owner_uid}"); db_query("COMMIT"); } _debug("article processed", $debug_enabled); } _debug("purging feed...", $debug_enabled); purge_feed($feed, 0, $debug_enabled); db_query("UPDATE ttrss_feeds\n\t\t\t\tSET last_updated = NOW(), last_error = '' WHERE id = '{$feed}'"); // db_query("COMMIT"); } else { $error_msg = db_escape_string(mb_substr($rss->error(), 0, 245)); _debug("fetch error: {$error_msg}", $debug_enabled); if (count($rss->errors()) > 1) { foreach ($rss->errors() as $error) { _debug("+ {$error}"); } } db_query("UPDATE ttrss_feeds SET last_error = '{$error_msg}',\n\t\t\t\tlast_updated = NOW() WHERE id = '{$feed}'"); unset($rss); } _debug("done", $debug_enabled); return $rss; }
static function create_published_article($title, $url, $content, $labels_str, $owner_uid) { $guid = 'SHA1:' . sha1("ttshared:" . $url . $owner_uid); // include owner_uid to prevent global GUID clash if (!$content) { $pluginhost = new PluginHost(); $pluginhost->load_all(PluginHost::KIND_ALL, $owner_uid); $pluginhost->load_data(); $af_readability = $pluginhost->get_plugin("Af_Readability"); if ($af_readability) { $enable_share_anything = $pluginhost->get($af_readability, "enable_share_anything"); if ($enable_share_anything) { $extracted_content = $af_readability->extract_content($url); if ($extracted_content) { $content = db_escape_string($extracted_content); } } } } $content_hash = sha1($content); if ($labels_str != "") { $labels = explode(",", $labels_str); } else { $labels = array(); } $rc = false; if (!$title) { $title = $url; } if (!$title && !$url) { return false; } if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) { return false; } db_query("BEGIN"); // only check for our user data here, others might have shared this with different content etc $result = db_query("SELECT id FROM ttrss_entries, ttrss_user_entries WHERE\n\t\t\tguid = '{$guid}' AND ref_id = id AND owner_uid = '{$owner_uid}' LIMIT 1"); if (db_num_rows($result) != 0) { $ref_id = db_fetch_result($result, 0, "id"); $result = db_query("SELECT int_id FROM ttrss_user_entries WHERE\n\t\t\t\tref_id = '{$ref_id}' AND owner_uid = '{$owner_uid}' LIMIT 1"); if (db_num_rows($result) != 0) { $int_id = db_fetch_result($result, 0, "int_id"); db_query("UPDATE ttrss_entries SET\n\t\t\t\t\tcontent = '{$content}', content_hash = '{$content_hash}' WHERE id = '{$ref_id}'"); db_query("UPDATE ttrss_user_entries SET published = true,\n\t\t\t\t\t\tlast_published = NOW() WHERE\n\t\t\t\t\t\tint_id = '{$int_id}' AND owner_uid = '{$owner_uid}'"); } else { db_query("INSERT INTO ttrss_user_entries\n\t\t\t\t\t(ref_id, uuid, feed_id, orig_feed_id, owner_uid, published, tag_cache, label_cache,\n\t\t\t\t\t\tlast_read, note, unread, last_published)\n\t\t\t\t\tVALUES\n\t\t\t\t\t('{$ref_id}', '', NULL, NULL, {$owner_uid}, true, '', '', NOW(), '', false, NOW())"); } if (count($labels) != 0) { foreach ($labels as $label) { label_add_article($ref_id, trim($label), $owner_uid); } } $rc = true; } else { $result = db_query("INSERT INTO ttrss_entries\n\t\t\t\t(title, guid, link, updated, content, content_hash, date_entered, date_updated)\n\t\t\t\tVALUES\n\t\t\t\t('{$title}', '{$guid}', '{$url}', NOW(), '{$content}', '{$content_hash}', NOW(), NOW())"); $result = db_query("SELECT id FROM ttrss_entries WHERE guid = '{$guid}'"); if (db_num_rows($result) != 0) { $ref_id = db_fetch_result($result, 0, "id"); db_query("INSERT INTO ttrss_user_entries\n\t\t\t\t\t(ref_id, uuid, feed_id, orig_feed_id, owner_uid, published, tag_cache, label_cache,\n\t\t\t\t\t\tlast_read, note, unread, last_published)\n\t\t\t\t\tVALUES\n\t\t\t\t\t('{$ref_id}', '', NULL, NULL, {$owner_uid}, true, '', '', NOW(), '', false, NOW())"); if (count($labels) != 0) { foreach ($labels as $label) { label_add_article($ref_id, trim($label), $owner_uid); } } $rc = true; } } db_query("COMMIT"); return $rc; }
function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false, $override_url = false) { require_once "lib/simplepie/simplepie.inc"; $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']; if ($debug_enabled) { _debug("update_rss_feed: start"); } $result = db_query($link, "SELECT id,update_interval,auth_login,\n\t\t\tfeed_url,auth_pass,cache_images,last_updated,\n\t\t\tmark_unread_on_update, owner_uid,\n\t\t\tpubsub_state\n\t\t\tFROM ttrss_feeds WHERE id = '{$feed}'"); if (db_num_rows($result) == 0) { if ($debug_enabled) { _debug("update_rss_feed: feed {$feed} NOT FOUND/SKIPPED"); } return false; } $last_updated = db_fetch_result($result, 0, "last_updated"); $owner_uid = db_fetch_result($result, 0, "owner_uid"); $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result, 0, "mark_unread_on_update")); $pubsub_state = db_fetch_result($result, 0, "pubsub_state"); db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()\n\t\t\tWHERE id = '{$feed}'"); $auth_login = db_fetch_result($result, 0, "auth_login"); $auth_pass = db_fetch_result($result, 0, "auth_pass"); $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images")); $fetch_url = db_fetch_result($result, 0, "feed_url"); $feed = db_escape_string($feed); /* if ($auth_login && $auth_pass ){ $url_parts = array(); preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts); if ($url_parts[1] && $url_parts[2]) { $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2]; } } */ if ($override_url) { $fetch_url = $override_url; } if ($debug_enabled) { _debug("update_rss_feed: fetching [{$fetch_url}]..."); } // Ignore cache if new feed or manual update. $cache_age = is_null($last_updated) || $last_updated == '1970-01-01 00:00:00' ? -1 : get_feed_update_interval($link, $feed) * 60; $simplepie_cache_dir = CACHE_DIR . "/simplepie"; if (!is_dir($simplepie_cache_dir)) { mkdir($simplepie_cache_dir); } $feed_data = fetch_file_contents($fetch_url, false, $auth_login, $auth_pass, false, $no_cache ? 15 : 45); if (!$feed_data) { global $fetch_last_error; if ($debug_enabled) { _debug("update_rss_feed: unable to fetch: {$fetch_last_error}"); } $error_escaped = db_escape_string($fetch_last_error); db_query($link, "UPDATE ttrss_feeds SET last_error = '{$error_escaped}',\n\t\t\t\t\tlast_updated = NOW() WHERE id = '{$feed}'"); return; } $pluginhost = new PluginHost($link); $pluginhost->set_debug($debug_enabled); $user_plugins = get_pref($link, "_ENABLED_PLUGINS", $owner_uid); $pluginhost->load(PLUGINS, $pluginhost::KIND_ALL); $pluginhost->load($user_plugins, $pluginhost::KIND_USER, $owner_uid); $pluginhost->load_data(); foreach ($pluginhost->get_hooks($pluginhost::HOOK_FEED_FETCHED) as $plugin) { $feed_data = $plugin->hook_feed_fetched($feed_data); } if ($debug_enabled) { _debug("update_rss_feed: fetch done, parsing..."); } $rss = new SimplePie(); $rss->set_sanitize_class("SanitizeDummy"); // simplepie ignores the above and creates default sanitizer anyway, // so let's override it... $rss->sanitize = new SanitizeDummy(); $rss->set_output_encoding('UTF-8'); $rss->set_raw_data($feed_data); if ($debug_enabled) { _debug("feed update interval (sec): " . get_feed_update_interval($link, $feed) * 60); } $rss->enable_cache(!$no_cache); if (!$no_cache) { $rss->set_cache_location($simplepie_cache_dir); $rss->set_cache_duration($cache_age); } @$rss->init(); // print_r($rss); $feed = db_escape_string($feed); if (!$rss->error()) { // We use local pluginhost here because we need to load different per-user feed plugins $pluginhost->run_hooks($pluginhost::HOOK_FEED_PARSED, "hook_feed_parsed", $rss); if ($debug_enabled) { _debug("update_rss_feed: processing feed data..."); } // db_query($link, "BEGIN"); if (DB_TYPE == "pgsql") { $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'"; } else { $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)"; } $result = db_query($link, "SELECT title,site_url,owner_uid,\n\t\t\t\t(favicon_last_checked IS NULL OR {$favicon_interval_qpart}) AS\n\t\t\t\t\t\tfavicon_needs_check\n\t\t\t\tFROM ttrss_feeds WHERE id = '{$feed}'"); $registered_title = db_fetch_result($result, 0, "title"); $orig_site_url = db_fetch_result($result, 0, "site_url"); $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0, "favicon_needs_check")); $owner_uid = db_fetch_result($result, 0, "owner_uid"); $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245)); if ($debug_enabled) { _debug("update_rss_feed: checking favicon..."); } if ($favicon_needs_check) { check_feed_favicon($site_url, $feed, $link); db_query($link, "UPDATE ttrss_feeds SET favicon_last_checked = NOW()\n\t\t\t\t\tWHERE id = '{$feed}'"); } if (!$registered_title || $registered_title == "[Unknown]") { $feed_title = db_escape_string($rss->get_title()); if ($debug_enabled) { _debug("update_rss_feed: registering title: {$feed_title}"); } db_query($link, "UPDATE ttrss_feeds SET\n\t\t\t\t\ttitle = '{$feed_title}' WHERE id = '{$feed}'"); } if ($site_url && $orig_site_url != $site_url) { db_query($link, "UPDATE ttrss_feeds SET\n\t\t\t\t\tsite_url = '{$site_url}' WHERE id = '{$feed}'"); } if ($debug_enabled) { _debug("update_rss_feed: loading filters & labels..."); } $filters = load_filters($link, $feed, $owner_uid); $labels = get_all_labels($link, $owner_uid); if ($debug_enabled) { //print_r($filters); _debug("update_rss_feed: " . count($filters) . " filters loaded."); } $items = $rss->get_items(); if (!is_array($items)) { if ($debug_enabled) { _debug("update_rss_feed: no articles found."); } db_query($link, "UPDATE ttrss_feeds\n\t\t\t\t\tSET last_updated = NOW(), last_error = '' WHERE id = '{$feed}'"); return; // no articles } if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) { if ($debug_enabled) { _debug("update_rss_feed: checking for PUSH hub..."); } $feed_hub_url = false; $links = $rss->get_links('hub'); if ($links && is_array($links)) { foreach ($links as $l) { $feed_hub_url = $l; break; } } if ($debug_enabled) { _debug("update_rss_feed: feed hub url: {$feed_hub_url}"); } if ($feed_hub_url && function_exists('curl_init') && !ini_get("open_basedir")) { require_once 'lib/pubsubhubbub/subscriber.php'; $callback_url = get_self_url_prefix() . "/public.php?op=pubsub&id={$feed}"; $s = new Subscriber($feed_hub_url, $callback_url); $rc = $s->subscribe($fetch_url); if ($debug_enabled) { _debug("update_rss_feed: feed hub url found, subscribe request sent."); } db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1\n\t\t\t\t\t\tWHERE id = '{$feed}'"); } } if ($debug_enabled) { _debug("update_rss_feed: processing articles..."); } foreach ($items as $item) { if ($_REQUEST['xdebug'] == 3) { print_r($item); } $entry_guid = $item->get_id(); if (!$entry_guid) { $entry_guid = $item->get_link(); } if (!$entry_guid) { $entry_guid = make_guid_from_title($item->get_title()); } if ($debug_enabled) { _debug("update_rss_feed: guid {$entry_guid}"); } if (!$entry_guid) { continue; } $entry_guid = "{$owner_uid},{$entry_guid}"; $entry_timestamp = ""; $entry_timestamp = strtotime($item->get_date()); if ($entry_timestamp == -1 || !$entry_timestamp) { $entry_timestamp = time(); $no_orig_date = 'true'; } else { $no_orig_date = 'false'; } $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp); if ($debug_enabled) { _debug("update_rss_feed: date {$entry_timestamp} [{$entry_timestamp_fmt}]"); } $entry_title = $item->get_title(); $entry_link = rewrite_relative_url($site_url, $item->get_link()); if ($debug_enabled) { _debug("update_rss_feed: title {$entry_title}"); _debug("update_rss_feed: link {$entry_link}"); } if (!$entry_title) { $entry_title = date("Y-m-d H:i:s", $entry_timestamp); } $entry_content = $item->get_content(); if (!$entry_content) { $entry_content = $item->get_description(); } if ($_REQUEST["xdebug"] == 2) { print "update_rss_feed: content: "; print $entry_content; print "\n"; } $entry_comments = $item->data["comments"]; if ($item->get_author()) { $entry_author_item = $item->get_author(); $entry_author = $entry_author_item->get_name(); if (!$entry_author) { $entry_author = $entry_author_item->get_email(); } $entry_author = db_escape_string($entry_author); } $entry_guid = db_escape_string(mb_substr($entry_guid, 0, 245)); $entry_comments = db_escape_string(mb_substr($entry_comments, 0, 245)); $entry_author = db_escape_string(mb_substr($entry_author, 0, 245)); $num_comments = $item->get_item_tags('http://purl.org/rss/1.0/modules/slash/', 'comments'); if (is_array($num_comments) && is_array($num_comments[0])) { $num_comments = (int) $num_comments[0]["data"]; } else { $num_comments = 0; } if ($debug_enabled) { _debug("update_rss_feed: num_comments: {$num_comments}"); _debug("update_rss_feed: looking for tags [1]..."); } // parse <category> entries into tags $additional_tags = array(); $additional_tags_src = $item->get_categories(); if (is_array($additional_tags_src)) { foreach ($additional_tags_src as $tobj) { array_push($additional_tags, $tobj->get_term()); } } if ($debug_enabled) { _debug("update_rss_feed: category tags:"); print_r($additional_tags); } if ($debug_enabled) { _debug("update_rss_feed: looking for tags [2]..."); } $entry_tags = array_unique($additional_tags); for ($i = 0; $i < count($entry_tags); $i++) { $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8'); } if ($debug_enabled) { //_debug("update_rss_feed: unfiltered tags found:"); //print_r($entry_tags); } if ($debug_enabled) { _debug("update_rss_feed: done collecting data."); } // TODO: less memory-hungry implementation if ($debug_enabled) { _debug("update_rss_feed: applying plugin filters.."); } // FIXME not sure if owner_uid is a good idea here, we may have a base entry without user entry (?) $result = db_query($link, "SELECT plugin_data,title,content,link,tag_cache,author FROM ttrss_entries, ttrss_user_entries\n\t\t\t\t\tWHERE ref_id = id AND guid = '" . db_escape_string($entry_guid) . "' AND owner_uid = {$owner_uid}"); if (db_num_rows($result) != 0) { $entry_plugin_data = db_fetch_result($result, 0, "plugin_data"); $stored_article = array("title" => db_fetch_result($result, 0, "title"), "content" => db_fetch_result($result, 0, "content"), "link" => db_fetch_result($result, 0, "link"), "tags" => explode(",", db_fetch_result($result, 0, "tag_cache")), "author" => db_fetch_result($result, 0, "author")); } else { $entry_plugin_data = ""; $stored_article = array(); } $article = array("owner_uid" => $owner_uid, "guid" => $entry_guid, "title" => $entry_title, "content" => $entry_content, "link" => $entry_link, "tags" => $entry_tags, "plugin_data" => $entry_plugin_data, "author" => $entry_author, "stored" => $stored_article); foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_FILTER) as $plugin) { $article = $plugin->hook_article_filter($article); } $entry_tags = $article["tags"]; $entry_guid = db_escape_string($entry_guid); $entry_content = db_escape_string($article["content"], false); $entry_title = db_escape_string($article["title"]); $entry_author = db_escape_string($article["author"]); $entry_link = db_escape_string($article["link"]); $entry_plugin_data = db_escape_string($article["plugin_data"]); if ($debug_enabled) { _debug("update_rss_feed: plugin data: {$entry_plugin_data}"); } if ($cache_images && is_writable(CACHE_DIR . '/images')) { $entry_content = cache_images($entry_content, $site_url, $debug_enabled); } $content_hash = "SHA1:" . sha1($entry_content); db_query($link, "BEGIN"); $result = db_query($link, "SELECT id FROM\tttrss_entries\n\t\t\t\t\tWHERE guid = '{$entry_guid}'"); if (db_num_rows($result) == 0) { if ($debug_enabled) { _debug("update_rss_feed: base guid [{$entry_guid}] not found"); } // base post entry does not exist, create it $result = db_query($link, "INSERT INTO ttrss_entries\n\t\t\t\t\t\t\t(title,\n\t\t\t\t\t\t\tguid,\n\t\t\t\t\t\t\tlink,\n\t\t\t\t\t\t\tupdated,\n\t\t\t\t\t\t\tcontent,\n\t\t\t\t\t\t\tcontent_hash,\n\t\t\t\t\t\t\tcached_content,\n\t\t\t\t\t\t\tno_orig_date,\n\t\t\t\t\t\t\tdate_updated,\n\t\t\t\t\t\t\tdate_entered,\n\t\t\t\t\t\t\tcomments,\n\t\t\t\t\t\t\tnum_comments,\n\t\t\t\t\t\t\tplugin_data,\n\t\t\t\t\t\t\tauthor)\n\t\t\t\t\t\tVALUES\n\t\t\t\t\t\t\t('{$entry_title}',\n\t\t\t\t\t\t\t'{$entry_guid}',\n\t\t\t\t\t\t\t'{$entry_link}',\n\t\t\t\t\t\t\t'{$entry_timestamp_fmt}',\n\t\t\t\t\t\t\t'{$entry_content}',\n\t\t\t\t\t\t\t'{$content_hash}',\n\t\t\t\t\t\t\t'',\n\t\t\t\t\t\t\t{$no_orig_date},\n\t\t\t\t\t\t\tNOW(),\n\t\t\t\t\t\t\tNOW(),\n\t\t\t\t\t\t\t'{$entry_comments}',\n\t\t\t\t\t\t\t'{$num_comments}',\n\t\t\t\t\t\t\t'{$entry_plugin_data}',\n\t\t\t\t\t\t\t'{$entry_author}')"); $article_labels = array(); } else { // we keep encountering the entry in feeds, so we need to // update date_updated column so that we don't get horrible // dupes when the entry gets purged and reinserted again e.g. // in the case of SLOW SLOW OMG SLOW updating feeds $base_entry_id = db_fetch_result($result, 0, "id"); db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()\n\t\t\t\t\t\tWHERE id = '{$base_entry_id}'"); $article_labels = get_article_labels($link, $base_entry_id, $owner_uid); } // now it should exist, if not - bad luck then $result = db_query($link, "SELECT\n\t\t\t\t\t\tid,content_hash,no_orig_date,title,plugin_data,\n\t\t\t\t\t\t" . SUBSTRING_FOR_DATE . "(date_updated,1,19) as date_updated,\n\t\t\t\t\t\t" . SUBSTRING_FOR_DATE . "(updated,1,19) as updated,\n\t\t\t\t\t\tnum_comments\n\t\t\t\t\tFROM\n\t\t\t\t\t\tttrss_entries\n\t\t\t\t\tWHERE guid = '{$entry_guid}'"); $entry_ref_id = 0; $entry_int_id = 0; if (db_num_rows($result) == 1) { if ($debug_enabled) { _debug("update_rss_feed: base guid [{$entry_guid}] found, checking for user record"); } // this will be used below in update handler $orig_content_hash = db_fetch_result($result, 0, "content_hash"); $orig_title = db_fetch_result($result, 0, "title"); $orig_num_comments = db_fetch_result($result, 0, "num_comments"); $orig_date_updated = strtotime(db_fetch_result($result, 0, "date_updated")); $orig_plugin_data = db_fetch_result($result, 0, "plugin_data"); $ref_id = db_fetch_result($result, 0, "id"); $entry_ref_id = $ref_id; // check for user post link to main table // do we allow duplicate posts with same GUID in different feeds? if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) { $dupcheck_qpart = "AND (feed_id = '{$feed}' OR feed_id IS NULL)"; } else { $dupcheck_qpart = ""; } /* Collect article tags here so we could filter by them: */ $article_filters = get_article_filters($filters, $entry_title, $entry_content, $entry_link, $entry_timestamp, $entry_author, $entry_tags); if ($debug_enabled) { _debug("update_rss_feed: article filters: "); if (count($article_filters) != 0) { print_r($article_filters); } } if (find_article_filter($article_filters, "filter")) { db_query($link, "COMMIT"); // close transaction in progress continue; } $score = calculate_article_score($article_filters); if ($debug_enabled) { _debug("update_rss_feed: initial score: {$score}"); } $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE\n\t\t\t\t\t\t\tref_id = '{$ref_id}' AND owner_uid = '{$owner_uid}'\n\t\t\t\t\t\t\t{$dupcheck_qpart}"; // if ($_REQUEST["xdebug"]) print "$query\n"; $result = db_query($link, $query); // okay it doesn't exist - create user entry if (db_num_rows($result) == 0) { if ($debug_enabled) { _debug("update_rss_feed: user record not found, creating..."); } if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) { $unread = 'true'; $last_read_qpart = 'NULL'; } else { $unread = 'false'; $last_read_qpart = 'NOW()'; } if (find_article_filter($article_filters, 'mark') || $score > 1000) { $marked = 'true'; } else { $marked = 'false'; } if (find_article_filter($article_filters, 'publish')) { $published = 'true'; } else { $published = 'false'; } // N-grams if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) { $result = db_query($link, "SELECT COUNT(*) AS similar FROM\n\t\t\t\t\t\t\t\t\tttrss_entries,ttrss_user_entries\n\t\t\t\t\t\t\t\tWHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'\n\t\t\t\t\t\t\t\t\tAND similarity(title, '{$entry_title}') >= " . _NGRAM_TITLE_DUPLICATE_THRESHOLD . "\n\t\t\t\t\t\t\t\t\tAND owner_uid = {$owner_uid}"); $ngram_similar = db_fetch_result($result, 0, "similar"); if ($debug_enabled) { _debug("update_rss_feed: N-gram similar results: {$ngram_similar}"); } if ($ngram_similar > 0) { $unread = 'false'; } } $result = db_query($link, "INSERT INTO ttrss_user_entries\n\t\t\t\t\t\t\t\t(ref_id, owner_uid, feed_id, unread, last_read, marked,\n\t\t\t\t\t\t\t\t\tpublished, score, tag_cache, label_cache, uuid)\n\t\t\t\t\t\t\tVALUES ('{$ref_id}', '{$owner_uid}', '{$feed}', {$unread},\n\t\t\t\t\t\t\t\t{$last_read_qpart}, {$marked}, {$published}, '{$score}', '', '', '')"); if (PUBSUBHUBBUB_HUB && $published == 'true') { $rss_link = get_self_url_prefix() . "/public.php?op=rss&id=-2&key=" . get_feed_access_key($link, -2, false, $owner_uid); $p = new Publisher(PUBSUBHUBBUB_HUB); $pubsub_result = $p->publish_update($rss_link); } $result = db_query($link, "SELECT int_id FROM ttrss_user_entries WHERE\n\t\t\t\t\t\t\t\tref_id = '{$ref_id}' AND owner_uid = '{$owner_uid}' AND\n\t\t\t\t\t\t\t\tfeed_id = '{$feed}' LIMIT 1"); if (db_num_rows($result) == 1) { $entry_int_id = db_fetch_result($result, 0, "int_id"); } } else { if ($debug_enabled) { _debug("update_rss_feed: user record FOUND"); } $entry_ref_id = db_fetch_result($result, 0, "ref_id"); $entry_int_id = db_fetch_result($result, 0, "int_id"); } if ($debug_enabled) { _debug("update_rss_feed: RID: {$entry_ref_id}, IID: {$entry_int_id}"); } $post_needs_update = false; $update_insignificant = false; if ($orig_num_comments != $num_comments) { $post_needs_update = true; $update_insignificant = true; } if ($entry_plugin_data != $orig_plugin_data) { $post_needs_update = true; $update_insignificant = true; } if ($content_hash != $orig_content_hash) { $post_needs_update = true; $update_insignificant = false; } if (db_escape_string($orig_title) != $entry_title) { $post_needs_update = true; $update_insignificant = false; } // if post needs update, update it and mark all user entries // linking to this post as updated if ($post_needs_update) { if (defined('DAEMON_EXTENDED_DEBUG')) { _debug("update_rss_feed: post {$entry_guid} needs update..."); } // print "<!-- post $orig_title needs update : $post_needs_update -->"; db_query($link, "UPDATE ttrss_entries\n\t\t\t\t\t\t\tSET title = '{$entry_title}', content = '{$entry_content}',\n\t\t\t\t\t\t\t\tcontent_hash = '{$content_hash}',\n\t\t\t\t\t\t\t\tupdated = '{$entry_timestamp_fmt}',\n\t\t\t\t\t\t\t\tnum_comments = '{$num_comments}',\n\t\t\t\t\t\t\t\tplugin_data = '{$entry_plugin_data}'\n\t\t\t\t\t\t\tWHERE id = '{$ref_id}'"); if (!$update_insignificant) { if ($mark_unread_on_update) { db_query($link, "UPDATE ttrss_user_entries\n\t\t\t\t\t\t\t\t\tSET last_read = null, unread = true WHERE ref_id = '{$ref_id}'"); } } } } db_query($link, "COMMIT"); if ($debug_enabled) { _debug("update_rss_feed: assigning labels..."); } assign_article_to_label_filters($link, $entry_ref_id, $article_filters, $owner_uid, $article_labels); if ($debug_enabled) { _debug("update_rss_feed: looking for enclosures..."); } // enclosures $enclosures = array(); $encs = $item->get_enclosures(); if (is_array($encs)) { foreach ($encs as $e) { $e_item = array($e->link, $e->type, $e->length); array_push($enclosures, $e_item); } } if ($debug_enabled) { _debug("update_rss_feed: article enclosures:"); print_r($enclosures); } db_query($link, "BEGIN"); foreach ($enclosures as $enc) { $enc_url = db_escape_string($enc[0]); $enc_type = db_escape_string($enc[1]); $enc_dur = db_escape_string($enc[2]); $result = db_query($link, "SELECT id FROM ttrss_enclosures\n\t\t\t\t\t\tWHERE content_url = '{$enc_url}' AND post_id = '{$entry_ref_id}'"); if (db_num_rows($result) == 0) { db_query($link, "INSERT INTO ttrss_enclosures\n\t\t\t\t\t\t\t(content_url, content_type, title, duration, post_id) VALUES\n\t\t\t\t\t\t\t('{$enc_url}', '{$enc_type}', '', '{$enc_dur}', '{$entry_ref_id}')"); } } db_query($link, "COMMIT"); // check for manual tags (we have to do it here since they're loaded from filters) foreach ($article_filters as $f) { if ($f["type"] == "tag") { $manual_tags = trim_array(explode(",", $f["param"])); foreach ($manual_tags as $tag) { if (tag_is_valid($tag)) { array_push($entry_tags, $tag); } } } } // Skip boring tags $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link, 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8'))); $filtered_tags = array(); $tags_to_cache = array(); if ($entry_tags && is_array($entry_tags)) { foreach ($entry_tags as $tag) { if (array_search($tag, $boring_tags) === false) { array_push($filtered_tags, $tag); } } } $filtered_tags = array_unique($filtered_tags); if ($debug_enabled) { _debug("update_rss_feed: filtered article tags:"); print_r($filtered_tags); } // Save article tags in the database if (count($filtered_tags) > 0) { db_query($link, "BEGIN"); foreach ($filtered_tags as $tag) { $tag = sanitize_tag($tag); $tag = db_escape_string($tag); if (!tag_is_valid($tag)) { continue; } $result = db_query($link, "SELECT id FROM ttrss_tags\n\t\t\t\t\t\t\tWHERE tag_name = '{$tag}' AND post_int_id = '{$entry_int_id}' AND\n\t\t\t\t\t\t\towner_uid = '{$owner_uid}' LIMIT 1"); if ($result && db_num_rows($result) == 0) { db_query($link, "INSERT INTO ttrss_tags\n\t\t\t\t\t\t\t\t\t(owner_uid,tag_name,post_int_id)\n\t\t\t\t\t\t\t\t\tVALUES ('{$owner_uid}','{$tag}', '{$entry_int_id}')"); } array_push($tags_to_cache, $tag); } /* update the cache */ $tags_to_cache = array_unique($tags_to_cache); $tags_str = db_escape_string(join(",", $tags_to_cache)); db_query($link, "UPDATE ttrss_user_entries\n\t\t\t\t\t\tSET tag_cache = '{$tags_str}' WHERE ref_id = '{$entry_ref_id}'\n\t\t\t\t\t\tAND owner_uid = {$owner_uid}"); db_query($link, "COMMIT"); } if (get_pref($link, "AUTO_ASSIGN_LABELS", $owner_uid, false)) { if ($debug_enabled) { _debug("update_rss_feed: auto-assigning labels..."); } foreach ($labels as $label) { $caption = $label["caption"]; if (preg_match("/\\b{$caption}\\b/i", "{$tags_str} " . strip_tags($entry_content) . " {$entry_title}")) { if (!labels_contains_caption($article_labels, $caption)) { label_add_article($link, $entry_ref_id, $caption, $owner_uid); } } } } if ($debug_enabled) { _debug("update_rss_feed: article processed"); } } if (!$last_updated) { if ($debug_enabled) { _debug("update_rss_feed: new feed, catching it up..."); } catchup_feed($link, $feed, false, $owner_uid); } if ($debug_enabled) { _debug("purging feed..."); } purge_feed($link, $feed, 0, $debug_enabled); db_query($link, "UPDATE ttrss_feeds\n\t\t\t\tSET last_updated = NOW(), last_error = '' WHERE id = '{$feed}'"); // db_query($link, "COMMIT"); } else { $error_msg = db_escape_string(mb_substr($rss->error(), 0, 245)); if ($debug_enabled) { _debug("update_rss_feed: error fetching feed: {$error_msg}"); } db_query($link, "UPDATE ttrss_feeds SET last_error = '{$error_msg}',\n\t\t\t\t\tlast_updated = NOW() WHERE id = '{$feed}'"); } unset($rss); if ($debug_enabled) { _debug("update_rss_feed: done"); } }