PageRenderTime 74ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-app.php

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