]> git.wh0rd.org - tt-rss.git/blob - backend.php
do not perform synchronous update on pubsub call
[tt-rss.git] / backend.php
1 <?php
2 /* remove ill effects of magic quotes */
3
4 if (get_magic_quotes_gpc()) {
5 function stripslashes_deep($value) {
6 $value = is_array($value) ?
7 array_map('stripslashes_deep', $value) : stripslashes($value);
8 return $value;
9 }
10
11 $_POST = array_map('stripslashes_deep', $_POST);
12 $_GET = array_map('stripslashes_deep', $_GET);
13 $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
14 $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
15 }
16
17 require_once "functions.php";
18 require_once "sessions.php";
19 require_once "modules/backend-rpc.php";
20 require_once "sanity_check.php";
21 require_once "config.php";
22 require_once "db.php";
23 require_once "db-prefs.php";
24
25 no_cache_incantation();
26
27 startup_gettext();
28
29 $script_started = getmicrotime();
30
31 $link = db_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
32
33 if (!$link) {
34 if (DB_TYPE == "mysql") {
35 print mysql_error();
36 }
37 // PG seems to display its own errors just fine by default.
38 return;
39 }
40
41 init_connection($link);
42
43 $op = $_REQUEST["op"];
44 $subop = $_REQUEST["subop"];
45 $mode = $_REQUEST["mode"];
46
47 if ((!$op || $op == "rss" || $op == "dlg") && !$_REQUEST["noxml"]) {
48 header("Content-Type: application/xml; charset=utf-8");
49 } else {
50 header("Content-Type: text/plain; charset=utf-8");
51 }
52
53 if (ENABLE_GZIP_OUTPUT) {
54 ob_start("ob_gzhandler");
55 }
56
57 if (SINGLE_USER_MODE) {
58 authenticate_user($link, "admin", null);
59 }
60
61 if (!($_SESSION["uid"] && validate_session($link)) && $op != "globalUpdateFeeds" &&
62 $op != "rss" && $op != "getUnread" && $op != "getProfiles" &&
63 $op != "fbexport" && $op != "logout" && $op != "pubsub") {
64
65 if ($op == 'pref-feeds' && $_REQUEST['subop'] == 'add') {
66 header("Content-Type: text/html");
67 login_sequence($link);
68 render_login_form($link);
69 } else {
70 header("Content-Type: text/plain");
71 print json_encode(array("error" => array("code" => 6)));
72 }
73 return;
74 }
75
76 $purge_intervals = array(
77 0 => __("Use default"),
78 -1 => __("Never purge"),
79 5 => __("1 week old"),
80 14 => __("2 weeks old"),
81 31 => __("1 month old"),
82 60 => __("2 months old"),
83 90 => __("3 months old"));
84
85 $update_intervals = array(
86 0 => __("Default interval"),
87 -1 => __("Disable updates"),
88 15 => __("Each 15 minutes"),
89 30 => __("Each 30 minutes"),
90 60 => __("Hourly"),
91 240 => __("Each 4 hours"),
92 720 => __("Each 12 hours"),
93 1440 => __("Daily"),
94 10080 => __("Weekly"));
95
96 $update_intervals_nodefault = array(
97 -1 => __("Disable updates"),
98 15 => __("Each 15 minutes"),
99 30 => __("Each 30 minutes"),
100 60 => __("Hourly"),
101 240 => __("Each 4 hours"),
102 720 => __("Each 12 hours"),
103 1440 => __("Daily"),
104 10080 => __("Weekly"));
105
106 $update_methods = array(
107 0 => __("Default"),
108 1 => __("Magpie"),
109 2 => __("SimplePie"),
110 3 => __("Twitter OAuth"));
111
112 if (DEFAULT_UPDATE_METHOD == "1") {
113 $update_methods[0] .= ' (SimplePie)';
114 } else {
115 $update_methods[0] .= ' (Magpie)';
116 }
117
118 $access_level_names = array(
119 0 => __("User"),
120 5 => __("Power User"),
121 10 => __("Administrator"));
122
123 require_once "modules/pref-prefs.php";
124 require_once "modules/popup-dialog.php";
125 require_once "modules/help.php";
126 require_once "modules/pref-feeds.php";
127 require_once "modules/pref-filters.php";
128 require_once "modules/pref-labels.php";
129 require_once "modules/pref-users.php";
130 require_once "modules/pref-instances.php";
131
132 $error = sanity_check($link);
133
134 if ($error['code'] != 0 && $op != "logout") {
135 print json_encode(array("error" => $error));
136 return;
137 }
138
139 switch($op) { // Select action according to $op value.
140 case "rpc":
141 // Handle remote procedure calls.
142 handle_rpc_request($link);
143 break; // rpc
144
145 case "feeds":
146 $subop = $_REQUEST["subop"];
147 $root = (bool)$_REQUEST["root"];
148
149 switch($subop) {
150 case "catchupAll":
151 db_query($link, "UPDATE ttrss_user_entries SET
152 last_read = NOW(),unread = false WHERE owner_uid = " . $_SESSION["uid"]);
153 ccache_zero_all($link, $_SESSION["uid"]);
154
155 break;
156
157 case "collapse":
158 $cat_id = db_escape_string($_REQUEST["cid"]);
159 $mode = (int) db_escape_string($_REQUEST['mode']);
160 toggle_collapse_cat($link, $cat_id, $mode);
161 return;
162 break;
163 }
164
165 if (!$root) {
166 print json_encode(outputFeedList($link));
167 } else {
168
169 $feeds = outputFeedList($link, false);
170
171 $root = array();
172 $root['id'] = 'root';
173 $root['name'] = __('Feeds');
174 $root['items'] = $feeds['items'];
175
176 $fl = array();
177 $fl['identifier'] = 'id';
178 $fl['label'] = 'name';
179 $fl['items'] = array($root);
180
181 print json_encode($fl);
182 }
183
184 break; // feeds
185
186 case "la":
187 $id = db_escape_string($_REQUEST['id']);
188
189 $result = db_query($link, "SELECT link FROM ttrss_entries, ttrss_user_entries
190 WHERE id = '$id' AND id = ref_id AND owner_uid = '".$_SESSION['uid']."'
191 LIMIT 1");
192
193 if (db_num_rows($result) == 1) {
194 $article_url = db_fetch_result($result, 0, 'link');
195 $article_url = str_replace("\n", "", $article_url);
196
197 header("Location: $article_url");
198 return;
199
200 } else {
201 print_error(__("Article not found."));
202 }
203 break;
204
205 case "view":
206
207 $id = db_escape_string($_REQUEST["id"]);
208 $cids = explode(",", db_escape_string($_REQUEST["cids"]));
209 $mode = db_escape_string($_REQUEST["mode"]);
210 $omode = db_escape_string($_REQUEST["omode"]);
211
212 // in prefetch mode we only output requested cids, main article
213 // just gets marked as read (it already exists in client cache)
214
215 $articles = array();
216
217 if ($mode == "") {
218 array_push($articles, format_article($link, $id, false));
219 } else if ($mode == "zoom") {
220 array_push($articles, format_article($link, $id, true, true));
221 } else if ($mode == "raw") {
222 if ($_REQUEST['html']) {
223 header("Content-Type: text/html");
224 print '<link rel="stylesheet" type="text/css" href="tt-rss.css"/>';
225 }
226
227 $article = format_article($link, $id, false);
228 print $article['content'];
229 return;
230 }
231
232 catchupArticleById($link, $id, 0);
233
234 if (!$_SESSION["bw_limit"]) {
235 foreach ($cids as $cid) {
236 if ($cid) {
237 array_push($articles, format_article($link, $cid, false, false));
238 }
239 }
240 }
241
242 print json_encode($articles);
243
244 break; // view
245
246 case "viewfeed":
247
248 $timing_info = getmicrotime();
249
250 $reply = array();
251
252 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("0", $timing_info);
253
254 $omode = db_escape_string($_REQUEST["omode"]);
255
256 $feed = db_escape_string($_REQUEST["feed"]);
257 $subop = db_escape_string($_REQUEST["subop"]);
258 $view_mode = db_escape_string($_REQUEST["view_mode"]);
259 $limit = (int) get_pref($link, "DEFAULT_ARTICLE_LIMIT");
260 @$cat_view = db_escape_string($_REQUEST["cat"]);
261 @$next_unread_feed = db_escape_string($_REQUEST["nuf"]);
262 @$offset = db_escape_string($_REQUEST["skip"]);
263 @$vgroup_last_feed = db_escape_string($_REQUEST["vgrlf"]);
264 $order_by = db_escape_string($_REQUEST["order_by"]);
265
266 /* Feed -5 is a special case: it is used to display auxiliary information
267 * when there's nothing to load - e.g. no stuff in fresh feed */
268
269 if ($feed == -5) {
270 print json_encode(generate_dashboard_feed($link));
271 return;
272 }
273
274 $result = false;
275
276 if ($feed < -10) {
277 $label_feed = -11-$feed;
278 $result = db_query($link, "SELECT id FROM ttrss_labels2 WHERE
279 id = '$label_feed' AND owner_uid = " . $_SESSION['uid']);
280 } else if (!$cat_view && $feed > 0) {
281 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE
282 id = '$feed' AND owner_uid = " . $_SESSION['uid']);
283 } else if ($cat_view && $feed > 0) {
284 $result = db_query($link, "SELECT id FROM ttrss_feed_categories WHERE
285 id = '$feed' AND owner_uid = " . $_SESSION['uid']);
286 }
287
288 if ($result && db_num_rows($result) == 0) {
289 print json_encode(generate_error_feed($link, __("Feed not found.")));
290 return;
291 }
292
293 /* Updating a label ccache means recalculating all of the caches
294 * so for performance reasons we don't do that here */
295
296 if ($feed >= 0) {
297 ccache_update($link, $feed, $_SESSION["uid"], $cat_view);
298 }
299
300 set_pref($link, "_DEFAULT_VIEW_MODE", $view_mode);
301 set_pref($link, "_DEFAULT_VIEW_LIMIT", $limit);
302 set_pref($link, "_DEFAULT_VIEW_ORDER_BY", $order_by);
303
304 if (!$cat_view && preg_match("/^[0-9][0-9]*$/", $feed)) {
305 db_query($link, "UPDATE ttrss_feeds SET last_viewed = NOW()
306 WHERE id = '$feed' AND owner_uid = ".$_SESSION["uid"]);
307 }
308
309 $reply['headlines'] = array();
310
311 if (!$next_unread_feed)
312 $reply['headlines']['id'] = $feed;
313 else
314 $reply['headlines']['id'] = $next_unread_feed;
315
316 $reply['headlines']['is_cat'] = (bool) $cat_view;
317
318 $override_order = false;
319
320 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
321 $date_sort_field = "updated";
322 } else {
323 $date_sort_field = "date_entered";
324 }
325
326 switch ($order_by) {
327 case "date":
328 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
329 $override_order = "$date_sort_field";
330 } else {
331 $override_order = "$date_sort_field DESC";
332 }
333 break;
334
335 case "title":
336 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
337 $override_order = "title DESC, $date_sort_field";
338 } else {
339 $override_order = "title, $date_sort_field DESC";
340 }
341 break;
342
343 case "score":
344 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
345 $override_order = "score, $date_sort_field";
346 } else {
347 $override_order = "score DESC, $date_sort_field DESC";
348 }
349 break;
350 }
351
352 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("04", $timing_info);
353
354 $ret = format_headlines_list($link, $feed, $subop,
355 $view_mode, $limit, $cat_view, $next_unread_feed, $offset,
356 $vgroup_last_feed, $override_order);
357
358 $topmost_article_ids = $ret[0];
359 $headlines_count = $ret[1];
360 $returned_feed = $ret[2];
361 $disable_cache = $ret[3];
362 $vgroup_last_feed = $ret[4];
363
364 // if ($_REQUEST["debug"]) print_r($ret);
365
366 $reply['headlines']['content'] =& $ret[5]['content'];
367 $reply['headlines']['toolbar'] =& $ret[5]['toolbar'];
368
369 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("05", $timing_info);
370
371 $headlines_unread = ccache_find($link, $returned_feed, $_SESSION["uid"],
372 $cat_view, true);
373
374 if ($headlines_unread == -1) {
375 $headlines_unread = getFeedUnread($link, $returned_feed, $cat_view);
376 }
377
378 $reply['headlines-info'] = array("count" => (int) $headlines_count,
379 "vgroup_last_feed" => $vgroup_last_feed,
380 "unread" => (int) $headlines_unread,
381 "disable_cache" => (bool) $disable_cache);
382
383 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("20", $timing_info);
384
385 if (is_array($topmost_article_ids) && !get_pref($link, 'COMBINED_DISPLAY_MODE') && !$_SESSION["bw_limit"]) {
386 $articles = array();
387
388 foreach ($topmost_article_ids as $id) {
389 array_push($articles, format_article($link, $id, false));
390 }
391
392 $reply['articles'] = $articles;
393 }
394
395 if ($subop) {
396 $reply['counters'] = getAllCounters($link, $omode, $feed);
397 }
398
399 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("30", $timing_info);
400
401 $reply['runtime-info'] = make_runtime_info($link);
402
403 print json_encode($reply);
404
405 break; // viewfeed
406
407 case "pref-feeds":
408 module_pref_feeds($link);
409 break; // pref-feeds
410
411 case "pref-filters":
412 module_pref_filters($link);
413 break; // pref-filters
414
415 case "pref-labels":
416 module_pref_labels($link);
417 break; // pref-labels
418
419 case "pref-prefs":
420 module_pref_prefs($link);
421 break; // pref-prefs
422
423 case "pref-users":
424 module_pref_users($link);
425 break; // prefs-users
426
427 case "help":
428 module_help($link);
429 break; // help
430
431 case "dlg":
432 module_popup_dialog($link);
433 break; // dlg
434
435 case "pref-pub-items":
436 module_pref_pub_items($link);
437 break; // pref-pub-items
438
439 case "globalUpdateFeeds":
440 // Update all feeds needing a update.
441 update_daemon_common($link, 0, true, true);
442 break; // globalUpdateFeeds
443
444 case "pref-feed-browser":
445 module_pref_feed_browser($link);
446 break; // pref-feed-browser
447
448 case "pref-instances":
449 module_pref_instances($link);
450 break; // pref-instances
451
452 case "rss":
453 $feed = db_escape_string($_REQUEST["id"]);
454 $key = db_escape_string($_REQUEST["key"]);
455 $is_cat = $_REQUEST["is_cat"] != false;
456 $limit = (int)db_escape_string($_REQUEST["limit"]);
457
458 $search = db_escape_string($_REQUEST["q"]);
459 $match_on = db_escape_string($_REQUEST["m"]);
460 $search_mode = db_escape_string($_REQUEST["smode"]);
461 $view_mode = db_escape_string($_REQUEST["view-mode"]);
462
463 if (SINGLE_USER_MODE) {
464 authenticate_user($link, "admin", null);
465 }
466
467 $owner_id = false;
468
469 if ($key) {
470 $result = db_query($link, "SELECT owner_uid FROM
471 ttrss_access_keys WHERE access_key = '$key' AND feed_id = '$feed'");
472
473 if (db_num_rows($result) == 1)
474 $owner_id = db_fetch_result($result, 0, "owner_uid");
475 }
476
477 if ($owner_id) {
478 $_SESSION['uid'] = $owner_id;
479
480 generate_syndicated_feed($link, 0, $feed, $is_cat, $limit,
481 $search, $search_mode, $match_on, $view_mode);
482 } else {
483 header('HTTP/1.1 403 Forbidden');
484 }
485 break; // rss
486
487 case "getUnread":
488 $login = db_escape_string($_REQUEST["login"]);
489 $fresh = $_REQUEST["fresh"] == "1";
490
491 $result = db_query($link, "SELECT id FROM ttrss_users WHERE login = '$login'");
492
493 if (db_num_rows($result) == 1) {
494 $uid = db_fetch_result($result, 0, "id");
495
496 print getGlobalUnread($link, $uid);
497
498 if ($fresh) {
499 print ";";
500 print getFeedArticles($link, -3, false, true, $uid);
501 }
502
503 } else {
504 print "-1;User not found";
505 }
506
507 break; // getUnread
508
509 case "digestTest":
510 print_r(prepare_headlines_digest($link, $_SESSION["uid"]));
511 break; // digestTest
512
513 case "digestSend":
514 send_headlines_digests($link);
515 break; // digestSend
516
517 case "loading":
518 header("Content-type: text/html");
519 print __("Loading, please wait...") . " " .
520 "<img src='images/indicator_tiny.gif'>";
521 break; // loading
522
523 case "getProfiles":
524 $login = db_escape_string($_REQUEST["login"]);
525 $password = db_escape_string($_REQUEST["password"]);
526
527 if (authenticate_user($link, $login, $password)) {
528 $result = db_query($link, "SELECT * FROM ttrss_settings_profiles
529 WHERE owner_uid = " . $_SESSION["uid"] . " ORDER BY title");
530
531 print "<select style='width: 100%' name='profile'>";
532
533 print "<option value='0'>" . __("Default profile") . "</option>";
534
535 while ($line = db_fetch_assoc($result)) {
536 $id = $line["id"];
537 $title = $line["title"];
538
539 print "<option value='$id'>$title</option>";
540 }
541
542 print "</select>";
543
544 $_SESSION = array();
545 }
546 break; // getprofiles
547
548 case "pubsub":
549 $mode = db_escape_string($_REQUEST['hub_mode']);
550 $feed_id = db_escape_string($_REQUEST['id']);
551 $feed_url = db_escape_string($_REQUEST['hub_topic']);
552
553 if (!PUBSUBHUBBUB_ENABLED) {
554 header('HTTP/1.0 404 Not Found');
555 echo "404 Not found";
556 return;
557 }
558
559 // TODO: implement hub_verifytoken checking
560
561 $result = db_query($link, "SELECT feed_url FROM ttrss_feeds
562 WHERE id = '$feed_id'");
563
564 if (db_num_rows($result) != 0) {
565
566 $check_feed_url = db_fetch_result($result, 0, "feed_url");
567
568 if ($check_feed_url && ($check_feed_url == $feed_url || !$feed_url)) {
569 if ($mode == "subscribe") {
570
571 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 2
572 WHERE id = '$feed_id'");
573
574 print $_REQUEST['hub_challenge'];
575 return;
576
577 } else if ($mode == "unsubscribe") {
578
579 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 0
580 WHERE id = '$feed_id'");
581
582 print $_REQUEST['hub_challenge'];
583 return;
584
585 } else if (!$mode) {
586
587 // Received update ping, schedule feed update.
588 //update_rss_feed($link, $feed_id, true, true);
589
590 db_query($link, "UPDATE ttrss_feeds SET
591 last_update_started = '1970-01-01',
592 last_updated = '1970-01-01' WHERE id = '$feed_id' AND
593 owner_uid = ".$_SESSION["uid"]);
594
595 }
596 } else {
597 header('HTTP/1.0 404 Not Found');
598 echo "404 Not found";
599 }
600 } else {
601 header('HTTP/1.0 404 Not Found');
602 echo "404 Not found";
603 }
604
605 break; // pubsub
606
607 case "logout":
608 logout_user();
609 header("Location: tt-rss.php");
610 break; // logout
611
612 case "fbexport":
613
614 $access_key = db_escape_string($_POST["key"]);
615
616 // TODO: rate limit checking using last_connected
617 $result = db_query($link, "SELECT id FROM ttrss_linked_instances
618 WHERE access_key = '$access_key'");
619
620 if (db_num_rows($result) == 1) {
621
622 $instance_id = db_fetch_result($result, 0, "id");
623
624 $result = db_query($link, "SELECT feed_url, site_url, title, subscribers
625 FROM ttrss_feedbrowser_cache ORDER BY subscribers DESC LIMIT 100");
626
627 $feeds = array();
628
629 while ($line = db_fetch_assoc($result)) {
630 array_push($feeds, $line);
631 }
632
633 db_query($link, "UPDATE ttrss_linked_instances SET
634 last_status_in = 1 WHERE id = '$instance_id'");
635
636 print json_encode(array("feeds" => $feeds));
637 } else {
638 print json_encode(array("error" => array("code" => 6)));
639 }
640 break; // fbexport
641
642 default:
643 header("Content-Type: text/plain");
644 print json_encode(array("error" => array("code" => 7)));
645 break; // fallback
646 } // Select action according to $op value.
647
648 // We close the connection to database.
649 db_close($link);
650 ?>