]> git.mxchange.org Git - friendica.git/blob - include/items.php
Class file relocations
[friendica.git] / include / items.php
1 <?php
2
3 /**
4  * @file include/items.php
5  */
6
7 use Friendica\App;
8 use Friendica\Core\System;
9 use Friendica\ParseUrl;
10 use Friendica\Util\Lock;
11 use Friendica\Core\Config;
12 use Friendica\Core\PConfig;
13 use Friendica\Core\Worker;
14 use Friendica\Database\DBM;
15 use Friendica\Protocol\DFRN;
16
17 require_once 'include/bbcode.php';
18 require_once 'include/oembed.php';
19 require_once 'include/salmon.php';
20 require_once 'include/crypto.php';
21 require_once 'include/Photo.php';
22 require_once 'include/tags.php';
23 require_once 'include/files.php';
24 require_once 'include/text.php';
25 require_once 'include/email.php';
26 require_once 'include/threads.php';
27 require_once 'include/socgraph.php';
28 require_once 'include/plaintext.php';
29 require_once 'include/ostatus.php';
30 require_once 'include/feed.php';
31 require_once 'include/Contact.php';
32 require_once 'mod/share.php';
33 require_once 'include/enotify.php';
34 require_once 'include/group.php';
35
36 /// @TODO one day with composer autoloader no more needed
37 require_once 'library/defuse/php-encryption-1.2.1/Crypto.php';
38
39 function construct_verb($item) {
40         if ($item['verb']) {
41                 return $item['verb'];
42         }
43         return ACTIVITY_POST;
44 }
45
46 /* limit_body_size()
47  *
48  *              The purpose of this function is to apply system message length limits to
49  *              imported messages without including any embedded photos in the length
50  */
51 if (! function_exists('limit_body_size')) {
52 function limit_body_size($body) {
53
54 //      logger('limit_body_size: start', LOGGER_DEBUG);
55
56         $maxlen = get_max_import_size();
57
58         // If the length of the body, including the embedded images, is smaller
59         // than the maximum, then don't waste time looking for the images
60         if ($maxlen && (strlen($body) > $maxlen)) {
61
62                 logger('limit_body_size: the total body length exceeds the limit', LOGGER_DEBUG);
63
64                 $orig_body = $body;
65                 $new_body = '';
66                 $textlen = 0;
67                 $max_found = false;
68
69                 $img_start = strpos($orig_body, '[img');
70                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
71                 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
72                 while (($img_st_close !== false) && ($img_end !== false)) {
73
74                         $img_st_close++; // make it point to AFTER the closing bracket
75                         $img_end += $img_start;
76                         $img_end += strlen('[/img]');
77
78                         if (! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
79                                 // This is an embedded image
80
81                                 if (($textlen + $img_start) > $maxlen ) {
82                                         if ($textlen < $maxlen) {
83                                                 logger('limit_body_size: the limit happens before an embedded image', LOGGER_DEBUG);
84                                                 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
85                                                 $textlen = $maxlen;
86                                         }
87                                 } else {
88                                         $new_body = $new_body . substr($orig_body, 0, $img_start);
89                                         $textlen += $img_start;
90                                 }
91
92                                 $new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start);
93                         } else {
94
95                                 if (($textlen + $img_end) > $maxlen ) {
96                                         if ($textlen < $maxlen) {
97                                                 logger('limit_body_size: the limit happens before the end of a non-embedded image', LOGGER_DEBUG);
98                                                 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
99                                                 $textlen = $maxlen;
100                                         }
101                                 } else {
102                                         $new_body = $new_body . substr($orig_body, 0, $img_end);
103                                         $textlen += $img_end;
104                                 }
105                         }
106                         $orig_body = substr($orig_body, $img_end);
107
108                         if ($orig_body === false) {
109                                 // in case the body ends on a closing image tag
110                                 $orig_body = '';
111                         }
112
113                         $img_start = strpos($orig_body, '[img');
114                         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
115                         $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
116                 }
117
118                 if (($textlen + strlen($orig_body)) > $maxlen) {
119                         if ($textlen < $maxlen) {
120                                 logger('limit_body_size: the limit happens after the end of the last image', LOGGER_DEBUG);
121                                 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
122                                 $textlen = $maxlen;
123                         }
124                 } else {
125                         logger('limit_body_size: the text size with embedded images extracted did not violate the limit', LOGGER_DEBUG);
126                         $new_body = $new_body . $orig_body;
127                         $textlen += strlen($orig_body);
128                 }
129
130                 return $new_body;
131         } else {
132                 return $body;
133         }
134 }}
135
136 function title_is_body($title, $body) {
137
138         $title = strip_tags($title);
139         $title = trim($title);
140         $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
141         $title = str_replace(array("\n", "\r", "\t", " "), array("", "", "", ""), $title);
142
143         $body = strip_tags($body);
144         $body = trim($body);
145         $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
146         $body = str_replace(array("\n", "\r", "\t", " "), array("", "", "", ""), $body);
147
148         if (strlen($title) < strlen($body)) {
149                 $body = substr($body, 0, strlen($title));
150         }
151
152         if (($title != $body) && (substr($title, -3) == "...")) {
153                 $pos = strrpos($title, "...");
154                 if ($pos > 0) {
155                         $title = substr($title, 0, $pos);
156                         $body = substr($body, 0, $pos);
157                 }
158         }
159
160         return ($title == $body);
161 }
162
163 function add_page_info_data($data) {
164         call_hooks('page_info_data', $data);
165
166         // It maybe is a rich content, but if it does have everything that a link has,
167         // then treat it that way
168         if (($data["type"] == "rich") && is_string($data["title"]) &&
169                 is_string($data["text"]) && (sizeof($data["images"]) > 0)) {
170                 $data["type"] = "link";
171         }
172
173         if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
174                 return "";
175         }
176
177         if ($no_photos && ($data["type"] == "photo")) {
178                 return "";
179         }
180
181         if (sizeof($data["images"]) > 0) {
182                 $preview = $data["images"][0];
183         } else {
184                 $preview = "";
185         }
186
187         // Escape some bad characters
188         $data["url"] = str_replace(array("[", "]"), array("&#91;", "&#93;"), htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
189         $data["title"] = str_replace(array("[", "]"), array("&#91;", "&#93;"), htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
190
191         $text = "[attachment type='".$data["type"]."'";
192
193         if ($data["text"] == "") {
194                 $data["text"] = $data["title"];
195         }
196
197         if ($data["text"] == "") {
198                 $data["text"] = $data["url"];
199         }
200
201         if ($data["url"] != "") {
202                 $text .= " url='".$data["url"]."'";
203         }
204
205         if ($data["title"] != "") {
206                 $text .= " title='".$data["title"]."'";
207         }
208
209         if (sizeof($data["images"]) > 0) {
210                 $preview = str_replace(array("[", "]"), array("&#91;", "&#93;"), htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
211                 // if the preview picture is larger than 500 pixels then show it in a larger mode
212                 // But only, if the picture isn't higher than large (To prevent huge posts)
213                 if (($data["images"][0]["width"] >= 500) && ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
214                         $text .= " image='".$preview."'";
215                 } else {
216                         $text .= " preview='".$preview."'";
217                 }
218         }
219
220         $text .= "]".$data["text"]."[/attachment]";
221
222         $hashtags = "";
223         if (isset($data["keywords"]) && count($data["keywords"])) {
224                 $hashtags = "\n";
225                 foreach ($data["keywords"] AS $keyword) {
226                         /// @todo make a positive list of allowed characters
227                         $hashtag = str_replace(array(" ", "+", "/", ".", "#", "'", "’", "`", "(", ")", "„", "“"),
228                                                 array("", "", "", "", "", "", "", "", "", "", "", ""), $keyword);
229                         $hashtags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url] ";
230                 }
231         }
232
233         return "\n".$text.$hashtags;
234 }
235
236 function query_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
237
238         $data = ParseUrl::getSiteinfoCached($url, true);
239
240         if ($photo != "") {
241                 $data["images"][0]["src"] = $photo;
242         }
243
244         logger('fetch page info for ' . $url . ' ' . print_r($data, true), LOGGER_DEBUG);
245
246         if (!$keywords && isset($data["keywords"])) {
247                 unset($data["keywords"]);
248         }
249
250         if (($keyword_blacklist != "") && isset($data["keywords"])) {
251                 $list = explode(", ", $keyword_blacklist);
252                 foreach ($list AS $keyword) {
253                         $keyword = trim($keyword);
254                         $index = array_search($keyword, $data["keywords"]);
255                         if ($index !== false) {
256                                 unset($data["keywords"][$index]);
257                         }
258                 }
259         }
260
261         return $data;
262 }
263
264 function add_page_keywords($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
265         $data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
266
267         $tags = "";
268         if (isset($data["keywords"]) && count($data["keywords"])) {
269                 foreach ($data["keywords"] AS $keyword) {
270                         $hashtag = str_replace(array(" ", "+", "/", ".", "#", "'"),
271                                 array("", "", "", "", "", ""), $keyword);
272
273                         if ($tags != "") {
274                                 $tags .= ", ";
275                         }
276
277                         $tags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url]";
278                 }
279         }
280
281         return $tags;
282 }
283
284 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
285         $data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
286
287         $text = add_page_info_data($data);
288
289         return $text;
290 }
291
292 function add_page_info_to_body($body, $texturl = false, $no_photos = false) {
293
294         logger('add_page_info_to_body: fetch page info for body ' . $body, LOGGER_DEBUG);
295
296         $URLSearchString = "^\[\]";
297
298         // Fix for Mastodon where the mentions are in a different format
299         $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
300                 '$2[url=$1]$3[/url]', $body);
301
302         // Adding these spaces is a quick hack due to my problems with regular expressions :)
303         preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
304
305         if (!$matches) {
306                 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
307         }
308
309         // Convert urls without bbcode elements
310         if (!$matches && $texturl) {
311                 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
312
313                 // Yeah, a hack. I really hate regular expressions :)
314                 if ($matches) {
315                         $matches[1] = $matches[2];
316                 }
317         }
318
319         if ($matches) {
320                 $footer = add_page_info($matches[1], $no_photos);
321         }
322
323         // Remove the link from the body if the link is attached at the end of the post
324         if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
325                 $removedlink = trim(str_replace($matches[1], "", $body));
326                 if (($removedlink == "") || strstr($body, $removedlink)) {
327                         $body = $removedlink;
328                 }
329
330                 $url = str_replace(array('/', '.'), array('\/', '\.'), $matches[1]);
331                 $removedlink = preg_replace("/\[url\=" . $url . "\](.*?)\[\/url\]/ism", '', $body);
332                 if (($removedlink == "") || strstr($body, $removedlink)) {
333                         $body = $removedlink;
334                 }
335         }
336
337         // Add the page information to the bottom
338         if (isset($footer) && (trim($footer) != "")) {
339                 $body .= $footer;
340         }
341
342         return $body;
343 }
344
345 /**
346  * Adds a "lang" specification in a "postopts" element of given $arr,
347  * if possible and not already present.
348  * Expects "body" element to exist in $arr.
349  *
350  * @todo Add a parameter to request forcing override
351  */
352 function item_add_language_opt(&$arr) {
353
354         if (version_compare(PHP_VERSION, '5.3.0', '<')) {
355                  // LanguageDetect.php not available ?
356                 return;
357         }
358
359         if (x($arr, 'postopts') ) {
360                 if (strstr($arr['postopts'], 'lang=') ) {
361                         // do not override
362                         /// @TODO Add parameter to request overriding
363                         return;
364                 }
365                 $postopts = $arr['postopts'];
366         } else {
367                 $postopts = "";
368         }
369
370         $naked_body = preg_replace('/\[(.+?)\]/','', $arr['body']);
371         $l = new Text_LanguageDetect();
372         $lng = $l->detect($naked_body, 3);
373
374         if (sizeof($lng) > 0) {
375                 if ($postopts != "") $postopts .= '&'; // arbitrary separator, to be reviewed
376                 $postopts .= 'lang=';
377                 $sep = "";
378                 foreach ($lng as $language => $score) {
379                         $postopts .= $sep . $language . ";" . $score;
380                         $sep = ':';
381                 }
382                 $arr['postopts'] = $postopts;
383         }
384 }
385
386 /**
387  * @brief Creates an unique guid out of a given uri
388  *
389  * @param string $uri uri of an item entry
390  * @param string $host (Optional) hostname for the GUID prefix
391  * @return string unique guid
392  */
393 function uri_to_guid($uri, $host = "") {
394
395         // Our regular guid routine is using this kind of prefix as well
396         // We have to avoid that different routines could accidentally create the same value
397         $parsed = parse_url($uri);
398
399         // When the hostname isn't given, we take it from the uri
400         if ($host == "") {
401                 // Is it in the format data@host.tld?
402                 if ((count($parsed) == 1) && strstr($uri, '@')) {
403                         $mailparts = explode('@', $uri);
404                         $host = array_pop($mailparts);
405                 } else {
406                         $host = $parsed["host"];
407                 }
408         }
409
410         // We use a hash of the hostname as prefix for the guid
411         $guid_prefix = hash("crc32", $host);
412
413         // Remove the scheme to make sure that "https" and "http" doesn't make a difference
414         unset($parsed["scheme"]);
415
416         // Glue it together to be able to make a hash from it
417         $host_id = implode("/", $parsed);
418
419         // We could use any hash algorithm since it isn't a security issue
420         $host_hash = hash("ripemd128", $host_id);
421
422         return $guid_prefix.$host_hash;
423 }
424
425 /**
426  * @brief Store the conversation data
427  *
428  * @param array $arr Item array with conversation data
429  * @return array Item array with removed conversation data
430  */
431 function store_conversation($arr) {
432         if (in_array($arr['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
433                 $conversation = array('item-uri' => $arr['uri'], 'received' => DBM::date());
434
435                 if (isset($arr['parent-uri']) && ($arr['parent-uri'] != $arr['uri'])) {
436                         $conversation['reply-to-uri'] = $arr['parent-uri'];
437                 }
438                 if (isset($arr['thr-parent']) && ($arr['thr-parent'] != $arr['uri'])) {
439                         $conversation['reply-to-uri'] = $arr['thr-parent'];
440                 }
441
442                 if (isset($arr['conversation-uri'])) {
443                         $conversation['conversation-uri'] = $arr['conversation-uri'];
444                 }
445
446                 if (isset($arr['conversation-href'])) {
447                         $conversation['conversation-href'] = $arr['conversation-href'];
448                 }
449
450                 if (isset($arr['protocol'])) {
451                         $conversation['protocol'] = $arr['protocol'];
452                 }
453
454                 if (isset($arr['source'])) {
455                         $conversation['source'] = $arr['source'];
456                 }
457
458                 $old_conv = dba::fetch_first("SELECT `item-uri`, `reply-to-uri`, `conversation-uri`, `conversation-href`, `protocol`, `source`
459                                 FROM `conversation` WHERE `item-uri` = ?", $conversation['item-uri']);
460                 if (DBM::is_result($old_conv)) {
461                         // Don't update when only the source has changed.
462                         // Only do this when there had been no source before.
463                         if ($old_conv['source'] != '') {
464                                 unset($old_conv['source']);
465                         }
466                         // Update structure data all the time but the source only when its from a better protocol.
467                         if (($old_conv['protocol'] < $conversation['protocol']) && ($old_conv['protocol'] != 0)) {
468                                 unset($conversation['protocol']);
469                                 unset($conversation['source']);
470                         }
471                         if (!dba::update('conversation', $conversation, array('item-uri' => $conversation['item-uri']), $old_conv)) {
472                                 logger('Conversation: update for '.$conversation['item-uri'].' from '.$conv['protocol'].' to '.$conversation['protocol'].' failed', LOGGER_DEBUG);
473                         }
474                 } else {
475                         if (!dba::insert('conversation', $conversation, true)) {
476                                 logger('Conversation: insert for '.$conversation['item-uri'].' (protocol '.$conversation['protocol'].') failed', LOGGER_DEBUG);
477                         }
478                 }
479         }
480
481         unset($arr['conversation-uri']);
482         unset($arr['conversation-href']);
483         unset($arr['protocol']);
484         unset($arr['source']);
485
486         return $arr;
487 }
488
489 /// @TODO add type-hint array
490 function item_store($arr, $force_parent = false, $notify = false, $dontcache = false) {
491
492         $a = get_app();
493
494         // If it is a posting where users should get notifications, then define it as wall posting
495         if ($notify) {
496                 $arr['wall'] = 1;
497                 $arr['type'] = 'wall';
498                 $arr['origin'] = 1;
499                 $arr['last-child'] = 1;
500                 $arr['network'] = NETWORK_DFRN;
501                 $arr['protocol'] = PROTOCOL_DFRN;
502
503                 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
504                 // In difference to the call to "uri_to_guid" several lines below we add the hash of our own host.
505                 // This is done because our host is the original creator of the post.
506                 if (!isset($arr['guid'])) {
507                         if (isset($arr['plink'])) {
508                                 $arr['guid'] = uri_to_guid($arr['plink'], $a->get_hostname());
509                         } elseif (isset($arr['uri'])) {
510                                 $arr['guid'] = uri_to_guid($arr['uri'], $a->get_hostname());
511                         }
512                 }
513         }
514
515         if ($notify) {
516                 $guid_prefix = "";
517         } elseif ((trim($arr['guid']) == "") && (trim($arr['plink']) != "")) {
518                 $arr['guid'] = uri_to_guid($arr['plink']);
519         } elseif ((trim($arr['guid']) == "") && (trim($arr['uri']) != "")) {
520                 $arr['guid'] = uri_to_guid($arr['uri']);
521         } else {
522                 $parsed = parse_url($arr["author-link"]);
523                 $guid_prefix = hash("crc32", $parsed["host"]);
524         }
525
526         $arr['guid']          = ((x($arr, 'guid'))          ? notags(trim($arr['guid']))          : get_guid(32, $guid_prefix));
527         $arr['uri']           = ((x($arr, 'uri'))           ? notags(trim($arr['uri']))           : item_new_uri($a->get_hostname(), $uid, $arr['guid']));
528
529         // Store conversation data
530         $arr = store_conversation($arr);
531
532         /*
533          * If a Diaspora signature structure was passed in, pull it out of the
534          * item array and set it aside for later storage.
535          */
536
537         $dsprsig = null;
538         if (x($arr, 'dsprsig')) {
539                 $encoded_signature = $arr['dsprsig'];
540                 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
541                 unset($arr['dsprsig']);
542         }
543
544         // Converting the plink
545         /// @todo Check if this is really still needed
546         if ($arr['network'] == NETWORK_OSTATUS) {
547                 if (isset($arr['plink'])) {
548                         $arr['plink'] = ostatus::convert_href($arr['plink']);
549                 } elseif (isset($arr['uri'])) {
550                         $arr['plink'] = ostatus::convert_href($arr['uri']);
551                 }
552         }
553
554         if (x($arr, 'gravity')) {
555                 $arr['gravity'] = intval($arr['gravity']);
556         } elseif ($arr['parent-uri'] === $arr['uri']) {
557                 $arr['gravity'] = 0;
558         } elseif (activity_match($arr['verb'],ACTIVITY_POST)) {
559                 $arr['gravity'] = 6;
560         } else {
561                 $arr['gravity'] = 6;   // extensible catchall
562         }
563
564         if (! x($arr, 'type')) {
565                 $arr['type']      = 'remote';
566         }
567
568         $uid = intval($arr['uid']);
569
570         // check for create date and expire time
571         $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
572
573         $r = dba::select('user', array('expire'), array('uid' => $uid), array("limit" => 1));
574         if (DBM::is_result($r) && ($r['expire'] > 0) && (($r['expire'] < $expire_interval) || ($expire_interval == 0))) {
575                 $expire_interval = $r['expire'];
576         }
577
578         if (($expire_interval > 0) && !empty($arr['created'])) {
579                 $expire_date = time() - ($expire_interval * 86400);
580                 $created_date = strtotime($arr['created']);
581                 if ($created_date < $expire_date) {
582                         logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($arr,true), LOGGER_DEBUG);
583                         return 0;
584                 }
585         }
586
587         /*
588          * Do we already have this item?
589          * We have to check several networks since Friendica posts could be repeated
590          * via OStatus (maybe Diasporsa as well)
591          */
592         if (in_array(trim($arr['network']), array(NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""))) {
593                 $r = q("SELECT `id`, `network` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` IN ('%s', '%s', '%s')  LIMIT 1",
594                                 dbesc(trim($arr['uri'])),
595                                 intval($uid),
596                                 dbesc(NETWORK_DIASPORA),
597                                 dbesc(NETWORK_DFRN),
598                                 dbesc(NETWORK_OSTATUS)
599                         );
600                 if (DBM::is_result($r)) {
601                         // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
602                         if ($uid != 0) {
603                                 logger("Item with uri ".$arr['uri']." already existed for user ".$uid." with id ".$r[0]["id"]." target network ".$r[0]["network"]." - new network: ".$arr['network']);
604                         }
605
606                         return $r[0]["id"];
607                 }
608         }
609
610         /// @TODO old-lost code?
611         // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
612         // Deactivated, since the bbcode parser can handle with it - and it destroys posts with some smileys that contain "<"
613         //if ((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
614         //      $arr['body'] = strip_tags($arr['body']);
615
616         item_add_language_opt($arr);
617
618         $arr['wall']          = ((x($arr, 'wall'))          ? intval($arr['wall'])                : 0);
619         $arr['extid']         = ((x($arr, 'extid'))         ? notags(trim($arr['extid']))         : '');
620         $arr['author-name']   = ((x($arr, 'author-name'))   ? trim($arr['author-name'])   : '');
621         $arr['author-link']   = ((x($arr, 'author-link'))   ? notags(trim($arr['author-link']))   : '');
622         $arr['author-avatar'] = ((x($arr, 'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
623         $arr['owner-name']    = ((x($arr, 'owner-name'))    ? trim($arr['owner-name'])    : '');
624         $arr['owner-link']    = ((x($arr, 'owner-link'))    ? notags(trim($arr['owner-link']))    : '');
625         $arr['owner-avatar']  = ((x($arr, 'owner-avatar'))  ? notags(trim($arr['owner-avatar']))  : '');
626         $arr['received']      = ((x($arr, 'received') !== false) ? datetime_convert('UTC','UTC', $arr['received']) : datetime_convert());
627         $arr['created']       = ((x($arr, 'created') !== false) ? datetime_convert('UTC','UTC', $arr['created']) : $arr['received']);
628         $arr['edited']        = ((x($arr, 'edited') !== false) ? datetime_convert('UTC','UTC', $arr['edited']) : $arr['created']);
629         $arr['changed']       = ((x($arr, 'changed') !== false) ? datetime_convert('UTC','UTC', $arr['changed']) : $arr['created']);
630         $arr['commented']     = ((x($arr, 'commented') !== false) ? datetime_convert('UTC','UTC', $arr['commented']) : $arr['created']);
631         $arr['title']         = ((x($arr, 'title'))         ? trim($arr['title'])         : '');
632         $arr['location']      = ((x($arr, 'location'))      ? trim($arr['location'])      : '');
633         $arr['coord']         = ((x($arr, 'coord'))         ? notags(trim($arr['coord']))         : '');
634         $arr['last-child']    = ((x($arr, 'last-child'))    ? intval($arr['last-child'])          : 0 );
635         $arr['visible']       = ((x($arr, 'visible') !== false) ? intval($arr['visible'])         : 1 );
636         $arr['deleted']       = 0;
637         $arr['parent-uri']    = ((x($arr, 'parent-uri'))    ? notags(trim($arr['parent-uri']))    : $arr['uri']);
638         $arr['verb']          = ((x($arr, 'verb'))          ? notags(trim($arr['verb']))          : '');
639         $arr['object-type']   = ((x($arr, 'object-type'))   ? notags(trim($arr['object-type']))   : '');
640         $arr['object']        = ((x($arr, 'object'))        ? trim($arr['object'])                : '');
641         $arr['target-type']   = ((x($arr, 'target-type'))   ? notags(trim($arr['target-type']))   : '');
642         $arr['target']        = ((x($arr, 'target'))        ? trim($arr['target'])                : '');
643         $arr['plink']         = ((x($arr, 'plink'))         ? notags(trim($arr['plink']))         : '');
644         $arr['allow_cid']     = ((x($arr, 'allow_cid'))     ? trim($arr['allow_cid'])             : '');
645         $arr['allow_gid']     = ((x($arr, 'allow_gid'))     ? trim($arr['allow_gid'])             : '');
646         $arr['deny_cid']      = ((x($arr, 'deny_cid'))      ? trim($arr['deny_cid'])              : '');
647         $arr['deny_gid']      = ((x($arr, 'deny_gid'))      ? trim($arr['deny_gid'])              : '');
648         $arr['private']       = ((x($arr, 'private'))       ? intval($arr['private'])             : 0 );
649         $arr['bookmark']      = ((x($arr, 'bookmark'))      ? intval($arr['bookmark'])            : 0 );
650         $arr['body']          = ((x($arr, 'body'))          ? trim($arr['body'])                  : '');
651         $arr['tag']           = ((x($arr, 'tag'))           ? notags(trim($arr['tag']))           : '');
652         $arr['attach']        = ((x($arr, 'attach'))        ? notags(trim($arr['attach']))        : '');
653         $arr['app']           = ((x($arr, 'app'))           ? notags(trim($arr['app']))           : '');
654         $arr['origin']        = ((x($arr, 'origin'))        ? intval($arr['origin'])              : 0 );
655         $arr['network']       = ((x($arr, 'network'))       ? trim($arr['network'])               : '');
656         $arr['postopts']      = ((x($arr, 'postopts'))      ? trim($arr['postopts'])              : '');
657         $arr['resource-id']   = ((x($arr, 'resource-id'))   ? trim($arr['resource-id'])           : '');
658         $arr['event-id']      = ((x($arr, 'event-id'))      ? intval($arr['event-id'])            : 0 );
659         $arr['inform']        = ((x($arr, 'inform'))        ? trim($arr['inform'])                : '');
660         $arr['file']          = ((x($arr, 'file'))          ? trim($arr['file'])                  : '');
661
662         // When there is no content then we don't post it
663         if ($arr['body'].$arr['title'] == '') {
664                 return 0;
665         }
666
667         // Items cannot be stored before they happen ...
668         if ($arr['created'] > datetime_convert()) {
669                 $arr['created'] = datetime_convert();
670         }
671
672         // We haven't invented time travel by now.
673         if ($arr['edited'] > datetime_convert()) {
674                 $arr['edited'] = datetime_convert();
675         }
676
677         if (($arr['author-link'] == "") && ($arr['owner-link'] == "")) {
678                 logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
679         }
680
681         if ($arr['plink'] == "") {
682                 $arr['plink'] = System::baseUrl() . '/display/' . urlencode($arr['guid']);
683         }
684
685         if ($arr['network'] == "") {
686                 $r = q("SELECT `network` FROM `contact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
687                         dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
688                         dbesc(normalise_link($arr['author-link'])),
689                         intval($arr['uid'])
690                 );
691
692                 if (!DBM::is_result($r))
693                         $r = q("SELECT `network` FROM `gcontact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' LIMIT 1",
694                                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
695                                 dbesc(normalise_link($arr['author-link']))
696                         );
697
698                 if (!DBM::is_result($r)) {
699                         $r = q("SELECT `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
700                                 intval($arr['contact-id']),
701                                 intval($arr['uid'])
702                         );
703                 }
704
705                 if (DBM::is_result($r)) {
706                         $arr['network'] = $r[0]["network"];
707                 }
708
709                 // Fallback to friendica (why is it empty in some cases?)
710                 if ($arr['network'] == "") {
711                         $arr['network'] = NETWORK_DFRN;
712                 }
713
714                 logger("item_store: Set network to " . $arr["network"] . " for " . $arr["uri"], LOGGER_DEBUG);
715         }
716
717         // The contact-id should be set before "item_store" was called - but there seems to be some issues
718         if ($arr["contact-id"] == 0) {
719                 /*
720                  * First we are looking for a suitable contact that matches with the author of the post
721                  * This is done only for comments (See below explanation at "gcontact-id")
722                  */
723                 if ($arr['parent-uri'] != $arr['uri']) {
724                         $arr["contact-id"] = get_contact($arr['author-link'], $uid);
725                 }
726
727                 // If not present then maybe the owner was found
728                 if ($arr["contact-id"] == 0) {
729                         $arr["contact-id"] = get_contact($arr['owner-link'], $uid);
730                 }
731
732                 // Still missing? Then use the "self" contact of the current user
733                 if ($arr["contact-id"] == 0) {
734                         $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid` = %d", intval($uid));
735
736                         if (DBM::is_result($r)) {
737                                 $arr["contact-id"] = $r[0]["id"];
738                         }
739                 }
740
741                 logger("Contact-id was missing for post ".$arr["guid"]." from user id ".$uid." - now set to ".$arr["contact-id"], LOGGER_DEBUG);
742         }
743
744         if ($arr["gcontact-id"] == 0) {
745                 /*
746                  * The gcontact should mostly behave like the contact. But is is supposed to be global for the system.
747                  * This means that wall posts, repeated posts, etc. should have the gcontact id of the owner.
748                  * On comments the author is the better choice.
749                  */
750                 if ($arr['parent-uri'] === $arr['uri']) {
751                         $arr["gcontact-id"] = get_gcontact_id(array("url" => $arr['owner-link'], "network" => $arr['network'],
752                                                                  "photo" => $arr['owner-avatar'], "name" => $arr['owner-name']));
753                 } else {
754                         $arr["gcontact-id"] = get_gcontact_id(array("url" => $arr['author-link'], "network" => $arr['network'],
755                                                                  "photo" => $arr['author-avatar'], "name" => $arr['author-name']));
756                 }
757         }
758
759         if ($arr["author-id"] == 0) {
760                 $arr["author-id"] = get_contact($arr["author-link"], 0);
761         }
762
763         if (blockedContact($arr["author-id"])) {
764                 logger('Contact '.$arr["author-id"].' is blocked, item '.$arr["uri"].' will not be stored');
765                 return 0;
766         }
767
768         if ($arr["owner-id"] == 0) {
769                 $arr["owner-id"] = get_contact($arr["owner-link"], 0);
770         }
771
772         if (blockedContact($arr["owner-id"])) {
773                 logger('Contact '.$arr["owner-id"].' is blocked, item '.$arr["uri"].' will not be stored');
774                 return 0;
775         }
776
777         if ($arr['guid'] != "") {
778                 // Checking if there is already an item with the same guid
779                 logger('checking for an item for user '.$arr['uid'].' on network '.$arr['network'].' with the guid '.$arr['guid'], LOGGER_DEBUG);
780                 $r = q("SELECT `guid` FROM `item` WHERE `guid` = '%s' AND `network` = '%s' AND `uid` = '%d' LIMIT 1",
781                         dbesc($arr['guid']), dbesc($arr['network']), intval($arr['uid']));
782
783                 if (DBM::is_result($r)) {
784                         logger('found item with guid '.$arr['guid'].' for user '.$arr['uid'].' on network '.$arr['network'], LOGGER_DEBUG);
785                         return 0;
786                 }
787         }
788
789         // Check for hashtags in the body and repair or add hashtag links
790         item_body_set_hashtags($arr);
791
792         $arr['thr-parent'] = $arr['parent-uri'];
793
794         if ($arr['parent-uri'] === $arr['uri']) {
795                 $parent_id = 0;
796                 $parent_deleted = 0;
797                 $allow_cid = $arr['allow_cid'];
798                 $allow_gid = $arr['allow_gid'];
799                 $deny_cid  = $arr['deny_cid'];
800                 $deny_gid  = $arr['deny_gid'];
801                 $notify_type = 'wall-new';
802         } else {
803
804                 // find the parent and snarf the item id and ACLs
805                 // and anything else we need to inherit
806
807                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
808                         dbesc($arr['parent-uri']),
809                         intval($arr['uid'])
810                 );
811
812                 if (DBM::is_result($r)) {
813
814                         // is the new message multi-level threaded?
815                         // even though we don't support it now, preserve the info
816                         // and re-attach to the conversation parent.
817
818                         if ($r[0]['uri'] != $r[0]['parent-uri']) {
819                                 $arr['parent-uri'] = $r[0]['parent-uri'];
820                                 $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
821                                         ORDER BY `id` ASC LIMIT 1",
822                                         dbesc($r[0]['parent-uri']),
823                                         dbesc($r[0]['parent-uri']),
824                                         intval($arr['uid'])
825                                 );
826
827                                 if (DBM::is_result($z)) {
828                                         $r = $z;
829                                 }
830                         }
831
832                         $parent_id      = $r[0]['id'];
833                         $parent_deleted = $r[0]['deleted'];
834                         $allow_cid      = $r[0]['allow_cid'];
835                         $allow_gid      = $r[0]['allow_gid'];
836                         $deny_cid       = $r[0]['deny_cid'];
837                         $deny_gid       = $r[0]['deny_gid'];
838                         $arr['wall']    = $r[0]['wall'];
839                         $notify_type    = 'comment-new';
840
841                         /*
842                          * If the parent is private, force privacy for the entire conversation
843                          * This differs from the above settings as it subtly allows comments from
844                          * email correspondents to be private even if the overall thread is not.
845                          */
846                         if ($r[0]['private']) {
847                                 $arr['private'] = $r[0]['private'];
848                         }
849
850                         /*
851                          * Edge case. We host a public forum that was originally posted to privately.
852                          * The original author commented, but as this is a comment, the permissions
853                          * weren't fixed up so it will still show the comment as private unless we fix it here.
854                          */
855                         if ((intval($r[0]['forum_mode']) == 1) && $r[0]['private']) {
856                                 $arr['private'] = 0;
857                         }
858
859                         // If its a post from myself then tag the thread as "mention"
860                         logger("item_store: Checking if parent ".$parent_id." has to be tagged as mention for user ".$arr['uid'], LOGGER_DEBUG);
861                         $u = q("SELECT `nickname` FROM `user` WHERE `uid` = %d", intval($arr['uid']));
862                         if (DBM::is_result($u)) {
863                                 $a = get_app();
864                                 $self = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
865                                 logger("item_store: 'myself' is ".$self." for parent ".$parent_id." checking against ".$arr['author-link']." and ".$arr['owner-link'], LOGGER_DEBUG);
866                                 if ((normalise_link($arr['author-link']) == $self) || (normalise_link($arr['owner-link']) == $self)) {
867                                         dba::update('thread', array('mention' => true), array('iid' => $parent_id));
868                                         logger("item_store: tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
869                                 }
870                         }
871                 } else {
872                         /*
873                          * Allow one to see reply tweets from status.net even when
874                          * we don't have or can't see the original post.
875                          */
876                         if ($force_parent) {
877                                 logger('item_store: $force_parent=true, reply converted to top-level post.');
878                                 $parent_id = 0;
879                                 $arr['parent-uri'] = $arr['uri'];
880                                 $arr['gravity'] = 0;
881                         } else {
882                                 logger('item_store: item parent '.$arr['parent-uri'].' for '.$arr['uid'].' was not found - ignoring item');
883                                 return 0;
884                         }
885
886                         $parent_deleted = 0;
887                 }
888         }
889
890         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `network` IN ('%s', '%s') AND `uid` = %d LIMIT 1",
891                 dbesc($arr['uri']),
892                 dbesc($arr['network']),
893                 dbesc(NETWORK_DFRN),
894                 intval($arr['uid'])
895         );
896         if (DBM::is_result($r)) {
897                 logger('duplicated item with the same uri found. '.print_r($arr,true));
898                 return 0;
899         }
900
901         // On Friendica and Diaspora the GUID is unique
902         if (in_array($arr['network'], array(NETWORK_DFRN, NETWORK_DIASPORA))) {
903                 $r = q("SELECT `id` FROM `item` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
904                         dbesc($arr['guid']),
905                         intval($arr['uid'])
906                 );
907                 if (DBM::is_result($r)) {
908                         logger('duplicated item with the same guid found. '.print_r($arr,true));
909                         return 0;
910                 }
911         } else {
912                 // Check for an existing post with the same content. There seems to be a problem with OStatus.
913                 $r = q("SELECT `id` FROM `item` WHERE `body` = '%s' AND `network` = '%s' AND `created` = '%s' AND `contact-id` = %d AND `uid` = %d LIMIT 1",
914                         dbesc($arr['body']),
915                         dbesc($arr['network']),
916                         dbesc($arr['created']),
917                         intval($arr['contact-id']),
918                         intval($arr['uid'])
919                 );
920                 if (DBM::is_result($r)) {
921                         logger('duplicated item with the same body found. '.print_r($arr,true));
922                         return 0;
923                 }
924         }
925
926         // Is this item available in the global items (with uid=0)?
927         if ($arr["uid"] == 0) {
928                 $arr["global"] = true;
929
930                 // Set the global flag on all items if this was a global item entry
931                 dba::update('item', array('global' => true), array('uri' => $arr["uri"]));
932         } else {
933                 $isglobal = q("SELECT `global` FROM `item` WHERE `uid` = 0 AND `uri` = '%s'", dbesc($arr["uri"]));
934
935                 $arr["global"] = (DBM::is_result($isglobal) && count($isglobal) > 0);
936         }
937
938         // ACL settings
939         if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
940                 $private = 1;
941         } else {
942                 $private = $arr['private'];
943         }
944
945         $arr["allow_cid"] = $allow_cid;
946         $arr["allow_gid"] = $allow_gid;
947         $arr["deny_cid"] = $deny_cid;
948         $arr["deny_gid"] = $deny_gid;
949         $arr["private"] = $private;
950         $arr["deleted"] = $parent_deleted;
951
952         // Fill the cache field
953         put_item_in_cache($arr);
954
955         if ($notify) {
956                 call_hooks('post_local', $arr);
957         } else {
958                 call_hooks('post_remote', $arr);
959         }
960
961         // This array field is used to trigger some automatic reactions
962         // It is mainly used in the "post_local" hook.
963         unset($arr['api_source']);
964
965         if (x($arr, 'cancel')) {
966                 logger('item_store: post cancelled by plugin.');
967                 return 0;
968         }
969
970         /*
971          * Check for already added items.
972          * There is a timing issue here that sometimes creates double postings.
973          * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
974          */
975         if ($arr["uid"] == 0) {
976                 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = 0 LIMIT 1", dbesc(trim($arr['uri'])));
977                 if (DBM::is_result($r)) {
978                         logger('Global item already stored. URI: '.$arr['uri'].' on network '.$arr['network'], LOGGER_DEBUG);
979                         return 0;
980                 }
981         }
982
983         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
984
985         dba::transaction();
986         $r = dba::insert('item', $arr);
987
988         // When the item was successfully stored we fetch the ID of the item.
989         if (DBM::is_result($r)) {
990                 $current_post = dba::lastInsertId();
991         } else {
992                 // This can happen - for example - if there are locking timeouts.
993                 dba::rollback();
994
995                 // Store the data into a spool file so that we can try again later.
996
997                 // At first we restore the Diaspora signature that we removed above.
998                 if (isset($encoded_signature)) {
999                         $arr['dsprsig'] = $encoded_signature;
1000                 }
1001
1002                 // Now we store the data in the spool directory
1003                 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1004                 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1005
1006                 $spoolpath = get_spoolpath();
1007                 if ($spoolpath != "") {
1008                         $spool = $spoolpath.'/'.$file;
1009                         file_put_contents($spool, json_encode($arr));
1010                         logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1011                 }
1012                 return 0;
1013         }
1014
1015         if ($current_post == 0) {
1016                 // This is one of these error messages that never should occur.
1017                 logger("couldn't find created item - we better quit now.");
1018                 dba::rollback();
1019                 return 0;
1020         }
1021
1022         // How much entries have we created?
1023         // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1024         $r = q("SELECT COUNT(*) AS `entries` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s'",
1025                 dbesc($arr['uri']),
1026                 intval($arr['uid']),
1027                 dbesc($arr['network'])
1028         );
1029
1030         if (!DBM::is_result($r)) {
1031                 // This shouldn't happen, since COUNT always works when the database connection is there.
1032                 logger("We couldn't count the stored entries. Very strange ...");
1033                 dba::rollback();
1034                 return 0;
1035         }
1036
1037         if ($r[0]["entries"] > 1) {
1038                 // There are duplicates. We delete our just created entry.
1039                 logger('Duplicated post occurred. uri = ' . $arr['uri'] . ' uid = ' . $arr['uid']);
1040
1041                 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1042                 dba::delete('item', array('id' => $current_post));
1043                 dba::commit();
1044                 return 0;
1045         } elseif ($r[0]["entries"] == 0) {
1046                 // This really should never happen since we quit earlier if there were problems.
1047                 logger("Something is terribly wrong. We haven't found our created entry.");
1048                 dba::rollback();
1049                 return 0;
1050         }
1051
1052         logger('item_store: created item '.$current_post);
1053         item_set_last_item($arr);
1054
1055         if (!$parent_id || ($arr['parent-uri'] === $arr['uri'])) {
1056                 $parent_id = $current_post;
1057         }
1058
1059         // Set parent id
1060         $r = dba::update('item', array('parent' => $parent_id), array('id' => $current_post));
1061
1062         $arr['id'] = $current_post;
1063         $arr['parent'] = $parent_id;
1064
1065         // update the commented timestamp on the parent
1066         // Only update "commented" if it is really a comment
1067         if (($arr['verb'] == ACTIVITY_POST) || !Config::get("system", "like_no_comment")) {
1068                 dba::update('item', array('commented' => datetime_convert(), 'changed' => datetime_convert()), array('id' => $parent_id));
1069         } else {
1070                 dba::update('item', array('changed' => datetime_convert()), array('id' => $parent_id));
1071         }
1072
1073         if ($dsprsig) {
1074
1075                 /*
1076                  * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1077                  * We can check for this condition when we decode and encode the stuff again.
1078                  */
1079                 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1080                         $dsprsig->signature = base64_decode($dsprsig->signature);
1081                         logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1082                 }
1083
1084                 dba::insert('sign', array('iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1085                                         'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer));
1086         }
1087
1088         $deleted = tag_deliver($arr['uid'], $current_post);
1089
1090         /*
1091          * current post can be deleted if is for a community page and no mention are
1092          * in it.
1093          */
1094         if (!$deleted && !$dontcache) {
1095
1096                 $r = q('SELECT * FROM `item` WHERE `id` = %d', intval($current_post));
1097                 if ((DBM::is_result($r)) && (count($r) == 1)) {
1098                         if ($notify) {
1099                                 call_hooks('post_local_end', $r[0]);
1100                         } else {
1101                                 call_hooks('post_remote_end', $r[0]);
1102                         }
1103                 } else {
1104                         logger('item_store: new item not found in DB, id ' . $current_post);
1105                 }
1106         }
1107
1108         if ($arr['parent-uri'] === $arr['uri']) {
1109                 add_thread($current_post);
1110         } else {
1111                 update_thread($parent_id);
1112         }
1113
1114         dba::commit();
1115
1116         /*
1117          * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1118          * This is not perfect - but a workable solution until we found the reason for the problem.
1119          */
1120         create_tags_from_item($current_post);
1121         create_files_from_item($current_post);
1122
1123         /*
1124          * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
1125          * It is done after the transaction to avoid dead locks.
1126          */
1127         if ($arr['last-child']) {
1128                 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
1129                         dbesc($arr['uri']),
1130                         intval($arr['uid']),
1131                         intval($current_post)
1132                 );
1133         }
1134
1135         if ($arr['parent-uri'] === $arr['uri']) {
1136                 add_shadow_thread($current_post);
1137         } else {
1138                 add_shadow_entry($current_post);
1139         }
1140
1141         check_item_notification($current_post, $uid);
1142
1143         if ($notify) {
1144                 Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "notifier", $notify_type, $current_post);
1145         }
1146
1147         return $current_post;
1148 }
1149
1150 /**
1151  * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1152  *
1153  * This can be used to filter for inactive contacts.
1154  * Only do this for public postings to avoid privacy problems, since poco data is public.
1155  * Don't set this value if it isn't from the owner (could be an author that we don't know)
1156  *
1157  * @param array $arr Contains the just posted item record
1158  */
1159 function item_set_last_item($arr) {
1160
1161         $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
1162
1163         // Is it a forum? Then we don't care about the rules from above
1164         if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
1165                 $isforum = q("SELECT `forum` FROM `contact` WHERE `id` = %d AND `forum`",
1166                                 intval($arr['contact-id']));
1167                 if (DBM::is_result($isforum)) {
1168                         $update = true;
1169                 }
1170         }
1171
1172         if ($update) {
1173                 dba::update('contact', array('success_update' => $arr['received'], 'last-item' => $arr['received']),
1174                         array('id' => $arr['contact-id']));
1175         }
1176         // Now do the same for the system wide contacts with uid=0
1177         if (!$arr['private']) {
1178                 dba::update('contact', array('success_update' => $arr['received'], 'last-item' => $arr['received']),
1179                         array('id' => $arr['owner-id']));
1180
1181                 if ($arr['owner-id'] != $arr['author-id']) {
1182                         dba::update('contact', array('success_update' => $arr['received'], 'last-item' => $arr['received']),
1183                                 array('id' => $arr['author-id']));
1184                 }
1185         }
1186 }
1187
1188 function item_body_set_hashtags(&$item) {
1189
1190         $tags = get_tags($item["body"]);
1191
1192         // No hashtags?
1193         if (!count($tags)) {
1194                 return false;
1195         }
1196
1197         // This sorting is important when there are hashtags that are part of other hashtags
1198         // Otherwise there could be problems with hashtags like #test and #test2
1199         rsort($tags);
1200
1201         $a = get_app();
1202
1203         $URLSearchString = "^\[\]";
1204
1205         // All hashtags should point to the home server if "local_tags" is activated
1206         if (Config::get('system', 'local_tags')) {
1207                 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1208                                 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
1209
1210                 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1211                                 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
1212         }
1213
1214         // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1215         $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1216                 function ($match) {
1217                         return ("[url=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/url]");
1218                 }, $item["body"]);
1219
1220         $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1221                 function ($match) {
1222                         return ("[bookmark=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/bookmark]");
1223                 }, $item["body"]);
1224
1225         $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1226                 function ($match) {
1227                         return ("[attachment " . str_replace("#", "&num;", $match[1]) . "]" . $match[2] . "[/attachment]");
1228                 }, $item["body"]);
1229
1230         // Repair recursive urls
1231         $item["body"] = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1232                         "&num;$2", $item["body"]);
1233
1234         foreach ($tags as $tag) {
1235                 if ((strpos($tag, '#') !== 0) || (strpos($tag, '[url='))) {
1236                         continue;
1237                 }
1238
1239                 $basetag = str_replace('_',' ',substr($tag,1));
1240
1241                 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1242
1243                 $item["body"] = str_replace($tag, $newtag, $item["body"]);
1244
1245                 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1246                         if (strlen($item["tag"])) {
1247                                 $item["tag"] = ','.$item["tag"];
1248                         }
1249                         $item["tag"] = $newtag.$item["tag"];
1250                 }
1251         }
1252
1253         // Convert back the masked hashtags
1254         $item["body"] = str_replace("&num;", "#", $item["body"]);
1255 }
1256
1257 function get_item_guid($id) {
1258         $r = q("SELECT `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($id));
1259         if (DBM::is_result($r)) {
1260                 return $r[0]["guid"];
1261         } else {
1262                 /// @TODO This else-block can be elimited again
1263                 return "";
1264         }
1265 }
1266
1267 function get_item_id($guid, $uid = 0) {
1268
1269         $nick = "";
1270         $id = 0;
1271
1272         if ($uid == 0) {
1273                 $uid == local_user();
1274         }
1275
1276         // Does the given user have this item?
1277         if ($uid) {
1278                 $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1279                         WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 AND `item`.`moderated` = 0
1280                                 AND `item`.`guid` = '%s' AND `item`.`uid` = %d", dbesc($guid), intval($uid));
1281                 if (DBM::is_result($r)) {
1282                         $id = $r[0]["id"];
1283                         $nick = $r[0]["nickname"];
1284                 }
1285         }
1286
1287         // Or is it anywhere on the server?
1288         if ($nick == "") {
1289                 $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1290                         WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 AND `item`.`moderated` = 0
1291                                 AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
1292                                 AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
1293                                 AND `item`.`private` = 0 AND `item`.`wall` = 1
1294                                 AND `item`.`guid` = '%s'", dbesc($guid));
1295                 if (DBM::is_result($r)) {
1296                         $id = $r[0]["id"];
1297                         $nick = $r[0]["nickname"];
1298                 }
1299         }
1300         return array("nick" => $nick, "id" => $id);
1301 }
1302
1303 // return - test
1304 function get_item_contact($item, $contacts) {
1305         if (! count($contacts) || (! is_array($item))) {
1306                 return false;
1307         }
1308         foreach ($contacts as $contact) {
1309                 if ($contact['id'] == $item['contact-id']) {
1310                         return $contact;
1311                         break; // NOTREACHED
1312                 }
1313         }
1314         return false;
1315 }
1316
1317 /**
1318  * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1319  * @param int $uid
1320  * @param int $item_id
1321  * @return bool true if item was deleted, else false
1322  */
1323 function tag_deliver($uid, $item_id) {
1324
1325         $a = get_app();
1326
1327         $mention = false;
1328
1329         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1330                 intval($uid)
1331         );
1332
1333         if (! DBM::is_result($u)) {
1334                 return;
1335         }
1336
1337         $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1338         $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1339
1340
1341         $i = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1342                 intval($item_id),
1343                 intval($uid)
1344         );
1345         if (! DBM::is_result($i)) {
1346                 return;
1347         }
1348
1349         $item = $i[0];
1350
1351         $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
1352
1353         /*
1354          * Diaspora uses their own hardwired link URL in @-tags
1355          * instead of the one we supply with webfinger
1356          */
1357         $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
1358
1359         $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1360         if ($cnt) {
1361                 foreach ($matches as $mtch) {
1362                         if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1363                                 $mention = true;
1364                                 logger('tag_deliver: mention found: ' . $mtch[2]);
1365                         }
1366                 }
1367         }
1368
1369         if (! $mention) {
1370                 if (($community_page || $prvgroup) &&
1371                           (!$item['wall']) && (!$item['origin']) && ($item['id'] == $item['parent'])) {
1372                         // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1373                         // delete it!
1374                         logger("tag_deliver: no-mention top-level post to communuty or private group. delete.");
1375                         dba::delete('item', array('id' => $item_id));
1376                         return true;
1377                 }
1378                 return;
1379         }
1380
1381         $arr = array('item' => $item, 'user' => $u[0], 'contact' => $r[0]);
1382
1383         call_hooks('tagged', $arr);
1384
1385         if ((! $community_page) && (! $prvgroup)) {
1386                 return;
1387         }
1388
1389         /*
1390          * tgroup delivery - setup a second delivery chain
1391          * prevent delivery looping - only proceed
1392          * if the message originated elsewhere and is a top-level post
1393          */
1394         if (($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent'])) {
1395                 return;
1396         }
1397
1398         // now change this copy of the post to a forum head message and deliver to all the tgroup members
1399         $c = q("SELECT `name`, `url`, `thumb` FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1400                 intval($u[0]['uid'])
1401         );
1402         if (! DBM::is_result($c)) {
1403                 return;
1404         }
1405
1406         // also reset all the privacy bits to the forum default permissions
1407
1408         $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1409
1410         $forum_mode = (($prvgroup) ? 2 : 1);
1411
1412         q("UPDATE `item` SET `wall` = 1, `origin` = 1, `forum_mode` = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1413                 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'  WHERE `id` = %d",
1414                 intval($forum_mode),
1415                 dbesc($c[0]['name']),
1416                 dbesc($c[0]['url']),
1417                 dbesc($c[0]['thumb']),
1418                 intval($private),
1419                 dbesc($u[0]['allow_cid']),
1420                 dbesc($u[0]['allow_gid']),
1421                 dbesc($u[0]['deny_cid']),
1422                 dbesc($u[0]['deny_gid']),
1423                 intval($item_id)
1424         );
1425         update_thread($item_id);
1426
1427         Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), 'notifier', 'tgroup', $item_id);
1428
1429 }
1430
1431
1432
1433 function tgroup_check($uid, $item) {
1434
1435         $mention = false;
1436
1437         // check that the message originated elsewhere and is a top-level post
1438
1439         if (($item['wall']) || ($item['origin']) || ($item['uri'] != $item['parent-uri'])) {
1440                 return false;
1441         }
1442
1443         /// @TODO Encapsulate this or find it encapsulated and replace all occurrances
1444         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1445                 intval($uid)
1446         );
1447         if (! DBM::is_result($u)) {
1448                 return false;
1449         }
1450
1451         $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1452         $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1453
1454         $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
1455
1456         /*
1457          * Diaspora uses their own hardwired link URL in @-tags
1458          * instead of the one we supply with webfinger
1459          */
1460         $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
1461
1462         $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1463         if ($cnt) {
1464                 foreach ($matches as $mtch) {
1465                         if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1466                                 $mention = true;
1467                                 logger('tgroup_check: mention found: ' . $mtch[2]);
1468                         }
1469                 }
1470         }
1471
1472         if (! $mention) {
1473                 return false;
1474         }
1475
1476         /// @TODO Combine both return statements into one
1477         return (($community_page) || ($prvgroup));
1478 }
1479
1480 /**
1481  * This function returns true if $update has an edited timestamp newer
1482  * than $existing, i.e. $update contains new data which should override
1483  * what's already there.  If there is no timestamp yet, the update is
1484  * assumed to be newer.  If the update has no timestamp, the existing
1485  * item is assumed to be up-to-date.  If the timestamps are equal it
1486  * assumes the update has been seen before and should be ignored.
1487  *
1488  * @todo fix type-hints (both array)
1489  */
1490 function edited_timestamp_is_newer($existing, $update) {
1491         if (!x($existing, 'edited') || !$existing['edited']) {
1492                 return true;
1493         }
1494         if (!x($update, 'edited') || !$update['edited']) {
1495                 return false;
1496         }
1497
1498         $existing_edited = datetime_convert('UTC', 'UTC', $existing['edited']);
1499         $update_edited = datetime_convert('UTC', 'UTC', $update['edited']);
1500         return (strcmp($existing_edited, $update_edited) < 0);
1501 }
1502
1503 /**
1504  *
1505  * consume_feed - process atom feed and update anything/everything we might need to update
1506  *
1507  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1508  *
1509  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1510  *             It is this person's stuff that is going to be updated.
1511  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1512  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1513  *             have a contact record.
1514  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1515  *        might not) try and subscribe to it.
1516  * $datedir sorts in reverse order
1517  * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1518  *      imported prior to its children being seen in the stream unless we are certain
1519  *      of how the feed is arranged/ordered.
1520  * With $pass = 1, we only pull parent items out of the stream.
1521  * With $pass = 2, we only pull children (comments/likes).
1522  *
1523  * So running this twice, first with pass 1 and then with pass 2 will do the right
1524  * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1525  * model where comments can have sub-threads. That would require some massive sorting
1526  * to get all the feed items into a mostly linear ordering, and might still require
1527  * recursion.
1528  *
1529  * @todo find proper type-hints
1530  */
1531 function consume_feed($xml, $importer, &$contact, &$hub, $datedir = 0, $pass = 0) {
1532         if ($contact['network'] === NETWORK_OSTATUS) {
1533                 if ($pass < 2) {
1534                         // Test - remove before flight
1535                         //$tempfile = tempnam(get_temppath(), "ostatus2");
1536                         //file_put_contents($tempfile, $xml);
1537                         logger("Consume OStatus messages ", LOGGER_DEBUG);
1538                         ostatus::import($xml, $importer, $contact, $hub);
1539                 }
1540                 return;
1541         }
1542
1543         if ($contact['network'] === NETWORK_FEED) {
1544                 if ($pass < 2) {
1545                         logger("Consume feeds", LOGGER_DEBUG);
1546                         feed_import($xml, $importer, $contact, $hub);
1547                 }
1548                 return;
1549         }
1550
1551         if ($contact['network'] === NETWORK_DFRN) {
1552                 logger("Consume DFRN messages", LOGGER_DEBUG);
1553
1554                 $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
1555                                         `contact`.`pubkey` AS `cpubkey`,
1556                                         `contact`.`prvkey` AS `cprvkey`,
1557                                         `contact`.`thumb` AS `thumb`,
1558                                         `contact`.`url` as `url`,
1559                                         `contact`.`name` as `senderName`,
1560                                         `user`.*
1561                         FROM `contact`
1562                         LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
1563                         WHERE `contact`.`id` = %d AND `user`.`uid` = %d",
1564                         dbesc($contact["id"]), dbesc($importer["uid"])
1565                 );
1566                 if (DBM::is_result($r)) {
1567                         logger("Now import the DFRN feed");
1568                         DFRN::import($xml, $r[0], true);
1569                         return;
1570                 }
1571         }
1572 }
1573
1574 /// @TODO type-hint is array
1575 function item_is_remote_self($contact, &$datarray) {
1576         $a = get_app();
1577
1578         if (!$contact['remote_self']) {
1579                 return false;
1580         }
1581
1582         // Prevent the forwarding of posts that are forwarded
1583         if ($datarray["extid"] == NETWORK_DFRN) {
1584                 return false;
1585         }
1586
1587         // Prevent to forward already forwarded posts
1588         if ($datarray["app"] == $a->get_hostname()) {
1589                 return false;
1590         }
1591
1592         // Only forward posts
1593         if ($datarray["verb"] != ACTIVITY_POST) {
1594                 return false;
1595         }
1596
1597         if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
1598                 return false;
1599         }
1600
1601         $datarray2 = $datarray;
1602         logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1603         if ($contact['remote_self'] == 2) {
1604                 $r = q("SELECT `id`,`url`,`name`,`thumb` FROM `contact` WHERE `uid` = %d AND `self`",
1605                         intval($contact['uid']));
1606                 if (DBM::is_result($r)) {
1607                         $datarray['contact-id'] = $r[0]["id"];
1608
1609                         $datarray['owner-name'] = $r[0]["name"];
1610                         $datarray['owner-link'] = $r[0]["url"];
1611                         $datarray['owner-avatar'] = $r[0]["thumb"];
1612
1613                         $datarray['author-name']   = $datarray['owner-name'];
1614                         $datarray['author-link']   = $datarray['owner-link'];
1615                         $datarray['author-avatar'] = $datarray['owner-avatar'];
1616
1617                         unset($datarray['created']);
1618                         unset($datarray['edited']);
1619                 }
1620
1621                 if ($contact['network'] != NETWORK_FEED) {
1622                         $datarray["guid"] = get_guid(32);
1623                         unset($datarray["plink"]);
1624                         $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
1625                         $datarray["parent-uri"] = $datarray["uri"];
1626                         $datarray["extid"] = $contact['network'];
1627                         $urlpart = parse_url($datarray2['author-link']);
1628                         $datarray["app"] = $urlpart["host"];
1629                 } else {
1630                         $datarray['private'] = 0;
1631                 }
1632         }
1633
1634         if ($contact['network'] != NETWORK_FEED) {
1635                 // Store the original post
1636                 $r = item_store($datarray2, false, false);
1637                 logger('remote-self post original item - Contact '.$contact['url'].' return '.$r.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1638         } else {
1639                 $datarray["app"] = "Feed";
1640         }
1641
1642         // Trigger automatic reactions for addons
1643         $datarray['api_source'] = true;
1644
1645         // We have to tell the hooks who we are - this really should be improved
1646         $_SESSION["authenticated"] = true;
1647         $_SESSION["uid"] = $contact['uid'];
1648
1649         return true;
1650 }
1651
1652 /// @TODO find proper type-hints
1653 function new_follower($importer, $contact, $datarray, $item, $sharing = false) {
1654         $url = notags(trim($datarray['author-link']));
1655         $name = notags(trim($datarray['author-name']));
1656         $photo = notags(trim($datarray['author-avatar']));
1657
1658         if (is_object($item)) {
1659                 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1660                 if ($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data']) {
1661                         $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1662                 }
1663         } else {
1664                 $nick = $item;
1665         }
1666
1667         if (is_array($contact)) {
1668                 if (($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
1669                         || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
1670                         $r = dba::update('contact', array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1671                                         array('id' => $contact['id'], 'uid' => $importer['uid']));
1672                 }
1673                 // send email notification to owner?
1674         } else {
1675
1676                 // create contact record
1677
1678                 $r = q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1679                         `blocked`, `readonly`, `pending`, `writable`)
1680                         VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1681                         intval($importer['uid']),
1682                         dbesc(datetime_convert()),
1683                         dbesc($url),
1684                         dbesc(normalise_link($url)),
1685                         dbesc($name),
1686                         dbesc($nick),
1687                         dbesc($photo),
1688                         dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
1689                         intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
1690                 );
1691                 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
1692                                 intval($importer['uid']),
1693                                 dbesc($url)
1694                 );
1695                 if (DBM::is_result($r)) {
1696                         $contact_record = $r[0];
1697                         update_contact_avatar($photo, $importer["uid"], $contact_record["id"], true);
1698                 }
1699
1700                 /// @TODO Encapsulate this into a function/method
1701                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1702                         intval($importer['uid'])
1703                 );
1704
1705                 if (DBM::is_result($r) && !in_array($r[0]['page-flags'], array(PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY))) {
1706
1707                         // create notification
1708                         $hash = random_string();
1709
1710                         if (is_array($contact_record)) {
1711                                 dba::insert('intro', array('uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1712                                                         'blocked' => false, 'knowyou' => false,
1713                                                         'hash' => $hash, 'datetime' => datetime_convert()));
1714                         }
1715
1716                         $def_gid = get_default_group($importer['uid'], $contact_record["network"]);
1717
1718                         if (intval($def_gid)) {
1719                                 group_add_member($importer['uid'], '', $contact_record['id'], $def_gid);
1720                         }
1721
1722                         if (($r[0]['notify-flags'] & NOTIFY_INTRO) &&
1723                                 in_array($r[0]['page-flags'], array(PAGE_NORMAL))) {
1724
1725                                 notification(array(
1726                                         'type'         => NOTIFY_INTRO,
1727                                         'notify_flags' => $r[0]['notify-flags'],
1728                                         'language'     => $r[0]['language'],
1729                                         'to_name'      => $r[0]['username'],
1730                                         'to_email'     => $r[0]['email'],
1731                                         'uid'          => $r[0]['uid'],
1732                                         'link'             => System::baseUrl() . '/notifications/intro',
1733                                         'source_name'  => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : t('[Name Withheld]')),
1734                                         'source_link'  => $contact_record['url'],
1735                                         'source_photo' => $contact_record['photo'],
1736                                         'verb'         => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1737                                         'otype'        => 'intro'
1738                                 ));
1739
1740                         }
1741                 } elseif (DBM::is_result($r) && in_array($r[0]['page-flags'], array(PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY))) {
1742                         $r = q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1",
1743                                         intval($importer['uid']),
1744                                         dbesc($url)
1745                         );
1746                 }
1747
1748         }
1749 }
1750
1751 function lose_follower($importer, $contact, array $datarray = array(), $item = "") {
1752
1753         if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
1754                 dba::update('contact', array('rel' => CONTACT_IS_SHARING), array('id' => $contact['id']));
1755         } else {
1756                 contact_remove($contact['id']);
1757         }
1758 }
1759
1760 function lose_sharer($importer, $contact, array $datarray = array(), $item = "") {
1761
1762         if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
1763                 dba::update('contact', array('rel' => CONTACT_IS_FOLLOWER), array('id' => $contact['id']));
1764         } else {
1765                 contact_remove($contact['id']);
1766         }
1767 }
1768
1769 function subscribe_to_hub($url, $importer, $contact, $hubmode = 'subscribe') {
1770
1771         $a = get_app();
1772
1773         if (is_array($importer)) {
1774                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1775                         intval($importer['uid'])
1776                 );
1777         }
1778
1779         /*
1780          * Diaspora has different message-ids in feeds than they do
1781          * through the direct Diaspora protocol. If we try and use
1782          * the feed, we'll get duplicates. So don't.
1783          */
1784         if ((! DBM::is_result($r)) || $contact['network'] === NETWORK_DIASPORA) {
1785                 return;
1786         }
1787
1788         $push_url = Config::get('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1789
1790         // Use a single verify token, even if multiple hubs
1791         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1792
1793         $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1794
1795         logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: '  . $push_url . ' with verifier ' . $verify_token);
1796
1797         if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
1798                 $r = dba::update('contact', array('hub-verify' => $verify_token), array('id' => $contact['id']));
1799         }
1800
1801         post_url($url, $params);
1802
1803         logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
1804
1805         return;
1806
1807 }
1808
1809 function fix_private_photos($s, $uid, $item = null, $cid = 0) {
1810
1811         if (Config::get('system','disable_embedded')) {
1812                 return $s;
1813         }
1814
1815         $a = get_app();
1816
1817         logger('fix_private_photos: check for photos', LOGGER_DEBUG);
1818         $site = substr(System::baseUrl(),strpos(System::baseUrl(),'://'));
1819
1820         $orig_body = $s;
1821         $new_body = '';
1822
1823         $img_start = strpos($orig_body, '[img');
1824         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1825         $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1826         while ( ($img_st_close !== false) && ($img_len !== false) ) {
1827
1828                 $img_st_close++; // make it point to AFTER the closing bracket
1829                 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
1830
1831                 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
1832
1833
1834                 if (stristr($image , $site . '/photo/')) {
1835                         // Only embed locally hosted photos
1836                         $replace = false;
1837                         $i = basename($image);
1838                         $i = str_replace(array('.jpg', '.png', '.gif'),array('', '',''), $i);
1839                         $x = strpos($i, '-');
1840
1841                         if ($x) {
1842                                 $res = substr($i, $x + 1);
1843                                 $i = substr($i, 0, $x);
1844                                 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1845                                         dbesc($i),
1846                                         intval($res),
1847                                         intval($uid)
1848
1849                                 );
1850                                 if (DBM::is_result($r)) {
1851                                         /*
1852                                          * Check to see if we should replace this photo link with an embedded image
1853                                          * 1. No need to do so if the photo is public
1854                                          * 2. If there's a contact-id provided, see if they're in the access list
1855                                          *    for the photo. If so, embed it.
1856                                          * 3. Otherwise, if we have an item, see if the item permissions match the photo
1857                                          *    permissions, regardless of order but first check to see if they're an exact
1858                                          *    match to save some processing overhead.
1859                                          */
1860                                         if (has_permissions($r[0])) {
1861                                                 if ($cid) {
1862                                                         $recips = enumerate_permissions($r[0]);
1863                                                         if (in_array($cid, $recips)) {
1864                                                                 $replace = true;
1865                                                         }
1866                                                 } elseif ($item) {
1867                                                         if (compare_permissions($item, $r[0])) {
1868                                                                 $replace = true;
1869                                                         }
1870                                                 }
1871                                         }
1872                                         if ($replace) {
1873                                                 $data = $r[0]['data'];
1874                                                 $type = $r[0]['type'];
1875
1876                                                 // If a custom width and height were specified, apply before embedding
1877                                                 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
1878                                                         logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
1879
1880                                                         $width = intval($match[1]);
1881                                                         $height = intval($match[2]);
1882
1883                                                         $ph = new Photo($data, $type);
1884                                                         if ($ph->is_valid()) {
1885                                                                 $ph->scaleImage(max($width, $height));
1886                                                                 $data = $ph->imageString();
1887                                                                 $type = $ph->getType();
1888                                                         }
1889                                                 }
1890
1891                                                 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
1892                                                 $image = 'data:' . $type . ';base64,' . base64_encode($data);
1893                                                 logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
1894                                         }
1895                                 }
1896                         }
1897                 }
1898
1899                 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
1900                 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
1901                 if ($orig_body === false) {
1902                         $orig_body = '';
1903                 }
1904
1905                 $img_start = strpos($orig_body, '[img');
1906                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1907                 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1908         }
1909
1910         $new_body = $new_body . $orig_body;
1911
1912         return $new_body;
1913 }
1914
1915 /// @TODO type-hint is array
1916 function has_permissions($obj) {
1917         return (
1918                 (
1919                         x($obj, 'allow_cid')
1920                 ) || (
1921                         x($obj, 'allow_gid')
1922                 ) || (
1923                         x($obj, 'deny_cid')
1924                 ) || (
1925                         x($obj, 'deny_gid')
1926                 )
1927         );
1928 }
1929
1930 /// @TODO type-hint is array
1931 function compare_permissions($obj1, $obj2) {
1932         // first part is easy. Check that these are exactly the same.
1933         if (($obj1['allow_cid'] == $obj2['allow_cid'])
1934                 && ($obj1['allow_gid'] == $obj2['allow_gid'])
1935                 && ($obj1['deny_cid'] == $obj2['deny_cid'])
1936                 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
1937                 return true;
1938         }
1939
1940         // This is harder. Parse all the permissions and compare the resulting set.
1941         $recipients1 = enumerate_permissions($obj1);
1942         $recipients2 = enumerate_permissions($obj2);
1943         sort($recipients1);
1944         sort($recipients2);
1945
1946         /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1947         return ($recipients1 == $recipients2);
1948 }
1949
1950 // returns an array of contact-ids that are allowed to see this object
1951 /// @TODO type-hint is array
1952 function enumerate_permissions($obj) {
1953         $allow_people = expand_acl($obj['allow_cid']);
1954         $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
1955         $deny_people  = expand_acl($obj['deny_cid']);
1956         $deny_groups  = expand_groups(expand_acl($obj['deny_gid']));
1957         $recipients   = array_unique(array_merge($allow_people, $allow_groups));
1958         $deny         = array_unique(array_merge($deny_people, $deny_groups));
1959         $recipients   = array_diff($recipients, $deny);
1960         return $recipients;
1961 }
1962
1963 function item_getfeedtags($item) {
1964         $ret = array();
1965         $matches = false;
1966         $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1967         if ($cnt) {
1968                 for ($x = 0; $x < $cnt; $x ++) {
1969                         if ($matches[1][$x]) {
1970                                 $ret[$matches[2][$x]] = array('#', $matches[1][$x], $matches[2][$x]);
1971                         }
1972                 }
1973         }
1974         $matches = false;
1975         $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1976         if ($cnt) {
1977                 for ($x = 0; $x < $cnt; $x ++) {
1978                         if ($matches[1][$x]) {
1979                                 $ret[] = array('@', $matches[1][$x], $matches[2][$x]);
1980                         }
1981                 }
1982         }
1983         return $ret;
1984 }
1985
1986 function item_expire($uid, $days, $network = "", $force = false) {
1987
1988         if ((! $uid) || ($days < 1)) {
1989                 return;
1990         }
1991
1992         /*
1993          * $expire_network_only = save your own wall posts
1994          * and just expire conversations started by others
1995          */
1996         $expire_network_only = PConfig::get($uid,'expire', 'network_only');
1997         $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
1998
1999         if ($network != "") {
2000                 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
2001
2002                 /*
2003                  * There is an index "uid_network_received" but not "uid_network_created"
2004                  * This avoids the creation of another index just for one purpose.
2005                  * And it doesn't really matter wether to look at "received" or "created"
2006                  */
2007                 $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
2008         } else {
2009                 $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
2010         }
2011
2012         $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
2013                 WHERE `uid` = %d $range
2014                 AND `id` = `parent`
2015                 $sql_extra
2016                 AND `deleted` = 0",
2017                 intval($uid),
2018                 intval($days)
2019         );
2020
2021         if (! DBM::is_result($r)) {
2022                 return;
2023         }
2024
2025         $expire_items = PConfig::get($uid, 'expire', 'items');
2026         $expire_items = (($expire_items === false) ? 1 : intval($expire_items)); // default if not set: 1
2027
2028         // Forcing expiring of items - but not notes and marked items
2029         if ($force) {
2030                 $expire_items = true;
2031         }
2032
2033         $expire_notes = PConfig::get($uid, 'expire', 'notes');
2034         $expire_notes = (($expire_notes === false) ? 1 : intval($expire_notes)); // default if not set: 1
2035
2036         $expire_starred = PConfig::get($uid, 'expire', 'starred');
2037         $expire_starred = (($expire_starred === false) ? 1 : intval($expire_starred)); // default if not set: 1
2038
2039         $expire_photos = PConfig::get($uid, 'expire', 'photos');
2040         $expire_photos = (($expire_photos === false) ? 0 : intval($expire_photos)); // default if not set: 0
2041
2042         logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2043
2044         foreach ($r as $item) {
2045
2046                 // don't expire filed items
2047
2048                 if (strpos($item['file'],'[') !== false) {
2049                         continue;
2050                 }
2051
2052                 // Only expire posts, not photos and photo comments
2053
2054                 if ($expire_photos == 0 && strlen($item['resource-id'])) {
2055                         continue;
2056                 } elseif ($expire_starred == 0 && intval($item['starred'])) {
2057                         continue;
2058                 } elseif ($expire_notes == 0 && $item['type'] == 'note') {
2059                         continue;
2060                 } elseif ($expire_items == 0 && $item['type'] != 'note') {
2061                         continue;
2062                 }
2063
2064                 drop_item($item['id'], false);
2065         }
2066
2067         Worker::add(array('priority' => PRIORITY_LOW, 'dont_fork' => true), "notifier", "expire", $uid);
2068 }
2069
2070 /// @TODO type-hint is array
2071 function drop_items($items) {
2072         $uid = 0;
2073
2074         if (! local_user() && ! remote_user()) {
2075                 return;
2076         }
2077
2078         if (count($items)) {
2079                 foreach ($items as $item) {
2080                         $owner = drop_item($item,false);
2081                         if ($owner && ! $uid)
2082                                 $uid = $owner;
2083                 }
2084         }
2085
2086         // multiple threads may have been deleted, send an expire notification
2087
2088         if ($uid) {
2089                 Worker::add(array('priority' => PRIORITY_LOW, 'dont_fork' => true), "notifier", "expire", $uid);
2090         }
2091 }
2092
2093
2094 function drop_item($id, $interactive = true) {
2095
2096         $a = get_app();
2097
2098         // locate item to be deleted
2099
2100         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
2101                 intval($id)
2102         );
2103
2104         if (! DBM::is_result($r)) {
2105                 if (! $interactive) {
2106                         return 0;
2107                 }
2108                 notice( t('Item not found.') . EOL);
2109                 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
2110         }
2111
2112         $item = $r[0];
2113
2114         if ($item['deleted']) {
2115                 return 0;
2116         }
2117
2118         $owner = $item['uid'];
2119
2120         $contact_id = 0;
2121
2122         // check if logged in user is either the author or owner of this item
2123
2124         if (is_array($_SESSION['remote'])) {
2125                 foreach ($_SESSION['remote'] as $visitor) {
2126                         if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
2127                                 $contact_id = $visitor['cid'];
2128                                 break;
2129                         }
2130                 }
2131         }
2132
2133
2134         if ((local_user() == $item['uid']) || ($contact_id) || (! $interactive)) {
2135
2136                 // Check if we should do HTML-based delete confirmation
2137                 if ($_REQUEST['confirm']) {
2138                         // <form> can't take arguments in its "action" parameter
2139                         // so add any arguments as hidden inputs
2140                         $query = explode_querystring($a->query_string);
2141                         $inputs = array();
2142                         foreach ($query['args'] as $arg) {
2143                                 if (strpos($arg, 'confirm=') === false) {
2144                                         $arg_parts = explode('=', $arg);
2145                                         $inputs[] = array('name' => $arg_parts[0], 'value' => $arg_parts[1]);
2146                                 }
2147                         }
2148
2149                         return replace_macros(get_markup_template('confirm.tpl'), array(
2150                                 '$method' => 'get',
2151                                 '$message' => t('Do you really want to delete this item?'),
2152                                 '$extra_inputs' => $inputs,
2153                                 '$confirm' => t('Yes'),
2154                                 '$confirm_url' => $query['base'],
2155                                 '$confirm_name' => 'confirmed',
2156                                 '$cancel' => t('Cancel'),
2157                         ));
2158                 }
2159                 // Now check how the user responded to the confirmation query
2160                 if ($_REQUEST['canceled']) {
2161                         goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
2162                 }
2163
2164                 logger('delete item: ' . $item['id'], LOGGER_DEBUG);
2165
2166                 // delete the item
2167                 $r = dba::update('item', array('deleted' => true, 'title' => '', 'body' => '',
2168                                         'edited' => datetime_convert(), 'changed' => datetime_convert()),
2169                                 array('id' => $item['id']));
2170
2171                 create_tags_from_item($item['id']);
2172                 create_files_from_item($item['id']);
2173                 delete_thread($item['id'], $item['parent-uri']);
2174
2175                 // clean up categories and tags so they don't end up as orphans
2176
2177                 $matches = false;
2178                 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
2179                 if ($cnt) {
2180                         foreach ($matches as $mtch) {
2181                                 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
2182                         }
2183                 }
2184
2185                 $matches = false;
2186
2187                 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
2188                 if ($cnt) {
2189                         foreach ($matches as $mtch) {
2190                                 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
2191                         }
2192                 }
2193
2194                 /*
2195                  * If item is a link to a photo resource, nuke all the associated photos
2196                  * (visitors will not have photo resources)
2197                  * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
2198                  * generate a resource-id and therefore aren't intimately linked to the item.
2199                  */
2200                 if (strlen($item['resource-id'])) {
2201                         q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
2202                                 dbesc($item['resource-id']),
2203                                 intval($item['uid'])
2204                         );
2205                         // ignore the result
2206                 }
2207
2208                 // If item is a link to an event, nuke the event record.
2209                 if (intval($item['event-id'])) {
2210                         q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d",
2211                                 intval($item['event-id']),
2212                                 intval($item['uid'])
2213                         );
2214                         // ignore the result
2215                 }
2216
2217                 // If item has attachments, drop them
2218                 foreach (explode(", ", $item['attach']) as $attach) {
2219                         preg_match("|attach/(\d+)|", $attach, $matches);
2220                         q("DELETE FROM `attach` WHERE `id` = %d AND `uid` = %d",
2221                                 intval($matches[1]),
2222                                 local_user()
2223                         );
2224                         // ignore the result
2225                 }
2226
2227                 // The new code splits the queries since the mysql optimizer really has bad problems with subqueries
2228
2229                 // Creating list of parents
2230                 $r = q("SELECT `id` FROM `item` WHERE `parent` = %d AND `uid` = %d",
2231                         intval($item['id']),
2232                         intval($item['uid'])
2233                 );
2234
2235                 $parentid = "";
2236
2237                 foreach ($r as $row) {
2238                         if ($parentid != "") {
2239                                 $parentid .= ", ";
2240                         }
2241
2242                         $parentid .= $row["id"];
2243                 }
2244
2245                 // Now delete them
2246                 if ($parentid != "") {
2247                         $r = q("DELETE FROM `item_id` WHERE `iid` IN (%s)", dbesc($parentid));
2248                         $r = q("DELETE FROM `sign` WHERE `iid` IN (%s)", dbesc($parentid));
2249                 }
2250
2251                 // If it's the parent of a comment thread, kill all the kids
2252                 if ($item['uri'] == $item['parent-uri']) {
2253                         $r = dba::update('item', array('deleted' => true, 'title' => '', 'body' => '',
2254                                         'edited' => datetime_convert(), 'changed' => datetime_convert()),
2255                                 array('parent-uri' => $item['parent-uri'], 'uid' => $item['uid']));
2256
2257                         create_tags_from_itemuri($item['parent-uri'], $item['uid']);
2258                         create_files_from_itemuri($item['parent-uri'], $item['uid']);
2259                         delete_thread_uri($item['parent-uri'], $item['uid']);
2260                         // ignore the result
2261                 } else {
2262                         // ensure that last-child is set in case the comment that had it just got wiped.
2263                         dba::update('item', array('last-child' => false, 'changed' => datetime_convert()),
2264                                         array('parent-uri' => $item['parent-uri'], 'uid' => $item['uid']));
2265
2266                         // who is the last child now?
2267                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d ORDER BY `edited` DESC LIMIT 1",
2268                                 dbesc($item['parent-uri']),
2269                                 intval($item['uid'])
2270                         );
2271                         if (DBM::is_result($r)) {
2272                                 dba::update('item', array('last-child' => true), array('id' => $r[0]['id']));
2273                         }
2274                 }
2275
2276                 // send the notification upstream/downstream
2277                 // The priority depends on how the deletion is done.
2278                 $drop_id = intval($item['id']);
2279                 $priority = ($interactive ? PRIORITY_HIGH : PRIORITY_LOW);
2280
2281                 Worker::add(array('priority' => $priority, 'dont_fork' => true), "notifier", "drop", $drop_id);
2282
2283                 if (! $interactive) {
2284                         return $owner;
2285                 }
2286                 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
2287                 //NOTREACHED
2288         } else {
2289                 if (! $interactive) {
2290                         return 0;
2291                 }
2292                 notice( t('Permission denied.') . EOL);
2293                 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
2294                 //NOTREACHED
2295         }
2296
2297 }
2298
2299 /// @todo: This query seems to be really slow
2300 function first_post_date($uid, $wall = false) {
2301         $r = q("SELECT `id`, `created` FROM `item`
2302                 WHERE `uid` = %d AND `wall` = %d AND `deleted` = 0 AND `visible` = 1 AND `moderated` = 0
2303                 AND `id` = `parent`
2304                 ORDER BY `created` ASC LIMIT 1",
2305                 intval($uid),
2306                 intval($wall ? 1 : 0)
2307         );
2308         if (DBM::is_result($r)) {
2309                 // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
2310                 return substr(datetime_convert('',date_default_timezone_get(), $r[0]['created']),0,10);
2311         }
2312         return false;
2313 }
2314
2315 /* modified posted_dates() {below} to arrange the list in years */
2316 function list_post_dates($uid, $wall) {
2317         $dnow = datetime_convert('',date_default_timezone_get(), 'now','Y-m-d');
2318
2319         $dthen = first_post_date($uid, $wall);
2320         if (! $dthen) {
2321                 return array();
2322         }
2323
2324         // Set the start and end date to the beginning of the month
2325         $dnow = substr($dnow, 0, 8) . '01';
2326         $dthen = substr($dthen, 0, 8) . '01';
2327
2328         $ret = array();
2329
2330         /*
2331          * Starting with the current month, get the first and last days of every
2332          * month down to and including the month of the first post
2333          */
2334         while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
2335                 $dyear = intval(substr($dnow, 0, 4));
2336                 $dstart = substr($dnow, 0, 8) . '01';
2337                 $dend = substr($dnow, 0, 8) . get_dim(intval($dnow), intval(substr($dnow, 5)));
2338                 $start_month = datetime_convert('', '', $dstart, 'Y-m-d');
2339                 $end_month = datetime_convert('', '', $dend, 'Y-m-d');
2340                 $str = day_translate(datetime_convert('', '', $dnow, 'F'));
2341                 if (!$ret[$dyear]) {
2342                         $ret[$dyear] = array();
2343                 }
2344                 $ret[$dyear][] = array($str, $end_month, $start_month);
2345                 $dnow = datetime_convert('', '', $dnow . ' -1 month', 'Y-m-d');
2346         }
2347         return $ret;
2348 }
2349
2350 function posted_dates($uid, $wall) {
2351         $dnow = datetime_convert('', date_default_timezone_get(), 'now', 'Y-m-d');
2352
2353         $dthen = first_post_date($uid, $wall);
2354         if (! $dthen) {
2355                 return array();
2356         }
2357
2358         // Set the start and end date to the beginning of the month
2359         $dnow = substr($dnow, 0, 8) . '01';
2360         $dthen = substr($dthen, 0, 8) . '01';
2361
2362         $ret = array();
2363         /*
2364          * Starting with the current month, get the first and last days of every
2365          * month down to and including the month of the first post
2366          */
2367         while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
2368                 $dstart = substr($dnow, 0, 8) . '01';
2369                 $dend = substr($dnow, 0, 8) . get_dim(intval($dnow), intval(substr($dnow, 5)));
2370                 $start_month = datetime_convert('', '', $dstart, 'Y-m-d');
2371                 $end_month = datetime_convert('', '', $dend, 'Y-m-d');
2372                 $str = day_translate(datetime_convert('', '', $dnow, 'F Y'));
2373                 $ret[] = array($str, $end_month, $start_month);
2374                 $dnow = datetime_convert('', '', $dnow . ' -1 month', 'Y-m-d');
2375         }
2376         return $ret;
2377 }
2378
2379
2380 function posted_date_widget($url, $uid, $wall) {
2381         $o = '';
2382
2383         if (! feature_enabled($uid, 'archives')) {
2384                 return $o;
2385         }
2386
2387         // For former Facebook folks that left because of "timeline"
2388         /*
2389          * @TODO old-lost code?
2390         if ($wall && intval(PConfig::get($uid, 'system', 'no_wall_archive_widget')))
2391                 return $o;
2392         */
2393
2394         $visible_years = PConfig::get($uid,'system','archive_visible_years');
2395         if (! $visible_years) {
2396                 $visible_years = 5;
2397         }
2398
2399         $ret = list_post_dates($uid, $wall);
2400
2401         if (! DBM::is_result($ret)) {
2402                 return $o;
2403         }
2404
2405         $cutoff_year = intval(datetime_convert('',date_default_timezone_get(), 'now', 'Y')) - $visible_years;
2406         $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
2407
2408         $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
2409                 '$title' => t('Archives'),
2410                 '$size' => $visible_years,
2411                 '$cutoff_year' => $cutoff_year,
2412                 '$cutoff' => $cutoff,
2413                 '$url' => $url,
2414                 '$dates' => $ret,
2415                 '$showmore' => t('show more')
2416
2417         ));
2418         return $o;
2419 }