]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
73b22d58a030cea41a8afbd67121e755f26954ad
[quix0rs-gnu-social.git] / classes / Notice.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.     If not, see <http://www.gnu.org/licenses/>.
18  *
19  * @category Notices
20  * @package  StatusNet
21  * @author   Brenda Wallace <shiny@cpan.org>
22  * @author   Christopher Vollick <psycotica0@gmail.com>
23  * @author   CiaranG <ciaran@ciarang.com>
24  * @author   Craig Andrews <candrews@integralblue.com>
25  * @author   Evan Prodromou <evan@controlezvous.ca>
26  * @author   Gina Haeussge <osd@foosel.net>
27  * @author   Jeffery To <jeffery.to@gmail.com>
28  * @author   Mike Cochrane <mikec@mikenz.geek.nz>
29  * @author   Robin Millette <millette@controlyourself.ca>
30  * @author   Sarven Capadisli <csarven@controlyourself.ca>
31  * @author   Tom Adams <tom@holizz.com>
32  * @license  GNU Affero General Public License http://www.gnu.org/licenses/
33  */
34
35 if (!defined('STATUSNET') && !defined('LACONICA')) {
36     exit(1);
37 }
38
39 /**
40  * Table Definition for notice
41  */
42 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
43
44 /* We keep the first three 20-notice pages, plus one for pagination check,
45  * in the memcached cache. */
46
47 define('NOTICE_CACHE_WINDOW', 61);
48
49 define('MAX_BOXCARS', 128);
50
51 class Notice extends Memcached_DataObject
52 {
53     ###START_AUTOCODE
54     /* the code below is auto generated do not remove the above tag */
55
56     public $__table = 'notice';                          // table name
57     public $id;                              // int(4)  primary_key not_null
58     public $profile_id;                      // int(4)  multiple_key not_null
59     public $uri;                             // varchar(255)  unique_key
60     public $content;                         // text
61     public $rendered;                        // text
62     public $url;                             // varchar(255)
63     public $created;                         // datetime  multiple_key not_null default_0000-00-00%2000%3A00%3A00
64     public $modified;                        // timestamp   not_null default_CURRENT_TIMESTAMP
65     public $reply_to;                        // int(4)
66     public $is_local;                        // int(4)
67     public $source;                          // varchar(32)
68     public $conversation;                    // int(4)
69     public $lat;                             // decimal(10,7)
70     public $lon;                             // decimal(10,7)
71     public $location_id;                     // int(4)
72     public $location_ns;                     // int(4)
73     public $repeat_of;                       // int(4)
74
75     /* Static get */
76     function staticGet($k,$v=NULL)
77     {
78         return Memcached_DataObject::staticGet('Notice',$k,$v);
79     }
80
81     /* the code above is auto generated do not remove the tag below */
82     ###END_AUTOCODE
83
84     /* Notice types */
85     const LOCAL_PUBLIC    =  1;
86     const REMOTE_OMB      =  0;
87     const LOCAL_NONPUBLIC = -1;
88     const GATEWAY         = -2;
89
90     function getProfile()
91     {
92         return Profile::staticGet('id', $this->profile_id);
93     }
94
95     function delete()
96     {
97         // For auditing purposes, save a record that the notice
98         // was deleted.
99
100         $deleted = new Deleted_notice();
101
102         $deleted->id         = $this->id;
103         $deleted->profile_id = $this->profile_id;
104         $deleted->uri        = $this->uri;
105         $deleted->created    = $this->created;
106         $deleted->deleted    = common_sql_now();
107
108         $deleted->insert();
109
110         // Clear related records
111
112         $this->clearReplies();
113         $this->clearRepeats();
114         $this->clearFaves();
115         $this->clearTags();
116         $this->clearGroupInboxes();
117
118         // NOTE: we don't clear inboxes
119         // NOTE: we don't clear queue items
120
121         $result = parent::delete();
122     }
123
124     function saveTags()
125     {
126         /* extract all #hastags */
127         $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
128         if (!$count) {
129             return true;
130         }
131
132         //turn each into their canonical tag
133         //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
134         $hashtags = array();
135         for($i=0; $i<count($match[1]); $i++) {
136             $hashtags[] = common_canonical_tag($match[1][$i]);
137         }
138
139         /* Add them to the database */
140         foreach(array_unique($hashtags) as $hashtag) {
141             /* elide characters we don't want in the tag */
142             $this->saveTag($hashtag);
143             self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
144         }
145         return true;
146     }
147
148     function saveTag($hashtag)
149     {
150         $tag = new Notice_tag();
151         $tag->notice_id = $this->id;
152         $tag->tag = $hashtag;
153         $tag->created = $this->created;
154         $id = $tag->insert();
155
156         if (!$id) {
157             throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
158                                               $last_error->message));
159             return;
160         }
161
162         // if it's saved, blow its cache
163         $tag->blowCache(false);
164     }
165
166     /**
167      * Save a new notice and push it out to subscribers' inboxes.
168      * Poster's permissions are checked before sending.
169      *
170      * @param int $profile_id Profile ID of the poster
171      * @param string $content source message text; links may be shortened
172      *                        per current user's preference
173      * @param string $source source key ('web', 'api', etc)
174      * @param array $options Associative array of optional properties:
175      *              string 'created' timestamp of notice; defaults to now
176      *              int 'is_local' source/gateway ID, one of:
177      *                  Notice::LOCAL_PUBLIC    - Local, ok to appear in public timeline
178      *                  Notice::REMOTE_OMB      - Sent from a remote OMB service;
179      *                                            hide from public timeline but show in
180      *                                            local "and friends" timelines
181      *                  Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
182      *                  Notice::GATEWAY         - From another non-OMB service;
183      *                                            will not appear in public views
184      *              float 'lat' decimal latitude for geolocation
185      *              float 'lon' decimal longitude for geolocation
186      *              int 'location_id' geoname identifier
187      *              int 'location_ns' geoname namespace to interpret location_id
188      *              int 'reply_to'; notice ID this is a reply to
189      *              int 'repeat_of'; notice ID this is a repeat of
190      *              string 'uri' permalink to notice; defaults to local notice URL
191      *
192      * @return Notice
193      * @throws ClientException
194      */
195     static function saveNew($profile_id, $content, $source, $options=null) {
196         $defaults = array('uri' => null,
197                           'reply_to' => null,
198                           'repeat_of' => null);
199
200         if (!empty($options)) {
201             $options = $options + $defaults;
202             extract($options);
203         }
204
205         if (!isset($is_local)) {
206             $is_local = Notice::LOCAL_PUBLIC;
207         }
208
209         $profile = Profile::staticGet($profile_id);
210
211         $final = common_shorten_links($content);
212
213         if (Notice::contentTooLong($final)) {
214             throw new ClientException(_('Problem saving notice. Too long.'));
215         }
216
217         if (empty($profile)) {
218             throw new ClientException(_('Problem saving notice. Unknown user.'));
219         }
220
221         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
222             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
223             throw new ClientException(_('Too many notices too fast; take a breather '.
224                                         'and post again in a few minutes.'));
225         }
226
227         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
228             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
229             throw new ClientException(_('Too many duplicate messages too quickly;'.
230                                         ' take a breather and post again in a few minutes.'));
231         }
232
233         if (!$profile->hasRight(Right::NEWNOTICE)) {
234             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
235             throw new ClientException(_('You are banned from posting notices on this site.'));
236         }
237
238         $notice = new Notice();
239         $notice->profile_id = $profile_id;
240
241         $autosource = common_config('public', 'autosource');
242
243         # Sandboxed are non-false, but not 1, either
244
245         if (!$profile->hasRight(Right::PUBLICNOTICE) ||
246             ($source && $autosource && in_array($source, $autosource))) {
247             $notice->is_local = Notice::LOCAL_NONPUBLIC;
248         } else {
249             $notice->is_local = $is_local;
250         }
251
252         if (!empty($created)) {
253             $notice->created = $created;
254         } else {
255             $notice->created = common_sql_now();
256         }
257
258         $notice->content = $final;
259         $notice->rendered = common_render_content($final, $notice);
260         $notice->source = $source;
261         $notice->uri = $uri;
262
263         // Handle repeat case
264
265         if (isset($repeat_of)) {
266             $notice->repeat_of = $repeat_of;
267         } else {
268             $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
269         }
270
271         if (!empty($notice->reply_to)) {
272             $reply = Notice::staticGet('id', $notice->reply_to);
273             $notice->conversation = $reply->conversation;
274         }
275
276         if (!empty($lat) && !empty($lon)) {
277             $notice->lat = $lat;
278             $notice->lon = $lon;
279         }
280
281         if (!empty($location_ns) && !empty($location_id)) {
282             $notice->location_id = $location_id;
283             $notice->location_ns = $location_ns;
284         }
285
286         if (Event::handle('StartNoticeSave', array(&$notice))) {
287
288             // XXX: some of these functions write to the DB
289
290             $id = $notice->insert();
291
292             if (!$id) {
293                 common_log_db_error($notice, 'INSERT', __FILE__);
294                 throw new ServerException(_('Problem saving notice.'));
295             }
296
297             // Update ID-dependent columns: URI, conversation
298
299             $orig = clone($notice);
300
301             $changed = false;
302
303             if (empty($uri)) {
304                 $notice->uri = common_notice_uri($notice);
305                 $changed = true;
306             }
307
308             // If it's not part of a conversation, it's
309             // the beginning of a new conversation.
310
311             if (empty($notice->conversation)) {
312                 $notice->conversation = $notice->id;
313                 $changed = true;
314             }
315
316             if ($changed) {
317                 if (!$notice->update($orig)) {
318                     common_log_db_error($notice, 'UPDATE', __FILE__);
319                     throw new ServerException(_('Problem saving notice.'));
320                 }
321             }
322
323         }
324
325         # Clear the cache for subscribed users, so they'll update at next request
326         # XXX: someone clever could prepend instead of clearing the cache
327         $notice->blowOnInsert();
328
329         $notice->distribute();
330
331         return $notice;
332     }
333
334     function blowOnInsert()
335     {
336         self::blow('profile:notice_ids:%d', $this->profile_id);
337         self::blow('public');
338
339         if ($this->conversation != $this->id) {
340             self::blow('notice:conversation_ids:%d', $this->conversation);
341         }
342
343         if (!empty($this->repeat_of)) {
344             self::blow('notice:repeats:%d', $this->repeat_of);
345         }
346
347         $original = Notice::staticGet('id', $this->repeat_of);
348
349         if (!empty($original)) {
350             $originalUser = User::staticGet('id', $original->profile_id);
351             if (!empty($originalUser)) {
352                 self::blow('user:repeats_of_me:%d', $originalUser->id);
353             }
354         }
355
356         $profile = Profile::staticGet($this->profile_id);
357         $profile->blowNoticeCount();
358     }
359
360     /** save all urls in the notice to the db
361      *
362      * follow redirects and save all available file information
363      * (mimetype, date, size, oembed, etc.)
364      *
365      * @return void
366      */
367     function saveUrls() {
368         common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
369     }
370
371     function saveUrl($data) {
372         list($url, $notice_id) = $data;
373         File::processNew($url, $notice_id);
374     }
375
376     static function checkDupes($profile_id, $content) {
377         $profile = Profile::staticGet($profile_id);
378         if (empty($profile)) {
379             return false;
380         }
381         $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
382         if (!empty($notice)) {
383             $last = 0;
384             while ($notice->fetch()) {
385                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
386                     return true;
387                 } else if ($notice->content == $content) {
388                     return false;
389                 }
390             }
391         }
392         # If we get here, oldest item in cache window is not
393         # old enough for dupe limit; do direct check against DB
394         $notice = new Notice();
395         $notice->profile_id = $profile_id;
396         $notice->content = $content;
397         if (common_config('db','type') == 'pgsql')
398           $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
399         else
400           $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
401
402         $cnt = $notice->count();
403         return ($cnt == 0);
404     }
405
406     static function checkEditThrottle($profile_id) {
407         $profile = Profile::staticGet($profile_id);
408         if (empty($profile)) {
409             return false;
410         }
411         # Get the Nth notice
412         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
413         if ($notice && $notice->fetch()) {
414             # If the Nth notice was posted less than timespan seconds ago
415             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
416                 # Then we throttle
417                 return false;
418             }
419         }
420         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
421         return true;
422     }
423
424     function getUploadedAttachment() {
425         $post = clone $this;
426         $query = 'select file.url as up, file.id as i from file join file_to_post on file.id = file_id where post_id=' . $post->escape($post->id) . ' and url like "%/notice/%/file"';
427         $post->query($query);
428         $post->fetch();
429         if (empty($post->up) || empty($post->i)) {
430             $ret = false;
431         } else {
432             $ret = array($post->up, $post->i);
433         }
434         $post->free();
435         return $ret;
436     }
437
438     function hasAttachments() {
439         $post = clone $this;
440         $query = "select count(file_id) as n_attachments from file join file_to_post on (file_id = file.id) join notice on (post_id = notice.id) where post_id = " . $post->escape($post->id);
441         $post->query($query);
442         $post->fetch();
443         $n_attachments = intval($post->n_attachments);
444         $post->free();
445         return $n_attachments;
446     }
447
448     function attachments() {
449         // XXX: cache this
450         $att = array();
451         $f2p = new File_to_post;
452         $f2p->post_id = $this->id;
453         if ($f2p->find()) {
454             while ($f2p->fetch()) {
455                 $f = File::staticGet($f2p->file_id);
456                 $att[] = clone($f);
457             }
458         }
459         return $att;
460     }
461
462     function getStreamByIds($ids)
463     {
464         $cache = common_memcache();
465
466         if (!empty($cache)) {
467             $notices = array();
468             foreach ($ids as $id) {
469                 $n = Notice::staticGet('id', $id);
470                 if (!empty($n)) {
471                     $notices[] = $n;
472                 }
473             }
474             return new ArrayWrapper($notices);
475         } else {
476             $notice = new Notice();
477             if (empty($ids)) {
478                 //if no IDs requested, just return the notice object
479                 return $notice;
480             }
481             $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
482
483             $notice->find();
484
485             $temp = array();
486
487             while ($notice->fetch()) {
488                 $temp[$notice->id] = clone($notice);
489             }
490
491             $wrapped = array();
492
493             foreach ($ids as $id) {
494                 if (array_key_exists($id, $temp)) {
495                     $wrapped[] = $temp[$id];
496                 }
497             }
498
499             return new ArrayWrapper($wrapped);
500         }
501     }
502
503     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
504     {
505         $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
506                               array(),
507                               'public',
508                               $offset, $limit, $since_id, $max_id, $since);
509
510         return Notice::getStreamByIds($ids);
511     }
512
513     function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
514     {
515         $notice = new Notice();
516
517         $notice->selectAdd(); // clears it
518         $notice->selectAdd('id');
519
520         $notice->orderBy('id DESC');
521
522         if (!is_null($offset)) {
523             $notice->limit($offset, $limit);
524         }
525
526         if (common_config('public', 'localonly')) {
527             $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
528         } else {
529             # -1 == blacklisted, -2 == gateway (i.e. Twitter)
530             $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
531             $notice->whereAdd('is_local !='. Notice::GATEWAY);
532         }
533
534         if ($since_id != 0) {
535             $notice->whereAdd('id > ' . $since_id);
536         }
537
538         if ($max_id != 0) {
539             $notice->whereAdd('id <= ' . $max_id);
540         }
541
542         if (!is_null($since)) {
543             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
544         }
545
546         $ids = array();
547
548         if ($notice->find()) {
549             while ($notice->fetch()) {
550                 $ids[] = $notice->id;
551             }
552         }
553
554         $notice->free();
555         $notice = NULL;
556
557         return $ids;
558     }
559
560     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
561     {
562         $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
563                               array($id),
564                               'notice:conversation_ids:'.$id,
565                               $offset, $limit, $since_id, $max_id, $since);
566
567         return Notice::getStreamByIds($ids);
568     }
569
570     function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
571     {
572         $notice = new Notice();
573
574         $notice->selectAdd(); // clears it
575         $notice->selectAdd('id');
576
577         $notice->conversation = $id;
578
579         $notice->orderBy('id DESC');
580
581         if (!is_null($offset)) {
582             $notice->limit($offset, $limit);
583         }
584
585         if ($since_id != 0) {
586             $notice->whereAdd('id > ' . $since_id);
587         }
588
589         if ($max_id != 0) {
590             $notice->whereAdd('id <= ' . $max_id);
591         }
592
593         if (!is_null($since)) {
594             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
595         }
596
597         $ids = array();
598
599         if ($notice->find()) {
600             while ($notice->fetch()) {
601                 $ids[] = $notice->id;
602             }
603         }
604
605         $notice->free();
606         $notice = NULL;
607
608         return $ids;
609     }
610
611     /**
612      * @param $groups array of Group *objects*
613      * @param $recipients array of profile *ids*
614      */
615     function whoGets($groups=null, $recipients=null)
616     {
617         $c = self::memcache();
618
619         if (!empty($c)) {
620             $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
621             if ($ni !== false) {
622                 return $ni;
623             }
624         }
625
626         if (is_null($groups)) {
627             $groups = $this->getGroups();
628         }
629
630         if (is_null($recipients)) {
631             $recipients = $this->getReplies();
632         }
633
634         $users = $this->getSubscribedUsers();
635
636         // FIXME: kind of ignoring 'transitional'...
637         // we'll probably stop supporting inboxless mode
638         // in 0.9.x
639
640         $ni = array();
641
642         foreach ($users as $id) {
643             $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
644         }
645
646         $profile = $this->getProfile();
647
648         foreach ($groups as $group) {
649             $users = $group->getUserMembers();
650             foreach ($users as $id) {
651                 if (!array_key_exists($id, $ni)) {
652                     $user = User::staticGet('id', $id);
653                     if (!$user->hasBlocked($profile)) {
654                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
655                     }
656                 }
657             }
658         }
659
660         foreach ($recipients as $recipient) {
661
662             if (!array_key_exists($recipient, $ni)) {
663                 $recipientUser = User::staticGet('id', $recipient);
664                 if (!empty($recipientUser)) {
665                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
666                 }
667             }
668         }
669
670         if (!empty($c)) {
671             // XXX: pack this data better
672             $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
673         }
674
675         return $ni;
676     }
677
678     function addToInboxes($groups, $recipients)
679     {
680         $ni = $this->whoGets($groups, $recipients);
681
682         Inbox::bulkInsert($this->id, array_keys($ni));
683
684         return;
685     }
686
687     function getSubscribedUsers()
688     {
689         $user = new User();
690
691         if(common_config('db','quote_identifiers'))
692           $user_table = '"user"';
693         else $user_table = 'user';
694
695         $qry =
696           'SELECT id ' .
697           'FROM '. $user_table .' JOIN subscription '.
698           'ON '. $user_table .'.id = subscription.subscriber ' .
699           'WHERE subscription.subscribed = %d ';
700
701         $user->query(sprintf($qry, $this->profile_id));
702
703         $ids = array();
704
705         while ($user->fetch()) {
706             $ids[] = $user->id;
707         }
708
709         $user->free();
710
711         return $ids;
712     }
713
714     /**
715      * @return array of Group objects
716      */
717     function saveGroups()
718     {
719         // Don't save groups for repeats
720
721         if (!empty($this->repeat_of)) {
722             return array();
723         }
724
725         $groups = array();
726
727         /* extract all !group */
728         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
729                                 strtolower($this->content),
730                                 $match);
731         if (!$count) {
732             return $groups;
733         }
734
735         $profile = $this->getProfile();
736
737         /* Add them to the database */
738
739         foreach (array_unique($match[1]) as $nickname) {
740             /* XXX: remote groups. */
741             $group = User_group::getForNickname($nickname);
742
743             if (empty($group)) {
744                 continue;
745             }
746
747             // we automatically add a tag for every group name, too
748
749             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
750                                              'notice_id' => $this->id));
751
752             if (is_null($tag)) {
753                 $this->saveTag($nickname);
754             }
755
756             if ($profile->isMember($group)) {
757
758                 $result = $this->addToGroupInbox($group);
759
760                 if (!$result) {
761                     common_log_db_error($gi, 'INSERT', __FILE__);
762                 }
763
764                 $groups[] = clone($group);
765             }
766         }
767
768         return $groups;
769     }
770
771     function addToGroupInbox($group)
772     {
773         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
774                                          'notice_id' => $this->id));
775
776         if (empty($gi)) {
777
778             $gi = new Group_inbox();
779
780             $gi->group_id  = $group->id;
781             $gi->notice_id = $this->id;
782             $gi->created   = $this->created;
783
784             $result = $gi->insert();
785
786             if (!$result) {
787                 common_log_db_error($gi, 'INSERT', __FILE__);
788                 throw new ServerException(_('Problem saving group inbox.'));
789             }
790
791             self::blow('user_group:notice_ids:%d', $gi->group_id);
792         }
793
794         return true;
795     }
796
797     /**
798      * @return array of integer profile IDs
799      */
800     function saveReplies()
801     {
802         // Don't save reply data for repeats
803
804         if (!empty($this->repeat_of)) {
805             return array();
806         }
807
808         // Alternative reply format
809         $tname = false;
810         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
811             $tname = $match[1];
812         }
813         // extract all @messages
814         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
815
816         $names = array();
817
818         if ($cnt || $tname) {
819             // XXX: is there another way to make an array copy?
820             $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
821         }
822
823         $sender = Profile::staticGet($this->profile_id);
824
825         $replied = array();
826
827         // store replied only for first @ (what user/notice what the reply directed,
828         // we assume first @ is it)
829
830         for ($i=0; $i<count($names); $i++) {
831             $nickname = $names[$i];
832             $recipient = common_relative_profile($sender, $nickname, $this->created);
833             if (empty($recipient)) {
834                 continue;
835             }
836             // Don't save replies from blocked profile to local user
837             $recipient_user = User::staticGet('id', $recipient->id);
838             if (!empty($recipient_user) && $recipient_user->hasBlocked($sender)) {
839                 continue;
840             }
841             $reply = new Reply();
842             $reply->notice_id = $this->id;
843             $reply->profile_id = $recipient->id;
844             $id = $reply->insert();
845             if (!$id) {
846                 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
847                 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
848                 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
849                 return array();
850             } else {
851                 $replied[$recipient->id] = 1;
852             }
853         }
854
855         // Hash format replies, too
856         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
857         if ($cnt) {
858             foreach ($match[1] as $tag) {
859                 $tagged = Profile_tag::getTagged($sender->id, $tag);
860                 foreach ($tagged as $t) {
861                     if (!$replied[$t->id]) {
862                         // Don't save replies from blocked profile to local user
863                         $t_user = User::staticGet('id', $t->id);
864                         if ($t_user && $t_user->hasBlocked($sender)) {
865                             continue;
866                         }
867                         $reply = new Reply();
868                         $reply->notice_id = $this->id;
869                         $reply->profile_id = $t->id;
870                         $id = $reply->insert();
871                         if (!$id) {
872                             common_log_db_error($reply, 'INSERT', __FILE__);
873                             return array();
874                         } else {
875                             $replied[$recipient->id] = 1;
876                         }
877                     }
878                 }
879             }
880         }
881
882         $recipientIds = array_keys($replied);
883
884         foreach ($recipientIds as $recipientId) {
885             $user = User::staticGet('id', $recipientId);
886             if (!empty($user)) {
887                 self::blow('reply:stream:%d', $reply->profile_id);
888                 mail_notify_attn($user, $this);
889             }
890         }
891
892         return $recipientIds;
893     }
894
895     function getReplies()
896     {
897         // XXX: cache me
898
899         $ids = array();
900
901         $reply = new Reply();
902         $reply->selectAdd();
903         $reply->selectAdd('profile_id');
904         $reply->notice_id = $this->id;
905
906         if ($reply->find()) {
907             while($reply->fetch()) {
908                 $ids[] = $reply->profile_id;
909             }
910         }
911
912         $reply->free();
913
914         return $ids;
915     }
916
917     /**
918      * Same calculation as saveGroups but without the saving
919      * @fixme merge the functions
920      * @return array of Group_inbox objects
921      */
922     function getGroups()
923     {
924         // Don't save groups for repeats
925
926         if (!empty($this->repeat_of)) {
927             return array();
928         }
929
930         // XXX: cache me
931
932         $groups = array();
933
934         $gi = new Group_inbox();
935
936         $gi->selectAdd();
937         $gi->selectAdd('group_id');
938
939         $gi->notice_id = $this->id;
940
941         if ($gi->find()) {
942             while ($gi->fetch()) {
943                 $groups[] = clone($gi);
944             }
945         }
946
947         $gi->free();
948
949         return $groups;
950     }
951
952     function asAtomEntry($namespace=false, $source=false)
953     {
954         $profile = $this->getProfile();
955
956         $xs = new XMLStringer(true);
957
958         if ($namespace) {
959             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
960                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
961                            'xmlns:georss' => 'http://www.georss.org/georss',
962                            'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
963                            'xmlns:ostatus' => 'http://ostatus.org/schema/1.0');
964         } else {
965             $attrs = array();
966         }
967
968         $xs->elementStart('entry', $attrs);
969
970         if ($source) {
971             $xs->elementStart('source');
972             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
973             $xs->element('link', array('href' => $profile->profileurl));
974             $user = User::staticGet('id', $profile->id);
975             if (!empty($user)) {
976                 $atom_feed = common_local_url('ApiTimelineUser',
977                                               array('format' => 'atom',
978                                                     'id' => $profile->nickname));
979                 $xs->element('link', array('rel' => 'self',
980                                            'type' => 'application/atom+xml',
981                                            'href' => $profile->profileurl));
982                 $xs->element('link', array('rel' => 'license',
983                                            'href' => common_config('license', 'url')));
984             }
985
986             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
987         }
988
989         if ($source) {
990             $xs->elementEnd('source');
991         }
992
993         $xs->element('title', null, $this->content);
994         $xs->element('summary', null, $this->content);
995
996         $xs->raw($profile->asAtomAuthor());
997         $xs->raw($profile->asActivityActor());
998
999         $xs->element('link', array('rel' => 'alternate',
1000                                    'href' => $this->bestUrl()));
1001
1002         $xs->element('id', null, $this->uri);
1003
1004         $xs->element('published', null, common_date_w3dtf($this->created));
1005         $xs->element('updated', null, common_date_w3dtf($this->created));
1006
1007         if ($this->reply_to) {
1008             $reply_notice = Notice::staticGet('id', $this->reply_to);
1009             if (!empty($reply_notice)) {
1010                 $xs->element('link', array('rel' => 'related',
1011                                            'href' => $reply_notice->bestUrl()));
1012                 $xs->element('thr:in-reply-to',
1013                              array('ref' => $reply_notice->uri,
1014                                    'href' => $reply_notice->bestUrl()));
1015             }
1016         }
1017
1018         if (!empty($this->conversation)
1019             && $this->conversation != $this->id) {
1020             $xs->element(
1021                 'link', array(
1022                     'rel' => 'ostatus:conversation',
1023                     'href' => common_local_url(
1024                         'conversation',
1025                         array('id' => $this->conversation)
1026                         )
1027                     )
1028                 );
1029         }
1030
1031         $reply_ids = $this->getReplies();
1032
1033         foreach ($reply_ids as $id) {
1034             $profile = Profile::staticGet('id', $id);
1035             if (!empty($profile)) {
1036                 $xs->element(
1037                     'link', array(
1038                         'rel' => 'ostatus:attention',
1039                         'href' => $profile->getAcctUri()
1040                     )
1041                 );
1042             }
1043         }
1044
1045         if (!empty($this->repeat_of)) {
1046             $repeat = Notice::staticGet('id', $this->repeat_of);
1047             if (!empty($repeat)) {
1048                 $xs->element(
1049                     'ostatus:forward',
1050                      array('ref' => $repeat->uri, 'href' => $repeat->bestUrl())
1051                 );
1052             }
1053         }
1054
1055         $xs->element('content', array('type' => 'html'), $this->rendered);
1056
1057         $tag = new Notice_tag();
1058         $tag->notice_id = $this->id;
1059         if ($tag->find()) {
1060             while ($tag->fetch()) {
1061                 $xs->element('category', array('term' => $tag->tag));
1062             }
1063         }
1064         $tag->free();
1065
1066         # Enclosures
1067         $attachments = $this->attachments();
1068         if($attachments){
1069             foreach($attachments as $attachment){
1070                 $enclosure=$attachment->getEnclosure();
1071                 if ($enclosure) {
1072                     $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1073                     if($enclosure->title){
1074                         $attributes['title']=$enclosure->title;
1075                     }
1076                     $xs->element('link', $attributes, null);
1077                 }
1078             }
1079         }
1080
1081         if (!empty($this->lat) && !empty($this->lon)) {
1082             $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1083         }
1084
1085         $xs->elementEnd('entry');
1086
1087         return $xs->getString();
1088     }
1089
1090     function bestUrl()
1091     {
1092         if (!empty($this->url)) {
1093             return $this->url;
1094         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1095             return $this->uri;
1096         } else {
1097             return common_local_url('shownotice',
1098                                     array('notice' => $this->id));
1099         }
1100     }
1101
1102     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1103     {
1104         $cache = common_memcache();
1105
1106         if (empty($cache) ||
1107             $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1108             is_null($limit) ||
1109             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1110             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1111                                                                       $max_id, $since)));
1112         }
1113
1114         $idkey = common_cache_key($cachekey);
1115
1116         $idstr = $cache->get($idkey);
1117
1118         if ($idstr !== false) {
1119             // Cache hit! Woohoo!
1120             $window = explode(',', $idstr);
1121             $ids = array_slice($window, $offset, $limit);
1122             return $ids;
1123         }
1124
1125         $laststr = $cache->get($idkey.';last');
1126
1127         if ($laststr !== false) {
1128             $window = explode(',', $laststr);
1129             $last_id = $window[0];
1130             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1131                                                                           $last_id, 0, null)));
1132
1133             $new_window = array_merge($new_ids, $window);
1134
1135             $new_windowstr = implode(',', $new_window);
1136
1137             $result = $cache->set($idkey, $new_windowstr);
1138             $result = $cache->set($idkey . ';last', $new_windowstr);
1139
1140             $ids = array_slice($new_window, $offset, $limit);
1141
1142             return $ids;
1143         }
1144
1145         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1146                                                                      0, 0, null)));
1147
1148         $windowstr = implode(',', $window);
1149
1150         $result = $cache->set($idkey, $windowstr);
1151         $result = $cache->set($idkey . ';last', $windowstr);
1152
1153         $ids = array_slice($window, $offset, $limit);
1154
1155         return $ids;
1156     }
1157
1158     /**
1159      * Determine which notice, if any, a new notice is in reply to.
1160      *
1161      * For conversation tracking, we try to see where this notice fits
1162      * in the tree. Rough algorithm is:
1163      *
1164      * if (reply_to is set and valid) {
1165      *     return reply_to;
1166      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1167      *     return ID of last notice by initial @name in content;
1168      * }
1169      *
1170      * Note that all @nickname instances will still be used to save "reply" records,
1171      * so the notice shows up in the mentioned users' "replies" tab.
1172      *
1173      * @param integer $reply_to   ID passed in by Web or API
1174      * @param integer $profile_id ID of author
1175      * @param string  $source     Source tag, like 'web' or 'gwibber'
1176      * @param string  $content    Final notice content
1177      *
1178      * @return integer ID of replied-to notice, or null for not a reply.
1179      */
1180
1181     static function getReplyTo($reply_to, $profile_id, $source, $content)
1182     {
1183         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1184
1185         // If $reply_to is specified, we check that it exists, and then
1186         // return it if it does
1187
1188         if (!empty($reply_to)) {
1189             $reply_notice = Notice::staticGet('id', $reply_to);
1190             if (!empty($reply_notice)) {
1191                 return $reply_to;
1192             }
1193         }
1194
1195         // If it's not a "low bandwidth" source (one where you can't set
1196         // a reply_to argument), we return. This is mostly web and API
1197         // clients.
1198
1199         if (!in_array($source, $lb)) {
1200             return null;
1201         }
1202
1203         // Is there an initial @ or T?
1204
1205         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1206             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1207             $nickname = common_canonical_nickname($match[1]);
1208         } else {
1209             return null;
1210         }
1211
1212         // Figure out who that is.
1213
1214         $sender = Profile::staticGet('id', $profile_id);
1215         if (empty($sender)) {
1216             return null;
1217         }
1218
1219         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1220
1221         if (empty($recipient)) {
1222             return null;
1223         }
1224
1225         // Get their last notice
1226
1227         $last = $recipient->getCurrentNotice();
1228
1229         if (!empty($last)) {
1230             return $last->id;
1231         }
1232     }
1233
1234     static function maxContent()
1235     {
1236         $contentlimit = common_config('notice', 'contentlimit');
1237         // null => use global limit (distinct from 0!)
1238         if (is_null($contentlimit)) {
1239             $contentlimit = common_config('site', 'textlimit');
1240         }
1241         return $contentlimit;
1242     }
1243
1244     static function contentTooLong($content)
1245     {
1246         $contentlimit = self::maxContent();
1247         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1248     }
1249
1250     function getLocation()
1251     {
1252         $location = null;
1253
1254         if (!empty($this->location_id) && !empty($this->location_ns)) {
1255             $location = Location::fromId($this->location_id, $this->location_ns);
1256         }
1257
1258         if (is_null($location)) { // no ID, or Location::fromId() failed
1259             if (!empty($this->lat) && !empty($this->lon)) {
1260                 $location = Location::fromLatLon($this->lat, $this->lon);
1261             }
1262         }
1263
1264         return $location;
1265     }
1266
1267     function repeat($repeater_id, $source)
1268     {
1269         $author = Profile::staticGet('id', $this->profile_id);
1270
1271         $content = sprintf(_('RT @%1$s %2$s'),
1272                            $author->nickname,
1273                            $this->content);
1274
1275         $maxlen = common_config('site', 'textlimit');
1276         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1277             // Web interface and current Twitter API clients will
1278             // pull the original notice's text, but some older
1279             // clients and RSS/Atom feeds will see this trimmed text.
1280             //
1281             // Unfortunately this is likely to lose tags or URLs
1282             // at the end of long notices.
1283             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1284         }
1285
1286         return self::saveNew($repeater_id, $content, $source,
1287                              array('repeat_of' => $this->id));
1288     }
1289
1290     // These are supposed to be in chron order!
1291
1292     function repeatStream($limit=100)
1293     {
1294         $cache = common_memcache();
1295
1296         if (empty($cache)) {
1297             $ids = $this->_repeatStreamDirect($limit);
1298         } else {
1299             $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1300             if ($idstr !== false) {
1301                 $ids = explode(',', $idstr);
1302             } else {
1303                 $ids = $this->_repeatStreamDirect(100);
1304                 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1305             }
1306             if ($limit < 100) {
1307                 // We do a max of 100, so slice down to limit
1308                 $ids = array_slice($ids, 0, $limit);
1309             }
1310         }
1311
1312         return Notice::getStreamByIds($ids);
1313     }
1314
1315     function _repeatStreamDirect($limit)
1316     {
1317         $notice = new Notice();
1318
1319         $notice->selectAdd(); // clears it
1320         $notice->selectAdd('id');
1321
1322         $notice->repeat_of = $this->id;
1323
1324         $notice->orderBy('created'); // NB: asc!
1325
1326         if (!is_null($offset)) {
1327             $notice->limit($offset, $limit);
1328         }
1329
1330         $ids = array();
1331
1332         if ($notice->find()) {
1333             while ($notice->fetch()) {
1334                 $ids[] = $notice->id;
1335             }
1336         }
1337
1338         $notice->free();
1339         $notice = NULL;
1340
1341         return $ids;
1342     }
1343
1344     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1345     {
1346         $options = array();
1347
1348         if (!empty($location_id) && !empty($location_ns)) {
1349
1350             $options['location_id'] = $location_id;
1351             $options['location_ns'] = $location_ns;
1352
1353             $location = Location::fromId($location_id, $location_ns);
1354
1355             if (!empty($location)) {
1356                 $options['lat'] = $location->lat;
1357                 $options['lon'] = $location->lon;
1358             }
1359
1360         } else if (!empty($lat) && !empty($lon)) {
1361
1362             $options['lat'] = $lat;
1363             $options['lon'] = $lon;
1364
1365             $location = Location::fromLatLon($lat, $lon);
1366
1367             if (!empty($location)) {
1368                 $options['location_id'] = $location->location_id;
1369                 $options['location_ns'] = $location->location_ns;
1370             }
1371         } else if (!empty($profile)) {
1372
1373             if (isset($profile->lat) && isset($profile->lon)) {
1374                 $options['lat'] = $profile->lat;
1375                 $options['lon'] = $profile->lon;
1376             }
1377
1378             if (isset($profile->location_id) && isset($profile->location_ns)) {
1379                 $options['location_id'] = $profile->location_id;
1380                 $options['location_ns'] = $profile->location_ns;
1381             }
1382         }
1383
1384         return $options;
1385     }
1386
1387     function clearReplies()
1388     {
1389         $replyNotice = new Notice();
1390         $replyNotice->reply_to = $this->id;
1391
1392         //Null any notices that are replies to this notice
1393
1394         if ($replyNotice->find()) {
1395             while ($replyNotice->fetch()) {
1396                 $orig = clone($replyNotice);
1397                 $replyNotice->reply_to = null;
1398                 $replyNotice->update($orig);
1399             }
1400         }
1401
1402         // Reply records
1403
1404         $reply = new Reply();
1405         $reply->notice_id = $this->id;
1406
1407         if ($reply->find()) {
1408             while($reply->fetch()) {
1409                 self::blow('reply:stream:%d', $reply->profile_id);
1410                 $reply->delete();
1411             }
1412         }
1413
1414         $reply->free();
1415     }
1416
1417     function clearRepeats()
1418     {
1419         $repeatNotice = new Notice();
1420         $repeatNotice->repeat_of = $this->id;
1421
1422         //Null any notices that are repeats of this notice
1423
1424         if ($repeatNotice->find()) {
1425             while ($repeatNotice->fetch()) {
1426                 $orig = clone($repeatNotice);
1427                 $repeatNotice->repeat_of = null;
1428                 $repeatNotice->update($orig);
1429             }
1430         }
1431     }
1432
1433     function clearFaves()
1434     {
1435         $fave = new Fave();
1436         $fave->notice_id = $this->id;
1437
1438         if ($fave->find()) {
1439             while ($fave->fetch()) {
1440                 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1441                 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1442                 self::blow('fave:ids_by_user:%d', $fave->user_id);
1443                 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1444                 $fave->delete();
1445             }
1446         }
1447
1448         $fave->free();
1449     }
1450
1451     function clearTags()
1452     {
1453         $tag = new Notice_tag();
1454         $tag->notice_id = $this->id;
1455
1456         if ($tag->find()) {
1457             while ($tag->fetch()) {
1458                 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
1459                 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
1460                 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
1461                 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
1462                 $tag->delete();
1463             }
1464         }
1465
1466         $tag->free();
1467     }
1468
1469     function clearGroupInboxes()
1470     {
1471         $gi = new Group_inbox();
1472
1473         $gi->notice_id = $this->id;
1474
1475         if ($gi->find()) {
1476             while ($gi->fetch()) {
1477                 self::blow('user_group:notice_ids:%d', $gi->group_id);
1478                 $gi->delete();
1479             }
1480         }
1481
1482         $gi->free();
1483     }
1484
1485     function distribute()
1486     {
1487         if (common_config('queue', 'inboxes')) {
1488             // If there's a failure, we want to _force_
1489             // distribution at this point.
1490             try {
1491                 $qm = QueueManager::get();
1492                 $qm->enqueue($this, 'distrib');
1493             } catch (Exception $e) {
1494                 // If the exception isn't transient, this
1495                 // may throw more exceptions as DQH does
1496                 // its own enqueueing. So, we ignore them!
1497                 try {
1498                     $handler = new DistribQueueHandler();
1499                     $handler->handle($this);
1500                 } catch (Exception $e) {
1501                     common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1502                 }
1503                 // Re-throw so somebody smarter can handle it.
1504                 throw $e;
1505             }
1506         } else {
1507             $handler = new DistribQueueHandler();
1508             $handler->handle($this);
1509         }
1510     }
1511
1512     function insert()
1513     {
1514         $result = parent::insert();
1515
1516         if ($result) {
1517             // Profile::hasRepeated() abuses pkeyGet(), so we
1518             // have to clear manually
1519             if (!empty($this->repeat_of)) {
1520                 $c = self::memcache();
1521                 if (!empty($c)) {
1522                     $ck = self::multicacheKey('Notice',
1523                                               array('profile_id' => $this->profile_id,
1524                                                     'repeat_of' => $this->repeat_of));
1525                     $c->delete($ck);
1526                 }
1527             }
1528         }
1529
1530         return $result;
1531     }
1532 }