Notice.php 116 KB

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