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