Notice.php 115 KB

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