Notice.php 115 KB

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