]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/DirectMessage/actions/apidirectmessage.php
DirectMessagePlugin actions modernified
[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     /**
114      * Handle the request
115      *
116      * Show the messages
117      *
118      * @param array $args $_REQUEST data (unused)
119      *
120      * @return void
121      */
122     function handle($args)
123     {
124         parent::handle($args);
125         $this->showMessages();
126     }
127
128     /**
129      * Show the messages
130      *
131      * @return void
132      */
133     function showMessages()
134     {
135         switch($this->format) {
136         case 'xml':
137             $this->showXmlDirectMessages();
138             break;
139         case 'rss':
140             $this->showRssDirectMessages();
141             break;
142         case 'atom':
143             $this->showAtomDirectMessages();
144             break;
145         case 'json':
146             $this->showJsonDirectMessages();
147             break;
148         default:
149             // TRANS: Client error displayed when coming across a non-supported API method.
150             $this->clientError(_('API method not found.'), $code = 404);
151             break;
152         }
153     }
154
155     /**
156      * Get notices
157      *
158      * @return array notices
159      */
160     function getMessages()
161     {
162         $message  = new Message();
163
164         if ($this->arg('sent')) {
165             $message->from_profile = $this->scoped->getID();
166         } else {
167             $message->to_profile = $this->scoped->getID();
168         }
169
170         if (!empty($this->max_id)) {
171             $message->whereAdd('id <= ' . $this->max_id);
172         }
173
174         if (!empty($this->since_id)) {
175             $message->whereAdd('id > ' . $this->since_id);
176         }
177
178         $message->orderBy('created DESC, id DESC');
179         $message->limit((($this->page - 1) * $this->count), $this->count);
180         $message->find();
181
182         $messages = array();
183
184         while ($message->fetch()) {
185             $messages[] = clone($message);
186         }
187
188         return $messages;
189     }
190
191     /**
192      * Is this action read only?
193      *
194      * @param array $args other arguments
195      *
196      * @return boolean true
197      */
198     function isReadOnly($args)
199     {
200         return true;
201     }
202
203     /**
204      * When was this notice last modified?
205      *
206      * @return string datestamp of the latest notice in the stream
207      */
208     function lastModified()
209     {
210         if (!empty($this->messages)) {
211             return strtotime($this->messages[0]->created);
212         }
213
214         return null;
215     }
216
217     // BEGIN import from lib/apiaction.php
218
219     function showSingleXmlDirectMessage($message)
220     {
221         $this->initDocument('xml');
222         $dmsg = $this->directMessageArray($message);
223         $this->showXmlDirectMessage($dmsg, true);
224         $this->endDocument('xml');
225     }
226
227     function showSingleJsonDirectMessage($message)
228     {
229         $this->initDocument('json');
230         $dmsg = $this->directMessageArray($message);
231         $this->showJsonObjects($dmsg);
232         $this->endDocument('json');
233     }
234
235     function showXmlDirectMessage($dm, $namespaces=false)
236     {
237         $attrs = array();
238         if ($namespaces) {
239             $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
240         }
241         $this->elementStart('direct_message', $attrs);
242         foreach($dm as $element => $value) {
243             switch ($element) {
244             case 'sender':
245             case 'recipient':
246                 $this->showTwitterXmlUser($value, $element);
247                 break;
248             case 'text':
249                 $this->element($element, null, common_xml_safe_str($value));
250                 break;
251             default:
252                 $this->element($element, null, $value);
253                 break;
254             }
255         }
256         $this->elementEnd('direct_message');
257     }
258
259     function directMessageArray($message)
260     {
261         $dmsg = array();
262
263         $from_profile = $message->getFrom();
264         $to_profile = $message->getTo();
265
266         $dmsg['id'] = intval($message->id);
267         $dmsg['sender_id'] = intval($from_profile->id);
268         $dmsg['text'] = trim($message->content);
269         $dmsg['recipient_id'] = intval($to_profile->id);
270         $dmsg['created_at'] = $this->dateTwitter($message->created);
271         $dmsg['sender_screen_name'] = $from_profile->nickname;
272         $dmsg['recipient_screen_name'] = $to_profile->nickname;
273         $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
274         $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
275
276         return $dmsg;
277     }
278
279     function rssDirectMessageArray($message)
280     {
281         $entry = array();
282
283         $from = $message->getFrom();
284
285         $entry['title'] = sprintf('Message from %1$s to %2$s',
286             $from->nickname, $message->getTo()->nickname);
287
288         $entry['content'] = common_xml_safe_str($message->rendered);
289         $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
290         $entry['published'] = common_date_iso8601($message->created);
291
292         $taguribase = TagURI::base();
293
294         $entry['id'] = "tag:$taguribase:$entry[link]";
295         $entry['updated'] = $entry['published'];
296
297         $entry['author-name'] = $from->getBestName();
298         $entry['author-uri'] = $from->homepage;
299
300         $entry['avatar'] = $from->avatarUrl(AVATAR_STREAM_SIZE);
301         try {
302             $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
303             $entry['avatar-type'] = $avatar->mediatype;
304         } catch (Exception $e) {
305             $entry['avatar-type'] = 'image/png';
306         }
307
308         // RSS item specific
309
310         $entry['description'] = $entry['content'];
311         $entry['pubDate'] = common_date_rfc2822($message->created);
312         $entry['guid'] = $entry['link'];
313
314         return $entry;
315     }
316
317     // END import from lib/apiaction.php
318
319     /**
320      * Shows a list of direct messages as Twitter-style XML array
321      *
322      * @return void
323      */
324     function showXmlDirectMessages()
325     {
326         $this->initDocument('xml');
327         $this->elementStart('direct-messages', array('type' => 'array',
328                                                      'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
329
330         foreach ($this->messages as $m) {
331             $dm_array = $this->directMessageArray($m);
332             $this->showXmlDirectMessage($dm_array);
333         }
334
335         $this->elementEnd('direct-messages');
336         $this->endDocument('xml');
337     }
338
339     /**
340      * Shows a list of direct messages as a JSON encoded array
341      *
342      * @return void
343      */
344     function showJsonDirectMessages()
345     {
346         $this->initDocument('json');
347
348         $dmsgs = array();
349
350         foreach ($this->messages as $m) {
351             $dm_array = $this->directMessageArray($m);
352             array_push($dmsgs, $dm_array);
353         }
354
355         $this->showJsonObjects($dmsgs);
356         $this->endDocument('json');
357     }
358
359     /**
360      * Shows a list of direct messages as RSS items
361      *
362      * @return void
363      */
364     function showRssDirectMessages()
365     {
366         $this->initDocument('rss');
367
368         $this->element('title', null, $this->title);
369
370         $this->element('link', null, $this->link);
371         $this->element('description', null, $this->subtitle);
372         $this->element('language', null, 'en-us');
373
374         $this->element(
375             'atom:link',
376             array(
377                 'type' => 'application/rss+xml',
378                 'href' => $this->selfuri_base . '.rss',
379                 'rel' => self
380                 ),
381             null
382         );
383         $this->element('ttl', null, '40');
384
385         foreach ($this->messages as $m) {
386             $entry = $this->rssDirectMessageArray($m);
387             $this->showTwitterRssItem($entry);
388         }
389
390         $this->endTwitterRss();
391     }
392
393     /**
394      * Shows a list of direct messages as Atom entries
395      *
396      * @return void
397      */
398     function showAtomDirectMessages()
399     {
400         $this->initDocument('atom');
401
402         $this->element('title', null, $this->title);
403         $this->element('id', null, $this->id);
404
405         $selfuri = common_root_url() . 'api/direct_messages.atom';
406
407         $this->element(
408             'link', array(
409             'href' => $this->link,
410             'rel' => 'alternate',
411             'type' => 'text/html'),
412             null
413         );
414         $this->element(
415             'link', array(
416             'href' => $this->selfuri_base . '.atom', 'rel' => 'self',
417             'type' => 'application/atom+xml'),
418             null
419         );
420         $this->element('updated', null, common_date_iso8601('now'));
421         $this->element('subtitle', null, $this->subtitle);
422
423         foreach ($this->messages as $m) {
424             $entry = $this->rssDirectMessageArray($m);
425             $this->showTwitterAtomEntry($entry);
426         }
427
428         $this->endDocument('atom');
429     }
430
431     /**
432      * An entity tag for this notice
433      *
434      * Returns an Etag based on the action name, language, and
435      * timestamps of the notice
436      *
437      * @return string etag
438      */
439     function etag()
440     {
441         if (!empty($this->messages)) {
442
443             $last = count($this->messages) - 1;
444
445             return '"' . implode(
446                 ':',
447                 array($this->arg('action'),
448                       common_user_cache_hash($this->auth_user),
449                       common_language(),
450                       strtotime($this->messages[0]->created),
451                       strtotime($this->messages[$last]->created)
452                 )
453             )
454             . '"';
455         }
456
457         return null;
458     }
459 }