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