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