PageRenderTime 70ms CodeModel.GetById 35ms RepoModel.GetById 1ms app.codeStats 0ms

/projektnamn/wordpress/wp-app.php

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