]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
fix notice -- drop unused return value of variable that isn't initialized :) thx...
[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, $tag->tag);
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         if (common_config('queue', 'inboxes')) {
330             $qm = QueueManager::get();
331             $qm->enqueue($notice, 'distrib');
332         } else {
333             $handler = new DistribQueueHandler();
334             $handler->handle($notice);
335         }
336
337         return $notice;
338     }
339
340     function blowOnInsert()
341     {
342         self::blow('profile:notice_ids:%d', $this->profile_id);
343         self::blow('public');
344
345         if ($this->conversation != $this->id) {
346             self::blow('notice:conversation_ids:%d', $this->conversation);
347         }
348
349         if (!empty($this->repeat_of)) {
350             self::blow('notice:repeats:%d', $this->repeat_of);
351         }
352
353         $original = Notice::staticGet('id', $this->repeat_of);
354
355         if (!empty($original)) {
356             $originalUser = User::staticGet('id', $original->profile_id);
357             if (!empty($originalUser)) {
358                 self::blow('user:repeats_of_me:%d', $originalUser->id);
359             }
360         }
361
362         $profile = Profile::staticGet($this->profile_id);
363         $profile->blowNoticeCount();
364     }
365
366     /** save all urls in the notice to the db
367      *
368      * follow redirects and save all available file information
369      * (mimetype, date, size, oembed, etc.)
370      *
371      * @return void
372      */
373     function saveUrls() {
374         common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
375     }
376
377     function saveUrl($data) {
378         list($url, $notice_id) = $data;
379         File::processNew($url, $notice_id);
380     }
381
382     static function checkDupes($profile_id, $content) {
383         $profile = Profile::staticGet($profile_id);
384         if (empty($profile)) {
385             return false;
386         }
387         $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
388         if (!empty($notice)) {
389             $last = 0;
390             while ($notice->fetch()) {
391                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
392                     return true;
393                 } else if ($notice->content == $content) {
394                     return false;
395                 }
396             }
397         }
398         # If we get here, oldest item in cache window is not
399         # old enough for dupe limit; do direct check against DB
400         $notice = new Notice();
401         $notice->profile_id = $profile_id;
402         $notice->content = $content;
403         if (common_config('db','type') == 'pgsql')
404           $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
405         else
406           $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
407
408         $cnt = $notice->count();
409         return ($cnt == 0);
410     }
411
412     static function checkEditThrottle($profile_id) {
413         $profile = Profile::staticGet($profile_id);
414         if (empty($profile)) {
415             return false;
416         }
417         # Get the Nth notice
418         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
419         if ($notice && $notice->fetch()) {
420             # If the Nth notice was posted less than timespan seconds ago
421             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
422                 # Then we throttle
423                 return false;
424             }
425         }
426         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
427         return true;
428     }
429
430     function getUploadedAttachment() {
431         $post = clone $this;
432         $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"';
433         $post->query($query);
434         $post->fetch();
435         if (empty($post->up) || empty($post->i)) {
436             $ret = false;
437         } else {
438             $ret = array($post->up, $post->i);
439         }
440         $post->free();
441         return $ret;
442     }
443
444     function hasAttachments() {
445         $post = clone $this;
446         $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);
447         $post->query($query);
448         $post->fetch();
449         $n_attachments = intval($post->n_attachments);
450         $post->free();
451         return $n_attachments;
452     }
453
454     function attachments() {
455         // XXX: cache this
456         $att = array();
457         $f2p = new File_to_post;
458         $f2p->post_id = $this->id;
459         if ($f2p->find()) {
460             while ($f2p->fetch()) {
461                 $f = File::staticGet($f2p->file_id);
462                 $att[] = clone($f);
463             }
464         }
465         return $att;
466     }
467
468     function getStreamByIds($ids)
469     {
470         $cache = common_memcache();
471
472         if (!empty($cache)) {
473             $notices = array();
474             foreach ($ids as $id) {
475                 $n = Notice::staticGet('id', $id);
476                 if (!empty($n)) {
477                     $notices[] = $n;
478                 }
479             }
480             return new ArrayWrapper($notices);
481         } else {
482             $notice = new Notice();
483             if (empty($ids)) {
484                 //if no IDs requested, just return the notice object
485                 return $notice;
486             }
487             $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
488
489             $notice->find();
490
491             $temp = array();
492
493             while ($notice->fetch()) {
494                 $temp[$notice->id] = clone($notice);
495             }
496
497             $wrapped = array();
498
499             foreach ($ids as $id) {
500                 if (array_key_exists($id, $temp)) {
501                     $wrapped[] = $temp[$id];
502                 }
503             }
504
505             return new ArrayWrapper($wrapped);
506         }
507     }
508
509     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
510     {
511         $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
512                               array(),
513                               'public',
514                               $offset, $limit, $since_id, $max_id, $since);
515
516         return Notice::getStreamByIds($ids);
517     }
518
519     function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
520     {
521         $notice = new Notice();
522
523         $notice->selectAdd(); // clears it
524         $notice->selectAdd('id');
525
526         $notice->orderBy('id DESC');
527
528         if (!is_null($offset)) {
529             $notice->limit($offset, $limit);
530         }
531
532         if (common_config('public', 'localonly')) {
533             $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
534         } else {
535             # -1 == blacklisted, -2 == gateway (i.e. Twitter)
536             $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
537             $notice->whereAdd('is_local !='. Notice::GATEWAY);
538         }
539
540         if ($since_id != 0) {
541             $notice->whereAdd('id > ' . $since_id);
542         }
543
544         if ($max_id != 0) {
545             $notice->whereAdd('id <= ' . $max_id);
546         }
547
548         if (!is_null($since)) {
549             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
550         }
551
552         $ids = array();
553
554         if ($notice->find()) {
555             while ($notice->fetch()) {
556                 $ids[] = $notice->id;
557             }
558         }
559
560         $notice->free();
561         $notice = NULL;
562
563         return $ids;
564     }
565
566     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
567     {
568         $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
569                               array($id),
570                               'notice:conversation_ids:'.$id,
571                               $offset, $limit, $since_id, $max_id, $since);
572
573         return Notice::getStreamByIds($ids);
574     }
575
576     function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
577     {
578         $notice = new Notice();
579
580         $notice->selectAdd(); // clears it
581         $notice->selectAdd('id');
582
583         $notice->conversation = $id;
584
585         $notice->orderBy('id DESC');
586
587         if (!is_null($offset)) {
588             $notice->limit($offset, $limit);
589         }
590
591         if ($since_id != 0) {
592             $notice->whereAdd('id > ' . $since_id);
593         }
594
595         if ($max_id != 0) {
596             $notice->whereAdd('id <= ' . $max_id);
597         }
598
599         if (!is_null($since)) {
600             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
601         }
602
603         $ids = array();
604
605         if ($notice->find()) {
606             while ($notice->fetch()) {
607                 $ids[] = $notice->id;
608             }
609         }
610
611         $notice->free();
612         $notice = NULL;
613
614         return $ids;
615     }
616
617     /**
618      * @param $groups array of Group *objects*
619      * @param $recipients array of profile *ids*
620      */
621     function whoGets($groups=null, $recipients=null)
622     {
623         $c = self::memcache();
624
625         if (!empty($c)) {
626             $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
627             if ($ni !== false) {
628                 return $ni;
629             }
630         }
631
632         if (is_null($groups)) {
633             $groups = $this->getGroups();
634         }
635
636         if (is_null($recipients)) {
637             $recipients = $this->getReplies();
638         }
639
640         $users = $this->getSubscribedUsers();
641
642         // FIXME: kind of ignoring 'transitional'...
643         // we'll probably stop supporting inboxless mode
644         // in 0.9.x
645
646         $ni = array();
647
648         foreach ($users as $id) {
649             $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
650         }
651
652         $profile = $this->getProfile();
653
654         foreach ($groups as $group) {
655             $users = $group->getUserMembers();
656             foreach ($users as $id) {
657                 if (!array_key_exists($id, $ni)) {
658                     $user = User::staticGet('id', $id);
659                     if (!$user->hasBlocked($profile)) {
660                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
661                     }
662                 }
663             }
664         }
665
666         foreach ($recipients as $recipient) {
667
668             if (!array_key_exists($recipient, $ni)) {
669                 $recipientUser = User::staticGet('id', $recipient);
670                 if (!empty($recipientUser)) {
671                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
672                 }
673             }
674         }
675
676         if (!empty($c)) {
677             // XXX: pack this data better
678             $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
679         }
680
681         return $ni;
682     }
683
684     function addToInboxes($groups, $recipients)
685     {
686         $ni = $this->whoGets($groups, $recipients);
687
688         Inbox::bulkInsert($this->id, array_keys($ni));
689
690         return;
691     }
692
693     function getSubscribedUsers()
694     {
695         $user = new User();
696
697         if(common_config('db','quote_identifiers'))
698           $user_table = '"user"';
699         else $user_table = 'user';
700
701         $qry =
702           'SELECT id ' .
703           'FROM '. $user_table .' JOIN subscription '.
704           'ON '. $user_table .'.id = subscription.subscriber ' .
705           'WHERE subscription.subscribed = %d ';
706
707         $user->query(sprintf($qry, $this->profile_id));
708
709         $ids = array();
710
711         while ($user->fetch()) {
712             $ids[] = $user->id;
713         }
714
715         $user->free();
716
717         return $ids;
718     }
719
720     /**
721      * @return array of Group objects
722      */
723     function saveGroups()
724     {
725         // Don't save groups for repeats
726
727         if (!empty($this->repeat_of)) {
728             return array();
729         }
730
731         $groups = array();
732
733         /* extract all !group */
734         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
735                                 strtolower($this->content),
736                                 $match);
737         if (!$count) {
738             return $groups;
739         }
740
741         $profile = $this->getProfile();
742
743         /* Add them to the database */
744
745         foreach (array_unique($match[1]) as $nickname) {
746             /* XXX: remote groups. */
747             $group = User_group::getForNickname($nickname);
748
749             if (empty($group)) {
750                 continue;
751             }
752
753             // we automatically add a tag for every group name, too
754
755             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
756                                              'notice_id' => $this->id));
757
758             if (is_null($tag)) {
759                 $this->saveTag($nickname);
760             }
761
762             if ($profile->isMember($group)) {
763
764                 $result = $this->addToGroupInbox($group);
765
766                 if (!$result) {
767                     common_log_db_error($gi, 'INSERT', __FILE__);
768                 }
769
770                 $groups[] = clone($group);
771             }
772         }
773
774         return $groups;
775     }
776
777     function addToGroupInbox($group)
778     {
779         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
780                                          'notice_id' => $this->id));
781
782         if (empty($gi)) {
783
784             $gi = new Group_inbox();
785
786             $gi->group_id  = $group->id;
787             $gi->notice_id = $this->id;
788             $gi->created   = $this->created;
789
790             $result = $gi->insert();
791
792             if (!result) {
793                 common_log_db_error($gi, 'INSERT', __FILE__);
794                 throw new ServerException(_('Problem saving group inbox.'));
795             }
796
797             self::blow('user_group:notice_ids:%d', $gi->group_id);
798         }
799
800         return true;
801     }
802
803     /**
804      * @return array of integer profile IDs
805      */
806     function saveReplies()
807     {
808         // Don't save reply data for repeats
809
810         if (!empty($this->repeat_of)) {
811             return array();
812         }
813
814         // Alternative reply format
815         $tname = false;
816         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
817             $tname = $match[1];
818         }
819         // extract all @messages
820         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
821
822         $names = array();
823
824         if ($cnt || $tname) {
825             // XXX: is there another way to make an array copy?
826             $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
827         }
828
829         $sender = Profile::staticGet($this->profile_id);
830
831         $replied = array();
832
833         // store replied only for first @ (what user/notice what the reply directed,
834         // we assume first @ is it)
835
836         for ($i=0; $i<count($names); $i++) {
837             $nickname = $names[$i];
838             $recipient = common_relative_profile($sender, $nickname, $this->created);
839             if (empty($recipient)) {
840                 continue;
841             }
842             // Don't save replies from blocked profile to local user
843             $recipient_user = User::staticGet('id', $recipient->id);
844             if (!empty($recipient_user) && $recipient_user->hasBlocked($sender)) {
845                 continue;
846             }
847             $reply = new Reply();
848             $reply->notice_id = $this->id;
849             $reply->profile_id = $recipient->id;
850             $id = $reply->insert();
851             if (!$id) {
852                 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
853                 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
854                 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
855                 return array();
856             } else {
857                 $replied[$recipient->id] = 1;
858             }
859         }
860
861         // Hash format replies, too
862         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
863         if ($cnt) {
864             foreach ($match[1] as $tag) {
865                 $tagged = Profile_tag::getTagged($sender->id, $tag);
866                 foreach ($tagged as $t) {
867                     if (!$replied[$t->id]) {
868                         // Don't save replies from blocked profile to local user
869                         $t_user = User::staticGet('id', $t->id);
870                         if ($t_user && $t_user->hasBlocked($sender)) {
871                             continue;
872                         }
873                         $reply = new Reply();
874                         $reply->notice_id = $this->id;
875                         $reply->profile_id = $t->id;
876                         $id = $reply->insert();
877                         if (!$id) {
878                             common_log_db_error($reply, 'INSERT', __FILE__);
879                             return array();
880                         } else {
881                             $replied[$recipient->id] = 1;
882                         }
883                     }
884                 }
885             }
886         }
887
888         $recipientIds = array_keys($replied);
889
890         foreach ($recipientIds as $recipientId) {
891             $user = User::staticGet('id', $recipientId);
892             if (!empty($user)) {
893                 self::blow('reply:stream:%d', $reply->profile_id);
894                 mail_notify_attn($user, $this);
895             }
896         }
897
898         return $recipientIds;
899     }
900
901     function getReplies()
902     {
903         // XXX: cache me
904
905         $ids = array();
906
907         $reply = new Reply();
908         $reply->selectAdd();
909         $reply->selectAdd('profile_id');
910         $reply->notice_id = $this->id;
911
912         if ($reply->find()) {
913             while($reply->fetch()) {
914                 $ids[] = $reply->profile_id;
915             }
916         }
917
918         $reply->free();
919
920         return $ids;
921     }
922
923     /**
924      * Same calculation as saveGroups but without the saving
925      * @fixme merge the functions
926      * @return array of Group objects
927      */
928     function getGroups()
929     {
930         // Don't save groups for repeats
931
932         if (!empty($this->repeat_of)) {
933             return array();
934         }
935
936         // XXX: cache me
937
938         $groups = array();
939
940         $gi = new Group_inbox();
941
942         $gi->selectAdd();
943         $gi->selectAdd('group_id');
944
945         $gi->notice_id = $this->id;
946
947         if ($gi->find()) {
948             while ($gi->fetch()) {
949                 $groups[] = clone($gi);
950             }
951         }
952
953         $gi->free();
954
955         return $groups;
956     }
957
958     function asAtomEntry($namespace=false, $source=false)
959     {
960         $profile = $this->getProfile();
961
962         $xs = new XMLStringer(true);
963
964         if ($namespace) {
965             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
966                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
967         } else {
968             $attrs = array();
969         }
970
971         $xs->elementStart('entry', $attrs);
972
973         if ($source) {
974             $xs->elementStart('source');
975             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
976             $xs->element('link', array('href' => $profile->profileurl));
977             $user = User::staticGet('id', $profile->id);
978             if (!empty($user)) {
979                 $atom_feed = common_local_url('ApiTimelineUser',
980                                               array('format' => 'atom',
981                                                     'id' => $profile->nickname));
982                 $xs->element('link', array('rel' => 'self',
983                                            'type' => 'application/atom+xml',
984                                            'href' => $profile->profileurl));
985                 $xs->element('link', array('rel' => 'license',
986                                            'href' => common_config('license', 'url')));
987             }
988
989             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
990         }
991
992         $xs->elementStart('author');
993         $xs->element('name', null, $profile->nickname);
994         $xs->element('uri', null, $profile->profileurl);
995         $xs->elementEnd('author');
996
997         if ($source) {
998             $xs->elementEnd('source');
999         }
1000
1001         $xs->element('title', null, $this->content);
1002         $xs->element('summary', null, $this->content);
1003
1004         $xs->element('link', array('rel' => 'alternate',
1005                                    'href' => $this->bestUrl()));
1006
1007         $xs->element('id', null, $this->uri);
1008
1009         $xs->element('published', null, common_date_w3dtf($this->created));
1010         $xs->element('updated', null, common_date_w3dtf($this->created));
1011
1012         if ($this->reply_to) {
1013             $reply_notice = Notice::staticGet('id', $this->reply_to);
1014             if (!empty($reply_notice)) {
1015                 $xs->element('link', array('rel' => 'related',
1016                                            'href' => $reply_notice->bestUrl()));
1017                 $xs->element('thr:in-reply-to',
1018                              array('ref' => $reply_notice->uri,
1019                                    'href' => $reply_notice->bestUrl()));
1020             }
1021         }
1022
1023         $xs->element('content', array('type' => 'html'), $this->rendered);
1024
1025         $tag = new Notice_tag();
1026         $tag->notice_id = $this->id;
1027         if ($tag->find()) {
1028             while ($tag->fetch()) {
1029                 $xs->element('category', array('term' => $tag->tag));
1030             }
1031         }
1032         $tag->free();
1033
1034         # Enclosures
1035         $attachments = $this->attachments();
1036         if($attachments){
1037             foreach($attachments as $attachment){
1038                 $enclosure=$attachment->getEnclosure();
1039                 if ($enclosure) {
1040                     $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1041                     if($enclosure->title){
1042                         $attributes['title']=$enclosure->title;
1043                     }
1044                     $xs->element('link', $attributes, null);
1045                 }
1046             }
1047         }
1048
1049         if (!empty($this->lat) && !empty($this->lon)) {
1050             $xs->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
1051             $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1052             $xs->elementEnd('geo');
1053         }
1054
1055         $xs->elementEnd('entry');
1056
1057         return $xs->getString();
1058     }
1059
1060     function bestUrl()
1061     {
1062         if (!empty($this->url)) {
1063             return $this->url;
1064         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1065             return $this->uri;
1066         } else {
1067             return common_local_url('shownotice',
1068                                     array('notice' => $this->id));
1069         }
1070     }
1071
1072     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1073     {
1074         $cache = common_memcache();
1075
1076         if (empty($cache) ||
1077             $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1078             is_null($limit) ||
1079             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1080             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1081                                                                       $max_id, $since)));
1082         }
1083
1084         $idkey = common_cache_key($cachekey);
1085
1086         $idstr = $cache->get($idkey);
1087
1088         if ($idstr !== false) {
1089             // Cache hit! Woohoo!
1090             $window = explode(',', $idstr);
1091             $ids = array_slice($window, $offset, $limit);
1092             return $ids;
1093         }
1094
1095         $laststr = $cache->get($idkey.';last');
1096
1097         if ($laststr !== false) {
1098             $window = explode(',', $laststr);
1099             $last_id = $window[0];
1100             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1101                                                                           $last_id, 0, null)));
1102
1103             $new_window = array_merge($new_ids, $window);
1104
1105             $new_windowstr = implode(',', $new_window);
1106
1107             $result = $cache->set($idkey, $new_windowstr);
1108             $result = $cache->set($idkey . ';last', $new_windowstr);
1109
1110             $ids = array_slice($new_window, $offset, $limit);
1111
1112             return $ids;
1113         }
1114
1115         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1116                                                                      0, 0, null)));
1117
1118         $windowstr = implode(',', $window);
1119
1120         $result = $cache->set($idkey, $windowstr);
1121         $result = $cache->set($idkey . ';last', $windowstr);
1122
1123         $ids = array_slice($window, $offset, $limit);
1124
1125         return $ids;
1126     }
1127
1128     /**
1129      * Determine which notice, if any, a new notice is in reply to.
1130      *
1131      * For conversation tracking, we try to see where this notice fits
1132      * in the tree. Rough algorithm is:
1133      *
1134      * if (reply_to is set and valid) {
1135      *     return reply_to;
1136      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1137      *     return ID of last notice by initial @name in content;
1138      * }
1139      *
1140      * Note that all @nickname instances will still be used to save "reply" records,
1141      * so the notice shows up in the mentioned users' "replies" tab.
1142      *
1143      * @param integer $reply_to   ID passed in by Web or API
1144      * @param integer $profile_id ID of author
1145      * @param string  $source     Source tag, like 'web' or 'gwibber'
1146      * @param string  $content    Final notice content
1147      *
1148      * @return integer ID of replied-to notice, or null for not a reply.
1149      */
1150
1151     static function getReplyTo($reply_to, $profile_id, $source, $content)
1152     {
1153         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1154
1155         // If $reply_to is specified, we check that it exists, and then
1156         // return it if it does
1157
1158         if (!empty($reply_to)) {
1159             $reply_notice = Notice::staticGet('id', $reply_to);
1160             if (!empty($reply_notice)) {
1161                 return $reply_to;
1162             }
1163         }
1164
1165         // If it's not a "low bandwidth" source (one where you can't set
1166         // a reply_to argument), we return. This is mostly web and API
1167         // clients.
1168
1169         if (!in_array($source, $lb)) {
1170             return null;
1171         }
1172
1173         // Is there an initial @ or T?
1174
1175         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1176             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1177             $nickname = common_canonical_nickname($match[1]);
1178         } else {
1179             return null;
1180         }
1181
1182         // Figure out who that is.
1183
1184         $sender = Profile::staticGet('id', $profile_id);
1185         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1186
1187         if (empty($recipient)) {
1188             return null;
1189         }
1190
1191         // Get their last notice
1192
1193         $last = $recipient->getCurrentNotice();
1194
1195         if (!empty($last)) {
1196             return $last->id;
1197         }
1198     }
1199
1200     static function maxContent()
1201     {
1202         $contentlimit = common_config('notice', 'contentlimit');
1203         // null => use global limit (distinct from 0!)
1204         if (is_null($contentlimit)) {
1205             $contentlimit = common_config('site', 'textlimit');
1206         }
1207         return $contentlimit;
1208     }
1209
1210     static function contentTooLong($content)
1211     {
1212         $contentlimit = self::maxContent();
1213         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1214     }
1215
1216     function getLocation()
1217     {
1218         $location = null;
1219
1220         if (!empty($this->location_id) && !empty($this->location_ns)) {
1221             $location = Location::fromId($this->location_id, $this->location_ns);
1222         }
1223
1224         if (is_null($location)) { // no ID, or Location::fromId() failed
1225             if (!empty($this->lat) && !empty($this->lon)) {
1226                 $location = Location::fromLatLon($this->lat, $this->lon);
1227             }
1228         }
1229
1230         return $location;
1231     }
1232
1233     function repeat($repeater_id, $source)
1234     {
1235         $author = Profile::staticGet('id', $this->profile_id);
1236
1237         $content = sprintf(_('RT @%1$s %2$s'),
1238                            $author->nickname,
1239                            $this->content);
1240
1241         $maxlen = common_config('site', 'textlimit');
1242         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1243             // Web interface and current Twitter API clients will
1244             // pull the original notice's text, but some older
1245             // clients and RSS/Atom feeds will see this trimmed text.
1246             //
1247             // Unfortunately this is likely to lose tags or URLs
1248             // at the end of long notices.
1249             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1250         }
1251
1252         return self::saveNew($repeater_id, $content, $source,
1253                              array('repeat_of' => $this->id));
1254     }
1255
1256     // These are supposed to be in chron order!
1257
1258     function repeatStream($limit=100)
1259     {
1260         $cache = common_memcache();
1261
1262         if (empty($cache)) {
1263             $ids = $this->_repeatStreamDirect($limit);
1264         } else {
1265             $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1266             if ($idstr !== false) {
1267                 $ids = explode(',', $idstr);
1268             } else {
1269                 $ids = $this->_repeatStreamDirect(100);
1270                 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1271             }
1272             if ($limit < 100) {
1273                 // We do a max of 100, so slice down to limit
1274                 $ids = array_slice($ids, 0, $limit);
1275             }
1276         }
1277
1278         return Notice::getStreamByIds($ids);
1279     }
1280
1281     function _repeatStreamDirect($limit)
1282     {
1283         $notice = new Notice();
1284
1285         $notice->selectAdd(); // clears it
1286         $notice->selectAdd('id');
1287
1288         $notice->repeat_of = $this->id;
1289
1290         $notice->orderBy('created'); // NB: asc!
1291
1292         if (!is_null($offset)) {
1293             $notice->limit($offset, $limit);
1294         }
1295
1296         $ids = array();
1297
1298         if ($notice->find()) {
1299             while ($notice->fetch()) {
1300                 $ids[] = $notice->id;
1301             }
1302         }
1303
1304         $notice->free();
1305         $notice = NULL;
1306
1307         return $ids;
1308     }
1309
1310     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1311     {
1312         $options = array();
1313
1314         if (!empty($location_id) && !empty($location_ns)) {
1315
1316             $options['location_id'] = $location_id;
1317             $options['location_ns'] = $location_ns;
1318
1319             $location = Location::fromId($location_id, $location_ns);
1320
1321             if (!empty($location)) {
1322                 $options['lat'] = $location->lat;
1323                 $options['lon'] = $location->lon;
1324             }
1325
1326         } else if (!empty($lat) && !empty($lon)) {
1327
1328             $options['lat'] = $lat;
1329             $options['lon'] = $lon;
1330
1331             $location = Location::fromLatLon($lat, $lon);
1332
1333             if (!empty($location)) {
1334                 $options['location_id'] = $location->location_id;
1335                 $options['location_ns'] = $location->location_ns;
1336             }
1337         } else if (!empty($profile)) {
1338
1339             if (isset($profile->lat) && isset($profile->lon)) {
1340                 $options['lat'] = $profile->lat;
1341                 $options['lon'] = $profile->lon;
1342             }
1343
1344             if (isset($profile->location_id) && isset($profile->location_ns)) {
1345                 $options['location_id'] = $profile->location_id;
1346                 $options['location_ns'] = $profile->location_ns;
1347             }
1348         }
1349
1350         return $options;
1351     }
1352
1353     function clearReplies()
1354     {
1355         $replyNotice = new Notice();
1356         $replyNotice->reply_to = $this->id;
1357
1358         //Null any notices that are replies to this notice
1359
1360         if ($replyNotice->find()) {
1361             while ($replyNotice->fetch()) {
1362                 $orig = clone($replyNotice);
1363                 $replyNotice->reply_to = null;
1364                 $replyNotice->update($orig);
1365             }
1366         }
1367
1368         // Reply records
1369
1370         $reply = new Reply();
1371         $reply->notice_id = $this->id;
1372
1373         if ($reply->find()) {
1374             while($reply->fetch()) {
1375                 self::blow('reply:stream:%d', $reply->profile_id);
1376                 $reply->delete();
1377             }
1378         }
1379
1380         $reply->free();
1381     }
1382
1383     function clearRepeats()
1384     {
1385         $repeatNotice = new Notice();
1386         $repeatNotice->repeat_of = $this->id;
1387
1388         //Null any notices that are repeats of this notice
1389
1390         if ($repeatNotice->find()) {
1391             while ($repeatNotice->fetch()) {
1392                 $orig = clone($repeatNotice);
1393                 $repeatNotice->repeat_of = null;
1394                 $repeatNotice->update($orig);
1395             }
1396         }
1397     }
1398
1399     function clearFaves()
1400     {
1401         $fave = new Fave();
1402         $fave->notice_id = $this->id;
1403
1404         if ($fave->find()) {
1405             while ($fave->fetch()) {
1406                 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1407                 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1408                 self::blow('fave:ids_by_user:%d', $fave->user_id);
1409                 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1410                 $fave->delete();
1411             }
1412         }
1413
1414         $fave->free();
1415     }
1416
1417     function clearTags()
1418     {
1419         $tag = new Notice_tag();
1420         $tag->notice_id = $this->id;
1421
1422         if ($tag->find()) {
1423             while ($tag->fetch()) {
1424                 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
1425                 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
1426                 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
1427                 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
1428                 $tag->delete();
1429             }
1430         }
1431
1432         $tag->free();
1433     }
1434
1435     function clearGroupInboxes()
1436     {
1437         $gi = new Group_inbox();
1438
1439         $gi->notice_id = $this->id;
1440
1441         if ($gi->find()) {
1442             while ($gi->fetch()) {
1443                 self::blow('user_group:notice_ids:%d', $gi->group_id);
1444                 $gi->delete();
1445             }
1446         }
1447
1448         $gi->free();
1449     }
1450 }