Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Item.php 118KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644
  1. <?php
  2. /**
  3. * @file src/Model/Item.php
  4. */
  5. namespace Friendica\Model;
  6. use Friendica\BaseObject;
  7. use Friendica\Content\Text\BBCode;
  8. use Friendica\Content\Text\HTML;
  9. use Friendica\Core\Config;
  10. use Friendica\Core\Hook;
  11. use Friendica\Core\L10n;
  12. use Friendica\Core\Lock;
  13. use Friendica\Core\Logger;
  14. use Friendica\Core\PConfig;
  15. use Friendica\Core\Protocol;
  16. use Friendica\Core\Renderer;
  17. use Friendica\Core\System;
  18. use Friendica\Core\Worker;
  19. use Friendica\Database\DBA;
  20. use Friendica\Protocol\Diaspora;
  21. use Friendica\Protocol\OStatus;
  22. use Friendica\Util\DateTimeFormat;
  23. use Friendica\Util\Map;
  24. use Friendica\Util\Network;
  25. use Friendica\Util\Security;
  26. use Friendica\Util\Strings;
  27. use Friendica\Util\XML;
  28. use Friendica\Worker\Delivery;
  29. use Friendica\Protocol\ActivityPub;
  30. use Text_LanguageDetect;
  31. class Item extends BaseObject
  32. {
  33. // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
  34. const PT_ARTICLE = 0;
  35. const PT_NOTE = 1;
  36. const PT_PAGE = 2;
  37. const PT_IMAGE = 16;
  38. const PT_AUDIO = 17;
  39. const PT_VIDEO = 18;
  40. const PT_DOCUMENT = 19;
  41. const PT_EVENT = 32;
  42. const PT_PERSONAL_NOTE = 128;
  43. // Field list that is used to display the items
  44. const DISPLAY_FIELDLIST = [
  45. 'uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network', 'gravity',
  46. 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
  47. 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
  48. 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
  49. 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
  50. 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
  51. 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
  52. 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
  53. 'writable', 'self', 'cid', 'alias',
  54. 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
  55. 'event-summary', 'event-desc', 'event-location', 'event-type',
  56. 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id',
  57. 'delivery_queue_count', 'delivery_queue_done'
  58. ];
  59. // Field list that is used to deliver items via the protocols
  60. const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
  61. 'parent-guid', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
  62. 'private', 'title', 'body', 'location', 'coord', 'app',
  63. 'attach', 'tag', 'deleted', 'extid', 'post-type',
  64. 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
  65. 'author-id', 'author-link', 'owner-link', 'contact-uid',
  66. 'signed_text', 'signature', 'signer', 'network'];
  67. // Field list for "item-content" table that is mixed with the item table
  68. const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
  69. 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
  70. 'object-type', 'object', 'target-type', 'target', 'plink'];
  71. // Field list for "item-content" table that is not present in the "item" table
  72. const CONTENT_FIELDLIST = ['language'];
  73. // All fields in the item table
  74. const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
  75. 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
  76. 'created', 'edited', 'commented', 'received', 'changed', 'verb',
  77. 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
  78. 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
  79. 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
  80. 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
  81. 'title', 'content-warning', 'body', 'location', 'coord', 'app',
  82. 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
  83. 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
  84. 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
  85. // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
  86. // The item-activity table only stores the index and needs this array to know the matching activity.
  87. const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE, ACTIVITY_FOLLOW, ACTIVITY2_ANNOUNCE];
  88. private static $legacy_mode = null;
  89. public static function isLegacyMode()
  90. {
  91. if (is_null(self::$legacy_mode)) {
  92. self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
  93. }
  94. return self::$legacy_mode;
  95. }
  96. /**
  97. * @brief returns an activity index from an activity string
  98. *
  99. * @param string $activity activity string
  100. * @return integer Activity index
  101. */
  102. public static function activityToIndex($activity)
  103. {
  104. $index = array_search($activity, self::ACTIVITIES);
  105. if (is_bool($index)) {
  106. $index = -1;
  107. }
  108. return $index;
  109. }
  110. /**
  111. * @brief returns an activity string from an activity index
  112. *
  113. * @param integer $index activity index
  114. * @return string Activity string
  115. */
  116. private static function indexToActivity($index)
  117. {
  118. if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
  119. return '';
  120. }
  121. return self::ACTIVITIES[$index];
  122. }
  123. /**
  124. * @brief Fetch a single item row
  125. *
  126. * @param mixed $stmt statement object
  127. * @return array current row
  128. */
  129. public static function fetch($stmt)
  130. {
  131. $row = DBA::fetch($stmt);
  132. if (is_bool($row)) {
  133. return $row;
  134. }
  135. // ---------------------- Transform item structure data ----------------------
  136. // We prefer the data from the user's contact over the public one
  137. if (!empty($row['author-link']) && !empty($row['contact-link']) &&
  138. ($row['author-link'] == $row['contact-link'])) {
  139. if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
  140. $row['author-avatar'] = $row['contact-avatar'];
  141. }
  142. if (isset($row['author-name']) && !empty($row['contact-name'])) {
  143. $row['author-name'] = $row['contact-name'];
  144. }
  145. }
  146. if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
  147. ($row['owner-link'] == $row['contact-link'])) {
  148. if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
  149. $row['owner-avatar'] = $row['contact-avatar'];
  150. }
  151. if (isset($row['owner-name']) && !empty($row['contact-name'])) {
  152. $row['owner-name'] = $row['contact-name'];
  153. }
  154. }
  155. // We can always comment on posts from these networks
  156. if (array_key_exists('writable', $row) &&
  157. in_array($row['internal-network'], Protocol::FEDERATED)) {
  158. $row['writable'] = true;
  159. }
  160. // ---------------------- Transform item content data ----------------------
  161. // Fetch data from the item-content table whenever there is content there
  162. if (self::isLegacyMode()) {
  163. $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
  164. foreach ($legacy_fields as $field) {
  165. if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
  166. $row[$field] = $row['internal-item-' . $field];
  167. }
  168. unset($row['internal-item-' . $field]);
  169. }
  170. }
  171. if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
  172. $row['verb'] = self::indexToActivity($row['internal-activity']);
  173. if (array_key_exists('title', $row)) {
  174. $row['title'] = '';
  175. }
  176. if (array_key_exists('body', $row)) {
  177. $row['body'] = $row['verb'];
  178. }
  179. if (array_key_exists('object', $row)) {
  180. $row['object'] = '';
  181. }
  182. if (array_key_exists('object-type', $row)) {
  183. $row['object-type'] = ACTIVITY_OBJ_NOTE;
  184. }
  185. } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
  186. // Posts don't have an object or target - but having tags or files.
  187. // We safe some performance by building tag and file strings only here.
  188. // We remove object and target since they aren't used for this type.
  189. if (array_key_exists('object', $row)) {
  190. $row['object'] = '';
  191. }
  192. if (array_key_exists('target', $row)) {
  193. $row['target'] = '';
  194. }
  195. }
  196. if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
  197. // Build the tag string out of the term entries
  198. if (array_key_exists('tag', $row) && empty($row['tag'])) {
  199. $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
  200. }
  201. // Build the file string out of the term entries
  202. if (array_key_exists('file', $row) && empty($row['file'])) {
  203. $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
  204. }
  205. }
  206. if (array_key_exists('signed_text', $row) && array_key_exists('interaction', $row) && !is_null($row['interaction'])) {
  207. $row['signed_text'] = $row['interaction'];
  208. }
  209. if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
  210. $row['ignored'] = $row['internal-user-ignored'];
  211. }
  212. // Remove internal fields
  213. unset($row['internal-activity']);
  214. unset($row['internal-network']);
  215. unset($row['internal-iid']);
  216. unset($row['internal-iaid']);
  217. unset($row['internal-icid']);
  218. unset($row['internal-user-ignored']);
  219. unset($row['interaction']);
  220. return $row;
  221. }
  222. /**
  223. * @brief Fills an array with data from an item query
  224. *
  225. * @param object $stmt statement object
  226. * @param bool $do_close
  227. * @return array Data array
  228. */
  229. public static function inArray($stmt, $do_close = true) {
  230. if (is_bool($stmt)) {
  231. return $stmt;
  232. }
  233. $data = [];
  234. while ($row = self::fetch($stmt)) {
  235. $data[] = $row;
  236. }
  237. if ($do_close) {
  238. DBA::close($stmt);
  239. }
  240. return $data;
  241. }
  242. /**
  243. * @brief Check if item data exists
  244. *
  245. * @param array $condition array of fields for condition
  246. *
  247. * @return boolean Are there rows for that condition?
  248. * @throws \Exception
  249. */
  250. public static function exists($condition) {
  251. $stmt = self::select(['id'], $condition, ['limit' => 1]);
  252. if (is_bool($stmt)) {
  253. $retval = $stmt;
  254. } else {
  255. $retval = (DBA::numRows($stmt) > 0);
  256. }
  257. DBA::close($stmt);
  258. return $retval;
  259. }
  260. /**
  261. * Retrieve a single record from the item table for a given user and returns it in an associative array
  262. *
  263. * @brief Retrieve a single record from a table
  264. * @param integer $uid User ID
  265. * @param array $selected
  266. * @param array $condition
  267. * @param array $params
  268. * @return bool|array
  269. * @throws \Exception
  270. * @see DBA::select
  271. */
  272. public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
  273. {
  274. $params['uid'] = $uid;
  275. if (empty($selected)) {
  276. $selected = Item::DISPLAY_FIELDLIST;
  277. }
  278. return self::selectFirst($selected, $condition, $params);
  279. }
  280. /**
  281. * @brief Select rows from the item table for a given user
  282. *
  283. * @param integer $uid User ID
  284. * @param array $selected Array of selected fields, empty for all
  285. * @param array $condition Array of fields for condition
  286. * @param array $params Array of several parameters
  287. *
  288. * @return boolean|object
  289. * @throws \Exception
  290. */
  291. public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
  292. {
  293. $params['uid'] = $uid;
  294. if (empty($selected)) {
  295. $selected = Item::DISPLAY_FIELDLIST;
  296. }
  297. return self::select($selected, $condition, $params);
  298. }
  299. /**
  300. * Retrieve a single record from the item table and returns it in an associative array
  301. *
  302. * @brief Retrieve a single record from a table
  303. * @param array $fields
  304. * @param array $condition
  305. * @param array $params
  306. * @return bool|array
  307. * @throws \Exception
  308. * @see DBA::select
  309. */
  310. public static function selectFirst(array $fields = [], array $condition = [], $params = [])
  311. {
  312. $params['limit'] = 1;
  313. $result = self::select($fields, $condition, $params);
  314. if (is_bool($result)) {
  315. return $result;
  316. } else {
  317. $row = self::fetch($result);
  318. DBA::close($result);
  319. return $row;
  320. }
  321. }
  322. /**
  323. * @brief Select rows from the item table
  324. *
  325. * @param array $selected Array of selected fields, empty for all
  326. * @param array $condition Array of fields for condition
  327. * @param array $params Array of several parameters
  328. *
  329. * @return boolean|object
  330. * @throws \Exception
  331. */
  332. public static function select(array $selected = [], array $condition = [], $params = [])
  333. {
  334. $uid = 0;
  335. $usermode = false;
  336. if (isset($params['uid'])) {
  337. $uid = $params['uid'];
  338. $usermode = true;
  339. }
  340. $fields = self::fieldlist($usermode);
  341. $select_fields = self::constructSelectFields($fields, $selected);
  342. $condition_string = DBA::buildCondition($condition);
  343. $condition_string = self::addTablesToFields($condition_string, $fields);
  344. if ($usermode) {
  345. $condition_string = $condition_string . ' AND ' . self::condition(false);
  346. }
  347. $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
  348. $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
  349. $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
  350. return DBA::p($sql, $condition);
  351. }
  352. /**
  353. * @brief Select rows from the starting post in the item table
  354. *
  355. * @param integer $uid User ID
  356. * @param array $selected
  357. * @param array $condition Array of fields for condition
  358. * @param array $params Array of several parameters
  359. *
  360. * @return boolean|object
  361. * @throws \Exception
  362. */
  363. public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
  364. {
  365. $params['uid'] = $uid;
  366. if (empty($selected)) {
  367. $selected = Item::DISPLAY_FIELDLIST;
  368. }
  369. return self::selectThread($selected, $condition, $params);
  370. }
  371. /**
  372. * Retrieve a single record from the starting post in the item table and returns it in an associative array
  373. *
  374. * @brief Retrieve a single record from a table
  375. * @param integer $uid User ID
  376. * @param array $selected
  377. * @param array $condition
  378. * @param array $params
  379. * @return bool|array
  380. * @throws \Exception
  381. * @see DBA::select
  382. */
  383. public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
  384. {
  385. $params['uid'] = $uid;
  386. if (empty($selected)) {
  387. $selected = Item::DISPLAY_FIELDLIST;
  388. }
  389. return self::selectFirstThread($selected, $condition, $params);
  390. }
  391. /**
  392. * Retrieve a single record from the starting post in the item table and returns it in an associative array
  393. *
  394. * @brief Retrieve a single record from a table
  395. * @param array $fields
  396. * @param array $condition
  397. * @param array $params
  398. * @return bool|array
  399. * @throws \Exception
  400. * @see DBA::select
  401. */
  402. public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
  403. {
  404. $params['limit'] = 1;
  405. $result = self::selectThread($fields, $condition, $params);
  406. if (is_bool($result)) {
  407. return $result;
  408. } else {
  409. $row = self::fetch($result);
  410. DBA::close($result);
  411. return $row;
  412. }
  413. }
  414. /**
  415. * @brief Select rows from the starting post in the item table
  416. *
  417. * @param array $selected Array of selected fields, empty for all
  418. * @param array $condition Array of fields for condition
  419. * @param array $params Array of several parameters
  420. *
  421. * @return boolean|object
  422. * @throws \Exception
  423. */
  424. public static function selectThread(array $selected = [], array $condition = [], $params = [])
  425. {
  426. $uid = 0;
  427. $usermode = false;
  428. if (isset($params['uid'])) {
  429. $uid = $params['uid'];
  430. $usermode = true;
  431. }
  432. $fields = self::fieldlist($usermode);
  433. $fields['thread'] = ['mention', 'ignored', 'iid'];
  434. $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
  435. 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
  436. 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
  437. 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
  438. $select_fields = self::constructSelectFields($fields, $selected);
  439. $condition_string = DBA::buildCondition($condition);
  440. $condition_string = self::addTablesToFields($condition_string, $threadfields);
  441. $condition_string = self::addTablesToFields($condition_string, $fields);
  442. if ($usermode) {
  443. $condition_string = $condition_string . ' AND ' . self::condition(true);
  444. }
  445. $param_string = DBA::buildParameter($params);
  446. $param_string = self::addTablesToFields($param_string, $threadfields);
  447. $param_string = self::addTablesToFields($param_string, $fields);
  448. $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
  449. $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
  450. return DBA::p($sql, $condition);
  451. }
  452. /**
  453. * @brief Returns a list of fields that are associated with the item table
  454. *
  455. * @param $usermode
  456. * @return array field list
  457. */
  458. private static function fieldlist($usermode)
  459. {
  460. $fields = [];
  461. $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
  462. 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
  463. 'created', 'edited', 'commented', 'received', 'changed', 'psid',
  464. 'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
  465. 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
  466. 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
  467. 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
  468. 'network' => 'internal-network', 'icid' => 'internal-icid',
  469. 'iaid' => 'internal-iaid'];
  470. if ($usermode) {
  471. $fields['user-item'] = ['ignored' => 'internal-user-ignored'];
  472. }
  473. $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
  474. $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
  475. $fields['item-delivery-data'] = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, ItemDeliveryData::FIELD_LIST);
  476. $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
  477. $fields['author'] = ['url' => 'author-link', 'name' => 'author-name', 'addr' => 'author-addr',
  478. 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
  479. $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name', 'addr' => 'owner-addr',
  480. 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
  481. $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
  482. 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
  483. 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
  484. $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
  485. $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
  486. $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
  487. 'start' => 'event-start','finish' => 'event-finish',
  488. 'summary' => 'event-summary','desc' => 'event-desc',
  489. 'location' => 'event-location', 'type' => 'event-type',
  490. 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
  491. 'ignore' => 'event-ignore', 'id' => 'event-id'];
  492. $fields['sign'] = ['signed_text', 'signature', 'signer'];
  493. $fields['diaspora-interaction'] = ['interaction'];
  494. return $fields;
  495. }
  496. /**
  497. * @brief Returns SQL condition for the "select" functions
  498. *
  499. * @param boolean $thread_mode Called for the items (false) or for the threads (true)
  500. *
  501. * @return string SQL condition
  502. */
  503. private static function condition($thread_mode)
  504. {
  505. if ($thread_mode) {
  506. $master_table = "`thread`";
  507. } else {
  508. $master_table = "`item`";
  509. }
  510. return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
  511. AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
  512. AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
  513. AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
  514. AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
  515. AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
  516. GRAVITY_PARENT, GRAVITY_PARENT);
  517. }
  518. /**
  519. * @brief Returns all needed "JOIN" commands for the "select" functions
  520. *
  521. * @param integer $uid User ID
  522. * @param string $sql_commands The parts of the built SQL commands in the "select" functions
  523. * @param boolean $thread_mode Called for the items (false) or for the threads (true)
  524. *
  525. * @param $user_mode
  526. * @return string The SQL joins for the "select" functions
  527. */
  528. private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
  529. {
  530. if ($thread_mode) {
  531. $master_table = "`thread`";
  532. $master_table_key = "`thread`.`iid`";
  533. $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
  534. } else {
  535. $master_table = "`item`";
  536. $master_table_key = "`item`.`id`";
  537. $joins = '';
  538. }
  539. if ($user_mode) {
  540. $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
  541. AND NOT `contact`.`blocked`
  542. AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
  543. OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
  544. STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
  545. STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
  546. LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
  547. LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
  548. LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
  549. Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
  550. } else {
  551. if (strpos($sql_commands, "`contact`.") !== false) {
  552. $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
  553. }
  554. if (strpos($sql_commands, "`author`.") !== false) {
  555. $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
  556. }
  557. if (strpos($sql_commands, "`owner`.") !== false) {
  558. $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
  559. }
  560. }
  561. if (strpos($sql_commands, "`group_member`.") !== false) {
  562. $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
  563. }
  564. if (strpos($sql_commands, "`user`.") !== false) {
  565. $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
  566. }
  567. if (strpos($sql_commands, "`event`.") !== false) {
  568. $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
  569. }
  570. if (strpos($sql_commands, "`sign`.") !== false) {
  571. $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
  572. }
  573. if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
  574. $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
  575. }
  576. if (strpos($sql_commands, "`item-activity`.") !== false) {
  577. $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id`";
  578. }
  579. if (strpos($sql_commands, "`item-content`.") !== false) {
  580. $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
  581. }
  582. if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
  583. $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
  584. }
  585. if (strpos($sql_commands, "`permissionset`.") !== false) {
  586. $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
  587. }
  588. if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
  589. $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
  590. }
  591. if (strpos($sql_commands, "`parent-item-author`.") !== false) {
  592. $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
  593. }
  594. return $joins;
  595. }
  596. /**
  597. * @brief Add the field list for the "select" functions
  598. *
  599. * @param array $fields The field definition array
  600. * @param array $selected The array with the selected fields from the "select" functions
  601. *
  602. * @return string The field list
  603. */
  604. private static function constructSelectFields($fields, $selected)
  605. {
  606. if (!empty($selected)) {
  607. $selected[] = 'internal-iid';
  608. $selected[] = 'internal-iaid';
  609. $selected[] = 'internal-icid';
  610. $selected[] = 'internal-network';
  611. }
  612. if (in_array('verb', $selected)) {
  613. $selected[] = 'internal-activity';
  614. }
  615. if (in_array('ignored', $selected)) {
  616. $selected[] = 'internal-user-ignored';
  617. }
  618. if (in_array('signed_text', $selected)) {
  619. $selected[] = 'interaction';
  620. }
  621. $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
  622. $selection = [];
  623. foreach ($fields as $table => $table_fields) {
  624. foreach ($table_fields as $field => $select) {
  625. if (empty($selected) || in_array($select, $selected)) {
  626. if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
  627. $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
  628. }
  629. if (is_int($field)) {
  630. $selection[] = "`" . $table . "`.`" . $select . "`";
  631. } else {
  632. $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
  633. }
  634. }
  635. }
  636. }
  637. return implode(", ", $selection);
  638. }
  639. /**
  640. * @brief add table definition to fields in an SQL query
  641. *
  642. * @param string $query SQL query
  643. * @param array $fields The field definition array
  644. *
  645. * @return string the changed SQL query
  646. */
  647. private static function addTablesToFields($query, $fields)
  648. {
  649. foreach ($fields as $table => $table_fields) {
  650. foreach ($table_fields as $alias => $field) {
  651. if (is_int($alias)) {
  652. $replace_field = $field;
  653. } else {
  654. $replace_field = $alias;
  655. }
  656. $search = "/([^\.])`" . $field . "`/i";
  657. $replace = "$1`" . $table . "`.`" . $replace_field . "`";
  658. $query = preg_replace($search, $replace, $query);
  659. }
  660. }
  661. return $query;
  662. }
  663. /**
  664. * @brief Update existing item entries
  665. *
  666. * @param array $fields The fields that are to be changed
  667. * @param array $condition The condition for finding the item entries
  668. *
  669. * In the future we may have to change permissions as well.
  670. * Then we had to add the user id as third parameter.
  671. *
  672. * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
  673. *
  674. * @return integer|boolean number of affected rows - or "false" if there was an error
  675. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  676. */
  677. public static function update(array $fields, array $condition)
  678. {
  679. if (empty($condition) || empty($fields)) {
  680. return false;
  681. }
  682. // To ensure the data integrity we do it in an transaction
  683. DBA::transaction();
  684. // We cannot simply expand the condition to check for origin entries
  685. // The condition needn't to be a simple array but could be a complex condition.
  686. // And we have to execute this query before the update to ensure to fetch the same data.
  687. $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'iaid', 'icid', 'tag', 'file'], $condition);
  688. $content_fields = [];
  689. foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
  690. if (isset($fields[$field])) {
  691. $content_fields[$field] = $fields[$field];
  692. if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
  693. unset($fields[$field]);
  694. } else {
  695. $fields[$field] = null;
  696. }
  697. }
  698. }
  699. $delivery_data = ItemDeliveryData::extractFields($fields);
  700. $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'postopts', 'inform'];
  701. foreach ($clear_fields as $field) {
  702. if (array_key_exists($field, $fields)) {
  703. $fields[$field] = null;
  704. }
  705. }
  706. if (array_key_exists('tag', $fields)) {
  707. $tags = $fields['tag'];
  708. $fields['tag'] = null;
  709. } else {
  710. $tags = null;
  711. }
  712. if (array_key_exists('file', $fields)) {
  713. $files = $fields['file'];
  714. $fields['file'] = null;
  715. } else {
  716. $files = null;
  717. }
  718. if (!empty($fields)) {
  719. $success = DBA::update('item', $fields, $condition);
  720. if (!$success) {
  721. DBA::close($items);
  722. DBA::rollback();
  723. return false;
  724. }
  725. }
  726. // When there is no content for the "old" item table, this will count the fetched items
  727. $rows = DBA::affectedRows();
  728. while ($item = DBA::fetch($items)) {
  729. if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
  730. self::updateActivity($content_fields, ['uri-id' => $item['uri-id']]);
  731. if (empty($item['iaid'])) {
  732. $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
  733. if (DBA::isResult($item_activity)) {
  734. $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
  735. foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
  736. if (self::isLegacyMode()) {
  737. $item_fields[$field] = null;
  738. } else {
  739. unset($item_fields[$field]);
  740. }
  741. }
  742. DBA::update('item', $item_fields, ['id' => $item['id']]);
  743. if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
  744. DBA::delete('item-content', ['id' => $item['icid']]);
  745. }
  746. }
  747. } elseif (!empty($item['icid'])) {
  748. DBA::update('item', ['icid' => null], ['id' => $item['id']]);
  749. if (!DBA::exists('item', ['icid' => $item['icid']])) {
  750. DBA::delete('item-content', ['id' => $item['icid']]);
  751. }
  752. }
  753. } else {
  754. self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
  755. if (empty($item['icid'])) {
  756. $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
  757. if (DBA::isResult($item_content)) {
  758. $item_fields = ['icid' => $item_content['id']];
  759. // Clear all fields in the item table that have a content in the item-content table
  760. foreach ($item_content as $field => $content) {
  761. if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
  762. if (self::isLegacyMode()) {
  763. $item_fields[$field] = null;
  764. } else {
  765. unset($item_fields[$field]);
  766. }
  767. }
  768. }
  769. DBA::update('item', $item_fields, ['id' => $item['id']]);
  770. }
  771. }
  772. }
  773. if (!is_null($tags)) {
  774. Term::insertFromTagFieldByItemId($item['id'], $tags);
  775. if (!empty($item['tag'])) {
  776. DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
  777. }
  778. }
  779. if (!is_null($files)) {
  780. Term::insertFromFileFieldByItemId($item['id'], $files);
  781. if (!empty($item['file'])) {
  782. DBA::update('item', ['file' => ''], ['id' => $item['id']]);
  783. }
  784. }
  785. ItemDeliveryData::update($item['id'], $delivery_data);
  786. self::updateThread($item['id']);
  787. // We only need to notfiy others when it is an original entry from us.
  788. // Only call the notifier when the item has some content relevant change.
  789. if ($item['origin'] && in_array('edited', array_keys($fields))) {
  790. Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, $item['id']);
  791. }
  792. }
  793. DBA::close($items);
  794. DBA::commit();
  795. return $rows;
  796. }
  797. /**
  798. * @brief Delete an item and notify others about it - if it was ours
  799. *
  800. * @param array $condition The condition for finding the item entries
  801. * @param integer $priority Priority for the notification
  802. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  803. */
  804. public static function delete($condition, $priority = PRIORITY_HIGH)
  805. {
  806. $items = self::select(['id'], $condition);
  807. while ($item = self::fetch($items)) {
  808. self::deleteById($item['id'], $priority);
  809. }
  810. DBA::close($items);
  811. }
  812. /**
  813. * @brief Delete an item for an user and notify others about it - if it was ours
  814. *
  815. * @param array $condition The condition for finding the item entries
  816. * @param integer $uid User who wants to delete this item
  817. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  818. */
  819. public static function deleteForUser($condition, $uid)
  820. {
  821. if ($uid == 0) {
  822. return;
  823. }
  824. $items = self::select(['id', 'uid'], $condition);
  825. while ($item = self::fetch($items)) {
  826. // "Deleting" global items just means hiding them
  827. if ($item['uid'] == 0) {
  828. DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
  829. } elseif ($item['uid'] == $uid) {
  830. self::deleteById($item['id'], PRIORITY_HIGH);
  831. } else {
  832. Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
  833. }
  834. }
  835. DBA::close($items);
  836. }
  837. /**
  838. * @brief Delete an item and notify others about it - if it was ours
  839. *
  840. * @param integer $item_id Item ID that should be delete
  841. * @param integer $priority Priority for the notification
  842. *
  843. * @return boolean success
  844. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  845. */
  846. public static function deleteById($item_id, $priority = PRIORITY_HIGH)
  847. {
  848. // locate item to be deleted
  849. $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
  850. 'deleted', 'file', 'resource-id', 'event-id', 'attach',
  851. 'verb', 'object-type', 'object', 'target', 'contact-id',
  852. 'icid', 'iaid', 'psid'];
  853. $item = self::selectFirst($fields, ['id' => $item_id]);
  854. if (!DBA::isResult($item)) {
  855. Logger::log('Item with ID ' . $item_id . " hasn't been found.", Logger::DEBUG);
  856. return false;
  857. }
  858. if ($item['deleted']) {
  859. Logger::log('Item with ID ' . $item_id . ' has already been deleted.', Logger::DEBUG);
  860. return false;
  861. }
  862. $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
  863. if (!DBA::isResult($parent)) {
  864. $parent = ['origin' => false];
  865. }
  866. // clean up categories and tags so they don't end up as orphans
  867. $matches = false;
  868. $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
  869. if ($cnt) {
  870. foreach ($matches as $mtch) {
  871. FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],true);
  872. }
  873. }
  874. $matches = false;
  875. $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
  876. if ($cnt) {
  877. foreach ($matches as $mtch) {
  878. FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],false);
  879. }
  880. }
  881. /*
  882. * If item is a link to a photo resource, nuke all the associated photos
  883. * (visitors will not have photo resources)
  884. * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
  885. * generate a resource-id and therefore aren't intimately linked to the item.
  886. */
  887. /// @TODO: this should first check if photo is used elsewhere
  888. if (strlen($item['resource-id'])) {
  889. Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
  890. }
  891. // If item is a link to an event, delete the event.
  892. if (intval($item['event-id'])) {
  893. Event::delete($item['event-id']);
  894. }
  895. // If item has attachments, drop them
  896. /// @TODO: this should first check if attachment is used elsewhere
  897. foreach (explode(",", $item['attach']) as $attach) {
  898. preg_match("|attach/(\d+)|", $attach, $matches);
  899. if (is_array($matches) && count($matches) > 1) {
  900. Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
  901. }
  902. }
  903. // Delete tags that had been attached to other items
  904. self::deleteTagsFromItem($item);
  905. // Set the item to "deleted"
  906. $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
  907. DBA::update('item', $item_fields, ['id' => $item['id']]);
  908. Term::insertFromTagFieldByItemId($item['id'], '');
  909. Term::insertFromFileFieldByItemId($item['id'], '');
  910. self::deleteThread($item['id'], $item['parent-uri']);
  911. if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
  912. self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
  913. }
  914. ItemDeliveryData::delete($item['id']);
  915. // We don't delete the item-activity here, since we need some of the data for ActivityPub
  916. if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
  917. DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
  918. }
  919. // When the permission set will be used in photo and events as well,
  920. // this query here needs to be extended.
  921. // @todo Currently deactivated. We need the permission set in the deletion process.
  922. // This is a reminder to add the removal somewhere else.
  923. //if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
  924. // DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
  925. //}
  926. // If it's the parent of a comment thread, kill all the kids
  927. if ($item['id'] == $item['parent']) {
  928. self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
  929. }
  930. // Is it our comment and/or our thread?
  931. if ($item['origin'] || $parent['origin']) {
  932. // When we delete the original post we will delete all existing copies on the server as well
  933. self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
  934. // send the notification upstream/downstream
  935. Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, intval($item['id']));
  936. } elseif ($item['uid'] != 0) {
  937. // When we delete just our local user copy of an item, we have to set a marker to hide it
  938. $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
  939. if (DBA::isResult($global_item)) {
  940. DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
  941. }
  942. }
  943. Logger::log('Item with ID ' . $item_id . " has been deleted.", Logger::DEBUG);
  944. return true;
  945. }
  946. private static function deleteTagsFromItem($item)
  947. {
  948. if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
  949. return;
  950. }
  951. $xo = XML::parseString($item["object"], false);
  952. $xt = XML::parseString($item["target"], false);
  953. if ($xt->type != ACTIVITY_OBJ_NOTE) {
  954. return;
  955. }
  956. $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
  957. if (!DBA::isResult($i)) {
  958. return;
  959. }
  960. // For tags, the owner cannot remove the tag on the author's copy of the post.
  961. $owner_remove = ($item["contact-id"] == $i["contact-id"]);
  962. $author_copy = $item["origin"];
  963. if (($owner_remove && $author_copy) || !$owner_remove) {
  964. return;
  965. }
  966. $tags = explode(',', $i["tag"]);
  967. $newtags = [];
  968. if (count($tags)) {
  969. foreach ($tags as $tag) {
  970. if (trim($tag) !== trim($xo->body)) {
  971. $newtags[] = trim($tag);
  972. }
  973. }
  974. }
  975. self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
  976. }
  977. private static function guid($item, $notify)
  978. {
  979. if (!empty($item['guid'])) {
  980. return Strings::escapeTags(trim($item['guid']));
  981. }
  982. if ($notify) {
  983. // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
  984. // We add the hash of our own host because our host is the original creator of the post.
  985. $prefix_host = \get_app()->getHostName();
  986. } else {
  987. $prefix_host = '';
  988. // We are only storing the post so we create a GUID from the original hostname.
  989. if (!empty($item['author-link'])) {
  990. $parsed = parse_url($item['author-link']);
  991. if (!empty($parsed['host'])) {
  992. $prefix_host = $parsed['host'];
  993. }
  994. }
  995. if (empty($prefix_host) && !empty($item['plink'])) {
  996. $parsed = parse_url($item['plink']);
  997. if (!empty($parsed['host'])) {
  998. $prefix_host = $parsed['host'];
  999. }
  1000. }
  1001. if (empty($prefix_host) && !empty($item['uri'])) {
  1002. $parsed = parse_url($item['uri']);
  1003. if (!empty($parsed['host'])) {
  1004. $prefix_host = $parsed['host'];
  1005. }
  1006. }
  1007. // Is it in the format data@host.tld? - Used for mail contacts
  1008. if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
  1009. $mailparts = explode('@', $item['author-link']);
  1010. $prefix_host = array_pop($mailparts);
  1011. }
  1012. }
  1013. if (!empty($item['plink'])) {
  1014. $guid = self::guidFromUri($item['plink'], $prefix_host);
  1015. } elseif (!empty($item['uri'])) {
  1016. $guid = self::guidFromUri($item['uri'], $prefix_host);
  1017. } else {
  1018. $guid = System::createUUID(hash('crc32', $prefix_host));
  1019. }
  1020. return $guid;
  1021. }
  1022. private static function contactId($item)
  1023. {
  1024. $contact_id = (int)$item["contact-id"];
  1025. if (!empty($contact_id)) {
  1026. return $contact_id;
  1027. }
  1028. Logger::log('Missing contact-id. Called by: '.System::callstack(), Logger::DEBUG);
  1029. /*
  1030. * First we are looking for a suitable contact that matches with the author of the post
  1031. * This is done only for comments
  1032. */
  1033. if ($item['parent-uri'] != $item['uri']) {
  1034. $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
  1035. }
  1036. // If not present then maybe the owner was found
  1037. if ($contact_id == 0) {
  1038. $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
  1039. }
  1040. // Still missing? Then use the "self" contact of the current user
  1041. if ($contact_id == 0) {
  1042. $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
  1043. if (DBA::isResult($self)) {
  1044. $contact_id = $self["id"];
  1045. }
  1046. }
  1047. Logger::log("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, Logger::DEBUG);
  1048. return $contact_id;
  1049. }
  1050. // This function will finally cover most of the preparation functionality in mod/item.php
  1051. public static function prepare(&$item)
  1052. {
  1053. /*
  1054. * @TODO: Unused code triggering inspection errors
  1055. *
  1056. $data = BBCode::getAttachmentData($item['body']);
  1057. if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
  1058. && ($posttype != Item::PT_PERSONAL_NOTE)) {
  1059. $posttype = Item::PT_PAGE;
  1060. $objecttype = ACTIVITY_OBJ_BOOKMARK;
  1061. }
  1062. */
  1063. }
  1064. public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
  1065. {
  1066. $orig_item = $item;
  1067. $priority = PRIORITY_HIGH;
  1068. // If it is a posting where users should get notifications, then define it as wall posting
  1069. if ($notify) {
  1070. $item['wall'] = 1;
  1071. $item['origin'] = 1;
  1072. $item['network'] = Protocol::DFRN;
  1073. $item['protocol'] = Conversation::PARCEL_DFRN;
  1074. if (is_int($notify)) {
  1075. $priority = $notify;
  1076. }
  1077. } else {
  1078. $item['network'] = trim(defaults($item, 'network', Protocol::PHANTOM));
  1079. }
  1080. $item['guid'] = self::guid($item, $notify);
  1081. $item['uri'] = Strings::escapeTags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
  1082. // Store URI data
  1083. $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
  1084. // Store conversation data
  1085. $item = Conversation::insert($item);
  1086. /*
  1087. * If a Diaspora signature structure was passed in, pull it out of the
  1088. * item array and set it aside for later storage.
  1089. */
  1090. $dsprsig = null;
  1091. if (isset($item['dsprsig'])) {
  1092. $encoded_signature = $item['dsprsig'];
  1093. $dsprsig = json_decode(base64_decode($item['dsprsig']));
  1094. unset($item['dsprsig']);
  1095. }
  1096. $diaspora_signed_text = '';
  1097. if (isset($item['diaspora_signed_text'])) {
  1098. $diaspora_signed_text = $item['diaspora_signed_text'];
  1099. unset($item['diaspora_signed_text']);
  1100. }
  1101. // Converting the plink
  1102. /// @TODO Check if this is really still needed
  1103. if ($item['network'] == Protocol::OSTATUS) {
  1104. if (isset($item['plink'])) {
  1105. $item['plink'] = OStatus::convertHref($item['plink']);
  1106. } elseif (isset($item['uri'])) {
  1107. $item['plink'] = OStatus::convertHref($item['uri']);
  1108. }
  1109. }
  1110. if (!empty($item['thr-parent'])) {
  1111. $item['parent-uri'] = $item['thr-parent'];
  1112. }
  1113. if (isset($item['gravity'])) {
  1114. $item['gravity'] = intval($item['gravity']);
  1115. } elseif ($item['parent-uri'] === $item['uri']) {
  1116. $item['gravity'] = GRAVITY_PARENT;
  1117. } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
  1118. $item['gravity'] = GRAVITY_COMMENT;
  1119. } elseif (activity_match($item['verb'], ACTIVITY_FOLLOW)) {
  1120. $item['gravity'] = GRAVITY_ACTIVITY;
  1121. } else {
  1122. $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
  1123. Logger::log('Unknown gravity for verb: ' . $item['verb'], Logger::DEBUG);
  1124. }
  1125. $uid = intval($item['uid']);
  1126. // check for create date and expire time
  1127. $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
  1128. $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
  1129. if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
  1130. $expire_interval = $user['expire'];
  1131. }
  1132. if (($expire_interval > 0) && !empty($item['created'])) {
  1133. $expire_date = time() - ($expire_interval * 86400);
  1134. $created_date = strtotime($item['created']);
  1135. if ($created_date < $expire_date) {
  1136. Logger::notice('Item created before expiration interval.', [
  1137. 'created' => date('c', $created_date),
  1138. 'expired' => date('c', $expire_date),
  1139. '$item' => $item
  1140. ]);
  1141. return 0;
  1142. }
  1143. }
  1144. /*
  1145. * Do we already have this item?
  1146. * We have to check several networks since Friendica posts could be repeated
  1147. * via OStatus (maybe Diasporsa as well)
  1148. */
  1149. if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
  1150. $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
  1151. trim($item['uri']), $item['uid'],
  1152. Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
  1153. $existing = self::selectFirst(['id', 'network'], $condition);
  1154. if (DBA::isResult($existing)) {
  1155. // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
  1156. if ($uid != 0) {
  1157. Logger::notice('Item already existed for user', [
  1158. 'uri' => $item['uri'],
  1159. 'uid' => $uid,
  1160. 'network' => $item['network'],
  1161. 'existing_id' => $existing["id"],
  1162. 'existing_network' => $existing["network"]
  1163. ]);
  1164. }
  1165. return $existing["id"];
  1166. }
  1167. }
  1168. $item['wall'] = intval(defaults($item, 'wall', 0));
  1169. $item['extid'] = trim(defaults($item, 'extid', ''));
  1170. $item['author-name'] = trim(defaults($item, 'author-name', ''));
  1171. $item['author-link'] = trim(defaults($item, 'author-link', ''));
  1172. $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
  1173. $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
  1174. $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
  1175. $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
  1176. $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
  1177. $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
  1178. $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
  1179. $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
  1180. $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
  1181. $item['title'] = trim(defaults($item, 'title', ''));
  1182. $item['location'] = trim(defaults($item, 'location', ''));
  1183. $item['coord'] = trim(defaults($item, 'coord', ''));
  1184. $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
  1185. $item['deleted'] = 0;
  1186. $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
  1187. $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
  1188. $item['verb'] = trim(defaults($item, 'verb', ''));
  1189. $item['object-type'] = trim(defaults($item, 'object-type', ''));
  1190. $item['object'] = trim(defaults($item, 'object', ''));
  1191. $item['target-type'] = trim(defaults($item, 'target-type', ''));
  1192. $item['target'] = trim(defaults($item, 'target', ''));
  1193. $item['plink'] = trim(defaults($item, 'plink', ''));
  1194. $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
  1195. $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
  1196. $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
  1197. $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
  1198. $item['private'] = intval(defaults($item, 'private', 0));
  1199. $item['body'] = trim(defaults($item, 'body', ''));
  1200. $item['tag'] = trim(defaults($item, 'tag', ''));
  1201. $item['attach'] = trim(defaults($item, 'attach', ''));
  1202. $item['app'] = trim(defaults($item, 'app', ''));
  1203. $item['origin'] = intval(defaults($item, 'origin', 0));
  1204. $item['postopts'] = trim(defaults($item, 'postopts', ''));
  1205. $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
  1206. $item['event-id'] = intval(defaults($item, 'event-id', 0));
  1207. $item['inform'] = trim(defaults($item, 'inform', ''));
  1208. $item['file'] = trim(defaults($item, 'file', ''));
  1209. // When there is no content then we don't post it
  1210. if ($item['body'].$item['title'] == '') {
  1211. Logger::notice('No body, no title.');
  1212. return 0;
  1213. }
  1214. self::addLanguageToItemArray($item);
  1215. // Items cannot be stored before they happen ...
  1216. if ($item['created'] > DateTimeFormat::utcNow()) {
  1217. $item['created'] = DateTimeFormat::utcNow();
  1218. }
  1219. // We haven't invented time travel by now.
  1220. if ($item['edited'] > DateTimeFormat::utcNow()) {
  1221. $item['edited'] = DateTimeFormat::utcNow();
  1222. }
  1223. $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
  1224. // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
  1225. $item["contact-id"] = self::contactId($item);
  1226. $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
  1227. 'photo' => $item['author-avatar'], 'network' => $item['network']];
  1228. $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item['author-link'], 0, false, $default));
  1229. if (Contact::isBlocked($item['author-id'])) {
  1230. Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
  1231. return 0;
  1232. }
  1233. if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
  1234. Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
  1235. return 0;
  1236. }
  1237. if (!empty($uid) && Contact::isBlockedByUser($item['author-id'], $uid)) {
  1238. Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
  1239. return 0;
  1240. }
  1241. $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
  1242. 'photo' => $item['owner-avatar'], 'network' => $item['network']];
  1243. $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item['owner-link'], 0, false, $default));
  1244. if (Contact::isBlocked($item['owner-id'])) {
  1245. Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
  1246. return 0;
  1247. }
  1248. if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
  1249. Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
  1250. return 0;
  1251. }
  1252. if (!empty($uid) && Contact::isBlockedByUser($item['owner-id'], $uid)) {
  1253. Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
  1254. return 0;
  1255. }
  1256. // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
  1257. if (!empty($uid) && !empty($item['causer-id']) && Contact::isBlockedByUser($item['causer-id'], $uid)) {
  1258. Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
  1259. return 0;
  1260. }
  1261. if (!empty($uid) && !empty($item['causer-id']) && ($item['parent-uri'] == $item['uri']) && Contact::isIgnoredByUser($item['causer-id'], $uid)) {
  1262. Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
  1263. return 0;
  1264. }
  1265. // We don't store the causer, we only have it here for the checks above
  1266. unset($item['causer-id']);
  1267. unset($item['causer-link']);
  1268. if ($item['network'] == Protocol::PHANTOM) {
  1269. $item['network'] = Protocol::DFRN;
  1270. Logger::notice('Missing network, setting to {network}.', [
  1271. 'uri' => $item["uri"],
  1272. 'network' => $item['network'],
  1273. 'callstack' => System::callstack()
  1274. ]);
  1275. }
  1276. // Checking if there is already an item with the same guid
  1277. $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
  1278. if (self::exists($condition)) {
  1279. Logger::notice('Found already existing item', [
  1280. 'guid' => $item['guid'],
  1281. 'uid' => $item['uid'],
  1282. 'network' => $item['network']
  1283. ]);
  1284. return 0;
  1285. }
  1286. if ($item['verb'] == ACTIVITY_FOLLOW) {
  1287. if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($uid))) {
  1288. // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
  1289. Logger::log("Follow: Don't store not origin follow request from us for " . $item['parent-uri'], Logger::DEBUG);
  1290. return 0;
  1291. }
  1292. $condition = ['verb' => ACTIVITY_FOLLOW, 'uid' => $item['uid'],
  1293. 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
  1294. if (self::exists($condition)) {
  1295. // It happens that we receive multiple follow requests by the same author - we only store one.
  1296. Logger::log('Follow: Found existing follow request from author ' . $item['author-id'] . ' for ' . $item['parent-uri'], Logger::DEBUG);
  1297. return 0;
  1298. }
  1299. }
  1300. // Check for hashtags in the body and repair or add hashtag links
  1301. self::setHashtags($item);
  1302. $item['thr-parent'] = $item['parent-uri'];
  1303. $notify_type = Delivery::POST;
  1304. $allow_cid = '';
  1305. $allow_gid = '';
  1306. $deny_cid = '';
  1307. $deny_gid = '';
  1308. if ($item['parent-uri'] === $item['uri']) {
  1309. $parent_id = 0;
  1310. $parent_deleted = 0;
  1311. $allow_cid = $item['allow_cid'];
  1312. $allow_gid = $item['allow_gid'];
  1313. $deny_cid = $item['deny_cid'];
  1314. $deny_gid = $item['deny_gid'];
  1315. } else {
  1316. // find the parent and snarf the item id and ACLs
  1317. // and anything else we need to inherit
  1318. $fields = ['uri', 'parent-uri', 'id', 'deleted',
  1319. 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
  1320. 'wall', 'private', 'forum_mode', 'origin'];
  1321. $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
  1322. $params = ['order' => ['id' => false]];
  1323. $parent = self::selectFirst($fields, $condition, $params);
  1324. if (DBA::isResult($parent)) {
  1325. // is the new message multi-level threaded?
  1326. // even though we don't support it now, preserve the info
  1327. // and re-attach to the conversation parent.
  1328. if ($parent['uri'] != $parent['parent-uri']) {
  1329. $item['parent-uri'] = $parent['parent-uri'];
  1330. $condition = ['uri' => $item['parent-uri'],
  1331. 'parent-uri' => $item['parent-uri'],
  1332. 'uid' => $item['uid']];
  1333. $params = ['order' => ['id' => false]];
  1334. $toplevel_parent = self::selectFirst($fields, $condition, $params);
  1335. if (DBA::isResult($toplevel_parent)) {
  1336. $parent = $toplevel_parent;
  1337. }
  1338. }
  1339. $parent_id = $parent['id'];
  1340. $parent_deleted = $parent['deleted'];
  1341. $allow_cid = $parent['allow_cid'];
  1342. $allow_gid = $parent['allow_gid'];
  1343. $deny_cid = $parent['deny_cid'];
  1344. $deny_gid = $parent['deny_gid'];
  1345. $item['wall'] = $parent['wall'];
  1346. /*
  1347. * If the parent is private, force privacy for the entire conversation
  1348. * This differs from the above settings as it subtly allows comments from
  1349. * email correspondents to be private even if the overall thread is not.
  1350. */
  1351. if ($parent['private']) {
  1352. $item['private'] = $parent['private'];
  1353. }
  1354. /*
  1355. * Edge case. We host a public forum that was originally posted to privately.
  1356. * The original author commented, but as this is a comment, the permissions
  1357. * weren't fixed up so it will still show the comment as private unless we fix it here.
  1358. */
  1359. if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
  1360. $item['private'] = 0;
  1361. }
  1362. // If its a post that originated here then tag the thread as "mention"
  1363. if ($item['origin'] && $item['uid']) {
  1364. DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
  1365. Logger::log('tagged thread ' . $parent_id . ' as mention for user ' . $item['uid'], Logger::DEBUG);
  1366. }
  1367. } else {
  1368. /*
  1369. * Allow one to see reply tweets from status.net even when
  1370. * we don't have or can't see the original post.
  1371. */
  1372. if ($force_parent) {
  1373. Logger::log('$force_parent=true, reply converted to top-level post.');
  1374. $parent_id = 0;
  1375. $item['parent-uri'] = $item['uri'];
  1376. $item['gravity'] = GRAVITY_PARENT;
  1377. } else {
  1378. Logger::log('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
  1379. return 0;
  1380. }
  1381. $parent_deleted = 0;
  1382. }
  1383. }
  1384. if (stristr($item['verb'], ACTIVITY_POKE)) {
  1385. $notify_type = Delivery::POKE;
  1386. }
  1387. $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
  1388. $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
  1389. $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
  1390. $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
  1391. if (self::exists($condition)) {
  1392. Logger::log('duplicated item with the same uri found. '.print_r($item,true));
  1393. return 0;
  1394. }
  1395. // On Friendica and Diaspora the GUID is unique
  1396. if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
  1397. $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
  1398. if (self::exists($condition)) {
  1399. Logger::log('duplicated item with the same guid found. '.print_r($item,true));
  1400. return 0;
  1401. }
  1402. } elseif ($item['network'] == Protocol::OSTATUS) {
  1403. // Check for an existing post with the same content. There seems to be a problem with OStatus.
  1404. $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
  1405. $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
  1406. if (self::exists($condition)) {
  1407. Logger::log('duplicated item with the same body found. '.print_r($item,true));
  1408. return 0;
  1409. }
  1410. }
  1411. // Is this item available in the global items (with uid=0)?
  1412. if ($item["uid"] == 0) {
  1413. $item["global"] = true;
  1414. // Set the global flag on all items if this was a global item entry
  1415. DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
  1416. } else {
  1417. $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
  1418. }
  1419. // ACL settings
  1420. if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
  1421. $private = 1;
  1422. } else {
  1423. $private = $item['private'];
  1424. }
  1425. $item["allow_cid"] = $allow_cid;
  1426. $item["allow_gid"] = $allow_gid;
  1427. $item["deny_cid"] = $deny_cid;
  1428. $item["deny_gid"] = $deny_gid;
  1429. $item["private"] = $private;
  1430. $item["deleted"] = $parent_deleted;
  1431. // Fill the cache field
  1432. self::putInCache($item);
  1433. if ($notify) {
  1434. $item['edit'] = false;
  1435. $item['parent'] = $parent_id;
  1436. Hook::callAll('post_local', $item);
  1437. unset($item['edit']);
  1438. unset($item['parent']);
  1439. } else {
  1440. Hook::callAll('post_remote', $item);
  1441. }
  1442. // This array field is used to trigger some automatic reactions
  1443. // It is mainly used in the "post_local" hook.
  1444. unset($item['api_source']);
  1445. if (!empty($item['cancel'])) {
  1446. Logger::log('post cancelled by addon.');
  1447. return 0;
  1448. }
  1449. /*
  1450. * Check for already added items.
  1451. * There is a timing issue here that sometimes creates double postings.
  1452. * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
  1453. */
  1454. if ($item["uid"] == 0) {
  1455. if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
  1456. Logger::log('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], Logger::DEBUG);
  1457. return 0;
  1458. }
  1459. }
  1460. Logger::log('' . print_r($item,true), Logger::DATA);
  1461. if (array_key_exists('tag', $item)) {
  1462. $tags = $item['tag'];
  1463. unset($item['tag']);
  1464. } else {
  1465. $tags = '';
  1466. }
  1467. if (array_key_exists('file', $item)) {
  1468. $files = $item['file'];
  1469. unset($item['file']);
  1470. } else {
  1471. $files = '';
  1472. }
  1473. // Creates or assigns the permission set
  1474. $item['psid'] = PermissionSet::fetchIDForPost($item);
  1475. // We are doing this outside of the transaction to avoid timing problems
  1476. if (!self::insertActivity($item)) {
  1477. self::insertContent($item);
  1478. }
  1479. $delivery_data = ItemDeliveryData::extractFields($item);
  1480. unset($item['postopts']);
  1481. unset($item['inform']);
  1482. // These fields aren't stored anymore in the item table, they are fetched upon request
  1483. unset($item['author-link']);
  1484. unset($item['author-name']);
  1485. unset($item['author-avatar']);
  1486. unset($item['author-network']);
  1487. unset($item['owner-link']);
  1488. unset($item['owner-name']);
  1489. unset($item['owner-avatar']);
  1490. DBA::transaction();
  1491. $ret = DBA::insert('item', $item);
  1492. // When the item was successfully stored we fetch the ID of the item.
  1493. if (DBA::isResult($ret)) {
  1494. $current_post = DBA::lastInsertId();
  1495. } else {
  1496. // This can happen - for example - if there are locking timeouts.
  1497. DBA::rollback();
  1498. // Store the data into a spool file so that we can try again later.
  1499. // At first we restore the Diaspora signature that we removed above.
  1500. if (isset($encoded_signature)) {
  1501. $item['dsprsig'] = $encoded_signature;
  1502. }
  1503. // Now we store the data in the spool directory
  1504. // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
  1505. $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
  1506. $spoolpath = get_spoolpath();
  1507. if ($spoolpath != "") {
  1508. $spool = $spoolpath.'/'.$file;
  1509. file_put_contents($spool, json_encode($orig_item));
  1510. Logger::log("Item wasn't stored - Item was spooled into file ".$file, Logger::DEBUG);
  1511. }
  1512. return 0;
  1513. }
  1514. if ($current_post == 0) {
  1515. // This is one of these error messages that never should occur.
  1516. Logger::log("couldn't find created item - we better quit now.");
  1517. DBA::rollback();
  1518. return 0;
  1519. }
  1520. // How much entries have we created?
  1521. // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
  1522. $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
  1523. if ($entries > 1) {
  1524. // There are duplicates. We delete our just created entry.
  1525. Logger::log('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
  1526. // Yes, we could do a rollback here - but we are having many users with MyISAM.
  1527. DBA::delete('item', ['id' => $current_post]);
  1528. DBA::commit();
  1529. return 0;
  1530. } elseif ($entries == 0) {
  1531. // This really should never happen since we quit earlier if there were problems.
  1532. Logger::log("Something is terribly wrong. We haven't found our created entry.");
  1533. DBA::rollback();
  1534. return 0;
  1535. }
  1536. Logger::log('created item '.$current_post);
  1537. self::updateContact($item);
  1538. if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
  1539. $parent_id = $current_post;
  1540. }
  1541. // Set parent id
  1542. DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
  1543. $item['id'] = $current_post;
  1544. $item['parent'] = $parent_id;
  1545. // update the commented timestamp on the parent
  1546. // Only update "commented" if it is really a comment
  1547. if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
  1548. DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
  1549. } else {
  1550. DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
  1551. }
  1552. if ($dsprsig) {
  1553. /*
  1554. * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
  1555. * We can check for this condition when we decode and encode the stuff again.
  1556. */
  1557. if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
  1558. $dsprsig->signature = base64_decode($dsprsig->signature);
  1559. Logger::log("Repaired double encoded signature from handle ".$dsprsig->signer, Logger::DEBUG);
  1560. }
  1561. if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) {
  1562. DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $dsprsig->signed_text], true);
  1563. } else {
  1564. // The other fields are used by very old Friendica servers, so we currently store them differently
  1565. DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
  1566. 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
  1567. }
  1568. }
  1569. if (!empty($diaspora_signed_text)) {
  1570. DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $diaspora_signed_text], true);
  1571. }
  1572. self::tagDeliver($item['uid'], $current_post);
  1573. /*
  1574. * current post can be deleted if is for a community page and no mention are
  1575. * in it.
  1576. */
  1577. if (!$dontcache) {
  1578. $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
  1579. if (DBA::isResult($posted_item)) {
  1580. if ($notify) {
  1581. Hook::callAll('post_local_end', $posted_item);
  1582. } else {
  1583. Hook::callAll('post_remote_end', $posted_item);
  1584. }
  1585. } else {
  1586. Logger::log('new item not found in DB, id ' . $current_post);
  1587. }
  1588. }
  1589. if ($item['parent-uri'] === $item['uri']) {
  1590. self::addThread($current_post);
  1591. } else {
  1592. self::updateThread($parent_id);
  1593. }
  1594. if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
  1595. ItemDeliveryData::insert($current_post, $delivery_data);
  1596. }
  1597. DBA::commit();
  1598. /*
  1599. * Due to deadlock issues with the "term" table we are doing these steps after the commit.
  1600. * This is not perfect - but a workable solution until we found the reason for the problem.
  1601. */
  1602. if (!empty($tags)) {
  1603. Term::insertFromTagFieldByItemId($current_post, $tags);
  1604. }
  1605. if (!empty($files)) {
  1606. Term::insertFromFileFieldByItemId($current_post, $files);
  1607. }
  1608. if ($item['parent-uri'] === $item['uri']) {
  1609. self::addShadow($current_post);
  1610. } else {
  1611. self::addShadowPost($current_post);
  1612. }
  1613. check_user_notification($current_post);
  1614. if ($notify || ($item['visible'] && ((!empty($parent) && $parent['origin']) || $item['origin']))) {
  1615. Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
  1616. }
  1617. return $current_post;
  1618. }
  1619. /**
  1620. * @brief Insert a new item content entry
  1621. *
  1622. * @param array $item The item fields that are to be inserted
  1623. * @return bool
  1624. * @throws \Exception
  1625. */
  1626. private static function insertActivity(&$item)
  1627. {
  1628. $activity_index = self::activityToIndex($item['verb']);
  1629. if ($activity_index < 0) {
  1630. return false;
  1631. }
  1632. $fields = ['activity' => $activity_index, 'uri-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
  1633. // We just remove everything that is content
  1634. foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
  1635. unset($item[$field]);
  1636. }
  1637. // To avoid timing problems, we are using locks.
  1638. $locked = Lock::acquire('item_insert_activity');
  1639. if (!$locked) {
  1640. Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
  1641. }
  1642. // Do we already have this content?
  1643. $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
  1644. if (DBA::isResult($item_activity)) {
  1645. $item['iaid'] = $item_activity['id'];
  1646. Logger::log('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
  1647. } elseif (DBA::insert('item-activity', $fields)) {
  1648. $item['iaid'] = DBA::lastInsertId();
  1649. Logger::log('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
  1650. } else {
  1651. // This shouldn't happen.
  1652. Logger::log('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
  1653. Lock::release('item_insert_activity');
  1654. return false;
  1655. }
  1656. if ($locked) {
  1657. Lock::release('item_insert_activity');
  1658. }
  1659. return true;
  1660. }
  1661. /**
  1662. * @brief Insert a new item content entry
  1663. *
  1664. * @param array $item The item fields that are to be inserted
  1665. * @throws \Exception
  1666. */
  1667. private static function insertContent(&$item)
  1668. {
  1669. $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
  1670. foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
  1671. if (isset($item[$field])) {
  1672. $fields[$field] = $item[$field];
  1673. unset($item[$field]);
  1674. }
  1675. }
  1676. // To avoid timing problems, we are using locks.
  1677. $locked = Lock::acquire('item_insert_content');
  1678. if (!$locked) {
  1679. Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
  1680. }
  1681. // Do we already have this content?
  1682. $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
  1683. if (DBA::isResult($item_content)) {
  1684. $item['icid'] = $item_content['id'];
  1685. Logger::log('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
  1686. } elseif (DBA::insert('item-content', $fields)) {
  1687. $item['icid'] = DBA::lastInsertId();
  1688. Logger::log('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
  1689. } else {
  1690. // This shouldn't happen.
  1691. Logger::log('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
  1692. }
  1693. if ($locked) {
  1694. Lock::release('item_insert_content');
  1695. }
  1696. }
  1697. /**
  1698. * @brief Update existing item content entries
  1699. *
  1700. * @param array $item The item fields that are to be changed
  1701. * @param array $condition The condition for finding the item content entries
  1702. * @return bool
  1703. * @throws \Exception
  1704. */
  1705. private static function updateActivity($item, $condition)
  1706. {
  1707. if (empty($item['verb'])) {
  1708. return false;
  1709. }
  1710. $activity_index = self::activityToIndex($item['verb']);
  1711. if ($activity_index < 0) {
  1712. return false;
  1713. }
  1714. $fields = ['activity' => $activity_index];
  1715. Logger::log('Update activity for ' . json_encode($condition));
  1716. DBA::update('item-activity', $fields, $condition, true);
  1717. return true;
  1718. }
  1719. /**
  1720. * @brief Update existing item content entries
  1721. *
  1722. * @param array $item The item fields that are to be changed
  1723. * @param array $condition The condition for finding the item content entries
  1724. * @throws \Exception
  1725. */
  1726. private static function updateContent($item, $condition)
  1727. {
  1728. // We have to select only the fields from the "item-content" table
  1729. $fields = [];
  1730. foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
  1731. if (isset($item[$field])) {
  1732. $fields[$field] = $item[$field];
  1733. }
  1734. }
  1735. if (empty($fields)) {
  1736. // when there are no fields at all, just use the condition
  1737. // This is to ensure that we always store content.
  1738. $fields = $condition;
  1739. }
  1740. Logger::log('Update content for ' . json_encode($condition));
  1741. DBA::update('item-content', $fields, $condition, true);
  1742. }
  1743. /**
  1744. * @brief Distributes public items to the receivers
  1745. *
  1746. * @param integer $itemid Item ID that should be added
  1747. * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
  1748. * @throws \Exception
  1749. */
  1750. public static function distribute($itemid, $signed_text = '')
  1751. {
  1752. $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
  1753. $parent = self::selectFirst(['owner-id'], $condition);
  1754. if (!DBA::isResult($parent)) {
  1755. return;
  1756. }
  1757. // Only distribute public items from native networks
  1758. $condition = ['id' => $itemid, 'uid' => 0,
  1759. 'network' => array_merge(Protocol::FEDERATED ,['']),
  1760. 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
  1761. $item = self::selectFirst(self::ITEM_FIELDLIST, $condition);
  1762. if (!DBA::isResult($item)) {
  1763. return;
  1764. }
  1765. $origin = $item['origin'];
  1766. unset($item['id']);
  1767. unset($item['parent']);
  1768. unset($item['mention']);
  1769. unset($item['wall']);
  1770. unset($item['origin']);
  1771. unset($item['starred']);
  1772. $users = [];
  1773. /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
  1774. $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
  1775. if (!DBA::isResult($owner)) {
  1776. return;
  1777. }
  1778. $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
  1779. $contacts = DBA::select('contact', ['uid'], $condition);
  1780. while ($contact = DBA::fetch($contacts)) {
  1781. if ($contact['uid'] == 0) {
  1782. continue;
  1783. }
  1784. $users[$contact['uid']] = $contact['uid'];
  1785. }
  1786. DBA::close($contacts);
  1787. $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
  1788. $contacts = DBA::select('contact', ['uid'], $condition);
  1789. while ($contact = DBA::fetch($contacts)) {
  1790. if ($contact['uid'] == 0) {
  1791. continue;
  1792. }
  1793. $users[$contact['uid']] = $contact['uid'];
  1794. }
  1795. DBA::close($contacts);
  1796. if (!empty($owner['alias'])) {
  1797. $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
  1798. $contacts = DBA::select('contact', ['uid'], $condition);
  1799. while ($contact = DBA::fetch($contacts)) {
  1800. if ($contact['uid'] == 0) {
  1801. continue;
  1802. }
  1803. $users[$contact['uid']] = $contact['uid'];
  1804. }
  1805. DBA::close($contacts);
  1806. }
  1807. $origin_uid = 0;
  1808. if ($item['uri'] != $item['parent-uri']) {
  1809. $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
  1810. while ($parent = self::fetch($parents)) {
  1811. $users[$parent['uid']] = $parent['uid'];
  1812. if ($parent['origin'] && !$origin) {
  1813. $origin_uid = $parent['uid'];
  1814. }
  1815. }
  1816. }
  1817. foreach ($users as $uid) {
  1818. if ($origin_uid == $uid) {
  1819. $item['diaspora_signed_text'] = $signed_text;
  1820. }
  1821. self::storeForUser($itemid, $item, $uid);
  1822. }
  1823. }
  1824. /**
  1825. * @brief Store public items for the receivers
  1826. *
  1827. * @param integer $itemid Item ID that should be added
  1828. * @param array $item The item entry that will be stored
  1829. * @param integer $uid The user that will receive the item entry
  1830. * @throws \Exception
  1831. */
  1832. private static function storeForUser($itemid, $item, $uid)
  1833. {
  1834. $item['uid'] = $uid;
  1835. $item['origin'] = 0;
  1836. $item['wall'] = 0;
  1837. if ($item['uri'] == $item['parent-uri']) {
  1838. $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
  1839. } else {
  1840. $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
  1841. }
  1842. if (empty($item['contact-id'])) {
  1843. $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
  1844. if (!DBA::isResult($self)) {
  1845. return;
  1846. }
  1847. $item['contact-id'] = $self['id'];
  1848. }
  1849. /// @todo Handling of "event-id"
  1850. $notify = false;
  1851. if ($item['uri'] == $item['parent-uri']) {
  1852. $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
  1853. if (DBA::isResult($contact)) {
  1854. $notify = self::isRemoteSelf($contact, $item);
  1855. }
  1856. }
  1857. $distributed = self::insert($item, false, $notify, true);
  1858. if (!$distributed) {
  1859. Logger::log("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", Logger::DEBUG);
  1860. } else {
  1861. Logger::log("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, Logger::DEBUG);
  1862. }
  1863. }
  1864. /**
  1865. * @brief Add a shadow entry for a given item id that is a thread starter
  1866. *
  1867. * We store every public item entry additionally with the user id "0".
  1868. * This is used for the community page and for the search.
  1869. * It is planned that in the future we will store public item entries only once.
  1870. *
  1871. * @param integer $itemid Item ID that should be added
  1872. * @throws \Exception
  1873. */
  1874. public static function addShadow($itemid)
  1875. {
  1876. $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
  1877. $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
  1878. $item = self::selectFirst($fields, $condition);
  1879. if (!DBA::isResult($item)) {
  1880. return;
  1881. }
  1882. // is it already a copy?
  1883. if (($itemid == 0) || ($item['uid'] == 0)) {
  1884. return;
  1885. }
  1886. // Is it a visible public post?
  1887. if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
  1888. return;
  1889. }
  1890. // is it an entry from a connector? Only add an entry for natively connected networks
  1891. if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
  1892. return;
  1893. }
  1894. if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
  1895. return;
  1896. }
  1897. $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
  1898. if (DBA::isResult($item)) {
  1899. // Preparing public shadow (removing user specific data)
  1900. $item['uid'] = 0;
  1901. unset($item['id']);
  1902. unset($item['parent']);
  1903. unset($item['wall']);
  1904. unset($item['mention']);
  1905. unset($item['origin']);
  1906. unset($item['starred']);
  1907. unset($item['postopts']);
  1908. unset($item['inform']);
  1909. if ($item['uri'] == $item['parent-uri']) {
  1910. $item['contact-id'] = $item['owner-id'];
  1911. } else {
  1912. $item['contact-id'] = $item['author-id'];
  1913. }
  1914. $public_shadow = self::insert($item, false, false, true);
  1915. Logger::log("Stored public shadow for thread ".$itemid." under id ".$public_shadow, Logger::DEBUG);
  1916. }
  1917. }
  1918. /**
  1919. * @brief Add a shadow entry for a given item id that is a comment
  1920. *
  1921. * This function does the same like the function above - but for comments
  1922. *
  1923. * @param integer $itemid Item ID that should be added
  1924. * @throws \Exception
  1925. */
  1926. public static function addShadowPost($itemid)
  1927. {
  1928. $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
  1929. if (!DBA::isResult($item)) {
  1930. return;
  1931. }
  1932. // Is it a toplevel post?
  1933. if ($item['id'] == $item['parent']) {
  1934. self::addShadow($itemid);
  1935. return;
  1936. }
  1937. // Is this a shadow entry?
  1938. if ($item['uid'] == 0) {
  1939. return;
  1940. }
  1941. // Is there a shadow parent?
  1942. if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
  1943. return;
  1944. }
  1945. // Is there already a shadow entry?
  1946. if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
  1947. return;
  1948. }
  1949. // Save "origin" and "parent" state
  1950. $origin = $item['origin'];
  1951. $parent = $item['parent'];
  1952. // Preparing public shadow (removing user specific data)
  1953. $item['uid'] = 0;
  1954. unset($item['id']);
  1955. unset($item['parent']);
  1956. unset($item['wall']);
  1957. unset($item['mention']);
  1958. unset($item['origin']);
  1959. unset($item['starred']);
  1960. unset($item['postopts']);
  1961. unset($item['inform']);
  1962. $item['contact-id'] = Contact::getIdForURL($item['author-link']);
  1963. $public_shadow = self::insert($item, false, false, true);
  1964. Logger::log("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, Logger::DEBUG);
  1965. // If this was a comment to a Diaspora post we don't get our comment back.
  1966. // This means that we have to distribute the comment by ourselves.
  1967. if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
  1968. self::distribute($public_shadow);
  1969. }
  1970. }
  1971. /**
  1972. * Adds a language specification in a "language" element of given $arr.
  1973. * Expects "body" element to exist in $arr.
  1974. *
  1975. * @param $item
  1976. * @throws \Text_LanguageDetect_Exception
  1977. */
  1978. private static function addLanguageToItemArray(&$item)
  1979. {
  1980. $naked_body = BBCode::toPlaintext($item['body'], false);
  1981. $ld = new Text_LanguageDetect();
  1982. $ld->setNameMode(2);
  1983. $languages = $ld->detect($naked_body, 3);
  1984. if (is_array($languages)) {
  1985. $item['language'] = json_encode($languages);
  1986. }
  1987. }
  1988. /**
  1989. * @brief Creates an unique guid out of a given uri
  1990. *
  1991. * @param string $uri uri of an item entry
  1992. * @param string $host hostname for the GUID prefix
  1993. * @return string unique guid
  1994. */
  1995. public static function guidFromUri($uri, $host)
  1996. {
  1997. // Our regular guid routine is using this kind of prefix as well
  1998. // We have to avoid that different routines could accidentally create the same value
  1999. $parsed = parse_url($uri);
  2000. // We use a hash of the hostname as prefix for the guid
  2001. $guid_prefix = hash("crc32", $host);
  2002. // Remove the scheme to make sure that "https" and "http" doesn't make a difference
  2003. unset($parsed["scheme"]);
  2004. // Glue it together to be able to make a hash from it
  2005. $host_id = implode("/", $parsed);
  2006. // We could use any hash algorithm since it isn't a security issue
  2007. $host_hash = hash("ripemd128", $host_id);
  2008. return $guid_prefix.$host_hash;
  2009. }
  2010. /**
  2011. * generate an unique URI
  2012. *
  2013. * @param integer $uid User id
  2014. * @param string $guid An existing GUID (Otherwise it will be generated)
  2015. *
  2016. * @return string
  2017. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  2018. */
  2019. public static function newURI($uid, $guid = "")
  2020. {
  2021. if ($guid == "") {
  2022. $guid = System::createUUID();
  2023. }
  2024. return self::getApp()->getBaseURL() . '/objects/' . $guid;
  2025. }
  2026. /**
  2027. * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
  2028. *
  2029. * This can be used to filter for inactive contacts.
  2030. * Only do this for public postings to avoid privacy problems, since poco data is public.
  2031. * Don't set this value if it isn't from the owner (could be an author that we don't know)
  2032. *
  2033. * @param array $arr Contains the just posted item record
  2034. * @throws \Exception
  2035. */
  2036. private static function updateContact($arr)
  2037. {
  2038. // Unarchive the author
  2039. $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
  2040. if (DBA::isResult($contact)) {
  2041. Contact::unmarkForArchival($contact);
  2042. }
  2043. // Unarchive the contact if it's not our own contact
  2044. $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
  2045. if (DBA::isResult($contact)) {
  2046. Contact::unmarkForArchival($contact);
  2047. }
  2048. $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
  2049. // Is it a forum? Then we don't care about the rules from above
  2050. if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) {
  2051. if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
  2052. $update = true;
  2053. }
  2054. }
  2055. if ($update) {
  2056. DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
  2057. ['id' => $arr['contact-id']]);
  2058. }
  2059. // Now do the same for the system wide contacts with uid=0
  2060. if (!$arr['private']) {
  2061. DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
  2062. ['id' => $arr['owner-id']]);
  2063. if ($arr['owner-id'] != $arr['author-id']) {
  2064. DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
  2065. ['id' => $arr['author-id']]);
  2066. }
  2067. }
  2068. }
  2069. public static function setHashtags(&$item)
  2070. {
  2071. $tags = BBCode::getTags($item["body"]);
  2072. // No hashtags?
  2073. if (!count($tags)) {
  2074. return false;
  2075. }
  2076. // What happens in [code], stays in [code]!
  2077. // escape the # and the [
  2078. // hint: we will also get in trouble with #tags, when we want markdown in posts -> ### Headline 3
  2079. $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
  2080. function ($match) {
  2081. // we truly ESCape all # and [ to prevent gettin weird tags in [code] blocks
  2082. $find = ['#', '['];
  2083. $replace = [chr(27).'sharp', chr(27).'leftsquarebracket'];
  2084. return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
  2085. }, $item["body"]);
  2086. // This sorting is important when there are hashtags that are part of other hashtags
  2087. // Otherwise there could be problems with hashtags like #test and #test2
  2088. rsort($tags);
  2089. $URLSearchString = "^\[\]";
  2090. // All hashtags should point to the home server if "local_tags" is activated
  2091. if (Config::get('system', 'local_tags')) {
  2092. $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  2093. "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
  2094. $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  2095. "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
  2096. }
  2097. // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
  2098. $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  2099. function ($match) {
  2100. return ("[url=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/url]");
  2101. }, $item["body"]);
  2102. $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
  2103. function ($match) {
  2104. return ("[bookmark=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/bookmark]");
  2105. }, $item["body"]);
  2106. $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
  2107. function ($match) {
  2108. return ("[attachment " . str_replace("#", "&num;", $match[1]) . "]" . $match[2] . "[/attachment]");
  2109. }, $item["body"]);
  2110. // Repair recursive urls
  2111. $item["body"] = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  2112. "&num;$2", $item["body"]);
  2113. foreach ($tags as $tag) {
  2114. if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || $tag[1] == '#') {
  2115. continue;
  2116. }
  2117. $basetag = str_replace('_',' ',substr($tag,1));
  2118. $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
  2119. $item["body"] = str_replace($tag, $newtag, $item["body"]);
  2120. if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
  2121. if (strlen($item["tag"])) {
  2122. $item["tag"] = ',' . $item["tag"];
  2123. }
  2124. $item["tag"] = $newtag . $item["tag"];
  2125. }
  2126. }
  2127. // Convert back the masked hashtags
  2128. $item["body"] = str_replace("&num;", "#", $item["body"]);
  2129. // Remember! What happens in [code], stays in [code]
  2130. // roleback the # and [
  2131. $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
  2132. function ($match) {
  2133. // we truly unESCape all sharp and leftsquarebracket
  2134. $find = [chr(27).'sharp', chr(27).'leftsquarebracket'];
  2135. $replace = ['#', '['];
  2136. return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
  2137. }, $item["body"]);
  2138. }
  2139. /**
  2140. * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
  2141. *
  2142. * @param int $uid
  2143. * @param int $item_id
  2144. * @return void true if item was deleted, else false
  2145. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  2146. * @throws \ImagickException
  2147. */
  2148. private static function tagDeliver($uid, $item_id)
  2149. {
  2150. $mention = false;
  2151. $user = DBA::selectFirst('user', [], ['uid' => $uid]);
  2152. if (!DBA::isResult($user)) {
  2153. return;
  2154. }
  2155. $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
  2156. $prvgroup = (($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) ? true : false);
  2157. $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
  2158. if (!DBA::isResult($item)) {
  2159. return;
  2160. }
  2161. $link = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
  2162. /*
  2163. * Diaspora uses their own hardwired link URL in @-tags
  2164. * instead of the one we supply with webfinger
  2165. */
  2166. $dlink = Strings::normaliseLink(System::baseUrl() . '/u/' . $user['nickname']);
  2167. $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
  2168. if ($cnt) {
  2169. foreach ($matches as $mtch) {
  2170. if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
  2171. $mention = true;
  2172. Logger::log('mention found: ' . $mtch[2]);
  2173. }
  2174. }
  2175. }
  2176. if (!$mention) {
  2177. if (($community_page || $prvgroup) &&
  2178. !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
  2179. // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
  2180. // delete it!
  2181. Logger::log("no-mention top-level post to community or private group. delete.");
  2182. DBA::delete('item', ['id' => $item_id]);
  2183. return true;
  2184. }
  2185. return;
  2186. }
  2187. $arr = ['item' => $item, 'user' => $user];
  2188. Hook::callAll('tagged', $arr);
  2189. if (!$community_page && !$prvgroup) {
  2190. return;
  2191. }
  2192. /*
  2193. * tgroup delivery - setup a second delivery chain
  2194. * prevent delivery looping - only proceed
  2195. * if the message originated elsewhere and is a top-level post
  2196. */
  2197. if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
  2198. return;
  2199. }
  2200. // now change this copy of the post to a forum head message and deliver to all the tgroup members
  2201. $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
  2202. if (!DBA::isResult($self)) {
  2203. return;
  2204. }
  2205. $owner_id = Contact::getIdForURL($self['url']);
  2206. // also reset all the privacy bits to the forum default permissions
  2207. $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
  2208. $psid = PermissionSet::fetchIDForPost($user);
  2209. $forum_mode = ($prvgroup ? 2 : 1);
  2210. $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
  2211. 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
  2212. self::update($fields, ['id' => $item_id]);
  2213. self::updateThread($item_id);
  2214. Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', Delivery::POST, $item_id);
  2215. }
  2216. public static function isRemoteSelf($contact, &$datarray)
  2217. {
  2218. $a = \get_app();
  2219. if (!$contact['remote_self']) {
  2220. return false;
  2221. }
  2222. // Prevent the forwarding of posts that are forwarded
  2223. if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
  2224. Logger::log('Already forwarded', Logger::DEBUG);
  2225. return false;
  2226. }
  2227. // Prevent to forward already forwarded posts
  2228. if ($datarray["app"] == $a->getHostName()) {
  2229. Logger::log('Already forwarded (second test)', Logger::DEBUG);
  2230. return false;
  2231. }
  2232. // Only forward posts
  2233. if ($datarray["verb"] != ACTIVITY_POST) {
  2234. Logger::log('No post', Logger::DEBUG);
  2235. return false;
  2236. }
  2237. if (($contact['network'] != Protocol::FEED) && $datarray['private']) {
  2238. Logger::log('Not public', Logger::DEBUG);
  2239. return false;
  2240. }
  2241. $datarray2 = $datarray;
  2242. Logger::log('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), Logger::DEBUG);
  2243. if ($contact['remote_self'] == 2) {
  2244. $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
  2245. ['uid' => $contact['uid'], 'self' => true]);
  2246. if (DBA::isResult($self)) {
  2247. $datarray['contact-id'] = $self["id"];
  2248. $datarray['owner-name'] = $self["name"];
  2249. $datarray['owner-link'] = $self["url"];
  2250. $datarray['owner-avatar'] = $self["thumb"];
  2251. $datarray['author-name'] = $datarray['owner-name'];
  2252. $datarray['author-link'] = $datarray['owner-link'];
  2253. $datarray['author-avatar'] = $datarray['owner-avatar'];
  2254. unset($datarray['edited']);
  2255. unset($datarray['network']);
  2256. unset($datarray['owner-id']);
  2257. unset($datarray['author-id']);
  2258. }
  2259. if ($contact['network'] != Protocol::FEED) {
  2260. $datarray["guid"] = System::createUUID();
  2261. unset($datarray["plink"]);
  2262. $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
  2263. $datarray["parent-uri"] = $datarray["uri"];
  2264. $datarray["thr-parent"] = $datarray["uri"];
  2265. $datarray["extid"] = Protocol::DFRN;
  2266. $urlpart = parse_url($datarray2['author-link']);
  2267. $datarray["app"] = $urlpart["host"];
  2268. } else {
  2269. $datarray['private'] = 0;
  2270. }
  2271. }
  2272. if ($contact['network'] != Protocol::FEED) {
  2273. // Store the original post
  2274. $result = self::insert($datarray2, false, false);
  2275. Logger::log('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), Logger::DEBUG);
  2276. } else {
  2277. $datarray["app"] = "Feed";
  2278. $result = true;
  2279. }
  2280. // Trigger automatic reactions for addons
  2281. $datarray['api_source'] = true;
  2282. // We have to tell the hooks who we are - this really should be improved
  2283. $_SESSION["authenticated"] = true;
  2284. $_SESSION["uid"] = $contact['uid'];
  2285. return $result;
  2286. }
  2287. /**
  2288. *
  2289. * @param string $s
  2290. * @param int $uid
  2291. * @param array $item
  2292. * @param int $cid
  2293. * @return string
  2294. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  2295. * @throws \ImagickException
  2296. */
  2297. public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
  2298. {
  2299. if (Config::get('system', 'disable_embedded')) {
  2300. return $s;
  2301. }
  2302. Logger::log('check for photos', Logger::DEBUG);
  2303. $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
  2304. $orig_body = $s;
  2305. $new_body = '';
  2306. $img_start = strpos($orig_body, '[img');
  2307. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  2308. $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
  2309. while (($img_st_close !== false) && ($img_len !== false)) {
  2310. $img_st_close++; // make it point to AFTER the closing bracket
  2311. $image = substr($orig_body, $img_start + $img_st_close, $img_len);
  2312. Logger::log('found photo ' . $image, Logger::DEBUG);
  2313. if (stristr($image, $site . '/photo/')) {
  2314. // Only embed locally hosted photos
  2315. $replace = false;
  2316. $i = basename($image);
  2317. $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
  2318. $x = strpos($i, '-');
  2319. if ($x) {
  2320. $res = substr($i, $x + 1);
  2321. $i = substr($i, 0, $x);
  2322. $photo = Photo::getPhotoForUser($uid, $i, $res);
  2323. if (DBA::isResult($photo)) {
  2324. /*
  2325. * Check to see if we should replace this photo link with an embedded image
  2326. * 1. No need to do so if the photo is public
  2327. * 2. If there's a contact-id provided, see if they're in the access list
  2328. * for the photo. If so, embed it.
  2329. * 3. Otherwise, if we have an item, see if the item permissions match the photo
  2330. * permissions, regardless of order but first check to see if they're an exact
  2331. * match to save some processing overhead.
  2332. */
  2333. if (self::hasPermissions($photo)) {
  2334. if ($cid) {
  2335. $recips = self::enumeratePermissions($photo);
  2336. if (in_array($cid, $recips)) {
  2337. $replace = true;
  2338. }
  2339. } elseif ($item) {
  2340. if (self::samePermissions($item, $photo)) {
  2341. $replace = true;
  2342. }
  2343. }
  2344. }
  2345. if ($replace) {
  2346. $photo_img = Photo::getImageForPhoto($photo);
  2347. // If a custom width and height were specified, apply before embedding
  2348. if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
  2349. Logger::log('scaling photo', Logger::DEBUG);
  2350. $width = intval($match[1]);
  2351. $height = intval($match[2]);
  2352. $photo_img->scaleDown(max($width, $height));
  2353. }
  2354. $data = $photo_img->asString();
  2355. $type = $photo_img->getType();
  2356. Logger::log('replacing photo', Logger::DEBUG);
  2357. $image = 'data:' . $type . ';base64,' . base64_encode($data);
  2358. Logger::log('replaced: ' . $image, Logger::DATA);
  2359. }
  2360. }
  2361. }
  2362. }
  2363. $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
  2364. $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
  2365. if ($orig_body === false) {
  2366. $orig_body = '';
  2367. }
  2368. $img_start = strpos($orig_body, '[img');
  2369. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  2370. $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
  2371. }
  2372. $new_body = $new_body . $orig_body;
  2373. return $new_body;
  2374. }
  2375. private static function hasPermissions($obj)
  2376. {
  2377. return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
  2378. !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
  2379. }
  2380. private static function samePermissions($obj1, $obj2)
  2381. {
  2382. // first part is easy. Check that these are exactly the same.
  2383. if (($obj1['allow_cid'] == $obj2['allow_cid'])
  2384. && ($obj1['allow_gid'] == $obj2['allow_gid'])
  2385. && ($obj1['deny_cid'] == $obj2['deny_cid'])
  2386. && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
  2387. return true;
  2388. }
  2389. // This is harder. Parse all the permissions and compare the resulting set.
  2390. $recipients1 = self::enumeratePermissions($obj1);
  2391. $recipients2 = self::enumeratePermissions($obj2);
  2392. sort($recipients1);
  2393. sort($recipients2);
  2394. /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
  2395. return ($recipients1 == $recipients2);
  2396. }
  2397. // returns an array of contact-ids that are allowed to see this object
  2398. public static function enumeratePermissions($obj)
  2399. {
  2400. $allow_people = expand_acl($obj['allow_cid']);
  2401. $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
  2402. $deny_people = expand_acl($obj['deny_cid']);
  2403. $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
  2404. $recipients = array_unique(array_merge($allow_people, $allow_groups));
  2405. $deny = array_unique(array_merge($deny_people, $deny_groups));
  2406. $recipients = array_diff($recipients, $deny);
  2407. return $recipients;
  2408. }
  2409. public static function getFeedTags($item)
  2410. {
  2411. $ret = [];
  2412. $matches = false;
  2413. $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
  2414. if ($cnt) {
  2415. for ($x = 0; $x < $cnt; $x ++) {
  2416. if ($matches[1][$x]) {
  2417. $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
  2418. }
  2419. }
  2420. }
  2421. $matches = false;
  2422. $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
  2423. if ($cnt) {
  2424. for ($x = 0; $x < $cnt; $x ++) {
  2425. if ($matches[1][$x]) {
  2426. $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
  2427. }
  2428. }
  2429. }
  2430. return $ret;
  2431. }
  2432. public static function expire($uid, $days, $network = "", $force = false)
  2433. {
  2434. if (!$uid || ($days < 1)) {
  2435. return;
  2436. }
  2437. $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
  2438. $uid, GRAVITY_PARENT];
  2439. /*
  2440. * $expire_network_only = save your own wall posts
  2441. * and just expire conversations started by others
  2442. */
  2443. $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
  2444. if ($expire_network_only) {
  2445. $condition[0] .= " AND NOT `wall`";
  2446. }
  2447. if ($network != "") {
  2448. $condition[0] .= " AND `network` = ?";
  2449. $condition[] = $network;
  2450. }
  2451. $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
  2452. $condition[] = $days;
  2453. $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
  2454. if (!DBA::isResult($items)) {
  2455. return;
  2456. }
  2457. $expire_items = PConfig::get($uid, 'expire', 'items', true);
  2458. // Forcing expiring of items - but not notes and marked items
  2459. if ($force) {
  2460. $expire_items = true;
  2461. }
  2462. $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
  2463. $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
  2464. $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
  2465. $expired = 0;
  2466. while ($item = Item::fetch($items)) {
  2467. // don't expire filed items
  2468. if (strpos($item['file'], '[') !== false) {
  2469. continue;
  2470. }
  2471. // Only expire posts, not photos and photo comments
  2472. if (!$expire_photos && strlen($item['resource-id'])) {
  2473. continue;
  2474. } elseif (!$expire_starred && intval($item['starred'])) {
  2475. continue;
  2476. } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
  2477. continue;
  2478. } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
  2479. continue;
  2480. }
  2481. self::deleteById($item['id'], PRIORITY_LOW);
  2482. ++$expired;
  2483. }
  2484. DBA::close($items);
  2485. Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
  2486. }
  2487. public static function firstPostDate($uid, $wall = false)
  2488. {
  2489. $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
  2490. $params = ['order' => ['received' => false]];
  2491. $thread = DBA::selectFirst('thread', ['received'], $condition, $params);
  2492. if (DBA::isResult($thread)) {
  2493. return substr(DateTimeFormat::local($thread['received']), 0, 10);
  2494. }
  2495. return false;
  2496. }
  2497. /**
  2498. * @brief add/remove activity to an item
  2499. *
  2500. * Toggle activities as like,dislike,attend of an item
  2501. *
  2502. * @param string $item_id
  2503. * @param string $verb
  2504. * Activity verb. One of
  2505. * like, unlike, dislike, undislike, attendyes, unattendyes,
  2506. * attendno, unattendno, attendmaybe, unattendmaybe
  2507. * @return bool
  2508. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  2509. * @throws \ImagickException
  2510. * @hook 'post_local_end'
  2511. * array $arr
  2512. * 'post_id' => ID of posted item
  2513. */
  2514. public static function performLike($item_id, $verb)
  2515. {
  2516. if (!local_user() && !remote_user()) {
  2517. return false;
  2518. }
  2519. switch ($verb) {
  2520. case 'like':
  2521. case 'unlike':
  2522. $activity = ACTIVITY_LIKE;
  2523. break;
  2524. case 'dislike':
  2525. case 'undislike':
  2526. $activity = ACTIVITY_DISLIKE;
  2527. break;
  2528. case 'attendyes':
  2529. case 'unattendyes':
  2530. $activity = ACTIVITY_ATTEND;
  2531. break;
  2532. case 'attendno':
  2533. case 'unattendno':
  2534. $activity = ACTIVITY_ATTENDNO;
  2535. break;
  2536. case 'attendmaybe':
  2537. case 'unattendmaybe':
  2538. $activity = ACTIVITY_ATTENDMAYBE;
  2539. break;
  2540. default:
  2541. Logger::log('like: unknown verb ' . $verb . ' for item ' . $item_id);
  2542. return false;
  2543. }
  2544. // Enable activity toggling instead of on/off
  2545. $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
  2546. Logger::log('like: verb ' . $verb . ' item ' . $item_id);
  2547. $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
  2548. if (!DBA::isResult($item)) {
  2549. Logger::log('like: unknown item ' . $item_id);
  2550. return false;
  2551. }
  2552. $item_uri = $item['uri'];
  2553. $uid = $item['uid'];
  2554. if (($uid == 0) && local_user()) {
  2555. $uid = local_user();
  2556. }
  2557. if (!Security::canWriteToUserWall($uid)) {
  2558. Logger::log('like: unable to write on wall ' . $uid);
  2559. return false;
  2560. }
  2561. // Retrieves the local post owner
  2562. $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
  2563. if (!DBA::isResult($owner_self_contact)) {
  2564. Logger::log('like: unknown owner ' . $uid);
  2565. return false;
  2566. }
  2567. // Retrieve the current logged in user's public contact
  2568. $author_id = public_contact();
  2569. $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
  2570. if (!DBA::isResult($author_contact)) {
  2571. Logger::log('like: unknown author ' . $author_id);
  2572. return false;
  2573. }
  2574. // Contact-id is the uid-dependant author contact
  2575. if (local_user() == $uid) {
  2576. $item_contact_id = $owner_self_contact['id'];
  2577. } else {
  2578. $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
  2579. $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
  2580. if (!DBA::isResult($item_contact)) {
  2581. Logger::log('like: unknown item contact ' . $item_contact_id);
  2582. return false;
  2583. }
  2584. }
  2585. // Look for an existing verb row
  2586. // event participation are essentially radio toggles. If you make a subsequent choice,
  2587. // we need to eradicate your first choice.
  2588. if ($event_verb_flag) {
  2589. $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
  2590. // Translate to the index based activity index
  2591. $activities = [];
  2592. foreach ($verbs as $verb) {
  2593. $activities[] = self::activityToIndex($verb);
  2594. }
  2595. } else {
  2596. $activities = self::activityToIndex($activity);
  2597. }
  2598. $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
  2599. 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
  2600. $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
  2601. // If it exists, mark it as deleted
  2602. if (DBA::isResult($like_item)) {
  2603. self::deleteById($like_item['id']);
  2604. if (!$event_verb_flag || $like_item['verb'] == $activity) {
  2605. return true;
  2606. }
  2607. }
  2608. // Verb is "un-something", just trying to delete existing entries
  2609. if (strpos($verb, 'un') === 0) {
  2610. return true;
  2611. }
  2612. $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE;
  2613. $new_item = [
  2614. 'guid' => System::createUUID(),
  2615. 'uri' => self::newURI($item['uid']),
  2616. 'uid' => $item['uid'],
  2617. 'contact-id' => $item_contact_id,
  2618. 'wall' => $item['wall'],
  2619. 'origin' => 1,
  2620. 'network' => Protocol::DFRN,
  2621. 'gravity' => GRAVITY_ACTIVITY,
  2622. 'parent' => $item['id'],
  2623. 'parent-uri' => $item['uri'],
  2624. 'thr-parent' => $item['uri'],
  2625. 'owner-id' => $author_id,
  2626. 'author-id' => $author_id,
  2627. 'body' => $activity,
  2628. 'verb' => $activity,
  2629. 'object-type' => $objtype,
  2630. 'allow_cid' => $item['allow_cid'],
  2631. 'allow_gid' => $item['allow_gid'],
  2632. 'deny_cid' => $item['deny_cid'],
  2633. 'deny_gid' => $item['deny_gid'],
  2634. 'visible' => 1,
  2635. 'unseen' => 1,
  2636. ];
  2637. $signed = Diaspora::createLikeSignature($uid, $new_item);
  2638. if (!empty($signed)) {
  2639. $new_item['diaspora_signed_text'] = json_encode($signed);
  2640. }
  2641. $new_item_id = self::insert($new_item);
  2642. // If the parent item isn't visible then set it to visible
  2643. if (!$item['visible']) {
  2644. self::update(['visible' => true], ['id' => $item['id']]);
  2645. }
  2646. $new_item['id'] = $new_item_id;
  2647. Hook::callAll('post_local_end', $new_item);
  2648. return true;
  2649. }
  2650. private static function addThread($itemid, $onlyshadow = false)
  2651. {
  2652. $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
  2653. 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
  2654. 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
  2655. $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
  2656. $item = self::selectFirst($fields, $condition);
  2657. if (!DBA::isResult($item)) {
  2658. return;
  2659. }
  2660. $item['iid'] = $itemid;
  2661. if (!$onlyshadow) {
  2662. $result = DBA::insert('thread', $item);
  2663. Logger::log("Add thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
  2664. }
  2665. }
  2666. private static function updateThread($itemid, $setmention = false)
  2667. {
  2668. $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
  2669. 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
  2670. 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
  2671. $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
  2672. $item = self::selectFirst($fields, $condition);
  2673. if (!DBA::isResult($item)) {
  2674. return;
  2675. }
  2676. if ($setmention) {
  2677. $item["mention"] = 1;
  2678. }
  2679. $fields = [];
  2680. foreach ($item as $field => $data) {
  2681. if (!in_array($field, ["guid"])) {
  2682. $fields[$field] = $data;
  2683. }
  2684. }
  2685. $result = DBA::update('thread', $fields, ['iid' => $itemid]);
  2686. Logger::log("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, Logger::DEBUG);
  2687. }
  2688. private static function deleteThread($itemid, $itemuri = "")
  2689. {
  2690. $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
  2691. if (!DBA::isResult($item)) {
  2692. Logger::log('No thread found for id '.$itemid, Logger::DEBUG);
  2693. return;
  2694. }
  2695. $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
  2696. Logger::log("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
  2697. if ($itemuri != "") {
  2698. $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
  2699. if (!self::exists($condition)) {
  2700. DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
  2701. Logger::log("deleteThread: Deleted shadow for item ".$itemuri, Logger::DEBUG);
  2702. }
  2703. }
  2704. }
  2705. public static function getPermissionsSQLByUserId($owner_id, $remote_verified = false, $groups = null, $remote_cid = null)
  2706. {
  2707. $local_user = local_user();
  2708. $remote_user = remote_user();
  2709. /*
  2710. * Construct permissions
  2711. *
  2712. * default permissions - anonymous user
  2713. */
  2714. $sql = " AND NOT `item`.`private`";
  2715. // Profile owner - everything is visible
  2716. if ($local_user && ($local_user == $owner_id)) {
  2717. $sql = '';
  2718. } elseif ($remote_user) {
  2719. /*
  2720. * Authenticated visitor. Unless pre-verified,
  2721. * check that the contact belongs to this $owner_id
  2722. * and load the groups the visitor belongs to.
  2723. * If pre-verified, the caller is expected to have already
  2724. * done this and passed the groups into this function.
  2725. */
  2726. $set = PermissionSet::get($owner_id, $remote_cid, $groups);
  2727. if (!empty($set)) {
  2728. $sql_set = " OR (`item`.`private` IN (1,2) AND `item`.`wall` AND `item`.`psid` IN (" . implode(',', $set) . "))";
  2729. } else {
  2730. $sql_set = '';
  2731. }
  2732. $sql = " AND (NOT `item`.`private`" . $sql_set . ")";
  2733. }
  2734. return $sql;
  2735. }
  2736. /**
  2737. * get translated item type
  2738. *
  2739. * @param $item
  2740. * @return string
  2741. */
  2742. public static function postType($item)
  2743. {
  2744. if (!empty($item['event-id'])) {
  2745. return L10n::t('event');
  2746. } elseif (!empty($item['resource-id'])) {
  2747. return L10n::t('photo');
  2748. } elseif (!empty($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
  2749. return L10n::t('activity');
  2750. } elseif ($item['id'] != $item['parent']) {
  2751. return L10n::t('comment');
  2752. }
  2753. return L10n::t('post');
  2754. }
  2755. /**
  2756. * Sets the "rendered-html" field of the provided item
  2757. *
  2758. * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
  2759. *
  2760. * @param array $item
  2761. * @param bool $update
  2762. *
  2763. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  2764. * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
  2765. */
  2766. public static function putInCache(&$item, $update = false)
  2767. {
  2768. $body = $item["body"];
  2769. $rendered_hash = defaults($item, 'rendered-hash', '');
  2770. $rendered_html = defaults($item, 'rendered-html', '');
  2771. if ($rendered_hash == ''
  2772. || $rendered_html == ""
  2773. || $rendered_hash != hash("md5", $item["body"])
  2774. || Config::get("system", "ignore_cache")
  2775. ) {
  2776. $a = self::getApp();
  2777. redir_private_images($a, $item);
  2778. $item["rendered-html"] = prepare_text($item["body"]);
  2779. $item["rendered-hash"] = hash("md5", $item["body"]);
  2780. $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
  2781. Hook::callAll('put_item_in_cache', $hook_data);
  2782. $item['rendered-html'] = $hook_data['rendered-html'];
  2783. $item['rendered-hash'] = $hook_data['rendered-hash'];
  2784. unset($hook_data);
  2785. // Force an update if the generated values differ from the existing ones
  2786. if ($rendered_hash != $item["rendered-hash"]) {
  2787. $update = true;
  2788. }
  2789. // Only compare the HTML when we forcefully ignore the cache
  2790. if (Config::get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
  2791. $update = true;
  2792. }
  2793. if ($update && !empty($item["id"])) {
  2794. self::update(
  2795. [
  2796. 'rendered-html' => $item["rendered-html"],
  2797. 'rendered-hash' => $item["rendered-hash"]
  2798. ],
  2799. ['id' => $item["id"]]
  2800. );
  2801. }
  2802. }
  2803. $item["body"] = $body;
  2804. }
  2805. /**
  2806. * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
  2807. * If attach is true, also add icons for item attachments.
  2808. *
  2809. * @param array $item
  2810. * @param boolean $attach
  2811. * @param boolean $is_preview
  2812. * @return string item body html
  2813. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  2814. * @throws \ImagickException
  2815. * @hook prepare_body_init item array before any work
  2816. * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
  2817. * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
  2818. * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
  2819. */
  2820. public static function prepareBody(array &$item, $attach = false, $is_preview = false)
  2821. {
  2822. $a = self::getApp();
  2823. Hook::callAll('prepare_body_init', $item);
  2824. // In order to provide theme developers more possibilities, event items
  2825. // are treated differently.
  2826. if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
  2827. $ev = Event::getItemHTML($item);
  2828. return $ev;
  2829. }
  2830. $tags = Term::populateTagsFromItem($item);
  2831. $item['tags'] = $tags['tags'];
  2832. $item['hashtags'] = $tags['hashtags'];
  2833. $item['mentions'] = $tags['mentions'];
  2834. // Compile eventual content filter reasons
  2835. $filter_reasons = [];
  2836. if (!$is_preview && public_contact() != $item['author-id']) {
  2837. if (!empty($item['content-warning']) && (!local_user() || !PConfig::get(local_user(), 'system', 'disable_cw', false))) {
  2838. $filter_reasons[] = L10n::t('Content warning: %s', $item['content-warning']);
  2839. }
  2840. $hook_data = [
  2841. 'item' => $item,
  2842. 'filter_reasons' => $filter_reasons
  2843. ];
  2844. Hook::callAll('prepare_body_content_filter', $hook_data);
  2845. $filter_reasons = $hook_data['filter_reasons'];
  2846. unset($hook_data);
  2847. }
  2848. // Update the cached values if there is no "zrl=..." on the links.
  2849. $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
  2850. // Or update it if the current viewer is the intented viewer.
  2851. if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
  2852. $update = true;
  2853. }
  2854. self::putInCache($item, $update);
  2855. $s = $item["rendered-html"];
  2856. $hook_data = [
  2857. 'item' => $item,
  2858. 'html' => $s,
  2859. 'preview' => $is_preview,
  2860. 'filter_reasons' => $filter_reasons
  2861. ];
  2862. Hook::callAll('prepare_body', $hook_data);
  2863. $s = $hook_data['html'];
  2864. unset($hook_data);
  2865. if (!$attach) {
  2866. // Replace the blockquotes with quotes that are used in mails.
  2867. $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
  2868. $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
  2869. return $s;
  2870. }
  2871. $as = '';
  2872. $vhead = false;
  2873. $matches = [];
  2874. preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
  2875. foreach ($matches as $mtch) {
  2876. $mime = $mtch[3];
  2877. $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
  2878. if (strpos($mime, 'video') !== false) {
  2879. if (!$vhead) {
  2880. $vhead = true;
  2881. $a->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'));
  2882. }
  2883. $url_parts = explode('/', $the_url);
  2884. $id = end($url_parts);
  2885. $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
  2886. '$video' => [
  2887. 'id' => $id,
  2888. 'title' => L10n::t('View Video'),
  2889. 'src' => $the_url,
  2890. 'mime' => $mime,
  2891. ],
  2892. ]);
  2893. }
  2894. $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
  2895. if ($filetype) {
  2896. $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
  2897. $filesubtype = str_replace('.', '-', $filesubtype);
  2898. } else {
  2899. $filetype = 'unkn';
  2900. $filesubtype = 'unkn';
  2901. }
  2902. $title = Strings::escapeHtml(trim(defaults($mtch, 4, $mtch[1])));
  2903. $title .= ' ' . $mtch[2] . ' ' . L10n::t('bytes');
  2904. $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
  2905. $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
  2906. }
  2907. if ($as != '') {
  2908. $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
  2909. }
  2910. // Map.
  2911. if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
  2912. $x = Map::byCoordinates(trim($item['coord']));
  2913. if ($x) {
  2914. $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
  2915. }
  2916. }
  2917. // Look for spoiler.
  2918. $spoilersearch = '<blockquote class="spoiler">';
  2919. // Remove line breaks before the spoiler.
  2920. while ((strpos($s, "\n" . $spoilersearch) !== false)) {
  2921. $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
  2922. }
  2923. while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
  2924. $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
  2925. }
  2926. while ((strpos($s, $spoilersearch) !== false)) {
  2927. $pos = strpos($s, $spoilersearch);
  2928. $rnd = Strings::getRandomHex(8);
  2929. $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
  2930. '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
  2931. $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
  2932. }
  2933. // Look for quote with author.
  2934. $authorsearch = '<blockquote class="author">';
  2935. while ((strpos($s, $authorsearch) !== false)) {
  2936. $pos = strpos($s, $authorsearch);
  2937. $rnd = Strings::getRandomHex(8);
  2938. $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
  2939. '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
  2940. $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
  2941. }
  2942. // Replace friendica image url size with theme preference.
  2943. if (!empty($a->theme_info['item_image_size'])) {
  2944. $ps = $a->theme_info['item_image_size'];
  2945. $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
  2946. }
  2947. $s = HTML::applyContentFilter($s, $filter_reasons);
  2948. $hook_data = ['item' => $item, 'html' => $s];
  2949. Hook::callAll('prepare_body_final', $hook_data);
  2950. return $hook_data['html'];
  2951. }
  2952. /**
  2953. * get private link for item
  2954. *
  2955. * @param array $item
  2956. * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
  2957. * @throws \Exception
  2958. */
  2959. public static function getPlink($item)
  2960. {
  2961. $a = self::getApp();
  2962. if ($a->user['nickname'] != "") {
  2963. $ret = [
  2964. 'href' => "display/" . $item['guid'],
  2965. 'orig' => "display/" . $item['guid'],
  2966. 'title' => L10n::t('View on separate page'),
  2967. 'orig_title' => L10n::t('view on separate page'),
  2968. ];
  2969. if (!empty($item['plink'])) {
  2970. $ret["href"] = $a->removeBaseURL($item['plink']);
  2971. $ret["title"] = L10n::t('link to source');
  2972. }
  2973. } elseif (!empty($item['plink']) && ($item['private'] != 1)) {
  2974. $ret = [
  2975. 'href' => $item['plink'],
  2976. 'orig' => $item['plink'],
  2977. 'title' => L10n::t('link to source'),
  2978. ];
  2979. } else {
  2980. $ret = [];
  2981. }
  2982. return $ret;
  2983. }
  2984. /**
  2985. * Is the given item array a post that is sent as starting post to a forum?
  2986. *
  2987. * @param array $item
  2988. * @param array $owner
  2989. *
  2990. * @return boolean "true" when it is a forum post
  2991. */
  2992. public static function isForumPost(array $item, array $owner = [])
  2993. {
  2994. if (empty($owner)) {
  2995. $owner = User::getOwnerDataById($item['uid']);
  2996. if (empty($owner)) {
  2997. return false;
  2998. }
  2999. }
  3000. if (($item['author-id'] == $item['owner-id']) ||
  3001. ($owner['id'] == $item['contact-id']) ||
  3002. ($item['uri'] != $item['parent-uri']) ||
  3003. $item['origin']) {
  3004. return false;
  3005. }
  3006. return Contact::isForum($item['contact-id']);
  3007. }
  3008. /**
  3009. * Search item id for given URI or plink
  3010. *
  3011. * @param string $uri
  3012. * @param integer $uid
  3013. *
  3014. * @return integer item id
  3015. */
  3016. public static function searchByLink($uri, $uid = 0)
  3017. {
  3018. $ssl_uri = str_replace('http://', 'https://', $uri);
  3019. $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
  3020. $item = DBA::selectFirst('item', ['id'], ['uri' => $uris, 'uid' => $uid]);
  3021. if (DBA::isResult($item)) {
  3022. return $item['id'];
  3023. }
  3024. $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
  3025. if (!DBA::isResult($itemcontent)) {
  3026. return 0;
  3027. }
  3028. $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
  3029. if (!DBA::isResult($itemuri)) {
  3030. return 0;
  3031. }
  3032. $item = DBA::selectFirst('item', ['id'], ['uri' => $itemuri['uri'], 'uid' => $uid]);
  3033. if (DBA::isResult($item)) {
  3034. return $item['id'];
  3035. }
  3036. return 0;
  3037. }
  3038. /**
  3039. * Fetches item for given URI or plink
  3040. *
  3041. * @param string $uri
  3042. * @param integer $uid
  3043. *
  3044. * @return integer item id
  3045. */
  3046. public static function fetchByLink($uri, $uid = 0)
  3047. {
  3048. $item_id = self::searchByLink($uri, $uid);
  3049. if (!empty($item_id)) {
  3050. echo "a\n";
  3051. return $item_id;
  3052. }
  3053. echo "b\n";
  3054. ActivityPub\Processor::fetchMissingActivity($uri);
  3055. $item_id = self::searchByLink($uri, $uid);
  3056. if (!empty($item_id)) {
  3057. echo "c\n";
  3058. return $item_id;
  3059. }
  3060. echo "d\n";
  3061. return 0;
  3062. }
  3063. }