Notice.php 116 KB

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