Notice.php 115 KB

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