]> git.wh0rd.org Git - tt-rss.git/blob - backend.php
backend/viewfeed: use JSON
[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         if (ENABLE_TRANSLATIONS == true) {
28                 startup_gettext();
29         }
30
31         $script_started = getmicrotime();
32
33         $link = db_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
34
35         if (!$link) {
36                 if (DB_TYPE == "mysql") {
37                         print mysql_error();
38                 }
39                 // PG seems to display its own errors just fine by default.
40                 return;
41         }
42
43         init_connection($link);
44
45         $op = $_REQUEST["op"];
46         $subop = $_REQUEST["subop"];
47         $mode = $_REQUEST["mode"];
48
49         $print_exec_time = false;
50
51         if ((!$op || $op == "rpc" || $op == "rss" ||
52                         $op == "digestSend" || $op == "dlg" ||
53                         $op == "globalUpdateFeeds") && !$_REQUEST["noxml"]) {
54                                 header("Content-Type: application/xml; charset=utf-8");
55
56                 } else {
57                 if (!$_REQUEST["noxml"]) {
58                         header("Content-Type: text/html; charset=utf-8");
59                 } else {
60                         header("Content-Type: text/plain; charset=utf-8");
61                 }
62         }
63
64         if (ENABLE_GZIP_OUTPUT) {
65                 ob_start("ob_gzhandler");
66         }
67
68         if (SINGLE_USER_MODE) {
69                 authenticate_user($link, "admin", null);
70         }
71
72         /* if (!($_SESSION["uid"] && validate_session($link)) && $op != "globalUpdateFeeds"
73                 && $op != "rss" && $op != "getUnread" && $op != "publish" && $op != "getProfiles") {
74
75                 if ($op == "rpc" || $op == "viewfeed" || $op == "view") {
76                         print_error_xml(6); exit;
77                 } else {
78                         header("Location: tt-rss.php?return=" .
79                                 urlencode($_SERVER['REQUEST_URI']));
80                 }
81                 exit;
82         } */
83
84         if (!($_SESSION["uid"] && validate_session($link)) && $op != "globalUpdateFeeds" &&
85                                 $op != "rss" && $op != "getUnread" && $op != "getProfiles") {
86
87                 header("Content-Type: text/plain");
88                 print json_encode(array("error" => array("code" => 6)));
89                 return;
90         }
91
92         $purge_intervals = array(
93                 0  => __("Use default"),
94                 -1 => __("Never purge"),
95                 5  => __("1 week old"),
96                 14 => __("2 weeks old"),
97                 31 => __("1 month old"),
98                 60 => __("2 months old"),
99                 90 => __("3 months old"));
100
101         $update_intervals = array(
102                 0   => __("Default interval"),
103                 -1  => __("Disable updates"),
104                 15  => __("Each 15 minutes"),
105                 30  => __("Each 30 minutes"),
106                 60  => __("Hourly"),
107                 240 => __("Each 4 hours"),
108                 720 => __("Each 12 hours"),
109                 1440 => __("Daily"),
110                 10080 => __("Weekly"));
111
112         $update_intervals_nodefault = array(
113                 -1  => __("Disable updates"),
114                 15  => __("Each 15 minutes"),
115                 30  => __("Each 30 minutes"),
116                 60  => __("Hourly"),
117                 240 => __("Each 4 hours"),
118                 720 => __("Each 12 hours"),
119                 1440 => __("Daily"),
120                 10080 => __("Weekly"));
121
122         $update_methods = array(
123                 0   => __("Default"),
124                 1   => __("Magpie"),
125                 2   => __("SimplePie"),
126                 3   => __("Twitter OAuth"));
127
128         if (DEFAULT_UPDATE_METHOD == "1") {
129                 $update_methods[0] .= ' (SimplePie)';
130         } else {
131                 $update_methods[0] .= ' (Magpie)';
132         }
133
134         $access_level_names = array(
135                 0 => __("User"),
136                 5 => __("Power User"),
137                 10 => __("Administrator"));
138
139         require_once "modules/pref-prefs.php";
140         require_once "modules/popup-dialog.php";
141         require_once "modules/help.php";
142         require_once "modules/pref-feeds.php";
143         require_once "modules/pref-filters.php";
144         require_once "modules/pref-labels.php";
145         require_once "modules/pref-users.php";
146
147         if (!sanity_check($link)) { return; }
148
149         switch($op) { // Select action according to $op value.
150                 case "rpc":
151                         // Handle remote procedure calls.
152                         handle_rpc_request($link);
153                 break; // rpc
154
155                 case "feeds":
156                         $subop = $_REQUEST["subop"];
157                         $root = (bool)$_REQUEST["root"];
158
159                         switch($subop) {
160                                 case "catchupAll":
161                                         db_query($link, "UPDATE ttrss_user_entries SET
162                                                 last_read = NOW(),unread = false WHERE owner_uid = " . $_SESSION["uid"]);
163                                         ccache_zero_all($link, $_SESSION["uid"]);
164
165                                 break;
166
167                                 case "collapse":
168                                         $cat_id = db_escape_string($_REQUEST["cid"]);
169                                         $mode = (int) db_escape_string($_REQUEST['mode']);
170                                         toggle_collapse_cat($link, $cat_id, $mode);
171                                         return;
172                                 break;
173                         }
174
175                         if (!$root) {
176                                 print json_encode(outputFeedList($link));
177                         } else {
178
179                                 $feeds = outputFeedList($link, false);
180
181                                 $root = array();
182                                 $root['id'] = 'root';
183                                 $root['name'] = __('Feeds');
184                                 $root['items'] = $feeds['items'];
185
186                                 $fl = array();
187                                 $fl['identifier'] = 'id';
188                                 $fl['label'] = 'name';
189                                 $fl['items'] = array($root);
190
191                                 print json_encode($fl);
192                         }
193
194                 break; // feeds
195
196                 case "la":
197                         $id = db_escape_string($_REQUEST['id']);
198
199                         $result = db_query($link, "SELECT link FROM ttrss_entries, ttrss_user_entries
200                                 WHERE id = '$id' AND id = ref_id AND owner_uid = '".$_SESSION['uid']."'");
201
202                         if (db_num_rows($result) == 1) {
203                                 $article_url = db_fetch_result($result, 0, 'link');
204                                 $article_url = str_replace("\n", "", $article_url);
205
206                                 header("Location: $article_url");
207                                 return;
208
209                         } else {
210                                 print_error(__("Article not found."));
211                         }
212                 break;
213
214                 case "view":
215
216                         $id = db_escape_string($_REQUEST["id"]);
217                         $cids = split(",", db_escape_string($_REQUEST["cids"]));
218                         $mode = db_escape_string($_REQUEST["mode"]);
219                         $omode = db_escape_string($_REQUEST["omode"]);
220
221                         // in prefetch mode we only output requested cids, main article
222                         // just gets marked as read (it already exists in client cache)
223
224                         $articles = array();
225
226                         if ($mode == "") {
227                                 array_push($articles, format_article($link, $id, false));
228                         } else if ($mode == "zoom") {
229                                 array_push($articles, format_article($link, $id, false, true, true));
230                         } else {
231                                 catchupArticleById($link, $id, 0);
232                         }
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 = -10-$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) {
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                         $reply['headlines']['content'] = $ret[5];
365                         $reply['headlines']['toolbar'] = $ret[6];
366
367                         if ($_REQUEST["debug"]) $timing_info = print_checkpoint("05", $timing_info);
368
369                         $headlines_unread = ccache_find($link, $returned_feed, $_SESSION["uid"],
370                                         $cat_view, true);
371
372                         if ($headlines_unread == -1) {
373                                 $headlines_unread = getFeedUnread($link, $returned_feed, $cat_view);
374                         }
375
376                         $reply['headlines-info'] = array("count" => (int) $headlines_count,
377                                 "vgroup_last_feed" => $vgroup_last_feed,
378                                 "unread" => (int) $headlines_unread,
379                                 "disable_cache" => (bool) $disable_cache);
380
381                         if ($_REQUEST["debug"]) $timing_info = print_checkpoint("20", $timing_info);
382
383                         if (is_array($topmost_article_ids) && !get_pref($link, 'COMBINED_DISPLAY_MODE') && !$_SESSION["bw_limit"]) {
384                                 $articles = array();
385
386                                 foreach ($topmost_article_ids as $id) {
387                                         array_push($articles, format_article($link, $id, $feed, false));
388                                 }
389
390                                 $reply['articles'] = $articles;
391                         }
392
393                         if ($subop) {
394                                 $reply['counters'] = getAllCounters($link, $omode, $feed);
395                         }
396
397                         if ($_REQUEST["debug"]) $timing_info = print_checkpoint("30", $timing_info);
398
399                         $reply['runtime-info'] = make_runtime_info($link);
400
401                         print json_encode($reply);
402
403                 break; // viewfeed
404
405                 case "pref-feeds":
406                         module_pref_feeds($link);
407                 break; // pref-feeds
408
409                 case "pref-filters":
410                         module_pref_filters($link);
411                 break; // pref-filters
412
413                 case "pref-labels":
414                         module_pref_labels($link);
415                 break; // pref-labels
416
417                 case "pref-prefs":
418                         module_pref_prefs($link);
419                 break; // pref-prefs
420
421                 case "pref-users":
422                         module_pref_users($link);
423                 break; // prefs-users
424
425                 case "help":
426                         module_help($link);
427                 break; // help
428
429                 case "dlg":
430                         module_popup_dialog($link);
431                 break; // dlg
432
433                 case "pref-pub-items":
434                         module_pref_pub_items($link);
435                 break; // pref-pub-items
436
437                 case "globalUpdateFeeds":
438                         // update feeds of all users, may be used anonymously
439
440                         print "<!--";
441                         // Update all feeds needing a update.
442                         update_daemon_common($link, 0, true, true);
443                         print " -->";
444
445                         print "<rpc-reply>
446                                 <message msg=\"All feeds updated\"/>
447                         </rpc-reply>";
448                 break; // globalUpdateFeeds
449
450                 case "pref-feed-browser":
451                         module_pref_feed_browser($link);
452                 break; // pref-feed-browser
453
454                 case "rss":
455                         $feed = db_escape_string($_REQUEST["id"]);
456                         $key = db_escape_string($_REQUEST["key"]);
457                         $is_cat = $_REQUEST["is_cat"] != false;
458                         $limit = (int)db_escape_string($_REQUEST["limit"]);
459
460                         $search = db_escape_string($_REQUEST["q"]);
461                         $match_on = db_escape_string($_REQUEST["m"]);
462                         $search_mode = db_escape_string($_REQUEST["smode"]);
463                         $view_mode = db_escape_string($_REQUEST["view-mode"]);
464
465                         if (SINGLE_USER_MODE) {
466                                 authenticate_user($link, "admin", null);
467                         }
468
469                         $owner_id = false;
470
471                         if ($key) {
472                                 $result = db_query($link, "SELECT owner_uid FROM
473                                         ttrss_access_keys WHERE access_key = '$key' AND feed_id = '$feed'");
474
475                                 if (db_num_rows($result) == 1)
476                                         $owner_id = db_fetch_result($result, 0, "owner_uid");
477                         }
478
479                         if ($owner_id) {
480                                 $_SESSION['uid'] = $owner_id;
481
482                                 generate_syndicated_feed($link, 0, $feed, $is_cat, $limit,
483                                         $search, $search_mode, $match_on, $view_mode);
484                         } else {
485                                 header('HTTP/1.1 403 Forbidden');
486                         }
487                 break; // rss
488
489                 case "getUnread":
490                         $login = db_escape_string($_REQUEST["login"]);
491                         $fresh = $_REQUEST["fresh"] == "1";
492
493                         header("Content-Type: text/plain; charset=utf-8");
494
495                         $result = db_query($link, "SELECT id FROM ttrss_users WHERE login = '$login'");
496
497                         if (db_num_rows($result) == 1) {
498                                 $uid = db_fetch_result($result, 0, "id");
499
500                                 print getGlobalUnread($link, $uid);
501
502                                 if ($fresh) {
503                                         print ";";
504                                         print getFeedArticles($link, -3, false, true, $uid);
505                                 }
506
507                         } else {
508                                 print "-1;User not found";
509                         }
510
511                         $print_exec_time = false;
512                 break; // getUnread
513
514                 case "digestTest":
515                         header("Content-Type: text/plain");
516                         print_r(prepare_headlines_digest($link, $_SESSION["uid"]));
517                         $print_exec_time = false;
518                 break; // digestTest
519
520                 case "digestSend":
521                         header("Content-Type: text/plain");
522                         send_headlines_digests($link);
523                         $print_exec_time = false;
524                 break; // digestSend
525
526                 case "loading":
527                         print __("Loading, please wait...") . " " .
528                                 "<img src='images/indicator_tiny.gif'>";
529
530                 case "getProfiles":
531                         $login = db_escape_string($_REQUEST["login"]);
532                         $password = db_escape_string($_REQUEST["password"]);
533
534                         if (authenticate_user($link, $login, $password)) {
535                                 $result = db_query($link, "SELECT * FROM ttrss_settings_profiles
536                                         WHERE owner_uid = " . $_SESSION["uid"] . " ORDER BY title");
537
538                                 print "<select style='width: 100%' name='profile'>";
539
540                                 print "<option value='0'>" . __("Default profile") . "</option>";
541
542                                 while ($line = db_fetch_assoc($result)) {
543                                         $id = $line["id"];
544                                         $title = $line["title"];
545
546                                         print "<option value='$id'>$title</option>";
547                                 }
548
549                                 print "</select>";
550
551                                 $_SESSION = array();
552                         }
553                 break;
554
555         } // Select action according to $op value.
556
557
558         // We close the connection to database.
559         db_close($link);
560 ?>
561
562 <?php if ($print_exec_time) { ?>
563 <!-- <?php echo sprintf("Backend execution time: %.4f seconds", getmicrotime() - $script_started) ?> -->
564 <?php } ?>