Notice.php 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905
  1. <?php
  2. /**
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2008-2011 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. * @author Mikael Nordfeldth <mmn@hethane.se>
  33. * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
  34. * @license GNU Affero General Public License http://www.gnu.org/licenses/
  35. */
  36. if (!defined('GNUSOCIAL')) { exit(1); }
  37. /**
  38. * Table Definition for notice
  39. */
  40. /* We keep 200 notices, the max number of notices available per API request,
  41. * in the memcached cache. */
  42. define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
  43. define('MAX_BOXCARS', 128);
  44. class Notice extends Managed_DataObject
  45. {
  46. ###START_AUTOCODE
  47. /* the code below is auto generated do not remove the above tag */
  48. public $__table = 'notice'; // table name
  49. public $id; // int(4) primary_key not_null
  50. public $profile_id; // int(4) multiple_key not_null
  51. public $uri; // varchar(191) unique_key not 255 because utf8mb4 takes more space
  52. public $content; // text
  53. public $rendered; // text
  54. public $url; // varchar(191) not 255 because utf8mb4 takes more space
  55. public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
  56. public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
  57. public $reply_to; // int(4)
  58. public $is_local; // int(4)
  59. public $source; // varchar(32)
  60. public $conversation; // int(4)
  61. public $lat; // decimal(10,7)
  62. public $lon; // decimal(10,7)
  63. public $location_id; // int(4)
  64. public $location_ns; // int(4)
  65. public $repeat_of; // int(4)
  66. public $verb; // varchar(191) not 255 because utf8mb4 takes more space
  67. public $object_type; // varchar(191) not 255 because utf8mb4 takes more space
  68. public $scope; // int(4)
  69. /* the code above is auto generated do not remove the tag below */
  70. ###END_AUTOCODE
  71. public static function schemaDef()
  72. {
  73. $def = array(
  74. 'fields' => array(
  75. 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
  76. 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
  77. 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universally unique identifier, usually a tag URI'),
  78. 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8_general_ci'),
  79. 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
  80. 'url' => array('type' => 'varchar', 'length' => 191, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
  81. 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
  82. 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
  83. 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
  84. 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
  85. 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
  86. 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
  87. 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
  88. 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
  89. 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
  90. 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
  91. 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
  92. 'object_type' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
  93. 'verb' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
  94. 'scope' => array('type' => 'int',
  95. 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
  96. ),
  97. 'primary key' => array('id'),
  98. 'unique keys' => array(
  99. 'notice_uri_key' => array('uri'),
  100. ),
  101. 'foreign keys' => array(
  102. 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
  103. 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
  104. 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
  105. 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
  106. ),
  107. 'indexes' => array(
  108. 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
  109. 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
  110. 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
  111. 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
  112. 'notice_replyto_idx' => array('reply_to')
  113. )
  114. );
  115. if (common_config('search', 'type') == 'fulltext') {
  116. $def['fulltext indexes'] = array('content' => array('content'));
  117. }
  118. return $def;
  119. }
  120. /* Notice types */
  121. const LOCAL_PUBLIC = 1;
  122. const REMOTE = 0;
  123. const LOCAL_NONPUBLIC = -1;
  124. const GATEWAY = -2;
  125. const PUBLIC_SCOPE = 0; // Useful fake constant
  126. const SITE_SCOPE = 1;
  127. const ADDRESSEE_SCOPE = 2;
  128. const GROUP_SCOPE = 4;
  129. const FOLLOWER_SCOPE = 8;
  130. protected $_profile = array();
  131. /**
  132. * Will always return a profile, if anything fails it will
  133. * (through _setProfile) throw a NoProfileException.
  134. */
  135. public function getProfile()
  136. {
  137. if (!isset($this->_profile[$this->profile_id])) {
  138. // We could've sent getKV directly to _setProfile, but occasionally we get
  139. // a "false" (instead of null), likely because it indicates a cache miss.
  140. $profile = Profile::getKV('id', $this->profile_id);
  141. $this->_setProfile($profile instanceof Profile ? $profile : null);
  142. }
  143. return $this->_profile[$this->profile_id];
  144. }
  145. public function _setProfile(Profile $profile=null)
  146. {
  147. if (!$profile instanceof Profile) {
  148. throw new NoProfileException($this->profile_id);
  149. }
  150. $this->_profile[$this->profile_id] = $profile;
  151. }
  152. function delete($useWhere=false)
  153. {
  154. // For auditing purposes, save a record that the notice
  155. // was deleted.
  156. // @fixme we have some cases where things get re-run and so the
  157. // insert fails.
  158. $deleted = Deleted_notice::getKV('id', $this->id);
  159. if (!$deleted instanceof Deleted_notice) {
  160. $deleted = Deleted_notice::getKV('uri', $this->uri);
  161. }
  162. if (!$deleted instanceof Deleted_notice) {
  163. $deleted = new Deleted_notice();
  164. $deleted->id = $this->id;
  165. $deleted->profile_id = $this->profile_id;
  166. $deleted->uri = $this->uri;
  167. $deleted->created = $this->created;
  168. $deleted->deleted = common_sql_now();
  169. $deleted->insert();
  170. }
  171. if (Event::handle('NoticeDeleteRelated', array($this))) {
  172. // Clear related records
  173. $this->clearReplies();
  174. $this->clearRepeats();
  175. $this->clearTags();
  176. $this->clearGroupInboxes();
  177. $this->clearFiles();
  178. $this->clearAttentions();
  179. // NOTE: we don't clear queue items
  180. }
  181. $result = parent::delete($useWhere);
  182. $this->blowOnDelete();
  183. return $result;
  184. }
  185. public function getUri()
  186. {
  187. return $this->uri;
  188. }
  189. /*
  190. * Get a Notice object by URI. Will call external plugins for help
  191. * using the event StartGetNoticeFromURI.
  192. *
  193. * @param string $uri A unique identifier for a resource (notice in this case)
  194. */
  195. static function fromUri($uri)
  196. {
  197. $notice = null;
  198. if (Event::handle('StartGetNoticeFromUri', array($uri, &$notice))) {
  199. $notice = Notice::getKV('uri', $uri);
  200. Event::handle('EndGetNoticeFromUri', array($uri, $notice));
  201. }
  202. if (!$notice instanceof Notice) {
  203. throw new UnknownUriException($uri);
  204. }
  205. return $notice;
  206. }
  207. /*
  208. * @param $root boolean If true, link to just the conversation root.
  209. *
  210. * @return URL to conversation
  211. */
  212. public function getConversationUrl($anchor=true)
  213. {
  214. return Conversation::getUrlFromNotice($this, $anchor);
  215. }
  216. /*
  217. * Get the local representation URL of this notice.
  218. */
  219. public function getLocalUrl()
  220. {
  221. return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
  222. }
  223. public function getTitle()
  224. {
  225. $title = null;
  226. if (Event::handle('GetNoticeTitle', array($this, &$title))) {
  227. // TRANS: Title of a notice posted without a title value.
  228. // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
  229. $title = sprintf(_('%1$s\'s status on %2$s'),
  230. $this->getProfile()->getFancyName(),
  231. common_exact_date($this->created));
  232. }
  233. return $title;
  234. }
  235. public function getContent()
  236. {
  237. return $this->content;
  238. }
  239. /*
  240. * Get the original representation URL of this notice.
  241. *
  242. * @param boolean $fallback Whether to fall back to generate a local URL or throw InvalidUrlException
  243. */
  244. public function getUrl($fallback=false)
  245. {
  246. // The risk is we start having empty urls and non-http uris...
  247. // and we can't really handle any other protocol right now.
  248. switch (true) {
  249. case common_valid_http_url($this->url): // should we allow non-http/https URLs?
  250. return $this->url;
  251. case !$this->isLocal() && common_valid_http_url($this->uri): // Sometimes we only have the URI for remote posts.
  252. return $this->uri;
  253. case $this->isLocal() || $fallback:
  254. // let's generate a valid link to our locally available notice on demand
  255. return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
  256. default:
  257. common_debug('No URL available for notice: id='.$this->id);
  258. throw new InvalidUrlException($this->url);
  259. }
  260. }
  261. public function get_object_type($canonical=false) {
  262. return $canonical
  263. ? ActivityObject::canonicalType($this->object_type)
  264. : $this->object_type;
  265. }
  266. public static function getByUri($uri)
  267. {
  268. $notice = new Notice();
  269. $notice->uri = $uri;
  270. if (!$notice->find(true)) {
  271. throw new NoResultException($notice);
  272. }
  273. return $notice;
  274. }
  275. public static function getById($id)
  276. {
  277. $notice = new Notice();
  278. $notice->id = $id;
  279. if (!$notice->find(true)) {
  280. throw new NoResultException($notice);
  281. }
  282. return $notice;
  283. }
  284. /**
  285. * Extract #hashtags from this notice's content and save them to the database.
  286. */
  287. function saveTags()
  288. {
  289. /* extract all #hastags */
  290. $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
  291. if (!$count) {
  292. return true;
  293. }
  294. /* Add them to the database */
  295. return $this->saveKnownTags($match[1]);
  296. }
  297. /**
  298. * Record the given set of hash tags in the db for this notice.
  299. * Given tag strings will be normalized and checked for dupes.
  300. */
  301. function saveKnownTags($hashtags)
  302. {
  303. //turn each into their canonical tag
  304. //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
  305. for($i=0; $i<count($hashtags); $i++) {
  306. /* elide characters we don't want in the tag */
  307. $hashtags[$i] = common_canonical_tag($hashtags[$i]);
  308. }
  309. foreach(array_unique($hashtags) as $hashtag) {
  310. $this->saveTag($hashtag);
  311. self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
  312. }
  313. return true;
  314. }
  315. /**
  316. * Record a single hash tag as associated with this notice.
  317. * Tag format and uniqueness must be validated by caller.
  318. */
  319. function saveTag($hashtag)
  320. {
  321. $tag = new Notice_tag();
  322. $tag->notice_id = $this->id;
  323. $tag->tag = $hashtag;
  324. $tag->created = $this->created;
  325. $id = $tag->insert();
  326. if (!$id) {
  327. // TRANS: Server exception. %s are the error details.
  328. throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
  329. $last_error->message));
  330. return;
  331. }
  332. // if it's saved, blow its cache
  333. $tag->blowCache(false);
  334. }
  335. /**
  336. * Save a new notice and push it out to subscribers' inboxes.
  337. * Poster's permissions are checked before sending.
  338. *
  339. * @param int $profile_id Profile ID of the poster
  340. * @param string $content source message text; links may be shortened
  341. * per current user's preference
  342. * @param string $source source key ('web', 'api', etc)
  343. * @param array $options Associative array of optional properties:
  344. * string 'created' timestamp of notice; defaults to now
  345. * int 'is_local' source/gateway ID, one of:
  346. * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
  347. * Notice::REMOTE - Sent from a remote service;
  348. * hide from public timeline but show in
  349. * local "and friends" timelines
  350. * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
  351. * Notice::GATEWAY - From another non-OStatus service;
  352. * will not appear in public views
  353. * float 'lat' decimal latitude for geolocation
  354. * float 'lon' decimal longitude for geolocation
  355. * int 'location_id' geoname identifier
  356. * int 'location_ns' geoname namespace to interpret location_id
  357. * int 'reply_to'; notice ID this is a reply to
  358. * int 'repeat_of'; notice ID this is a repeat of
  359. * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
  360. * string 'url' permalink to notice; defaults to local notice URL
  361. * string 'rendered' rendered HTML version of content
  362. * array 'replies' list of profile URIs for reply delivery in
  363. * place of extracting @-replies from content.
  364. * array 'groups' list of group IDs to deliver to, in place of
  365. * extracting ! tags from content
  366. * array 'tags' list of hashtag strings to save with the notice
  367. * in place of extracting # tags from content
  368. * array 'urls' list of attached/referred URLs to save with the
  369. * notice in place of extracting links from content
  370. * boolean 'distribute' whether to distribute the notice, default true
  371. * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
  372. * string 'verb' URL of the associated verb (default ActivityVerb::POST)
  373. * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
  374. *
  375. * @fixme tag override
  376. *
  377. * @return Notice
  378. * @throws ClientException
  379. */
  380. static function saveNew($profile_id, $content, $source, array $options=null) {
  381. $defaults = array('uri' => null,
  382. 'url' => null,
  383. 'conversation' => null, // URI of conversation
  384. 'reply_to' => null, // This will override convo URI if the parent is known
  385. 'repeat_of' => null, // This will override convo URI if the repeated notice is known
  386. 'scope' => null,
  387. 'distribute' => true,
  388. 'object_type' => null,
  389. 'verb' => null);
  390. if (!empty($options) && is_array($options)) {
  391. $options = array_merge($defaults, $options);
  392. extract($options);
  393. } else {
  394. extract($defaults);
  395. }
  396. if (!isset($is_local)) {
  397. $is_local = Notice::LOCAL_PUBLIC;
  398. }
  399. $profile = Profile::getKV('id', $profile_id);
  400. if (!$profile instanceof Profile) {
  401. // TRANS: Client exception thrown when trying to save a notice for an unknown user.
  402. throw new ClientException(_('Problem saving notice. Unknown user.'));
  403. }
  404. $user = User::getKV('id', $profile_id);
  405. if ($user instanceof User) {
  406. // Use the local user's shortening preferences, if applicable.
  407. $final = $user->shortenLinks($content);
  408. } else {
  409. $final = common_shorten_links($content);
  410. }
  411. if (Notice::contentTooLong($final)) {
  412. // TRANS: Client exception thrown if a notice contains too many characters.
  413. throw new ClientException(_('Problem saving notice. Too long.'));
  414. }
  415. if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
  416. common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
  417. // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
  418. throw new ClientException(_('Too many notices too fast; take a breather '.
  419. 'and post again in a few minutes.'));
  420. }
  421. if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
  422. common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
  423. // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
  424. throw new ClientException(_('Too many duplicate messages too quickly;'.
  425. ' take a breather and post again in a few minutes.'));
  426. }
  427. if (!$profile->hasRight(Right::NEWNOTICE)) {
  428. common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
  429. // TRANS: Client exception thrown when a user tries to post while being banned.
  430. throw new ClientException(_('You are banned from posting notices on this site.'), 403);
  431. }
  432. $notice = new Notice();
  433. $notice->profile_id = $profile_id;
  434. $autosource = common_config('public', 'autosource');
  435. // Sandboxed are non-false, but not 1, either
  436. if (!$profile->hasRight(Right::PUBLICNOTICE) ||
  437. ($source && $autosource && in_array($source, $autosource))) {
  438. $notice->is_local = Notice::LOCAL_NONPUBLIC;
  439. } else {
  440. $notice->is_local = $is_local;
  441. }
  442. if (!empty($created)) {
  443. $notice->created = $created;
  444. } else {
  445. $notice->created = common_sql_now();
  446. }
  447. if (!$notice->isLocal()) {
  448. // Only do these checks for non-local notices. Local notices will generate these values later.
  449. if (!common_valid_http_url($url)) {
  450. common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
  451. }
  452. if (empty($uri)) {
  453. throw new ServerException('No URI for remote notice. Cannot accept that.');
  454. }
  455. }
  456. $notice->content = $final;
  457. $notice->source = $source;
  458. $notice->uri = $uri;
  459. $notice->url = $url;
  460. // Get the groups here so we can figure out replies and such
  461. if (!isset($groups)) {
  462. $groups = User_group::idsFromText($notice->content, $profile);
  463. }
  464. $reply = null;
  465. // Handle repeat case
  466. if (isset($repeat_of)) {
  467. // Check for a private one
  468. $repeat = Notice::getKV('id', $repeat_of);
  469. if (!($repeat instanceof Notice)) {
  470. // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
  471. throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
  472. }
  473. if ($profile->id == $repeat->profile_id) {
  474. // TRANS: Client error displayed when trying to repeat an own notice.
  475. throw new ClientException(_('You cannot repeat your own notice.'));
  476. }
  477. if ($repeat->scope != Notice::SITE_SCOPE &&
  478. $repeat->scope != Notice::PUBLIC_SCOPE) {
  479. // TRANS: Client error displayed when trying to repeat a non-public notice.
  480. throw new ClientException(_('Cannot repeat a private notice.'), 403);
  481. }
  482. if (!$repeat->inScope($profile)) {
  483. // The generic checks above should cover this, but let's be sure!
  484. // TRANS: Client error displayed when trying to repeat a notice you cannot access.
  485. throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
  486. }
  487. if ($profile->hasRepeated($repeat)) {
  488. // TRANS: Client error displayed when trying to repeat an already repeated notice.
  489. throw new ClientException(_('You already repeated that notice.'));
  490. }
  491. $notice->repeat_of = $repeat->id;
  492. $notice->conversation = $repeat->conversation;
  493. } else {
  494. $reply = null;
  495. // If $reply_to is specified, we check that it exists, and then
  496. // return it if it does
  497. if (!empty($reply_to)) {
  498. $reply = Notice::getKV('id', $reply_to);
  499. } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
  500. // If the source lacks capability of sending the "reply_to"
  501. // metadata, let's try to find an inline replyto-reference.
  502. $reply = self::getInlineReplyTo($profile, $final);
  503. }
  504. if ($reply instanceof Notice) {
  505. if (!$reply->inScope($profile)) {
  506. // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
  507. // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
  508. throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
  509. $profile->nickname, $reply->id), 403);
  510. }
  511. // If it's a repeat, the reply_to should be to the original
  512. if ($reply->isRepeat()) {
  513. $notice->reply_to = $reply->repeat_of;
  514. } else {
  515. $notice->reply_to = $reply->id;
  516. }
  517. // But the conversation ought to be the same :)
  518. $notice->conversation = $reply->conversation;
  519. // If the original is private to a group, and notice has
  520. // no group specified, make it to the same group(s)
  521. if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
  522. $groups = array();
  523. $replyGroups = $reply->getGroups();
  524. foreach ($replyGroups as $group) {
  525. if ($profile->isMember($group)) {
  526. $groups[] = $group->id;
  527. }
  528. }
  529. }
  530. // Scope set below
  531. }
  532. // If we don't know the reply, we might know the conversation!
  533. // This will happen if a known remote user replies to an
  534. // unknown remote user - within a known conversation.
  535. if (empty($notice->conversation) and !empty($options['conversation'])) {
  536. $conv = Conversation::getKV('uri', $options['conversation']);
  537. if ($conv instanceof Conversation) {
  538. common_debug('Conversation stitched together from (probably) reply to unknown remote user. Activity creation time ('.$notice->created.') should maybe be compared to conversation creation time ('.$conv->created.').');
  539. $notice->conversation = $conv->id;
  540. } else {
  541. // Conversation URI was not found, so we must create it. But we can't create it
  542. // until we have a Notice ID because of the database layout...
  543. $notice->tmp_conv_uri = $options['conversation'];
  544. }
  545. } else {
  546. // If we're not using the attached conversation URI let's remove it
  547. // so we don't mistake ourselves later, when creating our own Conversation.
  548. // This implies that the notice knows which conversation it belongs to.
  549. $options['conversation'] = null;
  550. }
  551. }
  552. if (!empty($lat) && !empty($lon)) {
  553. $notice->lat = $lat;
  554. $notice->lon = $lon;
  555. }
  556. if (!empty($location_ns) && !empty($location_id)) {
  557. $notice->location_id = $location_id;
  558. $notice->location_ns = $location_ns;
  559. }
  560. if (!empty($rendered)) {
  561. $notice->rendered = $rendered;
  562. } else {
  563. $notice->rendered = common_render_content($final, $notice);
  564. }
  565. if (empty($verb)) {
  566. if ($notice->isRepeat()) {
  567. $notice->verb = ActivityVerb::SHARE;
  568. $notice->object_type = ActivityObject::ACTIVITY;
  569. } else {
  570. $notice->verb = ActivityVerb::POST;
  571. }
  572. } else {
  573. $notice->verb = $verb;
  574. }
  575. if (empty($object_type)) {
  576. $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
  577. } else {
  578. $notice->object_type = $object_type;
  579. }
  580. if (is_null($scope) && $reply instanceof Notice) {
  581. $notice->scope = $reply->scope;
  582. } else {
  583. $notice->scope = $scope;
  584. }
  585. $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
  586. if (Event::handle('StartNoticeSave', array(&$notice))) {
  587. // XXX: some of these functions write to the DB
  588. try {
  589. $notice->insert(); // throws exception on failure
  590. // If it's not part of a conversation, it's
  591. // the beginning of a new conversation.
  592. if (empty($notice->conversation)) {
  593. $orig = clone($notice);
  594. // $act->context->conversation will be null if it was not provided
  595. $conv = Conversation::create($notice, $options['conversation']);
  596. $notice->conversation = $conv->id;
  597. $notice->update($orig);
  598. }
  599. } catch (Exception $e) {
  600. // Let's test if we managed initial insert, which would imply
  601. // failing on some update-part (check 'insert()'). Delete if
  602. // something had been stored to the database.
  603. if (!empty($notice->id)) {
  604. $notice->delete();
  605. }
  606. throw $e;
  607. }
  608. }
  609. // Clear the cache for subscribed users, so they'll update at next request
  610. // XXX: someone clever could prepend instead of clearing the cache
  611. // Save per-notice metadata...
  612. if (isset($replies)) {
  613. $notice->saveKnownReplies($replies);
  614. } else {
  615. $notice->saveReplies();
  616. }
  617. if (isset($tags)) {
  618. $notice->saveKnownTags($tags);
  619. } else {
  620. $notice->saveTags();
  621. }
  622. // Note: groups may save tags, so must be run after tags are saved
  623. // to avoid errors on duplicates.
  624. // Note: groups should always be set.
  625. $notice->saveKnownGroups($groups);
  626. if (isset($urls)) {
  627. $notice->saveKnownUrls($urls);
  628. } else {
  629. $notice->saveUrls();
  630. }
  631. if ($distribute) {
  632. // Prepare inbox delivery, may be queued to background.
  633. $notice->distribute();
  634. }
  635. return $notice;
  636. }
  637. static function saveActivity(Activity $act, Profile $actor, array $options=array())
  638. {
  639. // First check if we're going to let this Activity through from the specific actor
  640. if (!$actor->hasRight(Right::NEWNOTICE)) {
  641. common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
  642. // TRANS: Client exception thrown when a user tries to post while being banned.
  643. throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
  644. }
  645. if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
  646. common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
  647. // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
  648. throw new ClientException(_m('Too many notices too fast; take a breather '.
  649. 'and post again in a few minutes.'));
  650. }
  651. // Get ActivityObject properties
  652. if (!empty($act->id)) {
  653. // implied object
  654. $options['uri'] = $act->id;
  655. $options['url'] = $act->link;
  656. } else {
  657. $actobj = count($act->objects)==1 ? $act->objects[0] : null;
  658. if (!is_null($actobj) && !empty($actobj->id)) {
  659. $options['uri'] = $actobj->id;
  660. if ($actobj->link) {
  661. $options['url'] = $actobj->link;
  662. } elseif (preg_match('!^https?://!', $actobj->id)) {
  663. $options['url'] = $actobj->id;
  664. }
  665. }
  666. }
  667. $defaults = array(
  668. 'groups' => array(),
  669. 'is_local' => self::LOCAL_PUBLIC,
  670. 'mentions' => array(),
  671. 'reply_to' => null,
  672. 'repeat_of' => null,
  673. 'scope' => null,
  674. 'source' => 'unknown',
  675. 'tags' => array(),
  676. 'uri' => null,
  677. 'url' => null,
  678. 'urls' => array(),
  679. 'distribute' => true);
  680. // options will have default values when nothing has been supplied
  681. $options = array_merge($defaults, $options);
  682. foreach (array_keys($defaults) as $key) {
  683. // Only convert the keynames we specify ourselves from 'defaults' array into variables
  684. $$key = $options[$key];
  685. }
  686. extract($options, EXTR_SKIP);
  687. $stored = new Notice();
  688. if (!empty($uri)) {
  689. $stored->uri = $uri;
  690. if ($stored->find()) {
  691. common_debug('cannot create duplicate Notice URI: '.$stored->uri);
  692. throw new Exception('Notice URI already exists');
  693. }
  694. }
  695. $stored->profile_id = $actor->id;
  696. $stored->source = $source;
  697. $stored->uri = $uri;
  698. $stored->url = $url;
  699. $stored->verb = $act->verb;
  700. // Use the local user's shortening preferences, if applicable.
  701. $stored->rendered = $actor->isLocal()
  702. ? $actor->shortenLinks($act->content)
  703. : $act->content;
  704. $stored->content = common_strip_html($stored->rendered);
  705. $autosource = common_config('public', 'autosource');
  706. // Sandboxed are non-false, but not 1, either
  707. if (!$actor->hasRight(Right::PUBLICNOTICE) ||
  708. ($source && $autosource && in_array($source, $autosource))) {
  709. $stored->is_local = Notice::LOCAL_NONPUBLIC;
  710. }
  711. // Maybe a missing act-time should be fatal if the actor is not local?
  712. if (!empty($act->time)) {
  713. $stored->created = common_sql_date($act->time);
  714. } else {
  715. $stored->created = common_sql_now();
  716. }
  717. $reply = null;
  718. if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
  719. $reply = self::getKV('uri', $act->context->replyToID);
  720. }
  721. if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
  722. $reply = self::getKV('uri', $act->target->id);
  723. }
  724. if ($reply instanceof Notice) {
  725. if (!$reply->inScope($actor)) {
  726. // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
  727. // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
  728. throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
  729. }
  730. $stored->reply_to = $reply->id;
  731. $stored->conversation = $reply->conversation;
  732. // If the original is private to a group, and notice has no group specified,
  733. // make it to the same group(s)
  734. if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
  735. $groups = array();
  736. $replyGroups = $reply->getGroups();
  737. foreach ($replyGroups as $group) {
  738. if ($actor->isMember($group)) {
  739. $groups[] = $group->id;
  740. }
  741. }
  742. }
  743. if (is_null($scope)) {
  744. $scope = $reply->scope;
  745. }
  746. }
  747. if ($act->context instanceof ActivityContext) {
  748. $location = $act->context->location;
  749. if ($location) {
  750. $stored->lat = $location->lat;
  751. $stored->lon = $location->lon;
  752. if ($location->location_id) {
  753. $stored->location_ns = $location->location_ns;
  754. $stored->location_id = $location->location_id;
  755. }
  756. }
  757. } else {
  758. $act->context = new ActivityContext();
  759. }
  760. $stored->scope = self::figureOutScope($actor, $groups, $scope);
  761. foreach ($act->categories as $cat) {
  762. if ($cat->term) {
  763. $term = common_canonical_tag($cat->term);
  764. if (!empty($term)) {
  765. $tags[] = $term;
  766. }
  767. }
  768. }
  769. foreach ($act->enclosures as $href) {
  770. // @todo FIXME: Save these locally or....?
  771. $urls[] = $href;
  772. }
  773. if (Event::handle('StartNoticeSave', array(&$stored))) {
  774. // XXX: some of these functions write to the DB
  775. try {
  776. $stored->insert(); // throws exception on error
  777. $orig = clone($stored); // for updating later in this try clause
  778. $object = null;
  779. Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
  780. if (empty($object)) {
  781. throw new ServerException('Unsuccessful call to StoreActivityObject '.$stored->uri . ': '.$act->asString());
  782. }
  783. // If it's not part of a conversation, it's
  784. // the beginning of a new conversation.
  785. if (empty($stored->conversation)) {
  786. // $act->context->conversation will be null if it was not provided
  787. $conv = Conversation::create($stored, $act->context->conversation);
  788. $stored->conversation = $conv->id;
  789. }
  790. $stored->update($orig);
  791. } catch (Exception $e) {
  792. if (empty($stored->id)) {
  793. common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
  794. } else {
  795. common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
  796. $stored->delete();
  797. }
  798. throw $e;
  799. }
  800. }
  801. if (!$stored instanceof Notice) {
  802. throw new ServerException('StartNoticeSave did not give back a Notice');
  803. }
  804. // Save per-notice metadata...
  805. $mentions = array();
  806. $groups = array();
  807. // This event lets plugins filter out non-local recipients (attentions we don't care about)
  808. // Used primarily for OStatus (and if we don't federate, all attentions would be local anyway)
  809. Event::handle('GetLocalAttentions', array($actor, $act->context->attention, &$mentions, &$groups));
  810. if (!empty($mentions)) {
  811. $stored->saveKnownReplies($mentions);
  812. } else {
  813. $stored->saveReplies();
  814. }
  815. if (!empty($tags)) {
  816. $stored->saveKnownTags($tags);
  817. } else {
  818. $stored->saveTags();
  819. }
  820. // Note: groups may save tags, so must be run after tags are saved
  821. // to avoid errors on duplicates.
  822. // Note: groups should always be set.
  823. $stored->saveKnownGroups($groups);
  824. if (!empty($urls)) {
  825. $stored->saveKnownUrls($urls);
  826. } else {
  827. $stored->saveUrls();
  828. }
  829. if ($distribute) {
  830. // Prepare inbox delivery, may be queued to background.
  831. $stored->distribute();
  832. }
  833. return $stored;
  834. }
  835. static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
  836. if (is_null($scope)) {
  837. $scope = self::defaultScope();
  838. }
  839. // For private streams
  840. try {
  841. $user = $actor->getUser();
  842. // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
  843. if ($user->private_stream && ($scope == Notice::PUBLIC_SCOPE || $scope == Notice::SITE_SCOPE)) {
  844. $scope |= Notice::FOLLOWER_SCOPE;
  845. }
  846. } catch (NoSuchUserException $e) {
  847. // TODO: Not a local user, so we don't know about scope preferences... yet!
  848. }
  849. // Force the scope for private groups
  850. foreach ($groups as $group_id) {
  851. $group = User_group::staticGet('id', $group_id);
  852. if ($group instanceof User_group) {
  853. if ($group->force_scope) {
  854. $scope |= Notice::GROUP_SCOPE;
  855. break;
  856. }
  857. }
  858. }
  859. return $scope;
  860. }
  861. function blowOnInsert($conversation = false)
  862. {
  863. $this->blowStream('profile:notice_ids:%d', $this->profile_id);
  864. if ($this->isPublic()) {
  865. $this->blowStream('public');
  866. $this->blowStream('networkpublic');
  867. }
  868. self::blow('notice:list-ids:conversation:%s', $this->conversation);
  869. self::blow('conversation:notice_count:%d', $this->conversation);
  870. if ($this->isRepeat()) {
  871. // XXX: we should probably only use one of these
  872. $this->blowStream('notice:repeats:%d', $this->repeat_of);
  873. self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
  874. }
  875. $original = Notice::getKV('id', $this->repeat_of);
  876. if ($original instanceof Notice) {
  877. $originalUser = User::getKV('id', $original->profile_id);
  878. if ($originalUser instanceof User) {
  879. $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
  880. }
  881. }
  882. $profile = Profile::getKV($this->profile_id);
  883. if ($profile instanceof Profile) {
  884. $profile->blowNoticeCount();
  885. }
  886. $ptags = $this->getProfileTags();
  887. foreach ($ptags as $ptag) {
  888. $ptag->blowNoticeStreamCache();
  889. }
  890. }
  891. /**
  892. * Clear cache entries related to this notice at delete time.
  893. * Necessary to avoid breaking paging on public, profile timelines.
  894. */
  895. function blowOnDelete()
  896. {
  897. $this->blowOnInsert();
  898. self::blow('profile:notice_ids:%d;last', $this->profile_id);
  899. if ($this->isPublic()) {
  900. self::blow('public;last');
  901. self::blow('networkpublic;last');
  902. }
  903. self::blow('fave:by_notice', $this->id);
  904. if ($this->conversation) {
  905. // In case we're the first, will need to calc a new root.
  906. self::blow('notice:conversation_root:%d', $this->conversation);
  907. }
  908. $ptags = $this->getProfileTags();
  909. foreach ($ptags as $ptag) {
  910. $ptag->blowNoticeStreamCache(true);
  911. }
  912. }
  913. function blowStream()
  914. {
  915. $c = self::memcache();
  916. if (empty($c)) {
  917. return false;
  918. }
  919. $args = func_get_args();
  920. $format = array_shift($args);
  921. $keyPart = vsprintf($format, $args);
  922. $cacheKey = Cache::key($keyPart);
  923. $c->delete($cacheKey);
  924. // delete the "last" stream, too, if this notice is
  925. // older than the top of that stream
  926. $lastKey = $cacheKey.';last';
  927. $lastStr = $c->get($lastKey);
  928. if ($lastStr !== false) {
  929. $window = explode(',', $lastStr);
  930. $lastID = $window[0];
  931. $lastNotice = Notice::getKV('id', $lastID);
  932. if (!$lastNotice instanceof Notice // just weird
  933. || strtotime($lastNotice->created) >= strtotime($this->created)) {
  934. $c->delete($lastKey);
  935. }
  936. }
  937. }
  938. /** save all urls in the notice to the db
  939. *
  940. * follow redirects and save all available file information
  941. * (mimetype, date, size, oembed, etc.)
  942. *
  943. * @return void
  944. */
  945. function saveUrls() {
  946. if (common_config('attachments', 'process_links')) {
  947. common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
  948. }
  949. }
  950. /**
  951. * Save the given URLs as related links/attachments to the db
  952. *
  953. * follow redirects and save all available file information
  954. * (mimetype, date, size, oembed, etc.)
  955. *
  956. * @return void
  957. */
  958. function saveKnownUrls($urls)
  959. {
  960. if (common_config('attachments', 'process_links')) {
  961. // @fixme validation?
  962. foreach (array_unique($urls) as $url) {
  963. try {
  964. File::processNew($url, $this->id);
  965. } catch (ServerException $e) {
  966. // Could not save URL. Log it?
  967. }
  968. }
  969. }
  970. }
  971. /**
  972. * @private callback
  973. */
  974. function saveUrl($url, $notice_id) {
  975. try {
  976. File::processNew($url, $notice_id);
  977. } catch (ServerException $e) {
  978. // Could not save URL. Log it?
  979. }
  980. }
  981. static function checkDupes($profile_id, $content) {
  982. $profile = Profile::getKV($profile_id);
  983. if (!$profile instanceof Profile) {
  984. return false;
  985. }
  986. $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
  987. if (!empty($notice)) {
  988. $last = 0;
  989. while ($notice->fetch()) {
  990. if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
  991. return true;
  992. } else if ($notice->content == $content) {
  993. return false;
  994. }
  995. }
  996. }
  997. // If we get here, oldest item in cache window is not
  998. // old enough for dupe limit; do direct check against DB
  999. $notice = new Notice();
  1000. $notice->profile_id = $profile_id;
  1001. $notice->content = $content;
  1002. $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
  1003. $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
  1004. $cnt = $notice->count();
  1005. return ($cnt == 0);
  1006. }
  1007. static function checkEditThrottle($profile_id) {
  1008. $profile = Profile::getKV($profile_id);
  1009. if (!$profile instanceof Profile) {
  1010. return false;
  1011. }
  1012. // Get the Nth notice
  1013. $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
  1014. if ($notice && $notice->fetch()) {
  1015. // If the Nth notice was posted less than timespan seconds ago
  1016. if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
  1017. // Then we throttle
  1018. return false;
  1019. }
  1020. }
  1021. // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
  1022. return true;
  1023. }
  1024. protected $_attachments = array();
  1025. function attachments() {
  1026. if (isset($this->_attachments[$this->id])) {
  1027. return $this->_attachments[$this->id];
  1028. }
  1029. $f2ps = File_to_post::listGet('post_id', array($this->id));
  1030. $ids = array();
  1031. foreach ($f2ps[$this->id] as $f2p) {
  1032. $ids[] = $f2p->file_id;
  1033. }
  1034. $files = File::multiGet('id', $ids);
  1035. $this->_attachments[$this->id] = $files->fetchAll();
  1036. return $this->_attachments[$this->id];
  1037. }
  1038. function _setAttachments($attachments)
  1039. {
  1040. $this->_attachments[$this->id] = $attachments;
  1041. }
  1042. function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
  1043. {
  1044. $stream = new PublicNoticeStream();
  1045. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  1046. }
  1047. function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
  1048. {
  1049. $stream = new ConversationNoticeStream($id);
  1050. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  1051. }
  1052. /**
  1053. * Is this notice part of an active conversation?
  1054. *
  1055. * @return boolean true if other messages exist in the same
  1056. * conversation, false if this is the only one
  1057. */
  1058. function hasConversation()
  1059. {
  1060. if (!empty($this->conversation)) {
  1061. $conversation = Notice::conversationStream(
  1062. $this->conversation,
  1063. 1,
  1064. 1
  1065. );
  1066. if ($conversation->N > 0) {
  1067. return true;
  1068. }
  1069. }
  1070. return false;
  1071. }
  1072. /**
  1073. * Grab the earliest notice from this conversation.
  1074. *
  1075. * @return Notice or null
  1076. */
  1077. function conversationRoot($profile=-1)
  1078. {
  1079. // XXX: can this happen?
  1080. if (empty($this->conversation)) {
  1081. return null;
  1082. }
  1083. // Get the current profile if not specified
  1084. if (is_int($profile) && $profile == -1) {
  1085. $profile = Profile::current();
  1086. }
  1087. // If this notice is out of scope, no root for you!
  1088. if (!$this->inScope($profile)) {
  1089. return null;
  1090. }
  1091. // If this isn't a reply to anything, then it's its own
  1092. // root if it's the earliest notice in the conversation:
  1093. if (empty($this->reply_to)) {
  1094. $root = new Notice;
  1095. $root->conversation = $this->conversation;
  1096. $root->orderBy('notice.created ASC');
  1097. $root->find();
  1098. $root->fetch();
  1099. $root->free();
  1100. return $root;
  1101. }
  1102. if (is_null($profile)) {
  1103. $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
  1104. } else {
  1105. $keypart = sprintf('notice:conversation_root:%d:%d',
  1106. $this->id,
  1107. $profile->id);
  1108. }
  1109. $root = self::cacheGet($keypart);
  1110. if ($root !== false && $root->inScope($profile)) {
  1111. return $root;
  1112. }
  1113. $last = $this;
  1114. while (true) {
  1115. try {
  1116. $parent = $last->getParent();
  1117. if ($parent->inScope($profile)) {
  1118. $last = $parent;
  1119. continue;
  1120. }
  1121. } catch (Exception $e) {
  1122. // Latest notice has no parent
  1123. }
  1124. // No parent, or parent out of scope
  1125. $root = $last;
  1126. break;
  1127. }
  1128. self::cacheSet($keypart, $root);
  1129. return $root;
  1130. }
  1131. /**
  1132. * Pull up a full list of local recipients who will be getting
  1133. * this notice in their inbox. Results will be cached, so don't
  1134. * change the input data wily-nilly!
  1135. *
  1136. * @param array $groups optional list of Group objects;
  1137. * if left empty, will be loaded from group_inbox records
  1138. * @param array $recipient optional list of reply profile ids
  1139. * if left empty, will be loaded from reply records
  1140. * @return array associating recipient user IDs with an inbox source constant
  1141. */
  1142. function whoGets(array $groups=null, array $recipients=null)
  1143. {
  1144. $c = self::memcache();
  1145. if (!empty($c)) {
  1146. $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
  1147. if ($ni !== false) {
  1148. return $ni;
  1149. }
  1150. }
  1151. if (is_null($recipients)) {
  1152. $recipients = $this->getReplies();
  1153. }
  1154. $ni = array();
  1155. // Give plugins a chance to add folks in at start...
  1156. if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
  1157. $users = $this->getSubscribedUsers();
  1158. foreach ($users as $id) {
  1159. $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
  1160. }
  1161. if (is_null($groups)) {
  1162. $groups = $this->getGroups();
  1163. }
  1164. foreach ($groups as $group) {
  1165. $users = $group->getUserMembers();
  1166. foreach ($users as $id) {
  1167. if (!array_key_exists($id, $ni)) {
  1168. $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
  1169. }
  1170. }
  1171. }
  1172. $ptAtts = $this->getAttentionsFromProfileTags();
  1173. foreach ($ptAtts as $key=>$val) {
  1174. if (!array_key_exists($key, $ni)) {
  1175. $ni[$key] = $val;
  1176. }
  1177. }
  1178. foreach ($recipients as $recipient) {
  1179. if (!array_key_exists($recipient, $ni)) {
  1180. $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
  1181. }
  1182. }
  1183. // Exclude any deleted, non-local, or blocking recipients.
  1184. $profile = $this->getProfile();
  1185. $originalProfile = null;
  1186. if ($this->isRepeat()) {
  1187. // Check blocks against the original notice's poster as well.
  1188. $original = Notice::getKV('id', $this->repeat_of);
  1189. if ($original instanceof Notice) {
  1190. $originalProfile = $original->getProfile();
  1191. }
  1192. }
  1193. foreach ($ni as $id => $source) {
  1194. try {
  1195. $user = User::getKV('id', $id);
  1196. if (!$user instanceof User ||
  1197. $user->hasBlocked($profile) ||
  1198. ($originalProfile && $user->hasBlocked($originalProfile))) {
  1199. unset($ni[$id]);
  1200. }
  1201. } catch (UserNoProfileException $e) {
  1202. // User doesn't have a profile; invalid; skip them.
  1203. unset($ni[$id]);
  1204. }
  1205. }
  1206. // Give plugins a chance to filter out...
  1207. Event::handle('EndNoticeWhoGets', array($this, &$ni));
  1208. }
  1209. if (!empty($c)) {
  1210. // XXX: pack this data better
  1211. $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
  1212. }
  1213. return $ni;
  1214. }
  1215. function getSubscribedUsers()
  1216. {
  1217. $user = new User();
  1218. if(common_config('db','quote_identifiers'))
  1219. $user_table = '"user"';
  1220. else $user_table = 'user';
  1221. $qry =
  1222. 'SELECT id ' .
  1223. 'FROM '. $user_table .' JOIN subscription '.
  1224. 'ON '. $user_table .'.id = subscription.subscriber ' .
  1225. 'WHERE subscription.subscribed = %d ';
  1226. $user->query(sprintf($qry, $this->profile_id));
  1227. $ids = array();
  1228. while ($user->fetch()) {
  1229. $ids[] = $user->id;
  1230. }
  1231. $user->free();
  1232. return $ids;
  1233. }
  1234. function getProfileTags()
  1235. {
  1236. $profile = $this->getProfile();
  1237. $list = $profile->getOtherTags($profile);
  1238. $ptags = array();
  1239. while($list->fetch()) {
  1240. $ptags[] = clone($list);
  1241. }
  1242. return $ptags;
  1243. }
  1244. public function getAttentionsFromProfileTags()
  1245. {
  1246. $ni = array();
  1247. $ptags = $this->getProfileTags();
  1248. foreach ($ptags as $ptag) {
  1249. $users = $ptag->getUserSubscribers();
  1250. foreach ($users as $id) {
  1251. $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
  1252. }
  1253. }
  1254. return $ni;
  1255. }
  1256. /**
  1257. * Record this notice to the given group inboxes for delivery.
  1258. * Overrides the regular parsing of !group markup.
  1259. *
  1260. * @param string $group_ids
  1261. * @fixme might prefer URIs as identifiers, as for replies?
  1262. * best with generalizations on user_group to support
  1263. * remote groups better.
  1264. */
  1265. function saveKnownGroups($group_ids)
  1266. {
  1267. if (!is_array($group_ids)) {
  1268. // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
  1269. throw new ServerException(_('Bad type provided to saveKnownGroups.'));
  1270. }
  1271. $groups = array();
  1272. foreach (array_unique($group_ids) as $id) {
  1273. $group = User_group::getKV('id', $id);
  1274. if ($group instanceof User_group) {
  1275. common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
  1276. $result = $this->addToGroupInbox($group);
  1277. if (!$result) {
  1278. common_log_db_error($gi, 'INSERT', __FILE__);
  1279. }
  1280. if (common_config('group', 'addtag')) {
  1281. // we automatically add a tag for every group name, too
  1282. $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
  1283. 'notice_id' => $this->id));
  1284. if (is_null($tag)) {
  1285. $this->saveTag($group->nickname);
  1286. }
  1287. }
  1288. $groups[] = clone($group);
  1289. } else {
  1290. common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
  1291. }
  1292. }
  1293. return $groups;
  1294. }
  1295. function addToGroupInbox(User_group $group)
  1296. {
  1297. $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
  1298. 'notice_id' => $this->id));
  1299. if (!$gi instanceof Group_inbox) {
  1300. $gi = new Group_inbox();
  1301. $gi->group_id = $group->id;
  1302. $gi->notice_id = $this->id;
  1303. $gi->created = $this->created;
  1304. $result = $gi->insert();
  1305. if (!$result) {
  1306. common_log_db_error($gi, 'INSERT', __FILE__);
  1307. // TRANS: Server exception thrown when an update for a group inbox fails.
  1308. throw new ServerException(_('Problem saving group inbox.'));
  1309. }
  1310. self::blow('user_group:notice_ids:%d', $gi->group_id);
  1311. }
  1312. return true;
  1313. }
  1314. /**
  1315. * Save reply records indicating that this notice needs to be
  1316. * delivered to the local users with the given URIs.
  1317. *
  1318. * Since this is expected to be used when saving foreign-sourced
  1319. * messages, we won't deliver to any remote targets as that's the
  1320. * source service's responsibility.
  1321. *
  1322. * Mail notifications etc will be handled later.
  1323. *
  1324. * @param array $uris Array of unique identifier URIs for recipients
  1325. */
  1326. function saveKnownReplies(array $uris)
  1327. {
  1328. if (empty($uris)) {
  1329. return;
  1330. }
  1331. $sender = Profile::getKV($this->profile_id);
  1332. foreach (array_unique($uris) as $uri) {
  1333. try {
  1334. $profile = Profile::fromUri($uri);
  1335. } catch (UnknownUriException $e) {
  1336. common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
  1337. continue;
  1338. }
  1339. if ($profile->hasBlocked($sender)) {
  1340. common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
  1341. continue;
  1342. }
  1343. $this->saveReply($profile->id);
  1344. self::blow('reply:stream:%d', $profile->id);
  1345. }
  1346. return;
  1347. }
  1348. /**
  1349. * Pull @-replies from this message's content in StatusNet markup format
  1350. * and save reply records indicating that this message needs to be
  1351. * delivered to those users.
  1352. *
  1353. * Mail notifications to local profiles will be sent later.
  1354. *
  1355. * @return array of integer profile IDs
  1356. */
  1357. function saveReplies()
  1358. {
  1359. // Don't save reply data for repeats
  1360. if ($this->isRepeat()) {
  1361. return array();
  1362. }
  1363. $sender = $this->getProfile();
  1364. $replied = array();
  1365. // If it's a reply, save for the replied-to author
  1366. try {
  1367. $parent = $this->getParent();
  1368. $parentauthor = $parent->getProfile();
  1369. $this->saveReply($parentauthor->id);
  1370. $replied[$parentauthor->id] = 1;
  1371. self::blow('reply:stream:%d', $parentauthor->id);
  1372. } catch (Exception $e) {
  1373. // Not a reply, since it has no parent!
  1374. }
  1375. // @todo ideally this parser information would only
  1376. // be calculated once.
  1377. $mentions = common_find_mentions($this->content, $this);
  1378. // store replied only for first @ (what user/notice what the reply directed,
  1379. // we assume first @ is it)
  1380. foreach ($mentions as $mention) {
  1381. foreach ($mention['mentioned'] as $mentioned) {
  1382. // skip if they're already covered
  1383. if (!empty($replied[$mentioned->id])) {
  1384. continue;
  1385. }
  1386. // Don't save replies from blocked profile to local user
  1387. $mentioned_user = User::getKV('id', $mentioned->id);
  1388. if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
  1389. continue;
  1390. }
  1391. $this->saveReply($mentioned->id);
  1392. $replied[$mentioned->id] = 1;
  1393. self::blow('reply:stream:%d', $mentioned->id);
  1394. }
  1395. }
  1396. $recipientIds = array_keys($replied);
  1397. return $recipientIds;
  1398. }
  1399. function saveReply($profileId)
  1400. {
  1401. $reply = new Reply();
  1402. $reply->notice_id = $this->id;
  1403. $reply->profile_id = $profileId;
  1404. $reply->modified = $this->created;
  1405. $reply->insert();
  1406. return $reply;
  1407. }
  1408. protected $_replies = array();
  1409. /**
  1410. * Pull the complete list of @-reply targets for this notice.
  1411. *
  1412. * @return array of integer profile ids
  1413. */
  1414. function getReplies()
  1415. {
  1416. if (isset($this->_replies[$this->id])) {
  1417. return $this->_replies[$this->id];
  1418. }
  1419. $replyMap = Reply::listGet('notice_id', array($this->id));
  1420. $ids = array();
  1421. foreach ($replyMap[$this->id] as $reply) {
  1422. $ids[] = $reply->profile_id;
  1423. }
  1424. $this->_replies[$this->id] = $ids;
  1425. return $ids;
  1426. }
  1427. function _setReplies($replies)
  1428. {
  1429. $this->_replies[$this->id] = $replies;
  1430. }
  1431. /**
  1432. * Pull the complete list of @-reply targets for this notice.
  1433. *
  1434. * @return array of Profiles
  1435. */
  1436. function getReplyProfiles()
  1437. {
  1438. $ids = $this->getReplies();
  1439. $profiles = Profile::multiGet('id', $ids);
  1440. return $profiles->fetchAll();
  1441. }
  1442. /**
  1443. * Send e-mail notifications to local @-reply targets.
  1444. *
  1445. * Replies must already have been saved; this is expected to be run
  1446. * from the distrib queue handler.
  1447. */
  1448. function sendReplyNotifications()
  1449. {
  1450. // Don't send reply notifications for repeats
  1451. if ($this->isRepeat()) {
  1452. return array();
  1453. }
  1454. $recipientIds = $this->getReplies();
  1455. if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
  1456. require_once INSTALLDIR.'/lib/mail.php';
  1457. foreach ($recipientIds as $recipientId) {
  1458. $user = User::getKV('id', $recipientId);
  1459. if ($user instanceof User) {
  1460. mail_notify_attn($user, $this);
  1461. }
  1462. }
  1463. Event::handle('EndNotifyMentioned', array($this, $recipientIds));
  1464. }
  1465. }
  1466. /**
  1467. * Pull list of groups this notice needs to be delivered to,
  1468. * as previously recorded by saveKnownGroups().
  1469. *
  1470. * @return array of Group objects
  1471. */
  1472. protected $_groups = array();
  1473. function getGroups()
  1474. {
  1475. // Don't save groups for repeats
  1476. if (!empty($this->repeat_of)) {
  1477. return array();
  1478. }
  1479. if (isset($this->_groups[$this->id])) {
  1480. return $this->_groups[$this->id];
  1481. }
  1482. $gis = Group_inbox::listGet('notice_id', array($this->id));
  1483. $ids = array();
  1484. foreach ($gis[$this->id] as $gi) {
  1485. $ids[] = $gi->group_id;
  1486. }
  1487. $groups = User_group::multiGet('id', $ids);
  1488. $this->_groups[$this->id] = $groups->fetchAll();
  1489. return $this->_groups[$this->id];
  1490. }
  1491. function _setGroups($groups)
  1492. {
  1493. $this->_groups[$this->id] = $groups;
  1494. }
  1495. /**
  1496. * Convert a notice into an activity for export.
  1497. *
  1498. * @param Profile $scoped The currently logged in/scoped profile
  1499. *
  1500. * @return Activity activity object representing this Notice.
  1501. */
  1502. function asActivity(Profile $scoped=null)
  1503. {
  1504. $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
  1505. if ($act instanceof Activity) {
  1506. return $act;
  1507. }
  1508. $act = new Activity();
  1509. if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
  1510. $act->id = $this->uri;
  1511. $act->time = strtotime($this->created);
  1512. try {
  1513. $act->link = $this->getUrl();
  1514. } catch (InvalidUrlException $e) {
  1515. // The notice is probably a share or similar, which don't
  1516. // have a representational URL of their own.
  1517. }
  1518. $act->content = common_xml_safe_str($this->rendered);
  1519. $profile = $this->getProfile();
  1520. $act->actor = $profile->asActivityObject();
  1521. $act->actor->extra[] = $profile->profileInfo($scoped);
  1522. $act->verb = $this->verb;
  1523. if (!$this->repeat_of) {
  1524. $act->objects[] = $this->asActivityObject();
  1525. }
  1526. // XXX: should this be handled by default processing for object entry?
  1527. // Categories
  1528. $tags = $this->getTags();
  1529. foreach ($tags as $tag) {
  1530. $cat = new AtomCategory();
  1531. $cat->term = $tag;
  1532. $act->categories[] = $cat;
  1533. }
  1534. // Enclosures
  1535. // XXX: use Atom Media and/or File activity objects instead
  1536. $attachments = $this->attachments();
  1537. foreach ($attachments as $attachment) {
  1538. // Include local attachments in Activity
  1539. if (!empty($attachment->filename)) {
  1540. $act->enclosures[] = $attachment->getEnclosure();
  1541. }
  1542. }
  1543. $ctx = new ActivityContext();
  1544. try {
  1545. $reply = $this->getParent();
  1546. $ctx->replyToID = $reply->getUri();
  1547. $ctx->replyToUrl = $reply->getUrl();
  1548. } catch (Exception $e) {
  1549. // This is not a reply to something
  1550. }
  1551. $ctx->location = $this->getLocation();
  1552. $conv = null;
  1553. if (!empty($this->conversation)) {
  1554. $conv = Conversation::getKV('id', $this->conversation);
  1555. if ($conv instanceof Conversation) {
  1556. $ctx->conversation = $conv->uri;
  1557. }
  1558. }
  1559. $reply_ids = $this->getReplies();
  1560. foreach ($reply_ids as $id) {
  1561. $rprofile = Profile::getKV('id', $id);
  1562. if ($rprofile instanceof Profile) {
  1563. $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
  1564. }
  1565. }
  1566. $groups = $this->getGroups();
  1567. foreach ($groups as $group) {
  1568. $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
  1569. }
  1570. switch ($this->scope) {
  1571. case Notice::PUBLIC_SCOPE:
  1572. $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
  1573. break;
  1574. case Notice::FOLLOWER_SCOPE:
  1575. $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
  1576. $ctx->attention[$surl] = ActivityObject::COLLECTION;
  1577. break;
  1578. }
  1579. $act->context = $ctx;
  1580. $source = $this->getSource();
  1581. if ($source instanceof Notice_source) {
  1582. $act->generator = ActivityObject::fromNoticeSource($source);
  1583. }
  1584. // Source
  1585. $atom_feed = $profile->getAtomFeed();
  1586. if (!empty($atom_feed)) {
  1587. $act->source = new ActivitySource();
  1588. // XXX: we should store the actual feed ID
  1589. $act->source->id = $atom_feed;
  1590. // XXX: we should store the actual feed title
  1591. $act->source->title = $profile->getBestName();
  1592. $act->source->links['alternate'] = $profile->profileurl;
  1593. $act->source->links['self'] = $atom_feed;
  1594. $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
  1595. $notice = $profile->getCurrentNotice();
  1596. if ($notice instanceof Notice) {
  1597. $act->source->updated = self::utcDate($notice->created);
  1598. }
  1599. $user = User::getKV('id', $profile->id);
  1600. if ($user instanceof User) {
  1601. $act->source->links['license'] = common_config('license', 'url');
  1602. }
  1603. }
  1604. if ($this->isLocal()) {
  1605. $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
  1606. 'format' => 'atom'));
  1607. $act->editLink = $act->selfLink;
  1608. }
  1609. Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
  1610. }
  1611. self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
  1612. return $act;
  1613. }
  1614. // This has gotten way too long. Needs to be sliced up into functional bits
  1615. // or ideally exported to a utility class.
  1616. function asAtomEntry($namespace=false,
  1617. $source=false,
  1618. $author=true,
  1619. Profile $scoped=null)
  1620. {
  1621. $act = $this->asActivity($scoped);
  1622. $act->extra[] = $this->noticeInfo($scoped);
  1623. return $act->asString($namespace, $author, $source);
  1624. }
  1625. /**
  1626. * Extra notice info for atom entries
  1627. *
  1628. * Clients use some extra notice info in the atom stream.
  1629. * This gives it to them.
  1630. *
  1631. * @param Profile $scoped The currently logged in/scoped profile
  1632. *
  1633. * @return array representation of <statusnet:notice_info> element
  1634. */
  1635. function noticeInfo(Profile $scoped=null)
  1636. {
  1637. // local notice ID (useful to clients for ordering)
  1638. $noticeInfoAttr = array('local_id' => $this->id);
  1639. // notice source
  1640. $ns = $this->getSource();
  1641. if ($ns instanceof Notice_source) {
  1642. $noticeInfoAttr['source'] = $ns->code;
  1643. if (!empty($ns->url)) {
  1644. $noticeInfoAttr['source_link'] = $ns->url;
  1645. if (!empty($ns->name)) {
  1646. $noticeInfoAttr['source'] = '<a href="'
  1647. . htmlspecialchars($ns->url)
  1648. . '" rel="nofollow">'
  1649. . htmlspecialchars($ns->name)
  1650. . '</a>';
  1651. }
  1652. }
  1653. }
  1654. // favorite and repeated
  1655. if ($scoped instanceof Profile) {
  1656. $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
  1657. }
  1658. if (!empty($this->repeat_of)) {
  1659. $noticeInfoAttr['repeat_of'] = $this->repeat_of;
  1660. }
  1661. Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
  1662. return array('statusnet:notice_info', $noticeInfoAttr, null);
  1663. }
  1664. /**
  1665. * Returns an XML string fragment with a reference to a notice as an
  1666. * Activity Streams noun object with the given element type.
  1667. *
  1668. * Assumes that 'activity' namespace has been previously defined.
  1669. *
  1670. * @param string $element one of 'subject', 'object', 'target'
  1671. * @return string
  1672. */
  1673. function asActivityNoun($element)
  1674. {
  1675. $noun = $this->asActivityObject();
  1676. return $noun->asString('activity:' . $element);
  1677. }
  1678. public function asActivityObject()
  1679. {
  1680. $object = new ActivityObject();
  1681. if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
  1682. $object->type = $this->object_type ?: ActivityObject::NOTE;
  1683. $object->id = $this->getUri();
  1684. $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
  1685. $object->content = $this->rendered;
  1686. $object->link = $this->getUrl();
  1687. $object->extra[] = array('status_net', array('notice_id' => $this->id));
  1688. Event::handle('EndActivityObjectFromNotice', array($this, &$object));
  1689. }
  1690. return $object;
  1691. }
  1692. /**
  1693. * Determine which notice, if any, a new notice is in reply to.
  1694. *
  1695. * For conversation tracking, we try to see where this notice fits
  1696. * in the tree. Beware that this may very well give false positives
  1697. * and add replies to wrong threads (if there have been newer posts
  1698. * by the same user as we're replying to).
  1699. *
  1700. * @param Profile $sender Author profile
  1701. * @param string $content Final notice content
  1702. *
  1703. * @return integer ID of replied-to notice, or null for not a reply.
  1704. */
  1705. static function getInlineReplyTo(Profile $sender, $content)
  1706. {
  1707. // Is there an initial @ or T?
  1708. if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
  1709. || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
  1710. $nickname = common_canonical_nickname($match[1]);
  1711. } else {
  1712. return null;
  1713. }
  1714. // Figure out who that is.
  1715. $recipient = common_relative_profile($sender, $nickname, common_sql_now());
  1716. if ($recipient instanceof Profile) {
  1717. // Get their last notice
  1718. $last = $recipient->getCurrentNotice();
  1719. if ($last instanceof Notice) {
  1720. return $last;
  1721. }
  1722. // Maybe in the future we want to handle something else below
  1723. // so don't return getCurrentNotice() immediately.
  1724. }
  1725. return null;
  1726. }
  1727. static function maxContent()
  1728. {
  1729. $contentlimit = common_config('notice', 'contentlimit');
  1730. // null => use global limit (distinct from 0!)
  1731. if (is_null($contentlimit)) {
  1732. $contentlimit = common_config('site', 'textlimit');
  1733. }
  1734. return $contentlimit;
  1735. }
  1736. static function contentTooLong($content)
  1737. {
  1738. $contentlimit = self::maxContent();
  1739. return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
  1740. }
  1741. function getLocation()
  1742. {
  1743. $location = null;
  1744. if (!empty($this->location_id) && !empty($this->location_ns)) {
  1745. $location = Location::fromId($this->location_id, $this->location_ns);
  1746. }
  1747. if (is_null($location)) { // no ID, or Location::fromId() failed
  1748. if (!empty($this->lat) && !empty($this->lon)) {
  1749. $location = Location::fromLatLon($this->lat, $this->lon);
  1750. }
  1751. }
  1752. return $location;
  1753. }
  1754. /**
  1755. * Convenience function for posting a repeat of an existing message.
  1756. *
  1757. * @param Profile $repeater Profile which is doing the repeat
  1758. * @param string $source: posting source key, eg 'web', 'api', etc
  1759. * @return Notice
  1760. *
  1761. * @throws Exception on failure or permission problems
  1762. */
  1763. function repeat(Profile $repeater, $source)
  1764. {
  1765. $author = $this->getProfile();
  1766. // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
  1767. // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
  1768. $content = sprintf(_('RT @%1$s %2$s'),
  1769. $author->getNickname(),
  1770. $this->content);
  1771. $maxlen = self::maxContent();
  1772. if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
  1773. // Web interface and current Twitter API clients will
  1774. // pull the original notice's text, but some older
  1775. // clients and RSS/Atom feeds will see this trimmed text.
  1776. //
  1777. // Unfortunately this is likely to lose tags or URLs
  1778. // at the end of long notices.
  1779. $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
  1780. }
  1781. // Scope is same as this one's
  1782. return self::saveNew($repeater->id,
  1783. $content,
  1784. $source,
  1785. array('repeat_of' => $this->id,
  1786. 'scope' => $this->scope));
  1787. }
  1788. // These are supposed to be in chron order!
  1789. function repeatStream($limit=100)
  1790. {
  1791. $cache = Cache::instance();
  1792. if (empty($cache)) {
  1793. $ids = $this->_repeatStreamDirect($limit);
  1794. } else {
  1795. $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
  1796. if ($idstr !== false) {
  1797. if (empty($idstr)) {
  1798. $ids = array();
  1799. } else {
  1800. $ids = explode(',', $idstr);
  1801. }
  1802. } else {
  1803. $ids = $this->_repeatStreamDirect(100);
  1804. $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
  1805. }
  1806. if ($limit < 100) {
  1807. // We do a max of 100, so slice down to limit
  1808. $ids = array_slice($ids, 0, $limit);
  1809. }
  1810. }
  1811. return NoticeStream::getStreamByIds($ids);
  1812. }
  1813. function _repeatStreamDirect($limit)
  1814. {
  1815. $notice = new Notice();
  1816. $notice->selectAdd(); // clears it
  1817. $notice->selectAdd('id');
  1818. $notice->repeat_of = $this->id;
  1819. $notice->orderBy('created, id'); // NB: asc!
  1820. if (!is_null($limit)) {
  1821. $notice->limit(0, $limit);
  1822. }
  1823. return $notice->fetchAll('id');
  1824. }
  1825. function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
  1826. {
  1827. $options = array();
  1828. if (!empty($location_id) && !empty($location_ns)) {
  1829. $options['location_id'] = $location_id;
  1830. $options['location_ns'] = $location_ns;
  1831. $location = Location::fromId($location_id, $location_ns);
  1832. if ($location instanceof Location) {
  1833. $options['lat'] = $location->lat;
  1834. $options['lon'] = $location->lon;
  1835. }
  1836. } else if (!empty($lat) && !empty($lon)) {
  1837. $options['lat'] = $lat;
  1838. $options['lon'] = $lon;
  1839. $location = Location::fromLatLon($lat, $lon);
  1840. if ($location instanceof Location) {
  1841. $options['location_id'] = $location->location_id;
  1842. $options['location_ns'] = $location->location_ns;
  1843. }
  1844. } else if (!empty($profile)) {
  1845. if (isset($profile->lat) && isset($profile->lon)) {
  1846. $options['lat'] = $profile->lat;
  1847. $options['lon'] = $profile->lon;
  1848. }
  1849. if (isset($profile->location_id) && isset($profile->location_ns)) {
  1850. $options['location_id'] = $profile->location_id;
  1851. $options['location_ns'] = $profile->location_ns;
  1852. }
  1853. }
  1854. return $options;
  1855. }
  1856. function clearAttentions()
  1857. {
  1858. $att = new Attention();
  1859. $att->notice_id = $this->getID();
  1860. if ($att->find()) {
  1861. while ($att->fetch()) {
  1862. // Can't do delete() on the object directly since it won't remove all of it
  1863. $other = clone($att);
  1864. $other->delete();
  1865. }
  1866. }
  1867. }
  1868. function clearReplies()
  1869. {
  1870. $replyNotice = new Notice();
  1871. $replyNotice->reply_to = $this->id;
  1872. //Null any notices that are replies to this notice
  1873. if ($replyNotice->find()) {
  1874. while ($replyNotice->fetch()) {
  1875. $orig = clone($replyNotice);
  1876. $replyNotice->reply_to = null;
  1877. $replyNotice->update($orig);
  1878. }
  1879. }
  1880. // Reply records
  1881. $reply = new Reply();
  1882. $reply->notice_id = $this->id;
  1883. if ($reply->find()) {
  1884. while($reply->fetch()) {
  1885. self::blow('reply:stream:%d', $reply->profile_id);
  1886. $reply->delete();
  1887. }
  1888. }
  1889. $reply->free();
  1890. }
  1891. function clearFiles()
  1892. {
  1893. $f2p = new File_to_post();
  1894. $f2p->post_id = $this->id;
  1895. if ($f2p->find()) {
  1896. while ($f2p->fetch()) {
  1897. $f2p->delete();
  1898. }
  1899. }
  1900. // FIXME: decide whether to delete File objects
  1901. // ...and related (actual) files
  1902. }
  1903. function clearRepeats()
  1904. {
  1905. $repeatNotice = new Notice();
  1906. $repeatNotice->repeat_of = $this->id;
  1907. //Null any notices that are repeats of this notice
  1908. if ($repeatNotice->find()) {
  1909. while ($repeatNotice->fetch()) {
  1910. $orig = clone($repeatNotice);
  1911. $repeatNotice->repeat_of = null;
  1912. $repeatNotice->update($orig);
  1913. }
  1914. }
  1915. }
  1916. function clearTags()
  1917. {
  1918. $tag = new Notice_tag();
  1919. $tag->notice_id = $this->id;
  1920. if ($tag->find()) {
  1921. while ($tag->fetch()) {
  1922. self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
  1923. self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
  1924. self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
  1925. self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
  1926. $tag->delete();
  1927. }
  1928. }
  1929. $tag->free();
  1930. }
  1931. function clearGroupInboxes()
  1932. {
  1933. $gi = new Group_inbox();
  1934. $gi->notice_id = $this->id;
  1935. if ($gi->find()) {
  1936. while ($gi->fetch()) {
  1937. self::blow('user_group:notice_ids:%d', $gi->group_id);
  1938. $gi->delete();
  1939. }
  1940. }
  1941. $gi->free();
  1942. }
  1943. function distribute()
  1944. {
  1945. // We always insert for the author so they don't
  1946. // have to wait
  1947. Event::handle('StartNoticeDistribute', array($this));
  1948. // If there's a failure, we want to _force_
  1949. // distribution at this point.
  1950. try {
  1951. $qm = QueueManager::get();
  1952. $qm->enqueue($this, 'distrib');
  1953. } catch (Exception $e) {
  1954. // If the exception isn't transient, this
  1955. // may throw more exceptions as DQH does
  1956. // its own enqueueing. So, we ignore them!
  1957. try {
  1958. $handler = new DistribQueueHandler();
  1959. $handler->handle($this);
  1960. } catch (Exception $e) {
  1961. common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
  1962. }
  1963. // Re-throw so somebody smarter can handle it.
  1964. throw $e;
  1965. }
  1966. }
  1967. function insert()
  1968. {
  1969. $result = parent::insert();
  1970. if ($result === false) {
  1971. common_log_db_error($this, 'INSERT', __FILE__);
  1972. // TRANS: Server exception thrown when a stored object entry cannot be saved.
  1973. throw new ServerException('Could not save Notice');
  1974. }
  1975. // Profile::hasRepeated() abuses pkeyGet(), so we
  1976. // have to clear manually
  1977. if (!empty($this->repeat_of)) {
  1978. $c = self::memcache();
  1979. if (!empty($c)) {
  1980. $ck = self::multicacheKey('Notice',
  1981. array('profile_id' => $this->profile_id,
  1982. 'repeat_of' => $this->repeat_of));
  1983. $c->delete($ck);
  1984. }
  1985. }
  1986. // Update possibly ID-dependent columns: URI, conversation
  1987. // (now that INSERT has added the notice's local id)
  1988. $orig = clone($this);
  1989. $changed = false;
  1990. // We can only get here if it's a local notice, since remote notices
  1991. // should've bailed out earlier due to lacking a URI.
  1992. if (empty($this->uri)) {
  1993. $this->uri = sprintf('%s%s=%d:%s=%s',
  1994. TagURI::mint(),
  1995. 'noticeId', $this->id,
  1996. 'objectType', $this->get_object_type(true));
  1997. $changed = true;
  1998. }
  1999. if ($changed && $this->update($orig) === false) {
  2000. common_log_db_error($notice, 'UPDATE', __FILE__);
  2001. // TRANS: Server exception thrown when a notice cannot be updated.
  2002. throw new ServerException(_('Problem saving notice.'));
  2003. }
  2004. $this->blowOnInsert();
  2005. return $result;
  2006. }
  2007. /**
  2008. * Get the source of the notice
  2009. *
  2010. * @return Notice_source $ns A notice source object. 'code' is the only attribute
  2011. * guaranteed to be populated.
  2012. */
  2013. function getSource()
  2014. {
  2015. if (empty($this->source)) {
  2016. return false;
  2017. }
  2018. $ns = new Notice_source();
  2019. switch ($this->source) {
  2020. case 'web':
  2021. case 'xmpp':
  2022. case 'mail':
  2023. case 'omb':
  2024. case 'system':
  2025. case 'api':
  2026. $ns->code = $this->source;
  2027. break;
  2028. default:
  2029. $ns = Notice_source::getKV($this->source);
  2030. if (!$ns) {
  2031. $ns = new Notice_source();
  2032. $ns->code = $this->source;
  2033. $app = Oauth_application::getKV('name', $this->source);
  2034. if ($app) {
  2035. $ns->name = $app->name;
  2036. $ns->url = $app->source_url;
  2037. }
  2038. }
  2039. break;
  2040. }
  2041. return $ns;
  2042. }
  2043. /**
  2044. * Determine whether the notice was locally created
  2045. *
  2046. * @return boolean locality
  2047. */
  2048. public function isLocal()
  2049. {
  2050. return ($this->is_local == Notice::LOCAL_PUBLIC ||
  2051. $this->is_local == Notice::LOCAL_NONPUBLIC);
  2052. }
  2053. public function isRepeat()
  2054. {
  2055. return !empty($this->repeat_of);
  2056. }
  2057. /**
  2058. * Get the list of hash tags saved with this notice.
  2059. *
  2060. * @return array of strings
  2061. */
  2062. public function getTags()
  2063. {
  2064. $tags = array();
  2065. $keypart = sprintf('notice:tags:%d', $this->id);
  2066. $tagstr = self::cacheGet($keypart);
  2067. if ($tagstr !== false) {
  2068. $tags = explode(',', $tagstr);
  2069. } else {
  2070. $tag = new Notice_tag();
  2071. $tag->notice_id = $this->id;
  2072. if ($tag->find()) {
  2073. while ($tag->fetch()) {
  2074. $tags[] = $tag->tag;
  2075. }
  2076. }
  2077. self::cacheSet($keypart, implode(',', $tags));
  2078. }
  2079. return $tags;
  2080. }
  2081. static private function utcDate($dt)
  2082. {
  2083. $dateStr = date('d F Y H:i:s', strtotime($dt));
  2084. $d = new DateTime($dateStr, new DateTimeZone('UTC'));
  2085. return $d->format(DATE_W3C);
  2086. }
  2087. /**
  2088. * Look up the creation timestamp for a given notice ID, even
  2089. * if it's been deleted.
  2090. *
  2091. * @param int $id
  2092. * @return mixed string recorded creation timestamp, or false if can't be found
  2093. */
  2094. public static function getAsTimestamp($id)
  2095. {
  2096. if (!$id) {
  2097. return false;
  2098. }
  2099. $notice = Notice::getKV('id', $id);
  2100. if ($notice) {
  2101. return $notice->created;
  2102. }
  2103. $deleted = Deleted_notice::getKV('id', $id);
  2104. if ($deleted) {
  2105. return $deleted->created;
  2106. }
  2107. return false;
  2108. }
  2109. /**
  2110. * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
  2111. * parameter, matching notices posted after the given one (exclusive).
  2112. *
  2113. * If the referenced notice can't be found, will return false.
  2114. *
  2115. * @param int $id
  2116. * @param string $idField
  2117. * @param string $createdField
  2118. * @return mixed string or false if no match
  2119. */
  2120. public static function whereSinceId($id, $idField='id', $createdField='created')
  2121. {
  2122. $since = Notice::getAsTimestamp($id);
  2123. if ($since) {
  2124. return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
  2125. }
  2126. return false;
  2127. }
  2128. /**
  2129. * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
  2130. * parameter, matching notices posted after the given one (exclusive), and
  2131. * if necessary add it to the data object's query.
  2132. *
  2133. * @param DB_DataObject $obj
  2134. * @param int $id
  2135. * @param string $idField
  2136. * @param string $createdField
  2137. * @return mixed string or false if no match
  2138. */
  2139. public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
  2140. {
  2141. $since = self::whereSinceId($id, $idField, $createdField);
  2142. if ($since) {
  2143. $obj->whereAdd($since);
  2144. }
  2145. }
  2146. /**
  2147. * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
  2148. * parameter, matching notices posted before the given one (inclusive).
  2149. *
  2150. * If the referenced notice can't be found, will return false.
  2151. *
  2152. * @param int $id
  2153. * @param string $idField
  2154. * @param string $createdField
  2155. * @return mixed string or false if no match
  2156. */
  2157. public static function whereMaxId($id, $idField='id', $createdField='created')
  2158. {
  2159. $max = Notice::getAsTimestamp($id);
  2160. if ($max) {
  2161. return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
  2162. }
  2163. return false;
  2164. }
  2165. /**
  2166. * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
  2167. * parameter, matching notices posted before the given one (inclusive), and
  2168. * if necessary add it to the data object's query.
  2169. *
  2170. * @param DB_DataObject $obj
  2171. * @param int $id
  2172. * @param string $idField
  2173. * @param string $createdField
  2174. * @return mixed string or false if no match
  2175. */
  2176. public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
  2177. {
  2178. $max = self::whereMaxId($id, $idField, $createdField);
  2179. if ($max) {
  2180. $obj->whereAdd($max);
  2181. }
  2182. }
  2183. function isPublic()
  2184. {
  2185. return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
  2186. ($this->is_local != Notice::GATEWAY));
  2187. }
  2188. /**
  2189. * Check that the given profile is allowed to read, respond to, or otherwise
  2190. * act on this notice.
  2191. *
  2192. * The $scope member is a bitmask of scopes, representing a logical AND of the
  2193. * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
  2194. * "only visible to people who are mentioned in the notice AND are users on this site."
  2195. * Users on the site who are not mentioned in the notice will not be able to see the
  2196. * notice.
  2197. *
  2198. * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
  2199. *
  2200. * @return boolean whether the profile is in the notice's scope
  2201. */
  2202. function inScope($profile)
  2203. {
  2204. if (is_null($profile)) {
  2205. $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
  2206. } else {
  2207. $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
  2208. }
  2209. $result = self::cacheGet($keypart);
  2210. if ($result === false) {
  2211. $bResult = false;
  2212. if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
  2213. $bResult = $this->_inScope($profile);
  2214. Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
  2215. }
  2216. $result = ($bResult) ? 1 : 0;
  2217. self::cacheSet($keypart, $result, 0, 300);
  2218. }
  2219. return ($result == 1) ? true : false;
  2220. }
  2221. protected function _inScope($profile)
  2222. {
  2223. if (!is_null($this->scope)) {
  2224. $scope = $this->scope;
  2225. } else {
  2226. $scope = self::defaultScope();
  2227. }
  2228. if ($scope == 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
  2229. return !$this->isHiddenSpam($profile);
  2230. }
  2231. // If there's scope, anon cannot be in scope
  2232. if (empty($profile)) {
  2233. return false;
  2234. }
  2235. // Author is always in scope
  2236. if ($this->profile_id == $profile->id) {
  2237. return true;
  2238. }
  2239. // Only for users on this site
  2240. if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
  2241. return false;
  2242. }
  2243. // Only for users mentioned in the notice
  2244. if ($scope & Notice::ADDRESSEE_SCOPE) {
  2245. $reply = Reply::pkeyGet(array('notice_id' => $this->id,
  2246. 'profile_id' => $profile->id));
  2247. if (!$reply instanceof Reply) {
  2248. return false;
  2249. }
  2250. }
  2251. // Only for members of the given group
  2252. if ($scope & Notice::GROUP_SCOPE) {
  2253. // XXX: just query for the single membership
  2254. $groups = $this->getGroups();
  2255. $foundOne = false;
  2256. foreach ($groups as $group) {
  2257. if ($profile->isMember($group)) {
  2258. $foundOne = true;
  2259. break;
  2260. }
  2261. }
  2262. if (!$foundOne) {
  2263. return false;
  2264. }
  2265. }
  2266. if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
  2267. if (!Subscription::exists($profile, $this->getProfile())) {
  2268. return false;
  2269. }
  2270. }
  2271. return !$this->isHiddenSpam($profile);
  2272. }
  2273. function isHiddenSpam($profile) {
  2274. // Hide posts by silenced users from everyone but moderators.
  2275. if (common_config('notice', 'hidespam')) {
  2276. try {
  2277. $author = $this->getProfile();
  2278. } catch(Exception $e) {
  2279. // If we can't get an author, keep it hidden.
  2280. // XXX: technically not spam, but, whatever.
  2281. return true;
  2282. }
  2283. if ($author->hasRole(Profile_role::SILENCED)) {
  2284. if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
  2285. return true;
  2286. }
  2287. }
  2288. }
  2289. return false;
  2290. }
  2291. public function getParent()
  2292. {
  2293. $parent = Notice::getKV('id', $this->reply_to);
  2294. if (!$parent instanceof Notice) {
  2295. throw new ServerException('Notice has no parent');
  2296. }
  2297. return $parent;
  2298. }
  2299. /**
  2300. * Magic function called at serialize() time.
  2301. *
  2302. * We use this to drop a couple process-specific references
  2303. * from DB_DataObject which can cause trouble in future
  2304. * processes.
  2305. *
  2306. * @return array of variable names to include in serialization.
  2307. */
  2308. function __sleep()
  2309. {
  2310. $vars = parent::__sleep();
  2311. $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
  2312. return array_diff($vars, $skip);
  2313. }
  2314. static function defaultScope()
  2315. {
  2316. $scope = common_config('notice', 'defaultscope');
  2317. if (is_null($scope)) {
  2318. if (common_config('site', 'private')) {
  2319. $scope = 1;
  2320. } else {
  2321. $scope = 0;
  2322. }
  2323. }
  2324. return $scope;
  2325. }
  2326. static function fillProfiles($notices)
  2327. {
  2328. $map = self::getProfiles($notices);
  2329. foreach ($notices as $entry=>$notice) {
  2330. try {
  2331. if (array_key_exists($notice->profile_id, $map)) {
  2332. $notice->_setProfile($map[$notice->profile_id]);
  2333. }
  2334. } catch (NoProfileException $e) {
  2335. common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
  2336. unset($notices[$entry]);
  2337. }
  2338. }
  2339. return array_values($map);
  2340. }
  2341. static function getProfiles(&$notices)
  2342. {
  2343. $ids = array();
  2344. foreach ($notices as $notice) {
  2345. $ids[] = $notice->profile_id;
  2346. }
  2347. $ids = array_unique($ids);
  2348. return Profile::pivotGet('id', $ids);
  2349. }
  2350. static function fillGroups(&$notices)
  2351. {
  2352. $ids = self::_idsOf($notices);
  2353. $gis = Group_inbox::listGet('notice_id', $ids);
  2354. $gids = array();
  2355. foreach ($gis as $id => $gi) {
  2356. foreach ($gi as $g)
  2357. {
  2358. $gids[] = $g->group_id;
  2359. }
  2360. }
  2361. $gids = array_unique($gids);
  2362. $group = User_group::pivotGet('id', $gids);
  2363. foreach ($notices as $notice)
  2364. {
  2365. $grps = array();
  2366. $gi = $gis[$notice->id];
  2367. foreach ($gi as $g) {
  2368. $grps[] = $group[$g->group_id];
  2369. }
  2370. $notice->_setGroups($grps);
  2371. }
  2372. }
  2373. static function _idsOf(array &$notices)
  2374. {
  2375. $ids = array();
  2376. foreach ($notices as $notice) {
  2377. $ids[$notice->id] = true;
  2378. }
  2379. return array_keys($ids);
  2380. }
  2381. static function fillAttachments(&$notices)
  2382. {
  2383. $ids = self::_idsOf($notices);
  2384. $f2pMap = File_to_post::listGet('post_id', $ids);
  2385. $fileIds = array();
  2386. foreach ($f2pMap as $noticeId => $f2ps) {
  2387. foreach ($f2ps as $f2p) {
  2388. $fileIds[] = $f2p->file_id;
  2389. }
  2390. }
  2391. $fileIds = array_unique($fileIds);
  2392. $fileMap = File::pivotGet('id', $fileIds);
  2393. foreach ($notices as $notice)
  2394. {
  2395. $files = array();
  2396. $f2ps = $f2pMap[$notice->id];
  2397. foreach ($f2ps as $f2p) {
  2398. $files[] = $fileMap[$f2p->file_id];
  2399. }
  2400. $notice->_setAttachments($files);
  2401. }
  2402. }
  2403. static function fillReplies(&$notices)
  2404. {
  2405. $ids = self::_idsOf($notices);
  2406. $replyMap = Reply::listGet('notice_id', $ids);
  2407. foreach ($notices as $notice) {
  2408. $replies = $replyMap[$notice->id];
  2409. $ids = array();
  2410. foreach ($replies as $reply) {
  2411. $ids[] = $reply->profile_id;
  2412. }
  2413. $notice->_setReplies($ids);
  2414. }
  2415. }
  2416. }