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