PageRenderTime 65ms CodeModel.GetById 17ms RepoModel.GetById 8ms app.codeStats 0ms

/wp-app.php

https://github.com/Mercedes/ratonesytortillas
PHP | 1127 lines | 853 code | 219 blank | 55 comment | 142 complexity | 593b7c0afa0f193a615db60b0b307b6f MD5 | raw file
  1. <?php
  2. /*
  3. * wp-app.php - Atom Publishing Protocol support for WordPress
  4. * Original code by: Elias Torres, http://torrez.us/archives/2006/08/31/491/
  5. * Modified by: Dougal Campbell, http://dougal.gunters.org/
  6. *
  7. * Version: 1.0.5-dc
  8. */
  9. define('APP_REQUEST', true);
  10. require_once('./wp-config.php');
  11. require_once(ABSPATH . WPINC . '/post-template.php');
  12. require_once(ABSPATH . WPINC . '/atomlib.php');
  13. require_once(ABSPATH . WPINC . '/feed.php');
  14. $_SERVER['PATH_INFO'] = preg_replace( '/.*\/wp-app\.php/', '', $_SERVER['REQUEST_URI'] );
  15. $app_logging = 0;
  16. // TODO: Should be an option somewhere
  17. $always_authenticate = 1;
  18. function log_app($label,$msg) {
  19. global $app_logging;
  20. if ($app_logging) {
  21. $fp = fopen( 'wp-app.log', 'a+');
  22. $date = gmdate( 'Y-m-d H:i:s' );
  23. fwrite($fp, "\n\n$date - $label\n$msg\n");
  24. fclose($fp);
  25. }
  26. }
  27. if ( !function_exists('wp_set_current_user') ) :
  28. function wp_set_current_user($id, $name = '') {
  29. global $current_user;
  30. if ( isset($current_user) && ($id == $current_user->ID) )
  31. return $current_user;
  32. $current_user = new WP_User($id, $name);
  33. return $current_user;
  34. }
  35. endif;
  36. function wa_posts_where_include_drafts_filter($where) {
  37. $where = str_replace("post_status = 'publish'","post_status = 'publish' OR post_status = 'future' OR post_status = 'draft' OR post_status = 'inherit'", $where);
  38. return $where;
  39. }
  40. add_filter('posts_where', 'wa_posts_where_include_drafts_filter');
  41. class AtomServer {
  42. var $ATOM_CONTENT_TYPE = 'application/atom+xml';
  43. var $CATEGORIES_CONTENT_TYPE = 'application/atomcat+xml';
  44. var $SERVICE_CONTENT_TYPE = 'application/atomsvc+xml';
  45. var $ATOM_NS = 'http://www.w3.org/2005/Atom';
  46. var $ATOMPUB_NS = 'http://www.w3.org/2007/app';
  47. var $ENTRIES_PATH = "posts";
  48. var $CATEGORIES_PATH = "categories";
  49. var $MEDIA_PATH = "attachments";
  50. var $ENTRY_PATH = "post";
  51. var $SERVICE_PATH = "service";
  52. var $MEDIA_SINGLE_PATH = "attachment";
  53. var $params = array();
  54. var $media_content_types = array('image/*','audio/*','video/*');
  55. var $atom_content_types = array('application/atom+xml');
  56. var $selectors = array();
  57. // support for head
  58. var $do_output = true;
  59. function AtomServer() {
  60. $this->script_name = array_pop(explode('/',$_SERVER['SCRIPT_NAME']));
  61. $this->app_base = get_bloginfo('url') . '/' . $this->script_name . '/';
  62. if ( isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) {
  63. $this->app_base = preg_replace( '/^http:\/\//', 'https://', $this->app_base );
  64. }
  65. $this->selectors = array(
  66. '@/service$@' =>
  67. array('GET' => 'get_service'),
  68. '@/categories$@' =>
  69. array('GET' => 'get_categories_xml'),
  70. '@/post/(\d+)$@' =>
  71. array('GET' => 'get_post',
  72. 'PUT' => 'put_post',
  73. 'DELETE' => 'delete_post'),
  74. '@/posts/?(\d+)?$@' =>
  75. array('GET' => 'get_posts',
  76. 'POST' => 'create_post'),
  77. '@/attachments/?(\d+)?$@' =>
  78. array('GET' => 'get_attachment',
  79. 'POST' => 'create_attachment'),
  80. '@/attachment/file/(\d+)$@' =>
  81. array('GET' => 'get_file',
  82. 'PUT' => 'put_file',
  83. 'DELETE' => 'delete_file'),
  84. '@/attachment/(\d+)$@' =>
  85. array('GET' => 'get_attachment',
  86. 'PUT' => 'put_attachment',
  87. 'DELETE' => 'delete_attachment'),
  88. );
  89. }
  90. function handle_request() {
  91. global $always_authenticate;
  92. $path = $_SERVER['PATH_INFO'];
  93. $method = $_SERVER['REQUEST_METHOD'];
  94. log_app('REQUEST',"$method $path\n================");
  95. $this->process_conditionals();
  96. //$this->process_conditionals();
  97. // exception case for HEAD (treat exactly as GET, but don't output)
  98. if($method == 'HEAD') {
  99. $this->do_output = false;
  100. $method = 'GET';
  101. }
  102. // redirect to /service in case no path is found.
  103. if(strlen($path) == 0 || $path == '/') {
  104. $this->redirect($this->get_service_url());
  105. }
  106. // dispatch
  107. foreach($this->selectors as $regex => $funcs) {
  108. if(preg_match($regex, $path, $matches)) {
  109. if(isset($funcs[$method])) {
  110. // authenticate regardless of the operation and set the current
  111. // user. each handler will decide if auth is required or not.
  112. $this->authenticate();
  113. $u = wp_get_current_user();
  114. if(!isset($u) || $u->ID == 0) {
  115. if ($always_authenticate) {
  116. $this->auth_required('Credentials required.');
  117. }
  118. }
  119. array_shift($matches);
  120. call_user_func_array(array(&$this,$funcs[$method]), $matches);
  121. exit();
  122. } else {
  123. // only allow what we have handlers for...
  124. $this->not_allowed(array_keys($funcs));
  125. }
  126. }
  127. }
  128. // oops, nothing found
  129. $this->not_found();
  130. }
  131. function get_service() {
  132. log_app('function','get_service()');
  133. if( !current_user_can( 'edit_posts' ) )
  134. $this->auth_required( __( 'Sorry, you do not have the right to access this blog.' ) );
  135. $entries_url = attribute_escape($this->get_entries_url());
  136. $categories_url = attribute_escape($this->get_categories_url());
  137. $media_url = attribute_escape($this->get_attachments_url());
  138. foreach ($this->media_content_types as $med) {
  139. $accepted_media_types = $accepted_media_types . "<accept>" . $med . "</accept>";
  140. }
  141. $atom_prefix="atom";
  142. $atom_blogname=get_bloginfo('name');
  143. $service_doc = <<<EOD
  144. <service xmlns="$this->ATOMPUB_NS" xmlns:$atom_prefix="$this->ATOM_NS">
  145. <workspace>
  146. <$atom_prefix:title>$atom_blogname Workspace</$atom_prefix:title>
  147. <collection href="$entries_url">
  148. <$atom_prefix:title>$atom_blogname Posts</$atom_prefix:title>
  149. <accept>$this->ATOM_CONTENT_TYPE;type=entry</accept>
  150. <categories href="$categories_url" />
  151. </collection>
  152. <collection href="$media_url">
  153. <$atom_prefix:title>$atom_blogname Media</$atom_prefix:title>
  154. $accepted_media_types
  155. </collection>
  156. </workspace>
  157. </service>
  158. EOD;
  159. $this->output($service_doc, $this->SERVICE_CONTENT_TYPE);
  160. }
  161. function get_categories_xml() {
  162. log_app('function','get_categories_xml()');
  163. if( !current_user_can( 'edit_posts' ) )
  164. $this->auth_required( __( 'Sorry, you do not have the right to access this blog.' ) );
  165. $home = attribute_escape(get_bloginfo_rss('home'));
  166. $categories = "";
  167. $cats = get_categories("hierarchical=0&hide_empty=0");
  168. foreach ((array) $cats as $cat) {
  169. $categories .= " <category term=\"" . attribute_escape($cat->name) . "\" />\n";
  170. }
  171. $output = <<<EOD
  172. <app:categories xmlns:app="$this->ATOMPUB_NS"
  173. xmlns="$this->ATOM_NS"
  174. fixed="yes" scheme="$home">
  175. $categories
  176. </app:categories>
  177. EOD;
  178. $this->output($output, $this->CATEGORIES_CONTENT_TYPE);
  179. }
  180. /*
  181. * Create Post (No arguments)
  182. */
  183. function create_post() {
  184. global $blog_id, $user_ID;
  185. $this->get_accepted_content_type($this->atom_content_types);
  186. $parser = new AtomParser();
  187. if(!$parser->parse()) {
  188. $this->client_error();
  189. }
  190. $entry = array_pop($parser->feed->entries);
  191. log_app('Received entry:', print_r($entry,true));
  192. $catnames = array();
  193. foreach($entry->categories as $cat)
  194. array_push($catnames, $cat["term"]);
  195. $wp_cats = get_categories(array('hide_empty' => false));
  196. $post_category = array();
  197. foreach($wp_cats as $cat) {
  198. if(in_array($cat->name, $catnames))
  199. array_push($post_category, $cat->term_id);
  200. }
  201. $publish = (isset($entry->draft) && trim($entry->draft) == 'yes') ? false : true;
  202. $cap = ($publish) ? 'publish_posts' : 'edit_posts';
  203. if(!current_user_can($cap))
  204. $this->auth_required(__('Sorry, you do not have the right to edit/publish new posts.'));
  205. $blog_ID = (int ) $blog_id;
  206. $post_status = ($publish) ? 'publish' : 'draft';
  207. $post_author = (int) $user_ID;
  208. $post_title = $entry->title[1];
  209. $post_content = $entry->content[1];
  210. $post_excerpt = $entry->summary[1];
  211. $pubtimes = $this->get_publish_time($entry->published);
  212. $post_date = $pubtimes[0];
  213. $post_date_gmt = $pubtimes[1];
  214. if ( isset( $_SERVER['HTTP_SLUG'] ) )
  215. $post_name = $_SERVER['HTTP_SLUG'];
  216. $post_data = compact('blog_ID', 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_name');
  217. $this->escape($post_data);
  218. log_app('Inserting Post. Data:', print_r($post_data,true));
  219. $postID = wp_insert_post($post_data);
  220. if ( is_wp_error( $postID ) )
  221. $this->internal_error($postID->get_error_message());
  222. if (!$postID)
  223. $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
  224. // getting warning here about unable to set headers
  225. // because something in the cache is printing to the buffer
  226. // could we clean up wp_set_post_categories or cache to not print
  227. // this could affect our ability to send back the right headers
  228. @wp_set_post_categories($postID, $post_category);
  229. $output = $this->get_entry($postID);
  230. log_app('function',"create_post($postID)");
  231. $this->created($postID, $output);
  232. }
  233. function get_post($postID) {
  234. global $entry;
  235. if( !current_user_can( 'edit_post', $postID ) )
  236. $this->auth_required( __( 'Sorry, you do not have the right to access this post.' ) );
  237. $this->set_current_entry($postID);
  238. $output = $this->get_entry($postID);
  239. log_app('function',"get_post($postID)");
  240. $this->output($output);
  241. }
  242. function put_post($postID) {
  243. // checked for valid content-types (atom+xml)
  244. // quick check and exit
  245. $this->get_accepted_content_type($this->atom_content_types);
  246. $parser = new AtomParser();
  247. if(!$parser->parse()) {
  248. $this->bad_request();
  249. }
  250. $parsed = array_pop($parser->feed->entries);
  251. log_app('Received UPDATED entry:', print_r($parsed,true));
  252. // check for not found
  253. global $entry;
  254. $this->set_current_entry($postID);
  255. if(!current_user_can('edit_post', $entry['ID']))
  256. $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
  257. $publish = (isset($parsed->draft) && trim($parsed->draft) == 'yes') ? false : true;
  258. extract($entry);
  259. $post_title = $parsed->title[1];
  260. $post_content = $parsed->content[1];
  261. $post_excerpt = $parsed->summary[1];
  262. $pubtimes = $this->get_publish_time($entry->published);
  263. $post_date = $pubtimes[0];
  264. $post_date_gmt = $pubtimes[1];
  265. $pubtimes = $this->get_publish_time($parsed->updated);
  266. $post_modified = $pubtimes[0];
  267. $post_modified_gmt = $pubtimes[1];
  268. // let's not go backwards and make something draft again.
  269. if(!$publish && $post_status == 'draft') {
  270. $post_status = ($publish) ? 'publish' : 'draft';
  271. } elseif($publish) {
  272. $post_status = 'publish';
  273. }
  274. $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt');
  275. $this->escape($postdata);
  276. $result = wp_update_post($postdata);
  277. if (!$result) {
  278. $this->internal_error(__('For some strange yet very annoying reason, this post could not be edited.'));
  279. }
  280. log_app('function',"put_post($postID)");
  281. $this->ok();
  282. }
  283. function delete_post($postID) {
  284. // check for not found
  285. global $entry;
  286. $this->set_current_entry($postID);
  287. if(!current_user_can('edit_post', $postID)) {
  288. $this->auth_required(__('Sorry, you do not have the right to delete this post.'));
  289. }
  290. if ($entry['post_type'] == 'attachment') {
  291. $this->delete_attachment($postID);
  292. } else {
  293. $result = wp_delete_post($postID);
  294. if (!$result) {
  295. $this->internal_error(__('For some strange yet very annoying reason, this post could not be deleted.'));
  296. }
  297. log_app('function',"delete_post($postID)");
  298. $this->ok();
  299. }
  300. }
  301. function get_attachment($postID = NULL) {
  302. if( !current_user_can( 'upload_files' ) )
  303. $this->auth_required( __( 'Sorry, you do not have permission to upload files.' ) );
  304. if (!isset($postID)) {
  305. $this->get_attachments();
  306. } else {
  307. $this->set_current_entry($postID);
  308. $output = $this->get_entry($postID, 'attachment');
  309. log_app('function',"get_attachment($postID)");
  310. $this->output($output);
  311. }
  312. }
  313. function create_attachment() {
  314. $type = $this->get_accepted_content_type();
  315. if(!current_user_can('upload_files'))
  316. $this->auth_required(__('You do not have permission to upload files.'));
  317. $fp = fopen("php://input", "rb");
  318. $bits = NULL;
  319. while(!feof($fp)) {
  320. $bits .= fread($fp, 4096);
  321. }
  322. fclose($fp);
  323. $slug = '';
  324. if ( isset( $_SERVER['HTTP_SLUG'] ) )
  325. $slug = sanitize_file_name( $_SERVER['HTTP_SLUG'] );
  326. elseif ( isset( $_SERVER['HTTP_TITLE'] ) )
  327. $slug = sanitize_file_name( $_SERVER['HTTP_TITLE'] );
  328. elseif ( empty( $slug ) ) // just make a random name
  329. $slug = substr( md5( uniqid( microtime() ) ), 0, 7);
  330. $ext = preg_replace( '|.*/([a-z0-9]+)|', '$1', $_SERVER['CONTENT_TYPE'] );
  331. $slug = "$slug.$ext";
  332. $file = wp_upload_bits( $slug, NULL, $bits);
  333. log_app('wp_upload_bits returns:',print_r($file,true));
  334. $url = $file['url'];
  335. $file = $file['file'];
  336. do_action('wp_create_file_in_uploads', $file); // replicate
  337. // Construct the attachment array
  338. $attachment = array(
  339. 'post_title' => $slug,
  340. 'post_content' => $slug,
  341. 'post_status' => 'attachment',
  342. 'post_parent' => 0,
  343. 'post_mime_type' => $type,
  344. 'guid' => $url
  345. );
  346. // Save the data
  347. $postID = wp_insert_attachment($attachment, $file);
  348. if (!$postID)
  349. $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
  350. $output = $this->get_entry($postID, 'attachment');
  351. $this->created($postID, $output, 'attachment');
  352. log_app('function',"create_attachment($postID)");
  353. }
  354. function put_attachment($postID) {
  355. // checked for valid content-types (atom+xml)
  356. // quick check and exit
  357. $this->get_accepted_content_type($this->atom_content_types);
  358. $parser = new AtomParser();
  359. if(!$parser->parse()) {
  360. $this->bad_request();
  361. }
  362. $parsed = array_pop($parser->feed->entries);
  363. // check for not found
  364. global $entry;
  365. $this->set_current_entry($postID);
  366. if(!current_user_can('edit_post', $entry['ID']))
  367. $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
  368. extract($entry);
  369. $post_title = $parsed->title[1];
  370. $post_content = $parsed->content[1];
  371. $pubtimes = $this->get_publish_time($parsed->updated);
  372. $post_modified = $pubtimes[0];
  373. $post_modified_gmt = $pubtimes[1];
  374. $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_modified', 'post_modified_gmt');
  375. $this->escape($postdata);
  376. $result = wp_update_post($postdata);
  377. if (!$result) {
  378. $this->internal_error(__('For some strange yet very annoying reason, this post could not be edited.'));
  379. }
  380. log_app('function',"put_attachment($postID)");
  381. $this->ok();
  382. }
  383. function delete_attachment($postID) {
  384. log_app('function',"delete_attachment($postID). File '$location' deleted.");
  385. // check for not found
  386. global $entry;
  387. $this->set_current_entry($postID);
  388. if(!current_user_can('edit_post', $postID)) {
  389. $this->auth_required(__('Sorry, you do not have the right to delete this post.'));
  390. }
  391. $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
  392. $filetype = wp_check_filetype($location);
  393. if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']))
  394. $this->internal_error(__('Error ocurred while accessing post metadata for file location.'));
  395. // delete file
  396. @unlink($location);
  397. // delete attachment
  398. $result = wp_delete_post($postID);
  399. if (!$result) {
  400. $this->internal_error(__('For some strange yet very annoying reason, this post could not be deleted.'));
  401. }
  402. log_app('function',"delete_attachment($postID). File '$location' deleted.");
  403. $this->ok();
  404. }
  405. function get_file($postID) {
  406. // check for not found
  407. global $entry;
  408. $this->set_current_entry($postID);
  409. // then whether user can edit the specific post
  410. if(!current_user_can('edit_post', $postID)) {
  411. $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
  412. }
  413. $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
  414. $filetype = wp_check_filetype($location);
  415. if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']))
  416. $this->internal_error(__('Error ocurred while accessing post metadata for file location.'));
  417. status_header('200');
  418. header('Content-Type: ' . $entry['post_mime_type']);
  419. header('Connection: close');
  420. $fp = fopen($location, "rb");
  421. while(!feof($fp)) {
  422. echo fread($fp, 4096);
  423. }
  424. fclose($fp);
  425. log_app('function',"get_file($postID)");
  426. exit;
  427. }
  428. function put_file($postID) {
  429. // first check if user can upload
  430. if(!current_user_can('upload_files'))
  431. $this->auth_required(__('You do not have permission to upload files.'));
  432. // check for not found
  433. global $entry;
  434. $this->set_current_entry($postID);
  435. // then whether user can edit the specific post
  436. if(!current_user_can('edit_post', $postID)) {
  437. $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
  438. }
  439. $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
  440. $filetype = wp_check_filetype($location);
  441. if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']))
  442. $this->internal_error(__('Error ocurred while accessing post metadata for file location.'));
  443. $fp = fopen("php://input", "rb");
  444. $localfp = fopen($location, "w+");
  445. while(!feof($fp)) {
  446. fwrite($localfp,fread($fp, 4096));
  447. }
  448. fclose($fp);
  449. fclose($localfp);
  450. $ID = $entry['ID'];
  451. $pubtimes = $this->get_publish_time($entry->published);
  452. $post_date = $pubtimes[0];
  453. $post_date_gmt = $pubtimes[1];
  454. $pubtimes = $this->get_publish_time($parsed->updated);
  455. $post_modified = $pubtimes[0];
  456. $post_modified_gmt = $pubtimes[1];
  457. $post_data = compact('ID', 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt');
  458. $result = wp_update_post($post_data);
  459. if (!$result) {
  460. $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
  461. }
  462. log_app('function',"put_file($postID)");
  463. $this->ok();
  464. }
  465. function get_entries_url($page = NULL) {
  466. if($GLOBALS['post_type'] == 'attachment') {
  467. $path = $this->MEDIA_PATH;
  468. } else {
  469. $path = $this->ENTRIES_PATH;
  470. }
  471. $url = $this->app_base . $path;
  472. if(isset($page) && is_int($page)) {
  473. $url .= "/$page";
  474. }
  475. return $url;
  476. }
  477. function the_entries_url($page = NULL) {
  478. echo $this->get_entries_url($page);
  479. }
  480. function get_categories_url($deprecated = '') {
  481. return $this->app_base . $this->CATEGORIES_PATH;
  482. }
  483. function the_categories_url() {
  484. echo $this->get_categories_url();
  485. }
  486. function get_attachments_url($page = NULL) {
  487. $url = $this->app_base . $this->MEDIA_PATH;
  488. if(isset($page) && is_int($page)) {
  489. $url .= "/$page";
  490. }
  491. return $url;
  492. }
  493. function the_attachments_url($page = NULL) {
  494. echo $this->get_attachments_url($page);
  495. }
  496. function get_service_url() {
  497. return $this->app_base . $this->SERVICE_PATH;
  498. }
  499. function get_entry_url($postID = NULL) {
  500. if(!isset($postID)) {
  501. global $post;
  502. $postID = (int) $post->ID;
  503. }
  504. $url = $this->app_base . $this->ENTRY_PATH . "/$postID";
  505. log_app('function',"get_entry_url() = $url");
  506. return $url;
  507. }
  508. function the_entry_url($postID = NULL) {
  509. echo $this->get_entry_url($postID);
  510. }
  511. function get_media_url($postID = NULL) {
  512. if(!isset($postID)) {
  513. global $post;
  514. $postID = (int) $post->ID;
  515. }
  516. $url = $this->app_base . $this->MEDIA_SINGLE_PATH ."/file/$postID";
  517. log_app('function',"get_media_url() = $url");
  518. return $url;
  519. }
  520. function the_media_url($postID = NULL) {
  521. echo $this->get_media_url($postID);
  522. }
  523. function set_current_entry($postID) {
  524. global $entry;
  525. log_app('function',"set_current_entry($postID)");
  526. if(!isset($postID)) {
  527. // $this->bad_request();
  528. $this->not_found();
  529. }
  530. $entry = wp_get_single_post($postID,ARRAY_A);
  531. if(!isset($entry) || !isset($entry['ID']))
  532. $this->not_found();
  533. return;
  534. }
  535. function get_posts($page = 1, $post_type = 'post') {
  536. log_app('function',"get_posts($page, '$post_type')");
  537. $feed = $this->get_feed($page, $post_type);
  538. $this->output($feed);
  539. }
  540. function get_attachments($page = 1, $post_type = 'attachment') {
  541. log_app('function',"get_attachments($page, '$post_type')");
  542. $GLOBALS['post_type'] = $post_type;
  543. $feed = $this->get_feed($page, $post_type);
  544. $this->output($feed);
  545. }
  546. function get_feed($page = 1, $post_type = 'post') {
  547. global $post, $wp, $wp_query, $posts, $wpdb, $blog_id;
  548. log_app('function',"get_feed($page, '$post_type')");
  549. ob_start();
  550. if(!isset($page)) {
  551. $page = 1;
  552. }
  553. $page = (int) $page;
  554. $count = get_option('posts_per_rss');
  555. wp('what_to_show=posts&posts_per_page=' . $count . '&offset=' . ($count * ($page-1) . '&orderby=modified'));
  556. $post = $GLOBALS['post'];
  557. $posts = $GLOBALS['posts'];
  558. $wp = $GLOBALS['wp'];
  559. $wp_query = $GLOBALS['wp_query'];
  560. $wpdb = $GLOBALS['wpdb'];
  561. $blog_id = (int) $GLOBALS['blog_id'];
  562. log_app('function',"query_posts(# " . print_r($wp_query, true) . "#)");
  563. log_app('function',"total_count(# $wp_query->max_num_pages #)");
  564. $last_page = $wp_query->max_num_pages;
  565. $next_page = (($page + 1) > $last_page) ? NULL : $page + 1;
  566. $prev_page = ($page - 1) < 1 ? NULL : $page - 1;
  567. $last_page = ((int)$last_page == 1 || (int)$last_page == 0) ? NULL : (int) $last_page;
  568. $self_page = $page > 1 ? $page : NULL;
  569. ?><feed xmlns="<?php echo $this->ATOM_NS ?>" xmlns:app="<?php echo $this->ATOMPUB_NS ?>" xml:lang="<?php echo get_option('rss_language'); ?>">
  570. <id><?php $this->the_entries_url() ?></id>
  571. <updated><?php echo mysql2date('Y-m-d\TH:i:s\Z', get_lastpostmodified('GMT')); ?></updated>
  572. <title type="text"><?php bloginfo_rss('name') ?></title>
  573. <subtitle type="text"><?php bloginfo_rss("description") ?></subtitle>
  574. <link rel="first" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url() ?>" />
  575. <?php if(isset($prev_page)): ?>
  576. <link rel="previous" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($prev_page) ?>" />
  577. <?php endif; ?>
  578. <?php if(isset($next_page)): ?>
  579. <link rel="next" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($next_page) ?>" />
  580. <?php endif; ?>
  581. <link rel="last" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($last_page) ?>" />
  582. <link rel="self" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($self_page) ?>" />
  583. <rights type="text">Copyright <?php echo mysql2date('Y', get_lastpostdate('blog')); ?></rights>
  584. <?php the_generator( 'atom' ); ?>
  585. <?php if ( have_posts() ) {
  586. while ( have_posts() ) {
  587. the_post();
  588. $this->echo_entry();
  589. }
  590. }
  591. ?></feed>
  592. <?php
  593. $feed = ob_get_contents();
  594. ob_end_clean();
  595. return $feed;
  596. }
  597. function get_entry($postID, $post_type = 'post') {
  598. log_app('function',"get_entry($postID, '$post_type')");
  599. ob_start();
  600. switch($post_type) {
  601. case 'post':
  602. $varname = 'p';
  603. break;
  604. case 'attachment':
  605. $varname = 'attachment_id';
  606. break;
  607. }
  608. query_posts($varname . '=' . $postID);
  609. if ( have_posts() ) {
  610. while ( have_posts() ) {
  611. the_post();
  612. $this->echo_entry();
  613. log_app('$post',print_r($GLOBALS['post'],true));
  614. $entry = ob_get_contents();
  615. break;
  616. }
  617. }
  618. ob_end_clean();
  619. log_app('get_entry returning:',$entry);
  620. return $entry;
  621. }
  622. function echo_entry() { ?>
  623. <entry xmlns="<?php echo $this->ATOM_NS ?>"
  624. xmlns:app="<?php echo $this->ATOMPUB_NS ?>" xml:lang="<?php echo get_option('rss_language'); ?>">
  625. <id><?php the_guid($GLOBALS['post']->ID); ?></id>
  626. <?php list($content_type, $content) = prep_atom_text_construct(get_the_title()); ?>
  627. <title type="<?php echo $content_type ?>"><?php echo $content ?></title>
  628. <updated><?php echo get_post_modified_time('Y-m-d\TH:i:s\Z', true); ?></updated>
  629. <published><?php echo get_post_time('Y-m-d\TH:i:s\Z', true); ?></published>
  630. <app:edited><?php echo get_post_modified_time('Y-m-d\TH:i:s\Z', true); ?></app:edited>
  631. <app:control>
  632. <app:draft><?php echo ($GLOBALS['post']->post_status == 'draft' ? 'yes' : 'no') ?></app:draft>
  633. </app:control>
  634. <author>
  635. <name><?php the_author()?></name>
  636. <?php if (get_the_author_url() && get_the_author_url() != 'http://') { ?>
  637. <uri><?php the_author_url()?></uri>
  638. <?php } ?>
  639. </author>
  640. <?php if($GLOBALS['post']->post_type == 'attachment') { ?>
  641. <link rel="edit-media" href="<?php $this->the_media_url() ?>" />
  642. <content type="<?php echo $GLOBALS['post']->post_mime_type ?>" src="<?php the_guid(); ?>"/>
  643. <?php } else { ?>
  644. <link href="<?php the_permalink_rss() ?>" />
  645. <?php if ( strlen( $GLOBALS['post']->post_content ) ) :
  646. list($content_type, $content) = prep_atom_text_construct(get_the_content()); ?>
  647. <content type="<?php echo $content_type ?>"><?php echo $content ?></content>
  648. <?php endif; ?>
  649. <?php } ?>
  650. <link rel="edit" href="<?php $this->the_entry_url() ?>" />
  651. <?php foreach(get_the_category() as $category) { ?>
  652. <category scheme="<?php bloginfo_rss('home') ?>" term="<?php echo $category->name?>" />
  653. <?php } ?>
  654. <?php list($content_type, $content) = prep_atom_text_construct(get_the_excerpt()); ?>
  655. <summary type="<?php echo $content_type ?>"><?php echo $content ?></summary>
  656. </entry>
  657. <?php }
  658. function ok() {
  659. log_app('Status','200: OK');
  660. header('Content-Type: text/plain');
  661. status_header('200');
  662. exit;
  663. }
  664. function no_content() {
  665. log_app('Status','204: No Content');
  666. header('Content-Type: text/plain');
  667. status_header('204');
  668. echo "Deleted.";
  669. exit;
  670. }
  671. function internal_error($msg = 'Internal Server Error') {
  672. log_app('Status','500: Server Error');
  673. header('Content-Type: text/plain');
  674. status_header('500');
  675. echo $msg;
  676. exit;
  677. }
  678. function bad_request() {
  679. log_app('Status','400: Bad Request');
  680. header('Content-Type: text/plain');
  681. status_header('400');
  682. exit;
  683. }
  684. function length_required() {
  685. log_app('Status','411: Length Required');
  686. header("HTTP/1.1 411 Length Required");
  687. header('Content-Type: text/plain');
  688. status_header('411');
  689. exit;
  690. }
  691. function invalid_media() {
  692. log_app('Status','415: Unsupported Media Type');
  693. header("HTTP/1.1 415 Unsupported Media Type");
  694. header('Content-Type: text/plain');
  695. exit;
  696. }
  697. function not_found() {
  698. log_app('Status','404: Not Found');
  699. header('Content-Type: text/plain');
  700. status_header('404');
  701. exit;
  702. }
  703. function not_allowed($allow) {
  704. log_app('Status','405: Not Allowed');
  705. header('Allow: ' . join(',', $allow));
  706. status_header('405');
  707. exit;
  708. }
  709. function redirect($url) {
  710. log_app('Status','302: Redirect');
  711. $escaped_url = attribute_escape($url);
  712. $content = <<<EOD
  713. <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
  714. <html>
  715. <head>
  716. <title>302 Found</title>
  717. </head>
  718. <body>
  719. <h1>Found</h1>
  720. <p>The document has moved <a href="$escaped_url">here</a>.</p>
  721. </body>
  722. </html>
  723. EOD;
  724. header('HTTP/1.1 302 Moved');
  725. header('Content-Type: text/html');
  726. header('Location: ' . $url);
  727. echo $content;
  728. exit;
  729. }
  730. function client_error($msg = 'Client Error') {
  731. log_app('Status','400: Client Error');
  732. header('Content-Type: text/plain');
  733. status_header('400');
  734. exit;
  735. }
  736. function created($post_ID, $content, $post_type = 'post') {
  737. log_app('created()::$post_ID',"$post_ID, $post_type");
  738. $edit = $this->get_entry_url($post_ID);
  739. switch($post_type) {
  740. case 'post':
  741. $ctloc = $this->get_entry_url($post_ID);
  742. break;
  743. case 'attachment':
  744. $edit = $this->app_base . "attachments/$post_ID";
  745. break;
  746. }
  747. header("Content-Type: $this->ATOM_CONTENT_TYPE");
  748. if(isset($ctloc))
  749. header('Content-Location: ' . $ctloc);
  750. header('Location: ' . $edit);
  751. status_header('201');
  752. echo $content;
  753. exit;
  754. }
  755. function auth_required($msg) {
  756. log_app('Status','401: Auth Required');
  757. nocache_headers();
  758. header('WWW-Authenticate: Basic realm="WordPress Atom Protocol"');
  759. header("HTTP/1.1 401 $msg");
  760. header('Status: ' . $msg);
  761. header('Content-Type: text/html');
  762. $content = <<<EOD
  763. <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
  764. <html>
  765. <head>
  766. <title>401 Unauthorized</title>
  767. </head>
  768. <body>
  769. <h1>401 Unauthorized</h1>
  770. <p>$msg</p>
  771. </body>
  772. </html>
  773. EOD;
  774. echo $content;
  775. exit;
  776. }
  777. function output($xml, $ctype = 'application/atom+xml') {
  778. status_header('200');
  779. $xml = '<?xml version="1.0" encoding="' . strtolower(get_option('blog_charset')) . '"?>'."\n".$xml;
  780. header('Connection: close');
  781. header('Content-Length: '. strlen($xml));
  782. header('Content-Type: ' . $ctype);
  783. header('Content-Disposition: attachment; filename=atom.xml');
  784. header('Date: '. date('r'));
  785. if($this->do_output)
  786. echo $xml;
  787. log_app('function', "output:\n$xml");
  788. exit;
  789. }
  790. function escape(&$array) {
  791. global $wpdb;
  792. foreach ($array as $k => $v) {
  793. if (is_array($v)) {
  794. $this->escape($array[$k]);
  795. } else if (is_object($v)) {
  796. //skip
  797. } else {
  798. $array[$k] = $wpdb->escape($v);
  799. }
  800. }
  801. }
  802. /*
  803. * Access credential through various methods and perform login
  804. */
  805. function authenticate() {
  806. $login_data = array();
  807. $already_md5 = false;
  808. log_app("authenticate()",print_r($_ENV, true));
  809. // if using mod_rewrite/ENV hack
  810. // http://www.besthostratings.com/articles/http-auth-php-cgi.html
  811. if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
  812. list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
  813. explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
  814. }
  815. // If Basic Auth is working...
  816. if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
  817. $login_data = array('login' => $_SERVER['PHP_AUTH_USER'], 'password' => $_SERVER['PHP_AUTH_PW']);
  818. log_app("Basic Auth",$login_data['login']);
  819. } else {
  820. // else, do cookie-based authentication
  821. if (function_exists('wp_get_cookie_login')) {
  822. $login_data = wp_get_cookie_login();
  823. $already_md5 = true;
  824. }
  825. }
  826. // call wp_login and set current user
  827. if (!empty($login_data) && wp_login($login_data['login'], $login_data['password'], $already_md5)) {
  828. $current_user = new WP_User(0, $login_data['login']);
  829. wp_set_current_user($current_user->ID);
  830. log_app("authenticate()",$login_data['login']);
  831. }
  832. }
  833. function get_accepted_content_type($types = NULL) {
  834. if(!isset($types)) {
  835. $types = $this->media_content_types;
  836. }
  837. if(!isset($_SERVER['CONTENT_LENGTH']) || !isset($_SERVER['CONTENT_TYPE'])) {
  838. $this->length_required();
  839. }
  840. $type = $_SERVER['CONTENT_TYPE'];
  841. list($type,$subtype) = explode('/',$type);
  842. list($subtype) = explode(";",$subtype); // strip MIME parameters
  843. log_app("get_accepted_content_type", "type=$type, subtype=$subtype");
  844. foreach($types as $t) {
  845. list($acceptedType,$acceptedSubtype) = explode('/',$t);
  846. if($acceptedType == '*' || $acceptedType == $type) {
  847. if($acceptedSubtype == '*' || $acceptedSubtype == $subtype)
  848. return $type . "/" . $subtype;
  849. }
  850. }
  851. $this->invalid_media();
  852. }
  853. function process_conditionals() {
  854. if(empty($this->params)) return;
  855. if($_SERVER['REQUEST_METHOD'] == 'DELETE') return;
  856. switch($this->params[0]) {
  857. case $this->ENTRY_PATH:
  858. global $post;
  859. $post = wp_get_single_post($this->params[1]);
  860. $wp_last_modified = get_post_modified_time('D, d M Y H:i:s', true);
  861. $post = NULL;
  862. break;
  863. case $this->ENTRIES_PATH:
  864. $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT';
  865. break;
  866. default:
  867. return;
  868. }
  869. $wp_etag = md5($wp_last_modified);
  870. @header("Last-Modified: $wp_last_modified");
  871. @header("ETag: $wp_etag");
  872. // Support for Conditional GET
  873. if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
  874. $client_etag = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']);
  875. else
  876. $client_etag = false;
  877. $client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE']);
  878. // If string is empty, return 0. If not, attempt to parse into a timestamp
  879. $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0;
  880. // Make a timestamp for our most recent modification...
  881. $wp_modified_timestamp = strtotime($wp_last_modified);
  882. if ( ($client_last_modified && $client_etag) ?
  883. (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) :
  884. (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) {
  885. status_header( 304 );
  886. exit;
  887. }
  888. }
  889. function rfc3339_str2time($str) {
  890. $match = false;
  891. if(!preg_match("/(\d{4}-\d{2}-\d{2})T(\d{2}\:\d{2}\:\d{2})\.?\d{0,3}(Z|[+-]+\d{2}\:\d{2})/", $str, $match))
  892. return false;
  893. if($match[3] == 'Z')
  894. $match[3] == '+0000';
  895. return strtotime($match[1] . " " . $match[2] . " " . $match[3]);
  896. }
  897. function get_publish_time($published) {
  898. $pubtime = $this->rfc3339_str2time($published);
  899. if(!$pubtime) {
  900. return array(current_time('mysql'),current_time('mysql',1));
  901. } else {
  902. return array(date("Y-m-d H:i:s", $pubtime), gmdate("Y-m-d H:i:s", $pubtime));
  903. }
  904. }
  905. }
  906. $server = new AtomServer();
  907. $server->handle_request();
  908. ?>