root/wordpress/wp-mail-sl.php

Revision 22, 13.5 kB (checked in by max.ca..@gmail.com, 2 years ago)

modded wordpress mail script. Modded for SL/My purposes.

Line 
1 <?php
2 //Modified version of wp-mail.php for wordpress.
3 //This modification handles SL Postcards, and creates an SLink to the location that you took the snapshot from.
4 //Extra Special thanks to Mr. Fong for making this all possible.
5 //Requires Imagemagick to be installed on your server.
6 //Version 1.0
7
8 //@REQUIRE: Remove filter from post.php if you want class in the imag thumbnail. very annoying. need to investigate that.
9 //comment this out: line 506: //$post_content    = apply_filters('content_save_pre',   $post_content);
10
11 //@TODO wp-admin pref pane.
12 //Max Case Apr 8 2007
13
14 //////You will need to modify the below,
15 //or create the folders /images/postcards/, and /images/postcards/thumbs/
16 // define path to where postcard images will be stored (include trailing slash)
17 define('POSTCARDS_DATA_DIR', $_SERVER['DOCUMENT_ROOT'] .'/images/postcards/');
18
19 // define path to where postcard thumbnails will be stored (include trailing slash)
20 define('POSTCARDS_THUMBNAILS_DATA_DIR', $_SERVER['DOCUMENT_ROOT'] .'/images/postcards/thumbs/');
21
22 ///End changes
23
24
25 require(dirname(__FILE__) . '/wp-config.php');
26
27 require_once(ABSPATH.WPINC.'/class-pop3.php');
28
29 error_reporting(2037);
30
31 ///Added by Max
32 //This is used to set who the message gets posted by -
33 //Under normal WP script, it's set to Admin.
34 //For SL, I would rather it be posted under my Max Case name, so I set it to 2. You may want to make this 1 again.
35 $default_author = 2;
36
37 $time_difference = get_option('gmt_offset') * 3600;
38
39 $phone_delim = '::';
40
41 $pop3 = new POP3();
42
43 if (!$pop3->connect(get_option('mailserver_url'), get_option('mailserver_port'))) :
44     echo "Ooops $pop3->ERROR <br />\n";
45     exit;
46 endif;
47
48 $count = $pop3->login(get_option('mailserver_login'), get_option('mailserver_pass'));
49 if (0 == $count) die(__('There doesn&#8217;t seem to be any new mail.'));
50
51
52 for ($i=1; $i <= $count; $i++) :
53
54     $message = $pop3->get($i);
55
56     $content = '';
57     $content_type = '';
58     $boundary = '';
59     $bodysignal = 0;
60     $dmonths = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
61                      'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
62                     
63      //SL Modifications here - just some vars we'll be using.
64      $locationholder = '';
65      $locationlink = '';
66      $locationhuman ='';
67      $link = '';
68      $preggers = 0;
69      $grab_coords = 0;//flag for when to grab coords
70      //////////
71
72
73     foreach ($message as $line) :
74         if (strlen($line) < 3) $bodysignal = 1;
75
76         if ($bodysignal)
77         {
78             $content .= $line;
79             
80             ////SL MOD here
81             if( strpos($line, '<!-- BEGIN POSTCARD DETAILS') !== FALSE)
82             {   //grab region name for region name & coords
83                 $grab_coords = 1;//TURN ON NEXT LINE FLAG
84             }
85             else if( $grab_coords)
86             {
87                 $grab_coords = 0; //TURN OFF NEXT LINE FLAG
88                 $g_temp explode(",", $line );
89
90                 $global_pos = array( "region"=>$g_temp[1], "x" =>$g_temp[2], "y" => $g_temp[3]);               
91                 //I leave next two vars as convenience to you. Not necessary
92                 //Format it into link
93                 $link = trim($global_pos['region']) . "/" . trim($global_pos['x']) . "/" . trim($global_pos['y']);
94                 //Build the HTML
95                 $linktext = trim($global_pos['region']) . " " . trim($global_pos['x']) . "," . trim($global_pos['y']);
96                 $locationhtml = "<p><a href=\"secondlife://". $link."\" title=\"". $linktext ."\">". $linktext ."</a></p>";
97             }
98             ///////////
99         } else {
100             if (preg_match('/Content-Type: /i', $line)) {
101                 $content_type = trim($line);
102                 $content_type = substr($content_type, 14, strlen($content_type)-14);
103                 $content_type = explode(';', $content_type);
104                 $content_type = $content_type[0];
105             }
106             if (($content_type == 'multipart/alternative') && (preg_match('/boundary="/', $line)) && ($boundary == '')) {
107                 $boundary = trim($line);
108                 $boundary = explode('"', $boundary);
109                 $boundary = $boundary[1];
110             }
111             if (preg_match('/Subject: /i', $line)) {
112                 $subject = trim($line);
113                 $subject = substr($subject, 9, strlen($subject)-9);
114                 $subject = wp_iso_descrambler($subject);
115                 // Captures any text in the subject before $phone_delim as the subject
116                 $subject = explode($phone_delim, $subject);
117                 $subject = $subject[0];
118             }
119
120             // Set the author using the email address (To or Reply-To, the last used)
121             // Modded by me to use $default_author var set up top.
122             if (preg_match('/From: /', $line) | preg_match('Reply-To: /', $line))  {
123                 $author=trim($line);
124             if ( ereg("([a-zA-Z0-9\_\-\.]+@[\a-zA-z0-9\_\-\.]+)", $author , $regs) ) {
125                 $author = $regs[1];
126                 echo "Author = {$author} <p>";
127                 $author = $wpdb->escape($author);
128                 $result = $wpdb->get_row("SELECT ID FROM $wpdb->users WHERE user_email='$author' LIMIT 1");
129                 if (!$result)
130                     $post_author = 1;
131                 else
132                     $post_author = $result->ID;
133             } else
134                 $post_author = $default_author;
135             }
136
137             if (preg_match('/Date: /i', $line)) { // of the form '20 Mar 2002 20:32:37'
138                 $ddate = trim($line);
139                 $ddate = str_replace('Date: ', '', $ddate);
140                 if (strpos($ddate, ',')) {
141                     $ddate = trim(substr($ddate, strpos($ddate, ',')+1, strlen($ddate)));
142                 }
143                 $date_arr = explode(' ', $ddate);
144                 $date_time = explode(':', $date_arr[3]);
145                 
146                 $ddate_H = $date_time[0];
147                 $ddate_i = $date_time[1];
148                 $ddate_s = $date_time[2];
149                 
150                 $ddate_m = $date_arr[1];
151                 $ddate_d = $date_arr[0];
152                 $ddate_Y = $date_arr[2];
153                 for ($j=0; $j<12; $j++) {
154                     if ($ddate_m == $dmonths[$j]) {
155                         $ddate_m = $j+1;
156                     }
157                 }
158
159                 $time_zn = intval($date_arr[4]) * 36;
160                 $ddate_U = gmmktime($ddate_H, $ddate_i, $ddate_s, $ddate_m, $ddate_d, $ddate_Y);
161                 $ddate_U = $ddate_U - $time_zn;
162                 $post_date = gmdate('Y-m-d H:i:s', $ddate_U + $time_difference);
163                 $post_date_gmt = gmdate('Y-m-d H:i:s', $ddate_U);
164             }
165         }
166     endforeach;
167     
168     // SL Postcard Mod
169     $mime_parts = array();
170     //////
171     
172     $subject = trim(str_replace(get_option('subjectprefix'), '', $subject));
173
174     if ($content_type == 'multipart/alternative') {
175         $content = explode('--'.$boundary, $content);
176         $mime_parts = explode(substr('--'. $boundary, 0, strlen($boundary) + 2 - 1), $content[2]);
177         $content = $content[2];
178         $content = explode('Content-Transfer-Encoding: quoted-printable', $content);
179         $content = strip_tags($content[1], '<img><p><br><i><b><u><em><strong><strike><font><span><div>');
180     }
181     
182     /**
183      * fong's mods for Second Life
184      *
185      * Not pretty, but it should work. It basically looks for a JPEG named
186      * secondlife-postcard.jpg, extracts the image, and eventually saves it to
187      * the filesystem. Then we'll add a link to that graphic to the post.
188      */
189     $image_file = '';
190     foreach ($mime_parts as $num => $part) {
191         // get rid of leading and trailing whitespace characters
192         $part = trim($part);
193
194         // parse each MIME attachment to see if it contains the image we want
195         // (as long as $image_file is empty, we haven't yet found the postcard
196         // image that should be here)
197         if (empty($image_file) && strpos($part, 'Content-Type: image/jpeg; name="secondlife-postcard.jpg"') !== false) {
198             // break out each line into its own array element
199             $lines = explode("\n", $part);
200
201             $image_data = '';
202             $headers = true;
203
204             foreach ($lines as $line) {
205                 if (trim($line) == '') {
206                     // we've parsed through the MIME attachment's headers,
207                     // now take all subsequent lines as the image data
208                     $headers = false;
209                 }
210                 if (!$headers) {
211                     $image_data .= $line;
212                 }
213             }
214
215             // decode image data so it's no longer base64-encoded
216             $image_data = base64_decode($image_data);
217             
218             // store it on the server
219             $data_dir = POSTCARDS_DATA_DIR;
220
221             // generate a unique filename for this image
222             
223             //uncommented by mitch
224            // $unique_file_name =  date("mdy_") . substr($subject, 0, 15);
225             $file_name date("mdy_") . substr($subject, 0, 15); //this is me
226             $file_name = str_replace(" ", "_", trim($file_name));//this is me
227             
228            // $image_file = $data_dir . md5(uniqid(rand(), true)) .'.jpg'; //this is fongs
229                 $image_file = $data_dir . $file_name .'.jpg';
230
231             // output the file now
232             if (!$handle = fopen($image_file, 'w')) {
233                 echo 'Fatal error: cannot open file for writing ('. $image_file .')';
234                 exit();
235             }
236             
237             if (fwrite($handle, $image_data) === false) {
238                 echo 'Fatal error: cannot write image to file ('. $image_file .')';
239                 exit();
240             }
241             
242             fclose($handle);
243         } elseif (strpos($part, 'Content-Type: text/html') !== false && strpos($part, 'Content-Transfer-Encoding: quoted-printable') !== false) {
244             // we've found the HTML content of our message, extract everything
245             // between the specified tags as our post body
246             $start_tag  = '<!-- BEGIN POSTCARD BODY -->';
247             $end_tag    = '<!-- END POSTCARD BODY -->';
248
249             // yes, there are better ways of doing this...
250             $postcard_body = $part;
251             $start_pos = strpos($part, $start_tag) + strlen($start_tag);
252             if ($start_pos !== false) {
253                 $postcard_body = substr($part, $start_pos);
254                 $end_pos = strpos($postcard_body, $end_tag);
255                 if ($end_pos !== false) {
256                     $postcard_body = substr($postcard_body, 0, $end_pos);
257                 }
258             }
259
260             $post_content = $postcard_body;
261
262             // replace =<newline> with nothing
263             $post_content = str_replace("=\r\n", "", $post_content);
264             $post_content = str_replace("=\n", "", $post_content);
265
266             // replace =0D with newlines as our post content
267             $post_content = str_replace("=0D\r\n", "\n", $post_content);
268             $post_content = str_replace("=0D\n", "\n", $post_content);
269             
270             //replae =20 as well. this is mitchs doing
271             $post_content = str_replace("=20\r\n", "\n", $post_content);
272             $post_content = str_replace("=20\n", "\n", $post_content);
273         }
274     }
275     
276     if (!empty($image_file)) {
277         // "normalize" the image
278         $tmp_image_file = POSTCARDS_DATA_DIR . md5(uniqid(rand(), true)) .'.jpg';
279
280         exec("/usr/bin/convert -normalize -gamma .9 -quality 100 $image_file $tmp_image_file", $output, $retvar);
281         if ($retvar != 0) {
282             exit('ImageMagick reported an error while trying to normalize the image (error code '. $retvar .').');
283         } else {
284             // normalize successful; replace original image with normalized one
285             @unlink($image_file);
286             if (rename($tmp_image_file, $image_file) === false) {
287                 exit('Unable to replace original image file with normalized version.');
288             }
289         }
290     
291         // create thumbnail image
292         $thumbnail_file = POSTCARDS_THUMBNAILS_DATA_DIR . basename($image_file);
293         exec("/usr/bin/convert -resize 25% $image_file $thumbnail_file", $output, $retvar);
294         if ($retvar != 0) {
295             exit('ImageMagick reported an error while trying to create thumbnail image (error code '. $retvar .').');
296         }
297
298         // get image size for thumbnail image
299         $size = @getimagesize($thumbnail_file);
300         if (empty($size)) {
301             exit('Fatal error: seems like ImageMagick did not create a valid image thumbnail!');
302         }
303
304         // link full-sized image file to thumbnail image
305         $post_content = "<a href=\"http://". $_SERVER['HTTP_HOST'] ."/images/postcards/". basename($image_file) ."\" title=\"". $subject ."\" target=\"_blank\"><img class=\"thumb\" src=\"http://". $_SERVER['HTTP_HOST'] ."/images/postcards/thumbs/". basename($thumbnail_file) ."\" alt=\"". $subject ."\" border=\"0\" ". $size[3] ." /></a>\n\n" . $locationhtml . $post_content;
306     }
307
308     $content = $post_content;
309     ///END FONG's MODS for SL Postcard
310     
311     $content = trim($content);
312     // Captures any text in the body after $phone_delim as the body
313     $content = explode($phone_delim, $content);
314     $content[1] ? $content = $content[1] : $content = $content[0];
315
316     echo "<p><b>Content-type:</b> $content_type, <b>boundary:</b> $boundary</p>\n";
317     echo "<p><b>Raw content:</b><br /><pre>".$content.'</pre></p>';
318
319     $content = trim($content);
320
321     $post_content = apply_filters('phone_content', $content);
322
323     $post_title = xmlrpc_getposttitle($content);
324
325     if ($post_title == '') $post_title = $subject;
326
327     if (empty($post_categories)) $post_categories[] = get_option('default_email_category');
328
329     $post_category = $post_categories;
330
331     // or maybe we should leave the choice to email drafts? propose a way
332     $post_status = 'publish';
333
334     $post_data = compact('post_content','post_title','post_date','post_date_gmt','post_author','post_category', 'post_status');
335     $post_data = add_magic_quotes($post_data);
336
337     $post_ID = wp_insert_post($post_data);
338
339     if (!$post_ID) {
340         // we couldn't post, for whatever reason. better move forward to the next email
341         continue;
342     }
343
344     do_action('publish_phone', $post_ID);
345
346     echo "\n<p><b>Author:</b> $post_author</p>";
347     echo "\n<p><b>Posted title:</b> $post_title<br />";
348     echo "\n<b>Posted content:</b><br /><pre>".$content.'</pre></p>';
349
350     if(!$pop3->delete($i)) {
351             echo '<p>Oops '.$pop3->ERROR.'</p></div>';
352             $pop3->reset();
353             exit;
354         } else {
355         echo "<p>Mission complete, message <strong>$i</strong> deleted.</p>";
356     }
357
358 endfor;
359
360 $pop3->quit();
361
362 ?>
Note: See TracBrowser for help on using the browser.