]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/DirectMessage/actions/apidirectmessage.php
Merge remote-tracking branch 'upstream/master' into social-master
[quix0rs-gnu-social.git] / plugins / DirectMessage / actions / apidirectmessage.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Show a the direct messages from or to a user
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  API
23  * @package   StatusNet
24  * @author    Adrian Lang <mail@adrianlang.de>
25  * @author    Evan Prodromou <evan@status.net>
26  * @author    Robin Millette <robin@millette.info>
27  * @author    Zach Copley <zach@status.net>
28  * @copyright 2009 StatusNet, Inc.
29  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
30  * @link      http://status.net/
31  */
32
33 if (!defined('GNUSOCIAL')) { exit(1); }
34
35 /**
36  * Show a list of direct messages from or to the authenticating user
37  *
38  * @category API
39  * @package  StatusNet
40  * @author   Adrian Lang <mail@adrianlang.de>
41  * @author   Evan Prodromou <evan@status.net>
42  * @author   Robin Millette <robin@millette.info>
43  * @author   Zach Copley <zach@status.net>
44  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
45  * @link     http://status.net/
46  */
47 class ApiDirectMessageAction extends ApiAuthAction
48 {
49     var $messages     = null;
50     var $title        = null;
51     var $subtitle     = null;
52     var $link         = null;
53     var $selfuri_base = null;
54     var $id           = null;
55
56     /**
57      * Take arguments for running
58      *
59      * @param array $args $_REQUEST args
60      *
61      * @return boolean success flag
62      */
63     protected function prepare(array $args=array())
64     {
65         parent::prepare($args);
66
67         if (!$this->scoped instanceof Profile) {
68             // TRANS: Client error given when a user was not found (404).
69             $this->clientError(_('No such user.'), 404);
70         }
71
72         $server   = common_root_url();
73         $taguribase = TagURI::base();
74
75         if ($this->arg('sent')) {
76
77             // Action was called by /api/direct_messages/sent.format
78
79             $this->title = sprintf(
80                 // TRANS: Title. %s is a user nickname.
81                 _("Direct messages from %s"),
82                 $this->scoped->getNickname()
83             );
84             $this->subtitle = sprintf(
85                 // TRANS: Subtitle. %s is a user nickname.
86                 _("All the direct messages sent from %s"),
87                 $this->scoped->getNickname()
88             );
89             $this->link = $server . $this->scoped->getNickname() . '/outbox';
90             $this->selfuri_base = common_root_url() . 'api/direct_messages/sent';
91             $this->id = "tag:$taguribase:SentDirectMessages:" . $this->scoped->getID();
92         } else {
93             $this->title = sprintf(
94                 // TRANS: Title. %s is a user nickname.
95                 _("Direct messages to %s"),
96                 $this->scoped->getNickname()
97             );
98             $this->subtitle = sprintf(
99                 // TRANS: Subtitle. %s is a user nickname.
100                 _("All the direct messages sent to %s"),
101                 $this->scoped->getNickname()
102             );
103             $this->link = $server . $this->scoped->getNickname() . '/inbox';
104             $this->selfuri_base = common_root_url() . 'api/direct_messages';
105             $this->id = "tag:$taguribase:DirectMessages:" . $this->scoped->getID();
106         }
107
108         $this->messages = $this->getMessages();
109
110         return true;
111     }
112
113     protected function handle()
114     {
115         parent::handle();
116         $this->showMessages();
117     }
118
119     /**
120      * Show the messages
121      *
122      * @return void
123      */
124     function showMessages()
125     {
126         switch($this->format) {
127         case 'xml':
128             $this->showXmlDirectMessages();
129             break;
130         case 'rss':
131             $this->showRssDirectMessages();
132             break;
133         case 'atom':
134             $this->showAtomDirectMessages();
135             break;
136         case 'json':
137             $this->showJsonDirectMessages();
138             break;
139         default:
140             // TRANS: Client error displayed when coming across a non-supported API method.
141             $this->clientError(_('API method not found.'), $code = 404);
142             break;
143         }
144     }
145
146     /**
147      * Get notices
148      *
149      * @return array notices
150      */
151     function getMessages()
152     {
153         $message  = new Message();
154
155         if ($this->arg('sent')) {
156             $message->from_profile = $this->scoped->getID();
157         } else {
158             $message->to_profile = $this->scoped->getID();
159         }
160
161         if (!empty($this->max_id)) {
162             $message->whereAdd('id <= ' . $this->max_id);
163         }
164
165         if (!empty($this->since_id)) {
166             $message->whereAdd('id > ' . $this->since_id);
167         }
168
169         $message->orderBy('created DESC, id DESC');
170         $message->limit((($this->page - 1) * $this->count), $this->count);
171         $message->find();
172
173         $messages = array();
174
175         while ($message->fetch()) {
176             $messages[] = clone($message);
177         }
178
179         return $messages;
180     }
181
182     /**
183      * Is this action read only?
184      *
185      * @param array $args other arguments
186      *
187      * @return boolean true
188      */
189     function isReadOnly(array $args=array())
190     {
191         return true;
192     }
193
194     /**
195      * When was this notice last modified?
196      *
197      * @return string datestamp of the latest notice in the stream
198      */
199     function lastModified()
200     {
201         if (!empty($this->messages)) {
202             return strtotime($this->messages[0]->created);
203         }
204
205         return null;
206     }
207
208     // BEGIN import from lib/apiaction.php
209
210     function showSingleXmlDirectMessage($message)
211     {
212         $this->initDocument('xml');
213         $dmsg = $this->directMessageArray($message);
214         $this->showXmlDirectMessage($dmsg, true);
215         $this->endDocument('xml');
216     }
217
218     function showSingleJsonDirectMessage($message)
219     {
220         $this->initDocument('json');
221         $dmsg = $this->directMessageArray($message);
222         $this->showJsonObjects($dmsg);
223         $this->endDocument('json');
224     }
225
226     function showXmlDirectMessage($dm, $namespaces=false)
227     {
228         $attrs = array();
229         if ($namespaces) {
230             $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
231         }
232         $this->elementStart('direct_message', $attrs);
233         foreach($dm as $element => $value) {
234             switch ($element) {
235             case 'sender':
236             case 'recipient':
237                 $this->showTwitterXmlUser($value, $element);
238                 break;
239             case 'text':
240                 $this->element($element, null, common_xml_safe_str($value));
241                 break;
242             default:
243                 $this->element($element, null, $value);
244                 break;
245             }
246         }
247         $this->elementEnd('direct_message');
248     }
249
250     function directMessageArray($message)
251     {
252         $dmsg = array();
253
254         $from_profile = $message->getFrom();
255         $to_profile = $message->getTo();
256
257         $dmsg['id'] = intval($message->id);
258         $dmsg['sender_id'] = intval($from_profile->id);
259         $dmsg['text'] = trim($message->content);
260         $dmsg['recipient_id'] = intval($to_profile->id);
261         $dmsg['created_at'] = $this->dateTwitter($message->created);
262         $dmsg['sender_screen_name'] = $from_profile->nickname;
263         $dmsg['recipient_screen_name'] = $to_profile->nickname;
264         $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
265         $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
266
267         return $dmsg;
268     }
269
270     function rssDirectMessageArray($message)
271     {
272         $entry = array();
273
274         $from = $message->getFrom();
275
276         $entry['title'] = sprintf('Message from %1$s to %2$s',
277             $from->nickname, $message->getTo()->nickname);
278
279         $entry['content'] = common_xml_safe_str($message->rendered);
280         $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
281         $entry['published'] = common_date_iso8601($message->created);
282
283         $taguribase = TagURI::base();
284
285         $entry['id'] = "tag:$taguribase:$entry[link]";
286         $entry['updated'] = $entry['published'];
287
288         $entry['author-name'] = $from->getBestName();
289         $entry['author-uri'] = $from->homepage;
290
291         $entry['avatar'] = $from->avatarUrl(AVATAR_STREAM_SIZE);
292         try {
293             $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
294             $entry['avatar-type'] = $avatar->mediatype;
295         } catch (Exception $e) {
296             $entry['avatar-type'] = 'image/png';
297         }
298
299         // RSS item specific
300
301         $entry['description'] = $entry['content'];
302         $entry['pubDate'] = common_date_rfc2822($message->created);
303         $entry['guid'] = $entry['link'];
304
305         return $entry;
306     }
307
308     // END import from lib/apiaction.php
309
310     /**
311      * Shows a list of direct messages as Twitter-style XML array
312      *
313      * @return void
314      */
315     function showXmlDirectMessages()
316     {
317         $this->initDocument('xml');
318         $this->elementStart('direct-messages', array('type' => 'array',
319                                                      'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
320
321         foreach ($this->messages as $m) {
322             $dm_array = $this->directMessageArray($m);
323             $this->showXmlDirectMessage($dm_array);
324         }
325
326         $this->elementEnd('direct-messages');
327         $this->endDocument('xml');
328     }
329
330     /**
331      * Shows a list of direct messages as a JSON encoded array
332      *
333      * @return void
334      */
335     function showJsonDirectMessages()
336     {
337         $this->initDocument('json');
338
339         $dmsgs = array();
340
341         foreach ($this->messages as $m) {
342             $dm_array = $this->directMessageArray($m);
343             array_push($dmsgs, $dm_array);
344         }
345
346         $this->showJsonObjects($dmsgs);
347         $this->endDocument('json');
348     }
349
350     /**
351      * Shows a list of direct messages as RSS items
352      *
353      * @return void
354      */
355     function showRssDirectMessages()
356     {
357         $this->initDocument('rss');
358
359         $this->element('title', null, $this->title);
360
361         $this->element('link', null, $this->link);
362         $this->element('description', null, $this->subtitle);
363         $this->element('language', null, 'en-us');
364
365         $this->element(
366             'atom:link',
367             array(
368                 'type' => 'application/rss+xml',
369                 'href' => $this->selfuri_base . '.rss',
370                 'rel' => self
371                 ),
372             null
373         );
374         $this->element('ttl', null, '40');
375
376         foreach ($this->messages as $m) {
377             $entry = $this->rssDirectMessageArray($m);
378             $this->showTwitterRssItem($entry);
379         }
380
381         $this->endTwitterRss();
382     }
383
384     /**
385      * Shows a list of direct messages as Atom entries
386      *
387      * @return void
388      */
389     function showAtomDirectMessages()
390     {
391         $this->initDocument('atom');
392
393         $this->element('title', null, $this->title);
394         $this->element('id', null, $this->id);
395
396         $selfuri = common_root_url() . 'api/direct_messages.atom';
397
398         $this->element(
399             'link', array(
400             'href' => $this->link,
401             'rel' => 'alternate',
402             'type' => 'text/html'),
403             null
404         );
405         $this->element(
406             'link', array(
407             'href' => $this->selfuri_base . '.atom', 'rel' => 'self',
408             'type' => 'application/atom+xml'),
409             null
410         );
411         $this->element('updated', null, common_date_iso8601('now'));
412         $this->element('subtitle', null, $this->subtitle);
413
414         foreach ($this->messages as $m) {
415             $entry = $this->rssDirectMessageArray($m);
416             $this->showTwitterAtomEntry($entry);
417         }
418
419         $this->endDocument('atom');
420     }
421
422     /**
423      * An entity tag for this notice
424      *
425      * Returns an Etag based on the action name, language, and
426      * timestamps of the notice
427      *
428      * @return string etag
429      */
430     function etag()
431     {
432         if (!empty($this->messages)) {
433
434             $last = count($this->messages) - 1;
435
436             return '"' . implode(
437                 ':',
438                 array($this->arg('action'),
439                       common_user_cache_hash($this->auth_user),
440                       common_language(),
441                       strtotime($this->messages[0]->created),
442                       strtotime($this->messages[$last]->created)
443                 )
444             )
445             . '"';
446         }
447
448         return null;
449     }
450 }