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