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