]> git.mxchange.org Git - friendica.git/blob - include/items.php
dcc99e8bd964878bc6e19e4a2c84e5e3160294ca
[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                 dba::insert('conversation', $conversation);
720         }
721
722         unset($arr['conversation-uri']);
723         unset($arr['conversation-href']);
724         unset($arr['protocol']);
725         unset($arr['source']);
726
727         if ($arr['parent-uri'] === $arr['uri']) {
728                 $parent_id = 0;
729                 $parent_deleted = 0;
730                 $allow_cid = $arr['allow_cid'];
731                 $allow_gid = $arr['allow_gid'];
732                 $deny_cid  = $arr['deny_cid'];
733                 $deny_gid  = $arr['deny_gid'];
734                 $notify_type = 'wall-new';
735         } else {
736
737                 // find the parent and snarf the item id and ACLs
738                 // and anything else we need to inherit
739
740                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
741                         dbesc($arr['parent-uri']),
742                         intval($arr['uid'])
743                 );
744
745                 if (dbm::is_result($r)) {
746
747                         // is the new message multi-level threaded?
748                         // even though we don't support it now, preserve the info
749                         // and re-attach to the conversation parent.
750
751                         if ($r[0]['uri'] != $r[0]['parent-uri']) {
752                                 $arr['parent-uri'] = $r[0]['parent-uri'];
753                                 $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
754                                         ORDER BY `id` ASC LIMIT 1",
755                                         dbesc($r[0]['parent-uri']),
756                                         dbesc($r[0]['parent-uri']),
757                                         intval($arr['uid'])
758                                 );
759
760                                 if (dbm::is_result($z)) {
761                                         $r = $z;
762                                 }
763                         }
764
765                         $parent_id      = $r[0]['id'];
766                         $parent_deleted = $r[0]['deleted'];
767                         $allow_cid      = $r[0]['allow_cid'];
768                         $allow_gid      = $r[0]['allow_gid'];
769                         $deny_cid       = $r[0]['deny_cid'];
770                         $deny_gid       = $r[0]['deny_gid'];
771                         $arr['wall']    = $r[0]['wall'];
772                         $notify_type    = 'comment-new';
773
774                         /*
775                          * If the parent is private, force privacy for the entire conversation
776                          * This differs from the above settings as it subtly allows comments from
777                          * email correspondents to be private even if the overall thread is not.
778                          */
779                         if ($r[0]['private']) {
780                                 $arr['private'] = $r[0]['private'];
781                         }
782
783                         /*
784                          * Edge case. We host a public forum that was originally posted to privately.
785                          * The original author commented, but as this is a comment, the permissions
786                          * weren't fixed up so it will still show the comment as private unless we fix it here.
787                          */
788                         if ((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private'])) {
789                                 $arr['private'] = 0;
790                         }
791
792                         // If its a post from myself then tag the thread as "mention"
793                         logger("item_store: Checking if parent ".$parent_id." has to be tagged as mention for user ".$arr['uid'], LOGGER_DEBUG);
794                         $u = q("SELECT `nickname` FROM `user` WHERE `uid` = %d", intval($arr['uid']));
795                         if (dbm::is_result($u)) {
796                                 $a = get_app();
797                                 $self = normalise_link(App::get_baseurl() . '/profile/' . $u[0]['nickname']);
798                                 logger("item_store: 'myself' is ".$self." for parent ".$parent_id." checking against ".$arr['author-link']." and ".$arr['owner-link'], LOGGER_DEBUG);
799                                 if ((normalise_link($arr['author-link']) == $self) OR (normalise_link($arr['owner-link']) == $self)) {
800                                         q("UPDATE `thread` SET `mention` = 1 WHERE `iid` = %d", intval($parent_id));
801                                         logger("item_store: tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
802                                 }
803                         }
804                 } else {
805                         /*
806                          * Allow one to see reply tweets from status.net even when
807                          * we don't have or can't see the original post.
808                          */
809                         if ($force_parent) {
810                                 logger('item_store: $force_parent=true, reply converted to top-level post.');
811                                 $parent_id = 0;
812                                 $arr['parent-uri'] = $arr['uri'];
813                                 $arr['gravity'] = 0;
814                         } else {
815                                 logger('item_store: item parent '.$arr['parent-uri'].' for '.$arr['uid'].' was not found - ignoring item');
816                                 return 0;
817                         }
818
819                         $parent_deleted = 0;
820                 }
821         }
822
823         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `network` IN ('%s', '%s') AND `uid` = %d LIMIT 1",
824                 dbesc($arr['uri']),
825                 dbesc($arr['network']),
826                 dbesc(NETWORK_DFRN),
827                 intval($arr['uid'])
828         );
829         if (dbm::is_result($r)) {
830                 logger('duplicated item with the same uri found. '.print_r($arr,true));
831                 return 0;
832         }
833
834         // On Friendica and Diaspora the GUID is unique
835         if (in_array($arr['network'], array(NETWORK_DFRN, NETWORK_DIASPORA))) {
836                 $r = q("SELECT `id` FROM `item` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
837                         dbesc($arr['guid']),
838                         intval($arr['uid'])
839                 );
840                 if (dbm::is_result($r)) {
841                         logger('duplicated item with the same guid found. '.print_r($arr,true));
842                         return 0;
843                 }
844         } else {
845                 // Check for an existing post with the same content. There seems to be a problem with OStatus.
846                 $r = q("SELECT `id` FROM `item` WHERE `body` = '%s' AND `network` = '%s' AND `created` = '%s' AND `contact-id` = %d AND `uid` = %d LIMIT 1",
847                         dbesc($arr['body']),
848                         dbesc($arr['network']),
849                         dbesc($arr['created']),
850                         intval($arr['contact-id']),
851                         intval($arr['uid'])
852                 );
853                 if (dbm::is_result($r)) {
854                         logger('duplicated item with the same body found. '.print_r($arr,true));
855                         return 0;
856                 }
857         }
858
859         // Is this item available in the global items (with uid=0)?
860         if ($arr["uid"] == 0) {
861                 $arr["global"] = true;
862
863                 // Set the global flag on all items if this was a global item entry
864                 q("UPDATE `item` SET `global` = 1 WHERE `uri` = '%s'", dbesc($arr["uri"]));
865         } else {
866                 $isglobal = q("SELECT `global` FROM `item` WHERE `uid` = 0 AND `uri` = '%s'", dbesc($arr["uri"]));
867
868                 $arr["global"] = (dbm::is_result($isglobal) && count($isglobal) > 0);
869         }
870
871         // ACL settings
872         if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
873                 $private = 1;
874         } else {
875                 $private = $arr['private'];
876         }
877
878         $arr["allow_cid"] = $allow_cid;
879         $arr["allow_gid"] = $allow_gid;
880         $arr["deny_cid"] = $deny_cid;
881         $arr["deny_gid"] = $deny_gid;
882         $arr["private"] = $private;
883         $arr["deleted"] = $parent_deleted;
884
885         // Fill the cache field
886         put_item_in_cache($arr);
887
888         if ($notify) {
889                 call_hooks('post_local', $arr);
890         } else {
891                 call_hooks('post_remote', $arr);
892         }
893
894         if (x($arr, 'cancel')) {
895                 logger('item_store: post cancelled by plugin.');
896                 return 0;
897         }
898
899         /*
900          * Check for already added items.
901          * There is a timing issue here that sometimes creates double postings.
902          * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
903          */
904         if ($arr["uid"] == 0) {
905                 $r = qu("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = 0 LIMIT 1", dbesc(trim($arr['uri'])));
906                 if (dbm::is_result($r)) {
907                         logger('Global item already stored. URI: '.$arr['uri'].' on network '.$arr['network'], LOGGER_DEBUG);
908                         return 0;
909                 }
910         }
911
912         // Store the unescaped version
913         $unescaped = $arr;
914
915         dbm::esc_array($arr, true);
916
917         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
918
919         q("COMMIT");
920         q("START TRANSACTION;");
921
922         $r = dbq("INSERT INTO `item` (`"
923                         . implode("`, `", array_keys($arr))
924                         . "`) VALUES ("
925                         . implode(", ", array_values($arr))
926                         . ")");
927
928         // And restore it
929         $arr = $unescaped;
930
931         // When the item was successfully stored we fetch the ID of the item.
932         if (dbm::is_result($r)) {
933                 $r = q("SELECT LAST_INSERT_ID() AS `item-id`");
934                 if (dbm::is_result($r)) {
935                         $current_post = $r[0]['item-id'];
936                 } else {
937                         // This shouldn't happen
938                         $current_post = 0;
939                 }
940         } else {
941                 // This can happen - for example - if there are locking timeouts.
942                 q("ROLLBACK");
943
944                 // Store the data into a spool file so that we can try again later.
945
946                 // At first we restore the Diaspora signature that we removed above.
947                 if (isset($encoded_signature)) {
948                         $arr['dsprsig'] = $encoded_signature;
949                 }
950
951                 // Now we store the data in the spool directory
952                 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
953                 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
954
955                 $spoolpath = get_spoolpath();
956                 if ($spoolpath != "") {
957                         $spool = $spoolpath.'/'.$file;
958                         file_put_contents($spool, json_encode($arr));
959                         logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
960                 }
961                 return 0;
962         }
963
964         if ($current_post == 0) {
965                 // This is one of these error messages that never should occur.
966                 logger("couldn't find created item - we better quit now.");
967                 q("ROLLBACK");
968                 return 0;
969         }
970
971         // How much entries have we created?
972         // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
973         $r = q("SELECT COUNT(*) AS `entries` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s'",
974                 dbesc($arr['uri']),
975                 intval($arr['uid']),
976                 dbesc($arr['network'])
977         );
978
979         if (!dbm::is_result($r)) {
980                 // This shouldn't happen, since COUNT always works when the database connection is there.
981                 logger("We couldn't count the stored entries. Very strange ...");
982                 q("ROLLBACK");
983                 return 0;
984         }
985
986         if ($r[0]["entries"] > 1) {
987                 // There are duplicates. We delete our just created entry.
988                 logger('Duplicated post occurred. uri = ' . $arr['uri'] . ' uid = ' . $arr['uid']);
989
990                 // Yes, we could do a rollback here - but we are having many users with MyISAM.
991                 q("DELETE FROM `item` WHERE `id` = %d", intval($current_post));
992                 q("COMMIT");
993                 return 0;
994         } elseif ($r[0]["entries"] == 0) {
995                 // This really should never happen since we quit earlier if there were problems.
996                 logger("Something is terribly wrong. We haven't found our created entry.");
997                 q("ROLLBACK");
998                 return 0;
999         }
1000
1001         logger('item_store: created item '.$current_post);
1002         item_set_last_item($arr);
1003
1004         if (!$parent_id || ($arr['parent-uri'] === $arr['uri'])) {
1005                 $parent_id = $current_post;
1006         }
1007
1008         // Set parent id
1009         $r = q("UPDATE `item` SET `parent` = %d WHERE `id` = %d",
1010                 intval($parent_id),
1011                 intval($current_post)
1012         );
1013
1014         $arr['id'] = $current_post;
1015         $arr['parent'] = $parent_id;
1016
1017         // update the commented timestamp on the parent
1018         // Only update "commented" if it is really a comment
1019         if (($arr['verb'] == ACTIVITY_POST) OR !get_config("system", "like_no_comment")) {
1020                 q("UPDATE `item` SET `commented` = '%s', `changed` = '%s' WHERE `id` = %d",
1021                         dbesc(datetime_convert()),
1022                         dbesc(datetime_convert()),
1023                         intval($parent_id)
1024                 );
1025         } else {
1026                 q("UPDATE `item` SET `changed` = '%s' WHERE `id` = %d",
1027                         dbesc(datetime_convert()),
1028                         intval($parent_id)
1029                 );
1030         }
1031
1032         if ($dsprsig) {
1033
1034                 /*
1035                  * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1036                  * We can check for this condition when we decode and encode the stuff again.
1037                  */
1038                 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1039                         $dsprsig->signature = base64_decode($dsprsig->signature);
1040                         logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1041                 }
1042
1043                 q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1044                         intval($current_post),
1045                         dbesc($dsprsig->signed_text),
1046                         dbesc($dsprsig->signature),
1047                         dbesc($dsprsig->signer)
1048                 );
1049         }
1050
1051         $deleted = tag_deliver($arr['uid'], $current_post);
1052
1053         /*
1054          * current post can be deleted if is for a community page and no mention are
1055          * in it.
1056          */
1057         if (!$deleted AND !$dontcache) {
1058
1059                 $r = q('SELECT * FROM `item` WHERE `id` = %d', intval($current_post));
1060                 if ((dbm::is_result($r)) && (count($r) == 1)) {
1061                         if ($notify) {
1062                                 call_hooks('post_local_end', $r[0]);
1063                         } else {
1064                                 call_hooks('post_remote_end', $r[0]);
1065                         }
1066                 } else {
1067                         logger('item_store: new item not found in DB, id ' . $current_post);
1068                 }
1069         }
1070
1071         if ($arr['parent-uri'] === $arr['uri']) {
1072                 add_thread($current_post);
1073         } else {
1074                 update_thread($parent_id);
1075         }
1076
1077         q("COMMIT");
1078
1079         /*
1080          * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1081          * This is not perfect - but a workable solution until we found the reason for the problem.
1082          */
1083         create_tags_from_item($current_post);
1084         create_files_from_item($current_post);
1085
1086         /*
1087          * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
1088          * It is done after the transaction to avoid dead locks.
1089          */
1090         if ($arr['last-child']) {
1091                 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
1092                         dbesc($arr['uri']),
1093                         intval($arr['uid']),
1094                         intval($current_post)
1095                 );
1096         }
1097
1098         if ($arr['parent-uri'] === $arr['uri']) {
1099                 add_shadow_thread($current_post);
1100         } else {
1101                 add_shadow_entry($current_post);
1102         }
1103
1104         check_item_notification($current_post, $uid);
1105
1106         if ($notify) {
1107                 proc_run(PRIORITY_HIGH, "include/notifier.php", $notify_type, $current_post);
1108         }
1109
1110         return $current_post;
1111 }
1112
1113 /**
1114  * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1115  *
1116  * This can be used to filter for inactive contacts.
1117  * Only do this for public postings to avoid privacy problems, since poco data is public.
1118  * Don't set this value if it isn't from the owner (could be an author that we don't know)
1119  *
1120  * @param array $arr Contains the just posted item record
1121  */
1122 function item_set_last_item($arr) {
1123
1124         $update = (!$arr['private'] AND (($arr["author-link"] === $arr["owner-link"]) OR ($arr["parent-uri"] === $arr["uri"])));
1125
1126         // Is it a forum? Then we don't care about the rules from above
1127         if (!$update AND ($arr["network"] == NETWORK_DFRN) AND ($arr["parent-uri"] === $arr["uri"])) {
1128                 $isforum = q("SELECT `forum` FROM `contact` WHERE `id` = %d AND `forum`",
1129                                 intval($arr['contact-id']));
1130                 if (dbm::is_result($isforum)) {
1131                         $update = true;
1132                 }
1133         }
1134
1135         if ($update) {
1136                 q("UPDATE `contact` SET `success_update` = '%s', `last-item` = '%s' WHERE `id` = %d",
1137                         dbesc($arr['received']),
1138                         dbesc($arr['received']),
1139                         intval($arr['contact-id'])
1140                 );
1141         }
1142         // Now do the same for the system wide contacts with uid=0
1143         if (!$arr['private']) {
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['owner-id'])
1148                 );
1149
1150                 if ($arr['owner-id'] != $arr['author-id']) {
1151                         q("UPDATE `contact` SET `success_update` = '%s', `last-item` = '%s' WHERE `id` = %d",
1152                                 dbesc($arr['received']),
1153                                 dbesc($arr['received']),
1154                                 intval($arr['author-id'])
1155                         );
1156                 }
1157         }
1158 }
1159
1160 function item_body_set_hashtags(&$item) {
1161
1162         $tags = get_tags($item["body"]);
1163
1164         // No hashtags?
1165         if (!count($tags)) {
1166                 return false;
1167         }
1168
1169         // This sorting is important when there are hashtags that are part of other hashtags
1170         // Otherwise there could be problems with hashtags like #test and #test2
1171         rsort($tags);
1172
1173         $a = get_app();
1174
1175         $URLSearchString = "^\[\]";
1176
1177         /// @TODO old-lost code?
1178         // All hashtags should point to the home server
1179         //$item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1180         //              "#[url=".App::get_baseurl()."/search?tag=$2]$2[/url]", $item["body"]);
1181
1182         //$item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1183         //              "#[url=".App::get_baseurl()."/search?tag=$2]$2[/url]", $item["tag"]);
1184
1185         // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1186         $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1187                 function ($match) {
1188                         return ("[url=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/url]");
1189                 }, $item["body"]);
1190
1191         $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1192                 function ($match) {
1193                         return ("[bookmark=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/bookmark]");
1194                 }, $item["body"]);
1195
1196         $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1197                 function ($match) {
1198                         return ("[attachment " . str_replace("#", "&num;", $match[1]) . "]" . $match[2] . "[/attachment]");
1199                 }, $item["body"]);
1200
1201         // Repair recursive urls
1202         $item["body"] = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1203                         "&num;$2", $item["body"]);
1204
1205         foreach ($tags as $tag) {
1206                 if ((strpos($tag, '#') !== 0) || (strpos($tag, '[url='))) {
1207                         continue;
1208                 }
1209
1210                 $basetag = str_replace('_',' ',substr($tag,1));
1211
1212                 $newtag = '#[url=' . App::get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1213
1214                 $item["body"] = str_replace($tag, $newtag, $item["body"]);
1215
1216                 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1217                         if (strlen($item["tag"])) {
1218                                 $item["tag"] = ','.$item["tag"];
1219                         }
1220                         $item["tag"] = $newtag.$item["tag"];
1221                 }
1222         }
1223
1224         // Convert back the masked hashtags
1225         $item["body"] = str_replace("&num;", "#", $item["body"]);
1226 }
1227
1228 function get_item_guid($id) {
1229         $r = q("SELECT `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($id));
1230         if (dbm::is_result($r)) {
1231                 return $r[0]["guid"];
1232         } else {
1233                 /// @TODO This else-block can be elimited again
1234                 return "";
1235         }
1236 }
1237
1238 function get_item_id($guid, $uid = 0) {
1239
1240         $nick = "";
1241         $id = 0;
1242
1243         if ($uid == 0) {
1244                 $uid == local_user();
1245         }
1246
1247         // Does the given user have this item?
1248         if ($uid) {
1249                 $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1250                         WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1251                                 AND `item`.`guid` = '%s' AND `item`.`uid` = %d", dbesc($guid), intval($uid));
1252                 if (dbm::is_result($r)) {
1253                         $id = $r[0]["id"];
1254                         $nick = $r[0]["nickname"];
1255                 }
1256         }
1257
1258         // Or is it anywhere on the server?
1259         if ($nick == "") {
1260                 $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1261                         WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1262                                 AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
1263                                 AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
1264                                 AND `item`.`private` = 0 AND `item`.`wall` = 1
1265                                 AND `item`.`guid` = '%s'", dbesc($guid));
1266                 if (dbm::is_result($r)) {
1267                         $id = $r[0]["id"];
1268                         $nick = $r[0]["nickname"];
1269                 }
1270         }
1271         return array("nick" => $nick, "id" => $id);
1272 }
1273
1274 // return - test
1275 function get_item_contact($item, $contacts) {
1276         if (! count($contacts) || (! is_array($item))) {
1277                 return false;
1278         }
1279         foreach ($contacts as $contact) {
1280                 if ($contact['id'] == $item['contact-id']) {
1281                         return $contact;
1282                         break; // NOTREACHED
1283                 }
1284         }
1285         return false;
1286 }
1287
1288 /**
1289  * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1290  * @param int $uid
1291  * @param int $item_id
1292  * @return bool true if item was deleted, else false
1293  */
1294 function tag_deliver($uid, $item_id) {
1295
1296         $a = get_app();
1297
1298         $mention = false;
1299
1300         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1301                 intval($uid)
1302         );
1303
1304         if (! dbm::is_result($u)) {
1305                 return;
1306         }
1307
1308         $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1309         $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1310
1311
1312         $i = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1313                 intval($item_id),
1314                 intval($uid)
1315         );
1316         if (! dbm::is_result($i)) {
1317                 return;
1318         }
1319
1320         $item = $i[0];
1321
1322         $link = normalise_link(App::get_baseurl() . '/profile/' . $u[0]['nickname']);
1323
1324         /*
1325          * Diaspora uses their own hardwired link URL in @-tags
1326          * instead of the one we supply with webfinger
1327          */
1328         $dlink = normalise_link(App::get_baseurl() . '/u/' . $u[0]['nickname']);
1329
1330         $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1331         if ($cnt) {
1332                 foreach ($matches as $mtch) {
1333                         if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1334                                 $mention = true;
1335                                 logger('tag_deliver: mention found: ' . $mtch[2]);
1336                         }
1337                 }
1338         }
1339
1340         if (! $mention) {
1341                 if (($community_page || $prvgroup) &&
1342                           (!$item['wall']) && (!$item['origin']) && ($item['id'] == $item['parent'])) {
1343                         // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1344                         // delete it!
1345                         logger("tag_deliver: no-mention top-level post to communuty or private group. delete.");
1346                         q("DELETE FROM item WHERE id = %d and uid = %d",
1347                                 intval($item_id),
1348                                 intval($uid)
1349                         );
1350                         return true;
1351                 }
1352                 return;
1353         }
1354
1355         $arr = array('item' => $item, 'user' => $u[0], 'contact' => $r[0]);
1356
1357         call_hooks('tagged', $arr);
1358
1359         if ((! $community_page) && (! $prvgroup)) {
1360                 return;
1361         }
1362
1363         /*
1364          * tgroup delivery - setup a second delivery chain
1365          * prevent delivery looping - only proceed
1366          * if the message originated elsewhere and is a top-level post
1367          */
1368         if (($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent'])) {
1369                 return;
1370         }
1371
1372         // now change this copy of the post to a forum head message and deliver to all the tgroup members
1373         $c = q("SELECT `name`, `url`, `thumb` FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1374                 intval($u[0]['uid'])
1375         );
1376         if (! dbm::is_result($c)) {
1377                 return;
1378         }
1379
1380         // also reset all the privacy bits to the forum default permissions
1381
1382         $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1383
1384         $forum_mode = (($prvgroup) ? 2 : 1);
1385
1386         q("UPDATE `item` SET `wall` = 1, `origin` = 1, `forum_mode` = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1387                 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'  WHERE `id` = %d",
1388                 intval($forum_mode),
1389                 dbesc($c[0]['name']),
1390                 dbesc($c[0]['url']),
1391                 dbesc($c[0]['thumb']),
1392                 intval($private),
1393                 dbesc($u[0]['allow_cid']),
1394                 dbesc($u[0]['allow_gid']),
1395                 dbesc($u[0]['deny_cid']),
1396                 dbesc($u[0]['deny_gid']),
1397                 intval($item_id)
1398         );
1399         update_thread($item_id);
1400
1401         proc_run(PRIORITY_HIGH,'include/notifier.php', 'tgroup', $item_id);
1402
1403 }
1404
1405
1406
1407 function tgroup_check($uid, $item) {
1408
1409         $mention = false;
1410
1411         // check that the message originated elsewhere and is a top-level post
1412
1413         if (($item['wall']) || ($item['origin']) || ($item['uri'] != $item['parent-uri'])) {
1414                 return false;
1415         }
1416
1417         /// @TODO Encapsulate this or find it encapsulated and replace all occurrances
1418         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1419                 intval($uid)
1420         );
1421         if (! dbm::is_result($u)) {
1422                 return false;
1423         }
1424
1425         $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1426         $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1427
1428         $link = normalise_link(App::get_baseurl() . '/profile/' . $u[0]['nickname']);
1429
1430         /*
1431          * Diaspora uses their own hardwired link URL in @-tags
1432          * instead of the one we supply with webfinger
1433          */
1434         $dlink = normalise_link(App::get_baseurl() . '/u/' . $u[0]['nickname']);
1435
1436         $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1437         if ($cnt) {
1438                 foreach ($matches as $mtch) {
1439                         if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1440                                 $mention = true;
1441                                 logger('tgroup_check: mention found: ' . $mtch[2]);
1442                         }
1443                 }
1444         }
1445
1446         if (! $mention) {
1447                 return false;
1448         }
1449
1450         /// @TODO Combine both return statements into one
1451         return (($community_page) || ($prvgroup));
1452 }
1453
1454 /**
1455  * This function returns true if $update has an edited timestamp newer
1456  * than $existing, i.e. $update contains new data which should override
1457  * what's already there.  If there is no timestamp yet, the update is
1458  * assumed to be newer.  If the update has no timestamp, the existing
1459  * item is assumed to be up-to-date.  If the timestamps are equal it
1460  * assumes the update has been seen before and should be ignored.
1461  *
1462  * @todo fix type-hints (both array)
1463  */
1464 function edited_timestamp_is_newer ($existing, $update) {
1465         if (!x($existing, 'edited') || !$existing['edited']) {
1466                 return true;
1467         }
1468         if (!x($update, 'edited') || !$update['edited']) {
1469                 return false;
1470         }
1471
1472         $existing_edited = datetime_convert('UTC', 'UTC', $existing['edited']);
1473         $update_edited = datetime_convert('UTC', 'UTC', $update['edited']);
1474         return (strcmp($existing_edited, $update_edited) < 0);
1475 }
1476
1477 /**
1478  *
1479  * consume_feed - process atom feed and update anything/everything we might need to update
1480  *
1481  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1482  *
1483  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1484  *             It is this person's stuff that is going to be updated.
1485  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1486  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1487  *             have a contact record.
1488  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1489  *        might not) try and subscribe to it.
1490  * $datedir sorts in reverse order
1491  * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1492  *      imported prior to its children being seen in the stream unless we are certain
1493  *      of how the feed is arranged/ordered.
1494  * With $pass = 1, we only pull parent items out of the stream.
1495  * With $pass = 2, we only pull children (comments/likes).
1496  *
1497  * So running this twice, first with pass 1 and then with pass 2 will do the right
1498  * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1499  * model where comments can have sub-threads. That would require some massive sorting
1500  * to get all the feed items into a mostly linear ordering, and might still require
1501  * recursion.
1502  *
1503  * @todo find proper type-hints
1504  */
1505 function consume_feed($xml, $importer, &$contact, &$hub, $datedir = 0, $pass = 0) {
1506         if ($contact['network'] === NETWORK_OSTATUS) {
1507                 if ($pass < 2) {
1508                         // Test - remove before flight
1509                         //$tempfile = tempnam(get_temppath(), "ostatus2");
1510                         //file_put_contents($tempfile, $xml);
1511                         logger("Consume OStatus messages ", LOGGER_DEBUG);
1512                         ostatus::import($xml, $importer, $contact, $hub);
1513                 }
1514                 return;
1515         }
1516
1517         if ($contact['network'] === NETWORK_FEED) {
1518                 if ($pass < 2) {
1519                         logger("Consume feeds", LOGGER_DEBUG);
1520                         feed_import($xml, $importer, $contact, $hub);
1521                 }
1522                 return;
1523         }
1524
1525         if ($contact['network'] === NETWORK_DFRN) {
1526                 logger("Consume DFRN messages", LOGGER_DEBUG);
1527
1528                 $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
1529                                         `contact`.`pubkey` AS `cpubkey`,
1530                                         `contact`.`prvkey` AS `cprvkey`,
1531                                         `contact`.`thumb` AS `thumb`,
1532                                         `contact`.`url` as `url`,
1533                                         `contact`.`name` as `senderName`,
1534                                         `user`.*
1535                         FROM `contact`
1536                         LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
1537                         WHERE `contact`.`id` = %d AND `user`.`uid` = %d",
1538                         dbesc($contact["id"]), dbesc($importer["uid"])
1539                 );
1540                 if (dbm::is_result($r)) {
1541                         logger("Now import the DFRN feed");
1542                         dfrn::import($xml, $r[0], true);
1543                         return;
1544                 }
1545         }
1546 }
1547
1548 /// @TODO type-hint is array
1549 function item_is_remote_self($contact, &$datarray) {
1550         $a = get_app();
1551
1552         if (!$contact['remote_self']) {
1553                 return false;
1554         }
1555
1556         // Prevent the forwarding of posts that are forwarded
1557         if ($datarray["extid"] == NETWORK_DFRN) {
1558                 return false;
1559         }
1560
1561         // Prevent to forward already forwarded posts
1562         if ($datarray["app"] == $a->get_hostname()) {
1563                 return false;
1564         }
1565
1566         // Only forward posts
1567         if ($datarray["verb"] != ACTIVITY_POST) {
1568                 return false;
1569         }
1570
1571         if (($contact['network'] != NETWORK_FEED) AND $datarray['private']) {
1572                 return false;
1573         }
1574
1575         $datarray2 = $datarray;
1576         logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1577         if ($contact['remote_self'] == 2) {
1578                 $r = q("SELECT `id`,`url`,`name`,`thumb` FROM `contact` WHERE `uid` = %d AND `self`",
1579                         intval($contact['uid']));
1580                 if (dbm::is_result($r)) {
1581                         $datarray['contact-id'] = $r[0]["id"];
1582
1583                         $datarray['owner-name'] = $r[0]["name"];
1584                         $datarray['owner-link'] = $r[0]["url"];
1585                         $datarray['owner-avatar'] = $r[0]["thumb"];
1586
1587                         $datarray['author-name']   = $datarray['owner-name'];
1588                         $datarray['author-link']   = $datarray['owner-link'];
1589                         $datarray['author-avatar'] = $datarray['owner-avatar'];
1590                 }
1591
1592                 if ($contact['network'] != NETWORK_FEED) {
1593                         $datarray["guid"] = get_guid(32);
1594                         unset($datarray["plink"]);
1595                         $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
1596                         $datarray["parent-uri"] = $datarray["uri"];
1597                         $datarray["extid"] = $contact['network'];
1598                         $urlpart = parse_url($datarray2['author-link']);
1599                         $datarray["app"] = $urlpart["host"];
1600                 } else {
1601                         $datarray['private'] = 0;
1602                 }
1603         }
1604
1605         if ($contact['network'] != NETWORK_FEED) {
1606                 // Store the original post
1607                 $r = item_store($datarray2, false, false);
1608                 logger('remote-self post original item - Contact '.$contact['url'].' return '.$r.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1609         } else {
1610                 $datarray["app"] = "Feed";
1611         }
1612
1613         return true;
1614 }
1615
1616 /// @TODO find proper type-hints
1617 function new_follower($importer, $contact, $datarray, $item, $sharing = false) {
1618         $url = notags(trim($datarray['author-link']));
1619         $name = notags(trim($datarray['author-name']));
1620         $photo = notags(trim($datarray['author-avatar']));
1621
1622         if (is_object($item)) {
1623                 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1624                 if ($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data']) {
1625                         $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1626                 }
1627         } else {
1628                 $nick = $item;
1629         }
1630
1631         if (is_array($contact)) {
1632                 if (($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
1633                         || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
1634                         $r = q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1635                                 intval(CONTACT_IS_FRIEND),
1636                                 intval($contact['id']),
1637                                 intval($importer['uid'])
1638                         );
1639                 }
1640                 // send email notification to owner?
1641         } else {
1642
1643                 // create contact record
1644
1645                 $r = q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1646                         `blocked`, `readonly`, `pending`, `writable`)
1647                         VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1648                         intval($importer['uid']),
1649                         dbesc(datetime_convert()),
1650                         dbesc($url),
1651                         dbesc(normalise_link($url)),
1652                         dbesc($name),
1653                         dbesc($nick),
1654                         dbesc($photo),
1655                         dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
1656                         intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
1657                 );
1658                 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
1659                                 intval($importer['uid']),
1660                                 dbesc($url)
1661                 );
1662                 if (dbm::is_result($r)) {
1663                         $contact_record = $r[0];
1664                         update_contact_avatar($photo, $importer["uid"], $contact_record["id"], true);
1665                 }
1666
1667                 /// @TODO Encapsulate this into a function/method
1668                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1669                         intval($importer['uid'])
1670                 );
1671
1672                 if (dbm::is_result($r) AND !in_array($r[0]['page-flags'], array(PAGE_SOAPBOX, PAGE_FREELOVE))) {
1673
1674                         // create notification
1675                         $hash = random_string();
1676
1677                         if (is_array($contact_record)) {
1678                                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1679                                         VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1680                                         intval($importer['uid']),
1681                                         intval($contact_record['id']),
1682                                         dbesc($hash),
1683                                         dbesc(datetime_convert())
1684                                 );
1685                         }
1686
1687                         $def_gid = get_default_group($importer['uid'], $contact_record["network"]);
1688
1689                         if (intval($def_gid)) {
1690                                 group_add_member($importer['uid'], '', $contact_record['id'], $def_gid);
1691                         }
1692
1693                         if (($r[0]['notify-flags'] & NOTIFY_INTRO) &&
1694                                 in_array($r[0]['page-flags'], array(PAGE_NORMAL))) {
1695
1696                                 notification(array(
1697                                         'type'         => NOTIFY_INTRO,
1698                                         'notify_flags' => $r[0]['notify-flags'],
1699                                         'language'     => $r[0]['language'],
1700                                         'to_name'      => $r[0]['username'],
1701                                         'to_email'     => $r[0]['email'],
1702                                         'uid'          => $r[0]['uid'],
1703                                         'link'             => App::get_baseurl() . '/notifications/intro',
1704                                         'source_name'  => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : t('[Name Withheld]')),
1705                                         'source_link'  => $contact_record['url'],
1706                                         'source_photo' => $contact_record['photo'],
1707                                         'verb'         => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1708                                         'otype'        => 'intro'
1709                                 ));
1710
1711                         }
1712                 } elseif (dbm::is_result($r) AND in_array($r[0]['page-flags'], array(PAGE_SOAPBOX, PAGE_FREELOVE))) {
1713                         $r = q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1",
1714                                         intval($importer['uid']),
1715                                         dbesc($url)
1716                         );
1717                 }
1718
1719         }
1720 }
1721
1722 function lose_follower($importer, $contact, array $datarray = array(), $item = "") {
1723
1724         if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
1725                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d",
1726                         intval(CONTACT_IS_SHARING),
1727                         intval($contact['id'])
1728                 );
1729         } else {
1730                 contact_remove($contact['id']);
1731         }
1732 }
1733
1734 function lose_sharer($importer, $contact, array $datarray = array(), $item = "") {
1735
1736         if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
1737                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d",
1738                         intval(CONTACT_IS_FOLLOWER),
1739                         intval($contact['id'])
1740                 );
1741         } else {
1742                 contact_remove($contact['id']);
1743         }
1744 }
1745
1746 function subscribe_to_hub($url, $importer, $contact, $hubmode = 'subscribe') {
1747
1748         $a = get_app();
1749
1750         if (is_array($importer)) {
1751                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1752                         intval($importer['uid'])
1753                 );
1754         }
1755
1756         /*
1757          * Diaspora has different message-ids in feeds than they do
1758          * through the direct Diaspora protocol. If we try and use
1759          * the feed, we'll get duplicates. So don't.
1760          */
1761         if ((! dbm::is_result($r)) || $contact['network'] === NETWORK_DIASPORA) {
1762                 return;
1763         }
1764
1765         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1766
1767         // Use a single verify token, even if multiple hubs
1768         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1769
1770         $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1771
1772         logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: '  . $push_url . ' with verifier ' . $verify_token);
1773
1774         if (!strlen($contact['hub-verify']) OR ($contact['hub-verify'] != $verify_token)) {
1775                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d",
1776                         dbesc($verify_token),
1777                         intval($contact['id'])
1778                 );
1779         }
1780
1781         post_url($url, $params);
1782
1783         logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
1784
1785         return;
1786
1787 }
1788
1789 function fix_private_photos($s, $uid, $item = null, $cid = 0) {
1790
1791         if (get_config('system','disable_embedded')) {
1792                 return $s;
1793         }
1794
1795         $a = get_app();
1796
1797         logger('fix_private_photos: check for photos', LOGGER_DEBUG);
1798         $site = substr(App::get_baseurl(),strpos(App::get_baseurl(),'://'));
1799
1800         $orig_body = $s;
1801         $new_body = '';
1802
1803         $img_start = strpos($orig_body, '[img');
1804         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1805         $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1806         while ( ($img_st_close !== false) && ($img_len !== false) ) {
1807
1808                 $img_st_close++; // make it point to AFTER the closing bracket
1809                 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
1810
1811                 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
1812
1813
1814                 if (stristr($image , $site . '/photo/')) {
1815                         // Only embed locally hosted photos
1816                         $replace = false;
1817                         $i = basename($image);
1818                         $i = str_replace(array('.jpg', '.png', '.gif'),array('', '',''), $i);
1819                         $x = strpos($i, '-');
1820
1821                         if ($x) {
1822                                 $res = substr($i, $x + 1);
1823                                 $i = substr($i, 0, $x);
1824                                 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1825                                         dbesc($i),
1826                                         intval($res),
1827                                         intval($uid)
1828
1829                                 );
1830                                 if (dbm::is_result($r)) {
1831                                         /*
1832                                          * Check to see if we should replace this photo link with an embedded image
1833                                          * 1. No need to do so if the photo is public
1834                                          * 2. If there's a contact-id provided, see if they're in the access list
1835                                          *    for the photo. If so, embed it.
1836                                          * 3. Otherwise, if we have an item, see if the item permissions match the photo
1837                                          *    permissions, regardless of order but first check to see if they're an exact
1838                                          *    match to save some processing overhead.
1839                                          */
1840                                         if (has_permissions($r[0])) {
1841                                                 if ($cid) {
1842                                                         $recips = enumerate_permissions($r[0]);
1843                                                         if (in_array($cid, $recips)) {
1844                                                                 $replace = true;
1845                                                         }
1846                                                 } elseif ($item) {
1847                                                         if (compare_permissions($item, $r[0])) {
1848                                                                 $replace = true;
1849                                                         }
1850                                                 }
1851                                         }
1852                                         if ($replace) {
1853                                                 $data = $r[0]['data'];
1854                                                 $type = $r[0]['type'];
1855
1856                                                 // If a custom width and height were specified, apply before embedding
1857                                                 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
1858                                                         logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
1859
1860                                                         $width = intval($match[1]);
1861                                                         $height = intval($match[2]);
1862
1863                                                         $ph = new Photo($data, $type);
1864                                                         if ($ph->is_valid()) {
1865                                                                 $ph->scaleImage(max($width, $height));
1866                                                                 $data = $ph->imageString();
1867                                                                 $type = $ph->getType();
1868                                                         }
1869                                                 }
1870
1871                                                 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
1872                                                 $image = 'data:' . $type . ';base64,' . base64_encode($data);
1873                                                 logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
1874                                         }
1875                                 }
1876                         }
1877                 }
1878
1879                 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
1880                 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
1881                 if ($orig_body === false) {
1882                         $orig_body = '';
1883                 }
1884
1885                 $img_start = strpos($orig_body, '[img');
1886                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1887                 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1888         }
1889
1890         $new_body = $new_body . $orig_body;
1891
1892         return $new_body;
1893 }
1894
1895 /// @TODO type-hint is array
1896 function has_permissions($obj) {
1897         return (
1898                 (
1899                         x($obj, 'allow_cid')
1900                 ) || (
1901                         x($obj, 'allow_gid')
1902                 ) || (
1903                         x($obj, 'deny_cid')
1904                 ) || (
1905                         x($obj, 'deny_gid')
1906                 )
1907         );
1908 }
1909
1910 /// @TODO type-hint is array
1911 function compare_permissions($obj1, $obj2) {
1912         // first part is easy. Check that these are exactly the same.
1913         if (($obj1['allow_cid'] == $obj2['allow_cid'])
1914                 && ($obj1['allow_gid'] == $obj2['allow_gid'])
1915                 && ($obj1['deny_cid'] == $obj2['deny_cid'])
1916                 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
1917                 return true;
1918         }
1919
1920         // This is harder. Parse all the permissions and compare the resulting set.
1921         $recipients1 = enumerate_permissions($obj1);
1922         $recipients2 = enumerate_permissions($obj2);
1923         sort($recipients1);
1924         sort($recipients2);
1925
1926         /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1927         return ($recipients1 == $recipients2);
1928 }
1929
1930 // returns an array of contact-ids that are allowed to see this object
1931 /// @TODO type-hint is array
1932 function enumerate_permissions($obj) {
1933         $allow_people = expand_acl($obj['allow_cid']);
1934         $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
1935         $deny_people  = expand_acl($obj['deny_cid']);
1936         $deny_groups  = expand_groups(expand_acl($obj['deny_gid']));
1937         $recipients   = array_unique(array_merge($allow_people, $allow_groups));
1938         $deny         = array_unique(array_merge($deny_people, $deny_groups));
1939         $recipients   = array_diff($recipients, $deny);
1940         return $recipients;
1941 }
1942
1943 function item_getfeedtags($item) {
1944         $ret = array();
1945         $matches = false;
1946         $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1947         if ($cnt) {
1948                 for ($x = 0; $x < $cnt; $x ++) {
1949                         if ($matches[1][$x]) {
1950                                 $ret[$matches[2][$x]] = array('#', $matches[1][$x], $matches[2][$x]);
1951                         }
1952                 }
1953         }
1954         $matches = false;
1955         $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1956         if ($cnt) {
1957                 for ($x = 0; $x < $cnt; $x ++) {
1958                         if ($matches[1][$x]) {
1959                                 $ret[] = array('@', $matches[1][$x], $matches[2][$x]);
1960                         }
1961                 }
1962         }
1963         return $ret;
1964 }
1965
1966 function item_expire($uid, $days, $network = "", $force = false) {
1967
1968         if ((! $uid) || ($days < 1)) {
1969                 return;
1970         }
1971
1972         /*
1973          * $expire_network_only = save your own wall posts
1974          * and just expire conversations started by others
1975          */
1976         $expire_network_only = get_pconfig($uid,'expire', 'network_only');
1977         $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
1978
1979         if ($network != "") {
1980                 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
1981
1982                 /*
1983                  * There is an index "uid_network_received" but not "uid_network_created"
1984                  * This avoids the creation of another index just for one purpose.
1985                  * And it doesn't really matter wether to look at "received" or "created"
1986                  */
1987                 $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1988         } else {
1989                 $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1990         }
1991
1992         $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
1993                 WHERE `uid` = %d $range
1994                 AND `id` = `parent`
1995                 $sql_extra
1996                 AND `deleted` = 0",
1997                 intval($uid),
1998                 intval($days)
1999         );
2000
2001         if (! dbm::is_result($r)) {
2002                 return;
2003         }
2004
2005         $expire_items = get_pconfig($uid, 'expire', 'items');
2006         $expire_items = (($expire_items === false) ? 1 : intval($expire_items)); // default if not set: 1
2007
2008         // Forcing expiring of items - but not notes and marked items
2009         if ($force) {
2010                 $expire_items = true;
2011         }
2012
2013         $expire_notes = get_pconfig($uid, 'expire', 'notes');
2014         $expire_notes = (($expire_notes === false) ? 1 : intval($expire_notes)); // default if not set: 1
2015
2016         $expire_starred = get_pconfig($uid, 'expire', 'starred');
2017         $expire_starred = (($expire_starred === false) ? 1 : intval($expire_starred)); // default if not set: 1
2018
2019         $expire_photos = get_pconfig($uid, 'expire', 'photos');
2020         $expire_photos = (($expire_photos === false) ? 0 : intval($expire_photos)); // default if not set: 0
2021
2022         logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2023
2024         foreach ($r as $item) {
2025
2026                 // don't expire filed items
2027
2028                 if (strpos($item['file'],'[') !== false) {
2029                         continue;
2030                 }
2031
2032                 // Only expire posts, not photos and photo comments
2033
2034                 if ($expire_photos == 0 && strlen($item['resource-id'])) {
2035                         continue;
2036                 } elseif ($expire_starred == 0 && intval($item['starred'])) {
2037                         continue;
2038                 } elseif ($expire_notes == 0 && $item['type'] == 'note') {
2039                         continue;
2040                 } elseif ($expire_items == 0 && $item['type'] != 'note') {
2041                         continue;
2042                 }
2043
2044                 drop_item($item['id'], false);
2045         }
2046
2047         proc_run(PRIORITY_HIGH, "include/notifier.php", "expire", $uid);
2048
2049 }
2050
2051 /// @TODO type-hint is array
2052 function drop_items($items) {
2053         $uid = 0;
2054
2055         if (! local_user() && ! remote_user()) {
2056                 return;
2057         }
2058
2059         if (count($items)) {
2060                 foreach ($items as $item) {
2061                         $owner = drop_item($item,false);
2062                         if ($owner && ! $uid)
2063                                 $uid = $owner;
2064                 }
2065         }
2066
2067         // multiple threads may have been deleted, send an expire notification
2068
2069         if ($uid) {
2070                 proc_run(PRIORITY_HIGH, "include/notifier.php", "expire", $uid);
2071         }
2072 }
2073
2074
2075 function drop_item($id, $interactive = true) {
2076
2077         $a = get_app();
2078
2079         // locate item to be deleted
2080
2081         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
2082                 intval($id)
2083         );
2084
2085         if (! dbm::is_result($r)) {
2086                 if (! $interactive) {
2087                         return 0;
2088                 }
2089                 notice( t('Item not found.') . EOL);
2090                 goaway(App::get_baseurl() . '/' . $_SESSION['return_url']);
2091         }
2092
2093         $item = $r[0];
2094
2095         $owner = $item['uid'];
2096
2097         $contact_id = 0;
2098
2099         // check if logged in user is either the author or owner of this item
2100
2101         if (is_array($_SESSION['remote'])) {
2102                 foreach ($_SESSION['remote'] as $visitor) {
2103                         if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
2104                                 $contact_id = $visitor['cid'];
2105                                 break;
2106                         }
2107                 }
2108         }
2109
2110
2111         if ((local_user() == $item['uid']) || ($contact_id) || (! $interactive)) {
2112
2113                 // Check if we should do HTML-based delete confirmation
2114                 if ($_REQUEST['confirm']) {
2115                         // <form> can't take arguments in its "action" parameter
2116                         // so add any arguments as hidden inputs
2117                         $query = explode_querystring($a->query_string);
2118                         $inputs = array();
2119                         foreach ($query['args'] as $arg) {
2120                                 if (strpos($arg, 'confirm=') === false) {
2121                                         $arg_parts = explode('=', $arg);
2122                                         $inputs[] = array('name' => $arg_parts[0], 'value' => $arg_parts[1]);
2123                                 }
2124                         }
2125
2126                         return replace_macros(get_markup_template('confirm.tpl'), array(
2127                                 '$method' => 'get',
2128                                 '$message' => t('Do you really want to delete this item?'),
2129                                 '$extra_inputs' => $inputs,
2130                                 '$confirm' => t('Yes'),
2131                                 '$confirm_url' => $query['base'],
2132                                 '$confirm_name' => 'confirmed',
2133                                 '$cancel' => t('Cancel'),
2134                         ));
2135                 }
2136                 // Now check how the user responded to the confirmation query
2137                 if ($_REQUEST['canceled']) {
2138                         goaway(App::get_baseurl() . '/' . $_SESSION['return_url']);
2139                 }
2140
2141                 logger('delete item: ' . $item['id'], LOGGER_DEBUG);
2142                 // delete the item
2143
2144                 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d",
2145                         dbesc(datetime_convert()),
2146                         dbesc(datetime_convert()),
2147                         intval($item['id'])
2148                 );
2149                 create_tags_from_item($item['id']);
2150                 create_files_from_item($item['id']);
2151                 delete_thread($item['id'], $item['parent-uri']);
2152
2153                 // clean up categories and tags so they don't end up as orphans
2154
2155                 $matches = false;
2156                 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
2157                 if ($cnt) {
2158                         foreach ($matches as $mtch) {
2159                                 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
2160                         }
2161                 }
2162
2163                 $matches = false;
2164
2165                 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
2166                 if ($cnt) {
2167                         foreach ($matches as $mtch) {
2168                                 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
2169                         }
2170                 }
2171
2172                 /*
2173                  * If item is a link to a photo resource, nuke all the associated photos
2174                  * (visitors will not have photo resources)
2175                  * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
2176                  * generate a resource-id and therefore aren't intimately linked to the item.
2177                  */
2178                 if (strlen($item['resource-id'])) {
2179                         q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
2180                                 dbesc($item['resource-id']),
2181                                 intval($item['uid'])
2182                         );
2183                         // ignore the result
2184                 }
2185
2186                 // If item is a link to an event, nuke the event record.
2187                 if (intval($item['event-id'])) {
2188                         q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d",
2189                                 intval($item['event-id']),
2190                                 intval($item['uid'])
2191                         );
2192                         // ignore the result
2193                 }
2194
2195                 // If item has attachments, drop them
2196                 foreach (explode(", ", $item['attach']) as $attach) {
2197                         preg_match("|attach/(\d+)|", $attach, $matches);
2198                         q("DELETE FROM `attach` WHERE `id` = %d AND `uid` = %d",
2199                                 intval($matches[1]),
2200                                 local_user()
2201                         );
2202                         // ignore the result
2203                 }
2204
2205
2206                 // clean up item_id and sign meta-data tables
2207
2208                 /*
2209                 /// @TODO Old code - caused very long queries and warning entries in the mysql logfiles:
2210
2211                 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
2212                         intval($item['id']),
2213                         intval($item['uid'])
2214                 );
2215
2216                 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
2217                         intval($item['id']),
2218                         intval($item['uid'])
2219                 );
2220                 */
2221
2222                 // The new code splits the queries since the mysql optimizer really has bad problems with subqueries
2223
2224                 // Creating list of parents
2225                 $r = q("SELECT `id` FROM `item` WHERE `parent` = %d AND `uid` = %d",
2226                         intval($item['id']),
2227                         intval($item['uid'])
2228                 );
2229
2230                 $parentid = "";
2231
2232                 foreach ($r as $row) {
2233                         if ($parentid != "") {
2234                                 $parentid .= ", ";
2235                         }
2236
2237                         $parentid .= $row["id"];
2238                 }
2239
2240                 // Now delete them
2241                 if ($parentid != "") {
2242                         $r = q("DELETE FROM `item_id` WHERE `iid` IN (%s)", dbesc($parentid));
2243                         $r = q("DELETE FROM `sign` WHERE `iid` IN (%s)", dbesc($parentid));
2244                 }
2245
2246                 // If it's the parent of a comment thread, kill all the kids
2247                 if ($item['uri'] == $item['parent-uri']) {
2248                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
2249                                 WHERE `parent-uri` = '%s' AND `uid` = %d ",
2250                                 dbesc(datetime_convert()),
2251                                 dbesc(datetime_convert()),
2252                                 dbesc($item['parent-uri']),
2253                                 intval($item['uid'])
2254                         );
2255                         create_tags_from_itemuri($item['parent-uri'], $item['uid']);
2256                         create_files_from_itemuri($item['parent-uri'], $item['uid']);
2257                         delete_thread_uri($item['parent-uri'], $item['uid']);
2258                         // ignore the result
2259                 } else {
2260                         // ensure that last-child is set in case the comment that had it just got wiped.
2261                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2262                                 dbesc(datetime_convert()),
2263                                 dbesc($item['parent-uri']),
2264                                 intval($item['uid'])
2265                         );
2266                         // who is the last child now?
2267                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d ORDER BY `edited` DESC LIMIT 1",
2268                                 dbesc($item['parent-uri']),
2269                                 intval($item['uid'])
2270                         );
2271                         if (dbm::is_result($r)) {
2272                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2273                                         intval($r[0]['id'])
2274                                 );
2275                         }
2276                 }
2277
2278                 $drop_id = intval($item['id']);
2279
2280                 // send the notification upstream/downstream as the case may be
2281
2282                 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $drop_id);
2283
2284                 if (! $interactive) {
2285                         return $owner;
2286                 }
2287                 goaway(App::get_baseurl() . '/' . $_SESSION['return_url']);
2288                 //NOTREACHED
2289         } else {
2290                 if (! $interactive) {
2291                         return 0;
2292                 }
2293                 notice( t('Permission denied.') . EOL);
2294                 goaway(App::get_baseurl() . '/' . $_SESSION['return_url']);
2295                 //NOTREACHED
2296         }
2297
2298 }
2299
2300
2301 function first_post_date($uid, $wall = false) {
2302         $r = q("SELECT `id`, `created` FROM `item`
2303                 WHERE `uid` = %d AND `wall` = %d AND `deleted` = 0 AND `visible` = 1 AND `moderated` = 0
2304                 AND `id` = `parent`
2305                 ORDER BY `created` ASC LIMIT 1",
2306                 intval($uid),
2307                 intval($wall ? 1 : 0)
2308         );
2309         if (dbm::is_result($r)) {
2310                 // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
2311                 return substr(datetime_convert('',date_default_timezone_get(), $r[0]['created']),0,10);
2312         }
2313         return false;
2314 }
2315
2316 /* modified posted_dates() {below} to arrange the list in years */
2317 function list_post_dates($uid, $wall) {
2318         $dnow = datetime_convert('',date_default_timezone_get(), 'now','Y-m-d');
2319
2320         $dthen = first_post_date($uid, $wall);
2321         if (! $dthen) {
2322                 return array();
2323         }
2324
2325         // Set the start and end date to the beginning of the month
2326         $dnow = substr($dnow, 0, 8) . '01';
2327         $dthen = substr($dthen, 0, 8) . '01';
2328
2329         $ret = array();
2330
2331         /*
2332          * Starting with the current month, get the first and last days of every
2333          * month down to and including the month of the first post
2334          */
2335         while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
2336                 $dyear = intval(substr($dnow, 0, 4));
2337                 $dstart = substr($dnow, 0, 8) . '01';
2338                 $dend = substr($dnow, 0, 8) . get_dim(intval($dnow), intval(substr($dnow, 5)));
2339                 $start_month = datetime_convert('', '', $dstart, 'Y-m-d');
2340                 $end_month = datetime_convert('', '', $dend, 'Y-m-d');
2341                 $str = day_translate(datetime_convert('', '', $dnow, 'F'));
2342                 if (!$ret[$dyear]) {
2343                         $ret[$dyear] = array();
2344                 }
2345                 $ret[$dyear][] = array($str, $end_month, $start_month);
2346                 $dnow = datetime_convert('', '', $dnow . ' -1 month', 'Y-m-d');
2347         }
2348         return $ret;
2349 }
2350
2351 function posted_dates($uid, $wall) {
2352         $dnow = datetime_convert('', date_default_timezone_get(), 'now', 'Y-m-d');
2353
2354         $dthen = first_post_date($uid, $wall);
2355         if (! $dthen) {
2356                 return array();
2357         }
2358
2359         // Set the start and end date to the beginning of the month
2360         $dnow = substr($dnow, 0, 8) . '01';
2361         $dthen = substr($dthen, 0, 8) . '01';
2362
2363         $ret = array();
2364         /*
2365          * Starting with the current month, get the first and last days of every
2366          * month down to and including the month of the first post
2367          */
2368         while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
2369                 $dstart = substr($dnow, 0, 8) . '01';
2370                 $dend = substr($dnow, 0, 8) . get_dim(intval($dnow), intval(substr($dnow, 5)));
2371                 $start_month = datetime_convert('', '', $dstart, 'Y-m-d');
2372                 $end_month = datetime_convert('', '', $dend, 'Y-m-d');
2373                 $str = day_translate(datetime_convert('', '', $dnow, 'F Y'));
2374                 $ret[] = array($str, $end_month, $start_month);
2375                 $dnow = datetime_convert('', '', $dnow . ' -1 month', 'Y-m-d');
2376         }
2377         return $ret;
2378 }
2379
2380
2381 function posted_date_widget($url, $uid, $wall) {
2382         $o = '';
2383
2384         if (! feature_enabled($uid, 'archives')) {
2385                 return $o;
2386         }
2387
2388         // For former Facebook folks that left because of "timeline"
2389         /*
2390          * @TODO old-lost code?
2391         if ($wall && intval(get_pconfig($uid, 'system', 'no_wall_archive_widget')))
2392                 return $o;
2393         */
2394
2395         $visible_years = get_pconfig($uid,'system','archive_visible_years');
2396         if (! $visible_years) {
2397                 $visible_years = 5;
2398         }
2399
2400         $ret = list_post_dates($uid, $wall);
2401
2402         if (! dbm::is_result($ret)) {
2403                 return $o;
2404         }
2405
2406         $cutoff_year = intval(datetime_convert('',date_default_timezone_get(), 'now', 'Y')) - $visible_years;
2407         $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
2408
2409         $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
2410                 '$title' => t('Archives'),
2411                 '$size' => $visible_years,
2412                 '$cutoff_year' => $cutoff_year,
2413                 '$cutoff' => $cutoff,
2414                 '$url' => $url,
2415                 '$dates' => $ret,
2416                 '$showmore' => t('show more')
2417
2418         ));
2419         return $o;
2420 }