From d473c3c500a39ce1efdf6902114f899644bcc002 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 9 Feb 2015 00:43:38 -0800 Subject: fix for service_plink() after observing it in the wild --- include/network.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/network.php b/include/network.php index 366ac0d24..a7127c1a2 100644 --- a/include/network.php +++ b/include/network.php @@ -1531,7 +1531,7 @@ function service_plink($contact, $guid) { $m = parse_url($contact['xchan_url']); if($m) { - $url = $scheme . '://' . $m['host'] . (($m['port']) ? ':' . $m['port'] : ''); + $url = $m['scheme'] . '://' . $m['host'] . (($m['port']) ? ':' . $m['port'] : ''); } else $url = 'https://' . substr($contact['xchan_addr'],strpos($contact['xchan_addr'],'@')+1); -- cgit v1.2.3 From e2aa0a273c112e01b2f5837f0bca7c7e8d8d4807 Mon Sep 17 00:00:00 2001 From: marijus Date: Mon, 9 Feb 2015 21:46:22 +0100 Subject: improve sql query --- include/attach.php | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) (limited to 'include') diff --git a/include/attach.php b/include/attach.php index f61fea9a5..f878a886f 100644 --- a/include/attach.php +++ b/include/attach.php @@ -1258,15 +1258,10 @@ function recursive_activity_recipients($allow_cid, $allow_gid, $deny_cid, $deny_ } function in_group($group_id) { - //TODO: make these two queries one with a join. - $x = q("SELECT id FROM groups WHERE hash = '%s'", + $r = q("SELECT xchan FROM group_member left join groups on group_member.gid = group.id WHERE hash = '%s' ", dbesc($group_id) ); - $r = q("SELECT xchan FROM group_member WHERE gid = %d", - intval($x[0]['id']) - ); - foreach($r as $ig) { $group_members[] = $ig['xchan']; } -- cgit v1.2.3 From 0e74ebc6a9f6ef6f8348a68d9ecee98795edd56b Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 9 Feb 2015 15:12:15 -0800 Subject: title missing sending to diaspora (which doesn't support titles but let's not go there). --- include/bb2diaspora.php | 21 ++------------------- 1 file changed, 2 insertions(+), 19 deletions(-) (limited to 'include') diff --git a/include/bb2diaspora.php b/include/bb2diaspora.php index 5c93ac3aa..fa3aa3aa2 100644 --- a/include/bb2diaspora.php +++ b/include/bb2diaspora.php @@ -271,22 +271,6 @@ function bb2diaspora_itemwallwall(&$item) { . $item['body']; } - // We have to do something similar for wall-to-wall comments. ITEM_WALL|ITEM_ORIGIN indicates that it was posted on this site. - // Regular matrix comments may have one of these bits set, but not both. - - // Update: this is getting triggered way too often and unnecessarily. Commenting out until we find a better solution. - // It's not an easy problem. For now we'll live with the mis-attributions, as wall to wall comments are much less frequent - // than wall-to-wall posts. - -// if(($item['mid'] != $item['parent_mid']) && ($item['author_xchan'] != $item['owner_xchan']) && (($item['item_flags'] & (ITEM_WALL|ITEM_ORIGIN)) == (ITEM_WALL|ITEM_ORIGIN)) && (is_array($item['author'])) && $item['author']['xchan_url'] && $item['author']['xchan_name'] && $item['author']['xchan_photo_m']) { -// logger('bb2diaspora_itemwallwall: wall to wall comment',LOGGER_DEBUG); - // post will come across with the owner's identity. Throw a preamble onto the post to indicate the true author. -// $item['body'] = "\n\n" -// . '[img]' . $item['author']['xchan_photo_m'] . '[/img]' -// . '[url=' . $item['author']['xchan_url'] . ']' . $item['author']['xchan_name'] . '[/url]' . "\n\n" -// . $item['body']; -// } - // $item['author'] might cause a surprise further down the line if it wasn't expected to be here. if(! $author_exists) @@ -311,8 +295,6 @@ function bb2diaspora_itembody($item,$force_update = false) { logger('bb2diaspora_itembody: cached '); $newitem = $item; $newitem['body'] = $meta['body']; -// this won't work - the post is now in markdown -// bb2diaspora_itemwallwall($newitem); return $newitem['body']; } } @@ -333,7 +315,8 @@ function bb2diaspora_itembody($item,$force_update = false) { bb2diaspora_itemwallwall($newitem); - $body = preg_replace('/\#\^http/i', 'http', $newitem['body']); + $title = $newitem['title']; + $body = preg_replace('/\#\^http/i', 'http', $newitem['body']); // protect tags and mentions from hijacking -- cgit v1.2.3 From 55c3c54ef6fe3f3d80df01c94d334bdfbf395683 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 9 Feb 2015 19:54:48 -0800 Subject: apply max_import_size to Diaspora posts --- include/diaspora.php | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) (limited to 'include') diff --git a/include/diaspora.php b/include/diaspora.php index 22574f9f8..4280d9d77 100755 --- a/include/diaspora.php +++ b/include/diaspora.php @@ -827,6 +827,12 @@ function diaspora_post($importer,$xml,$msg) { $body = scale_external_images($body); } + $maxlen = get_max_import_size(); + + if($maxlen && mb_strlen($body) > $maxlen) { + $body = mb_substr($body,0,$maxlen,'UTF-8'); + logger('message length exceeds max_import_size: truncated'); + } //WTF? FIXME // Add OEmbed and other information to the body @@ -1040,6 +1046,14 @@ function diaspora_reshare($importer,$xml,$msg) { //return; } + $maxlen = get_max_import_size(); + + if($maxlen && mb_strlen($body) > $maxlen) { + $body = mb_substr($body,0,$maxlen,'UTF-8'); + logger('message length exceeds max_import_size: truncated'); + } + + //if(! $body) { // logger('diaspora_reshare: empty body: source= ' . $x); // return; @@ -1354,6 +1368,15 @@ function diaspora_comment($importer,$xml,$msg) { $body = diaspora2bb($text); + + $maxlen = get_max_import_size(); + + if($maxlen && mb_strlen($body) > $maxlen) { + $body = mb_substr($body,0,$maxlen,'UTF-8'); + logger('message length exceeds max_import_size: truncated'); + } + + $datarray = array(); $tags = get_tags($body); @@ -1540,6 +1563,15 @@ function diaspora_conversation($importer,$xml,$msg) { $body = diaspora2bb($msg_text); + + $maxlen = get_max_import_size(); + + if($maxlen && mb_strlen($body) > $maxlen) { + $body = mb_substr($body,0,$maxlen,'UTF-8'); + logger('message length exceeds max_import_size: truncated'); + } + + $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid; $author_signature = base64_decode($msg_author_signature); @@ -1677,6 +1709,17 @@ function diaspora_message($importer,$xml,$msg) { $subject = $conversation['subject']; $body = diaspora2bb($msg_text); + + + $maxlen = get_max_import_size(); + + if($maxlen && mb_strlen($body) > $maxlen) { + $body = mb_substr($body,0,$maxlen,'UTF-8'); + logger('message length exceeds max_import_size: truncated'); + } + + + $message_id = $msg_diaspora_handle . ':' . $msg_guid; $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid; -- cgit v1.2.3 From c69494524590b7ffa07fcab6780c603ded2cb720 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 9 Feb 2015 21:18:50 -0800 Subject: like formatting for extended consensus items --- include/ItemObject.php | 23 +++++++++++++++++++++ include/conversation.php | 53 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) (limited to 'include') diff --git a/include/ItemObject.php b/include/ItemObject.php index 344664fd2..8f1112f6a 100644 --- a/include/ItemObject.php +++ b/include/ItemObject.php @@ -135,6 +135,28 @@ class Item extends BaseObject { $location = format_location($item); + + // process action responses - e.g. like/dislike/attend/agree/whatever + $response_verbs = array('like'); + if(feature_enabled($conv->get_profile_owner(),'dislike')) + $response_verbs[] = 'dislike'; + if($item['resource_type'] === 'event') { + $response_verbs[] = 'attendyes'; + $response_verbs[] = 'attendno'; + $response_verbs[] = 'attendmaybe'; + } + $consensus = (($item['item_flags'] & ITEM_CONSENSUS)? true : false); + if($consensus) { + $response_verbs[] = 'agree'; + $response_verbs[] = 'disagree'; + $response_verbs[] = 'abstain'; + } + + $responses = get_responses($conv_responses,$response_verbs,$this,$item); + + + $like_button_label = tt('Like','Likes',$like_count,'noun'); + $like_count = ((x($conv_responses['like'],$item['mid'])) ? $conv_responses['like'][$item['mid']] : ''); $like_list = ((x($conv_responses['like'],$item['mid'])) ? $conv_responses['like'][$item['mid'] . '-l'] : ''); if (count($like_list) > MAX_LIKERS) { @@ -307,6 +329,7 @@ class Item extends BaseObject { 'comment_count_txt' => $comment_count_txt, 'list_unseen_txt' => $list_unseen_txt, 'markseen' => t('Mark all seen'), + 'responses' => $responses, 'like_count' => $like_count, 'like_list' => $like_list, 'like_list_part' => $like_list_part, diff --git a/include/conversation.php b/include/conversation.php index 27b52ba6e..244c812ef 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -1629,3 +1629,56 @@ function profile_tabs($a, $is_owner=False, $nickname=Null){ return replace_macros($tpl,array('$tabs' => $arr['tabs'])); } + + +function get_responses($conv_responses,$response_verbs,$ob,$item) { + $ret = array(); + foreach($response_verbs as $v) { + $ret[$v] = array(); + $ret[$v]['count'] = ((x($conv_responses[$v],$item['mid'])) ? $conv_responses[$v][$item['mid']] : ''); + $ret[$v]['list'] = ((x($conv_responses[$v],$item['mid'])) ? $conv_responses[$v][$item['mid'] . '-l'] : ''); + if(count($ret[$v]['list']) > MAX_LIKERS) { + $ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS); + array_push($ret[$v]['list_part'], '' . t('View all') . ''); + } + else { + $ret[$v]['list_part'] = ''; + } + $ret[$v]['button'] = get_response_button_text($v,$ret[$v]['count']); + } + $ret['count'] = count($ret); + return $ret; +} + +function get_response_button_text($v,$count) { + switch($v) { + case 'like': + return tt('Like','Likes',$count,'noun'); + break; + case 'dislike': + return tt('Dislike','Dislikes',$count,'noun'); + break; + case 'attendyes': + return tt('Attending','Attending',$count,'noun'); + break; + case 'attendno': + return tt('Not Attending','Not Attending',$count,'noun'); + break; + case 'attendmaybe': + return tt('Undecided','Undecided',$count,'noun'); + break; + case 'agree': + return tt('Agree','Agrees',$count,'noun'); + break; + case 'agree': + return tt('Disagree','Disagrees',$count,'noun'); + break; + case 'abstain': + return tt('Abstain','Abstains',$count,'noun'); + break; + default: + return ''; + break; + } +} -- cgit v1.2.3 From 81e7b47b76e6cc72995e910190e4164d28ec5664 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 10 Feb 2015 00:11:37 -0800 Subject: more progress on event confirmations --- include/ItemObject.php | 9 +++++++-- include/conversation.php | 31 ++++++++++++++++++++++++++++--- 2 files changed, 35 insertions(+), 5 deletions(-) (limited to 'include') diff --git a/include/ItemObject.php b/include/ItemObject.php index 8f1112f6a..3638b2ffb 100644 --- a/include/ItemObject.php +++ b/include/ItemObject.php @@ -134,16 +134,19 @@ class Item extends BaseObject { $profile_name = $item['author']['xchan_name']; $location = format_location($item); - + $isevent = false; + $attend = null; // process action responses - e.g. like/dislike/attend/agree/whatever $response_verbs = array('like'); if(feature_enabled($conv->get_profile_owner(),'dislike')) $response_verbs[] = 'dislike'; - if($item['resource_type'] === 'event') { + if($item['obj_type'] === ACTIVITY_OBJ_EVENT) { $response_verbs[] = 'attendyes'; $response_verbs[] = 'attendno'; $response_verbs[] = 'attendmaybe'; + $isevent = true; + $attend = array( t('I will attend'), t('I will not attend'), t('I might attend')); } $consensus = (($item['item_flags'] & ITEM_CONSENSUS)? true : false); if($consensus) { @@ -275,6 +278,8 @@ class Item extends BaseObject { 'body' => $body, 'text' => strip_tags($body), 'id' => $this->get_id(), + 'isevent' => $isevent, + 'attend' => $attend, 'linktitle' => sprintf( t('View %s\'s profile - %s'), $profile_name, $item['author']['xchan_addr']), 'olinktitle' => sprintf( t('View %s\'s profile - %s'), $this->get_owner_name(), $item['owner']['xchan_addr']), 'llink' => $item['llink'], diff --git a/include/conversation.php b/include/conversation.php index 244c812ef..308b56586 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -402,7 +402,7 @@ function visible_activity($item) { // likes (etc.) can apply to other things besides posts. Check if they are post children, // in which case we handle them specially - $hidden_activities = array(ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_AGREE, ACTIVITY_DISAGREE, ACTIVITY_ABSTAIN); + $hidden_activities = array(ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_AGREE, ACTIVITY_DISAGREE, ACTIVITY_ABSTAIN, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE); foreach($hidden_activities as $act) { if((activity_match($item['verb'],$act)) && ($item['mid'] != $item['parent_mid'])) { return false; @@ -552,7 +552,7 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $ $items = $cb['items']; - $conv_responses = array(array('like'),array('dislike'),array('agree'),array('disagree'),array('abstain')); + $conv_responses = array(array('like'),array('dislike'),array('agree'),array('disagree'),array('abstain'),array('attendyes'),array('attendno'),array('attendmaybe')); // array with html for each thread (parent+comments) $threads = array(); @@ -784,10 +784,20 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $ if(feature_enabled($profile_owner, 'dislike')) like_puller($a, $item, $conv_responses, 'dislike'); + if($item['obj_type'] === ACTIVITY_OBJ_EVENT) { + like_puller($a, $item, $conv_responses, 'attendyes'); + like_puller($a, $item, $conv_responses, 'attendno'); + like_puller($a, $item, $conv_responses, 'attendmaybe'); + +logger('responses: ' . print_r($conv_responses,true)); + + } + like_puller($a, $item, $conv_responses, 'agree'); like_puller($a, $item, $conv_responses, 'disagree'); like_puller($a, $item, $conv_responses, 'abstain'); + if(! visible_activity($item)) { continue; } @@ -998,13 +1008,28 @@ function like_puller($a, $item, &$arr, $mode) { case 'unabstain': $verb = ACTIVITY_ABSTAIN; break; + case 'attendyes': + case 'unattendyes': + $verb = ACTIVITY_ATTEND; + break; + case 'attendno': + case 'unattendno': + $verb = ACTIVITY_ATTENDNO; + break; + case 'attendmaybe': + case 'unattendmaybe': + $verb = ACTIVITY_ATTENDMAYBE; + break; default: return; break; } +logger('verb: ' . $verb); +if($verb === ACTIVITY_ATTENDNO) + logger('item: ' . $item['verb']); if((activity_match($item['verb'], $verb)) && ($item['id'] != $item['parent'])) { - +logger('match:' . $verb); if($item['author']['xchan_url']) $url = chanlink_url($item['author']['xchan_url']); -- cgit v1.2.3 From f7cce634479bb95258209a6aadb9becd3c6b94a3 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 10 Feb 2015 00:44:34 -0800 Subject: cleanup event attendance - make sure it works in list mode. --- include/conversation.php | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) (limited to 'include') diff --git a/include/conversation.php b/include/conversation.php index 308b56586..b777e479b 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -784,15 +784,9 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $ if(feature_enabled($profile_owner, 'dislike')) like_puller($a, $item, $conv_responses, 'dislike'); - if($item['obj_type'] === ACTIVITY_OBJ_EVENT) { - like_puller($a, $item, $conv_responses, 'attendyes'); - like_puller($a, $item, $conv_responses, 'attendno'); - like_puller($a, $item, $conv_responses, 'attendmaybe'); - -logger('responses: ' . print_r($conv_responses,true)); - - } - + like_puller($a, $item, $conv_responses, 'attendyes'); + like_puller($a, $item, $conv_responses, 'attendno'); + like_puller($a, $item, $conv_responses, 'attendmaybe'); like_puller($a, $item, $conv_responses, 'agree'); like_puller($a, $item, $conv_responses, 'disagree'); like_puller($a, $item, $conv_responses, 'abstain'); @@ -1024,12 +1018,9 @@ function like_puller($a, $item, &$arr, $mode) { return; break; } -logger('verb: ' . $verb); -if($verb === ACTIVITY_ATTENDNO) - logger('item: ' . $item['verb']); if((activity_match($item['verb'], $verb)) && ($item['id'] != $item['parent'])) { -logger('match:' . $verb); + if($item['author']['xchan_url']) $url = chanlink_url($item['author']['xchan_url']); -- cgit v1.2.3 From 4632d30a786863d4ecb33fc651f49076d0006386 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 10 Feb 2015 14:47:09 -0800 Subject: more attendance --- include/conversation.php | 142 +++++++++++++++++++++++------------------------ 1 file changed, 69 insertions(+), 73 deletions(-) (limited to 'include') diff --git a/include/conversation.php b/include/conversation.php index b777e479b..4da6636fa 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -552,7 +552,12 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $ $items = $cb['items']; - $conv_responses = array(array('like'),array('dislike'),array('agree'),array('disagree'),array('abstain'),array('attendyes'),array('attendno'),array('attendmaybe')); + $conv_responses = array( + 'like' => array('title' => t('Likes','title')),'dislike' => array('title' => t('Dislikes','title')), + 'agree' => array('title' => t('Agree','title')),'disagree' => array('title' => t('Disagree','title')), 'abstain' => array('title' => t('Abstain','title')), + 'attendyes' => array('title' => t('Attending','title')), 'attendno' => array('title' => t('Not attending','title')), 'attendmaybe' => array('title' => t('Might attend','title')) + ); + // array with html for each thread (parent+comments) $threads = array(); @@ -779,18 +784,7 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $ } } - like_puller($a, $item, $conv_responses, 'like'); - - if(feature_enabled($profile_owner, 'dislike')) - like_puller($a, $item, $conv_responses, 'dislike'); - - like_puller($a, $item, $conv_responses, 'attendyes'); - like_puller($a, $item, $conv_responses, 'attendno'); - like_puller($a, $item, $conv_responses, 'attendmaybe'); - like_puller($a, $item, $conv_responses, 'agree'); - like_puller($a, $item, $conv_responses, 'disagree'); - like_puller($a, $item, $conv_responses, 'abstain'); - + builtin_activity_puller($item, $conv_responses); if(! visible_activity($item)) { continue; @@ -968,81 +962,82 @@ function item_photo_menu($item){ } /** - * @brief Returns a like/dislike entry. - * It gives back a HTML link to the channel that liked/disliked. + * @brief Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.) + * Increments the count of each matching activity and adds a link to the author as needed. * * @param array $a (not used) * @param array $item - * @param array &$arr - * @param string $mode like/dislike + * @param array &$conv_responses (already created with builtin activity structure) * @return void */ -function like_puller($a, $item, &$arr, $mode) { +function builtin_activity_puller($item, &$conv_responses) { - $url = ''; - switch($mode) { - case 'like': - case 'unlike': - $verb = ACTIVITY_LIKE; - break; - case 'dislike': - case 'undislike': - $verb = ACTIVITY_DISLIKE; - break; - case 'agree': - case 'unagree': - $verb = ACTIVITY_AGREE; - break; - case 'disagree': - case 'undisagree': - $verb = ACTIVITY_DISAGREE; - break; - case 'abstain': - case 'unabstain': - $verb = ACTIVITY_ABSTAIN; - break; - case 'attendyes': - case 'unattendyes': - $verb = ACTIVITY_ATTEND; - break; - case 'attendno': - case 'unattendno': - $verb = ACTIVITY_ATTENDNO; - break; - case 'attendmaybe': - case 'unattendmaybe': - $verb = ACTIVITY_ATTENDMAYBE; - break; - default: - return; - break; - } - if((activity_match($item['verb'], $verb)) && ($item['id'] != $item['parent'])) { + foreach($conv_responses as $mode => $v) { - if($item['author']['xchan_url']) - $url = chanlink_url($item['author']['xchan_url']); + $url = ''; - if(! $item['thr_parent']) - $item['thr_parent'] = $item['parent_mid']; + switch($mode) { + case 'like': + $verb = ACTIVITY_LIKE; + break; + case 'dislike': + $verb = ACTIVITY_DISLIKE; + break; + case 'agree': + $verb = ACTIVITY_AGREE; + break; + case 'disagree': + $verb = ACTIVITY_DISAGREE; + break; + case 'abstain': + $verb = ACTIVITY_ABSTAIN; + break; + case 'attendyes': + $verb = ACTIVITY_ATTEND; + break; + case 'attendno': + $verb = ACTIVITY_ATTENDNO; + break; + case 'attendmaybe': + $verb = ACTIVITY_ATTENDMAYBE; + break; + default: + return; + break; + } - if(! ((isset($arr[$mode][$item['thr_parent'] . '-l'])) && (is_array($arr[$mode][$item['thr_parent'] . '-l'])))) - $arr[$mode][$item['thr_parent'] . '-l'] = array(); - if(! isset($arr[$mode][$item['thr_parent']])) - $arr[$mode][$item['thr_parent']] = 1; - else - $arr[$mode][$item['thr_parent']] ++; - $name = (($item['author']['xchan_name']) ? $item['author']['xchan_name'] : t('Unknown')); + if((activity_match($item['verb'], $verb)) && ($item['id'] != $item['parent'])) { - if($url) - $arr[$mode][$item['thr_parent'] . '-l'][] = '' . $name . ''; - else - $arr[$mode][$item['thr_parent'] . '-l'][] = '' . $name . ''; + + $name = (($item['author']['xchan_name']) ? $item['author']['xchan_name'] : t('Unknown')); + $url = (($item['author']['xchan_url']) + ? '' . $name . '' + : '' . $name . '' + ); + + if(! $item['thr_parent']) + $item['thr_parent'] = $item['parent_mid']; + + if(! ((isset($conv_responses[$mode][$item['thr_parent'] . '-l'])) + && (is_array($conv_responses[$mode][$item['thr_parent'] . '-l'])))) + $conv_responses[$mode][$item['thr_parent'] . '-l'] = array(); + + // only list each unique author once + if(in_array($url,$conv_responses[$mode][$item['thr_parent'] . '-l'])) + continue; + + if(! isset($conv_responses[$mode][$item['thr_parent']])) + $conv_responses[$mode][$item['thr_parent']] = 1; + else + $conv_responses[$mode][$item['thr_parent']] ++; + + $conv_responses[$mode][$item['thr_parent'] . '-l'][] = $url; + } } - return; } // Format the like/dislike text for a profile item @@ -1662,6 +1657,7 @@ function get_responses($conv_responses,$response_verbs,$ob,$item) { $ret[$v]['list_part'] = ''; } $ret[$v]['button'] = get_response_button_text($v,$ret[$v]['count']); + $ret[$v]['title'] = $conv_responses[$v]['title']; } $ret['count'] = count($ret); return $ret; -- cgit v1.2.3 From 79da33dafdac1427ac07b4414a5da5f9f3a2b03d Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 10 Feb 2015 17:49:46 -0800 Subject: improvements in duplicate like detection, especially w/r/t event participation --- include/Contact.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/Contact.php b/include/Contact.php index de3a75bb7..9490fd2da 100644 --- a/include/Contact.php +++ b/include/Contact.php @@ -374,7 +374,7 @@ function mark_orphan_hubsxchans() { if($dirmode == DIRECTORY_MODE_NORMAL) return; - $r = q("update hubloc set hubloc_status = (hubloc_status | %d) where not (hubloc_status & %d)>0 + $r = q("update hubloc set hubloc_status = (hubloc_status | %d) where (hubloc_status & %d) = 0 and hubloc_network = 'zot' and hubloc_connected < %s - interval %s", intval(HUBLOC_OFFLINE), intval(HUBLOC_OFFLINE), -- cgit v1.2.3 From 79223b6b3d38bfbfb3a6d9530f6ccc5b7bb096c8 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 10 Feb 2015 19:10:18 -0800 Subject: item voting tools --- include/ItemObject.php | 4 ++++ include/conversation.php | 5 +++++ include/features.php | 1 + include/items.php | 4 ++-- 4 files changed, 12 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/ItemObject.php b/include/ItemObject.php index 3638b2ffb..7f5ee83a3 100644 --- a/include/ItemObject.php +++ b/include/ItemObject.php @@ -148,11 +148,13 @@ class Item extends BaseObject { $isevent = true; $attend = array( t('I will attend'), t('I will not attend'), t('I might attend')); } + $consensus = (($item['item_flags'] & ITEM_CONSENSUS)? true : false); if($consensus) { $response_verbs[] = 'agree'; $response_verbs[] = 'disagree'; $response_verbs[] = 'abstain'; + $conlabels = array( t('I agree'), t('I disagree'), t('I abstain')); } $responses = get_responses($conv_responses,$response_verbs,$this,$item); @@ -280,6 +282,8 @@ class Item extends BaseObject { 'id' => $this->get_id(), 'isevent' => $isevent, 'attend' => $attend, + 'consensus' => $consensus, + 'conlabels' => $conlabels, 'linktitle' => sprintf( t('View %s\'s profile - %s'), $profile_name, $item['author']['xchan_addr']), 'olinktitle' => sprintf( t('View %s\'s profile - %s'), $this->get_owner_name(), $item['owner']['xchan_addr']), 'llink' => $item['llink'], diff --git a/include/conversation.php b/include/conversation.php index 4da6636fa..2c89249cb 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -1085,6 +1085,8 @@ function status_editor($a,$x,$popup=false) { // if(feature_enabled(local_channel(),'richtext')) // $plaintext = false; + $voting = feature_enabled(local_channel(),'consensus_tools'); + $mimeselect = ''; if(array_key_exists('mimetype',$x) && $x['mimetype']) { if($x['mimetype'] != 'text/bbcode') @@ -1176,6 +1178,9 @@ function status_editor($a,$x,$popup=false) { '$shortaudio' => t('audio link'), '$setloc' => t('Set your location'), '$shortsetloc' => t('set location'), + '$voting' => t('Toggle voting'), + '$feature_voting' => $voting, + '$consensus' => 0, '$noloc' => ((get_pconfig($x['profile_uid'],'system','use_browser_location')) ? t('Clear browser location') : ''), '$shortnoloc' => t('clear location'), '$title' => ((x($x,'title')) ? htmlspecialchars($x['title'], ENT_COMPAT,'UTF-8') : ''), diff --git a/include/features.php b/include/features.php index 6b4bc34c6..fc14858a8 100644 --- a/include/features.php +++ b/include/features.php @@ -60,6 +60,7 @@ function get_features() { array('large_photos', t('Large Photos'), t('Include large (640px) photo thumbnails in posts. If not enabled, use small (320px) photo thumbnails'),false), array('channel_sources', t('Channel Sources'), t('Automatically import channel content from other channels or feeds'),false), array('content_encrypt', t('Even More Encryption'), t('Allow optional encryption of content end-to-end with a shared secret key'),false), + array('consensus_tools', t('Enable voting tools'), t('Provide a class of post which others can vote on'),false), array('adult_photo_flagging', t('Flag Adult Photos'), t('Provide photo edit option to hide adult photos from default album view'),false), ), diff --git a/include/items.php b/include/items.php index 0b2106572..2207635b6 100755 --- a/include/items.php +++ b/include/items.php @@ -843,9 +843,9 @@ function get_item_elements($x) { if(array_key_exists('flags',$x) && in_array('deleted',$x['flags'])) - $arr['item_restrict'] = ITEM_DELETED; + $arr['item_restrict'] |= ITEM_DELETED; if(array_key_exists('flags',$x) && in_array('hidden',$x['flags'])) - $arr['item_restrict'] = ITEM_HIDDEN; + $arr['item_restrict'] |= ITEM_HIDDEN; // Here's the deal - the site might be down or whatever but if there's a new person you've never // seen before sending stuff to your stream, we MUST be able to look them up and import their data from their -- cgit v1.2.3 From 149a588b11dae7b21f24e728be45fa04224bacd3 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 10 Feb 2015 20:21:54 -0800 Subject: ensure we have permission before displaying buttons --- include/ItemObject.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/ItemObject.php b/include/ItemObject.php index 7f5ee83a3..9dc364f9e 100644 --- a/include/ItemObject.php +++ b/include/ItemObject.php @@ -141,7 +141,7 @@ class Item extends BaseObject { $response_verbs = array('like'); if(feature_enabled($conv->get_profile_owner(),'dislike')) $response_verbs[] = 'dislike'; - if($item['obj_type'] === ACTIVITY_OBJ_EVENT) { + if($item['obj_type'] === ACTIVITY_OBJ_EVENT && $this->is_commentable) { $response_verbs[] = 'attendyes'; $response_verbs[] = 'attendno'; $response_verbs[] = 'attendmaybe'; @@ -149,7 +149,7 @@ class Item extends BaseObject { $attend = array( t('I will attend'), t('I will not attend'), t('I might attend')); } - $consensus = (($item['item_flags'] & ITEM_CONSENSUS)? true : false); + $consensus = ((($item['item_flags'] & ITEM_CONSENSUS) && $this->is_commentable) ? true : false); if($consensus) { $response_verbs[] = 'agree'; $response_verbs[] = 'disagree'; -- cgit v1.2.3 From 583af02f71f17039202a2e4009a3ab8586774663 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 10 Feb 2015 20:43:04 -0800 Subject: fix permissions --- include/ItemObject.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/ItemObject.php b/include/ItemObject.php index 9dc364f9e..ff7da2418 100644 --- a/include/ItemObject.php +++ b/include/ItemObject.php @@ -141,7 +141,7 @@ class Item extends BaseObject { $response_verbs = array('like'); if(feature_enabled($conv->get_profile_owner(),'dislike')) $response_verbs[] = 'dislike'; - if($item['obj_type'] === ACTIVITY_OBJ_EVENT && $this->is_commentable) { + if($item['obj_type'] === ACTIVITY_OBJ_EVENT && $this->is_commentable()) { $response_verbs[] = 'attendyes'; $response_verbs[] = 'attendno'; $response_verbs[] = 'attendmaybe'; @@ -149,7 +149,7 @@ class Item extends BaseObject { $attend = array( t('I will attend'), t('I will not attend'), t('I might attend')); } - $consensus = ((($item['item_flags'] & ITEM_CONSENSUS) && $this->is_commentable) ? true : false); + $consensus = ((($item['item_flags'] & ITEM_CONSENSUS) && $this->is_commentable()) ? true : false); if($consensus) { $response_verbs[] = 'agree'; $response_verbs[] = 'disagree'; -- cgit v1.2.3 From e8bdf2b8d741354fd479bd5fc31f704e2c6f6c88 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 10 Feb 2015 21:21:18 -0800 Subject: more permissions tweaking --- include/ItemObject.php | 21 ++++++++++++++++----- include/conversation.php | 3 +++ 2 files changed, 19 insertions(+), 5 deletions(-) (limited to 'include') diff --git a/include/ItemObject.php b/include/ItemObject.php index ff7da2418..c429a0131 100644 --- a/include/ItemObject.php +++ b/include/ItemObject.php @@ -136,30 +136,40 @@ class Item extends BaseObject { $location = format_location($item); $isevent = false; $attend = null; + $canvote = false; // process action responses - e.g. like/dislike/attend/agree/whatever $response_verbs = array('like'); if(feature_enabled($conv->get_profile_owner(),'dislike')) $response_verbs[] = 'dislike'; - if($item['obj_type'] === ACTIVITY_OBJ_EVENT && $this->is_commentable()) { + if($item['obj_type'] === ACTIVITY_OBJ_EVENT) { $response_verbs[] = 'attendyes'; $response_verbs[] = 'attendno'; $response_verbs[] = 'attendmaybe'; - $isevent = true; - $attend = array( t('I will attend'), t('I will not attend'), t('I might attend')); + if($this->is_commentable()) { + $isevent = true; + $attend = array( t('I will attend'), t('I will not attend'), t('I might attend')); + } } - $consensus = ((($item['item_flags'] & ITEM_CONSENSUS) && $this->is_commentable()) ? true : false); + $consensus = (($item['item_flags'] & ITEM_CONSENSUS) ? true : false); if($consensus) { $response_verbs[] = 'agree'; $response_verbs[] = 'disagree'; $response_verbs[] = 'abstain'; - $conlabels = array( t('I agree'), t('I disagree'), t('I abstain')); + if($this->is_commentable()) { + $conlabels = array( t('I agree'), t('I disagree'), t('I abstain')); + $canvote = true; + } } + if(! feature_enabled($conv->get_profile_owner(),'dislike')) + unset($conv_responses['dislike']); + $responses = get_responses($conv_responses,$response_verbs,$this,$item); + $like_button_label = tt('Like','Likes',$like_count,'noun'); $like_count = ((x($conv_responses['like'],$item['mid'])) ? $conv_responses['like'][$item['mid']] : ''); @@ -284,6 +294,7 @@ class Item extends BaseObject { 'attend' => $attend, 'consensus' => $consensus, 'conlabels' => $conlabels, + 'canvote' => $canvote, 'linktitle' => sprintf( t('View %s\'s profile - %s'), $profile_name, $item['author']['xchan_addr']), 'olinktitle' => sprintf( t('View %s\'s profile - %s'), $this->get_owner_name(), $item['owner']['xchan_addr']), 'llink' => $item['llink'], diff --git a/include/conversation.php b/include/conversation.php index 2c89249cb..addae3a9f 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -1038,6 +1038,7 @@ function builtin_activity_puller($item, &$conv_responses) { $conv_responses[$mode][$item['thr_parent'] . '-l'][] = $url; } } + } // Format the like/dislike text for a profile item @@ -1648,6 +1649,7 @@ function profile_tabs($a, $is_owner=False, $nickname=Null){ function get_responses($conv_responses,$response_verbs,$ob,$item) { + $ret = array(); foreach($response_verbs as $v) { $ret[$v] = array(); @@ -1665,6 +1667,7 @@ function get_responses($conv_responses,$response_verbs,$ob,$item) { $ret[$v]['title'] = $conv_responses[$v]['title']; } $ret['count'] = count($ret); +//logger('ret: ' . print_r($ret,true)); return $ret; } -- cgit v1.2.3 From 3f76cbf40b57b34f32a64435ca125c0576985c34 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 11 Feb 2015 01:53:17 -0800 Subject: cut/paste typo --- include/conversation.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/conversation.php b/include/conversation.php index addae3a9f..0af603ca9 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -1691,7 +1691,7 @@ function get_response_button_text($v,$count) { case 'agree': return tt('Agree','Agrees',$count,'noun'); break; - case 'agree': + case 'disagree': return tt('Disagree','Disagrees',$count,'noun'); break; case 'abstain': -- cgit v1.2.3 From 499841a72253e81eff9e47b902bbec73debbfe1b Mon Sep 17 00:00:00 2001 From: marijus Date: Wed, 11 Feb 2015 10:54:43 +0100 Subject: typo agree->disagree --- include/conversation.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/conversation.php b/include/conversation.php index addae3a9f..0af603ca9 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -1691,7 +1691,7 @@ function get_response_button_text($v,$count) { case 'agree': return tt('Agree','Agrees',$count,'noun'); break; - case 'agree': + case 'disagree': return tt('Disagree','Disagrees',$count,'noun'); break; case 'abstain': -- cgit v1.2.3 From b86ed864aa88ddb7e1792151ed59d3c6768752e8 Mon Sep 17 00:00:00 2001 From: marijus Date: Wed, 11 Feb 2015 12:09:04 +0100 Subject: to get the correct total count we should probably only count the arrays with count key set --- include/conversation.php | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'include') diff --git a/include/conversation.php b/include/conversation.php index 0af603ca9..3db8d7204 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -1666,8 +1666,17 @@ function get_responses($conv_responses,$response_verbs,$ob,$item) { $ret[$v]['button'] = get_response_button_text($v,$ret[$v]['count']); $ret[$v]['title'] = $conv_responses[$v]['title']; } - $ret['count'] = count($ret); + + $count = 0; + foreach($ret as $key) { + if ($key['count'] == true) + $count++; + } + + $ret['count'] = $count; + //logger('ret: ' . print_r($ret,true)); + return $ret; } -- cgit v1.2.3 From 8c061f143f7e019fdea3a2a03d96fc4ec8e39edd Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 11 Feb 2015 15:26:35 -0800 Subject: more efficient processing of response activities, plus a proof of concept fix for the problem of receiving a delete notification before we actually get the item which we're supposed to delete. --- include/conversation.php | 6 +++++ include/items.php | 11 +++++++-- include/zot.php | 61 ++++++++++++++++++++++++++++++++++-------------- 3 files changed, 59 insertions(+), 19 deletions(-) (limited to 'include') diff --git a/include/conversation.php b/include/conversation.php index 0af603ca9..ea7719d4b 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -972,7 +972,10 @@ function item_photo_menu($item){ */ function builtin_activity_puller($item, &$conv_responses) { + // if this item is a post or comment there's nothing for us to do here, just return. + if(activity_match($item['verb'],ACTIVITY_POST)) + return; foreach($conv_responses as $mode => $v) { @@ -1036,6 +1039,9 @@ function builtin_activity_puller($item, &$conv_responses) { $conv_responses[$mode][$item['thr_parent']] ++; $conv_responses[$mode][$item['thr_parent'] . '-l'][] = $url; + + // there can only be one activity verb per item so if we found anything, we can stop looking + $return; } } diff --git a/include/items.php b/include/items.php index 2207635b6..de69a0f81 100755 --- a/include/items.php +++ b/include/items.php @@ -2280,9 +2280,16 @@ function item_store($arr,$allow_exec = false) { ); - send_status_notifications($current_post,$arr); + // If _creating_ a deleted item, don't propagate it further or send out notifications. + // We need to store the item details just in case the delete came in before the original post, + // so that we have an item in the DB that's marked deleted and won't store a fresh post + // that isn't aware that we were already told to delete it. + + if(! ($arr['item_restrict'] & ITEM_DELETED)) { + send_status_notifications($current_post,$arr); + tag_deliver($arr['uid'],$current_post); + } - tag_deliver($arr['uid'],$current_post); $ret['success'] = true; $ret['item_id'] = $current_post; diff --git a/include/zot.php b/include/zot.php index 7e9a6ee54..7fd6f0d4a 100644 --- a/include/zot.php +++ b/include/zot.php @@ -1576,6 +1576,12 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque // remove_community_tag is a no-op if this isn't a community tag activity remove_community_tag($sender,$arr,$channel['channel_id']); + // set these just in case we need to store a fresh copy of the deleted post. + // This could happen if the delete got here before the original post did. + + $arr['aid'] = $channel['channel_account_id']; + $arr['uid'] = $channel['channel_id']; + $item_id = delete_imported_item($sender,$arr,$channel['channel_id']); $result[] = array($d['hash'],(($item_id) ? 'deleted' : 'delete_failed'),$channel['channel_name'] . ' <' . $channel['channel_address'] . '@' . get_app()->get_hostname() . '>',$arr['mid']); @@ -1725,35 +1731,56 @@ function delete_imported_item($sender,$item,$uid) { logger('delete_imported_item invoked',LOGGER_DEBUG); - $r = q("select id, item_restrict from item where ( author_xchan = '%s' or owner_xchan = '%s' or source_xchan = '%s' ) - and mid = '%s' and uid = %d limit 1", - dbesc($sender['hash']), - dbesc($sender['hash']), - dbesc($sender['hash']), + $ownership_valid = false; + $item_found = false; + $post_id = 0; + + $r = q("select id, item_restrict, author_xchan, owner_xchan, source_xchan from item where mid = '%s' and uid = %d limit 1", dbesc($item['mid']), intval($uid) ); + if($r) { + if($r[0]['author_xchan'] === $sender['hash'] || $r[0]['owner_xchan'] === $sender['hash'] || $r[0]['source_xchan'] === $sender['hash']) + $ownership_valid = true; + $post_id = $r[0]['id']; + $item_found = true; + } + else { - if(! $r) { + // perhaps the item is still in transit and the delete notification got here before the actual item did. Store it with the deleted flag set. + // item_store() won't try to deliver any notifications or start delivery chains if this flag is set. + // This means we won't end up with potentially even more delivery threads trying to push this delete notification. + // But this will ensure that if the (undeleted) original post comes in at a later date, we'll reject it because it will have an older timestamp. + + logger('delete received for non-existent item - storing item data.'); + if($arr['author_xchan'] === $sender['hash'] || $arr['owner_xchan'] === $sender['hash'] || $arr['source_xchan'] === $sender['hash']) { + $ownership_valid = true; + $item_result = item_store($arr); + $post_id = $item_result['item_id']; + } + } + + if($ownership_valid == false) { logger('delete_imported_item: failed: ownership issue'); return false; } - if($r[0]['item_restrict'] & ITEM_DELETED) { - logger('delete_imported_item: item was already deleted'); - return false; - } + if($item_found) { + if($r[0]['item_restrict'] & ITEM_DELETED) { + logger('delete_imported_item: item was already deleted'); + return false; + } - require_once('include/items.php'); + require_once('include/items.php'); - // Use phased deletion to set the deleted flag, call both tag_deliver and the notifier to notify downstream channels - // and then clean up after ourselves with a cron job after several days to do the delete_item_lowlevel() (DROPITEM_PHASE2). + // Use phased deletion to set the deleted flag, call both tag_deliver and the notifier to notify downstream channels + // and then clean up after ourselves with a cron job after several days to do the delete_item_lowlevel() (DROPITEM_PHASE2). - drop_item($r[0]['id'],false, DROPITEM_PHASE1); - - tag_deliver($uid,$r[0]['id']); + drop_item($post_id,false, DROPITEM_PHASE1); + tag_deliver($uid,$post_id); + } - return $r[0]['id']; + return $post_id; } function process_mail_delivery($sender,$arr,$deliveries) { -- cgit v1.2.3 From c62d605608ea3cfa0430e007fe6bc7df5fa0d25f Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 11 Feb 2015 16:11:21 -0800 Subject: well that was certainly fun. And the reason why likes and other acitivity deletions weren't propagating. Hopefully this is the last reason and there aren't more lurking further down the chain. --- include/zot.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'include') diff --git a/include/zot.php b/include/zot.php index 7fd6f0d4a..62e45b2b3 100644 --- a/include/zot.php +++ b/include/zot.php @@ -1582,7 +1582,7 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque $arr['aid'] = $channel['channel_account_id']; $arr['uid'] = $channel['channel_id']; - $item_id = delete_imported_item($sender,$arr,$channel['channel_id']); + $item_id = delete_imported_item($sender,$arr,$channel['channel_id'],$relay); $result[] = array($d['hash'],(($item_id) ? 'deleted' : 'delete_failed'),$channel['channel_name'] . ' <' . $channel['channel_address'] . '@' . get_app()->get_hostname() . '>',$arr['mid']); if($relay && $item_id) { @@ -1727,7 +1727,7 @@ function update_imported_item($sender,$item,$uid) { } -function delete_imported_item($sender,$item,$uid) { +function delete_imported_item($sender,$item,$uid,$relay) { logger('delete_imported_item invoked',LOGGER_DEBUG); @@ -1768,7 +1768,8 @@ function delete_imported_item($sender,$item,$uid) { if($item_found) { if($r[0]['item_restrict'] & ITEM_DELETED) { logger('delete_imported_item: item was already deleted'); - return false; + if(! $relay) + return false; } require_once('include/items.php'); -- cgit v1.2.3 From 2b2fa5a973a2c2b97b2689b926fe2ae6bca3685d Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 11 Feb 2015 20:38:06 -0800 Subject: issue #843 --- include/attach.php | 4 ++-- include/items.php | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/attach.php b/include/attach.php index f878a886f..5ed2cf6d2 100644 --- a/include/attach.php +++ b/include/attach.php @@ -65,10 +65,10 @@ function z_mime_content_type($filename) { 'mov' => 'video/quicktime', 'ogg' => 'application/ogg', 'opus' => 'audio/ogg', - 'webm' => 'audio/webm', 'webm' => 'video/webm', - 'mp4' => 'audio/mp4', +// 'webm' => 'audio/webm', 'mp4' => 'video/mp4', +// 'mp4' => 'audio/mp4', // adobe 'pdf' => 'application/pdf', diff --git a/include/items.php b/include/items.php index de69a0f81..deaed18e1 100755 --- a/include/items.php +++ b/include/items.php @@ -2720,6 +2720,9 @@ function tag_deliver($uid,$item_id) { if($obj['id'] !== $u[0]['channel_hash']) $poke_notify = false; } + if($item['item_restrict'] & ITEM_DELETED) + $poke_notify = false; + $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1)); if($poke_notify) { -- cgit v1.2.3 From 6ec44793b34fb7473d5ccb7da7a7318daec8e415 Mon Sep 17 00:00:00 2001 From: Alexandre Hannud Abdo Date: Thu, 12 Feb 2015 05:44:24 -0200 Subject: Dot not trim body in order to avoid issues with signature checks --- include/items.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/items.php b/include/items.php index deaed18e1..91fa1d70a 100755 --- a/include/items.php +++ b/include/items.php @@ -1945,7 +1945,7 @@ function item_store($arr,$allow_exec = false) { $arr['title'] = ((array_key_exists('title',$arr) && strlen($arr['title'])) ? trim($arr['title']) : ''); - $arr['body'] = ((array_key_exists('body',$arr) && strlen($arr['body'])) ? trim($arr['body']) : ''); + $arr['body'] = ((array_key_exists('body',$arr) && strlen($arr['body'])) ? $arr['body'] : ''); $arr['diaspora_meta'] = ((x($arr,'diaspora_meta')) ? $arr['diaspora_meta'] : ''); $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : ''); @@ -2451,7 +2451,7 @@ function item_store_update($arr,$allow_exec = false) { $arr['item_private'] = ((array_key_exists('item_private',$arr)) ? intval($arr['item_private']) : $orig[0]['item_private']); $arr['title'] = ((array_key_exists('title',$arr) && strlen($arr['title'])) ? trim($arr['title']) : ''); - $arr['body'] = ((array_key_exists('body',$arr) && strlen($arr['body'])) ? trim($arr['body']) : ''); + $arr['body'] = ((array_key_exists('body',$arr) && strlen($arr['body'])) ? $arr['body'] : ''); $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : $orig[0]['attach']); $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : $orig[0]['app']); // $arr['item_restrict'] = ((x($arr,'item_restrict')) ? intval($arr['item_restrict']) : $orig[0]['item_restrict'] ); -- cgit v1.2.3 From da2349bb6a85d13f0aa29046bef3021cf0c884ba Mon Sep 17 00:00:00 2001 From: friendica Date: Thu, 12 Feb 2015 17:45:25 -0800 Subject: provide relief to sites that are severely impacted by the slow ITEM_UNSEEN searches. This does not incorporate any other flag optimisations as that will require a major DB update and possibly involve significant downtime. This is just to bite off a little chunk now and provide some much needed relief. --- include/ItemObject.php | 2 +- include/api.php | 5 +---- include/attach.php | 4 +++- include/diaspora.php | 4 ++-- include/items.php | 9 ++++----- include/notify.php | 2 +- 6 files changed, 12 insertions(+), 14 deletions(-) (limited to 'include') diff --git a/include/ItemObject.php b/include/ItemObject.php index c429a0131..136e08eb7 100644 --- a/include/ItemObject.php +++ b/include/ItemObject.php @@ -612,7 +612,7 @@ class Item extends BaseObject { if((! visible_activity($child->data)) || array_key_exists('author_blocked',$child->data)) { continue; } - if($child->data['item_flags'] & ITEM_UNSEEN) + if(intval($child->data['item_unseen'])) $total ++; } } diff --git a/include/api.php b/include/api.php index d00cdcf8a..d5c2a429c 100644 --- a/include/api.php +++ b/include/api.php @@ -1004,10 +1004,7 @@ require_once('include/items.php'); // at the network timeline just mark everything seen. if (api_user() == $user_info['uid']) { - $r = q("UPDATE `item` SET item_flags = ( item_flags & ~%d ) - WHERE (item_flags & %d)>0 and uid = %d", - intval(ITEM_UNSEEN), - intval(ITEM_UNSEEN), + $r = q("UPDATE `item` SET item_unseen = 0 where item_unseen = 1 and uid = %d", intval($user_info['uid']) ); } diff --git a/include/attach.php b/include/attach.php index 5ed2cf6d2..3350a591e 100644 --- a/include/attach.php +++ b/include/attach.php @@ -998,7 +998,8 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $objtype = ACTIVITY_OBJ_FILE; - $item_flags = ITEM_WALL|ITEM_ORIGIN|ITEM_UNSEEN; + $item_flags = ITEM_WALL|ITEM_ORIGIN; +; $private = (($allow_cid || $allow_gid || $deny_cid || $deny_gid) ? 1 : 0); @@ -1038,6 +1039,7 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $arr['mid'] = $u_mid; $arr['parent_mid'] = $u_mid; $arr['item_flags'] = $item_flags; + $arr['item_unseen'] = 1; $arr['author_xchan'] = $poster['xchan_hash']; $arr['owner_xchan'] = $poster['xchan_hash']; $arr['title'] = ''; diff --git a/include/diaspora.php b/include/diaspora.php index 4280d9d77..559a9d14d 100755 --- a/include/diaspora.php +++ b/include/diaspora.php @@ -923,8 +923,8 @@ function diaspora_post($importer,$xml,$msg) { $datarray['app'] = $app; - $datarray['item_flags'] = ITEM_UNSEEN|ITEM_THREAD_TOP; - + $datarray['item_flags'] = ITEM_THREAD_TOP; + $datarray['item_unseen'] = 1; $result = item_store($datarray); return; diff --git a/include/items.php b/include/items.php index 91fa1d70a..717a4bf71 100755 --- a/include/items.php +++ b/include/items.php @@ -2043,13 +2043,12 @@ function item_store($arr,$allow_exec = false) { $arr['comment_policy'] = ((x($arr,'comment_policy')) ? notags(trim($arr['comment_policy'])) : 'contacts' ); - $arr['item_flags'] = $arr['item_flags'] | ITEM_UNSEEN; + $arr['item_unseen'] = ((array_key_exists('item_unseen',$arr)) ? intval($arr['item_unseen']) : 1); if($arr['comment_policy'] == 'none') $arr['item_flags'] = $arr['item_flags'] | ITEM_NOCOMMENT; - // handle time travelers // Allow a bit of fudge in case somebody just has a slightly slow/fast clock @@ -2332,8 +2331,8 @@ function item_store_update($arr,$allow_exec = false) { // override the unseen flag with the original - if($arr['item_flags'] & ITEM_UNSEEN) - $arr['item_flags'] = $arr['item_flags'] ^ ITEM_UNSEEN; + if(intval($arr['item_flags'])) + $arr['item_unseen'] = 0; if($orig[0]['item_flags'] & ITEM_VERIFIED) $orig[0]['item_flags'] = $orig[0]['item_flags'] ^ ITEM_VERIFIED; @@ -4562,7 +4561,7 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C } } - $simple_update = (($client_mode & CLIENT_MODE_UPDATE) ? " and ( item.item_flags & " . intval(ITEM_UNSEEN) . " )>0 " : ''); + $simple_update = (($client_mode & CLIENT_MODE_UPDATE) ? " and ( item.item_unseen = 1 ) " : ''); if($client_mode & CLIENT_MODE_LOAD) $simple_update = ''; diff --git a/include/notify.php b/include/notify.php index aa96fa279..eef838664 100644 --- a/include/notify.php +++ b/include/notify.php @@ -32,7 +32,7 @@ function format_notification($item) { 'url' => $item['author']['xchan_url'], 'photo' => $item['author']['xchan_photo_s'], 'when' => relative_date($item['created']), - 'class' => (($item['item_flags'] & ITEM_UNSEEN) ? 'notify-unseen' : 'notify-seen'), + 'class' => (intval($item['item_unseen']) ? 'notify-unseen' : 'notify-seen'), 'message' => strip_tags(bbcode($itemem_text)) ); -- cgit v1.2.3 From 4b513d3322e03ed59e796ca60d09ee1d26cc50fb Mon Sep 17 00:00:00 2001 From: friendica Date: Thu, 12 Feb 2015 19:22:07 -0800 Subject: issue #896 --- include/text.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/text.php b/include/text.php index 3d4e9cd01..c93bc4e70 100644 --- a/include/text.php +++ b/include/text.php @@ -625,7 +625,8 @@ function get_tags($s) { // The lookbehind is used to prevent a match in the middle of a word // '=' needs to be avoided because when the replacement is made (in handle_tag()) it has to be ignored there // Feel free to allow '=' if the issue with '=' is solved in handle_tag() - if(preg_match_all('/(? Date: Fri, 13 Feb 2015 10:01:26 +0100 Subject: item_unseen update --- include/attach.php | 1 + 1 file changed, 1 insertion(+) (limited to 'include') diff --git a/include/attach.php b/include/attach.php index 3350a591e..f973102e8 100644 --- a/include/attach.php +++ b/include/attach.php @@ -1082,6 +1082,7 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $arr['mid'] = $mid; $arr['parent_mid'] = $mid; $arr['item_flags'] = $item_flags; + $arr['item_unseen'] = 1; $arr['author_xchan'] = $poster['xchan_hash']; $arr['owner_xchan'] = $poster['xchan_hash']; $arr['title'] = ''; -- cgit v1.2.3 From 8696795ce69ee50c7a4e63f5a7e740de466f5df6 Mon Sep 17 00:00:00 2001 From: Alexandre Hannud Abdo Date: Fri, 13 Feb 2015 06:54:49 -0200 Subject: Fixes tag delivery regex for when multiple tags are present Previous regex would cause matches to span several tags when present, thus never recognizing the mention. --- include/items.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/items.php b/include/items.php index 717a4bf71..18ce149ed 100755 --- a/include/items.php +++ b/include/items.php @@ -2861,7 +2861,7 @@ function tag_deliver($uid,$item_id) { if(preg_match($pattern,$body,$matches)) $tagged = true; - $pattern = '/@\!?\[zrl\=(.*?)\](.*?)\+\[\/zrl\]/'; + $pattern = '/@\!?\[zrl\=([^\]]*?)\]((?:.(?!\[zrl\=))*?)\+\[\/zrl\]/'; if(preg_match_all($pattern,$body,$matches,PREG_SET_ORDER)) { $max_forums = get_config('system','max_tagged_forums'); @@ -3022,7 +3022,7 @@ function tgroup_check($uid,$item) { // $pattern = '/@\!?\[zrl\=' . preg_quote($term['url'],'/') . '\]' . preg_quote($term['term'] . '+','/') . '\[\/zrl\]/'; - $pattern = '/@\!?\[zrl\=(.*?)\](.*?)\+\[\/zrl\]/'; + $pattern = '/@\!?\[zrl\=([^\]]*?)\]((?:.(?!\[zrl\=))*?)\+\[\/zrl\]/'; $found = false; -- cgit v1.2.3 From 7bb2e25ea030b7c32d35766631d85ac24b192f11 Mon Sep 17 00:00:00 2001 From: friendica Date: Fri, 13 Feb 2015 13:04:31 -0800 Subject: missing param --- include/zot.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/zot.php b/include/zot.php index 62e45b2b3..da6ca16c3 100644 --- a/include/zot.php +++ b/include/zot.php @@ -1884,7 +1884,7 @@ function process_rating_delivery($sender,$arr) { } else { $x = q("insert into xlink ( xlink_xchan, xlink_link, xlink_rating, xlink_rating_text, xlink_sig, xlink_updated, xlink_static ) - values( '%s', '%s', %d, '%s', '%s', 1 ) ", + values( '%s', '%s', %d, '%s', '%s', '%s', 1 ) ", dbesc($sender['hash']), dbesc($arr['target']), intval($arr['rating']), -- cgit v1.2.3 From 59828593c14a64cecf7ee5c077da9f918062ed60 Mon Sep 17 00:00:00 2001 From: friendica Date: Fri, 13 Feb 2015 14:25:04 -0800 Subject: some ratings fixes --- include/dir_fns.php | 2 +- include/socgraph.php | 23 ----------------------- 2 files changed, 1 insertion(+), 24 deletions(-) (limited to 'include') diff --git a/include/dir_fns.php b/include/dir_fns.php index 8c0161ff1..5ed626b8a 100644 --- a/include/dir_fns.php +++ b/include/dir_fns.php @@ -247,7 +247,7 @@ function sync_directories($dirmode) { logger('rating updated'); } else { - $z = q("insert into xlink ( xlink_xchan, xlink_link, xlink_rating, xlink_rating_text, xlink_sig, xlink_updated, xlink_static ) values( '%s', '%s', %d, '%s', '%s', 1 ) ", + $z = q("insert into xlink ( xlink_xchan, xlink_link, xlink_rating, xlink_rating_text, xlink_sig, xlink_updated, xlink_static ) values( '%s', '%s', %d, '%s', '%s', '%s', 1 ) ", dbesc($rr['channel']), dbesc($rr['target']), intval($rr['rating']), diff --git a/include/socgraph.php b/include/socgraph.php index 13957e814..59830ef1b 100644 --- a/include/socgraph.php +++ b/include/socgraph.php @@ -185,29 +185,6 @@ function poco_load($xchan = '',$url = null) { $total ++; - - $r = q("select * from xlink where xlink_xchan = '%s' and xlink_link = '%s' and xlink_static = 0 limit 1", - dbesc($xchan), - dbesc($hash) - ); - - if(! $r) { - q("insert into xlink ( xlink_xchan, xlink_link, xlink_rating, xlink_rating_text, xlink_updated, xlink_static ) values ( '%s', '%s', %d, '%s', '%s', 0 ) ", - dbesc($xchan), - dbesc($hash), - intval($rating), - dbesc($rating_text), - dbesc(datetime_convert()) - ); - } - else { - q("update xlink set xlink_updated = '%s', xlink_rating = %d, xlink_rating_text = '%s' where xlink_id = %d", - dbesc(datetime_convert()), - intval($rating), - dbesc($rating_text), - intval($r[0]['xlink_id']) - ); - } } logger("poco_load: loaded $total entries",LOGGER_DEBUG); -- cgit v1.2.3 From 6ed8fb30b8b6b70c1f9a2ff5651d6a4892060db9 Mon Sep 17 00:00:00 2001 From: Einer von Vielen Date: Sat, 14 Feb 2015 20:33:51 +0100 Subject: Changed bb code [toc] to make it more flexible This usage is know closer to the original usage of http://ndabas.github.io/toc/ Changed: - jquery.toc.js: Do not check for empty headings - bbcode.php: Added processing of [toc] with parameters - main.js: Use the default params for jquery.toc.js - bbcode.html: Added more help for [toc] and corrected some html --- include/bbcode.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/bbcode.php b/include/bbcode.php index 8f2b5bd38..82d0bd1d1 100644 --- a/include/bbcode.php +++ b/include/bbcode.php @@ -582,9 +582,14 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { if (strpos($Text,'[h6]') !== false) { $Text = preg_replace("(\[h6\](.*?)\[\/h6\])ism",'
$1
',$Text); } - // Check for table of content + // Check for table of content without params if (strpos($Text,'[toc]') !== false) { - $Text = preg_replace("/\[toc\]/ism",'
    ',$Text); + $Text = preg_replace("/\[toc\]/ism",'
      ',$Text); + } + // Check for table of content with params + if (strpos($Text,'[toc') !== false) { + $Text = preg_replace("/\[toc([^\]]+?)\]/ism",'',$Text); + } // Check for centered text if (strpos($Text,'[/center]') !== false) { -- cgit v1.2.3 From a5f7df46675e94471cd4128504eb17d8e5a0e9b1 Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 15 Feb 2015 19:15:55 -0800 Subject: issue #860, replace br html element with linefeed between table rows --- include/bbcode.php | 1 + 1 file changed, 1 insertion(+) (limited to 'include') diff --git a/include/bbcode.php b/include/bbcode.php index 8f2b5bd38..749bc2334 100644 --- a/include/bbcode.php +++ b/include/bbcode.php @@ -625,6 +625,7 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { $Text = preg_replace("/\[table border=1\](.*?)\[\/table\]/sm", '$1
      ' ,$Text); $Text = preg_replace("/\[table border=0\](.*?)\[\/table\]/sm", '$1
      ' ,$Text); } + $Text = str_replace('
      ',"\n",$Text); $Text = str_replace('[hr]','
      ', $Text); // This is actually executed in prepare_body() -- cgit v1.2.3 From 1c4b9199809581504ee66212f3bb434fd9773aff Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 15 Feb 2015 23:45:22 -0800 Subject: force site_url to be lowercase when stored. Otherwise rating hubs on postgres could get real messy. --- include/zot.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/zot.php b/include/zot.php index da6ca16c3..926764635 100644 --- a/include/zot.php +++ b/include/zot.php @@ -2442,7 +2442,7 @@ function import_site($arr,$pubkey) { } $directory_url = htmlspecialchars($arr['directory_url'],ENT_COMPAT,'UTF-8',false); - $url = htmlspecialchars($arr['url'],ENT_COMPAT,'UTF-8',false); + $url = htmlspecialchars(strtolower($arr['url']),ENT_COMPAT,'UTF-8',false); $sellpage = htmlspecialchars($arr['sellpage'],ENT_COMPAT,'UTF-8',false); $site_location = htmlspecialchars($arr['location'],ENT_COMPAT,'UTF-8',false); $site_realm = htmlspecialchars($arr['realm'],ENT_COMPAT,'UTF-8',false); -- cgit v1.2.3 From b4f639239fb0d6d5ed58fb7139bb7f88f1b77150 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 16 Feb 2015 11:09:12 -0800 Subject: mopping up the public site ratings --- include/widgets.php | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'include') diff --git a/include/widgets.php b/include/widgets.php index d457db07d..fbbc74224 100644 --- a/include/widgets.php +++ b/include/widgets.php @@ -962,4 +962,11 @@ function widget_rating($arr) { return $o; +} + +// used by site ratings pages to provide a return link +function widget_pubsites() { + if(get_app()->poi) + return; + return ''; } \ No newline at end of file -- cgit v1.2.3 From 972fc91e12b08eb0aae31c448b7879408ddab229 Mon Sep 17 00:00:00 2001 From: Habeas Codice Date: Mon, 16 Feb 2015 15:08:53 -0800 Subject: remove superfluous non-boolean boolean --- include/api.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/api.php b/include/api.php index d5c2a429c..d0c4ed0aa 100644 --- a/include/api.php +++ b/include/api.php @@ -808,8 +808,8 @@ require_once('include/items.php'); require_once('include/security.php'); - $lastwall = q("SELECT * from item where 1 - and item_private = 0 and item_restrict = 0 + $lastwall = q("SELECT * from item where + item_private = 0 and item_restrict = 0 and author_xchan = '%s' and allow_cid = '' and allow_gid = '' and deny_cid = '' and deny_gid = '' and verb = '%s' -- cgit v1.2.3 From ca8e22101803454be60af35d2cf71ae80224805a Mon Sep 17 00:00:00 2001 From: Habeas Codice Date: Mon, 16 Feb 2015 15:09:43 -0800 Subject: normalize age data mysql has type tinyint(3) which probably turns into a 24-bit value, but postgres uses 3-digit decimal as its constraint (probably what the mysql schema was intended to do). either that or mysql silently truncates while postgres respects the constraint. Either way, bad data gets in unchecked, now it's checked. --- include/zot.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/zot.php b/include/zot.php index da6ca16c3..cbe0c9303 100644 --- a/include/zot.php +++ b/include/zot.php @@ -2243,6 +2243,11 @@ function import_directory_profile($hash,$profile,$addr,$ud_flags = UPDATE_FLAGS_ $r = q("select * from xprof where xprof_hash = '%s' limit 1", dbesc($hash) ); + + $age = intval($arr['xprof_age']); + if($age > 150) + $age = 150; + if($r) { $update = false; foreach($r[0] as $k => $v) { @@ -2271,7 +2276,7 @@ function import_directory_profile($hash,$profile,$addr,$ud_flags = UPDATE_FLAGS_ where xprof_hash = '%s'", dbesc($arr['xprof_desc']), dbesc($arr['xprof_dob']), - intval($arr['xprof_age']), + $age, dbesc($arr['xprof_gender']), dbesc($arr['xprof_marital']), dbesc($arr['xprof_sexual']), @@ -2294,7 +2299,7 @@ function import_directory_profile($hash,$profile,$addr,$ud_flags = UPDATE_FLAGS_ dbesc($arr['xprof_hash']), dbesc($arr['xprof_desc']), dbesc($arr['xprof_dob']), - intval($arr['xprof_age']), + $age, dbesc($arr['xprof_gender']), dbesc($arr['xprof_marital']), dbesc($arr['xprof_sexual']), -- cgit v1.2.3 From 533f39debe494dc826570ff030fcda35041d9038 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 16 Feb 2015 17:01:13 -0800 Subject: bring back like/dislike summaries on photos --- include/ItemObject.php | 4 ---- include/conversation.php | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) (limited to 'include') diff --git a/include/ItemObject.php b/include/ItemObject.php index 136e08eb7..1785d55e7 100644 --- a/include/ItemObject.php +++ b/include/ItemObject.php @@ -168,10 +168,6 @@ class Item extends BaseObject { $responses = get_responses($conv_responses,$response_verbs,$this,$item); - - - $like_button_label = tt('Like','Likes',$like_count,'noun'); - $like_count = ((x($conv_responses['like'],$item['mid'])) ? $conv_responses['like'][$item['mid']] : ''); $like_list = ((x($conv_responses['like'],$item['mid'])) ? $conv_responses['like'][$item['mid'] . '-l'] : ''); if (count($like_list) > MAX_LIKERS) { diff --git a/include/conversation.php b/include/conversation.php index 17822d0d5..8bc42b34b 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -1664,7 +1664,7 @@ function get_responses($conv_responses,$response_verbs,$ob,$item) { if(count($ret[$v]['list']) > MAX_LIKERS) { $ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS); array_push($ret[$v]['list_part'], '' . t('View all') . ''); + . (($ob) ? $ob->get_id() : $item['id']) . '">' . t('View all') . ''); } else { $ret[$v]['list_part'] = ''; -- cgit v1.2.3 From 33e406d7fc74c1701ed4bb1d2a2b2a1bb330683f Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 17 Feb 2015 18:13:20 -0800 Subject: make tag clouds honour the full permissions repertoire, not just yes/no public/private, but who are you and what tags can you see --- include/taxonomy.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/taxonomy.php b/include/taxonomy.php index be80008df..d36c05db2 100644 --- a/include/taxonomy.php +++ b/include/taxonomy.php @@ -98,7 +98,12 @@ function format_term_for_display($term) { function tagadelic($uid, $count = 0, $authors = '', $flags = 0, $restrict = 0, $type = TERM_HASHTAG) { - $sql_options = ''; + require_once('include/security.php'); + + if(! perm_is_allowed($uid,get_observer_hash(),'view_stream')) + return array(); + + $sql_options = item_permissions_sql($uid); $count = intval($count); if($flags) @@ -114,7 +119,7 @@ function tagadelic($uid, $count = 0, $authors = '', $flags = 0, $restrict = 0, $ // Fetch tags $r = q("select term, count(term) as total from term left join item on term.oid = item.id where term.uid = %d and term.type = %d - and otype = %d and item_restrict = %d and item_private = 0 + and otype = %d and item_restrict = %d $sql_options group by term order by total desc %s", intval($uid), -- cgit v1.2.3 From e00be4de2353e1ca58570bf37fd247ff99fa549f Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 17 Feb 2015 19:47:36 -0800 Subject: The Diaspora communications policies allow comments to public posts literally from anybody. Allow this policy model by default for commenters from that network. This policy decision can be set or disabled on the addon/features settings page. --- include/diaspora.php | 52 +++++++++++++++++++++++++++++++++++----------------- 1 file changed, 35 insertions(+), 17 deletions(-) (limited to 'include') diff --git a/include/diaspora.php b/include/diaspora.php index 559a9d14d..d2e27aafe 100755 --- a/include/diaspora.php +++ b/include/diaspora.php @@ -1271,31 +1271,21 @@ function diaspora_comment($importer,$xml,$msg) { return; } - if((! $importer['system']) && (! perm_is_allowed($importer['channel_id'],$contact['xchan_hash'],'post_comments'))) { - logger('diaspora_comment: Ignoring this author.'); - return 202; - } - // Friendica is currently truncating guids at 64 chars + + $pubcomment = get_pconfig($importer['channel_id'],'system','diaspora_public_comments'); - $search_guid = $guid; - if(strlen($guid) == 64) - $search_guid = $guid . '%'; + // by default comments on public posts are allowed from anybody on Diaspora. That is their policy. + // Once this setting is set to something we'll track your preference and it will over-ride the default. - $r = q("SELECT * FROM item WHERE uid = %d AND mid like '%s' LIMIT 1", - intval($importer['channel_id']), - dbesc($search_guid) - ); - if($r) { - logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid); - return; - } + if($pubcomment === false) + $pubcomment = 1; + // Friendica is currently truncating guids at 64 chars $search_guid = $parent_guid; if(strlen($parent_guid) == 64) $search_guid = $parent_guid . '%'; - $r = q("SELECT * FROM item WHERE uid = %d AND mid LIKE '%s' LIMIT 1", intval($importer['channel_id']), dbesc($search_guid) @@ -1304,8 +1294,36 @@ function diaspora_comment($importer,$xml,$msg) { logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid); return; } + $parent_item = $r[0]; + if(intval($parent_item['item_private'])) + $pubcomment = 0; + + // So basically if something arrives at the sys channel it's by definition public and we allow it. + // If $pubcomment and the parent was public, we allow it. + // In all other cases, honour the permissions for this Diaspora connection + + if((! $importer['system']) && (! $pubcomment) && (! perm_is_allowed($importer['channel_id'],$contact['xchan_hash'],'post_comments'))) { + logger('diaspora_comment: Ignoring this author.'); + return 202; + } + + $search_guid = $guid; + if(strlen($guid) == 64) + $search_guid = $guid . '%'; + + + $r = q("SELECT * FROM item WHERE uid = %d AND mid like '%s' LIMIT 1", + intval($importer['channel_id']), + dbesc($search_guid) + ); + if($r) { + logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid); + return; + } + + /* How Diaspora performs comment signature checking: -- cgit v1.2.3 From 2fbb6a5ff5c2b097e42e41ff73587127998ae86e Mon Sep 17 00:00:00 2001 From: marijus Date: Wed, 18 Feb 2015 10:41:38 +0100 Subject: do not send activity to channels with no permission to view filestorage --- include/attach.php | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/attach.php b/include/attach.php index f973102e8..43b56e4f6 100644 --- a/include/attach.php +++ b/include/attach.php @@ -974,6 +974,11 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, if(!$object) return; + //filter out receivers which do not have permission to view filestorage + $arr_allow_cid = expand_acl($allow_cid); + $arr_allow_cid = check_list_permissions($channel_id, $arr_allow_cid, 'view_storage'); + $allow_cid = perms2str($arr_allow_cid); + $is_dir = (($object['flags'] & ATTACH_FLAG_DIR) ? true : false); //do not send activity for folders for now @@ -987,6 +992,9 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $r_perms = recursive_activity_recipients($allow_cid, $allow_gid, $deny_cid, $deny_gid, $folder_hash); + //filter out receivers which do not have permission to view filestorage + $r_perms['allow_cid'] = check_list_permissions($channel_id, $r_perms['allow_cid'], 'view_storage'); + $allow_cid = perms2str($r_perms['allow_cid']); $allow_gid = perms2str($r_perms['allow_gid']); $deny_cid = perms2str($r_perms['deny_cid']); @@ -999,7 +1007,6 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $objtype = ACTIVITY_OBJ_FILE; $item_flags = ITEM_WALL|ITEM_ORIGIN; -; $private = (($allow_cid || $allow_gid || $deny_cid || $deny_gid) ? 1 : 0); @@ -1157,6 +1164,13 @@ function recursive_activity_recipients($allow_cid, $allow_gid, $deny_cid, $deny_ $arr_allow_cid = expand_acl($allow_cid); $arr_allow_gid = expand_acl($allow_gid); + + //turn allow_gid into allow_cid's + foreach($arr_allow_gid as $gid) { + $in_group = in_group($gid); + $arr_allow_cid = array_unique(array_merge($arr_allow_cid, $in_group)); + } + $arr_deny_cid = expand_acl($deny_cid); $arr_deny_gid = expand_acl($deny_gid); @@ -1261,10 +1275,15 @@ function recursive_activity_recipients($allow_cid, $allow_gid, $deny_cid, $deny_ } function in_group($group_id) { - $r = q("SELECT xchan FROM group_member left join groups on group_member.gid = group.id WHERE hash = '%s' ", + //TODO: make these two queries one with a join. + $x = q("SELECT id FROM groups WHERE hash = '%s'", dbesc($group_id) ); + $r = q("SELECT xchan FROM group_member WHERE gid = %d", + intval($x[0]['id']) + ); + foreach($r as $ig) { $group_members[] = $ig['xchan']; } -- cgit v1.2.3 From 9d745cd072d3f13e968776f190dd4f7814ae92eb Mon Sep 17 00:00:00 2001 From: zottel Date: Wed, 18 Feb 2015 11:44:43 +0100 Subject: also deliver public posts to channels with channel_w_stream = PERMS_AUTHED --- include/zot.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/zot.php b/include/zot.php index 852376c4b..3b22fde70 100644 --- a/include/zot.php +++ b/include/zot.php @@ -1315,9 +1315,9 @@ function public_recips($msg) { if($msg['notify']['sender']['url'] === z_root()) - $sql = " where (( " . $col . " & " . PERMS_NETWORK . " )>0 or ( " . $col . " & " . PERMS_SITE . " )>0 or ( " . $col . " & " . PERMS_PUBLIC . ")>0) "; + $sql = " where (( " . $col . " & " . PERMS_NETWORK . " )>0 or ( " . $col . " & " . PERMS_SITE . " )>0 or ( " . $col . " & " . PERMS_PUBLIC . ")>0) or ( " . $col . " & " . PERMS_AUTHED . ")>0) "; else - $sql = " where (( " . $col . " & " . PERMS_NETWORK . " )>0 or ( " . $col . " & " . PERMS_PUBLIC . ")>0) "; + $sql = " where (( " . $col . " & " . PERMS_NETWORK . " )>0 or ( " . $col . " & " . PERMS_PUBLIC . ")>0) or ( " . $col . " & " . PERMS_AUTHED . ")>0) "; $r = q("select channel_hash as hash from channel $sql or channel_hash = '%s' ", -- cgit v1.2.3 From d0fe0b5d5f8e2210297458f18884694d66aec8d9 Mon Sep 17 00:00:00 2001 From: zottel Date: Wed, 18 Feb 2015 11:48:05 +0100 Subject: fix parens mismatch from last commit --- include/zot.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/zot.php b/include/zot.php index 3b22fde70..98b54a04c 100644 --- a/include/zot.php +++ b/include/zot.php @@ -1315,9 +1315,9 @@ function public_recips($msg) { if($msg['notify']['sender']['url'] === z_root()) - $sql = " where (( " . $col . " & " . PERMS_NETWORK . " )>0 or ( " . $col . " & " . PERMS_SITE . " )>0 or ( " . $col . " & " . PERMS_PUBLIC . ")>0) or ( " . $col . " & " . PERMS_AUTHED . ")>0) "; + $sql = " where (( " . $col . " & " . PERMS_NETWORK . " )>0 or ( " . $col . " & " . PERMS_SITE . " )>0 or ( " . $col . " & " . PERMS_PUBLIC . ")>0 or ( " . $col . " & " . PERMS_AUTHED . ")>0) "; else - $sql = " where (( " . $col . " & " . PERMS_NETWORK . " )>0 or ( " . $col . " & " . PERMS_PUBLIC . ")>0) or ( " . $col . " & " . PERMS_AUTHED . ")>0) "; + $sql = " where (( " . $col . " & " . PERMS_NETWORK . " )>0 or ( " . $col . " & " . PERMS_PUBLIC . ")>0 or ( " . $col . " & " . PERMS_AUTHED . ")>0) "; $r = q("select channel_hash as hash from channel $sql or channel_hash = '%s' ", -- cgit v1.2.3 From fc52536ce70774b24e6f38114ff1e46f392eb983 Mon Sep 17 00:00:00 2001 From: friendica Date: Thu, 19 Feb 2015 15:07:41 -0800 Subject: diaspora: move reshare encapsulation after tag parsing, since it seriously screws up the tag parser and reshares end up with a lot of unlinked tags. --- include/diaspora.php | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) (limited to 'include') diff --git a/include/diaspora.php b/include/diaspora.php index d2e27aafe..6523630f6 100755 --- a/include/diaspora.php +++ b/include/diaspora.php @@ -1067,24 +1067,13 @@ function diaspora_reshare($importer,$xml,$msg) { $orig_author_photo = $person['xchan_photo_m']; } - $newbody = "[share author='" . urlencode($orig_author_name) - . "' profile='" . $orig_author_link - . "' avatar='" . $orig_author_photo - . "' link='" . $orig_url - . "' posted='" . datetime_convert('UTC','UTC',unxmlify($source_xml->post->status_message->created_at)) - . "' message_id='" . unxmlify($source_xml->post->status_message->guid) - . "']" . $body . "[/share]"; - $created = unxmlify($xml->created_at); $private = ((unxmlify($xml->public) == 'false') ? 1 : 0); $datarray = array(); - $str_tags = ''; - - $tags = get_tags($newbody); - + $tags = get_tags($body); if(count($tags)) { @@ -1116,7 +1105,7 @@ function diaspora_reshare($importer,$xml,$msg) { } } - $cnt = preg_match_all('/@\[url=(.*?)\](.*?)\[\/url\]/ism',$newbody,$matches,PREG_SET_ORDER); + $cnt = preg_match_all('/@\[url=(.*?)\](.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER); if($cnt) { foreach($matches as $mtch) { $datarray['term'][] = array( @@ -1129,6 +1118,16 @@ function diaspora_reshare($importer,$xml,$msg) { } } + + $newbody = "[share author='" . urlencode($orig_author_name) + . "' profile='" . $orig_author_link + . "' avatar='" . $orig_author_photo + . "' link='" . $orig_url + . "' posted='" . datetime_convert('UTC','UTC',unxmlify($source_xml->post->status_message->created_at)) + . "' message_id='" . unxmlify($source_xml->post->status_message->guid) + . "']" . $body . "[/share]"; + + $plink = service_plink($contact,$guid); $datarray['uid'] = $importer['channel_id']; -- cgit v1.2.3 From 8db367754621c7ee81c3157785a914cf8627d7b2 Mon Sep 17 00:00:00 2001 From: friendica Date: Thu, 19 Feb 2015 16:29:49 -0800 Subject: Diaspora tag replacement was wretchedly buggy. Use our standard tag replacement calls instead. --- include/diaspora.php | 156 +++++++++------------------------------------------ 1 file changed, 27 insertions(+), 129 deletions(-) (limited to 'include') diff --git a/include/diaspora.php b/include/diaspora.php index 6523630f6..553c7474c 100755 --- a/include/diaspora.php +++ b/include/diaspora.php @@ -841,68 +841,25 @@ function diaspora_post($importer,$xml,$msg) { $datarray = array(); - $tags = get_tags($body); - - - if(count($tags)) { + // Look for tags and linkify them + $results = linkify_tags(get_app(), $body, $importer['channel_id']); + if($results) { $datarray['term'] = array(); - - foreach($tags as $tag) { - if(strpos($tag,'#') === 0) { - if((strpos($tag,'[url=')) || (strpos($tag,'[zrl'))) - continue; - - // don't link tags that are already embedded in links - - if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body)) - continue; - if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body)) - continue; - - $basetag = str_replace('_',' ',substr($tag,1)); - $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body); - + foreach($results as $result) { + $success = $result['success']; + if($success['replaced']) { $datarray['term'][] = array( 'uid' => $importer['channel_id'], - 'type' => TERM_HASHTAG, + 'type' => $success['termtype'], 'otype' => TERM_OBJ_POST, - 'term' => $basetag, - 'url' => z_root() . '/search?tag=' . rawurlencode($basetag) + 'term' => $success['term'], + 'url' => $success['url'] ); } } } - $cnt = preg_match_all('/@\[url=(.*?)\](.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER); - if($cnt) { - foreach($matches as $mtch) { - $datarray['term'][] = array( - 'uid' => $importer['channel_id'], - 'type' => TERM_MENTION, - 'otype' => TERM_OBJ_POST, - 'term' => $mtch[2], - 'url' => $mtch[1] - ); - } - } - - $cnt = preg_match_all('/@\[zrl=(.*?)\](.*?)\[\/zrl\]/ism',$body,$matches,PREG_SET_ORDER); - if($cnt) { - foreach($matches as $mtch) { - // don't include plustags in the term - $term = ((substr($mtch[2],-1,1) === '+') ? substr($mtch[2],0,-1) : $mtch[2]); - $datarray['term'][] = array( - 'uid' => $importer['channel_id'], - 'type' => TERM_MENTION, - 'otype' => TERM_OBJ_POST, - 'term' => $term, - 'url' => $mtch[1] - ); - } - } - - $plink = service_plink($contact,$guid); @@ -1053,12 +1010,6 @@ function diaspora_reshare($importer,$xml,$msg) { logger('message length exceeds max_import_size: truncated'); } - - //if(! $body) { - // logger('diaspora_reshare: empty body: source= ' . $x); - // return; - //} - $person = find_diaspora_person_by_handle($orig_author); if($person) { @@ -1073,52 +1024,25 @@ function diaspora_reshare($importer,$xml,$msg) { $datarray = array(); - $tags = get_tags($body); - - if(count($tags)) { + // Look for tags and linkify them + $results = linkify_tags(get_app(), $body, $importer['channel_id']); + if($results) { $datarray['term'] = array(); - - foreach($tags as $tag) { - if(strpos($tag,'#') === 0) { - if((strpos($tag,'[url=')) || (strpos($tag,'[zrl'))) - continue; - - // don't link tags that are already embedded in links - - if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$newbody)) - continue; - if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$newbody)) - continue; - - $basetag = str_replace('_',' ',substr($tag,1)); - $newbody = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$newbody); - + foreach($results as $result) { + $success = $result['success']; + if($success['replaced']) { $datarray['term'][] = array( 'uid' => $importer['channel_id'], - 'type' => TERM_HASHTAG, + 'type' => $success['termtype'], 'otype' => TERM_OBJ_POST, - 'term' => $basetag, - 'url' => z_root() . '/search?tag=' . rawurlencode($basetag) + 'term' => $success['term'], + 'url' => $success['url'] ); } } } - $cnt = preg_match_all('/@\[url=(.*?)\](.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER); - if($cnt) { - foreach($matches as $mtch) { - $datarray['term'][] = array( - 'uid' => $importer['channel_id'], - 'type' => TERM_MENTION, - 'otype' => TERM_OBJ_POST, - 'term' => $mtch[2], - 'url' => $mtch[1] - ); - } - } - - $newbody = "[share author='" . urlencode($orig_author_name) . "' profile='" . $orig_author_link . "' avatar='" . $orig_author_photo @@ -1396,51 +1320,25 @@ function diaspora_comment($importer,$xml,$msg) { $datarray = array(); - $tags = get_tags($body); - - if(count($tags)) { + // Look for tags and linkify them + $results = linkify_tags(get_app(), $body, $importer['channel_id']); + if($results) { $datarray['term'] = array(); - - foreach($tags as $tag) { - if(strpos($tag,'#') === 0) { - if((strpos($tag,'[url=')) || (strpos($tag,'[zrl'))) - continue; - - // don't link tags that are already embedded in links - - if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body)) - continue; - if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body)) - continue; - - $basetag = str_replace('_',' ',substr($tag,1)); - $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body); - + foreach($results as $result) { + $success = $result['success']; + if($success['replaced']) { $datarray['term'][] = array( 'uid' => $importer['channel_id'], - 'type' => TERM_HASHTAG, + 'type' => $success['termtype'], 'otype' => TERM_OBJ_POST, - 'term' => $basetag, - 'url' => z_root() . '/search?tag=' . rawurlencode($basetag) + 'term' => $success['term'], + 'url' => $success['url'] ); } } } - $cnt = preg_match_all('/@\[url=(.*?)\](.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER); - if($cnt) { - foreach($matches as $mtch) { - $datarray['term'][] = array( - 'uid' => $importer['channel_id'], - 'type' => TERM_MENTION, - 'otype' => TERM_OBJ_POST, - 'term' => $mtch[2], - 'url' => $mtch[1] - ); - } - } - $datarray['uid'] = $importer['channel_id']; $datarray['verb'] = ACTIVITY_POST; $datarray['mid'] = $guid; -- cgit v1.2.3 From 8c71e0e86184b844a69bfeabefdbb6ea50a849c9 Mon Sep 17 00:00:00 2001 From: friendica Date: Thu, 19 Feb 2015 17:42:18 -0800 Subject: directory interface cleanup and documentation so that debugging realms won't be stabbing in the dark. --- include/dir_fns.php | 53 ++++++++++++++++++++++++++++++++++++++++++++++----- include/directory.php | 6 +++++- 2 files changed, 53 insertions(+), 6 deletions(-) (limited to 'include') diff --git a/include/dir_fns.php b/include/dir_fns.php index 5ed626b8a..686c5140f 100644 --- a/include/dir_fns.php +++ b/include/dir_fns.php @@ -64,8 +64,16 @@ function check_upstream_directory() { set_config('system','directory_server',''); return; } + +/** + * @function dir_sort_links() + * Called by the directory_sort widget + */ + + function dir_sort_links() { + // Build urls without order and pubforums so it's easy to tack on the changed value // Probably there's an easier way to do this @@ -119,6 +127,20 @@ function dir_safe_mode() { return $o; } +/** + * @function sync_directories($mode) + * + * @param int $mode; + * + * Checks the directory mode of this hub to see if it is some form of directory server. If it is, + * get the directory realm of this hub. Fetch a list of all other directory servers in this realm and request + * a directory sync packet. This will contain both directory updates and new ratings. Store these all in the DB. + * In the case of updates, we will query each of them asynchronously from a poller task. Ratings are stored + * directly if the rater's signature matches. + * + */ + + function sync_directories($dirmode) { if($dirmode == DIRECTORY_MODE_STANDALONE || $dirmode == DIRECTORY_MODE_NORMAL) @@ -175,15 +197,18 @@ function sync_directories($dirmode) { logger('sync directories: ' . $rr['site_directory']); - // for brand new directory servers, only load the last couple of days. Everything before that will be repeats. + // for brand new directory servers, only load the last couple of days. + // It will take about a month for a new directory to obtain the full current repertoire of channels. + // FIXME - go back and pick up earlier ratings if this is a new directory server. These do not get refreshed. $syncdate = (($rr['site_sync'] === NULL_DATE) ? datetime_convert('UTC','UTC','now - 2 days') : $rr['site_sync']); $x = z_fetch_url($rr['site_directory'] . '?f=&sync=' . urlencode($syncdate)); if(! $x['success']) continue; + $j = json_decode($x['body'],true); - if((! $j['transactions']) || (! is_array($j['transactions']))) + if(!($j['transactions']) || ($j['ratings'])) continue; q("update site set site_sync = '%s' where site_url = '%s'", @@ -193,7 +218,7 @@ function sync_directories($dirmode) { logger('sync_directories: ' . $rr['site_url'] . ': ' . print_r($j,true), LOGGER_DATA); - if(count($j['transactions'])) { + if(is_array($j['transactions']) && count($j['transactions'])) { foreach($j['transactions'] as $t) { $r = q("select * from updates where ud_guid = '%s' limit 1", dbesc($t['transaction_id']) @@ -216,7 +241,7 @@ function sync_directories($dirmode) { ); } } - if(count($j['ratings'])) { + if(is_array($j['ratings']) && count($j['ratings'])) { foreach($j['ratings'] as $rr) { $x = q("select * from xlink where xlink_xchan = '%s' and xlink_link = '%s' and xlink_static = 1", dbesc($rr['channel']), @@ -224,6 +249,10 @@ function sync_directories($dirmode) { ); if($x && $x[0]['xlink_updated'] >= $rr['edited']) continue; + + // Ratings are signed by the rater. We need to verify before we can accept it. + // TODO - queue or defer if the xchan is not yet present on our site + $y = q("select xchan_pubkey from xchan where xchan_hash = '%s' limit 1", dbesc($rr['channel']) ); @@ -263,6 +292,18 @@ function sync_directories($dirmode) { } +/** + * $function update_directory_entry($ud) + * + * @param array $ud; // Entry from update table + * Given an update record, probe the channel, grab a zot-info packet and refresh/sync the data + * + * Ignore updating records marked as deleted + * + * If successful, + * sets ud_last in the DB to the current datetime for this reddress/webbie + */ + function update_directory_entry($ud) { logger('update_directory_entry: ' . print_r($ud,true), LOGGER_DATA); @@ -289,7 +330,9 @@ function update_directory_entry($ud) { /** * @function local_dir_update($uid,$force) - * push local channel updates to a local directory server + * push local channel updates to a local directory server + * This is called from include/directory.php if a profile is to be pushed + * to the directory and the local hub in this case is any kind of directory server. * */ diff --git a/include/directory.php b/include/directory.php index a7324a99a..801d4ec8e 100644 --- a/include/directory.php +++ b/include/directory.php @@ -38,7 +38,9 @@ function directory_run($argv, $argc){ $channel = $x[0]; - if(($dirmode == DIRECTORY_MODE_PRIMARY) || ($dirmode == DIRECTORY_MODE_STANDALONE)) { + if($dirmode != DIRECTORY_MODE_NORMAL) { + + // this is an in-memory update and we don't need to send a network packet. local_dir_update($argv[1],$force); @@ -54,6 +56,8 @@ function directory_run($argv, $argc){ return; } + // otherwise send the changes upstream + $directory = find_upstream_directory($dirmode); $url = $directory['url'] . '/post'; -- cgit v1.2.3 From ffd47e6b9544c4ef717fdd545563831df84bf93b Mon Sep 17 00:00:00 2001 From: Habeas Codice Date: Fri, 20 Feb 2015 19:48:51 -0800 Subject: catch negative ages nix extra var --- include/zot.php | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) (limited to 'include') diff --git a/include/zot.php b/include/zot.php index 98b54a04c..0d8fe8714 100644 --- a/include/zot.php +++ b/include/zot.php @@ -2244,10 +2244,11 @@ function import_directory_profile($hash,$profile,$addr,$ud_flags = UPDATE_FLAGS_ dbesc($hash) ); - $age = intval($arr['xprof_age']); - if($age > 150) - $age = 150; - + if($arr['xprof_age'] > 150) + $arr['xprof_age'] = 150; + if($arr['xprof_age'] < 0) + $arr['xprof_age'] = 0; + if($r) { $update = false; foreach($r[0] as $k => $v) { @@ -2276,7 +2277,7 @@ function import_directory_profile($hash,$profile,$addr,$ud_flags = UPDATE_FLAGS_ where xprof_hash = '%s'", dbesc($arr['xprof_desc']), dbesc($arr['xprof_dob']), - $age, + intval($arr['xprof_age']), dbesc($arr['xprof_gender']), dbesc($arr['xprof_marital']), dbesc($arr['xprof_sexual']), @@ -2299,7 +2300,7 @@ function import_directory_profile($hash,$profile,$addr,$ud_flags = UPDATE_FLAGS_ dbesc($arr['xprof_hash']), dbesc($arr['xprof_desc']), dbesc($arr['xprof_dob']), - $age, + intval($arr['xprof_age']), dbesc($arr['xprof_gender']), dbesc($arr['xprof_marital']), dbesc($arr['xprof_sexual']), -- cgit v1.2.3 From 86aefe0e012939fb08193fa59ba74deed062a1af Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 22 Feb 2015 15:27:45 -0800 Subject: new session functions --- include/session.php | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'include') diff --git a/include/session.php b/include/session.php index ed4dfdd16..00e1d8fbe 100644 --- a/include/session.php +++ b/include/session.php @@ -6,7 +6,36 @@ $session_exists = 0; $session_expire = 180000; +$session_mirror = null; + +function red_session_start() { + global $session_mirror; + + session_start(); + $session_mirror = $_SESSION; + session_write_close(); +} + +function red_session_get($var) { + global $session_mirror; + if(is_null($session_mirror)) + red_session_start(); + return $session_mirror[$var]; +} +function red_session_put($var,$val) { + session_start(); + $_SESSION[$var'] = $val; + $session_mirror = $_SESSION; + session_write_close(); +} + +function red_session_destroy() { + session_start(); + unset($_SESSION); + unset($session_mirror); + session_write_close(); +} function new_cookie($time) { -- cgit v1.2.3 From 0109c0fcf3a9eff33f6dd6a651b351f20c948eb4 Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 22 Feb 2015 17:37:57 -0800 Subject: fi8x the typo --- include/session.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/session.php b/include/session.php index 00e1d8fbe..8ae2194ec 100644 --- a/include/session.php +++ b/include/session.php @@ -25,7 +25,7 @@ function red_session_get($var) { function red_session_put($var,$val) { session_start(); - $_SESSION[$var'] = $val; + $_SESSION[$var] = $val; $session_mirror = $_SESSION; session_write_close(); } -- cgit v1.2.3 From 324e59b1b68cb3a799194e51218b503044fb3975 Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 22 Feb 2015 18:06:33 -0800 Subject: remove these functions for now. --- include/session.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'include') diff --git a/include/session.php b/include/session.php index 8ae2194ec..739eca213 100644 --- a/include/session.php +++ b/include/session.php @@ -6,6 +6,7 @@ $session_exists = 0; $session_expire = 180000; +/* $session_mirror = null; function red_session_start() { @@ -36,7 +37,7 @@ function red_session_destroy() { unset($session_mirror); session_write_close(); } - +*/ function new_cookie($time) { $old_sid = session_id(); -- cgit v1.2.3 From e1cf396feba2fe33ea992570b1d90edaaeb87ad5 Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 22 Feb 2015 20:58:11 -0800 Subject: remove the new session functions from the trunk. Don't yet know if they'll come back or not. --- include/session.php | 33 --------------------------------- 1 file changed, 33 deletions(-) (limited to 'include') diff --git a/include/session.php b/include/session.php index 739eca213..0e2adb77d 100644 --- a/include/session.php +++ b/include/session.php @@ -6,39 +6,6 @@ $session_exists = 0; $session_expire = 180000; -/* -$session_mirror = null; - -function red_session_start() { - global $session_mirror; - - session_start(); - $session_mirror = $_SESSION; - session_write_close(); -} - -function red_session_get($var) { - global $session_mirror; - if(is_null($session_mirror)) - red_session_start(); - return $session_mirror[$var]; -} - -function red_session_put($var,$val) { - session_start(); - $_SESSION[$var] = $val; - $session_mirror = $_SESSION; - session_write_close(); -} - -function red_session_destroy() { - session_start(); - unset($_SESSION); - unset($session_mirror); - session_write_close(); -} -*/ - function new_cookie($time) { $old_sid = session_id(); -- cgit v1.2.3 From d0e7fc76cd112dde0947540c84274358d8f84560 Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 22 Feb 2015 20:59:24 -0800 Subject: no longer needed --- include/fixd.php | 33 --------------------------------- 1 file changed, 33 deletions(-) delete mode 100644 include/fixd.php (limited to 'include') diff --git a/include/fixd.php b/include/fixd.php deleted file mode 100644 index bce5eb348..000000000 --- a/include/fixd.php +++ /dev/null @@ -1,33 +0,0 @@ - Date: Sun, 22 Feb 2015 22:58:09 -0800 Subject: notes about private realm registrations and multiple primary directories. --- include/ratenotif.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/ratenotif.php b/include/ratenotif.php index 4fa0077a6..8be3b15b7 100644 --- a/include/ratenotif.php +++ b/include/ratenotif.php @@ -76,8 +76,8 @@ function ratenotif_run($argv, $argc){ if($j && $j['success'] && is_array($j['directories'])) { foreach($j['directories'] as $h) { -// if($h == z_root()) -// continue; + if($h == z_root()) + continue; $hash = random_string(); $n = zot_build_packet($channel,'notify',null,null,$hash); -- cgit v1.2.3 From 8d0377466657a02c2e0bbeacd2af0a181ceda898 Mon Sep 17 00:00:00 2001 From: zottel Date: Mon, 23 Feb 2015 14:53:10 +0100 Subject: make redirections restriction in z_fetch_url() work --- include/network.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/network.php b/include/network.php index a7127c1a2..6874063ab 100644 --- a/include/network.php +++ b/include/network.php @@ -109,7 +109,7 @@ function z_fetch_url($url, $binary = false, $redirects = 0, $opts = array()) { $url_parsed = @parse_url($newurl); if (isset($url_parsed)) { @curl_close($ch); - return z_fetch_url($newurl,$binary,$redirects++,$opts); + return z_fetch_url($newurl,$binary,++$redirects,$opts); } } -- cgit v1.2.3 From fbbcc10025bdf01c17a80a1b790e1f72dcaa8b2c Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 23 Feb 2015 11:33:16 -0800 Subject: apply fix from 8d03774 to z_post_url also --- include/network.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/network.php b/include/network.php index 6874063ab..db32396e4 100644 --- a/include/network.php +++ b/include/network.php @@ -239,7 +239,7 @@ function z_post_url($url,$params, $redirects = 0, $opts = array()) { if($http_code == 303) { return z_fetch_url($newurl,false,$redirects++,$opts); } else { - return z_post_url($newurl,$params,$redirects++,$opts); + return z_post_url($newurl,$params,++$redirects,$opts); } } } -- cgit v1.2.3 From d29de912b439b8252efff8b644f034cf7fc7d3e2 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 23 Feb 2015 16:27:12 -0800 Subject: public_recips cleanup --- include/zot.php | 48 ++++++++++++++++++++++++++++++------------------ 1 file changed, 30 insertions(+), 18 deletions(-) (limited to 'include') diff --git a/include/zot.php b/include/zot.php index 0d8fe8714..b19b1474a 100644 --- a/include/zot.php +++ b/include/zot.php @@ -1270,12 +1270,13 @@ function zot_import($arr, $sender_url) { // A public message with no listed recipients can be delivered to anybody who -// has PERMS_NETWORK for that type of post, or PERMS_SITE and is one the same +// has PERMS_NETWORK for that type of post, PERMS_AUTHED (in-network senders are +// by definition authenticated) or PERMS_SITE and is one the same // site, or PERMS_SPECIFIC and the sender is a contact who is granted // permissions via their connection permissions in the address book. // Here we take a given message and construct a list of hashes of everybody -// on the site that we should deliver to. - +// on the site that we should try and deliver to. +// Some of these will be rejected, but this gives us a place to start. function public_recips($msg) { @@ -1294,15 +1295,9 @@ function public_recips($msg) { $check_mentions = true; } else { - // if this is a comment and it wasn't sent by the post owner, check to see who is allowing them to comment. - // We should have one specific recipient and this step shouldn't be needed unless somebody stuffed up their software. - // We may need this step to protect us from bad guys intentionally stuffing up their software. - // If it is sent by the post owner, we don't need to do this. We only need to see who is receiving the - // owner's stream (which was already set above) - as they control the comment permissions - if($msg['notify']['sender']['guid_sig'] != $msg['message']['owner']['guid_sig']) { - $col = 'channel_w_comment'; - $field = PERMS_W_COMMENT; - } + $col = 'channel_w_comment'; + $field = PERMS_W_COMMENT; + } } elseif($msg['message']['type'] === 'mail') { @@ -1313,21 +1308,38 @@ function public_recips($msg) { if(! $col) return NULL; - + $col = dbesc($col); + + // First find those channels who are accepting posts from anybody, or at least + // something greater than just their connections. + if($msg['notify']['sender']['url'] === z_root()) - $sql = " where (( " . $col . " & " . PERMS_NETWORK . " )>0 or ( " . $col . " & " . PERMS_SITE . " )>0 or ( " . $col . " & " . PERMS_PUBLIC . ")>0 or ( " . $col . " & " . PERMS_AUTHED . ")>0) "; + $sql = " where (( " . $col . " & " . intval(PERMS_NETWORK) . " ) > 0 + or ( " . $col . " & " . intval(PERMS_SITE) . " ) > 0 + or ( " . $col . " & " . intval(PERMS_PUBLIC) . ") > 0 + or ( " . $col . " & " . intval(PERMS_AUTHED) . ") > 0 ) "; else - $sql = " where (( " . $col . " & " . PERMS_NETWORK . " )>0 or ( " . $col . " & " . PERMS_PUBLIC . ")>0 or ( " . $col . " & " . PERMS_AUTHED . ")>0) "; + $sql = " where (( " . $col . " & " . intval(PERMS_NETWORK) . " ) > 0 + or ( " . $col . " & " . intval(PERMS_PUBLIC) . ") > 0 + or ( " . $col . " & " . intval(PERMS_AUTHED) . ") > 0 ) "; - $r = q("select channel_hash as hash from channel $sql or channel_hash = '%s' ", + $r = q("select channel_hash as hash from channel $sql or channel_hash = '%s' + and ( channel_pageflags & " . intval(PAGE_REMOVED) . " ) = 0 ", dbesc($msg['notify']['sender']['hash']) ); if(! $r) $r = array(); - $x = q("select channel_hash as hash from channel left join abook on abook_channel = channel_id where abook_xchan = '%s' and not ( channel_pageflags & " . PAGE_REMOVED . " )>0 and (( " . $col . " & " . PERMS_SPECIFIC . " )>0 and ( abook_my_perms & " . $field . " )>0) OR ( " . $col . " & " . PERMS_PENDING . " )>0 OR (( " . $col . " & " . PERMS_CONTACTS . " )>0 and not ( abook_flags & " . ABOOK_FLAG_PENDING . " )>0) ", + // Now we have to get a bit dirty. Find every channel that has the sender in their connections (abook) + // and is allowing this sender at least at a high level. + + $x = q("select channel_hash as hash from channel left join abook on abook_channel = channel_id + where abook_xchan = '%s' and ( channel_pageflags & " . intval(PAGE_REMOVED) . " ) = 0 + and (( " . $col . " & " . intval(PERMS_SPECIFIC) . " ) > 0 and ( abook_my_perms & " . intval($field) . " ) > 0 ) + OR ( " . $col . " & " . intval(PERMS_PENDING) . " ) > 0 + OR (( " . $col . " & " . intval(PERMS_CONTACTS) . " ) > 0 and ( abook_flags & " . intval(ABOOK_FLAG_PENDING) . " ) = 0 ) ", dbesc($msg['notify']['sender']['hash']) ); @@ -1411,7 +1423,7 @@ function allowed_public_recips($msg) { $condensed_recips[] = $rr['hash']; $results = array(); - $r = q("select channel_hash as hash from channel left join abook on abook_channel = channel_id where abook_xchan = '%s' and not ( channel_pageflags & %d )>0 ", + $r = q("select channel_hash as hash from channel left join abook on abook_channel = channel_id where abook_xchan = '%s' and not ( channel_pageflags & %d ) > 0 ", dbesc($hash), intval(PAGE_REMOVED) ); -- cgit v1.2.3 From 11df605c2e065e123e58bd73525e7ca2113f40b8 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 24 Feb 2015 00:45:03 -0800 Subject: support rel=me on channel "homepage" url --- include/identity.php | 2 +- include/text.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'include') diff --git a/include/identity.php b/include/identity.php index 415e85f2f..f63b576b2 100644 --- a/include/identity.php +++ b/include/identity.php @@ -893,7 +893,7 @@ function profile_sidebar($profile, $block = 0, $show_connect = true) { || (x($profile,'country_name') == 1)) $location = t('Location:'); - $profile['homepage'] = linkify($profile['homepage']); + $profile['homepage'] = linkify($profile['homepage'],true); $gender = ((x($profile,'gender') == 1) ? t('Gender:') : False); $marital = ((x($profile,'marital') == 1) ? t('Status:') : False); diff --git a/include/text.php b/include/text.php index c93bc4e70..2a524f7f1 100644 --- a/include/text.php +++ b/include/text.php @@ -873,8 +873,8 @@ function valid_email($x){ */ -function linkify($s) { - $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\@\~\#\'\%\$\!\+]*)/", ' $1', $s); +function linkify($s,$me = false) { + $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\@\~\#\'\%\$\!\+]*)/", (($me) ? ' $1' : ' $1'), $s); $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s); return($s); } -- cgit v1.2.3 From 08f054130f5a57e2928e129131e7609271ec7f40 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 24 Feb 2015 16:36:27 -0800 Subject: require access token to view, query, or join directories in private realms, if the realm is so configured. --- include/dir_fns.php | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) (limited to 'include') diff --git a/include/dir_fns.php b/include/dir_fns.php index 686c5140f..37a7c04e7 100644 --- a/include/dir_fns.php +++ b/include/dir_fns.php @@ -48,7 +48,7 @@ function check_upstream_directory() { if($directory) { $h = parse_url($directory); if($h) { - $x = zot_finger('sys@' . $h['host']); + $x = zot_finger('[system]@' . $h['host']); if($x['success']) { $j = json_decode($x['body'],true); if(array_key_exists('site',$j) && array_key_exists('directory_mode',$j['site'])) { @@ -166,20 +166,23 @@ function sync_directories($dirmode) { // FIXME - what to do if we're in a different realm? if((! $r) && (z_root() != DIRECTORY_FALLBACK_MASTER)) { - $r = array( + $r = array(); + $r[] = array( 'site_url' => DIRECTORY_FALLBACK_MASTER, 'site_flags' => DIRECTORY_MODE_PRIMARY, 'site_update' => NULL_DATE, 'site_directory' => DIRECTORY_FALLBACK_MASTER . '/dirsearch', - 'site_realm' => DIRECTORY_REALM + 'site_realm' => DIRECTORY_REALM, + 'site_valid' => 1 ); - $x = q("insert into site ( site_url, site_flags, site_update, site_directory, site_realm ) + $x = q("insert into site ( site_url, site_flags, site_update, site_directory, site_realm, site_valid ) values ( '%s', %d', '%s', '%s', '%s' ) ", dbesc($r[0]['site_url']), intval($r[0]['site_flags']), dbesc($r[0]['site_update']), dbesc($r[0]['site_directory']), - dbesc($r[0]['site_realm']) + dbesc($r[0]['site_realm']), + intval($r[0]['site_valid']) ); $r = q("select * from site where (site_flags & %d) > 0 and site_url != '%s'", @@ -201,8 +204,11 @@ function sync_directories($dirmode) { // It will take about a month for a new directory to obtain the full current repertoire of channels. // FIXME - go back and pick up earlier ratings if this is a new directory server. These do not get refreshed. + $token = get_config('system','realm_token'); + + $syncdate = (($rr['site_sync'] === NULL_DATE) ? datetime_convert('UTC','UTC','now - 2 days') : $rr['site_sync']); - $x = z_fetch_url($rr['site_directory'] . '?f=&sync=' . urlencode($syncdate)); + $x = z_fetch_url($rr['site_directory'] . '?f=&sync=' . urlencode($syncdate) . (($token) ? '&t=' . $token : '')); if(! $x['success']) continue; -- cgit v1.2.3 From 1434130264836916001fe191dd237e51af5c6e3e Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 24 Feb 2015 20:21:21 -0800 Subject: don't send deleted items upstream - only downstream. --- include/notifier.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'include') diff --git a/include/notifier.php b/include/notifier.php index fe6ac33c0..c77857087 100644 --- a/include/notifier.php +++ b/include/notifier.php @@ -315,9 +315,12 @@ function notifier_run($argv, $argc){ $r = fetch_post_tags($r); $target_item = $r[0]; + $deleted_item = false; - if($target_item['item_restrict'] & ITEM_DELETED) + if($target_item['item_restrict'] & ITEM_DELETED) { logger('notifier: target item ITEM_DELETED', LOGGER_DEBUG); + $deleted_item = true; + } $unforwardable = ITEM_UNPUBLISHED|ITEM_DELAYED_PUBLISH|ITEM_WEBPAGE|ITEM_BUILDBLOCK|ITEM_PDL; if($target_item['item_restrict'] & $unforwardable) { @@ -376,7 +379,7 @@ function notifier_run($argv, $argc){ // tag_deliver'd post which needs to be sent back to the original author - if(($cmd === 'uplink') && ($parent_item['item_flags'] & ITEM_UPLINK) && (! $top_level_post)) { + if(($cmd === 'uplink') && ($parent_item['item_flags'] & ITEM_UPLINK) && (! $top_level_post) && (! $deleted_item)) { logger('notifier: uplink'); $uplink = true; } @@ -397,7 +400,7 @@ function notifier_run($argv, $argc){ // if our parent is a tag_delivery recipient, uplink to the original author causing // a delivery fork. - if(($parent_item['item_flags'] & ITEM_UPLINK) && (! $top_level_post) && ($cmd !== 'uplink')) { + if(($parent_item['item_flags'] & ITEM_UPLINK) && (! $top_level_post) && ($cmd !== 'uplink') && (! $deleted_item)) { logger('notifier: uplinking this item'); proc_run('php','include/notifier.php','uplink',$item_id); } -- cgit v1.2.3 From 2a2cc309ce2f9a991978d7dda841663825a95370 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 25 Feb 2015 01:39:45 -0800 Subject: solve some (hopefully most) missing delivery issues --- include/zot.php | 68 ++++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 55 insertions(+), 13 deletions(-) (limited to 'include') diff --git a/include/zot.php b/include/zot.php index b19b1474a..6068c5e8c 100644 --- a/include/zot.php +++ b/include/zot.php @@ -1295,9 +1295,33 @@ function public_recips($msg) { $check_mentions = true; } else { - $col = 'channel_w_comment'; - $field = PERMS_W_COMMENT; + // This doesn't look like it works so I have to explain what happened. These are my + // notes (below) from when I got this section of code working. + + // ... so public_recips and allowed_public_recips is working so much better + // than before, but was still not quite right. We seem to be getting all the right + // results for top-level posts now, but comments aren't getting through on channels + // for which we've allowed them to send us their stream, but not comment on our posts. + // The reason is we were seeing if they could comment - and we only need to do that if + // we own the post. If they own the post, we only need to check if they can send us their stream. + + // if this is a comment and it wasn't sent by the post owner, check to see who is allowing them to comment. + // We should have one specific recipient and this step shouldn't be needed unless somebody stuffed up + // their software. We may need this step to protect us from bad guys intentionally stuffing up their software. + // If it is sent by the post owner, we don't need to do this. We only need to see who is receiving the + // owner's stream (which was already set above) - as they control the comment permissions, not us. + + // Note that by doing this we introduce another bug because some public forums have channel_w_stream + // permissions set to themselves only. We also need in this function to add these public forums to the + // public recipient list based on if they are tagged or not and have tag permissions. This is complicated + // by the fact that this activity doesn't have the public forum tag. It's the parent activity that + // contains the tag. we'll solve that further below. + + if($msg['notify']['sender']['guid_sig'] != $msg['message']['owner']['guid_sig']) { + $col = 'channel_w_comment'; + $field = PERMS_W_COMMENT; + } } } elseif($msg['message']['type'] === 'mail') { @@ -1359,22 +1383,40 @@ function public_recips($msg) { // look for any public mentions on this site // They will get filtered by tgroup_check() so we don't need to check permissions now - if($check_mentions && $msg['message']['tags']) { - if(is_array($msg['message']['tags']) && $msg['message']['tags']) { - foreach($msg['message']['tags'] as $tag) { - if(($tag['type'] === 'mention') && (strpos($tag['url'],z_root()) !== false)) { - $address = basename($tag['url']); - if($address) { - $z = q("select channel_hash as hash from channel where channel_address = '%s' limit 1", - dbesc($address) - ); - if($z) - $r = array_merge($r,$z); + if($check_mentions) { + // It's a top level post. Look at the tags. See if any of them are mentions and are on this hub. + if($msg['message']['tags']) { + if(is_array($msg['message']['tags']) && $msg['message']['tags']) { + foreach($msg['message']['tags'] as $tag) { + if(($tag['type'] === 'mention') && (strpos($tag['url'],z_root()) !== false)) { + $address = basename($tag['url']); + if($address) { + $z = q("select channel_hash as hash from channel where channel_address = '%s' limit 1", + dbesc($address) + ); + if($z) + $r = array_merge($r,$z); + } } } } } } + else { + // this is a comment. Find any parent with ITEM_UPLINK set. + if($msg['message']['message_top']) { + $z = q("select owner_xchan as hash from item where parent_mid = '%s' and ( item_flags & %d ) > 0 ", + dbesc($msg['message']['message_top']), + intval(ITEM_UPLINK) + ); + if($z) + $r = array_merge($r,$z); + } + } + + // FIXME + // There are probably a lot of duplicates in $r at this point. We really need to filter those out. + // It's a bit of work since it's a multi-dimensional array logger('public_recips: ' . print_r($r,true), LOGGER_DATA); return $r; -- cgit v1.2.3 From 1a071ea4f07d4e3a1dd4199f6523d61f8bbc69b8 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 25 Feb 2015 03:14:49 -0800 Subject: call post_local hooks prior to storing a post that is going to be sourced. There are some fields in the actual stored item that may change when we start the second delivery chain so a few plugins may not deal with these items correctly. Since we only source public items these effects will be slight. --- include/items.php | 2 ++ include/zot.php | 7 +++++++ 2 files changed, 9 insertions(+) (limited to 'include') diff --git a/include/items.php b/include/items.php index 18ce149ed..b1e17b171 100755 --- a/include/items.php +++ b/include/items.php @@ -3136,6 +3136,8 @@ function start_delivery_chain($channel,$item,$item_id,$parent) { intval($item_id) ); + + if($r) proc_run('php','include/notifier.php','tgroup',$item_id); else diff --git a/include/zot.php b/include/zot.php index 6068c5e8c..59d158a0b 100644 --- a/include/zot.php +++ b/include/zot.php @@ -1680,6 +1680,13 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque else { $arr['aid'] = $channel['channel_account_id']; $arr['uid'] = $channel['channel_id']; + + // if it's a sourced post, call the post_local hooks as if it were + // posted locally so that crosspost connectors will be triggered. + + if(check_item_source($arr['uid'],$arr)) + call_hooks('post_local',$arr); + $item_result = item_store($arr); $item_id = 0; if($item_result['success']) { -- cgit v1.2.3 From b32841e2ddc53758957ca3afccb3e045fdf2e9fe Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 25 Feb 2015 15:27:33 -0800 Subject: Found the cause of the delete looping, and I can prevent it going forward. The issue remains what to do about comments which are already in the DB and have ITEM_ORIGIN incorrectly set. We can't exactly reset them because the "original" context has been lost. (Sorry but couldn't resist an insider pun that none of you will be able to follow anyway). Read the comments. --- include/items.php | 11 ++++++++++- include/notifier.php | 9 +++++++-- include/zot.php | 49 +++++++++++++++++++++++++++++++++++++------------ 3 files changed, 54 insertions(+), 15 deletions(-) (limited to 'include') diff --git a/include/items.php b/include/items.php index b1e17b171..b7bdad838 100755 --- a/include/items.php +++ b/include/items.php @@ -3073,7 +3073,16 @@ function start_delivery_chain($channel,$item,$item_id,$parent) { if((! $private) && $new_public_policy) $private = 1; - $flag_bits = $item['item_flags'] | ITEM_WALL|ITEM_ORIGIN; + $flag_bits = $item['item_flags'] | ITEM_WALL; + + // The message didn't necessarily originate on this site, (we'll honour it if it did), + // but the parent post of this thread will be reset as a local post, as it is the top of + // this delivery chain and is coming from this site, regardless of where the original + // originated. + + if(! $parent) + $flag_bits = $flag_bits | ITEM_ORIGIN; + // unset the nocomment bit if it's there. diff --git a/include/notifier.php b/include/notifier.php index c77857087..f64732884 100644 --- a/include/notifier.php +++ b/include/notifier.php @@ -366,6 +366,11 @@ function notifier_run($argv, $argc){ $encoded_item = encode_item($target_item); + // Send comments to the owner to re-deliver to everybody in the conversation + // We only do this if the item in question originated on this site. This prevents looping. + // To clarify, a site accepting a new comment is responsible for sending it to the owner for relay. + // Relaying should never be initiated on a post that arrived from elsewhere. + $relay_to_owner = (((! $top_level_post) && ($target_item['item_flags'] & ITEM_ORIGIN)) ? true : false); $uplink = false; @@ -379,7 +384,7 @@ function notifier_run($argv, $argc){ // tag_deliver'd post which needs to be sent back to the original author - if(($cmd === 'uplink') && ($parent_item['item_flags'] & ITEM_UPLINK) && (! $top_level_post) && (! $deleted_item)) { + if(($cmd === 'uplink') && ($parent_item['item_flags'] & ITEM_UPLINK) && (! $top_level_post)) { logger('notifier: uplink'); $uplink = true; } @@ -400,7 +405,7 @@ function notifier_run($argv, $argc){ // if our parent is a tag_delivery recipient, uplink to the original author causing // a delivery fork. - if(($parent_item['item_flags'] & ITEM_UPLINK) && (! $top_level_post) && ($cmd !== 'uplink') && (! $deleted_item)) { + if(($parent_item['item_flags'] & ITEM_UPLINK) && (! $top_level_post) && ($cmd !== 'uplink')) { logger('notifier: uplinking this item'); proc_run('php','include/notifier.php','uplink',$item_id); } diff --git a/include/zot.php b/include/zot.php index 59d158a0b..455702b06 100644 --- a/include/zot.php +++ b/include/zot.php @@ -1297,7 +1297,9 @@ function public_recips($msg) { else { // This doesn't look like it works so I have to explain what happened. These are my - // notes (below) from when I got this section of code working. + // notes (below) from when I got this section of code working. You would think that + // we only have to find those with the requisite stream or comment permissions, + // depending on whether this is a top-level post or a comment - but you would be wrong. // ... so public_recips and allowed_public_recips is working so much better // than before, but was still not quite right. We seem to be getting all the right @@ -1403,9 +1405,12 @@ function public_recips($msg) { } } else { - // this is a comment. Find any parent with ITEM_UPLINK set. + // This is a comment. We need to find any parent with ITEM_UPLINK set. But in fact, let's just return + // everybody that stored a copy of the parent. This way we know we're covered. We'll check the + // comment permissions when we deliver them. + if($msg['message']['message_top']) { - $z = q("select owner_xchan as hash from item where parent_mid = '%s' and ( item_flags & %d ) > 0 ", + $z = q("select owner_xchan as hash from item where parent_mid = '%s' ", dbesc($msg['message']['message_top']), intval(ITEM_UPLINK) ); @@ -1414,10 +1419,22 @@ function public_recips($msg) { } } - // FIXME - // There are probably a lot of duplicates in $r at this point. We really need to filter those out. + // There are probably a lot of duplicates in $r at this point. We need to filter those out. // It's a bit of work since it's a multi-dimensional array + if($r) { + $uniq = array(); + + foreach($r as $rr) { + if(! in_array($rr['hash'],$uniq)) + $uniq[] = $rr['hash']; + } + $r = array(); + foreach($uniq as $rr) { + $r[] = array('hash' => $rr); + } + } + logger('public_recips: ' . print_r($r,true), LOGGER_DATA); return $r; } @@ -1427,9 +1444,16 @@ function public_recips($msg) { function allowed_public_recips($msg) { - logger('allowed_public_recips: ' . print_r($msg,true),LOGGER_DATA); + if(array_key_exists('public_scope',$msg['message'])) + $scope = $msg['message']['public_scope']; + + // Mail won't have a public scope. + // in fact, it's doubtful mail will ever get here since it almost universally + // has a recipient, but in fact we don't require this, so it's technically + // possible to send mail to anybody that's listening. + $recips = public_recips($msg); if(! $recips) @@ -1438,11 +1462,6 @@ function allowed_public_recips($msg) { if($msg['message']['type'] === 'mail') return $recips; - if(array_key_exists('public_scope',$msg['message'])) - $scope = $msg['message']['public_scope']; - - $hash = make_xchan_hash($msg['notify']['sender']['guid'],$msg['notify']['sender']['guid_sig']); - if($scope === 'public' || $scope === 'network: red' || $scope === 'authenticated') return $recips; @@ -1454,12 +1473,17 @@ function allowed_public_recips($msg) { } if($scope === 'self') { + + $hash = make_xchan_hash($msg['notify']['sender']['guid'],$msg['notify']['sender']['guid_sig']); + foreach($recips as $r) if($r['hash'] === $hash) return array('hash' => $hash); } - if($scope === 'contacts') { + // note: we shouldn't ever see $scope === 'specific' in this function, but handle it anyway + + if($scope === 'contacts' || $scope === 'any connections' || $scope === 'specific') { $condensed_recips = array(); foreach($recips as $rr) $condensed_recips[] = $rr['hash']; @@ -1477,6 +1501,7 @@ function allowed_public_recips($msg) { return $results; } + return array(); } -- cgit v1.2.3 From b9e485be54317b68c994c5ffa3b2ffe21f767775 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 25 Feb 2015 16:51:39 -0800 Subject: this may actually fix the deliver loop when deleting existing items. It's hackish but I don't see any other way out. --- include/items.php | 15 +++++++++++++++ include/notifier.php | 9 ++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) (limited to 'include') diff --git a/include/items.php b/include/items.php index b7bdad838..d6c6f5043 100755 --- a/include/items.php +++ b/include/items.php @@ -4799,3 +4799,18 @@ function set_linkified_perms($linkified, &$str_contact_allow, &$str_group_allow, } } } + + +/* + * We can't trust ITEM_ORIGIN to tell us if this is a local comment + * which needs to be relayed, because it was misconfigured at one point for several + * months and set for some remote items (in alternate delivery chains). This could + * cause looping, so use this hackish but accurate method. + */ + + +function comment_local_origin($item) { + if(stripos($item['mid'],get_app()->get_hostname()) && ($item['parent'] != $item['id'])) + return true; + return false; +} \ No newline at end of file diff --git a/include/notifier.php b/include/notifier.php index f64732884..22adc78a3 100644 --- a/include/notifier.php +++ b/include/notifier.php @@ -371,7 +371,14 @@ function notifier_run($argv, $argc){ // To clarify, a site accepting a new comment is responsible for sending it to the owner for relay. // Relaying should never be initiated on a post that arrived from elsewhere. - $relay_to_owner = (((! $top_level_post) && ($target_item['item_flags'] & ITEM_ORIGIN)) ? true : false); + // We should normally be able to rely on ITEM_ORIGIN, but start_delivery_chain() incorrectly set this + // flag on comments for an extended period. So we'll also call comment_local_origin() which looks at + // the hostname in the message_id and provides a second (fallback) opinion. + + $relay_to_owner = (((! $top_level_post) && ($target_item['item_flags'] & ITEM_ORIGIN) && comment_local_origin()) + ? true + : false + ); $uplink = false; -- cgit v1.2.3 From ac3384e661115fac5d771f62fc3eaa1587e5326f Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 25 Feb 2015 17:24:09 -0800 Subject: syntax - missing arg --- include/notifier.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/notifier.php b/include/notifier.php index 22adc78a3..36a52b209 100644 --- a/include/notifier.php +++ b/include/notifier.php @@ -375,7 +375,7 @@ function notifier_run($argv, $argc){ // flag on comments for an extended period. So we'll also call comment_local_origin() which looks at // the hostname in the message_id and provides a second (fallback) opinion. - $relay_to_owner = (((! $top_level_post) && ($target_item['item_flags'] & ITEM_ORIGIN) && comment_local_origin()) + $relay_to_owner = (((! $top_level_post) && ($target_item['item_flags'] & ITEM_ORIGIN) && comment_local_origin($target_item)) ? true : false ); -- cgit v1.2.3 From b57010e3da6c0521121a622c27013c8af7678132 Mon Sep 17 00:00:00 2001 From: Habeas Codice Date: Thu, 26 Feb 2015 08:20:29 -0800 Subject: more fake null shenanigans --- include/zot.php | 117 +++++++++++--------------------------------------------- 1 file changed, 23 insertions(+), 94 deletions(-) (limited to 'include') diff --git a/include/zot.php b/include/zot.php index 455702b06..9a5a0898c 100644 --- a/include/zot.php +++ b/include/zot.php @@ -1295,35 +1295,9 @@ function public_recips($msg) { $check_mentions = true; } else { + $col = 'channel_w_comment'; + $field = PERMS_W_COMMENT; - // This doesn't look like it works so I have to explain what happened. These are my - // notes (below) from when I got this section of code working. You would think that - // we only have to find those with the requisite stream or comment permissions, - // depending on whether this is a top-level post or a comment - but you would be wrong. - - // ... so public_recips and allowed_public_recips is working so much better - // than before, but was still not quite right. We seem to be getting all the right - // results for top-level posts now, but comments aren't getting through on channels - // for which we've allowed them to send us their stream, but not comment on our posts. - // The reason is we were seeing if they could comment - and we only need to do that if - // we own the post. If they own the post, we only need to check if they can send us their stream. - - // if this is a comment and it wasn't sent by the post owner, check to see who is allowing them to comment. - // We should have one specific recipient and this step shouldn't be needed unless somebody stuffed up - // their software. We may need this step to protect us from bad guys intentionally stuffing up their software. - // If it is sent by the post owner, we don't need to do this. We only need to see who is receiving the - // owner's stream (which was already set above) - as they control the comment permissions, not us. - - // Note that by doing this we introduce another bug because some public forums have channel_w_stream - // permissions set to themselves only. We also need in this function to add these public forums to the - // public recipient list based on if they are tagged or not and have tag permissions. This is complicated - // by the fact that this activity doesn't have the public forum tag. It's the parent activity that - // contains the tag. we'll solve that further below. - - if($msg['notify']['sender']['guid_sig'] != $msg['message']['owner']['guid_sig']) { - $col = 'channel_w_comment'; - $field = PERMS_W_COMMENT; - } } } elseif($msg['message']['type'] === 'mail') { @@ -1385,55 +1359,22 @@ function public_recips($msg) { // look for any public mentions on this site // They will get filtered by tgroup_check() so we don't need to check permissions now - if($check_mentions) { - // It's a top level post. Look at the tags. See if any of them are mentions and are on this hub. - if($msg['message']['tags']) { - if(is_array($msg['message']['tags']) && $msg['message']['tags']) { - foreach($msg['message']['tags'] as $tag) { - if(($tag['type'] === 'mention') && (strpos($tag['url'],z_root()) !== false)) { - $address = basename($tag['url']); - if($address) { - $z = q("select channel_hash as hash from channel where channel_address = '%s' limit 1", - dbesc($address) - ); - if($z) - $r = array_merge($r,$z); - } + if($check_mentions && $msg['message']['tags']) { + if(is_array($msg['message']['tags']) && $msg['message']['tags']) { + foreach($msg['message']['tags'] as $tag) { + if(($tag['type'] === 'mention') && (strpos($tag['url'],z_root()) !== false)) { + $address = basename($tag['url']); + if($address) { + $z = q("select channel_hash as hash from channel where channel_address = '%s' limit 1", + dbesc($address) + ); + if($z) + $r = array_merge($r,$z); } } } } } - else { - // This is a comment. We need to find any parent with ITEM_UPLINK set. But in fact, let's just return - // everybody that stored a copy of the parent. This way we know we're covered. We'll check the - // comment permissions when we deliver them. - - if($msg['message']['message_top']) { - $z = q("select owner_xchan as hash from item where parent_mid = '%s' ", - dbesc($msg['message']['message_top']), - intval(ITEM_UPLINK) - ); - if($z) - $r = array_merge($r,$z); - } - } - - // There are probably a lot of duplicates in $r at this point. We need to filter those out. - // It's a bit of work since it's a multi-dimensional array - - if($r) { - $uniq = array(); - - foreach($r as $rr) { - if(! in_array($rr['hash'],$uniq)) - $uniq[] = $rr['hash']; - } - $r = array(); - foreach($uniq as $rr) { - $r[] = array('hash' => $rr); - } - } logger('public_recips: ' . print_r($r,true), LOGGER_DATA); return $r; @@ -1444,15 +1385,8 @@ function public_recips($msg) { function allowed_public_recips($msg) { - logger('allowed_public_recips: ' . print_r($msg,true),LOGGER_DATA); - - if(array_key_exists('public_scope',$msg['message'])) - $scope = $msg['message']['public_scope']; - // Mail won't have a public scope. - // in fact, it's doubtful mail will ever get here since it almost universally - // has a recipient, but in fact we don't require this, so it's technically - // possible to send mail to anybody that's listening. + logger('allowed_public_recips: ' . print_r($msg,true),LOGGER_DATA); $recips = public_recips($msg); @@ -1462,6 +1396,11 @@ function allowed_public_recips($msg) { if($msg['message']['type'] === 'mail') return $recips; + if(array_key_exists('public_scope',$msg['message'])) + $scope = $msg['message']['public_scope']; + + $hash = make_xchan_hash($msg['notify']['sender']['guid'],$msg['notify']['sender']['guid_sig']); + if($scope === 'public' || $scope === 'network: red' || $scope === 'authenticated') return $recips; @@ -1473,17 +1412,12 @@ function allowed_public_recips($msg) { } if($scope === 'self') { - - $hash = make_xchan_hash($msg['notify']['sender']['guid'],$msg['notify']['sender']['guid_sig']); - foreach($recips as $r) if($r['hash'] === $hash) return array('hash' => $hash); } - // note: we shouldn't ever see $scope === 'specific' in this function, but handle it anyway - - if($scope === 'contacts' || $scope === 'any connections' || $scope === 'specific') { + if($scope === 'contacts') { $condensed_recips = array(); foreach($recips as $rr) $condensed_recips[] = $rr['hash']; @@ -1501,7 +1435,6 @@ function allowed_public_recips($msg) { return $results; } - return array(); } @@ -1705,13 +1638,6 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque else { $arr['aid'] = $channel['channel_account_id']; $arr['uid'] = $channel['channel_id']; - - // if it's a sourced post, call the post_local hooks as if it were - // posted locally so that crosspost connectors will be triggered. - - if(check_item_source($arr['uid'],$arr)) - call_hooks('post_local',$arr); - $item_result = item_store($arr); $item_id = 0; if($item_result['success']) { @@ -2880,6 +2806,9 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { if(count($clean)) { foreach($clean as $k => $v) { + if($k == 'abook_dob') + $v = dbescdate($v); + $r = dbq("UPDATE abook set " . dbesc($k) . " = '" . dbesc($v) . "' where abook_xchan = '" . dbesc($clean['abook_xchan']) . "' and abook_channel = " . intval($channel['channel_id'])); } -- cgit v1.2.3 From f55e2101209c34faf1cc6d4d568c8b55af4a1ecb Mon Sep 17 00:00:00 2001 From: Habeas Codice Date: Thu, 26 Feb 2015 08:22:15 -0800 Subject: Revert "more fake null shenanigans" This reverts commit b57010e3da6c0521121a622c27013c8af7678132. --- include/zot.php | 117 +++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 94 insertions(+), 23 deletions(-) (limited to 'include') diff --git a/include/zot.php b/include/zot.php index 9a5a0898c..455702b06 100644 --- a/include/zot.php +++ b/include/zot.php @@ -1295,9 +1295,35 @@ function public_recips($msg) { $check_mentions = true; } else { - $col = 'channel_w_comment'; - $field = PERMS_W_COMMENT; + // This doesn't look like it works so I have to explain what happened. These are my + // notes (below) from when I got this section of code working. You would think that + // we only have to find those with the requisite stream or comment permissions, + // depending on whether this is a top-level post or a comment - but you would be wrong. + + // ... so public_recips and allowed_public_recips is working so much better + // than before, but was still not quite right. We seem to be getting all the right + // results for top-level posts now, but comments aren't getting through on channels + // for which we've allowed them to send us their stream, but not comment on our posts. + // The reason is we were seeing if they could comment - and we only need to do that if + // we own the post. If they own the post, we only need to check if they can send us their stream. + + // if this is a comment and it wasn't sent by the post owner, check to see who is allowing them to comment. + // We should have one specific recipient and this step shouldn't be needed unless somebody stuffed up + // their software. We may need this step to protect us from bad guys intentionally stuffing up their software. + // If it is sent by the post owner, we don't need to do this. We only need to see who is receiving the + // owner's stream (which was already set above) - as they control the comment permissions, not us. + + // Note that by doing this we introduce another bug because some public forums have channel_w_stream + // permissions set to themselves only. We also need in this function to add these public forums to the + // public recipient list based on if they are tagged or not and have tag permissions. This is complicated + // by the fact that this activity doesn't have the public forum tag. It's the parent activity that + // contains the tag. we'll solve that further below. + + if($msg['notify']['sender']['guid_sig'] != $msg['message']['owner']['guid_sig']) { + $col = 'channel_w_comment'; + $field = PERMS_W_COMMENT; + } } } elseif($msg['message']['type'] === 'mail') { @@ -1359,22 +1385,55 @@ function public_recips($msg) { // look for any public mentions on this site // They will get filtered by tgroup_check() so we don't need to check permissions now - if($check_mentions && $msg['message']['tags']) { - if(is_array($msg['message']['tags']) && $msg['message']['tags']) { - foreach($msg['message']['tags'] as $tag) { - if(($tag['type'] === 'mention') && (strpos($tag['url'],z_root()) !== false)) { - $address = basename($tag['url']); - if($address) { - $z = q("select channel_hash as hash from channel where channel_address = '%s' limit 1", - dbesc($address) - ); - if($z) - $r = array_merge($r,$z); + if($check_mentions) { + // It's a top level post. Look at the tags. See if any of them are mentions and are on this hub. + if($msg['message']['tags']) { + if(is_array($msg['message']['tags']) && $msg['message']['tags']) { + foreach($msg['message']['tags'] as $tag) { + if(($tag['type'] === 'mention') && (strpos($tag['url'],z_root()) !== false)) { + $address = basename($tag['url']); + if($address) { + $z = q("select channel_hash as hash from channel where channel_address = '%s' limit 1", + dbesc($address) + ); + if($z) + $r = array_merge($r,$z); + } } } } } } + else { + // This is a comment. We need to find any parent with ITEM_UPLINK set. But in fact, let's just return + // everybody that stored a copy of the parent. This way we know we're covered. We'll check the + // comment permissions when we deliver them. + + if($msg['message']['message_top']) { + $z = q("select owner_xchan as hash from item where parent_mid = '%s' ", + dbesc($msg['message']['message_top']), + intval(ITEM_UPLINK) + ); + if($z) + $r = array_merge($r,$z); + } + } + + // There are probably a lot of duplicates in $r at this point. We need to filter those out. + // It's a bit of work since it's a multi-dimensional array + + if($r) { + $uniq = array(); + + foreach($r as $rr) { + if(! in_array($rr['hash'],$uniq)) + $uniq[] = $rr['hash']; + } + $r = array(); + foreach($uniq as $rr) { + $r[] = array('hash' => $rr); + } + } logger('public_recips: ' . print_r($r,true), LOGGER_DATA); return $r; @@ -1385,9 +1444,16 @@ function public_recips($msg) { function allowed_public_recips($msg) { - logger('allowed_public_recips: ' . print_r($msg,true),LOGGER_DATA); + if(array_key_exists('public_scope',$msg['message'])) + $scope = $msg['message']['public_scope']; + + // Mail won't have a public scope. + // in fact, it's doubtful mail will ever get here since it almost universally + // has a recipient, but in fact we don't require this, so it's technically + // possible to send mail to anybody that's listening. + $recips = public_recips($msg); if(! $recips) @@ -1396,11 +1462,6 @@ function allowed_public_recips($msg) { if($msg['message']['type'] === 'mail') return $recips; - if(array_key_exists('public_scope',$msg['message'])) - $scope = $msg['message']['public_scope']; - - $hash = make_xchan_hash($msg['notify']['sender']['guid'],$msg['notify']['sender']['guid_sig']); - if($scope === 'public' || $scope === 'network: red' || $scope === 'authenticated') return $recips; @@ -1412,12 +1473,17 @@ function allowed_public_recips($msg) { } if($scope === 'self') { + + $hash = make_xchan_hash($msg['notify']['sender']['guid'],$msg['notify']['sender']['guid_sig']); + foreach($recips as $r) if($r['hash'] === $hash) return array('hash' => $hash); } - if($scope === 'contacts') { + // note: we shouldn't ever see $scope === 'specific' in this function, but handle it anyway + + if($scope === 'contacts' || $scope === 'any connections' || $scope === 'specific') { $condensed_recips = array(); foreach($recips as $rr) $condensed_recips[] = $rr['hash']; @@ -1435,6 +1501,7 @@ function allowed_public_recips($msg) { return $results; } + return array(); } @@ -1638,6 +1705,13 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque else { $arr['aid'] = $channel['channel_account_id']; $arr['uid'] = $channel['channel_id']; + + // if it's a sourced post, call the post_local hooks as if it were + // posted locally so that crosspost connectors will be triggered. + + if(check_item_source($arr['uid'],$arr)) + call_hooks('post_local',$arr); + $item_result = item_store($arr); $item_id = 0; if($item_result['success']) { @@ -2806,9 +2880,6 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { if(count($clean)) { foreach($clean as $k => $v) { - if($k == 'abook_dob') - $v = dbescdate($v); - $r = dbq("UPDATE abook set " . dbesc($k) . " = '" . dbesc($v) . "' where abook_xchan = '" . dbesc($clean['abook_xchan']) . "' and abook_channel = " . intval($channel['channel_id'])); } -- cgit v1.2.3 From 82bb21695259afd234031d7f3b41e2478cfc480c Mon Sep 17 00:00:00 2001 From: Habeas Codice Date: Thu, 26 Feb 2015 08:23:02 -0800 Subject: more fake null shenanigans --- include/zot.php | 3 +++ 1 file changed, 3 insertions(+) (limited to 'include') diff --git a/include/zot.php b/include/zot.php index 455702b06..2a0fcd118 100644 --- a/include/zot.php +++ b/include/zot.php @@ -2880,6 +2880,9 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { if(count($clean)) { foreach($clean as $k => $v) { + if($k == 'abook_dob') + $v = dbescdate($v); + $r = dbq("UPDATE abook set " . dbesc($k) . " = '" . dbesc($v) . "' where abook_xchan = '" . dbesc($clean['abook_xchan']) . "' and abook_channel = " . intval($channel['channel_id'])); } -- cgit v1.2.3 From 09f80270defdd2dfbf5cf4cc9da0cae686874aba Mon Sep 17 00:00:00 2001 From: friendica Date: Thu, 26 Feb 2015 14:20:43 -0800 Subject: loop breaker --- include/zot.php | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'include') diff --git a/include/zot.php b/include/zot.php index 455702b06..e290697b6 100644 --- a/include/zot.php +++ b/include/zot.php @@ -1856,7 +1856,23 @@ function delete_imported_item($sender,$item,$uid,$relay) { logger('delete_imported_item: item was already deleted'); if(! $relay) return false; + + // This is a bit hackish, but may have to suffice until the notification/delivery loop is optimised + // a bit further. We're going to strip the ITEM_ORIGIN on this item if it's a comment, because + // it was already deleted, and we're already relaying, and this ensures that no other process or + // code path downstream can relay it again (causing a loop). Since it's already gone it's not coming + // back, and we aren't going to (or shouldn't at any rate) delete it again in the future - so losing + // this information from the metadata should have no other discernible impact. + + if(($r[0]['id'] != $r[0]['parent']) && ($r[0]['item_flags'] & ITEM_ORIGIN)) { + $x = q("update item set item_flags = %d where id = %d and uid = %d", + intval($r[0]['item_flags'] ^ ITEM_ORIGIN), + intval($r[0]['id']), + intval($r[0]['uid']) + ); + } } + require_once('include/items.php'); -- cgit v1.2.3 From 2b44c5fc72ac1a76b0a711d459ddcb52ed6666dc Mon Sep 17 00:00:00 2001 From: friendica Date: Fri, 27 Feb 2015 13:43:12 -0800 Subject: Fix a couple of places where we weren't checking for dead hublocs. Add a function to mark a hubloc dead. --- include/hubloc.php | 11 ++++++++++- include/notifier.php | 19 ++++++++++++++----- 2 files changed, 24 insertions(+), 6 deletions(-) (limited to 'include') diff --git a/include/hubloc.php b/include/hubloc.php index b5a3d47c5..94f1dc985 100644 --- a/include/hubloc.php +++ b/include/hubloc.php @@ -170,7 +170,16 @@ function hubloc_change_primary($hubloc) { return true; } - + +// We use the post url to distinguish between http and https hublocs. +// The https might be alive, and the http dead. + +function hubloc_mark_as_down($posturl) { + $r = q("update hubloc set hubloc_status = ( hubloc_status | %d ) where hubloc_posturl = '%s'", + intval(HUBLOC_OFFLINE) + ); +} + function xchan_store($arr) { diff --git a/include/notifier.php b/include/notifier.php index 36a52b209..a9c4905ae 100644 --- a/include/notifier.php +++ b/include/notifier.php @@ -100,10 +100,14 @@ function notifier_run($argv, $argc){ // Get the recipient $r = q("select abook.*, hubloc.* from abook left join hubloc on hubloc_hash = abook_xchan - where abook_id = %d and not ( abook_flags & %d )>0 limit 1", + where abook_id = %d and not ( abook_flags & %d ) > 0 + and not (hubloc_flags & %d) > 0 and not (hubloc_status & %d) > 0 limit 1", intval($item_id), - intval(ABOOK_FLAG_SELF) + intval(ABOOK_FLAG_SELF), + intval(HUBLOC_FLAGS_DELETED), + intval(HUBLOC_OFFLINE) ); + if($r) { // Get the sender $s = q("select * from channel left join xchan on channel_hash = xchan_hash where channel_id = %d limit 1", @@ -116,8 +120,11 @@ function notifier_run($argv, $argc){ } else { // send a refresh message to each hub they have registered here - $h = q("select * from hubloc where hubloc_hash = '%s'", - dbesc($r[0]['hubloc_hash']) + $h = q("select * from hubloc where hubloc_hash = '%s' + and not (hubloc_flags & %d) > 0 and not (hubloc_status & %d) > 0", + dbesc($r[0]['hubloc_hash']), + intval(HUBLOC_FLAGS_DELETED), + intval(HUBLOC_OFFLINE) ); if($h) { foreach($h as $hh) { @@ -138,7 +145,6 @@ function notifier_run($argv, $argc){ } } } - return; } @@ -491,6 +497,9 @@ function notifier_run($argv, $argc){ logger('notifier: hub choice: ' . intval($relay_to_owner) . ' ' . intval($private) . ' ' . $cmd, LOGGER_DEBUG); + // FIXME: I think we need to remove the private bit or this clause will never execute. Needs more coffee to think it through. + // We may in fact have to send it to clones in case the one we pick recently died. + if($relay_to_owner && (! $private) && ($cmd !== 'relay')) { // If sending a followup to the post owner, only send it to one channel clone - to avoid race conditions. -- cgit v1.2.3 From ba7bdd79b720dcb58dfd88a38f43444eb4da06f4 Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 1 Mar 2015 15:55:27 -0800 Subject: queue management actions. Still needs further work such as indication of last successful connection or indication that the hub was marked offline, but these are potentially expensive queries. --- include/hubloc.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/hubloc.php b/include/hubloc.php index 94f1dc985..98c1a21f3 100644 --- a/include/hubloc.php +++ b/include/hubloc.php @@ -175,8 +175,9 @@ function hubloc_change_primary($hubloc) { // The https might be alive, and the http dead. function hubloc_mark_as_down($posturl) { - $r = q("update hubloc set hubloc_status = ( hubloc_status | %d ) where hubloc_posturl = '%s'", - intval(HUBLOC_OFFLINE) + $r = q("update hubloc set hubloc_status = ( hubloc_status | %d ) where hubloc_callback = '%s'", + intval(HUBLOC_OFFLINE), + dbesc($posturl) ); } -- cgit v1.2.3 From d83460cd2ae5216208a17154d7a9858a5a633b33 Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 1 Mar 2015 18:58:50 -0800 Subject: The never ending saga of parent = 0 bugs on Dreamhost. --- include/items.php | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'include') diff --git a/include/items.php b/include/items.php index d6c6f5043..8f16d23c1 100755 --- a/include/items.php +++ b/include/items.php @@ -2087,6 +2087,16 @@ function item_store($arr,$allow_exec = false) { if($r) { + // in case item_store was killed before the parent's parent attribute got set, + // set it now. This happens with some regularity on Dreamhost. This will keep + // us from getting notifications for threads that exist but which we can't see. + + if(($r[0]['mid'] === $r[0]['parent_mid']) && (! intval($r[0]['parent']))) { + q("update item set parent = id where id = %d", + intval($r[0]['id']) + ); + } + if(comments_are_now_closed($r[0])) { logger('item_store: comments closed'); $ret['message'] = 'Comments closed.'; -- cgit v1.2.3 From 36af4265380e2555d35d7dfbf912b657af45b26c Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 1 Mar 2015 20:14:42 -0800 Subject: Nag hub admins with self-signed certs to fix them. Otherwise we'll just have to start marking them as dead sites. --- include/poller.php | 1 + 1 file changed, 1 insertion(+) (limited to 'include') diff --git a/include/poller.php b/include/poller.php index fd78ce087..06311eb39 100644 --- a/include/poller.php +++ b/include/poller.php @@ -150,6 +150,7 @@ function poller_run($argv, $argc){ call_hooks('cron_weekly',datetime_convert()); + z_check_cert(); require_once('include/hubloc.php'); prune_hub_reinstalls(); -- cgit v1.2.3 From 7d0783c4dd08b63033d403d462ee2f30ef7100a6 Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 1 Mar 2015 23:50:31 -0800 Subject: increase the dynamic range of the tag clouds slightly. --- include/taxonomy.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/taxonomy.php b/include/taxonomy.php index d36c05db2..3d1ac7058 100644 --- a/include/taxonomy.php +++ b/include/taxonomy.php @@ -152,7 +152,7 @@ function tagadelic($uid, $count = 0, $authors = '', $flags = 0, $restrict = 0, $ $range = max(.01, $max - $min) * 1.0001; for($x = 0; $x < count($tags); $x ++) { - $tags[$x][2] = 1 + floor(5 * ($tags[$x][1] - $min) / $range); + $tags[$x][2] = 1 + floor(7 * ($tags[$x][1] - $min) / $range); } return $tags; -- cgit v1.2.3 From e4a2e353d8bc02f6a4e61d6cca999a098f34f593 Mon Sep 17 00:00:00 2001 From: zottel Date: Mon, 2 Mar 2015 11:05:03 +0100 Subject: make public delivery to contacts or any connections work again $hash wasn't defined in this case --- include/zot.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'include') diff --git a/include/zot.php b/include/zot.php index b09f65b7b..e1c780742 100644 --- a/include/zot.php +++ b/include/zot.php @@ -1472,10 +1472,9 @@ function allowed_public_recips($msg) { return array(); } - if($scope === 'self') { - - $hash = make_xchan_hash($msg['notify']['sender']['guid'],$msg['notify']['sender']['guid_sig']); + $hash = make_xchan_hash($msg['notify']['sender']['guid'],$msg['notify']['sender']['guid_sig']); + if($scope === 'self') { foreach($recips as $r) if($r['hash'] === $hash) return array('hash' => $hash); -- cgit v1.2.3 From e6eee5ba92bc64ea0c9855831bddf66acccd9bee Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 2 Mar 2015 11:09:38 -0800 Subject: tagcloud tweaks --- include/taxonomy.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/taxonomy.php b/include/taxonomy.php index 3d1ac7058..ef3639067 100644 --- a/include/taxonomy.php +++ b/include/taxonomy.php @@ -152,7 +152,7 @@ function tagadelic($uid, $count = 0, $authors = '', $flags = 0, $restrict = 0, $ $range = max(.01, $max - $min) * 1.0001; for($x = 0; $x < count($tags); $x ++) { - $tags[$x][2] = 1 + floor(7 * ($tags[$x][1] - $min) / $range); + $tags[$x][2] = 1 + floor(9 * ($tags[$x][1] - $min) / $range); } return $tags; @@ -199,7 +199,7 @@ function dir_tagadelic($count = 0) { $range = max(.01, $max - $min) * 1.0001; for($x = 0; $x < count($tags); $x ++) { - $tags[$x][2] = 1 + floor(5 * ($tags[$x][1] - $min) / $range); + $tags[$x][2] = 1 + floor(9 * ($tags[$x][1] - $min) / $range); } return $tags; -- cgit v1.2.3 From 0d601563d02d7e9b7414586486f1623a93cf958b Mon Sep 17 00:00:00 2001 From: Klaus Weidenbach Date: Wed, 4 Mar 2015 00:03:19 +0100 Subject: Some cleanups and documentation. Fixed some wrong variable names. Initialized some variables before using them. Removed some checks for STATUSNET_PRIVACY_COMPATIBILITY in include/security.php as it does not seem to be defined anywhere. --- include/bookmarks.php | 2 +- include/comanche.php | 54 +++++++++++----------- include/language.php | 15 ++++--- include/photos.php | 75 +++++++++++++++++++------------ include/security.php | 36 ++++++--------- include/socgraph.php | 46 +++++++------------ include/taxonomy.php | 121 ++++++++++++++++++++++++++------------------------ 7 files changed, 174 insertions(+), 175 deletions(-) (limited to 'include') diff --git a/include/bookmarks.php b/include/bookmarks.php index e70158476..c6e8e86f2 100644 --- a/include/bookmarks.php +++ b/include/bookmarks.php @@ -9,7 +9,7 @@ function bookmark_add($channel,$sender,$taxonomy,$private,$opts = null) { $ischat = false; if(is_array($opts)) { - $menu_id = ((x($opts,'menu_id')) ? intval($opt['menu_id']) : 0); + $menu_id = ((x($opts,'menu_id')) ? intval($opts['menu_id']) : 0); $menu_name = ((x($opts,'menu_name')) ? escape_tags($opts['menu_name']) : ''); $ischat = ((x($opts,'ischat')) ? intval($opts['ischat']) : 0); } diff --git a/include/comanche.php b/include/comanche.php index b181d415a..9db375c38 100644 --- a/include/comanche.php +++ b/include/comanche.php @@ -15,23 +15,22 @@ require_once('include/widgets.php'); // page layout from the given description -function pdl_selector($uid,$current="") { - +function pdl_selector($uid, $current="") { $o = ''; - $sql_extra = item_permissions_sql($uid); + //$sql_extra = item_permissions_sql($uid); $r = q("select item_id.*, mid from item_id left join item on iid = item.id where item_id.uid = %d and item_id.uid = item.uid and service = 'PDL' order by sid asc", - intval($owner) + intval($uid) ); $arr = array('channel_id' => $uid, 'current' => $current, 'entries' => $r); call_hooks('pdl_selector',$arr); $entries = $arr['entries']; - $current = $arr['current']; - - $o .= "'; $entries[] = array('title' => t('Default'), 'mid' => ''); foreach($entries as $selection) { $selected = (($selection == $current) ? ' selected="selected" ' : ''); @@ -40,16 +39,17 @@ function pdl_selector($uid,$current="") { $o .= ''; return $o; -} +} -function comanche_parser(&$a,$s) { +function comanche_parser(&$a, $s) { + $matches = array(); $cnt = preg_match_all("/\[comment\](.*?)\[\/comment\]/ism", $s, $matches, PREG_SET_ORDER); if($cnt) { foreach($matches as $mtch) { - $s = str_replace($mtch[0],'',$s); + $s = str_replace($mtch[0], '', $s); } } @@ -99,14 +99,14 @@ function comanche_parser(&$a,$s) { function comanche_menu($name,$class = '') { $channel_id = comanche_get_channel_id(); if($channel_id) { - $m = menu_fetch($name,$channel_id,get_observer_hash()); - return menu_render($m,$class); + $m = menu_fetch($name,$channel_id, get_observer_hash()); + return menu_render($m, $class); } } function comanche_replace_region($match) { $a = get_app(); - if(array_key_exists($match[1],$a->page)) { + if(array_key_exists($match[1], $a->page)) { return $a->page[$match[1]]; } } @@ -121,15 +121,15 @@ function comanche_get_channel_id() { $channel_id = ((is_array(get_app()->profile)) ? get_app()->profile['profile_uid'] : 0); if((! $channel_id) && (local_channel())) $channel_id = local_channel(); + return $channel_id; } function comanche_block($name) { - + $o = ''; $channel_id = comanche_get_channel_id(); - + if($channel_id) { - $o = ''; $r = q("select * from item inner join item_id on iid = item.id and item_id.uid = item.uid and item.uid = %d and service = 'BUILDBLOCK' and sid = '%s' limit 1", intval($channel_id), dbesc($name) @@ -138,11 +138,12 @@ function comanche_block($name) { $o = '
      '; if($r[0]['title']) $o .= '

      ' . $r[0]['title'] . '

      '; - $o .= prepare_text($r[0]['body'],$r[0]['mimetype']); - $o .= '
      '; + $o .= prepare_text($r[0]['body'], $r[0]['mimetype']); + $o .= ''; } } + return $o; } @@ -154,8 +155,9 @@ function comanche_block($name) { // of what template and webpage options we might desire. function comanche_webpage(&$a,$s) { - $ret = array(); + $matches = array(); + $cnt = preg_match_all("/\[authored\](.*?)\[\/authored\]/ism", $s, $matches, PREG_SET_ORDER); if($cnt) { foreach($matches as $mtch) { @@ -170,9 +172,10 @@ function comanche_webpage(&$a,$s) { // the global app environment, or config storage until we implement argument passing -function comanche_widget($name,$text) { - $a = get_app(); +function comanche_widget($name, $text) { $vars = array(); + $matches = array(); + $cnt = preg_match_all("/\[var=(.*?)\](.*?)\[\/var\]/ism", $text, $matches, PREG_SET_ORDER); if($cnt) { foreach($matches as $mtch) { @@ -186,12 +189,13 @@ function comanche_widget($name,$text) { } -function comanche_region(&$a,$s) { +function comanche_region(&$a, $s) { + $matches = array(); $cnt = preg_match_all("/\[menu\](.*?)\[\/menu\]/ism", $s, $matches, PREG_SET_ORDER); if($cnt) { foreach($matches as $mtch) { - $s = str_replace($mtch[0],comanche_menu(trim($mtch[1])),$s); + $s = str_replace($mtch[0], comanche_menu(trim($mtch[1])), $s); } } @@ -244,7 +248,3 @@ function register_page_template($arr) { get_app()->page_layouts[$arr['template']] = array($arr['variant']); return; } - - - - diff --git a/include/language.php b/include/language.php index f5ee3471e..ec5fa84fa 100644 --- a/include/language.php +++ b/include/language.php @@ -24,6 +24,7 @@ */ function get_browser_language() { $langs = array(); + $lang_parse = array(); if (x($_SERVER,'HTTP_ACCEPT_LANGUAGE')) { // break up string into pieces (languages and q factors) @@ -33,7 +34,7 @@ function get_browser_language() { if (count($lang_parse[1])) { // create a list like "en" => 0.8 $langs = array_combine($lang_parse[1], $lang_parse[4]); - + // set default to 1 for any without q factor foreach ($langs as $lang => $val) { if ($val === '') $langs[$lang] = 1; @@ -144,16 +145,16 @@ function load_translation_table($lang, $install = false) { /** * @brief translate string if translation exists. * - * @param $s string that should get translated - * @param $ctx optional context to appear in po file + * @param string $s string that should get translated + * @param string $ctx optional context to appear in po file * @return translated string if exists, otherwise return $s * */ -function t($s,$ctx = '') { +function t($s, $ctx = '') { global $a; - $cs = $ctx?"__ctx:".$ctx."__ ".$s:$s; - if(x($a->strings,$cs)) { + $cs = $ctx ? '__ctx:' . $ctx . '__ ' . $s : $s; + if(x($a->strings, $cs)) { $t = $a->strings[$cs]; return is_array($t) ? $t[0] : $t; } @@ -218,7 +219,7 @@ function detect_language($s) { // strip off bbcode $naked_body = preg_replace('/\[(.+?)\]/', '', $naked_body); if(mb_strlen($naked_body) < intval($min_length)) { - logger('detect language: string length less than ' . intval($min_length), LOGGER_DATA); + logger('string length less than ' . intval($min_length), LOGGER_DATA); return ''; } diff --git a/include/photos.php b/include/photos.php index ee94bac60..794ff7748 100644 --- a/include/photos.php +++ b/include/photos.php @@ -53,7 +53,7 @@ function photo_upload($channel, $observer, $args) { $visible = 1; else $visible = 0; - + if(intval($args['not_visible']) || $args['not_visible'] === 'true') $visible = 0; @@ -98,7 +98,6 @@ function photo_upload($channel, $observer, $args) { logger('photo_upload: received file: ' . $filename . ' as ' . $src . ' ('. $type . ') ' . $filesize . ' bytes', LOGGER_DEBUG); - $maximagesize = get_config('system','maximagesize'); if(($maximagesize) && ($filesize > $maximagesize)) { @@ -133,7 +132,6 @@ function photo_upload($channel, $observer, $args) { call_hooks('photo_post_end',$ret); return $ret; } - $ph = photo_factory($imagedata, $type); @@ -185,7 +183,7 @@ function photo_upload($channel, $observer, $args) { $r1 = $ph->save($p); if(! $r1) $errors = true; - + if(($width > 640 || $height > 640) && (! $errors)) { $ph->scaleImage(640); $p['scale'] = 1; @@ -204,7 +202,6 @@ function photo_upload($channel, $observer, $args) { $errors = true; } - if($errors) { q("delete from photo where resource_id = '%s' and uid = %d", dbesc($photo_hash), @@ -220,16 +217,15 @@ function photo_upload($channel, $observer, $args) { $width_x_height = $ph->getWidth() . 'x' . $ph->getHeight(); - $basename = basename($filename); $mid = item_message_id(); // Create item container $item_flags = ITEM_WALL|ITEM_ORIGIN|ITEM_THREAD_TOP; - $item_restrict = (($visible) ? ITEM_VISIBLE : ITEM_HIDDEN); + $item_restrict = (($visible) ? ITEM_VISIBLE : ITEM_HIDDEN); $title = ''; $mid = item_message_id(); - + $arr = array(); $arr['aid'] = $account_id; @@ -254,7 +250,7 @@ function photo_upload($channel, $observer, $args) { // We should also put a width_x_height on large photos. Left as an exercise for // devs looking fo simple stuff to fix. - $larger = feature_enabled($channel['channel_id'],'large_photos'); + $larger = feature_enabled($channel['channel_id'], 'large_photos'); if($larger) { $tag = '[zmg]'; if($r2) @@ -273,7 +269,7 @@ function photo_upload($channel, $observer, $args) { $arr['body'] = '[zrl=' . z_root() . '/photos/' . $channel['channel_address'] . '/image/' . $photo_hash . ']' . $tag . z_root() . "/photo/{$photo_hash}-{$smallest}.".$ph->getExt() . '[/zmg]' . '[/zrl]'; - + $result = item_store($arr); $item_id = $result['item_id']; @@ -291,15 +287,23 @@ function photo_upload($channel, $observer, $args) { return $ret; } - - - -function photos_albums_list($channel,$observer) { +/** + * @brief Returns a list with all photo albums observer is allowed to see. + * + * Returns an associative array with all albums where observer has permissions. + * + * @param array $channel + * @param array $observer + * @return bool|array false if no view_photos permission or an array + * * success (bool) + * * albums (array) + */ +function photos_albums_list($channel, $observer) { $channel_id = $channel['channel_id']; $observer_xchan = (($observer) ? $observer['xchan_hash'] : ''); - if(! perm_is_allowed($channel_id,$observer_xchan,'view_photos')) + if(! perm_is_allowed($channel_id, $observer_xchan, 'view_photos')) return false; // FIXME - create a permissions SQL which works on arbitrary observers and channels, regardless of login or web status @@ -310,7 +314,6 @@ function photos_albums_list($channel,$observer) { intval($channel_id), intval(PHOTO_NORMAL), intval(PHOTO_PROFILE) - ); // add various encodings to the array so we can just loop through and pick them out in a template @@ -330,8 +333,8 @@ function photos_albums_list($channel,$observer) { $ret['albums'][] = $entry; } } - return $ret; + return $ret; } function photos_album_widget($channelx,$observer,$albums = null) { @@ -395,17 +398,32 @@ function photos_list_photos($channel,$observer,$album = '') { return $ret; } - - -function photos_album_exists($channel_id,$album) { - $r = q("SELECT id from photo where album = '%s' and uid = %d limit 1", +/** + * @brief Check if given photo album exists in channel. + * + * @param int $channel_id id of the channel + * @param string $album name of the album + * @return boolean + */ +function photos_album_exists($channel_id, $album) { + $r = q("SELECT id FROM photo WHERE album = '%s' AND uid = %d limit 1", dbesc($album), intval($channel_id) ); + return (($r) ? true : false); } -function photos_album_rename($channel_id,$oldname,$newname) { +/** + * @brief Renames a photo album in a channel. + * + * @todo Do we need to check if new album name already exists? + * @param int $channel_id id of the channel + * @param string $oldname The name of the album to rename + * @param string $newname The new name of the album + * @return bool|array + */ +function photos_album_rename($channel_id, $oldname, $newname) { return q("UPDATE photo SET album = '%s' WHERE album = '%s' AND uid = %d", dbesc($newname), dbesc($oldname), @@ -437,8 +455,8 @@ function photos_album_get_db_idstr($channel_id,$album,$remote_xchan = '') { $str = implode(',',$arr); return $str; } - return false; + return false; } function photos_create_item($channel, $creator_hash, $photo, $visible = false) { @@ -446,11 +464,10 @@ function photos_create_item($channel, $creator_hash, $photo, $visible = false) { // Create item container $item_flags = ITEM_WALL|ITEM_ORIGIN|ITEM_THREAD_TOP; - $item_restrict = (($visible) ? ITEM_VISIBLE : ITEM_HIDDEN); + $item_restrict = (($visible) ? ITEM_VISIBLE : ITEM_HIDDEN); - $title = ''; $mid = item_message_id(); - + $arr = array(); $arr['aid'] = $channel['channel_account_id']; @@ -470,13 +487,13 @@ function photos_create_item($channel, $creator_hash, $photo, $visible = false) { $arr['deny_gid'] = $photo['deny_gid']; $arr['plink'] = z_root() . '/channel/' . $channel['channel_address'] . '/?f=&mid=' . $arr['mid']; - + $arr['body'] = '[zrl=' . z_root() . '/photos/' . $channel['channel_address'] . '/image/' . $photo['resource_id'] . ']' . '[zmg]' . z_root() . '/photo/' . $photo['resource_id'] . '-' . $photo['scale'] . '[/zmg]' . '[/zrl]'; - + $result = item_store($arr); $item_id = $result['item_id']; - return $item_id; + return $item_id; } diff --git a/include/security.php b/include/security.php index 216299099..e9b41dcf9 100644 --- a/include/security.php +++ b/include/security.php @@ -22,7 +22,7 @@ function authenticate_success($user_record, $login_initial = false, $interactive $a->account = $user_record; $_SESSION['account_id'] = $user_record['account_id']; $_SESSION['authenticated'] = 1; - + if($login_initial || $update_lastlog) { q("update account set account_lastlog = '%s' where account_id = %d", dbesc(datetime_convert()), @@ -150,11 +150,7 @@ function change_channel($change_channel) { */ function permissions_sql($owner_id, $remote_verified = false, $groups = null) { - if(defined('STATUSNET_PRIVACY_COMPATIBILITY')) - return ''; - $local_channel = local_channel(); - $remote_channel = remote_channel(); /** * Construct permissions @@ -173,7 +169,7 @@ function permissions_sql($owner_id, $remote_verified = false, $groups = null) { */ if(($local_channel) && ($local_channel == $owner_id)) { - $sql = ''; + $sql = ''; } /** @@ -194,7 +190,7 @@ function permissions_sql($owner_id, $remote_verified = false, $groups = null) { if(is_array($groups) && count($groups)) { foreach($groups as $g) $gs .= '|<' . $g . '>'; - } + } $regexop = db_getfunc('REGEXP'); $sql = sprintf( " AND ( NOT (deny_cid like '%s' OR deny_gid $regexop '%s') @@ -223,11 +219,7 @@ function permissions_sql($owner_id, $remote_verified = false, $groups = null) { */ function item_permissions_sql($owner_id, $remote_verified = false, $groups = null) { - if(defined('STATUSNET_PRIVACY_COMPATIBILITY')) - return ''; - $local_channel = local_channel(); - $remote_channel = remote_channel(); /** * Construct permissions @@ -246,7 +238,7 @@ function item_permissions_sql($owner_id, $remote_verified = false, $groups = nul } /** - * Authenticated visitor. Unless pre-verified, + * Authenticated visitor. Unless pre-verified, * check that the contact belongs to this $owner_id * and load the groups the visitor belongs to. * If pre-verified, the caller is expected to have already @@ -330,7 +322,7 @@ function public_permissions_sql($observer_hash) { */ function get_form_security_token($typename = '') { $a = get_app(); - + $timestamp = time(); $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $timestamp . $typename); @@ -340,16 +332,16 @@ function get_form_security_token($typename = '') { function check_form_security_token($typename = '', $formname = 'form_security_token') { if (!x($_REQUEST, $formname)) return false; $hash = $_REQUEST[$formname]; - + $max_livetime = 10800; // 3 hours - + $a = get_app(); - + $x = explode('.', $hash); if (time() > (IntVal($x[0]) + $max_livetime)) return false; - + $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $x[0] . $typename); - + return ($sec_hash == $x[1]); } @@ -417,7 +409,7 @@ function stream_perms_api_uids($perms = NULL ) { if($r) { foreach($r as $rr) if(! in_array($rr['channel_id'], $ret)) - $ret[] = $rr['channel_id']; + $ret[] = $rr['channel_id']; } $str = ''; @@ -425,7 +417,7 @@ function stream_perms_api_uids($perms = NULL ) { foreach($ret as $rr) { if($str) $str .= ','; - $str .= intval($rr); + $str .= intval($rr); } } logger('stream_perms_api_uids: ' . $str, LOGGER_DEBUG); @@ -447,7 +439,7 @@ function stream_perms_xchans($perms = NULL ) { if($r) { foreach($r as $rr) if(! in_array($rr['channel_hash'], $ret)) - $ret[] = $rr['channel_hash']; + $ret[] = $rr['channel_hash']; } $str = ''; @@ -455,7 +447,7 @@ function stream_perms_xchans($perms = NULL ) { foreach($ret as $rr) { if($str) $str .= ','; - $str .= "'" . dbesc($rr) . "'"; + $str .= "'" . dbesc($rr) . "'"; } } logger('stream_perms_xchans: ' . $str, LOGGER_DEBUG); diff --git a/include/socgraph.php b/include/socgraph.php index 59830ef1b..7f03f8696 100644 --- a/include/socgraph.php +++ b/include/socgraph.php @@ -3,7 +3,7 @@ require_once('include/dir_fns.php'); require_once('include/zot.php'); -/* +/** * poco_load * * xchan is your connection @@ -21,13 +21,10 @@ require_once('include/zot.php'); * the given uid, cid to the global contact entry. There can be many uid/cid combinations * pointing to the same global contact id. * + * @param string $xchan + * @param string $url */ - - - - -function poco_load($xchan = '',$url = null) { - $a = get_app(); +function poco_load($xchan = '', $url = null) { if($xchan && ! $url) { $r = q("select xchan_connurl from xchan where xchan_hash = '%s' limit 1", @@ -43,7 +40,6 @@ function poco_load($xchan = '',$url = null) { return; } - $url = $url . '?f=&fields=displayName,hash,urls,photos,rating' ; logger('poco_load: ' . $url, LOGGER_DEBUG); @@ -148,7 +144,7 @@ function poco_load($xchan = '',$url = null) { logger('poco_load: missing data'); continue; } - + $x = q("select xchan_hash from xchan where xchan_hash = '%s' limit 1", dbesc($hash) ); @@ -182,9 +178,8 @@ function poco_load($xchan = '',$url = null) { continue; } } - - $total ++; + $total ++; } logger("poco_load: loaded $total entries",LOGGER_DEBUG); @@ -193,7 +188,6 @@ function poco_load($xchan = '',$url = null) { db_utcnow(), db_quoteinterval('2 DAY') ); - } @@ -230,7 +224,6 @@ function common_friends($uid,$xchan,$start = 0,$limit=100000000,$shuffle = false ); return $r; - } @@ -246,8 +239,8 @@ function count_common_friends_zcid($uid,$zcid) { if(count($r)) return $r[0]['total']; - return 0; + return 0; } function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) { @@ -269,7 +262,6 @@ function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = fal ); return $r; - } @@ -284,8 +276,8 @@ function count_all_friends($uid,$cid) { if(count($r)) return $r[0]['total']; - return 0; + return 0; } @@ -358,9 +350,7 @@ function suggestion_query($uid, $myxchan, $start = 0, $limit = 80) { function update_suggestions() { - $a = get_app(); - - $dirmode = get_config('system','directory_mode'); + $dirmode = get_config('system', 'directory_mode'); if($dirmode === false) $dirmode = DIRECTORY_MODE_NORMAL; @@ -374,8 +364,6 @@ function update_suggestions() { if(! $url) return; - - $ret = z_fetch_url($url); if($ret['success']) { @@ -388,7 +376,6 @@ function update_suggestions() { db_utcnow(), db_quoteinterval('7 DAY') ); - $j = json_decode($ret['body'],true); if($j && $j['success']) { foreach($j['entries'] as $host) { @@ -422,7 +409,6 @@ function poco($a,$extended = false) { $system_mode = true; } - $format = (($_REQUEST['format']) ? $_REQUEST['format'] : 'json'); $justme = false; @@ -437,7 +423,7 @@ function poco($a,$extended = false) { } if(argc() > 4 && intval(argv(4)) && $justme == false) $cid = intval(argv(4)); - + if(! $system_mode) { $r = q("SELECT channel_id from channel where channel_address = '%s' limit 1", @@ -487,8 +473,8 @@ function poco($a,$extended = false) { $startIndex = intval($_GET['startIndex']); if(! $startIndex) $startIndex = 0; - $itemsPerPage = ((x($_GET,'count') && intval($_GET['count'])) ? intval($_GET['count']) : $totalResults); + $itemsPerPage = ((x($_GET,'count') && intval($_GET['count'])) ? intval($_GET['count']) : $totalResults); if($system_mode) { $r = q("SELECT abook.*, xchan.* from abook left join xchan on abook_xchan = xchan_hash where ( abook_flags & " . ABOOK_FLAG_SELF . @@ -496,8 +482,7 @@ function poco($a,$extended = false) { intval($itemsPerPage), intval($startIndex) ); - } - else { + } else { $r = q("SELECT abook.*, xchan.* from abook left join xchan on abook_xchan = xchan_hash where abook_channel = %d $sql_extra LIMIT %d OFFSET %d", intval($channel_id), @@ -525,8 +510,7 @@ function poco($a,$extended = false) { } } - $ret['entry'] = array(); - + $ret['entry'] = array(); $fields_ret = array( 'id' => false, @@ -540,10 +524,10 @@ function poco($a,$extended = false) { 'rating' => false ); - if((! x($_GET,'fields')) || ($_GET['fields'] === '@all')) + if((! x($_GET,'fields')) || ($_GET['fields'] === '@all')) { foreach($fields_ret as $k => $v) $fields_ret[$k] = true; - else { + } else { $fields_req = explode(',',$_GET['fields']); foreach($fields_req as $f) $fields_ret[trim($f)] = true; diff --git a/include/taxonomy.php b/include/taxonomy.php index ef3639067..4333cdf03 100644 --- a/include/taxonomy.php +++ b/include/taxonomy.php @@ -38,6 +38,7 @@ function term_query($table,$s,$type = TERM_UNKNOWN) { function store_item_tag($uid,$iid,$otype,$type,$term,$url = '') { if(! $term) return false; + $r = q("select * from term where uid = %d and oid = %d and otype = %d and type = %d and term = '%s' and url = '%s' ", @@ -50,6 +51,7 @@ function store_item_tag($uid,$iid,$otype,$type,$term,$url = '') { ); if($r) return false; + $r = q("insert into term (uid, oid, otype, type, term, url) values( %d, %d, %d, %d, '%s', '%s') ", intval($uid), @@ -59,9 +61,11 @@ function store_item_tag($uid,$iid,$otype,$type,$term,$url = '') { dbesc($term), dbesc($url) ); + return $r; } - + + function get_terms_oftype($arr,$type) { $ret = array(); if(! (is_array($arr) && count($arr))) @@ -74,6 +78,7 @@ function get_terms_oftype($arr,$type) { foreach($arr as $x) if($x['type'] == $t) $ret[] = $x; + return $ret; } @@ -99,7 +104,7 @@ function format_term_for_display($term) { function tagadelic($uid, $count = 0, $authors = '', $flags = 0, $restrict = 0, $type = TERM_HASHTAG) { require_once('include/security.php'); - + if(! perm_is_allowed($uid,get_observer_hash(),'view_stream')) return array(); @@ -112,6 +117,7 @@ function tagadelic($uid, $count = 0, $authors = '', $flags = 0, $restrict = 0, $ if($authors) { if(! is_array($authors)) $authors = array($authors); + stringify_array_elms($authors,true); $sql_options .= " and author_xchan in (" . implode(',',$authors) . ") "; } @@ -131,8 +137,8 @@ function tagadelic($uid, $count = 0, $authors = '', $flags = 0, $restrict = 0, $ if(! $r) return array(); - - // Find minimum and maximum log-count. + + // Find minimum and maximum log-count. $tags = array(); $min = 1e9; $max = -1e9; @@ -158,16 +164,17 @@ function tagadelic($uid, $count = 0, $authors = '', $flags = 0, $restrict = 0, $ return $tags; } + function tags_sort($a,$b) { - if(strtolower($a[0]) == strtolower($b[0])) - return 0; - return((strtolower($a[0]) < strtolower($b[0])) ? -1 : 1); + if(strtolower($a[0]) == strtolower($b[0])) + return 0; + + return((strtolower($a[0]) < strtolower($b[0])) ? -1 : 1); } function dir_tagadelic($count = 0) { - $sql_options = ''; $count = intval($count); // Fetch tags @@ -178,8 +185,8 @@ function dir_tagadelic($count = 0) { if(! $r) return array(); - - // Find minimum and maximum log-count. + + // Find minimum and maximum log-count. $tags = array(); $min = 1e9; $max = -1e9; @@ -207,65 +214,66 @@ function dir_tagadelic($count = 0) { function tagblock($link,$uid,$count = 0,$authors = '',$flags = 0,$restrict = 0,$type = TERM_HASHTAG) { - $o = ''; - $tab = 0; - $r = tagadelic($uid,$count,$authors,$flags,$restrict,$type); - - if($r) { - $o = '

      ' . t('Tags') . '

      '; - foreach($r as $rr) { - $o .= '#'.$rr[0].' ' . "\r\n"; + $o = ''; + + $r = tagadelic($uid,$count,$authors,$flags,$restrict,$type); + + if($r) { + $o = '

      ' . t('Tags') . '

      '; + foreach($r as $rr) { + $o .= '#'.$rr[0].' ' . "\r\n"; + } + $o .= '
      '; } - $o .= '
      '; - } + return $o; } + function wtagblock($uid,$count = 0,$authors = '',$flags = 0,$restrict = 0,$type = TERM_HASHTAG) { - $o = ''; - $tab = 0; - $r = tagadelic($uid,$count,$authors,$flags,$restrict,$type); + $o = ''; - if($r) { - $c = q("select channel_address from channel where channel_id = %d limit 1", - intval($uid) - ); + $r = tagadelic($uid,$count,$authors,$flags,$restrict,$type); - $o = '

      ' . t('Tags') . '

      '; - foreach($r as $rr) { - $o .= '#'.$rr[0].' ' . "\r\n"; + if($r) { + $c = q("select channel_address from channel where channel_id = %d limit 1", + intval($uid) + ); + + $o = '

      ' . t('Tags') . '

      '; + foreach($r as $rr) { + $o .= '#'.$rr[0].' ' . "\r\n"; + } + $o .= '
      '; } - $o .= '
      '; - } + return $o; } function catblock($uid,$count = 0,$authors = '',$flags = 0,$restrict = 0,$type = TERM_CATEGORY) { - $o = ''; - $tab = 0; + $o = ''; - $r = tagadelic($uid,$count,$authors,$flags,$restrict,$type); + $r = tagadelic($uid,$count,$authors,$flags,$restrict,$type); - if($r) { - $c = q("select channel_address from channel where channel_id = %d limit 1", - intval($uid) - ); - - $o = '

      ' . t('Categories') . '

      '; - foreach($r as $rr) { - $o .= ''.$rr[0].' ' . "\r\n"; + if($r) { + $c = q("select channel_address from channel where channel_id = %d limit 1", + intval($uid) + ); + + $o = '

      ' . t('Categories') . '

      '; + foreach($r as $rr) { + $o .= ''.$rr[0].' ' . "\r\n"; + } + $o .= '
      '; } - $o .= '
      '; - } + return $o; } - function dir_tagblock($link,$r) { $o = ''; - $tab = 0; if(! $r) $r = get_app()->data['directory_keywords']; @@ -277,14 +285,12 @@ function dir_tagblock($link,$r) { } $o .= ''; } + return $o; } - - - /** * verbs: [0] = first person singular, e.g. "I want", [1] = 3rd person singular, e.g. "Bill wants" * We use the first person form when creating an activity, but the third person for use in activities @@ -292,8 +298,6 @@ function dir_tagblock($link,$r) { * require obj_verbs() to provide full conjugations and specify which form to use in the $_REQUEST params to this module. */ - - function obj_verbs() { $verbs = array( 'has' => array( t('have'), t('has')), @@ -304,26 +308,27 @@ function obj_verbs() { $arr = array('verbs' => $verbs); call_hooks('obj_verbs', $arr); + return $arr['verbs']; } function obj_verb_selector($current = '') { $verbs = obj_verbs(); - $o .= ''; foreach($verbs as $k => $v) { $selected = (($k == $current) ? ' selected="selected" ' : ''); $o .= ''; } $o .= ''; - return $o; + return $o; } function get_things($profile_hash,$uid) { $sql_extra = (($profile_hash) ? " and obj_page = '" . $profile_hash . "' " : ''); - + $r = q("select * from obj left join term on obj_obj = term_hash where term_hash != '' and uid = %d and obj_type = %d $sql_extra order by obj_verb, term", intval($uid), intval(TERM_OBJ_THING) @@ -379,11 +384,11 @@ function get_things($profile_hash,$uid) { for($x = 0; $x < count($l); $x ++) $l[$x]['xchan_url'] = zid($l[$x]['xchan_url']); - + if(! $things[$rr['obj_verb']]) $things[$rr['obj_verb']] = array(); - $things[$rr['obj_verb']][] = array('term' => $rr['term'],'url' => $rr['url'],'img' => $rr['imgurl'], 'profile' => $rr['profile_name'],'term_hash' => $rr['term_hash'], 'likes' => $l,'like_count' => count($l),'like_label' => tt('Like','Likes',count($l),'noun')); + $things[$rr['obj_verb']][] = array('term' => $rr['term'],'url' => $rr['url'],'img' => $rr['imgurl'], 'profile' => $rr['profile_name'],'term_hash' => $rr['term_hash'], 'likes' => $l,'like_count' => count($l),'like_label' => tt('Like','Likes',count($l),'noun')); } $sorted_things = array(); if($things) { @@ -395,6 +400,6 @@ function get_things($profile_hash,$uid) { } } //logger('things: ' . print_r($sorted_things,true)); - return $sorted_things; + return $sorted_things; } \ No newline at end of file -- cgit v1.2.3 From 85f79990af13a2c71aa9c053761de6dbf8f37841 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 3 Mar 2015 15:22:24 -0800 Subject: don't let a zot-finger bring a dead hub back to life unless it's the site we're currently talking to. --- include/zot.php | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) (limited to 'include') diff --git a/include/zot.php b/include/zot.php index e1c780742..29513b8c5 100644 --- a/include/zot.php +++ b/include/zot.php @@ -2036,7 +2036,7 @@ function sync_locations($sender,$arr,$absolute = false) { $ret = array(); if($arr['locations']) { - + $xisting = q("select hubloc_id, hubloc_url, hubloc_sitekey from hubloc where hubloc_hash = '%s'", dbesc($sender['hash']) ); @@ -2100,19 +2100,21 @@ function sync_locations($sender,$arr,$absolute = false) { // update connection timestamp if this is the site we're talking to // This only happens when called from import_xchan + $current_site = false; + if(array_key_exists('site',$arr) && $location['url'] == $arr['site']['url']) { q("update hubloc set hubloc_connected = '%s', hubloc_updated = '%s' where hubloc_id = %d", dbesc(datetime_convert()), dbesc(datetime_convert()), intval($r[0]['hubloc_id']) ); + $current_site = true; } - // if it's marked offline/dead, bring it back - // Should we do this? It's basically saying that the channel knows better than - // the directory server if the site is alive. + // If it is the site we're currently talking to, and it's marked offline, + // either we have some bad information - or the thing came back to life. - if($r[0]['hubloc_status'] & HUBLOC_OFFLINE) { + if(($current_site) && ($r[0]['hubloc_status'] & HUBLOC_OFFLINE)) { q("update hubloc set hubloc_status = (hubloc_status & ~%d) where hubloc_id = %d", intval(HUBLOC_OFFLINE), intval($r[0]['hubloc_id']) -- cgit v1.2.3 From 99e4d2362c3e02f7ef593208a365d81254c25156 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 3 Mar 2015 15:54:38 -0800 Subject: I'm going to use the site_update timestamp to indicate whenever we successfully connect with a site. This way we can mark hubs dead on non-directory servers; but we have to wait before implementing this until we have a history of site_update being updated. --- include/zot.php | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'include') diff --git a/include/zot.php b/include/zot.php index 29513b8c5..670583929 100644 --- a/include/zot.php +++ b/include/zot.php @@ -984,6 +984,14 @@ function zot_process_response($hub,$arr,$outq) { logger('zot_process_response: headers: ' . print_r($arr['header'],true), LOGGER_DATA); } + // update the timestamp for this site + + $r = q("update site set site_update = '%s' where site_url = '%s'", + dbesc(datetime_convert()), + dbesc(dirname($hub)) + ); + + // synchronous message types are handled immediately // async messages remain in the queue until processed. @@ -2585,6 +2593,13 @@ function import_site($arr,$pubkey) { logger('import_site: update failed. ' . print_r($arr,true)); } } + else { + // update the timestamp to indicate we communicated with this site + q("update site set site_update = '%s' where site_url = '%s'", + dbesc(datetime_convert()), + dbesc($url) + ); + } } else { $update = true; -- cgit v1.2.3 From 6d92ac7e58cc3fc65b5452c962c1af12d82a1b13 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 3 Mar 2015 16:00:24 -0800 Subject: enable sql_extra on pdl_selector --- include/comanche.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/comanche.php b/include/comanche.php index 9db375c38..e8d3ca5a1 100644 --- a/include/comanche.php +++ b/include/comanche.php @@ -18,9 +18,9 @@ require_once('include/widgets.php'); function pdl_selector($uid, $current="") { $o = ''; - //$sql_extra = item_permissions_sql($uid); + $sql_extra = item_permissions_sql($uid); - $r = q("select item_id.*, mid from item_id left join item on iid = item.id where item_id.uid = %d and item_id.uid = item.uid and service = 'PDL' order by sid asc", + $r = q("select item_id.*, mid from item_id left join item on iid = item.id where item_id.uid = %d and item_id.uid = item.uid and service = 'PDL' $sql_extra order by sid asc", intval($uid) ); -- cgit v1.2.3 From 64e7c8b20f241f7f63ad78c23fdf872f3422d561 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 4 Mar 2015 01:26:02 -0800 Subject: notes on what's needed to fix the queueing algorithms. --- include/queue.php | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'include') diff --git a/include/queue.php b/include/queue.php index b6a540ef9..8e97b4a1a 100644 --- a/include/queue.php +++ b/include/queue.php @@ -39,6 +39,14 @@ function queue_run($argv, $argc){ // so that we don't start off a thousand deliveries for a couple of dead hubs. // The zot driver will deliver everything destined for a single hub once contact is made (*if* contact is made). // Other drivers will have to do something different here and may need their own query. + + // Note: this requires some tweaking as new posts to long dead hubs once a day will keep them in the + // "every 15 minutes" category. We probably need to prioritise them when inserted into the queue + // or just prior to this query based on recent and long-term delivery history. If we have good reason to believe + // the site is permanently down, there's no reason to attempt delivery at all, or at most not more than once + // or twice a day. + + if(ACTIVE_DBTYPE == DBTYPE_POSTGRES) { $prefix = 'DISTINCT ON (outq_posturl)'; $suffix = 'ORDER BY outq_posturl'; -- cgit v1.2.3 From 410f3335a9e97276b3262196f50798ff56624af5 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 4 Mar 2015 15:14:10 -0800 Subject: parse_url: if url returns an image/audio/video file instead of a webpage, return the bbcode for the appropriate content type. This results in two web fetches of the url in question, but the first one is just a HEAD. This way we won't try and download and parse an entire video. TODO: img's are checked to see if they should be zid-ified, but audio/video currently are not. --- include/network.php | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'include') diff --git a/include/network.php b/include/network.php index db32396e4..5912ad79d 100644 --- a/include/network.php +++ b/include/network.php @@ -19,6 +19,7 @@ function get_capath() { * 'timeout' => int seconds, default system config value or 60 seconds * 'http_auth' => username:password * 'novalidate' => do not validate SSL certs, default is to validate using our CA list + * 'nobody' => only return the header * * @returns array * 'return_code' => HTTP return code or 0 if timeout or failure @@ -51,6 +52,9 @@ function z_fetch_url($url, $binary = false, $redirects = 0, $opts = array()) { if(x($opts,'headers')) @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']); + if(x($opts,'nobody')) + @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']); + if(x($opts,'timeout') && intval($opts['timeout'])) { @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']); } @@ -182,6 +186,9 @@ function z_post_url($url,$params, $redirects = 0, $opts = array()) { if(x($opts,'headers')) @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']); + if(x($opts,'nobody')) + @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']); + if(x($opts,'timeout') && intval($opts['timeout'])) { @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']); } -- cgit v1.2.3 From 011ccd57f62335c915b5ac75e20c45a36a64a888 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 4 Mar 2015 17:56:07 -0800 Subject: add queue priority --- include/deliver.php | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'include') diff --git a/include/deliver.php b/include/deliver.php index 47d8562df..459c0f94b 100644 --- a/include/deliver.php +++ b/include/deliver.php @@ -20,6 +20,24 @@ function deliver_run($argv, $argc) { dbesc($argv[$x]) ); if($r) { + $h = parse_url($r[0]['outq_posturl']); + if($h) { + $base = $h['scheme'] . '://' . $h['host'] . (($h['port']) ? ':' . $h['port'] : ''); + if($base !== z_root()) { + $x = q("select site_update from site where site_url = '%s' ", + dbesc($base) + ); + if($x && $x[0]['site_update'] < datetime_convert('UTC','UTC','now - 1 month')) { + q("update outq set outq_priority = %d where outq_hash = '%s'", + intval($r[0]['outq_priority'] + 10) + dbesc($r[0]['outq_hash']) + ); + logger('immediate delivery deferred for site ' . $base); + continue; + } + } + } + if($r[0]['outq_driver'] === 'post') { $result = z_post_url($r[0]['outq_posturl'],$r[0]['outq_msg']); if($result['success'] && $result['return_code'] < 300) { -- cgit v1.2.3 From 1d5d80808ca1463e67f7586f8c804347f3dfb5f4 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 4 Mar 2015 18:11:47 -0800 Subject: don't re-use $x --- include/deliver.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/deliver.php b/include/deliver.php index 459c0f94b..95fb19a79 100644 --- a/include/deliver.php +++ b/include/deliver.php @@ -24,10 +24,10 @@ function deliver_run($argv, $argc) { if($h) { $base = $h['scheme'] . '://' . $h['host'] . (($h['port']) ? ':' . $h['port'] : ''); if($base !== z_root()) { - $x = q("select site_update from site where site_url = '%s' ", + $y = q("select site_update from site where site_url = '%s' ", dbesc($base) ); - if($x && $x[0]['site_update'] < datetime_convert('UTC','UTC','now - 1 month')) { + if($y && $y[0]['site_update'] < datetime_convert('UTC','UTC','now - 1 month')) { q("update outq set outq_priority = %d where outq_hash = '%s'", intval($r[0]['outq_priority'] + 10) dbesc($r[0]['outq_hash']) -- cgit v1.2.3 From ad3b4da3ff5751a5e0da6ba7e46a4fc8731d4d28 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 4 Mar 2015 18:23:54 -0800 Subject: missing comma --- include/deliver.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/deliver.php b/include/deliver.php index 95fb19a79..498440271 100644 --- a/include/deliver.php +++ b/include/deliver.php @@ -29,7 +29,7 @@ function deliver_run($argv, $argc) { ); if($y && $y[0]['site_update'] < datetime_convert('UTC','UTC','now - 1 month')) { q("update outq set outq_priority = %d where outq_hash = '%s'", - intval($r[0]['outq_priority'] + 10) + intval($r[0]['outq_priority'] + 10), dbesc($r[0]['outq_hash']) ); logger('immediate delivery deferred for site ' . $base); -- cgit v1.2.3 From 76eb0a7e5606d61153b199094482c4c55685a035 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 4 Mar 2015 18:55:17 -0800 Subject: Deprecate the "wall uploads" photo album. Photo uploads (from any source) with no album specified will go now into an album based on YYYY-MM. --- include/photos.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/photos.php b/include/photos.php index 794ff7748..cd753ffea 100644 --- a/include/photos.php +++ b/include/photos.php @@ -31,7 +31,7 @@ function photo_upload($channel, $observer, $args) { if($newalbum) $album = $newalbum; else - $album = datetime_convert('UTC',date_default_timezone_get(),'now', 'Y'); + $album = datetime_convert('UTC',date_default_timezone_get(),'now', 'Y-m'); } /** -- cgit v1.2.3 From 2ea162136e8ab68ca0ad854a4225471ffd35a5a8 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 4 Mar 2015 20:00:54 -0800 Subject: the link icon on comments now calls the link parsing tool (just like the main editor window). Eventually the link specific icons (image, link, audio, video) will all be handled by inserting a link using the link icon (here and in the main editor window) and the separate buttons will go away. We also need to tie this to oembed so that there's one place to insert a link - no matter what kind of link it is, and we'll try to find the best way to render that as content. Similarly upload will upload content, no matter what kind of content; and we'll likewise try and figure out the best way to present whatever content was uploaded (img, file, audio, video, whatever). --- include/js_strings.php | 1 + 1 file changed, 1 insertion(+) (limited to 'include') diff --git a/include/js_strings.php b/include/js_strings.php index 56ffa9536..84c1d70fb 100644 --- a/include/js_strings.php +++ b/include/js_strings.php @@ -20,6 +20,7 @@ function js_strings() { '$rating_val' => t('Rating'), '$rating_text' => t('Describe (optional)'), '$submit' => t('Submit'), + '$linkurl' => t('Please enter a link URL'), '$t01' => ((t('timeago.prefixAgo') != 'timeago.prefixAgo') ? t('timeago.prefixAgo') : ''), '$t02' => ((t('timeago.prefixFromNow') != 'timeago.prefixFromNow') ? t('timeago.prefixFromNow') : ''), -- cgit v1.2.3 From 2b45bf190869f8ad489c2f0e82597b7ffb315f0f Mon Sep 17 00:00:00 2001 From: Klaus Date: Fri, 6 Mar 2015 00:21:32 +0100 Subject: RedDAV: fix renaming files. How can no one have spot this bug yet?!? Is no one using WebDAV? Took me 2 days to figure out it was not my RedDAV rewrite, but that this should have never worked. :-! --- include/RedDAV/RedFile.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'include') diff --git a/include/RedDAV/RedFile.php b/include/RedDAV/RedFile.php index 9ce6490a7..b7aa5473a 100644 --- a/include/RedDAV/RedFile.php +++ b/include/RedDAV/RedFile.php @@ -80,7 +80,8 @@ class RedFile extends DAV\Node implements DAV\IFile { $newName = str_replace('/', '%2F', $newName); $r = q("UPDATE attach SET filename = '%s' WHERE hash = '%s' AND id = %d", - dbesc($this->data['filename']), + dbesc($newName), + dbesc($this->data['hash']), intval($this->data['id']) ); } -- cgit v1.2.3 From 22391a24378cae317cdf62dc4be4b31b68e8191f Mon Sep 17 00:00:00 2001 From: friendica Date: Thu, 5 Mar 2015 18:24:49 -0800 Subject: straighten out some directory stuff, which required some Comanche structural changes --- include/comanche.php | 66 ++++++++++++++++++++++++++++------------------------ include/dir_fns.php | 26 +++++++++++++++++++-- include/widgets.php | 3 --- 3 files changed, 59 insertions(+), 36 deletions(-) (limited to 'include') diff --git a/include/comanche.php b/include/comanche.php index e8d3ca5a1..1ddabb693 100644 --- a/include/comanche.php +++ b/include/comanche.php @@ -43,7 +43,7 @@ function pdl_selector($uid, $current="") { -function comanche_parser(&$a, $s) { +function comanche_parser(&$a, $s, $pass = 0) { $matches = array(); $cnt = preg_match_all("/\[comment\](.*?)\[\/comment\]/ism", $s, $matches, PREG_SET_ORDER); @@ -53,43 +53,47 @@ function comanche_parser(&$a, $s) { } } - $cnt = preg_match("/\[layout\](.*?)\[\/layout\]/ism", $s, $matches); - if($cnt) - $a->page['template'] = trim($matches[1]); + if($pass == 0) { + $cnt = preg_match("/\[layout\](.*?)\[\/layout\]/ism", $s, $matches); + if($cnt) + $a->page['template'] = trim($matches[1]); - $cnt = preg_match("/\[template=(.*?)\](.*?)\[\/template\]/ism", $s, $matches); - if($cnt) { - $a->page['template'] = trim($matches[2]); - $a->page['template_style'] = trim($matches[2]) . '_' . $matches[1]; - } + $cnt = preg_match("/\[template=(.*?)\](.*?)\[\/template\]/ism", $s, $matches); + if($cnt) { + $a->page['template'] = trim($matches[2]); + $a->page['template_style'] = trim($matches[2]) . '_' . $matches[1]; + } - $cnt = preg_match("/\[template\](.*?)\[\/template\]/ism", $s, $matches); - if($cnt) { - $a->page['template'] = trim($matches[1]); - } + $cnt = preg_match("/\[template\](.*?)\[\/template\]/ism", $s, $matches); + if($cnt) { + $a->page['template'] = trim($matches[1]); + } - $cnt = preg_match("/\[theme=(.*?)\](.*?)\[\/theme\]/ism", $s, $matches); - if($cnt) { - $a->layout['schema'] = trim($matches[1]); - $a->layout['theme'] = trim($matches[2]); - } + $cnt = preg_match("/\[theme=(.*?)\](.*?)\[\/theme\]/ism", $s, $matches); + if($cnt) { + $a->layout['schema'] = trim($matches[1]); + $a->layout['theme'] = trim($matches[2]); + } - $cnt = preg_match("/\[theme\](.*?)\[\/theme\]/ism", $s, $matches); - if($cnt) - $a->layout['theme'] = trim($matches[1]); + $cnt = preg_match("/\[theme\](.*?)\[\/theme\]/ism", $s, $matches); + if($cnt) + $a->layout['theme'] = trim($matches[1]); - $cnt = preg_match_all("/\[region=(.*?)\](.*?)\[\/region\]/ism", $s, $matches, PREG_SET_ORDER); - if($cnt) { - foreach($matches as $mtch) { - $a->layout['region_' . $mtch[1]] = comanche_region($a,$mtch[2]); - } } + else { + $cnt = preg_match_all("/\[region=(.*?)\](.*?)\[\/region\]/ism", $s, $matches, PREG_SET_ORDER); + if($cnt) { + foreach($matches as $mtch) { + $a->layout['region_' . $mtch[1]] = comanche_region($a,$mtch[2]); + } + } - $cnt = preg_match_all("/\[webpage\](.*?)\[\/webpage\]/ism", $s, $matches, PREG_SET_ORDER); - if($cnt) { - // only the last webpage definition is used if there is more than one - foreach($matches as $mtch) { - $a->layout['webpage'] = comanche_webpage($a,$mtch[1]); + $cnt = preg_match_all("/\[webpage\](.*?)\[\/webpage\]/ism", $s, $matches, PREG_SET_ORDER); + if($cnt) { + // only the last webpage definition is used if there is more than one + foreach($matches as $mtch) { + $a->layout['webpage'] = comanche_webpage($a,$mtch[1]); + } } } diff --git a/include/dir_fns.php b/include/dir_fns.php index 37a7c04e7..468e28ae5 100644 --- a/include/dir_fns.php +++ b/include/dir_fns.php @@ -74,7 +74,26 @@ function check_upstream_directory() { function dir_sort_links() { - // Build urls without order and pubforums so it's easy to tack on the changed value + $safe_mode = 1; + + $observer = get_observer_hash(); + + if ($observer) + $safe_mode = get_xconfig($observer,'directory','safe_mode'); + if($safe_mode === false) + $safe_mode = 1; + + if(! $safe_mode) + $toggle = t('Enable Safe Search'); + else + $toggle = t('Disable Safe Search'); + + if($observer) + $globaldir = get_xconfig($observer,'directory','globaldir'); + else + $globaldir = ((array_key_exists('globaldir',$_SESSION)) ? intval($_SESSION['globaldir']) : false); + + // Build urls without order and pubforums so it's easy to tack on the changed value // Probably there's an easier way to do this $current_order = (($_REQUEST['order']) ? $_REQUEST['order'] : 'normal'); @@ -104,7 +123,10 @@ function dir_sort_links() { '$selected_sort' => $current_order, '$sorturl' => $sorturl, '$forumsurl' => $forumsurl, - + '$safemode' => t('Safe Mode'), + '$toggle' => $toggle, + '$globaldir' => $globaldir, + '$localdir' => t('This Website Only'), )); return $o; } diff --git a/include/widgets.php b/include/widgets.php index fbbc74224..17c740967 100644 --- a/include/widgets.php +++ b/include/widgets.php @@ -605,9 +605,6 @@ function widget_vcard($arr) { * The following directory widgets are only useful on the directory page */ -function widget_dirsafemode($arr) { - return dir_safe_mode(); -} function widget_dirsort($arr) { return dir_sort_links(); -- cgit v1.2.3 From f6da235a7d0eae48f7b691a139825708b99dcd75 Mon Sep 17 00:00:00 2001 From: friendica Date: Thu, 5 Mar 2015 23:31:01 -0800 Subject: major cleanup of directory options --- include/dir_fns.php | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/dir_fns.php b/include/dir_fns.php index 468e28ae5..cd6d452d6 100644 --- a/include/dir_fns.php +++ b/include/dir_fns.php @@ -80,6 +80,8 @@ function dir_sort_links() { if ($observer) $safe_mode = get_xconfig($observer,'directory','safe_mode'); + else + $safe_mode = ((array_key_exists('safemode',$_SESSION)) ? intval($_SESSION['safemode']) : false); if($safe_mode === false) $safe_mode = 1; @@ -96,7 +98,7 @@ function dir_sort_links() { // Build urls without order and pubforums so it's easy to tack on the changed value // Probably there's an easier way to do this - $current_order = (($_REQUEST['order']) ? $_REQUEST['order'] : 'normal'); + $current_order = (($_REQUEST['order']) ? $_REQUEST['order'] : 'date'); $url = 'directory?f='; $tmp = array_merge($_GET,$_POST); @@ -107,6 +109,8 @@ function dir_sort_links() { $tmp = array_merge($_GET,$_POST); unset($tmp['pubforums']); + unset($tmp['global']); + unset($tmp['safe']); unset($tmp['q']); unset($tmp['f']); $forumsurl = $url . http_build_query($tmp); @@ -125,7 +129,10 @@ function dir_sort_links() { '$forumsurl' => $forumsurl, '$safemode' => t('Safe Mode'), '$toggle' => $toggle, - '$globaldir' => $globaldir, + '$safemode' => array('safemode', t('Safe Mode'),$safe_mode,'','',' onchange=\'window.location.href="' . $forumsurl . '&safe="+(this.checked ? 1 : 0)\''), + + '$pubforums' => array('pubforums', t('Public Forums Only'),(x($_REQUEST,'pubforums') ? $_REQUEST['pubforums'] : ''),'','',' onchange=\'window.location.href="' . $forumsurl . '&pubforums="+(this.checked ? 1 : 0)\''), + '$globaldir' => array('globaldir', t('This Website Only'), 1-intval($globaldir),'','',' onchange=\'window.location.href="' . $forumsurl . '&global="+(this.checked ? 0 : 1)\''), '$localdir' => t('This Website Only'), )); return $o; -- cgit v1.2.3 From 53e908d7b7ea1b1ff9aa5ca6154dc4c9e7ca0d13 Mon Sep 17 00:00:00 2001 From: friendica Date: Fri, 6 Mar 2015 20:45:26 -0800 Subject: when fixing "naked links" make sure not to double link double urls as seen in archive.org - which has the complete unescaped target url, scheme and all, as part of its own. --- include/bbcode.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/bbcode.php b/include/bbcode.php index 9a607c80d..6b8cb941f 100644 --- a/include/bbcode.php +++ b/include/bbcode.php @@ -472,7 +472,7 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { $urlchars = '[a-zA-Z0-9\:\/\-\?\&\;\.\=\@\_\~\#\%\$\!\+\,]'; if (strpos($Text,'http') !== false) { - $Text = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/$urlchars+)/ism", '$1$2', $Text); + $Text = preg_replace("/([^\]\='".'"'."\/]|^|\#\^)(https?\:\/\/$urlchars+)/ism", '$1$2', $Text); } if (strpos($Text,'[/qr]') !== false) { -- cgit v1.2.3 From 480dac1af2dd5ed5ba3105577559568237fe5d80 Mon Sep 17 00:00:00 2001 From: friendica Date: Sat, 7 Mar 2015 23:35:56 -0800 Subject: add reddress to profile - but all is not as it seems. Copy to clipboard is blocked because it isn't really a reddress and won't work if you copy it and try and use it somewhere. We should really convert the symbol back to '@' on copy and allow it to be copied, but this isn't as easy as it sounds and is left as an exercise for the community. If we just allow it to be copied we'll get a lot of bugs that making friends doesn't work. It does, but that isn't a legitimate reddress and even if we made allowances for it, Diaspora and Friendica and other webfinger based services wouldn't and would just say it can't be found or it's an illegal address. So if we block copy we'll just get bugs that it can't be copied. Eventually somebody will see this checkin and take it on themselves to figure out how to fix the address when copied to clipboard and then allow it to be copied. And there will be joy. --- include/identity.php | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'include') diff --git a/include/identity.php b/include/identity.php index f63b576b2..079c1a245 100644 --- a/include/identity.php +++ b/include/identity.php @@ -724,12 +724,13 @@ function profile_load(&$a, $nickname, $profile = '') { $p[0]['extra_fields'] = $extra_fields; - $z = q("select xchan_photo_date from xchan where xchan_hash = '%s' limit 1", + $z = q("select xchan_photo_date, xchan_addr from xchan where xchan_hash = '%s' limit 1", dbesc($p[0]['channel_hash']) ); - if($z) + if($z) { $p[0]['picdate'] = $z[0]['xchan_photo_date']; - + $p[0]['reddress'] = str_replace('@','@',$z[0]['xchan_addr']); + } // fetch user tags if this isn't the default profile @@ -817,6 +818,7 @@ function profile_sidebar($profile, $block = 0, $show_connect = true) { $location = false; $address = false; $pdesc = true; + $reddress = true; if((! is_array($profile)) && (! count($profile))) return $o; @@ -906,7 +908,7 @@ logger('online: ' . $profile['online']); } if(($profile['hidewall'] && (! local_channel()) && (! remote_channel())) || $block ) { - $location = $pdesc = $gender = $marital = $homepage = $online = False; + $location = $reddress = $pdesc = $gender = $marital = $homepage = $online = False; } $firstname = ((strpos($profile['channel_name'],' ')) @@ -957,6 +959,7 @@ logger('online: ' . $profile['online']); '$homepage' => $homepage, '$chanmenu' => $channel_menu, '$diaspora' => $diaspora, + '$reddress' => $reddress, '$rating' => $z, '$contact_block' => $contact_block, )); -- cgit v1.2.3 From b5683bfac4fd5e0e6cc15995c5c4f574e54e33da Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 8 Mar 2015 14:11:38 -0700 Subject: change default affinity (abook_closeness) to 80 for all new connections going forward (was 99). This way it can be adjusted down later without requiring you to change all your existing connections upward (since your existing connections are likely all sitting at 99 at the moment). The default setting is also configurable with a pconfig system.new_abook_closeness --- include/diaspora.php | 8 +++++++- include/follow.php | 8 +++++++- include/zot.php | 8 +++++++- 3 files changed, 21 insertions(+), 3 deletions(-) (limited to 'include') diff --git a/include/diaspora.php b/include/diaspora.php index 553c7474c..7295b4261 100755 --- a/include/diaspora.php +++ b/include/diaspora.php @@ -709,13 +709,19 @@ function diaspora_request($importer,$xml) { $their_perms = PERMS_R_STREAM|PERMS_R_PROFILE|PERMS_R_PHOTOS|PERMS_R_ABOOK|PERMS_W_STREAM|PERMS_W_COMMENT|PERMS_W_MAIL|PERMS_W_CHAT|PERMS_R_STORAGE|PERMS_R_PAGES; + + $closeness = get_pconfig($importer['channel_id'],'system','new_abook_closeness'); + if($closeness === false) + $closeness = 80; + + $r = q("insert into abook ( abook_account, abook_channel, abook_xchan, abook_my_perms, abook_their_perms, abook_closeness, abook_rating, abook_created, abook_updated, abook_connected, abook_dob, abook_flags) values ( %d, %d, '%s', %d, %d, %d, %d, '%s', '%s', '%s', '%s', %d )", intval($importer['channel_account_id']), intval($importer['channel_id']), dbesc($ret['xchan_hash']), intval($default_perms), intval($their_perms), - intval(99), + intval($closeness), intval(0), dbesc(datetime_convert()), dbesc(datetime_convert()), diff --git a/include/follow.php b/include/follow.php index 2d6791420..e13b5f775 100644 --- a/include/follow.php +++ b/include/follow.php @@ -227,10 +227,16 @@ function new_contact($uid,$url,$channel,$interactive = false, $confirm = false) ); } else { - $r = q("insert into abook ( abook_account, abook_channel, abook_xchan, abook_flags, abook_their_perms, abook_my_perms, abook_created, abook_updated ) + + $closeness = get_pconfig($uid,'system','new_abook_closeness'); + if($closeness === false) + $closeness = 80; + + $r = q("insert into abook ( abook_account, abook_channel, abook_closeness, abook_xchan, abook_flags, abook_their_perms, abook_my_perms, abook_created, abook_updated ) values( %d, %d, '%s', %d, %d, %d, '%s', '%s' ) ", intval($aid), intval($uid), + intval($closeness), dbesc($xchan_hash), intval(($is_http) ? ABOOK_FLAG_FEED : 0), intval(($is_http) ? $their_perms|PERMS_R_STREAM|PERMS_A_REPUBLISH : $their_perms), diff --git a/include/zot.php b/include/zot.php index 670583929..c9019ca7a 100644 --- a/include/zot.php +++ b/include/zot.php @@ -464,9 +464,15 @@ function zot_refresh($them,$channel = null, $force = false) { // Keep original perms to check if we need to notify them $previous_perms = get_all_perms($channel['channel_id'],$x['hash']); - $y = q("insert into abook ( abook_account, abook_channel, abook_xchan, abook_their_perms, abook_my_perms, abook_created, abook_updated, abook_dob, abook_flags ) values ( %d, %d, '%s', %d, %d, '%s', '%s', '%s', %d )", + + $closeness = get_pconfig($channel['channel_id'],'system','new_abook_closeness'); + if($closeness === false) + $closeness = 80; + + $y = q("insert into abook ( abook_account, abook_channel, abook_closeness, abook_xchan, abook_their_perms, abook_my_perms, abook_created, abook_updated, abook_dob, abook_flags ) values ( %d, %d, '%s', %d, %d, '%s', '%s', '%s', %d )", intval($channel['channel_account_id']), intval($channel['channel_id']), + intval($closeness), dbesc($x['hash']), intval($their_perms), intval($default_perms), -- cgit v1.2.3 From 904596c7da50f63fd23c9008c97f6cc86d8c8697 Mon Sep 17 00:00:00 2001 From: Alexandre Hannud Abdo Date: Mon, 9 Mar 2015 03:07:48 -0300 Subject: Fix missing value in insert for default closeness --- include/follow.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/follow.php b/include/follow.php index e13b5f775..fd4e1597a 100644 --- a/include/follow.php +++ b/include/follow.php @@ -233,7 +233,7 @@ function new_contact($uid,$url,$channel,$interactive = false, $confirm = false) $closeness = 80; $r = q("insert into abook ( abook_account, abook_channel, abook_closeness, abook_xchan, abook_flags, abook_their_perms, abook_my_perms, abook_created, abook_updated ) - values( %d, %d, '%s', %d, %d, %d, '%s', '%s' ) ", + values( %d, %d, %d, '%s', %d, %d, %d, '%s', '%s' ) ", intval($aid), intval($uid), intval($closeness), -- cgit v1.2.3 From e7d32442762dfda9a65468fb448fcd7e4ec5566a Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 9 Mar 2015 15:16:52 -0700 Subject: Allow site to over-ride directory options. Bugger off. --- include/dir_fns.php | 69 ++++++++++++++++++++++++----------------------------- 1 file changed, 31 insertions(+), 38 deletions(-) (limited to 'include') diff --git a/include/dir_fns.php b/include/dir_fns.php index cd6d452d6..4c6c40f15 100644 --- a/include/dir_fns.php +++ b/include/dir_fns.php @@ -65,6 +65,35 @@ function check_upstream_directory() { return; } +function get_globaldir_setting($observer) { + + if($observer) + $globaldir = get_xconfig($observer,'directory','globaldir'); + else + $globaldir = ((array_key_exists('globaldir',$_SESSION)) ? intval($_SESSION['globaldir']) : false); + + if($globaldir === false) + $globaldir = get_config('directory','globaldir'); + + return $globaldir; +} + +function get_safemode_setting($observer) { + + if ($observer) + $safe_mode = get_xconfig($observer,'directory','safe_mode'); + else + $safe_mode = ((array_key_exists('safemode',$_SESSION)) ? intval($_SESSION['safemode']) : false); + + if($safe_mode === false) + $safe_mode = get_config('directory','safe_mode'); + + if($safe_mode === false) + $safe_mode = 1; + + return $safe_mode; +} + /** * @function dir_sort_links() * Called by the directory_sort widget @@ -78,22 +107,8 @@ function dir_sort_links() { $observer = get_observer_hash(); - if ($observer) - $safe_mode = get_xconfig($observer,'directory','safe_mode'); - else - $safe_mode = ((array_key_exists('safemode',$_SESSION)) ? intval($_SESSION['safemode']) : false); - if($safe_mode === false) - $safe_mode = 1; - - if(! $safe_mode) - $toggle = t('Enable Safe Search'); - else - $toggle = t('Disable Safe Search'); - - if($observer) - $globaldir = get_xconfig($observer,'directory','globaldir'); - else - $globaldir = ((array_key_exists('globaldir',$_SESSION)) ? intval($_SESSION['globaldir']) : false); + $safe_mode = get_safemode_setting($observer); + $globaldir = get_globaldir_setting($observer); // Build urls without order and pubforums so it's easy to tack on the changed value // Probably there's an easier way to do this @@ -121,40 +136,18 @@ function dir_sort_links() { '$reverse' => t('Reverse Alphabetic'), '$date' => t('Newest to Oldest'), '$reversedate' => t('Oldest to Newest'), - '$pubforums' => t('Public Forums Only'), - '$pubforumsonly' => x($_REQUEST,'pubforums') ? $_REQUEST['pubforums'] : '', '$sort' => t('Sort'), '$selected_sort' => $current_order, '$sorturl' => $sorturl, '$forumsurl' => $forumsurl, - '$safemode' => t('Safe Mode'), - '$toggle' => $toggle, '$safemode' => array('safemode', t('Safe Mode'),$safe_mode,'','',' onchange=\'window.location.href="' . $forumsurl . '&safe="+(this.checked ? 1 : 0)\''), '$pubforums' => array('pubforums', t('Public Forums Only'),(x($_REQUEST,'pubforums') ? $_REQUEST['pubforums'] : ''),'','',' onchange=\'window.location.href="' . $forumsurl . '&pubforums="+(this.checked ? 1 : 0)\''), '$globaldir' => array('globaldir', t('This Website Only'), 1-intval($globaldir),'','',' onchange=\'window.location.href="' . $forumsurl . '&global="+(this.checked ? 0 : 1)\''), - '$localdir' => t('This Website Only'), )); return $o; } -function dir_safe_mode() { - $observer = get_observer_hash(); - if (! $observer) - return; - if ($observer) - $safe_mode = get_xconfig($observer,'directory','safe_mode'); - if($safe_mode === '0') - $toggle = t('Enable Safe Search'); - else - $toggle = t('Disable Safe Search'); - $o = replace_macros(get_markup_template('safesearch.tpl'), array( - '$safemode' => t('Safe Mode'), - '$toggle' => $toggle, - )); - - return $o; -} /** * @function sync_directories($mode) -- cgit v1.2.3 From 26a414fe4b3ab4b1d995233f0402532ad41eaeb7 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 9 Mar 2015 16:25:55 -0700 Subject: make network page default options work more or less universally instead of just from the navbar, and fix some saved-search weirdness related to the delete-term icon --- include/nav.php | 3 +-- include/widgets.php | 8 +++++--- 2 files changed, 6 insertions(+), 5 deletions(-) (limited to 'include') diff --git a/include/nav.php b/include/nav.php index 5e8317cfa..f8a112592 100644 --- a/include/nav.php +++ b/include/nav.php @@ -176,9 +176,8 @@ EOT; if(local_channel()) { - $network_options = get_pconfig(local_channel(),'system','network_page_default'); - $nav['network'] = array('network' . (($network_options) ? '?f=&' . $network_options : ''), + $nav['network'] = array('network', t('Matrix'), "", t('Your matrix'),'network_nav_btn'); $nav['network']['mark'] = array('', t('Mark all matrix notifications seen'), '',''); diff --git a/include/widgets.php b/include/widgets.php index 17c740967..243c4a25e 100644 --- a/include/widgets.php +++ b/include/widgets.php @@ -233,7 +233,6 @@ function widget_savedsearch($arr) { $srchurl = rtrim(preg_replace('/searchsave\=[^\&].*?(\&|$)/is','',$srchurl),'&'); $hasq = ((strpos($srchurl,'?') !== false) ? true : false); $srchurl = rtrim(preg_replace('/searchremove\=[^\&].*?(\&|$)/is','',$srchurl),'&'); - $hasq = ((strpos($srchurl,'?') !== false) ? true : false); $srchurl = rtrim(preg_replace('/search\=[^\&].*?(\&|$)/is','',$srchurl),'&'); $srchurl = rtrim(preg_replace('/submit\=[^\&].*?(\&|$)/is','',$srchurl),'&'); @@ -241,7 +240,10 @@ function widget_savedsearch($arr) { $hasq = ((strpos($srchurl,'?') !== false) ? true : false); + $hasamp = ((strpos($srchurl,'&') !== false) ? true : false); + if(($hasamp) && (! $hasq)) + $srchurl = substr($srchurl,0,strpos($srchurl,'&')) . '?f=&' . substr($srchurl,strpos($srchurl,'&')+1); $o = ''; @@ -257,8 +259,8 @@ function widget_savedsearch($arr) { $saved[] = array( 'id' => $rr['tid'], 'term' => $rr['term'], - 'dellink' => z_root() . '/' . $srchurl . (($hasq) ? '' : '?f=') . '&searchremove=1&search=' . urlencode($rr['term']), - 'srchlink' => z_root() . '/' . $srchurl . (($hasq) ? '' : '?f=') . '&search=' . urlencode($rr['term']), + 'dellink' => z_root() . '/' . $srchurl . (($hasq || $hasamp) ? '' : '?f=') . '&searchremove=1&search=' . urlencode($rr['term']), + 'srchlink' => z_root() . '/' . $srchurl . (($hasq || $hasamp) ? '' : '?f=') . '&search=' . urlencode($rr['term']), 'displayterm' => htmlspecialchars($rr['term'], ENT_COMPAT,'UTF-8'), 'encodedterm' => urlencode($rr['term']), 'delete' => t('Remove term'), -- cgit v1.2.3 From 972780c3ce1ffa0e70a72a167b9088c937a07d84 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 9 Mar 2015 16:28:06 -0700 Subject: whitespace --- include/nav.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'include') diff --git a/include/nav.php b/include/nav.php index f8a112592..1134d1b48 100644 --- a/include/nav.php +++ b/include/nav.php @@ -177,8 +177,7 @@ EOT; if(local_channel()) { - $nav['network'] = array('network', - t('Matrix'), "", t('Your matrix'),'network_nav_btn'); + $nav['network'] = array('network', t('Matrix'), "", t('Your matrix'),'network_nav_btn'); $nav['network']['mark'] = array('', t('Mark all matrix notifications seen'), '',''); $nav['home'] = array('channel/' . $channel['channel_address'], t('Channel Home'), "", t('Channel home'),'home_nav_btn'); -- cgit v1.2.3 From 0134a41015dd79092cb6a42ad0f7122d0af9bc6d Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 9 Mar 2015 19:57:35 -0700 Subject: more work on queue optimisations --- include/deliver.php | 10 ++++++++++ include/notifier.php | 21 ++++++++++++++++++--- include/queue.php | 15 +++++++++++---- 3 files changed, 39 insertions(+), 7 deletions(-) (limited to 'include') diff --git a/include/deliver.php b/include/deliver.php index 498440271..0fb7a4aeb 100644 --- a/include/deliver.php +++ b/include/deliver.php @@ -20,6 +20,12 @@ function deliver_run($argv, $argc) { dbesc($argv[$x]) ); if($r) { + + /** + * Check to see if we have any recent communications with this hub (in the last month). + * If not, reduce the outq_priority. + */ + $h = parse_url($r[0]['outq_posturl']); if($h) { $base = $h['scheme'] . '://' . $h['host'] . (($h['port']) ? ':' . $h['port'] : ''); @@ -38,6 +44,8 @@ function deliver_run($argv, $argc) { } } + // "post" queue driver - used for diaspora and friendica-over-diaspora communications. + if($r[0]['outq_driver'] === 'post') { $result = z_post_url($r[0]['outq_posturl'],$r[0]['outq_msg']); if($result['success'] && $result['return_code'] < 300) { @@ -92,9 +100,11 @@ function deliver_run($argv, $argc) { logger('deliver: dest: ' . $r[0]['outq_posturl'], LOGGER_DEBUG); $result = zot_zot($r[0]['outq_posturl'],$r[0]['outq_notify']); if($result['success']) { + logger('deliver: remote zot delivery succeeded to ' . $r[0]['outq_posturl']); zot_process_response($r[0]['outq_posturl'],$result, $r[0]); } else { + logger('deliver: remote zot delivery failed to ' . $r[0]['outq_posturl']); $y = q("update outq set outq_updated = '%s' where outq_hash = '%s'", dbesc(datetime_convert()), dbesc($argv[$x]) diff --git a/include/notifier.php b/include/notifier.php index a9c4905ae..bec18142a 100644 --- a/include/notifier.php +++ b/include/notifier.php @@ -135,10 +135,25 @@ function notifier_run($argv, $argc){ )); if($data) { $result = zot_zot($hh['hubloc_callback'],$data); -// zot_queue_item is not yet written -// if(! $result['success']) -// zot_queue_item(); + // if immediate delivery failed, stick it in the queue to try again later. + + if(! $result['success']) { + $hash = random_string(); + q("insert into outq ( outq_hash, outq_account, outq_channel, outq_driver, outq_posturl, outq_async, outq_created, outq_updated, outq_notify, outq_msg ) + values ( '%s', %d, %d, '%s', '%s', %d, '%s', '%s', '%s', '%s' )", + dbesc($hash), + intval($s[0]['channel_account_id']), + intval($s[0]['channel_id']), + dbesc('zot'), + dbesc($hh['hubloc_callback']), + intval(1), + dbesc(datetime_convert()), + dbesc(datetime_convert()), + dbesc($data), + dbesc('') + ); + } } } } diff --git a/include/queue.php b/include/queue.php index 8e97b4a1a..7d2ad3b2d 100644 --- a/include/queue.php +++ b/include/queue.php @@ -46,13 +46,18 @@ function queue_run($argv, $argc){ // the site is permanently down, there's no reason to attempt delivery at all, or at most not more than once // or twice a day. - + // FIXME: can we sort postgres on outq_priority and maintain the 'distinct' ? + // The order by max(outq_priority) might be a dodgy query because of the group by. + // The desired result is to return a sequence in the order most likely to be delivered in this run. + // If a hub has already been sitting in the queue for a few days, they should be delivered last; + // hence every failure should drop them further down the priority list. + if(ACTIVE_DBTYPE == DBTYPE_POSTGRES) { $prefix = 'DISTINCT ON (outq_posturl)'; $suffix = 'ORDER BY outq_posturl'; } else { $prefix = ''; - $suffix = 'GROUP BY outq_posturl'; + $suffix = 'GROUP BY outq_posturl ORDER BY max(outq_priority)'; } $r = q("SELECT $prefix * FROM outq WHERE outq_delivered = 0 and (( outq_created > %s - INTERVAL %s and outq_updated < %s - INTERVAL %s ) OR ( outq_updated < %s - INTERVAL %s )) $suffix", db_utcnow(), db_quoteinterval('12 HOUR'), @@ -77,7 +82,7 @@ function queue_run($argv, $argc){ } else { logger('queue: queue post returned ' . $result['return_code'] . ' from ' . $rr['outq_posturl'],LOGGER_DEBUG); - $y = q("update outq set outq_updated = '%s' where outq_hash = '%s'", + $y = q("update outq set outq_updated = '%s', outq_priority = outq_priority + 10 where outq_hash = '%s'", dbesc(datetime_convert()), dbesc($rr['outq_hash']) ); @@ -86,11 +91,13 @@ function queue_run($argv, $argc){ } $result = zot_zot($rr['outq_posturl'],$rr['outq_notify']); if($result['success']) { + logger('queue: deliver zot success to ' . $rr['outq_posturl'], LOGGER_DEBUG); zot_process_response($rr['outq_posturl'],$result, $rr); } else { $deadguys[] = $rr['outq_posturl']; - $y = q("update outq set outq_updated = '%s' where outq_hash = '%s'", + logger('queue: deliver zot returned ' . $result['return_code'] . ' from ' . $rr['outq_posturl'],LOGGER_DEBUG); + $y = q("update outq set outq_updated = '%s', outq_priority = outq_priority + 10 where outq_hash = '%s'", dbesc(datetime_convert()), dbesc($rr['outq_hash']) ); -- cgit v1.2.3 From 54a9fb1774a256a0f61bc7a8a9ffdcee83b9895b Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 10 Mar 2015 12:22:22 -0700 Subject: diaspora's spammy permission model seems to have leaked through our firehose. Don't let it. --- include/zot.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/zot.php b/include/zot.php index c9019ca7a..c3325609b 100644 --- a/include/zot.php +++ b/include/zot.php @@ -1547,8 +1547,11 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque $channel = $r[0]; - // allow public postings to the sys channel regardless of permissions - if(($channel['channel_pageflags'] & PAGE_SYSTEM) && (! $arr['item_private'])) { + // allow public postings to the sys channel regardless of permissions, but not + // for comments travelling upstream. Wait and catch them on the way down. + // They may have been blocked by the owner. + + if(($channel['channel_pageflags'] & PAGE_SYSTEM) && (! $arr['item_private']) && (! $relay)) { $local_public = true; $r = q("select xchan_flags from xchan where xchan_hash = '%s' limit 1", -- cgit v1.2.3 From 946beb61910409abe592355c9bcdc88a70e514a3 Mon Sep 17 00:00:00 2001 From: Klaus Weidenbach Date: Tue, 10 Mar 2015 21:42:26 +0100 Subject: View upload photo button only if you have permission. Check if post_photos permission is available otherwise hide the photo upload button. Or should we show the button and just disable it with a title, about missing permission to upload photos? In comments we use the same icon, but just add [img] bb-code. Should we provide this if no permission to upload photos. Do we need different icons for [img] and photo upload buttons? --- include/conversation.php | 113 ++++++++++++++++++++++------------------------- 1 file changed, 54 insertions(+), 59 deletions(-) (limited to 'include') diff --git a/include/conversation.php b/include/conversation.php index 8bc42b34b..bc1883efc 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -1081,7 +1081,7 @@ function format_like($cnt,$arr,$type,$id) { } -function status_editor($a,$x,$popup=false) { +function status_editor($a, $x, $popup = false) { $o = ''; @@ -1092,28 +1092,28 @@ function status_editor($a,$x,$popup=false) { // if(feature_enabled(local_channel(),'richtext')) // $plaintext = false; - $voting = feature_enabled(local_channel(),'consensus_tools'); + $voting = feature_enabled(local_channel(), 'consensus_tools'); $mimeselect = ''; - if(array_key_exists('mimetype',$x) && $x['mimetype']) { + if(array_key_exists('mimetype', $x) && $x['mimetype']) { if($x['mimetype'] != 'text/bbcode') $plaintext = true; if($x['mimetype'] === 'choose') { $mimeselect = mimetype_select($x['profile_uid']); } else - $mimeselect = ''; + $mimeselect = ''; } $layoutselect = ''; - if(array_key_exists('layout',$x) && $x['layout']) { + if(array_key_exists('layout', $x) && $x['layout']) { if($x['layout'] === 'choose') { $layoutselect = layout_select($x['profile_uid']); } else - $layoutselect = ''; + $layoutselect = ''; } - + if(array_key_exists('channel_select',$x) && $x['channel_select']) { require_once('include/identity.php'); @@ -1126,7 +1126,7 @@ function status_editor($a,$x,$popup=false) { $webpage = ((x($x,'webpage')) ? $x['webpage'] : ''); $tpl = get_markup_template('jot-header.tpl'); - + $a->page['htmlhead'] .= replace_macros($tpl, array( '$newpost' => 'true', '$baseurl' => $a->get_baseurl(true), @@ -1135,8 +1135,8 @@ function status_editor($a,$x,$popup=false) { '$nickname' => $x['nickname'], '$ispublic' => t('Visible to everybody'), '$linkurl' => t('Please enter a link URL:'), - '$vidurl' => t("Please enter a video link/URL:"), - '$audurl' => t("Please enter an audio link/URL:"), + '$vidurl' => t('Please enter a video link/URL:'), + '$audurl' => t('Please enter an audio link/URL:'), '$term' => t('Tag term:'), '$fileas' => t('Save to Folder:'), '$whereareu' => t('Where are you right now?'), @@ -1144,35 +1144,35 @@ function status_editor($a,$x,$popup=false) { )); - $tpl = get_markup_template("jot.tpl"); + $tpl = get_markup_template('jot.tpl'); $jotplugins = ''; $jotnets = ''; $preview = t('Preview'); // $preview = ((feature_enabled($x['profile_uid'],'preview')) ? t('Preview') : ''); - if(x($x,'nopreview')) + if(x($x, 'nopreview')) $preview = ''; - $defexpire = ((($z = get_pconfig($x['profile_uid'],'system','default_post_expire')) && (! $webpage)) ? $z : ''); - + $defexpire = ((($z = get_pconfig($x['profile_uid'], 'system', 'default_post_expire')) && (! $webpage)) ? $z : ''); - $cipher = get_pconfig($x['profile_uid'],'system','default_cipher'); + $cipher = get_pconfig($x['profile_uid'], 'system', 'default_cipher'); if(! $cipher) $cipher = 'aes256'; call_hooks('jot_tool', $jotplugins); call_hooks('jot_networks', $jotnets); - $o .= replace_macros($tpl,array( - '$return_path' => ((x($x,'return_path')) ? $x['return_path'] : $a->query_string), + $o .= replace_macros($tpl, array( + '$return_path' => ((x($x, 'return_path')) ? $x['return_path'] : $a->query_string), '$action' => $a->get_baseurl(true) . '/item', '$share' => (x($x,'button') ? $x['button'] : t('Share')), '$webpage' => $webpage, '$placeholdpagetitle' => ((x($x,'ptlabel')) ? $x['ptlabel'] : t('Page link title')), - '$pagetitle' => (x($x,'pagetitle') ? $x['pagetitle'] : ''), + '$pagetitle' => (x($x,'pagetitle') ? $x['pagetitle'] : ''), '$id_select' => $id_select, '$id_seltext' => t('Post as'), + '$writephoto' => perm_is_allowed($x['profile_uid'], get_observer_hash(), 'post_photos'), '$upload' => t('Upload photo'), '$shortupload' => t('upload photo'), '$attach' => t('Attach file'), @@ -1188,11 +1188,11 @@ function status_editor($a,$x,$popup=false) { '$voting' => t('Toggle voting'), '$feature_voting' => $voting, '$consensus' => 0, - '$noloc' => ((get_pconfig($x['profile_uid'],'system','use_browser_location')) ? t('Clear browser location') : ''), + '$noloc' => ((get_pconfig($x['profile_uid'], 'system', 'use_browser_location')) ? t('Clear browser location') : ''), '$shortnoloc' => t('clear location'), - '$title' => ((x($x,'title')) ? htmlspecialchars($x['title'], ENT_COMPAT,'UTF-8') : ''), + '$title' => ((x($x, 'title')) ? htmlspecialchars($x['title'], ENT_COMPAT,'UTF-8') : ''), '$placeholdertitle' => t('Title (optional)'), - '$catsenabled' => ((feature_enabled($x['profile_uid'],'categories') && (! $webpage)) ? 'categories' : ''), + '$catsenabled' => ((feature_enabled($x['profile_uid'], 'categories') && (! $webpage)) ? 'categories' : ''), '$category' => "", '$placeholdercategory' => t('Categories (optional, comma-separated list)'), '$wait' => t('Please wait'), @@ -1211,26 +1211,24 @@ function status_editor($a,$x,$popup=false) { '$acl' => $x['acl'], '$mimeselect' => $mimeselect, '$layoutselect' => $layoutselect, - '$showacl' => ((array_key_exists('showacl',$x)) ? $x['showacl'] : true), + '$showacl' => ((array_key_exists('showacl', $x)) ? $x['showacl'] : true), '$bang' => $x['bang'], '$profile_uid' => $x['profile_uid'], '$preview' => $preview, - '$source' => ((x($x,'source')) ? $x['source'] : ''), + '$source' => ((x($x, 'source')) ? $x['source'] : ''), '$jotplugins' => $jotplugins, '$defexpire' => $defexpire, - '$feature_expire' => ((feature_enabled($x['profile_uid'],'content_expire') && (! $webpage)) ? true : false), + '$feature_expire' => ((feature_enabled($x['profile_uid'], 'content_expire') && (! $webpage)) ? true : false), '$expires' => t('Set expiration date'), - '$feature_encrypt' => ((feature_enabled($x['profile_uid'],'content_encrypt') && (! $webpage)) ? true : false), + '$feature_encrypt' => ((feature_enabled($x['profile_uid'], 'content_encrypt') && (! $webpage)) ? true : false), '$encrypt' => t('Encrypt text'), '$cipher' => $cipher, '$expiryModalOK' => t('OK'), '$expiryModalCANCEL' => t('Cancel') )); - - if ($popup==true){ - $o = ''; - + if ($popup === true) { + $o = ''; } return $o; @@ -1279,13 +1277,12 @@ function add_children_to_list($children, &$arr) { } } -function conv_sort($arr,$order) { +function conv_sort($arr, $order) { if((!(is_array($arr) && count($arr)))) return array(); $parents = array(); - $children = array(); foreach($arr as $x) if($x['id'] == $x['parent']) @@ -1340,6 +1337,7 @@ function find_thread_parent_index($arr,$x) { foreach($arr as $k => $v) if($v['id'] == $x['parent']) return $k; + return false; } @@ -1368,6 +1366,7 @@ function render_location_default($item) { else $location = '' . $coord . ''; } + return $location; } @@ -1389,14 +1388,15 @@ function prepare_page($item) { // prepare_body calls unobscure() as a side effect. Do it here so that // the template will get passed an unobscured title. - $body = prepare_body($item,true); - $tpl = get_pconfig($item['uid'],'system','pagetemplate'); - if (! $tpl) - $tpl = 'page_display.tpl'; - return replace_macros(get_markup_template($tpl),array( + $body = prepare_body($item, true); + $tpl = get_pconfig($item['uid'], 'system', 'pagetemplate'); + if (! $tpl) + $tpl = 'page_display.tpl'; + + return replace_macros(get_markup_template($tpl), array( '$author' => (($naked) ? '' : $item['author']['xchan_name']), '$auth_url' => (($naked) ? '' : zid($item['author']['xchan_url'])), - '$date' => (($naked) ? '' : datetime_convert('UTC',date_default_timezone_get(),$item['created'],'Y-m-d H:i')), + '$date' => (($naked) ? '' : datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'Y-m-d H:i')), '$title' => smilies(bbcode($item['title'])), '$body' => $body, '$preview' => $preview, @@ -1420,15 +1420,15 @@ function network_tabs() { if(x($_GET,'new')) { $new_active = 'active'; } - + if(x($_GET,'search')) { $search_active = 'active'; } - + if(x($_GET,'star')) { $starred_active = 'active'; } - + if(x($_GET,'conv')) { $conv_active = 'active'; } @@ -1441,8 +1441,7 @@ function network_tabs() { $public_active = 'active'; } - - + if (($new_active == '') && ($starred_active == '') && ($conv_active == '') @@ -1458,7 +1457,7 @@ function network_tabs() { case 'comment' : $all_active = 'active'; $no_active=''; break; } } - + if ($no_active=='active') $all_active='active'; $cmd = $a->cmd; @@ -1469,22 +1468,22 @@ function network_tabs() { if(! get_config('system','disable_discover_tab')) { $tabs[] = array( 'label' => t('Discover'), - 'url'=>z_root() . '/' . $cmd . '?f=&fh=1' , - 'sel'=> $public_active, - 'title'=> t('Imported public streams'), + 'url' => z_root() . '/' . $cmd . '?f=&fh=1' , + 'sel' => $public_active, + 'title' => t('Imported public streams'), ); } $tabs[] = array( 'label' => t('Commented Order'), - 'url'=>z_root() . '/' . $cmd . '?f=&order=comment' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : '') . ((x($_GET,'gid')) ? '&gid=' . $_GET['gid'] : ''), + 'url'=>z_root() . '/' . $cmd . '?f=&order=comment' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : '') . ((x($_GET,'gid')) ? '&gid=' . $_GET['gid'] : ''), 'sel'=>$all_active, 'title'=> t('Sort by Comment Date'), ); - + $tabs[] = array( 'label' => t('Posted Order'), - 'url'=>z_root() . '/' . $cmd . '?f=&order=post' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : '') . ((x($_GET,'gid')) ? '&gid=' . $_GET['gid'] : ''), + 'url'=>z_root() . '/' . $cmd . '?f=&order=post' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : '') . ((x($_GET,'gid')) ? '&gid=' . $_GET['gid'] : ''), 'sel'=>$postord_active, 'title' => t('Sort by Post Date'), ); @@ -1498,7 +1497,7 @@ function network_tabs() { ); } - if(feature_enabled(local_channel(),'new_tab')) { + if(feature_enabled(local_channel(),'new_tab')) { $tabs[] = array( 'label' => t('New'), 'url' => z_root() . '/' . $cmd . '?f=' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : '') . '&new=1' . ((x($_GET,'gid')) ? '&gid=' . $_GET['gid'] : ''), @@ -1524,15 +1523,14 @@ function network_tabs() { 'sel'=> $spam_active, 'title' => t('Posts flagged as SPAM'), ); - } + } $arr = array('tabs' => $tabs); call_hooks('network_tabs', $arr); $tpl = get_markup_template('common_tabs.tpl'); - return replace_macros($tpl,array('$tabs' => $arr['tabs'])); - + return replace_macros($tpl, array('$tabs' => $arr['tabs'])); } @@ -1550,13 +1548,13 @@ function profile_tabs($a, $is_owner=False, $nickname=Null){ $nickname = $channel['channel_address']; $uid = (($a->profile['profile_uid']) ? $a->profile['profile_uid'] : local_channel()); - + if (get_pconfig($uid,'system','noprofiletabs')) return; - + if(x($_GET,'tab')) $tab = notags(trim($_GET['tab'])); - + $url = $a->get_baseurl() . '/channel/' . $nickname; $pr = $a->get_baseurl() . '/profile/' . $nickname; @@ -1636,13 +1634,10 @@ function profile_tabs($a, $is_owner=False, $nickname=Null){ 'id' => 'webpages-tab', ); } - else { // FIXME // we probably need a listing of events that were created by // this channel and are visible to the observer - - } $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs); -- cgit v1.2.3 From 09d0401edb616df843224b8cdff2e255de70a562 Mon Sep 17 00:00:00 2001 From: Klaus Weidenbach Date: Tue, 10 Mar 2015 23:17:13 +0100 Subject: Fix SQL query for removing orphan hooks. initialize some variables before using them. commented out some unused variables. --- include/plugin.php | 89 +++++++++++++++++++++++++++++++++++------------------- 1 file changed, 58 insertions(+), 31 deletions(-) (limited to 'include') diff --git a/include/plugin.php b/include/plugin.php index 08decc8e3..b6cfc8d89 100755 --- a/include/plugin.php +++ b/include/plugin.php @@ -38,7 +38,7 @@ function uninstall_plugin($plugin) { return false; logger("Addons: uninstalling " . $plugin); - $t = @filemtime('addon/' . $plugin . '/' . $plugin . '.php'); + //$t = @filemtime('addon/' . $plugin . '/' . $plugin . '.php'); @include_once('addon/' . $plugin . '/' . $plugin . '.php'); if(function_exists($plugin . '_uninstall')) { $func = $plugin . '_uninstall'; @@ -68,7 +68,7 @@ function install_plugin($plugin) { $func(); } - $plugin_admin = (function_exists($plugin . "_plugin_admin") ? 1 : 0); + $plugin_admin = (function_exists($plugin . '_plugin_admin') ? 1 : 0); $r = q("INSERT INTO `addon` (`name`, `installed`, `timestamp`, `plugin_admin`) VALUES ( '%s', 1, %d , %d ) ", dbesc($plugin), @@ -91,7 +91,7 @@ function load_plugin($plugin) { return false; logger("Addons: loading " . $plugin, LOGGER_DEBUG); - $t = @filemtime('addon/' . $plugin . '/' . $plugin . '.php'); + //$t = @filemtime('addon/' . $plugin . '/' . $plugin . '.php'); @include_once('addon/' . $plugin . '/' . $plugin . '.php'); if(function_exists($plugin . '_load')) { $func = $plugin . '_load'; @@ -120,6 +120,7 @@ function plugin_is_installed($name) { ); if($r) return true; + return false; } @@ -189,7 +190,7 @@ function register_hook($hook, $file, $function, $priority = 0) { if(count($r)) return true; - $r = q("INSERT INTO `hook` (`hook`, `file`, `function`, `priority`) VALUES ( '%s', '%s', '%s', '%s' ) ", + $r = q("INSERT INTO `hook` (`hook`, `file`, `function`, `priority`) VALUES ( '%s', '%s', '%s', '%s' )", dbesc($hook), dbesc($file), dbesc($function), @@ -228,11 +229,13 @@ function load_hooks() { $a = get_app(); // if(! is_array($a->hooks)) $a->hooks = array(); + $r = q("SELECT * FROM hook WHERE true ORDER BY priority DESC"); if($r) { foreach($r as $rr) { if(! array_key_exists($rr['hook'],$a->hooks)) $a->hooks[$rr['hook']] = array(); + $a->hooks[$rr['hook']][] = array($rr['file'],$rr['function']); } } @@ -256,32 +259,41 @@ function load_hooks() { * name of hook to attach callback * @param string $fn; * function name of callback handler - * */ -function insert_hook($hook,$fn) { +function insert_hook($hook, $fn) { $a = get_app(); if(! is_array($a->hooks)) $a->hooks = array(); - if(! array_key_exists($hook,$a->hooks)) + + if(! array_key_exists($hook, $a->hooks)) $a->hooks[$hook] = array(); - $a->hooks[$hook][] = array('',$fn); -} + $a->hooks[$hook][] = array('', $fn); +} +/** + * @brief Calls a hook. + * + * Use this function when you want to be able to allow a hook to manipulate + * the provided data. + * + * @param string $name of the hook to call + * @param string|array &$data to transmit to the callback handler + */ function call_hooks($name, &$data = null) { $a = get_app(); - if((is_array($a->hooks)) && (array_key_exists($name,$a->hooks))) { + if((is_array($a->hooks)) && (array_key_exists($name, $a->hooks))) { foreach($a->hooks[$name] as $hook) { if($hook[0]) @include_once($hook[0]); + if(function_exists($hook[1])) { $func = $hook[1]; - $func($a,$data); - } - else { + $func($a, $data); + } else { // remove orphan hooks - q("delete from hook where hook = '%s' and file = '$s' and function = '%s' limit 1", + q("DELETE FROM hook WHERE hook = '%s' AND file = '%s' AND function = '%s'", dbesc($name), dbesc($hook[0]), dbesc($hook[1]) @@ -308,16 +320,18 @@ function call_hooks($name, &$data = null) { * @return array with the plugin information */ function get_plugin_info($plugin){ - $info = Array( + $m = array(); + $info = array( 'name' => $plugin, - 'description' => "", + 'description' => '', 'author' => array(), - 'version' => "", - 'compat' => "" + 'version' => '', + 'compat' => '' ); - if (!is_file("addon/$plugin/$plugin.php")) return $info; - + if (!is_file("addon/$plugin/$plugin.php")) + return $info; + $f = file_get_contents("addon/$plugin/$plugin.php"); $r = preg_match("|/\*.*\*/|msU", $f, $m); @@ -328,7 +342,7 @@ function get_plugin_info($plugin){ if ($l != ""){ list($k, $v) = array_map("trim", explode(":", $l, 2)); $k = strtolower($k); - if ($k == "author"){ + if ($k == 'author'){ $r = preg_match("|([^<]+)<([^>]+)>|", $v, $m); if ($r) { $info['author'][] = array('name' => $m[1], 'link' => $m[2]); @@ -343,6 +357,7 @@ function get_plugin_info($plugin){ } } } + return $info; } @@ -363,13 +378,14 @@ function get_plugin_info($plugin){ * @return array */ function get_theme_info($theme){ - $info=Array( + $m = array(); + $info = array( 'name' => $theme, - 'description' => "", + 'description' => '', 'author' => array(), - 'version' => "", - 'compat' => "", - 'credits' => "", + 'version' => '', + 'compat' => '', + 'credits' => '', 'maintainer' => array(), 'experimental' => false, 'unsupported' => false @@ -377,10 +393,12 @@ function get_theme_info($theme){ if(file_exists("view/theme/$theme/experimental")) $info['experimental'] = true; + if(file_exists("view/theme/$theme/unsupported")) $info['unsupported'] = true; - if (!is_file("view/theme/$theme/php/theme.php")) return $info; + if (!is_file("view/theme/$theme/php/theme.php")) + return $info; $f = file_get_contents("view/theme/$theme/php/theme.php"); $r = preg_match("|/\*.*\*/|msU", $f, $m); @@ -392,7 +410,7 @@ function get_theme_info($theme){ if ($l != ""){ list($k, $v) = array_map("trim", explode(":", $l, 2)); $k = strtolower($k); - if ($k == "author"){ + if ($k == 'author'){ $r = preg_match("|([^<]+)<([^>]+)>|", $v, $m); if ($r) { $info['author'][] = array('name' => $m[1], 'link' => $m[2]); @@ -400,7 +418,7 @@ function get_theme_info($theme){ $info['author'][] = array('name' => $v); } } - elseif ($k == "maintainer"){ + elseif ($k == 'maintainer'){ $r = preg_match("|([^<]+)<([^>]+)>|", $v, $m); if ($r) { $info['maintainer'][] = array('name' => $m[1], 'link' => $m[2]); @@ -415,10 +433,18 @@ function get_theme_info($theme){ } } } + return $info; } - +/** + * @brief Returns the theme's screenshot. + * + * The screenshot is expected as view/theme/$theme/img/screenshot.[png|jpg]. + * + * @param sring $theme The name of the theme + * @return string + */ function get_theme_screenshot($theme) { $a = get_app(); $exts = array('.png', '.jpg'); @@ -426,6 +452,7 @@ function get_theme_screenshot($theme) { if(file_exists('view/theme/' . $theme . '/img/screenshot' . $ext)) return($a->get_baseurl() . '/view/theme/' . $theme . '/img/screenshot' . $ext); } + return($a->get_baseurl() . '/images/blank.png'); } @@ -458,7 +485,7 @@ function head_get_css() { } function format_css_if_exists($source) { - if(strpos($source[0],'/') !== false) + if(strpos($source[0], '/') !== false) $path = $source[0]; else $path = theme_include($source[0]); -- cgit v1.2.3 From 5b35f1e6c4fbf0fd941c6d292b9c9b5847b64d0b Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 10 Mar 2015 15:43:15 -0700 Subject: Change logic of "don't create a status post for this photo upload" and turn it into a bona-fide on/off toggle. This takes up one more vertical line, but we have it to spare, and the single button (while concise visually) provided no feedback of the current state, or indicate whether a second click toggled it. Some addons use this setting so addons will need to be pulled when this is pulled in order to remain in sync. --- include/Import/refimport.php | 2 +- include/photos.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'include') diff --git a/include/Import/refimport.php b/include/Import/refimport.php index 181b2b398..b9b6bf639 100644 --- a/include/Import/refimport.php +++ b/include/Import/refimport.php @@ -174,7 +174,7 @@ function reflect_photo_callback($matches) { 'resource_id' => str_replace('-','',$hash), 'filename' => $hash . '.jpg', 'type' => 'image/jpeg', - 'not_visible' => true + 'visible' => false ) ); diff --git a/include/photos.php b/include/photos.php index cd753ffea..4841e649d 100644 --- a/include/photos.php +++ b/include/photos.php @@ -54,8 +54,8 @@ function photo_upload($channel, $observer, $args) { else $visible = 0; - if(intval($args['not_visible']) || $args['not_visible'] === 'true') - $visible = 0; + if(intval($args['visible']) || $args['visible'] === 'true') + $visible = 1; $str_group_allow = perms2str(((is_array($args['group_allow'])) ? $args['group_allow'] : explode(',',$args['group_allow']))); $str_contact_allow = perms2str(((is_array($args['contact_allow'])) ? $args['contact_allow'] : explode(',',$args['contact_allow']))); -- cgit v1.2.3 From 65ffd209d43a4af9d0c866465d28fde26a2bbd83 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 10 Mar 2015 19:43:15 -0700 Subject: allow urls using the zot: or zots: URL schemes to exist without getting filtered away. --- include/bbcode.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/bbcode.php b/include/bbcode.php index 6b8cb941f..aa6641ca2 100644 --- a/include/bbcode.php +++ b/include/bbcode.php @@ -864,7 +864,7 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { // fix any escaped ampersands that may have been converted into links $Text = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$Text); - $Text = preg_replace("/\<(.*?)(src|href)=\"[^hfm#](.*?)\>/ism",'<$1$2="">',$Text); + $Text = preg_replace("/\<(.*?)(src|href)=\"[^zhfm#](.*?)\>/ism",'<$1$2="">',$Text); $Text = bb_replace_images($Text,$saved_images); -- cgit v1.2.3 From 0014cf4ff232328c3e3d0993eb8e9893a7c16f54 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 11 Mar 2015 00:21:57 -0700 Subject: skip trying to come up with an intelligent way to decide what photos should get a status post - leave it manual. --- include/photos.php | 20 +------------------- 1 file changed, 1 insertion(+), 19 deletions(-) (limited to 'include') diff --git a/include/photos.php b/include/photos.php index 4841e649d..c2f5ed4ba 100644 --- a/include/photos.php +++ b/include/photos.php @@ -34,29 +34,11 @@ function photo_upload($channel, $observer, $args) { $album = datetime_convert('UTC',date_default_timezone_get(),'now', 'Y-m'); } - /** - * - * We create a wall item for every photo, but we don't want to - * overwhelm the data stream with a hundred newly uploaded photos. - * So we will make the first photo uploaded to this album in the last several hours - * visible by default, the rest will become visible over time when and if - * they acquire comments, likes, dislikes, and/or tags - * - */ - - $r = q("SELECT * FROM photo WHERE album = '%s' AND uid = %d AND created > %s - INTERVAL %s ", - dbesc($album), - intval($channel_id), - db_utcnow(), db_quoteinterval('3 HOUR') - ); - if((! $r) || ($album == t('Profile Photos'))) + if(intval($args['visible']) || $args['visible'] === 'true') $visible = 1; else $visible = 0; - if(intval($args['visible']) || $args['visible'] === 'true') - $visible = 1; - $str_group_allow = perms2str(((is_array($args['group_allow'])) ? $args['group_allow'] : explode(',',$args['group_allow']))); $str_contact_allow = perms2str(((is_array($args['contact_allow'])) ? $args['contact_allow'] : explode(',',$args['contact_allow']))); $str_group_deny = perms2str(((is_array($args['group_deny'])) ? $args['group_deny'] : explode(',',$args['group_deny']))); -- cgit v1.2.3 From 35fc14d6ab286a20bc8c510733c46cbd5f0d9676 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 11 Mar 2015 15:11:57 -0700 Subject: don't relay diaspora comments to sys channel --- include/diaspora.php | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'include') diff --git a/include/diaspora.php b/include/diaspora.php index 7295b4261..da55b8fb6 100755 --- a/include/diaspora.php +++ b/include/diaspora.php @@ -1287,6 +1287,12 @@ function diaspora_comment($importer,$xml,$msg) { // our post, so he/she must be a contact of ours and his/her public key // should be in $msg['key'] + if($importer['system']) { + // don't relay to the sys channel + logger('diaspora_comment: relay to sys channel blocked.'); + return; + } + $author_signature = base64_decode($author_signature); if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) { -- cgit v1.2.3 From 4e98a70e66ccac9de891760219bf86eda3bb3d68 Mon Sep 17 00:00:00 2001 From: Michael Johnston Date: Wed, 11 Mar 2015 20:56:40 -0400 Subject: add missing %d for abook_closeness --- include/zot.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/zot.php b/include/zot.php index c3325609b..5c12dc4ba 100644 --- a/include/zot.php +++ b/include/zot.php @@ -469,7 +469,7 @@ function zot_refresh($them,$channel = null, $force = false) { if($closeness === false) $closeness = 80; - $y = q("insert into abook ( abook_account, abook_channel, abook_closeness, abook_xchan, abook_their_perms, abook_my_perms, abook_created, abook_updated, abook_dob, abook_flags ) values ( %d, %d, '%s', %d, %d, '%s', '%s', '%s', %d )", + $y = q("insert into abook ( abook_account, abook_channel, abook_closeness, abook_xchan, abook_their_perms, abook_my_perms, abook_created, abook_updated, abook_dob, abook_flags ) values ( %d, %d, %d, '%s', %d, %d, '%s', '%s', '%s', %d )", intval($channel['channel_account_id']), intval($channel['channel_id']), intval($closeness), -- cgit v1.2.3 From 1b3fee05e6db1fa80cd1a76395fa9e558e1e53c4 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 11 Mar 2015 18:04:43 -0700 Subject: turn parse_url into the definitive url attaching mechanism --- include/bbcode.php | 22 +++++++++++++++++++++- include/oembed.php | 16 ++++++++++++++-- 2 files changed, 35 insertions(+), 3 deletions(-) (limited to 'include') diff --git a/include/bbcode.php b/include/bbcode.php index aa6641ca2..32e5d014f 100644 --- a/include/bbcode.php +++ b/include/bbcode.php @@ -756,11 +756,17 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { // html5 video and audio if (strpos($Text,'[/video]') !== false) { - $Text = preg_replace_callback("/\[video\](.*?\.(ogg|ogv|oga|ogm|webm|mp4))\[\/video\]/ism", 'tryzrlvideo', $Text); + $Text = preg_replace_callback("/\[video\](.*?\.(ogg|ogv|oga|ogm|webm|mp4|mpeg|mpg))\[\/video\]/ism", 'tryzrlvideo', $Text); } if (strpos($Text,'[/audio]') !== false) { $Text = preg_replace_callback("/\[audio\](.*?\.(ogg|ogv|oga|ogm|webm|mp4|mp3|opus))\[\/audio\]/ism", 'tryzrlaudio', $Text); } + if (strpos($Text,'[/zvideo]') !== false) { + $Text = preg_replace_callback("/\[zvideo\](.*?\.(ogg|ogv|oga|ogm|webm|mp4|mpeg|mpg))\[\/zvideo\]/ism", 'tryzrlvideo', $Text); + } + if (strpos($Text,'[/zaudio]') !== false) { + $Text = preg_replace_callback("/\[zaudio\](.*?\.(ogg|ogv|oga|ogm|webm|mp4|mp3|opus))\[\/zaudio\]/ism", 'tryzrlaudio', $Text); + } // Try to Oembed if ($tryoembed) { @@ -771,6 +777,13 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { if (strpos($Text,'[/audio]') !== false) { $Text = preg_replace_callback("/\[audio\](.*?)\[\/audio\]/ism", 'tryoembed', $Text); } + + if (strpos($Text,'[/zvideo]') !== false) { + $Text = preg_replace_callback("/\[zvideo\](.*?)\[\/zvideo\]/ism", 'tryoembed', $Text); + } + if (strpos($Text,'[/zaudio]') !== false) { + $Text = preg_replace_callback("/\[zaudio\](.*?)\[\/zaudio\]/ism", 'tryoembed', $Text); + } } // if video couldn't be embedded, link to it instead. @@ -781,6 +794,13 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { $Text = preg_replace("/\[audio\](.*?)\[\/audio\]/", '$1', $Text); } + if (strpos($Text,'[/zvideo]') !== false) { + $Text = preg_replace("/\[zvideo\](.*?)\[\/zvideo\]/", '$1', $Text); + } + if (strpos($Text,'[/zaudio]') !== false) { + $Text = preg_replace("/\[zaudio\](.*?)\[\/zaudio\]/", '$1', $Text); + } + diff --git a/include/oembed.php b/include/oembed.php index 38c433e99..ea91ec22b 100755 --- a/include/oembed.php +++ b/include/oembed.php @@ -8,13 +8,25 @@ function oembed_replacecb($matches){ } +// if the url is embeddable with oembed, return the bbcode link. + +function oembed_process($url) { + $j = oembed_fetch_url($url); + logger('oembed_process: ' . print_r($j,true)); + if($j && $j->type !== 'error') + return '[embed]' . $url . '[/embed]'; + return false; +} + + + function oembed_fetch_url($embedurl){ $a = get_app(); $txt = Cache::get($a->videowidth . $embedurl); - if(strstr($txt,'youtu')) { + if(strstr($txt,'youtu') && strstr(z_root(),'https:')) { $txt = str_replace('http:','https:',$txt); } @@ -105,7 +117,7 @@ function oembed_format_object($j){ $th=120; $tw = $th*$tr; $tpl=get_markup_template('oembed_video.tpl'); - if(strstr($embedurl,'youtu')) { + if(strstr($embedurl,'youtu') && strstr(z_root(),'https:')) { $embedurl = str_replace('http:','https:',$embedurl); $j->thumbnail_url = str_replace('http:','https:', $j->thumbnail_url); $jhtml = str_replace('http:','https:', $jhtml); -- cgit v1.2.3 From d80088f6f6b2d976fc683fcc6db52d2d5ba2f092 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 11 Mar 2015 18:12:04 -0700 Subject: make embeds bookmarkable --- include/oembed.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/oembed.php b/include/oembed.php index ea91ec22b..0628afaa9 100755 --- a/include/oembed.php +++ b/include/oembed.php @@ -154,7 +154,7 @@ function oembed_format_object($j){ // add link to source if not present in "rich" type if ( $j->type!='rich' || !strpos($j->html,$embedurl) ){ $embedlink = (isset($j->title))?$j->title:$embedurl; - $ret .= "$embedlink"; + $ret .= '#^' . "$embedlink"; $ret .= "
      "; if (isset($j->author_name)) $ret.=" by ".$j->author_name; if (isset($j->provider_name)) $ret.=" on ".$j->provider_name; -- cgit v1.2.3 From b3a9a6c802170a15cc58fd3af966b35f81c50818 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 11 Mar 2015 18:56:28 -0700 Subject: remove the now redundant audio/video buttons and label the editor text style buttons which didn't have them. Unused editor buttons were commented in case we need to bring them back. If things go smoothly we can remove them. Use the link icon going forward - for all links. --- include/ItemObject.php | 2 +- include/conversation.php | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) (limited to 'include') diff --git a/include/ItemObject.php b/include/ItemObject.php index 1785d55e7..4fc01e6d4 100644 --- a/include/ItemObject.php +++ b/include/ItemObject.php @@ -672,7 +672,7 @@ class Item extends BaseObject { '$edquote' => t('Quote'), '$edcode' => t('Code'), '$edimg' => t('Image'), - '$edurl' => t('Link'), + '$edurl' => t('Insert Link'), '$edvideo' => t('Video'), '$preview' => t('Preview'), // ((feature_enabled($conv->get_profile_owner(),'preview')) ? t('Preview') : ''), '$indent' => $indent, diff --git a/include/conversation.php b/include/conversation.php index bc1883efc..0e35202fa 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -1173,6 +1173,11 @@ function status_editor($a, $x, $popup = false) { '$id_select' => $id_select, '$id_seltext' => t('Post as'), '$writephoto' => perm_is_allowed($x['profile_uid'], get_observer_hash(), 'post_photos'), + '$bold' => t('Bold'), + '$italic' => t('Italic'), + '$underline' => t('Underline'), + '$quote' => t('Quote'), + '$code' => t('Code'), '$upload' => t('Upload photo'), '$shortupload' => t('upload photo'), '$attach' => t('Attach file'), -- cgit v1.2.3 From 124b17dcf44d6a9aac34b28ee455bd46738cb4ee Mon Sep 17 00:00:00 2001 From: Klaus Weidenbach Date: Fri, 13 Mar 2015 00:16:19 +0100 Subject: Some cleanups. Fixed dbesc_identifier(), but it is not used yet. Corrected some other variable names and variable initialization before using them. --- include/dba/dba_driver.php | 23 ++++----- include/session.php | 115 ++++++++++++++++++++++++++++----------------- include/text.php | 29 +++++++----- 3 files changed, 99 insertions(+), 68 deletions(-) (limited to 'include') diff --git a/include/dba/dba_driver.php b/include/dba/dba_driver.php index 4a0f5e37b..708d8e709 100755 --- a/include/dba/dba_driver.php +++ b/include/dba/dba_driver.php @@ -24,7 +24,6 @@ function dba_factory($server, $port,$user,$pass,$db,$dbtype,$install = false) { $dba = null; - $dbtype = intval($dbtype); if($dbtype == DBTYPE_POSTGRES) { @@ -59,7 +58,7 @@ abstract class dba_driver { const INSTALL_SCRIPT='install/schema_mysql.sql'; const NULL_DATE = '0000-00-00 00:00:00'; const UTC_NOW = 'UTC_TIMESTAMP()'; - + protected $debug = 0; protected $db; public $connected = false; @@ -121,11 +120,11 @@ abstract class dba_driver { function get_null_date() { return static::NULL_DATE; } - + function get_install_script() { return static::INSTALL_SCRIPT; } - + function utcnow() { return static::UTC_NOW; } @@ -145,6 +144,7 @@ abstract class dba_driver { return false; } } + return true; } @@ -166,19 +166,19 @@ abstract class dba_driver { function quote_interval($txt) { return $txt; } - + function optimize_table($table) { q('OPTIMIZE TABLE '.$table); } - + function concat($fld, $sep) { return 'GROUP_CONCAT(DISTINCT '.$fld.' SEPARATOR \''.$sep.'\')'; } - + function escapebin($str) { return $this->escape($str); } - + function unescapebin($str) { return $str; } @@ -193,6 +193,7 @@ function printable($s) { $s = str_replace("\x00",'.',$s); if(x($_SERVER,'SERVER_NAME')) $s = escape_tags($s); + return $s; } @@ -252,7 +253,7 @@ function db_quoteinterval($txt) { function dbesc_identifier($str) { global $db; - return $db->escape_identifier($txt); + return $db->escape_identifier($str); } function db_utcnow() { @@ -349,6 +350,7 @@ function dbesc_array_cb(&$item, $key) { $item = '0001-01-01 00:00:00'; else if($item == '0001-01-01 00:00:00' && ACTIVE_DBTYPE == DBTYPE_MYSQL) $item = '0000-00-00 00:00:00'; + $item = dbesc($item); } } @@ -382,8 +384,7 @@ function db_getfunc($f) { $f = strtolower($f); if(isset($lookup[$f]) && isset($lookup[$f][ACTIVE_DBTYPE])) return $lookup[$f][ACTIVE_DBTYPE]; - + logger('Unable to abstract DB function "'. $f . '" for dbtype ' . ACTIVE_DBTYPE, LOGGER_DEBUG); return $f; } - diff --git a/include/session.php b/include/session.php index 0e2adb77d..31b3f0614 100644 --- a/include/session.php +++ b/include/session.php @@ -1,21 +1,29 @@ -query_string); $stripped = str_replace('q=','',$stripped); $stripped = trim($stripped,'/'); - $pagenum = $a->pager['page']; + //$pagenum = $a->pager['page']; $url = $a->get_baseurl() . '/' . $stripped; - return replace_macros(get_markup_template('alt_pager.tpl'),array( + return replace_macros(get_markup_template('alt_pager.tpl'), array( '$has_less' => (($a->pager['page'] > 1) ? true : false), '$has_more' => (($i > 0 && $i >= $a->pager['itemspage']) ? true : false), '$less' => $less, @@ -600,6 +596,7 @@ function activity_match($haystack,$needle) { function get_tags($s) { $ret = array(); + $match = array(); // ignore anything in a code block @@ -1061,7 +1058,6 @@ function list_smilies() { * */ function smilies($s, $sample = false) { - $a = get_app(); if(intval(get_config('system','no_smilies')) || (local_channel() && intval(get_pconfig(local_channel(),'system','no_smilies')))) @@ -2111,6 +2107,7 @@ function handle_tag($a, &$body, &$access_tag, &$str_tags, $profile_uid, $tag) { $replaced = false; $r = null; + $match = array(); $termtype = ((strpos($tag,'#') === 0) ? TERM_HASHTAG : TERM_UNKNOWN); $termtype = ((strpos($tag,'@') === 0) ? TERM_MENTION : $termtype); @@ -2354,7 +2351,7 @@ function handle_tag($a, &$body, &$access_tag, &$str_tags, $profile_uid, $tag) { function linkify_tags($a, &$body, $uid) { $str_tags = ''; $tagged = array(); - $result = array(); + $results = array(); $tags = get_tags($body); @@ -2375,18 +2372,23 @@ function linkify_tags($a, &$body, $uid) { if($fullnametagged) continue; + // @FIXME which $profile_uid? It's not set anywhere. $success = handle_tag($a, $body, $access_tag, $str_tags, ($uid) ? $uid : $profile_uid , $tag); $results[] = array('success' => $success, 'access_tag' => $access_tag); if($success['replaced']) $tagged[] = $tag; } } + return $results; } /** - * @brief returns icon name for use with e.g. font-awesome based on mime-type + * @brief returns icon name for use with e.g. font-awesome based on mime-type. + * + * These are the the font-awesome names of version 3.2.1. The newer font-awesome + * 4 has different names. * - * @param string $type + * @param string $type mime type * @return string */ function getIconFromType($type) { @@ -2439,10 +2441,10 @@ function getIconFromType($type) { * @brief Returns a human readable formatted string for filesizes. * * @param int $size filesize in bytes - * @return string + * @return string human readable formatted filesize */ function userReadableSize($size) { - $ret = ""; + $ret = ''; if (is_numeric($size)) { $incr = 0; $k = 1024; @@ -2451,7 +2453,8 @@ function userReadableSize($size) { $incr++; $size = round($size / $k, 2); } - $ret = $size . " " . $unit[$incr]; + $ret = $size . ' ' . $unit[$incr]; } + return $ret; } -- cgit v1.2.3 From f458c29a2bd3cadfc17324e35a9367c61d9bb19f Mon Sep 17 00:00:00 2001 From: friendica Date: Fri, 13 Mar 2015 14:48:44 -0700 Subject: invoke tgroup_check() on diaspora posts/comments in case the recipient is a forum with channel_w_stream permissions restricted. --- include/diaspora.php | 53 +++++++++++++++++++++++++++++++++------------------- 1 file changed, 34 insertions(+), 19 deletions(-) (limited to 'include') diff --git a/include/diaspora.php b/include/diaspora.php index da55b8fb6..e3bfc2806 100755 --- a/include/diaspora.php +++ b/include/diaspora.php @@ -805,11 +805,6 @@ function diaspora_post($importer,$xml,$msg) { } - if((! $importer['system']) && (! perm_is_allowed($importer['channel_id'],$contact['xchan_hash'],'send_stream'))) { - logger('diaspora_post: Ignoring this author.'); - return 202; - } - $search_guid = ((strlen($guid) == 64) ? $guid . '%' : $guid); $r = q("SELECT id FROM item WHERE uid = %d AND mid like '%s' LIMIT 1", @@ -889,6 +884,15 @@ function diaspora_post($importer,$xml,$msg) { $datarray['item_flags'] = ITEM_THREAD_TOP; $datarray['item_unseen'] = 1; + + $tgroup = tgroup_check($importer['channel_id'],$datarray); + + if((! $importer['system']) && (! perm_is_allowed($importer['channel_id'],$contact['xchan_hash'],'send_stream')) && (! $tgroup)) { + logger('diaspora_post: Ignoring this author.'); + return 202; + } + + $result = item_store($datarray); return; @@ -955,11 +959,6 @@ function diaspora_reshare($importer,$xml,$msg) { if(! $contact) return; - if((! $importer['system']) && (! perm_is_allowed($importer['channel_id'],$contact['xchan_hash'],'send_stream'))) { - logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true)); - return 202; - } - $search_guid = ((strlen($guid) == 64) ? $guid . '%' : $guid); $r = q("SELECT id FROM item WHERE uid = %d AND mid like '%s' LIMIT 1", intval($importer['channel_id']), @@ -1072,6 +1071,15 @@ function diaspora_reshare($importer,$xml,$msg) { $datarray['app'] = 'Diaspora'; + + $tgroup = tgroup_check($importer['channel_id'],$datarray); + + if((! $importer['system']) && (! perm_is_allowed($importer['channel_id'],$contact['xchan_hash'],'send_stream')) && (! $tgroup)) { + logger('diaspora_post: Ignoring this author.'); + return 202; + } + + $result = item_store($datarray); return; @@ -1229,15 +1237,6 @@ function diaspora_comment($importer,$xml,$msg) { if(intval($parent_item['item_private'])) $pubcomment = 0; - // So basically if something arrives at the sys channel it's by definition public and we allow it. - // If $pubcomment and the parent was public, we allow it. - // In all other cases, honour the permissions for this Diaspora connection - - if((! $importer['system']) && (! $pubcomment) && (! perm_is_allowed($importer['channel_id'],$contact['xchan_hash'],'post_comments'))) { - logger('diaspora_comment: Ignoring this author.'); - return 202; - } - $search_guid = $guid; if(strlen($guid) == 64) $search_guid = $guid . '%'; @@ -1382,6 +1381,22 @@ function diaspora_comment($importer,$xml,$msg) { $datarray['diaspora_meta'] = json_encode(crypto_encapsulate(json_encode($x),$key)); } + + + // So basically if something arrives at the sys channel it's by definition public and we allow it. + // If $pubcomment and the parent was public, we allow it. + // In all other cases, honour the permissions for this Diaspora connection + + $tgroup = tgroup_check($importer['channel_id'],$datarray); + + if((! $importer['system']) && (! $pubcomment) && (! perm_is_allowed($importer['channel_id'],$contact['xchan_hash'],'post_comments')) && (! $tgroup)) { + logger('diaspora_comment: Ignoring this author.'); + return 202; + } + + + + $result = item_store($datarray); if($result && $result['success']) -- cgit v1.2.3 From 80816a71955b8959bd9f1e24ee39d52aac3158eb Mon Sep 17 00:00:00 2001 From: Klaus Weidenbach Date: Sat, 14 Mar 2015 00:10:06 +0100 Subject: Some documentation, fix chatroom service class lookup. Add some Doxygen documentation and fixing a service class lookup for chatroom_create(). --- include/account.php | 51 ++++++++++++++++++++++++++++++++++++++------------- include/chat.php | 47 +++++++++++++++++++++++++++++++---------------- 2 files changed, 69 insertions(+), 29 deletions(-) (limited to 'include') diff --git a/include/account.php b/include/account.php index 19c13d5bd..5793c2724 100644 --- a/include/account.php +++ b/include/account.php @@ -559,7 +559,7 @@ function downgrade_accounts() { // or what the subscriber is not allowed to do. -function service_class_allows($uid,$property,$usage = false) { +function service_class_allows($uid, $property, $usage = false) { $a = get_app(); if($uid == local_channel()) { $service_class = $a->account['account_service_class']; @@ -586,13 +586,26 @@ function service_class_allows($uid,$property,$usage = false) { else { if(! array_key_exists($property,$arr)) return true; + return (((intval($usage)) < intval($arr[$property])) ? true : false); } } -// like service_class_allows but queries by account rather than channel -function account_service_class_allows($aid,$property,$usage = false) { - $a = get_app(); +/** + * @brief Checks service class restrictions by account_id. + * + * Like service_class_allows() but queries by account rather than channel. + * + * @see service_class_allows() + * + * @param int $aid account_id + * @param string $property + * @param int|boolean $usage, default false + * @return boolean + * + * @todo Can't we use here internally account_service_class_fetch() to reduce duplicate code? + */ +function account_service_class_allows($aid, $property, $usage = false) { $r = q("select account_service_class as service_class from account where account_id = %d limit 1", intval($aid) ); @@ -603,21 +616,33 @@ function account_service_class_allows($aid,$property,$usage = false) { if(! x($service_class)) return true; // everything is allowed - $arr = get_config('service_class',$service_class); + $arr = get_config('service_class', $service_class); if(! is_array($arr) || (! count($arr))) return true; if($usage === false) return ((x($arr[$property])) ? (bool) $arr[$property] : true); else { - if(! array_key_exists($property,$arr)) + if(! array_key_exists($property, $arr)) return true; + return (((intval($usage)) < intval($arr[$property])) ? true : false); } } - -function service_class_fetch($uid,$property) { +/** + * @brief Fetches a service class for a channel_id and property. + * + * This method not just checks if a service class is allowed like service_class_allows(), + * but also returns the service class value. + * If no service class is available it returns false and everything should be + * allowed. + * + * @param int $uid channel_id + * @param string $property + * @return boolean|int + */ +function service_class_fetch($uid, $property) { $a = get_app(); if($uid == local_channel()) { $service_class = $a->account['account_service_class']; @@ -635,17 +660,17 @@ function service_class_fetch($uid,$property) { if(! x($service_class)) return false; // everything is allowed - $arr = get_config('service_class',$service_class); + $arr = get_config('service_class', $service_class); if(! is_array($arr) || (! count($arr))) return false; - return((array_key_exists($property,$arr)) ? $arr[$property] : false); + return((array_key_exists($property, $arr)) ? $arr[$property] : false); } // like service_class_fetch but queries by account rather than channel -function account_service_class_fetch($aid,$property) { +function account_service_class_fetch($aid, $property) { $r = q("select account_service_class as service_class from account where account_id = %d limit 1", intval($aid) @@ -657,12 +682,12 @@ function account_service_class_fetch($aid,$property) { if(! x($service_class)) return false; // everything is allowed - $arr = get_config('service_class',$service_class); + $arr = get_config('service_class', $service_class); if(! is_array($arr) || (! count($arr))) return false; - return((array_key_exists($property,$arr)) ? $arr[$property] : false); + return((array_key_exists($property, $arr)) ? $arr[$property] : false); } diff --git a/include/chat.php b/include/chat.php index b19d495bb..05bb02bb9 100644 --- a/include/chat.php +++ b/include/chat.php @@ -1,7 +1,20 @@ - false); @@ -24,14 +37,14 @@ function chatroom_create($channel,$arr) { intval($channel['channel_account_id']) ); if($r) - $limit = service_class_fetch($channel_id,'chatrooms'); + $limit = service_class_fetch($channel['channel_id'], 'chatrooms'); - if(($r) && ($limit !== false) && ($r[0]['total'] >= $limit)) { - $ret['message'] = upgrade_message(); - return $ret; - } + if(($r) && ($limit !== false) && ($r[0]['total'] >= $limit)) { + $ret['message'] = upgrade_message(); + return $ret; + } - if(! array_key_exists('expire',$arr)) + if(! array_key_exists('expire', $arr)) $arr['expire'] = 120; // minutes, e.g. 2 hours $created = datetime_convert(); @@ -60,6 +73,7 @@ function chatroom_create($channel,$arr) { function chatroom_destroy($channel,$arr) { $ret = array('success' => false); + if(intval($arr['cr_id'])) $sql_extra = " and cr_id = " . intval($arr['cr_id']) . " "; elseif(trim($arr['cr_name'])) @@ -72,7 +86,7 @@ function chatroom_destroy($channel,$arr) { $r = q("select * from chatroom where cr_uid = %d $sql_extra limit 1", intval($channel['channel_id']) ); - if(! $r) { + if(! $r) { $ret['message'] = t('Invalid room specifier.'); return $ret; } @@ -88,12 +102,13 @@ function chatroom_destroy($channel,$arr) { intval($r[0]['cr_id']) ); } + $ret['success'] = true; return $ret; } -function chatroom_enter($observer_xchan,$room_id,$status,$client) { +function chatroom_enter($observer_xchan, $room_id, $status, $client) { if(! $room_id || ! $observer_xchan) return; @@ -117,7 +132,7 @@ function chatroom_enter($observer_xchan,$room_id,$status,$client) { return false; } - $limit = service_class_fetch($r[0]['cr_uid'],'chatters_inroom'); + $limit = service_class_fetch($r[0]['cr_uid'], 'chatters_inroom'); if($limit !== false) { $y = q("select count(*) as total from chatpresence where cp_room = %d", intval($room_id) @@ -157,12 +172,12 @@ function chatroom_enter($observer_xchan,$room_id,$status,$client) { dbesc($status), dbesc($client) ); - + return $r; } -function chatroom_leave($observer_xchan,$room_id,$client) { +function chatroom_leave($observer_xchan, $room_id, $client) { if(! $room_id || ! $observer_xchan) return; @@ -208,7 +223,7 @@ function chatroom_list_count($uid) { * It is the caller's responsibility to enter the room. */ -function chat_message($uid,$room_id,$xchan,$text) { +function chat_message($uid, $room_id, $xchan, $text) { $ret = array('success' => false); @@ -230,14 +245,14 @@ function chat_message($uid,$room_id,$xchan,$text) { 'chat_text' => $text ); - call_hooks('chat_message',$arr); + call_hooks('chat_message', $arr); $x = q("insert into chat ( chat_room, chat_xchan, created, chat_text ) values( %d, '%s', '%s', '%s' )", intval($room_id), dbesc($xchan), dbesc(datetime_convert()), - dbesc($arr['chat_text']) + dbesc($arr['chat_text']) ); $ret['success'] = true; -- cgit v1.2.3 From b76cdf82d298c92bdf5a59b6bf6b55da504a46ea Mon Sep 17 00:00:00 2001 From: friendica Date: Fri, 13 Mar 2015 19:24:17 -0700 Subject: create terms for Diaspora mention tags - which in Diaspora are handled differently than other tag links and have to be done separately; they aren't processed by linkify_tags which handles all of our other tag processing. Also move the abook_channel clause in mod_network to the join statement. This works fine in mysql and achievies the desired result. I hope postgres can handle an expression as a join clause. --- include/diaspora.php | 100 +++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 97 insertions(+), 3 deletions(-) (limited to 'include') diff --git a/include/diaspora.php b/include/diaspora.php index e3bfc2806..1e0e48a86 100755 --- a/include/diaspora.php +++ b/include/diaspora.php @@ -845,8 +845,9 @@ function diaspora_post($importer,$xml,$msg) { // Look for tags and linkify them $results = linkify_tags(get_app(), $body, $importer['channel_id']); + $datarray['term'] = array(); + if($results) { - $datarray['term'] = array(); foreach($results as $result) { $success = $result['success']; if($success['replaced']) { @@ -861,6 +862,37 @@ function diaspora_post($importer,$xml,$msg) { } } + $cnt = preg_match_all('/@\[url=(.*?)\](.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER); + if($cnt) { + foreach($matches as $mtch) { + $datarray['term'][] = array( + 'uid' => $importer['channel_id'], + 'type' => TERM_MENTION, + 'otype' => TERM_OBJ_POST, + 'term' => $mtch[2], + 'url' => $mtch[1] + ); + } + } + + $cnt = preg_match_all('/@\[zrl=(.*?)\](.*?)\[\/zrl\]/ism',$body,$matches,PREG_SET_ORDER); + if($cnt) { + foreach($matches as $mtch) { + // don't include plustags in the term + $term = ((substr($mtch[2],-1,1) === '+') ? substr($mtch[2],0,-1) : $mtch[2]); + $datarray['term'][] = array( + 'uid' => $importer['channel_id'], + 'type' => TERM_MENTION, + 'otype' => TERM_OBJ_POST, + 'term' => $term, + 'url' => $mtch[1] + ); + } + } + + + + $plink = service_plink($contact,$guid); @@ -1032,8 +1064,9 @@ function diaspora_reshare($importer,$xml,$msg) { // Look for tags and linkify them $results = linkify_tags(get_app(), $body, $importer['channel_id']); + $datarray['term'] = array(); + if($results) { - $datarray['term'] = array(); foreach($results as $result) { $success = $result['success']; if($success['replaced']) { @@ -1048,6 +1081,38 @@ function diaspora_reshare($importer,$xml,$msg) { } } + $cnt = preg_match_all('/@\[url=(.*?)\](.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER); + if($cnt) { + foreach($matches as $mtch) { + $datarray['term'][] = array( + 'uid' => $importer['channel_id'], + 'type' => TERM_MENTION, + 'otype' => TERM_OBJ_POST, + 'term' => $mtch[2], + 'url' => $mtch[1] + ); + } + } + + $cnt = preg_match_all('/@\[zrl=(.*?)\](.*?)\[\/zrl\]/ism',$body,$matches,PREG_SET_ORDER); + if($cnt) { + foreach($matches as $mtch) { + // don't include plustags in the term + $term = ((substr($mtch[2],-1,1) === '+') ? substr($mtch[2],0,-1) : $mtch[2]); + $datarray['term'][] = array( + 'uid' => $importer['channel_id'], + 'type' => TERM_MENTION, + 'otype' => TERM_OBJ_POST, + 'term' => $term, + 'url' => $mtch[1] + ); + } + } + + + + + $newbody = "[share author='" . urlencode($orig_author_name) . "' profile='" . $orig_author_link . "' avatar='" . $orig_author_photo @@ -1334,8 +1399,9 @@ function diaspora_comment($importer,$xml,$msg) { // Look for tags and linkify them $results = linkify_tags(get_app(), $body, $importer['channel_id']); + $datarray['term'] = array(); + if($results) { - $datarray['term'] = array(); foreach($results as $result) { $success = $result['success']; if($success['replaced']) { @@ -1350,6 +1416,34 @@ function diaspora_comment($importer,$xml,$msg) { } } + $cnt = preg_match_all('/@\[url=(.*?)\](.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER); + if($cnt) { + foreach($matches as $mtch) { + $datarray['term'][] = array( + 'uid' => $importer['channel_id'], + 'type' => TERM_MENTION, + 'otype' => TERM_OBJ_POST, + 'term' => $mtch[2], + 'url' => $mtch[1] + ); + } + } + + $cnt = preg_match_all('/@\[zrl=(.*?)\](.*?)\[\/zrl\]/ism',$body,$matches,PREG_SET_ORDER); + if($cnt) { + foreach($matches as $mtch) { + // don't include plustags in the term + $term = ((substr($mtch[2],-1,1) === '+') ? substr($mtch[2],0,-1) : $mtch[2]); + $datarray['term'][] = array( + 'uid' => $importer['channel_id'], + 'type' => TERM_MENTION, + 'otype' => TERM_OBJ_POST, + 'term' => $term, + 'url' => $mtch[1] + ); + } + } + $datarray['uid'] = $importer['channel_id']; $datarray['verb'] = ACTIVITY_POST; $datarray['mid'] = $guid; -- cgit v1.2.3 From 864116805b7adf8e82be582c2df8524c44a829fd Mon Sep 17 00:00:00 2001 From: Klaus Weidenbach Date: Mon, 16 Mar 2015 00:20:14 +0100 Subject: Documentation and remove duplicate code. Add a bit Doxygen documentation and remove some duplicate code from account.php. --- include/account.php | 151 +++++++++++++++++++++++++++------------------------- 1 file changed, 79 insertions(+), 72 deletions(-) (limited to 'include') diff --git a/include/account.php b/include/account.php index 5793c2724..caac0b178 100644 --- a/include/account.php +++ b/include/account.php @@ -523,9 +523,7 @@ function downgrade_accounts() { $basic = get_config('system','default_service_class'); - foreach($r as $rr) { - if(($basic) && ($rr['account_service_class']) && ($rr['account_service_class'] != $basic)) { $x = q("UPDATE account set account_service_class = '%s', account_expires = '%s' where account_id = %d", @@ -550,97 +548,96 @@ function downgrade_accounts() { } - -// check service_class restrictions. If there are no service_classes defined, everything is allowed. -// if $usage is supplied, we check against a maximum count and return true if the current usage is -// less than the subscriber plan allows. Otherwise we return boolean true or false if the property -// is allowed (or not) in this subscriber plan. An unset property for this service plan means -// the property is allowed, so it is only necessary to provide negative properties for each plan, -// or what the subscriber is not allowed to do. - - +/** + * @brief Check service_class restrictions. + * + * If there are no service_classes defined, everything is allowed. + * If $usage is supplied, we check against a maximum count and return true if + * the current usage is less than the subscriber plan allows. Otherwise we + * return boolean true or false if the property is allowed (or not) in this + * subscriber plan. An unset property for this service plan means the property + * is allowed, so it is only necessary to provide negative properties for each + * plan, or what the subscriber is not allowed to do. + * + * Like account_service_class_allows() but queries directly by account rather + * than channel. Service classes are set for accounts, so we look up the + * account for the channel and fetch the service class restrictions of the + * account. + * + * @see account_service_class_allows() if you have a channel_id already + * @see service_class_fetch() + * + * @param int $uid The channel_id to check + * @param string $property The service class property to check for + * @param string|boolean $usage (optional) The value to check against + * @return boolean + */ function service_class_allows($uid, $property, $usage = false) { - $a = get_app(); - if($uid == local_channel()) { - $service_class = $a->account['account_service_class']; - } - else { - $r = q("select account_service_class as service_class - from channel c, account a - where c.channel_account_id=a.account_id and c.channel_id= %d limit 1", - intval($uid) - ); - if($r !== false and count($r)) { - $service_class = $r[0]['service_class']; - } - } - if(! x($service_class)) - return true; // everything is allowed - - $arr = get_config('service_class',$service_class); - if(! is_array($arr) || (! count($arr))) - return true; + $limit = service_class_fetch($uid, $property); - if($usage === false) - return ((x($arr[$property])) ? (bool) $arr[$property] : true); - else { - if(! array_key_exists($property,$arr)) - return true; + if($limit === false) + return true; // No service class set => everything is allowed - return (((intval($usage)) < intval($arr[$property])) ? true : false); + if($usage === false) { + // We use negative values for not allowed properties in a subscriber plan + return ((x($limit)) ? (bool) $limit : true); + } else { + return (((intval($usage)) < intval($limit)) ? true : false); } } /** - * @brief Checks service class restrictions by account_id. + * @brief Check service class restrictions by account. * - * Like service_class_allows() but queries by account rather than channel. + * If there are no service_classes defined, everything is allowed. + * If $usage is supplied, we check against a maximum count and return true if + * the current usage is less than the subscriber plan allows. Otherwise we + * return boolean true or false if the property is allowed (or not) in this + * subscriber plan. An unset property for this service plan means the property + * is allowed, so it is only necessary to provide negative properties for each + * plan, or what the subscriber is not allowed to do. * - * @see service_class_allows() + * Like service_class_allows() but queries directly by account rather than channel. * - * @param int $aid account_id - * @param string $property - * @param int|boolean $usage, default false - * @return boolean + * @see service_class_allows() if you have a channel_id instead of an account_id + * @see account_service_class_fetch() * - * @todo Can't we use here internally account_service_class_fetch() to reduce duplicate code? + * @param int $aid The account_id to check + * @param string $property The service class property to check for + * @param int|boolean $usage, (optional) The value to check against + * @return boolean */ function account_service_class_allows($aid, $property, $usage = false) { - $r = q("select account_service_class as service_class from account where account_id = %d limit 1", - intval($aid) - ); - if($r !== false and count($r)) { - $service_class = $r[0]['service_class']; - } - if(! x($service_class)) - return true; // everything is allowed + $limit = account_service_class_fetch($aid, $property); - $arr = get_config('service_class', $service_class); - if(! is_array($arr) || (! count($arr))) - return true; + if($limit === false) + return true; // No service class is set => everything is allowed - if($usage === false) - return ((x($arr[$property])) ? (bool) $arr[$property] : true); - else { - if(! array_key_exists($property, $arr)) - return true; - - return (((intval($usage)) < intval($arr[$property])) ? true : false); + if($usage === false) { + // We use negative values for not allowed properties in a subscriber plan + return ((x($limit)) ? (bool) $limit : true); + } else { + return (((intval($usage)) < intval($limit)) ? true : false); } } /** - * @brief Fetches a service class for a channel_id and property. + * @brief Queries a service class value for a channel and property. + * + * Service classes are set for accounts, so look up the account for this channel + * and fetch the service classe of the account. * - * This method not just checks if a service class is allowed like service_class_allows(), - * but also returns the service class value. * If no service class is available it returns false and everything should be * allowed. * - * @param int $uid channel_id - * @param string $property + * @see account_service_class_fetch() + * + * @param int $uid The channel_id to query + * @param string $property The service property name to check for * @return boolean|int + * + * @todo Should we merge this with account_service_class_fetch()? */ function service_class_fetch($uid, $property) { $a = get_app(); @@ -668,8 +665,18 @@ function service_class_fetch($uid, $property) { return((array_key_exists($property, $arr)) ? $arr[$property] : false); } -// like service_class_fetch but queries by account rather than channel - +/** + * @brief Queries a service class value for an account and property. + * + * Like service_class_fetch() but queries by account rather than channel. + * + * @see service_class_fetch() if you have channel_id. + * @see account_service_class_allows() + * + * @param int $aid The account_id to query + * @param string $property The service property name to check for + * @return boolean|int + */ function account_service_class_fetch($aid, $property) { $r = q("select account_service_class as service_class from account where account_id = %d limit 1", @@ -692,7 +699,7 @@ function account_service_class_fetch($aid, $property) { function upgrade_link($bbcode = false) { - $l = get_config('service_class','upgrade_link'); + $l = get_config('service_class', 'upgrade_link'); if(! $l) return ''; if($bbcode) @@ -710,4 +717,4 @@ function upgrade_message($bbcode = false) { function upgrade_bool_message($bbcode = false) { $x = upgrade_link($bbcode); return t('This action is not available under your subscription plan.') . (($x) ? ' ' . $x : '') ; -} +} \ No newline at end of file -- cgit v1.2.3 From 52374bcd6e5726828219bed7a8c04f5456b167d5 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 16 Mar 2015 15:33:08 -0700 Subject: phase one of the great file storage unification - use one button for uploads of any type (image or attachment). We'll sort out which one it is and deal with it appropriately. --- include/conversation.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/conversation.php b/include/conversation.php index 0e35202fa..a85d582ce 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -1172,7 +1172,7 @@ function status_editor($a, $x, $popup = false) { '$pagetitle' => (x($x,'pagetitle') ? $x['pagetitle'] : ''), '$id_select' => $id_select, '$id_seltext' => t('Post as'), - '$writephoto' => perm_is_allowed($x['profile_uid'], get_observer_hash(), 'post_photos'), + '$writefiles' => (perm_is_allowed($x['profile_uid'], get_observer_hash(), 'post_photos') || perm_is_allowed($x['profile_uid'], get_observer_hash(), 'write_storage')), '$bold' => t('Bold'), '$italic' => t('Italic'), '$underline' => t('Underline'), -- cgit v1.2.3 From f660b7523bfdab782970f689d01ee1e90d1dff38 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 16 Mar 2015 15:35:46 -0700 Subject: also update the api to match --- include/api.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/api.php b/include/api.php index d0c4ed0aa..8c0e32ecc 100644 --- a/include/api.php +++ b/include/api.php @@ -663,8 +663,8 @@ require_once('include/items.php'); $a->argv[1] = $user_info['screen_name']; $_REQUEST['silent']='1'; //tell wall_upload function to return img info instead of echo - require_once('mod/wall_upload.php'); - $posted = wall_upload_post($a); + require_once('mod/wall_attach.php'); + $posted = wall_attach_post($a); //now that we have the img url in bbcode we can add it to the status and insert the wall item. $_REQUEST['body']=$txt."\n\n".$posted; -- cgit v1.2.3 From 178b768e3ce43f3c75abec1540fcdc909c8c2197 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 16 Mar 2015 17:08:50 -0700 Subject: openid cleanup --- include/text.php | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) (limited to 'include') diff --git a/include/text.php b/include/text.php index 4c64c71bb..7468a3622 100644 --- a/include/text.php +++ b/include/text.php @@ -736,7 +736,7 @@ function contact_block() { if((! is_array($a->profile)) || ($a->profile['hide_friends'])) return $o; - $r = q("SELECT COUNT(abook_id) AS total FROM abook left join xchan on abook_xchan = xchan_hash WHERE abook_channel = %d and not ( abook_flags & %d )>0 and not (xchan_flags & %d)>0", + $r = q("SELECT COUNT(abook_id) AS total FROM abook left join xchan on abook_xchan = xchan_hash WHERE abook_channel = %d and ( abook_flags & %d ) = 0 and ( xchan_flags & %d ) = 0", intval($a->profile['uid']), intval($abook_flags), intval($xchan_flags) @@ -748,12 +748,10 @@ function contact_block() { $contacts = t('No connections'); $micropro = null; } else { - if(ACTIVE_DBTYPE == DBTYPE_POSTGRES) { - $randfunc = 'RANDOM()'; - } else { - $randfunc = 'RAND()'; - } - $r = q("SELECT abook.*, xchan.* FROM abook left join xchan on abook.abook_xchan = xchan.xchan_hash WHERE abook_channel = %d AND not ( abook_flags & %d)>0 and not (xchan_flags & %d )>0 ORDER BY $randfunc LIMIT %d", + + $randfunc = db_getfunc('RAND'); + + $r = q("SELECT abook.*, xchan.* FROM abook left join xchan on abook.abook_xchan = xchan.xchan_hash WHERE abook_channel = %d AND ( abook_flags & %d ) = 0 and ( xchan_flags & %d ) = 0 ORDER BY $randfunc LIMIT %d", intval($a->profile['uid']), intval($abook_flags|ABOOK_FLAG_ARCHIVED), intval($xchan_flags), -- cgit v1.2.3 From 7c194c37b891f122740de52d154db0af612e0074 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 16 Mar 2015 20:08:05 -0700 Subject: started to add the ability to geotag photos (default will be disabled) but my phone isn't outputting the GPS tags even after being explicitly enabled so I'll have to wait until I've got a device that I can reliably test against. --- include/photo/photo_driver.php | 11 +++++++++-- include/photos.php | 4 +++- 2 files changed, 12 insertions(+), 3 deletions(-) (limited to 'include') diff --git a/include/photo/photo_driver.php b/include/photo/photo_driver.php index e63125671..6f508bf72 100644 --- a/include/photo/photo_driver.php +++ b/include/photo/photo_driver.php @@ -241,9 +241,9 @@ abstract class photo_driver { if((! function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) return; - $exif = @exif_read_data($filename); + $exif = @exif_read_data($filename,null,true); if($exif) { - $ort = $exif['Orientation']; + $ort = $exif['IFD0']['Orientation']; switch($ort) { @@ -280,7 +280,14 @@ abstract class photo_driver { $this->rotate(90); break; } + + // logger('exif: ' . print_r($exif,true)); + return $exif; + } + + return false; + } diff --git a/include/photos.php b/include/photos.php index c2f5ed4ba..4b7809fc1 100644 --- a/include/photos.php +++ b/include/photos.php @@ -125,7 +125,9 @@ function photo_upload($channel, $observer, $args) { return $ret; } - $ph->orient($src); + $exif = $ph->orient($src); + + @unlink($src); $max_length = get_config('system','max_image_length'); -- cgit v1.2.3 From bc22df9057198018f9cc490d0e3e013692f52b90 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 16 Mar 2015 22:06:03 -0700 Subject: display a map for photos if allowed. Note: there is a bug in that if the map div starts with display:none one needs to reload the frame or zoom in or they end up at minimum resolution. Still trying to sort this out. --- include/photos.php | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) (limited to 'include') diff --git a/include/photos.php b/include/photos.php index 4b7809fc1..4785e47c4 100644 --- a/include/photos.php +++ b/include/photos.php @@ -205,6 +205,17 @@ function photo_upload($channel, $observer, $args) { // Create item container + $lat = $lon = null; + + if($exif && $exif['GPS']) { + if(get_pconfig($channel_id,'system','allow_photo_location')) { + $lat = getGps($exif['GPS']['GPSLatitude'], $exif['GPSLatitudeRef']); + $lon = getGps($exif['GPS']['GPSLongitude'], $exif['GPSLongitudeRef']); + } + } + + + $item_flags = ITEM_WALL|ITEM_ORIGIN|ITEM_THREAD_TOP; $item_restrict = (($visible) ? ITEM_VISIBLE : ITEM_HIDDEN); $title = ''; @@ -212,6 +223,9 @@ function photo_upload($channel, $observer, $args) { $arr = array(); + if($lat && $lon) + $arr['coord'] = $lat . ' ' . $lon; + $arr['aid'] = $account_id; $arr['uid'] = $channel_id; $arr['mid'] = $mid; @@ -481,3 +495,30 @@ function photos_create_item($channel, $creator_hash, $photo, $visible = false) { return $item_id; } + + +function getGps($exifCoord, $hemi) { + + $degrees = count($exifCoord) > 0 ? gps2Num($exifCoord[0]) : 0; + $minutes = count($exifCoord) > 1 ? gps2Num($exifCoord[1]) : 0; + $seconds = count($exifCoord) > 2 ? gps2Num($exifCoord[2]) : 0; + + $flip = ($hemi == 'W' or $hemi == 'S') ? -1 : 1; + + return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600))); + +} + +function gps2Num($coordPart) { + + $parts = explode('/', $coordPart); + + if (count($parts) <= 0) + return 0; + + if (count($parts) == 1) + return $parts[0]; + + return floatval($parts[0]) / floatval($parts[1]); +} + -- cgit v1.2.3 From 7af012b1f95fb329c9bf127a60e0a383d853e37d Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 17 Mar 2015 00:13:47 -0700 Subject: The random bad signatures are because something somewhere is trimming the body text. It could be any one of hundreds of functions that touch the message body. We really want to trim the body text, so I'm putting back all the trim statements - in mod/item and item_store and item_store_update. The last fix for random bad sigs noted that one of the trims wasn't there, so the others were removed. The correct fix is for all the trims to be there. We will probably have a few (quite a few) bad sigs during the transition back to trimmed text but this should nail it for anybody on recent code and with new content. --- include/items.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/items.php b/include/items.php index 8f16d23c1..2518c0d4f 100755 --- a/include/items.php +++ b/include/items.php @@ -1945,7 +1945,7 @@ function item_store($arr,$allow_exec = false) { $arr['title'] = ((array_key_exists('title',$arr) && strlen($arr['title'])) ? trim($arr['title']) : ''); - $arr['body'] = ((array_key_exists('body',$arr) && strlen($arr['body'])) ? $arr['body'] : ''); + $arr['body'] = ((array_key_exists('body',$arr) && strlen($arr['body'])) ? trim($arr['body']) : ''); $arr['diaspora_meta'] = ((x($arr,'diaspora_meta')) ? $arr['diaspora_meta'] : ''); $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : ''); @@ -2460,7 +2460,7 @@ function item_store_update($arr,$allow_exec = false) { $arr['item_private'] = ((array_key_exists('item_private',$arr)) ? intval($arr['item_private']) : $orig[0]['item_private']); $arr['title'] = ((array_key_exists('title',$arr) && strlen($arr['title'])) ? trim($arr['title']) : ''); - $arr['body'] = ((array_key_exists('body',$arr) && strlen($arr['body'])) ? $arr['body'] : ''); + $arr['body'] = ((array_key_exists('body',$arr) && strlen($arr['body'])) ? trim($arr['body']) : ''); $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : $orig[0]['attach']); $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : $orig[0]['app']); // $arr['item_restrict'] = ((x($arr,'item_restrict')) ? intval($arr['item_restrict']) : $orig[0]['item_restrict'] ); -- cgit v1.2.3 From fab8209ebd4a052f8af5918de8603fd21a4bc7a6 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 17 Mar 2015 00:33:43 -0700 Subject: turn photo location mapping into a feature --- include/features.php | 1 + include/photos.php | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'include') diff --git a/include/features.php b/include/features.php index fc14858a8..08b32fe19 100644 --- a/include/features.php +++ b/include/features.php @@ -44,6 +44,7 @@ function get_features() { array('webpages', t('Web Pages'), t('Provide managed web pages on your channel'),false), array('private_notes', t('Private Notes'), t('Enables a tool to store notes and reminders'),false), array('nav_channel_select', t('Navigation Channel Select'), t('Change channels directly from within the navigation dropdown menu'),false), + array('photo_location', t('Photo Location'), t('Photo metadata is normally stripped. This extracts the location (if present) prior to stripping metadata and links it to a map.'),false), //FIXME - needs a description, but how the hell do we explain this to normals? diff --git a/include/photos.php b/include/photos.php index 4785e47c4..4d3f4c755 100644 --- a/include/photos.php +++ b/include/photos.php @@ -208,7 +208,7 @@ function photo_upload($channel, $observer, $args) { $lat = $lon = null; if($exif && $exif['GPS']) { - if(get_pconfig($channel_id,'system','allow_photo_location')) { + if(feature_enabled($channel_id,'photo_location')) { $lat = getGps($exif['GPS']['GPSLatitude'], $exif['GPSLatitudeRef']); $lon = getGps($exif['GPS']['GPSLongitude'], $exif['GPSLongitudeRef']); } -- cgit v1.2.3 From 6b3afb5eecca2964222e8dc09ddfae86e802c2f4 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 17 Mar 2015 00:53:24 -0700 Subject: get the correct hemisphere for geotagged photos --- include/photos.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/photos.php b/include/photos.php index 4d3f4c755..c4d5a33aa 100644 --- a/include/photos.php +++ b/include/photos.php @@ -209,8 +209,8 @@ function photo_upload($channel, $observer, $args) { if($exif && $exif['GPS']) { if(feature_enabled($channel_id,'photo_location')) { - $lat = getGps($exif['GPS']['GPSLatitude'], $exif['GPSLatitudeRef']); - $lon = getGps($exif['GPS']['GPSLongitude'], $exif['GPSLongitudeRef']); + $lat = getGps($exif['GPS']['GPSLatitude'], $exif['GPS']['GPSLatitudeRef']); + $lon = getGps($exif['GPS']['GPSLongitude'], $exif['GPS']['GPSLongitudeRef']); } } -- cgit v1.2.3 From 5a7e35fbf8e70f04e4253e5cc2a79925cd3385d1 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 18 Mar 2015 17:36:06 -0700 Subject: Change wording on the photo location feature. When photos are merged with DAV storage we won't be stripping metadata by default. --- include/features.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/features.php b/include/features.php index 08b32fe19..3a1752052 100644 --- a/include/features.php +++ b/include/features.php @@ -44,7 +44,7 @@ function get_features() { array('webpages', t('Web Pages'), t('Provide managed web pages on your channel'),false), array('private_notes', t('Private Notes'), t('Enables a tool to store notes and reminders'),false), array('nav_channel_select', t('Navigation Channel Select'), t('Change channels directly from within the navigation dropdown menu'),false), - array('photo_location', t('Photo Location'), t('Photo metadata is normally stripped. This extracts the location (if present) prior to stripping metadata and links it to a map.'),false), + array('photo_location', t('Photo Location'), t('If location data is available on uploaded photos, link this to a map.'),false), //FIXME - needs a description, but how the hell do we explain this to normals? -- cgit v1.2.3 From 63683734a21e90149c464f7e9b03e7aedc29868e Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 18 Mar 2015 19:06:05 -0700 Subject: make the channel item query match recent changes to network item query (and some slightly older changes in display item query), and allow '@' in linkified urls. --- include/bbcode.php | 2 +- include/text.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/bbcode.php b/include/bbcode.php index 32e5d014f..6f7ef8973 100644 --- a/include/bbcode.php +++ b/include/bbcode.php @@ -469,7 +469,7 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { // Perform URL Search - $urlchars = '[a-zA-Z0-9\:\/\-\?\&\;\.\=\@\_\~\#\%\$\!\+\,]'; + $urlchars = '[a-zA-Z0-9\:\/\-\?\&\;\.\=\@\_\~\#\%\$\!\+\,\@]'; if (strpos($Text,'http') !== false) { $Text = preg_replace("/([^\]\='".'"'."\/]|^|\#\^)(https?\:\/\/$urlchars+)/ism", '$1$2', $Text); diff --git a/include/text.php b/include/text.php index 7468a3622..54d8b2ad7 100644 --- a/include/text.php +++ b/include/text.php @@ -869,7 +869,7 @@ function valid_email($x){ function linkify($s,$me = false) { - $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\@\~\#\'\%\$\!\+]*)/", (($me) ? ' $1' : ' $1'), $s); + $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\@\~\#\'\%\$\!\+\,\@]*)/", (($me) ? ' $1' : ' $1'), $s); $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s); return($s); } -- cgit v1.2.3 From 24ebaaf0f70f3452c72c0ac4017bff1144728da8 Mon Sep 17 00:00:00 2001 From: friendica Date: Thu, 19 Mar 2015 15:24:09 -0700 Subject: ratenotif: loop oddity --- include/ratenotif.php | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'include') diff --git a/include/ratenotif.php b/include/ratenotif.php index 8be3b15b7..63fd7c2ee 100644 --- a/include/ratenotif.php +++ b/include/ratenotif.php @@ -94,21 +94,21 @@ function ratenotif_run($argv, $argc){ dbesc($n), dbesc(json_encode($encoded_item)) ); - } - $deliver[] = $hash; - if(count($deliver) >= $deliveries_per_process) { - proc_run('php','include/deliver.php',$deliver); - $deliver = array(); - if($interval) - @time_sleep_until(microtime(true) + (float) $interval); - } + $deliver[] = $hash; + if(count($deliver) >= $deliveries_per_process) { + proc_run('php','include/deliver.php',$deliver); + $deliver = array(); + if($interval) + @time_sleep_until(microtime(true) + (float) $interval); + } + } // catch any stragglers if(count($deliver)) { - proc_run('php','include/deliver.php',$deliver); + proc_run('php','include/deliver.php',$deliver); } } } -- cgit v1.2.3 From b1fd6c53a5f86fd752db9c5394cae8f67492f07e Mon Sep 17 00:00:00 2001 From: friendica Date: Thu, 19 Mar 2015 15:56:30 -0700 Subject: tweaks to directory registrations which don't seem to be happening, also downgrade any directory that claims to be a primary directory for RED_GLOBAL. --- include/poller.php | 4 ++-- include/zot.php | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/poller.php b/include/poller.php index 06311eb39..43cc3f3c0 100644 --- a/include/poller.php +++ b/include/poller.php @@ -166,8 +166,8 @@ function poller_run($argv, $argc){ ); $dirmode = intval(get_config('system','directory_mode')); - if($dirmode == DIRECTORY_MODE_SECONDARY) { - logger('regdir: ' . print_r(z_fetch_url(get_directory_primary() . '/regdir?f=&url=' . z_root() . '&realm=' . get_directory_realm()),true)); + if($dirmode === DIRECTORY_MODE_SECONDARY) { + logger('regdir: ' . print_r(z_fetch_url(get_directory_primary() . '/regdir?f=&url=' . urlencode(z_root()) . '&realm=' . urlencode(get_directory_realm())),true)); } /** diff --git a/include/zot.php b/include/zot.php index 5c12dc4ba..99a787cd9 100644 --- a/include/zot.php +++ b/include/zot.php @@ -2536,6 +2536,9 @@ function import_site($arr,$pubkey) { if($arr['directory_mode'] == 'standalone') $site_directory = DIRECTORY_MODE_STANDALONE; + + + $register_policy = 0; if($arr['register_policy'] == 'closed') $register_policy = REGISTER_CLOSED; @@ -2573,6 +2576,17 @@ function import_site($arr,$pubkey) { $site_location = htmlspecialchars($arr['location'],ENT_COMPAT,'UTF-8',false); $site_realm = htmlspecialchars($arr['realm'],ENT_COMPAT,'UTF-8',false); + // You can have one and only one primary directory per realm. + // Downgrade any others claiming to be primary. As they have + // flubbed up this badly already, don't let them be directory servers at all. + + if(($site_directory === DIRECTORY_MODE_PRIMARY) + && ($site_realm === get_directory_realm()) + && ($arr['url'] != get_directory_primary())) { + $site_directory = DIRECTORY_MODE_NORMAL; + } + + if($exists) { if(($siterecord['site_flags'] != $site_directory) || ($siterecord['site_access'] != $access_policy) -- cgit v1.2.3 From 2010d6a33299dec10a8f85cde0944e5c245f9554 Mon Sep 17 00:00:00 2001 From: friendica Date: Thu, 19 Mar 2015 16:22:08 -0700 Subject: Explicitly force link for 'All Collections' on the network page to gid=0 so it can be used with a default page over-ride for gid. --- include/group.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/group.php b/include/group.php index be19f6efe..70668a355 100644 --- a/include/group.php +++ b/include/group.php @@ -254,7 +254,7 @@ function group_side($every="connections",$each="group",$edit = false, $group_id 'text' => t('All Channels'), 'id' => 0, 'selected' => (($group_id == 0) ? 'group-selected' : ''), - 'href' => $every, + 'href' => $every . (($every === 'network') ? '?f=&gid=0' : ''), ); -- cgit v1.2.3 From 6698d7b03a88533eda8d79581b7e13565d36fa7e Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Fri, 20 Mar 2015 17:37:01 +0100 Subject: possible improvement regarding deletion --- include/attach.php | 71 ++++++++++++++++++++++++++++++++---------------------- 1 file changed, 42 insertions(+), 29 deletions(-) (limited to 'include') diff --git a/include/attach.php b/include/attach.php index 43b56e4f6..8ffb4bb96 100644 --- a/include/attach.php +++ b/include/attach.php @@ -827,7 +827,7 @@ function attach_delete($channel_id, $resource) { intval($channel_id) ); - file_activity($channel_id, $object, $allow_cid='', $allow_gid='', $deny_cid='', $deny_gid='', 'update', $no_activity=false); + file_activity($channel_id, $object, $object['allow_cid'], $object['allow_gid'], $object['deny_cid'], $object['deny_gid'], 'update', $no_activity=false); } @@ -974,10 +974,14 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, if(!$object) return; - //filter out receivers which do not have permission to view filestorage + //turn strings into arrays $arr_allow_cid = expand_acl($allow_cid); + $arr_allow_gid = expand_acl($allow_gid); + $arr_deny_cid = expand_acl($deny_cid); + $arr_deny_gid = expand_acl($deny_gid); + + //filter out receivers which do not have permission to view filestorage $arr_allow_cid = check_list_permissions($channel_id, $arr_allow_cid, 'view_storage'); - $allow_cid = perms2str($arr_allow_cid); $is_dir = (($object['flags'] & ATTACH_FLAG_DIR) ? true : false); @@ -990,15 +994,16 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $folder_hash = $object['folder']; - $r_perms = recursive_activity_recipients($allow_cid, $allow_gid, $deny_cid, $deny_gid, $folder_hash); + $r_perms = recursive_activity_recipients($arr_allow_cid, $arr_allow_gid, $arr_deny_cid, $arr_deny_gid, $folder_hash); - //filter out receivers which do not have permission to view filestorage - $r_perms['allow_cid'] = check_list_permissions($channel_id, $r_perms['allow_cid'], 'view_storage'); + //split up returned perms + $arr_allow_cid = $r_perms['allow_cid']; + $arr_allow_gid = $r_perms['allow_gid']; + $arr_deny_cid = $r_perms['deny_cid']; + $arr_deny_gid = $r_perms['deny_gid']; - $allow_cid = perms2str($r_perms['allow_cid']); - $allow_gid = perms2str($r_perms['allow_gid']); - $deny_cid = perms2str($r_perms['deny_cid']); - $deny_gid = perms2str($r_perms['deny_gid']); + //filter out receivers which do not have permission to view filestorage + $arr_allow_cid = check_list_permissions($channel_id, $arr_allow_cid, 'view_storage'); } @@ -1008,7 +1013,7 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $item_flags = ITEM_WALL|ITEM_ORIGIN; - $private = (($allow_cid || $allow_gid || $deny_cid || $deny_gid) ? 1 : 0); + $private = (($arr_allow_cid[0] || $arr_allow_gid[0] || $arr_deny_cid[0] || $arr_deny_gid[0]) ? 1 : 0); $jsonobject = json_encode($object); @@ -1037,6 +1042,17 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, if($update && $verb == 'post' ) { //send update activity and create a new one + //updates should be sent to everybody with recursive perms and all eventual former allowed members ($object['allow_cid'] etc.). + $o_arr_allow_cid = expand_acl($object['allow_cid']); + $o_arr_allow_gid = expand_acl($object['allow_gid']); + $o_arr_deny_cid = expand_acl($object['deny_cid']); + $o_arr_deny_gid = expand_acl($object['deny_gid']); + //merge arrays and remove duplicates + $arr_allow_cid = array_unique(array_merge($arr_allow_cid, $o_arr_allow_cid)); + $arr_allow_gid = array_unique(array_merge($arr_allow_gid, $o_arr_allow_gid)); + $arr_deny_cid = array_unique(array_merge($arr_deny_cid, $o_arr_deny_cid)); + $arr_deny_gid = array_unique(array_merge($arr_deny_gid, $o_arr_deny_gid)); + $u_mid = item_message_id(); $arr = array(); @@ -1050,11 +1066,10 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $arr['author_xchan'] = $poster['xchan_hash']; $arr['owner_xchan'] = $poster['xchan_hash']; $arr['title'] = ''; - //updates should be visible to everybody -> perms may have changed - $arr['allow_cid'] = ''; - $arr['allow_gid'] = ''; - $arr['deny_cid'] = ''; - $arr['deny_gid'] = ''; + $arr['allow_cid'] = perms2str($arr_allow_cid); + $arr['allow_gid'] = perms2str($arr_allow_gid); + $arr['deny_cid'] = perms2str($arr_deny_cid); + $arr['deny_gid'] = perms2str($arr_deny_gid); $arr['item_restrict'] = ITEM_HIDDEN; $arr['item_private'] = 0; $arr['verb'] = ACTIVITY_UPDATE; @@ -1093,10 +1108,10 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $arr['author_xchan'] = $poster['xchan_hash']; $arr['owner_xchan'] = $poster['xchan_hash']; $arr['title'] = ''; - $arr['allow_cid'] = $allow_cid; - $arr['allow_gid'] = $allow_gid; - $arr['deny_cid'] = $deny_cid; - $arr['deny_gid'] = $deny_gid; + $arr['allow_cid'] = perms2str($arr_allow_cid); + $arr['allow_gid'] = perms2str($arr_allow_gid); + $arr['deny_cid'] = perms2str($arr_deny_cid); + $arr['deny_gid'] = perms2str($arr_deny_gid); $arr['item_restrict'] = ITEM_HIDDEN; $arr['item_private'] = $private; $arr['verb'] = (($update) ? ACTIVITY_UPDATE : ACTIVITY_POST); @@ -1123,7 +1138,7 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, function get_file_activity_object($channel_id, $hash, $cloudpath) { - $x = q("SELECT creator, filename, filetype, filesize, revision, folder, flags, created, edited FROM attach WHERE uid = %d AND hash = '%s' LIMIT 1", + $x = q("SELECT creator, filename, filetype, filesize, revision, folder, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid FROM attach WHERE uid = %d AND hash = '%s' LIMIT 1", intval($channel_id), dbesc($hash) ); @@ -1152,28 +1167,26 @@ function get_file_activity_object($channel_id, $hash, $cloudpath) { 'folder' => $x[0]['folder'], 'flags' => $x[0]['flags'], 'created' => $x[0]['created'], - 'edited' => $x[0]['edited'] + 'edited' => $x[0]['edited'], + 'allow_cid' => $x[0]['allow_cid'], + 'allow_gid' => $x[0]['allow_gid'], + 'deny_cid' => $x[0]['deny_cid'], + 'deny_gid' => $x[0]['deny_gid'] ); return $object; } -function recursive_activity_recipients($allow_cid, $allow_gid, $deny_cid, $deny_gid, $folder_hash) { +function recursive_activity_recipients($arr_allow_cid, $arr_llow_gid, $arr_deny_cid, $arr_deny_gid, $folder_hash) { $poster = get_app()->get_observer(); - $arr_allow_cid = expand_acl($allow_cid); - $arr_allow_gid = expand_acl($allow_gid); - //turn allow_gid into allow_cid's foreach($arr_allow_gid as $gid) { $in_group = in_group($gid); $arr_allow_cid = array_unique(array_merge($arr_allow_cid, $in_group)); } - $arr_deny_cid = expand_acl($deny_cid); - $arr_deny_gid = expand_acl($deny_gid); - $count = 0; while($folder_hash) { $x = q("SELECT allow_cid, allow_gid, deny_cid, deny_gid, folder FROM attach WHERE hash = '%s' LIMIT 1", -- cgit v1.2.3 From 264b43db05fe0a9a4ec4402eb43c7ecf501d4fee Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Fri, 20 Mar 2015 17:46:13 +0100 Subject: some cleanup --- include/attach.php | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) (limited to 'include') diff --git a/include/attach.php b/include/attach.php index 8ffb4bb96..7d0b99c05 100644 --- a/include/attach.php +++ b/include/attach.php @@ -1043,15 +1043,10 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, //send update activity and create a new one //updates should be sent to everybody with recursive perms and all eventual former allowed members ($object['allow_cid'] etc.). - $o_arr_allow_cid = expand_acl($object['allow_cid']); - $o_arr_allow_gid = expand_acl($object['allow_gid']); - $o_arr_deny_cid = expand_acl($object['deny_cid']); - $o_arr_deny_gid = expand_acl($object['deny_gid']); - //merge arrays and remove duplicates - $arr_allow_cid = array_unique(array_merge($arr_allow_cid, $o_arr_allow_cid)); - $arr_allow_gid = array_unique(array_merge($arr_allow_gid, $o_arr_allow_gid)); - $arr_deny_cid = array_unique(array_merge($arr_deny_cid, $o_arr_deny_cid)); - $arr_deny_gid = array_unique(array_merge($arr_deny_gid, $o_arr_deny_gid)); + $u_arr_allow_cid = array_unique(array_merge($arr_allow_cid, expand_acl($object['allow_cid']))); + $u_arr_allow_gid = array_unique(array_merge($arr_allow_gid, expand_acl($object['allow_gid']))); + $u_arr_deny_cid = array_unique(array_merge($arr_deny_cid, expand_acl($object['deny_cid']))); + $u_arr_deny_gid = array_unique(array_merge($arr_deny_gid, expand_acl($object['deny_gid']))); $u_mid = item_message_id(); @@ -1066,10 +1061,10 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $arr['author_xchan'] = $poster['xchan_hash']; $arr['owner_xchan'] = $poster['xchan_hash']; $arr['title'] = ''; - $arr['allow_cid'] = perms2str($arr_allow_cid); - $arr['allow_gid'] = perms2str($arr_allow_gid); - $arr['deny_cid'] = perms2str($arr_deny_cid); - $arr['deny_gid'] = perms2str($arr_deny_gid); + $arr['allow_cid'] = perms2str($u_arr_allow_cid); + $arr['allow_gid'] = perms2str($u_arr_allow_gid); + $arr['deny_cid'] = perms2str($u_arr_deny_cid); + $arr['deny_gid'] = perms2str($u_arr_deny_gid); $arr['item_restrict'] = ITEM_HIDDEN; $arr['item_private'] = 0; $arr['verb'] = ACTIVITY_UPDATE; -- cgit v1.2.3 From ead45292e134fa03726912905ca1ca58ccb12fec Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Sat, 21 Mar 2015 00:06:18 +0100 Subject: some tabs title statuseditor restructuring --- include/items.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/items.php b/include/items.php index 2518c0d4f..8e293d761 100755 --- a/include/items.php +++ b/include/items.php @@ -4823,4 +4823,4 @@ function comment_local_origin($item) { if(stripos($item['mid'],get_app()->get_hostname()) && ($item['parent'] != $item['id'])) return true; return false; -} \ No newline at end of file +} -- cgit v1.2.3 From 85dd08427c6067554762854c584eae0ca90fea43 Mon Sep 17 00:00:00 2001 From: friendica Date: Fri, 20 Mar 2015 18:50:45 -0700 Subject: change permission roles for things like channel admin to make them more easily manually settable from the connections edit page. --- include/permissions.php | 54 ++++++++++++++++++++++++------------------------- 1 file changed, 27 insertions(+), 27 deletions(-) (limited to 'include') diff --git a/include/permissions.php b/include/permissions.php index ccbde1a7c..4d7def346 100644 --- a/include/permissions.php +++ b/include/permissions.php @@ -578,18 +578,18 @@ function get_role_perms($role) { $ret['channel_r_profile'] = PERMS_PUBLIC; $ret['channel_r_photos'] = PERMS_PUBLIC; $ret['channel_r_abook'] = PERMS_PUBLIC; - $ret['channel_w_stream'] = 0; + $ret['channel_w_stream'] = PERMS_SPECIFIC; $ret['channel_w_wall'] = PERMS_SPECIFIC; $ret['channel_w_tagwall'] = PERMS_SPECIFIC; $ret['channel_w_comment'] = PERMS_SPECIFIC; $ret['channel_w_mail'] = PERMS_SPECIFIC; - $ret['channel_w_photos'] = 0; + $ret['channel_w_photos'] = PERMS_SPECIFIC; $ret['channel_w_chat'] = PERMS_SPECIFIC; - $ret['channel_a_delegate'] = 0; + $ret['channel_a_delegate'] = PERMS_SPECIFIC; $ret['channel_r_storage'] = PERMS_PUBLIC; - $ret['channel_w_storage'] = 0; + $ret['channel_w_storage'] = PERMS_SPECIFIC; $ret['channel_r_pages'] = PERMS_PUBLIC; - $ret['channel_w_pages'] = 0; + $ret['channel_w_pages'] = PERMS_SPECIFIC; $ret['channel_a_republish'] = PERMS_SPECIFIC; $ret['channel_w_like'] = PERMS_NETWORK; @@ -610,18 +610,18 @@ function get_role_perms($role) { $ret['channel_r_profile'] = PERMS_PUBLIC; $ret['channel_r_photos'] = PERMS_PUBLIC; $ret['channel_r_abook'] = PERMS_PUBLIC; - $ret['channel_w_stream'] = 0; + $ret['channel_w_stream'] = PERMS_SPECIFIC; $ret['channel_w_wall'] = PERMS_SPECIFIC; $ret['channel_w_tagwall'] = PERMS_SPECIFIC; $ret['channel_w_comment'] = PERMS_SPECIFIC; $ret['channel_w_mail'] = PERMS_SPECIFIC; - $ret['channel_w_photos'] = 0; + $ret['channel_w_photos'] = PERMS_SPECIFIC; $ret['channel_w_chat'] = PERMS_SPECIFIC; - $ret['channel_a_delegate'] = 0; + $ret['channel_a_delegate'] = PERMS_SPECIFIC; $ret['channel_r_storage'] = PERMS_PUBLIC; - $ret['channel_w_storage'] = 0; + $ret['channel_w_storage'] = PERMS_SPECIFIC; $ret['channel_r_pages'] = PERMS_PUBLIC; - $ret['channel_w_pages'] = 0; + $ret['channel_w_pages'] = PERMS_SPECIFIC; $ret['channel_a_republish'] = PERMS_SPECIFIC; $ret['channel_w_like'] = PERMS_SPECIFIC; @@ -642,18 +642,18 @@ function get_role_perms($role) { $ret['channel_r_profile'] = PERMS_SPECIFIC; $ret['channel_r_photos'] = PERMS_SPECIFIC; $ret['channel_r_abook'] = PERMS_SPECIFIC; - $ret['channel_w_stream'] = 0; + $ret['channel_w_stream'] = PERMS_SPECIFIC; $ret['channel_w_wall'] = PERMS_SPECIFIC; - $ret['channel_w_tagwall'] = 0; + $ret['channel_w_tagwall'] = PERMS_SPECIFIC; $ret['channel_w_comment'] = PERMS_SPECIFIC; $ret['channel_w_mail'] = PERMS_SPECIFIC; - $ret['channel_w_photos'] = 0; + $ret['channel_w_photos'] = PERMS_SPECIFIC; $ret['channel_w_chat'] = PERMS_SPECIFIC; - $ret['channel_a_delegate'] = 0; + $ret['channel_a_delegate'] = PERMS_SPECIFIC; $ret['channel_r_storage'] = PERMS_SPECIFIC; - $ret['channel_w_storage'] = 0; + $ret['channel_w_storage'] = PERMS_SPECIFIC; $ret['channel_r_pages'] = PERMS_SPECIFIC; - $ret['channel_w_pages'] = 0; + $ret['channel_w_pages'] = PERMS_SPECIFIC; $ret['channel_a_republish'] = PERMS_SPECIFIC; $ret['channel_w_like'] = PERMS_SPECIFIC; @@ -736,18 +736,18 @@ function get_role_perms($role) { $ret['channel_r_profile'] = PERMS_PUBLIC; $ret['channel_r_photos'] = PERMS_PUBLIC; $ret['channel_r_abook'] = PERMS_PUBLIC; - $ret['channel_w_stream'] = 0; - $ret['channel_w_wall'] = 0; - $ret['channel_w_tagwall'] = 0; - $ret['channel_w_comment'] = 0; - $ret['channel_w_mail'] = 0; - $ret['channel_w_photos'] = 0; - $ret['channel_w_chat'] = 0; - $ret['channel_a_delegate'] = 0; + $ret['channel_w_stream'] = PERMS_SPECIFIC; + $ret['channel_w_wall'] = PERMS_SPECIFIC; + $ret['channel_w_tagwall'] = PERMS_SPECIFIC; + $ret['channel_w_comment'] = PERMS_SPECIFIC; + $ret['channel_w_mail'] = PERMS_SPECIFIC; + $ret['channel_w_photos'] = PERMS_SPECIFIC; + $ret['channel_w_chat'] = PERMS_SPECIFIC; + $ret['channel_a_delegate'] = PERMS_SPECIFIC; $ret['channel_r_storage'] = PERMS_PUBLIC; - $ret['channel_w_storage'] = 0; + $ret['channel_w_storage'] = PERMS_SPECIFIC; $ret['channel_r_pages'] = PERMS_PUBLIC; - $ret['channel_w_pages'] = 0; + $ret['channel_w_pages'] = PERMS_SPECIFIC; $ret['channel_a_republish'] = PERMS_SPECIFIC; $ret['channel_w_like'] = PERMS_NETWORK; @@ -775,7 +775,7 @@ function get_role_perms($role) { $ret['channel_w_mail'] = PERMS_SPECIFIC; $ret['channel_w_photos'] = PERMS_SPECIFIC; $ret['channel_w_chat'] = PERMS_SPECIFIC; - $ret['channel_a_delegate'] = 0; + $ret['channel_a_delegate'] = PERMS_SPECIFIC; $ret['channel_r_storage'] = PERMS_PUBLIC; $ret['channel_w_storage'] = PERMS_SPECIFIC; $ret['channel_r_pages'] = PERMS_PUBLIC; -- cgit v1.2.3 From daed7fbeada3c781a6b5d7c8dd69d35733d93ef1 Mon Sep 17 00:00:00 2001 From: Klaus Weidenbach Date: Sat, 21 Mar 2015 19:12:43 +0100 Subject: Bugfix und variable initialization. Fixed a wrong perm_is_allowed() parameter, commented some other places where we use variables that are not set and should not work. --- include/attach.php | 61 +++++++++++++++++++++++++++++++++-------------------- include/network.php | 7 +++--- 2 files changed, 41 insertions(+), 27 deletions(-) (limited to 'include') diff --git a/include/attach.php b/include/attach.php index 7d0b99c05..04fd25ace 100644 --- a/include/attach.php +++ b/include/attach.php @@ -275,7 +275,11 @@ function attach_by_hash($hash, $rev = 0) { * * @see attach_by_hash() * @param $hash - * @param $ref + * @param $rev revision default 0 + * @return array Everything except data. + * * \e boolean \b success boolean true or false + * * \e string \b message (optional) only when success is false + * * \e array \b data array of attach DB entry without data component */ function attach_by_hash_nodata($hash, $rev = 0) { @@ -318,6 +322,7 @@ function attach_by_hash_nodata($hash, $rev = 0) { $ret['success'] = true; $ret['data'] = $r[0]; + return $ret; } @@ -361,6 +366,7 @@ function attach_store($channel, $observer_hash, $options = '', $arr = null) { $existing_size = 0; if($options === 'replace') { + /** @BUG $replace is undefined here */ $x = q("select id, hash, filesize from attach where id = %d and uid = %d limit 1", intval($replace), intval($channel_id) @@ -373,7 +379,7 @@ function attach_store($channel, $observer_hash, $options = '', $arr = null) { $existing_size = intval($x[0]['filesize']); $hash = $x[0]['hash']; } - + if($options === 'revise' || $options === 'update') { $sql_options = " order by revision desc "; if($options === 'update' && $arr && array_key_exists('revision',$arr)) @@ -513,22 +519,24 @@ function attach_store($channel, $observer_hash, $options = '', $arr = null) { } /** - * Read a virtual directory and return contents, checking permissions of all parent components. - * @function z_readdir + * @brief Read a virtual directory and return contents. + * + * Also checking permissions of all parent components. + * * @param integer $channel_id * @param string $observer_hash hash of current observer * @param string $pathname * @param string $parent_hash (optional) * - * @returns array $ret - * $ret['success'] = boolean true or false - * $ret['message'] = error message if success is false - * $ret['data'] = array of attach DB entries without data component + * @return array $ret + * * \e boolean \b success boolean true or false + * * \e string \b message error message if success is false + * * \e array \b data array of attach DB entries without data component */ function z_readdir($channel_id, $observer_hash, $pathname, $parent_hash = '') { $ret = array('success' => false); - if(! perm_is_allowed($r[0]['uid'], get_observer_hash(), 'view_storage')) { + if(! perm_is_allowed($channel_id, get_observer_hash(), 'view_storage')) { $ret['message'] = t('Permission denied.'); return $ret; } @@ -833,12 +841,14 @@ function attach_delete($channel_id, $resource) { /** * @brief Returns path to file in cloud/. - * This function cannot be used with mod/dav as it always returns a path valid under mod/cloud + * + * @warning This function cannot be used with mod/dav as it always returns a + * path valid under mod/cloud. * - * @param array - * $arr[uid] int the channels uid - * $arr[folder] string - * $arr[filename]] string + * @param array assoziative array with: + * * \e int \b uid the channel's uid + * * \e string \b folder + * * \e string \b filename * @return string * path to the file in cloud/ */ @@ -895,6 +905,7 @@ function get_cloudpath($arr) { * @return string with the full folder path */ function get_parent_cloudpath($channel_id, $channel_name, $attachHash) { + $parentFullPath = ''; // build directory tree $parentHash = $attachHash; do { @@ -933,9 +944,9 @@ function find_folder_hash_by_attach_hash($channel_id, $attachHash) { /** * @brief Returns the filename of an attachment in a given channel. * - * @param mixed $channel_id + * @param int $channel_id * The id of the channel - * @param mixed $attachHash + * @param string $attachHash * The hash of the attachment * @return string * The filename of the attachment @@ -949,6 +960,7 @@ function find_filename_by_hash($channel_id, $attachHash) { if ($r) { $filename = $r[0]['filename']; } + return $filename; } @@ -1172,8 +1184,10 @@ function get_file_activity_object($channel_id, $hash, $cloudpath) { } -function recursive_activity_recipients($arr_allow_cid, $arr_llow_gid, $arr_deny_cid, $arr_deny_gid, $folder_hash) { +function recursive_activity_recipients($arr_allow_cid, $arr_allow_gid, $arr_deny_cid, $arr_deny_gid, $folder_hash) { + $ret = array(); + $parent_arr = array(); $poster = get_app()->get_observer(); //turn allow_gid into allow_cid's @@ -1194,8 +1208,10 @@ function recursive_activity_recipients($arr_allow_cid, $arr_llow_gid, $arr_deny_ $parent_arr['allow_cid'][] = expand_acl($x[0]['allow_cid']); $parent_arr['allow_gid'][] = expand_acl($x[0]['allow_gid']); - //TODO: should find a much better solution for the allow_cid <-> allow_gid problem. - //Do not use allow_gid for now. Instead lookup the members of the group directly and add them to allow_cid. + /** + * @TODO should find a much better solution for the allow_cid <-> allow_gid problem. + * Do not use allow_gid for now. Instead lookup the members of the group directly and add them to allow_cid. + * */ if($parent_arr['allow_gid']) { foreach($parent_arr['allow_gid'][$count] as $gid) { $in_group = in_group($gid); @@ -1207,11 +1223,9 @@ function recursive_activity_recipients($arr_allow_cid, $arr_llow_gid, $arr_deny_ $parent_arr['deny_gid'][] = expand_acl($x[0]['deny_gid']); $count++; - } $folder_hash = $x[0]['folder']; - } //if none of the parent folders is private just return file perms @@ -1279,11 +1293,12 @@ function recursive_activity_recipients($arr_allow_cid, $arr_llow_gid, $arr_deny_ } return $ret; - } function in_group($group_id) { - //TODO: make these two queries one with a join. + $group_members = array(); + + /** @TODO make these two queries one with a join. */ $x = q("SELECT id FROM groups WHERE hash = '%s'", dbesc($group_id) ); diff --git a/include/network.php b/include/network.php index 5912ad79d..6aefc0b30 100644 --- a/include/network.php +++ b/include/network.php @@ -32,8 +32,6 @@ function z_fetch_url($url, $binary = false, $redirects = 0, $opts = array()) { $ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => ""); - $a = get_app(); - $ch = @curl_init($url); if(($redirects > 8) || (! $ch)) return false; @@ -71,7 +69,6 @@ function z_fetch_url($url, $binary = false, $redirects = 0, $opts = array()) { @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, ((x($opts,'novalidate') && intval($opts['novalidate'])) ? false : true)); - $prx = get_config('system','proxy'); if(strlen($prx)) { @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); @@ -518,6 +515,7 @@ function allowed_email($email) { function avatar_img($email) { + $avatar = array(); $a = get_app(); $avatar['size'] = 175; @@ -527,10 +525,11 @@ function avatar_img($email) { call_hooks('avatar_lookup', $avatar); - if(! $avatar['success']) + if (! $avatar['success']) $avatar['url'] = $a->get_baseurl() . '/' . get_default_profile_photo(); logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG); + return $avatar['url']; } -- cgit v1.2.3 From 9d143e3f2dae4bd24b234a00dce7f0a59f24f470 Mon Sep 17 00:00:00 2001 From: Klaus Weidenbach Date: Sat, 21 Mar 2015 22:03:59 +0100 Subject: Fixed an exit of a loop in builtin_activity_puller(). There was a "$return", but I think it should be "return". --- include/conversation.php | 260 ++++++++++++++++++++++++----------------------- 1 file changed, 132 insertions(+), 128 deletions(-) (limited to 'include') diff --git a/include/conversation.php b/include/conversation.php index a85d582ce..8a834f339 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -205,22 +205,22 @@ function localize_item(&$item){ $item['body'] .= "\n\n\n" . $Bphoto; } - if (stristr($item['verb'],ACTIVITY_POKE)) { + if (stristr($item['verb'], ACTIVITY_POKE)) { - // FIXME for obscured private posts, until then leave untranslated + /** @FIXME for obscured private posts, until then leave untranslated */ return; $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1)); if(! $verb) return; + if ($item['obj_type']=="" || $item['obj_type']!== ACTIVITY_OBJ_PERSON) return; $Aname = $item['author']['xchan_name']; $Alink = $item['author']['xchan_url']; - $obj= json_decode_plus($item['object']); - + $Blink = $Bphoto = ''; if($obj['link']) { @@ -246,7 +246,6 @@ function localize_item(&$item){ $item['body'] = $item['localize'] = sprintf($txt, $A, $B); $item['body'] .= "\n\n\n" . $Bphoto; - } if (stristr($item['verb'],ACTIVITY_MOOD)) { $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1)); @@ -375,54 +374,72 @@ function localize_item(&$item){ && strlen($item['body']) && (! strpos($item['body'],'data'))) { $item['body'] = json_encode(crypto_encapsulate($item['body'],get_config('system','pubkey'))); } - } /** - * Count the total of comments on this item and its desendants + * @brief Count the total of comments on this item and its desendants. + * + * @param array $item an assoziative item-array which provides: + * * \e array \b children + * @return number */ function count_descendants($item) { $total = count($item['children']); - if($total > 0) { - foreach($item['children'] as $child) { - if(! visible_activity($child)) - $total --; - $total += count_descendants($child); - } - } + if ($total > 0) { + foreach ($item['children'] as $child) { + if (! visible_activity($child)) + $total --; + + $total += count_descendants($child); + } + } return $total; } +/** + * @brief Check if the activity of the item is visible. + * + * likes (etc.) can apply to other things besides posts. Check if they are post + * children, in which case we handle them specially. + * + * @param array $item + * @return boolean + */ function visible_activity($item) { - - // likes (etc.) can apply to other things besides posts. Check if they are post children, - // in which case we handle them specially - $hidden_activities = array(ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_AGREE, ACTIVITY_DISAGREE, ACTIVITY_ABSTAIN, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE); - foreach($hidden_activities as $act) { - if((activity_match($item['verb'],$act)) && ($item['mid'] != $item['parent_mid'])) { + + foreach ($hidden_activities as $act) { + if ((activity_match($item['verb'], $act)) && ($item['mid'] != $item['parent_mid'])) { return false; } } + return true; } /** - * "Render" a conversation or list of items for HTML display. + * @brief "Render" a conversation or list of items for HTML display. + * * There are two major forms of display: - * - Sequential or unthreaded ("New Item View" or search results) - * - conversation view + * - Sequential or unthreaded ("New Item View" or search results) + * - conversation view + * * The $mode parameter decides between the various renderings and also * figures out how to determine page owner and other contextual items * that are based on unique features of the calling module. * + * @param App &$a + * @param array $items + * @param string $mode + * @param boolean $update + * @param string $page_mode default traditional + * @param string $prepared_item + * @return string */ - - function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $prepared_item = '') { $content_html = ''; @@ -432,39 +449,38 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $ $ssl_state = ((local_channel()) ? true : false); - if(local_channel()) + if (local_channel()) load_pconfig(local_channel(),''); $arr_blocked = null; - if(local_channel()) + if (local_channel()) $str_blocked = get_pconfig(local_channel(),'system','blocked'); - if(! local_channel() && ($mode == 'network')) { + if (! local_channel() && ($mode == 'network')) { $sys = get_sys_channel(); $id = $sys['channel_id']; $str_blocked = get_pconfig($id,'system','blocked'); } - - if($str_blocked) { - $arr_blocked = explode(',',$str_blocked); - for($x = 0; $x < count($arr_blocked); $x ++) + + if ($str_blocked) { + $arr_blocked = explode(',',$str_blocked); + for ($x = 0; $x < count($arr_blocked); $x ++) $arr_blocked[$x] = trim($arr_blocked[$x]); } - - $profile_owner = 0; - $page_writeable = false; + $profile_owner = 0; + $page_writeable = false; $live_update_div = ''; $preview = (($page_mode === 'preview') ? true : false); $previewing = (($preview) ? ' preview ' : ''); - if($mode === 'network') { + if ($mode === 'network') { $profile_owner = local_channel(); $page_writeable = true; - if(!$update) { + if (!$update) { // The special div is needed for liveUpdate to kick in for this page. // We only launch liveUpdate if you aren't filtering in some incompatible // way and also you aren't writing a comment (discovered in javascript). @@ -490,13 +506,13 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $ } } - elseif($mode === 'channel') { + elseif ($mode === 'channel') { $profile_owner = $a->profile['profile_uid']; $page_writeable = ($profile_owner == local_channel()); - if(!$update) { + if (!$update) { $tab = notags(trim($_GET['tab'])); - if($tab === 'posts') { + if ($tab === 'posts') { // This is ugly, but we can't pass the profile_uid through the session to the ajax updater, // because browser prefetching might change it on us. We have to deliver it with the page. @@ -507,23 +523,23 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $ } } - elseif($mode === 'display') { + elseif ($mode === 'display') { $profile_owner = local_channel(); $page_writeable = false; $live_update_div = '
      ' . "\r\n"; } - elseif($mode === 'page') { + elseif ($mode === 'page') { $profile_owner = $a->profile['uid']; $page_writeable = ($profile_owner == local_channel()); $live_update_div = '
      ' . "\r\n"; } - elseif($mode === 'search') { + elseif ($mode === 'search') { $live_update_div = '' . "\r\n"; } - elseif($mode === 'photos') { + elseif ($mode === 'photos') { $profile_onwer = $a->profile['profile_uid']; $page_writeable = ($profile_owner == local_channel()); $live_update_div = '
      ' . "\r\n"; @@ -533,12 +549,12 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $ $page_dropping = ((local_channel() && local_channel() == $profile_owner) ? true : false); - if(! feature_enabled($profile_owner,'multi_delete')) + if (! feature_enabled($profile_owner,'multi_delete')) $page_dropping = false; $channel = $a->get_channel(); - $observer = $a->get_observer(); + $observer = $a->get_observer(); if($update) $return_url = $_SESSION['return_url']; @@ -637,7 +653,6 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $ else $dropping = false; - $drop = array( 'pagedropping' => $page_dropping, 'dropping' => $dropping, @@ -647,7 +662,7 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $ $star = false; $isstarred = "unstarred icon-star-empty"; - + $lock = (($item['item_private'] || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) ? t('Private Message') : false @@ -659,17 +674,14 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $ $verified = (($item['item_flags'] & ITEM_VERIFIED) ? t('Message signature validated') : ''); $forged = ((($item['sig']) && (! ($item['item_flags'] & ITEM_VERIFIED))) ? t('Message signature incorrect') : ''); - $unverified = ''; - $tags=array(); $terms = get_terms_oftype($item['term'],array(TERM_HASHTAG,TERM_MENTION,TERM_UNKNOWN)); if(count($terms)) foreach($terms as $tag) $tags[] = format_term_for_display($tag); - $body = prepare_body($item,true); $tmp_item = array( @@ -731,12 +743,9 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $ // $threads[$threadsid]['id'] = $item['item_id']; $threads[] = $arr['output']; - } - } - else - { + else { // Normal View // logger('conv: items: ' . print_r($items,true)); @@ -751,7 +760,6 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $ if($mode === 'display' && $items) $conv->set_profile_owner($items[0]['uid']); - // get all the topmost parents // this shouldn't be needed, as we should have only them in our array // But for now, this array respects the old style, just in case @@ -831,20 +839,19 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $ // logger('nouveau: ' . print_r($threads,true)); - $o .= replace_macros($page_template, array( - '$baseurl' => $a->get_baseurl($ssl_state), + $o .= replace_macros($page_template, array( + '$baseurl' => $a->get_baseurl($ssl_state), '$photo_item' => $content_html, - '$live_update' => $live_update_div, - '$remove' => t('remove'), - '$mode' => $mode, - '$user' => $a->user, - '$threads' => $threads, + '$live_update' => $live_update_div, + '$remove' => t('remove'), + '$mode' => $mode, + '$user' => $a->user, + '$threads' => $threads, '$wait' => t('Loading...'), - '$dropping' => ($page_dropping?t('Delete Selected Items'):False), - )); + '$dropping' => ($page_dropping?t('Delete Selected Items'):False), + )); return $o; - } @@ -892,7 +899,6 @@ function item_photo_menu($item){ $vsrc_link = ""; $follow_url = ""; - $local_channel = local_channel(); if($local_channel) { @@ -910,7 +916,7 @@ function item_photo_menu($item){ } } - $profile_link = chanlink_hash($item['author_xchan']); + $profile_link = chanlink_hash($item['author_xchan']); if($item['uid'] > 0) $pm_url = $a->get_baseurl($ssl_state) . '/mail/new/?f=&hash=' . $item['author_xchan']; @@ -927,7 +933,6 @@ function item_photo_menu($item){ $posts_link = $a->get_baseurl($ssl_state) . '/network/?cid=' . $contact['abook_id']; $clean_url = normalise_link($item['author-link']); - } $menu = Array( @@ -943,7 +948,6 @@ function item_photo_menu($item){ t("Poke") => $poke_link ); - $args = array('item' => $item, 'menu' => $menu); call_hooks('item_photo_menu', $args); @@ -958,17 +962,17 @@ function item_photo_menu($item){ } elseif ($v!="") $o .= "
    • $k
    • \n"; } + return $o; } /** * @brief Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.) + * * Increments the count of each matching activity and adds a link to the author as needed. * - * @param array $a (not used) * @param array $item * @param array &$conv_responses (already created with builtin activity structure) - * @return void */ function builtin_activity_puller($item, &$conv_responses) { @@ -1011,11 +1015,7 @@ function builtin_activity_puller($item, &$conv_responses) { break; } - - if((activity_match($item['verb'], $verb)) && ($item['id'] != $item['parent'])) { - - $name = (($item['author']['xchan_name']) ? $item['author']['xchan_name'] : t('Unknown')); $url = (($item['author']['xchan_url']) ? '' . $name . '' @@ -1041,31 +1041,33 @@ function builtin_activity_puller($item, &$conv_responses) { $conv_responses[$mode][$item['thr_parent'] . '-l'][] = $url; // there can only be one activity verb per item so if we found anything, we can stop looking - $return; + return; } } } -// Format the like/dislike text for a profile item -// $cnt = number of people who like/dislike the item -// $arr = array of pre-linked names of likers/dislikers -// $type = one of 'like, 'dislike' -// $id = item id -// returns formatted text - -function format_like($cnt,$arr,$type,$id) { +/** + * @brief Format the like/dislike text for a profile item. + * + * @param int $cnt number of people who like/dislike the item + * @param array $arr array of pre-linked names of likers/dislikers + * @param string $typ eone of 'like, 'dislike' + * @param int $id item id + * @return string formatted text + */ +function format_like($cnt, $arr, $type, $id) { $o = ''; - if($cnt == 1) + if ($cnt == 1) { $o .= (($type === 'like') ? sprintf( t('%s likes this.'), $arr[0]) : sprintf( t('%s doesn\'t like this.'), $arr[0])) . EOL ; - else { + } else { $spanatts = 'class="fakelink" onclick="openClose(\'' . $type . 'list-' . $id . '\');"'; $o .= (($type === 'like') ? sprintf( tt('%2$d people like this.','%2$d people like this.',$cnt), $spanatts, $cnt) : sprintf( tt('%2$d people don\'t like this.','%2$d people don\'t like this.',$cnt), $spanatts, $cnt) ); - $o .= EOL ; + $o .= EOL; $total = count($arr); if($total >= MAX_LIKERS) $arr = array_slice($arr, 0, MAX_LIKERS - 1); @@ -1077,6 +1079,7 @@ function format_like($cnt,$arr,$type,$id) { $str = (($type === 'like') ? sprintf( t('%s like this.'), $str) : sprintf( t('%s don\'t like this.'), $str)); $o .= "\t" . ''; } + return $o; } @@ -1098,7 +1101,7 @@ function status_editor($a, $x, $popup = false) { if(array_key_exists('mimetype', $x) && $x['mimetype']) { if($x['mimetype'] != 'text/bbcode') $plaintext = true; - if($x['mimetype'] === 'choose') { + if($x['mimetype'] === 'choose') { $mimeselect = mimetype_select($x['profile_uid']); } else @@ -1376,7 +1379,6 @@ function render_location_default($item) { } - function prepare_page($item) { $a = get_app(); $naked = ((get_pconfig($item['uid'],'system','nakedpage')) ? 1 : 0); @@ -1446,7 +1448,6 @@ function network_tabs() { $public_active = 'active'; } - if (($new_active == '') && ($starred_active == '') && ($conv_active == '') @@ -1538,15 +1539,20 @@ function network_tabs() { return replace_macros($tpl, array('$tabs' => $arr['tabs'])); } - - -function profile_tabs($a, $is_owner=False, $nickname=Null){ +/** + * @brief + * + * @param App $a + * @param boolean $is_owner default false + * @param string $nickname default null + * @return void|string + */ +function profile_tabs($a, $is_owner = false, $nickname = null){ // Don't provide any profile tabs if we're running as the sys channel - - if($a->is_sys) + if ($a->is_sys) return; - + $channel = $a->get_channel(); if (is_null($nickname)) @@ -1554,10 +1560,10 @@ function profile_tabs($a, $is_owner=False, $nickname=Null){ $uid = (($a->profile['profile_uid']) ? $a->profile['profile_uid'] : local_channel()); - if (get_pconfig($uid,'system','noprofiletabs')) + if (get_pconfig($uid, 'system', 'noprofiletabs')) return; - if(x($_GET,'tab')) + if (x($_GET, 'tab')) $tab = notags(trim($_GET['tab'])); $url = $a->get_baseurl() . '/channel/' . $nickname; @@ -1575,42 +1581,42 @@ function profile_tabs($a, $is_owner=False, $nickname=Null){ $p = get_all_perms($uid,get_observer_hash()); - if($p['view_profile']) { + if ($p['view_profile']) { $tabs[] = array( 'label' => t('About'), - 'url' => $pr, - 'sel' => ((argv(0) == 'profile') ? 'active' : ''), + 'url' => $pr, + 'sel' => ((argv(0) == 'profile') ? 'active' : ''), 'title' => t('Profile Details'), 'id' => 'profile-tab', ); } - if($p['view_photos']) { + if ($p['view_photos']) { $tabs[] = array( 'label' => t('Photos'), - 'url' => $a->get_baseurl() . '/photos/' . $nickname, - 'sel' => ((argv(0) == 'photos') ? 'active' : ''), + 'url' => $a->get_baseurl() . '/photos/' . $nickname, + 'sel' => ((argv(0) == 'photos') ? 'active' : ''), 'title' => t('Photo Albums'), 'id' => 'photo-tab', ); } - if($p['view_storage']) { + if ($p['view_storage']) { $tabs[] = array( 'label' => t('Files'), - 'url' => $a->get_baseurl() . '/cloud/' . $nickname . ((get_observer_hash()) ? '' : '?f=&davguest=1'), - 'sel' => ((argv(0) == 'cloud' || argv(0) == 'sharedwithme') ? 'active' : ''), + 'url' => $a->get_baseurl() . '/cloud/' . $nickname . ((get_observer_hash()) ? '' : '?f=&davguest=1'), + 'sel' => ((argv(0) == 'cloud' || argv(0) == 'sharedwithme') ? 'active' : ''), 'title' => t('Files and Storage'), 'id' => 'files-tab', ); } - if($p['chat']) { + if ($p['chat']) { require_once('include/chat.php'); $has_chats = chatroom_list_count($uid); if ($has_chats) { $tabs[] = array( 'label' => t('Chatrooms'), - 'url' => $a->get_baseurl() . '/chat/' . $nickname, - 'sel' => ((argv(0) == 'chat') ? 'active' : '' ), + 'url' => $a->get_baseurl() . '/chat/' . $nickname, + 'sel' => ((argv(0) == 'chat') ? 'active' : '' ), 'title' => t('Chatrooms'), 'id' => 'chat-tab', ); @@ -1619,30 +1625,29 @@ function profile_tabs($a, $is_owner=False, $nickname=Null){ require_once('include/menu.php'); $has_bookmarks = menu_list_count(local_channel(),'',MENU_BOOKMARK) + menu_list_count(local_channel(),'',MENU_SYSTEM|MENU_BOOKMARK); - if($is_owner && $has_bookmarks) { + if ($is_owner && $has_bookmarks) { $tabs[] = array( 'label' => t('Bookmarks'), - 'url' => $a->get_baseurl() . '/bookmarks', - 'sel' => ((argv(0) == 'bookmarks') ? 'active' : ''), + 'url' => $a->get_baseurl() . '/bookmarks', + 'sel' => ((argv(0) == 'bookmarks') ? 'active' : ''), 'title' => t('Saved Bookmarks'), 'id' => 'bookmarks-tab', ); } - - if($is_owner && feature_enabled($uid,'webpages')) { + if ($is_owner && feature_enabled($uid,'webpages')) { $tabs[] = array( 'label' => t('Webpages'), - 'url' => $a->get_baseurl() . '/webpages/' . $nickname, - 'sel' => ((argv(0) == 'webpages') ? 'active' : ''), + 'url' => $a->get_baseurl() . '/webpages/' . $nickname, + 'sel' => ((argv(0) == 'webpages') ? 'active' : ''), 'title' => t('Manage Webpages'), 'id' => 'webpages-tab', ); - } - else { - // FIXME - // we probably need a listing of events that were created by - // this channel and are visible to the observer + } else { + /** + * @FIXME we probably need a listing of events that were created by + * this channel and are visible to the observer + */ } $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs); @@ -1665,8 +1670,7 @@ function get_responses($conv_responses,$response_verbs,$ob,$item) { $ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS); array_push($ret[$v]['list_part'], '' . t('View all') . ''); - } - else { + } else { $ret[$v]['list_part'] = ''; } $ret[$v]['button'] = get_response_button_text($v,$ret[$v]['count']); @@ -1674,9 +1678,9 @@ function get_responses($conv_responses,$response_verbs,$ob,$item) { } $count = 0; - foreach($ret as $key) { - if ($key['count'] == true) - $count++; + foreach ($ret as $key) { + if ($key['count'] == true) + $count++; } $ret['count'] = $count; -- cgit v1.2.3 From a2e3ca6fd8ba8c0630de089d772fdd668b84428b Mon Sep 17 00:00:00 2001 From: friendica Date: Sat, 21 Mar 2015 16:46:28 -0700 Subject: add loadtime search to channel and fix it for home. display and search need further investigation --- include/text.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'include') diff --git a/include/text.php b/include/text.php index 54d8b2ad7..86da3ee42 100644 --- a/include/text.php +++ b/include/text.php @@ -2370,8 +2370,7 @@ function linkify_tags($a, &$body, $uid) { if($fullnametagged) continue; - // @FIXME which $profile_uid? It's not set anywhere. - $success = handle_tag($a, $body, $access_tag, $str_tags, ($uid) ? $uid : $profile_uid , $tag); + $success = handle_tag($a, $body, $access_tag, $str_tags, ($uid) ? $uid : $a->profile_uid , $tag); $results[] = array('success' => $success, 'access_tag' => $access_tag); if($success['replaced']) $tagged[] = $tag; } -- cgit v1.2.3 From 96239b364809b12f67c093cdaa1e9b49ab7a9c20 Mon Sep 17 00:00:00 2001 From: Klaus Weidenbach Date: Sun, 22 Mar 2015 14:15:04 +0100 Subject: Two possible bugfixes in bb2diaspora.php. I have found two suspicious parts and tried to correct them. I have no diaspora enabled hubs and I am also not sure what influence these two changes will have: $unset($item['author']) ==> unset($item['author']); if(cnt) ==> if($cnt) Before merging can someone with diaspora contacts test this. --- include/bb2diaspora.php | 76 ++++++++++++++++++++++++++++++++----------------- 1 file changed, 50 insertions(+), 26 deletions(-) (limited to 'include') diff --git a/include/bb2diaspora.php b/include/bb2diaspora.php index fa3aa3aa2..118e78639 100644 --- a/include/bb2diaspora.php +++ b/include/bb2diaspora.php @@ -1,4 +1,8 @@ - Date: Sun, 22 Mar 2015 14:24:07 +0100 Subject: do not override item_private here anymore --- include/attach.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/attach.php b/include/attach.php index 04fd25ace..1daa42aef 100644 --- a/include/attach.php +++ b/include/attach.php @@ -1078,7 +1078,7 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $arr['deny_cid'] = perms2str($u_arr_deny_cid); $arr['deny_gid'] = perms2str($u_arr_deny_gid); $arr['item_restrict'] = ITEM_HIDDEN; - $arr['item_private'] = 0; + $arr['item_private'] = $private; $arr['verb'] = ACTIVITY_UPDATE; $arr['obj_type'] = $objtype; $arr['object'] = $u_jsonobject; -- cgit v1.2.3 From e345d6793d5f6910dd230f661ca5d1a837b1b504 Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Sun, 22 Mar 2015 16:29:57 +0100 Subject: move the maintenance part to include/sharedwithme.php --- include/sharedwithme.php | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 include/sharedwithme.php (limited to 'include') diff --git a/include/sharedwithme.php b/include/sharedwithme.php new file mode 100644 index 000000000..3936dc90f --- /dev/null +++ b/include/sharedwithme.php @@ -0,0 +1,32 @@ + Date: Sun, 22 Mar 2015 18:23:37 -0700 Subject: put a lower time limit on time travellers --- include/poller.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'include') diff --git a/include/poller.php b/include/poller.php index 43cc3f3c0..b70ef75b0 100644 --- a/include/poller.php +++ b/include/poller.php @@ -82,11 +82,13 @@ function poller_run($argv, $argc){ } // publish any applicable items that were set to be published in the future - // (time travel posts) + // (time travel posts). Restrict to items that have come of age in the last + // couple of days to limit the query to something reasonable. - $r = q("select id from item where ( item_restrict & %d ) > 0 and created <= %s ", + $r = q("select id from item where ( item_restrict & %d ) > 0 and created <= %s and created > '%s' ", intval(ITEM_DELAYED_PUBLISH), - db_utcnow() + db_utcnow(), + dbesc(datetime_convert('UTC','UTC','now - 2 days')) ); if($r) { foreach($r as $rr) { -- cgit v1.2.3 From 62b2fa6ac7ee85c8572eb868eb30dc2e20cf3040 Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 22 Mar 2015 20:30:23 -0700 Subject: operation snakebite, cont. --- include/api.php | 10 ++++++++++ include/hubloc.php | 4 ++-- 2 files changed, 12 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/api.php b/include/api.php index 8c0e32ecc..fdc8edece 100644 --- a/include/api.php +++ b/include/api.php @@ -727,6 +727,16 @@ require_once('include/items.php'); else $_REQUEST['parent_mid'] = $parent; + if($_REQUEST['namespace'] && $parent) { + $x = q("select iid from item_id where service = '%s' and sid = '%s' limit 1", + dbesc($_REQUEST['namespace']), + dbesc($parent) + ); + if($x) { + $_REQUEST['parent'] = $x[0]['iid']; + } + } + if(requestdata('lat') && requestdata('long')) $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long')); diff --git a/include/hubloc.php b/include/hubloc.php index 98c1a21f3..ece7bd21a 100644 --- a/include/hubloc.php +++ b/include/hubloc.php @@ -256,12 +256,12 @@ function xchan_fetch($arr) { if(! $key) return false; - $r = q("select * from xchan where $key = '$v'"); + $r = q("select * from xchan where $key = '$v' limit 1"); if(! $r) return false; $ret = array(); - foreach($r as $k => $v) { + foreach($r[0] as $k => $v) { if($k === 'xchan_addr') $ret['address'] = $v; else -- cgit v1.2.3 From f2127d4ba717484140530e17eb8ae495cab349d7 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 23 Mar 2015 15:36:17 -0700 Subject: limit notification detail queries for items and events --- include/api.php | 6 +++++- include/hubloc.php | 4 +++- 2 files changed, 8 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/api.php b/include/api.php index fdc8edece..3ac8ddbda 100644 --- a/include/api.php +++ b/include/api.php @@ -622,10 +622,14 @@ require_once('include/items.php'); function api_red_xchan(&$a,$type) { + logger('api_xchan'); + if(api_user() === false) return false; + logger('api_xchan'); require_once('include/hubloc.php'); - if($_SERVER['request_method'] === 'POST') { + + if($_SERVER['REQUEST_METHOD'] === 'POST') { $r = xchan_store($_REQUEST); } $r = xchan_fetch($_REQUEST); diff --git a/include/hubloc.php b/include/hubloc.php index ece7bd21a..a4efe1c75 100644 --- a/include/hubloc.php +++ b/include/hubloc.php @@ -184,6 +184,8 @@ function hubloc_mark_as_down($posturl) { function xchan_store($arr) { + logger('xchan_store: ' . print_r($arr,true)); + if(! $arr['hash']) $arr['hash'] = $arr['guid']; if(! $arr['hash']) @@ -202,7 +204,7 @@ function xchan_store($arr) { if(! $arr['url']) $arr['url'] = z_root(); if(! $arr['photo']) - $arr['photo'] = get_default_profile_photo(); + $arr['photo'] = z_root() . '/' . get_default_profile_photo(); $r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_guid_sig, xchan_pubkey, xchan_addr, xchan_url, xchan_connurl, xchan_follow, xchan_connpage, xchan_name, xchan_network, xchan_instance_url, xchan_flags, xchan_name_date ) values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s','%s','%s','%s',%d,'%s') ", dbesc($arr['hash']), -- cgit v1.2.3 From d32f63df82de01f66d5babe932f20aed9a5b3ee2 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 23 Mar 2015 17:51:43 -0700 Subject: explicitly unset delegate session vars on logout --- include/auth.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'include') diff --git a/include/auth.php b/include/auth.php index 6c9c33861..643894e32 100644 --- a/include/auth.php +++ b/include/auth.php @@ -29,7 +29,8 @@ function nuke_session() { unset($_SESSION['mobile_theme']); unset($_SESSION['show_mobile']); unset($_SESSION['page_flags']); - unset($_SESSION['submanage']); + unset($_SESSION['delegate']); + unset($_SESSION['delegate_channel']); unset($_SESSION['my_url']); unset($_SESSION['my_address']); unset($_SESSION['addr']); -- cgit v1.2.3 From c2acab21d44bfaa8e051a42a13b72c056c95b0a3 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 23 Mar 2015 19:56:10 -0700 Subject: improve performance of the zotfeed queries --- include/items.php | 19 +++++++++---------- include/security.php | 6 ++++-- include/text.php | 10 +++++++--- 3 files changed, 20 insertions(+), 15 deletions(-) (limited to 'include') diff --git a/include/items.php b/include/items.php index 8e293d761..32e5dcbe5 100755 --- a/include/items.php +++ b/include/items.php @@ -4366,12 +4366,11 @@ function zot_feed($uid,$observer_xchan,$arr) { $sql_extra = item_permissions_sql($uid); } + $limit = " LIMIT 100 "; + if($mindate != NULL_DATE) { $sql_extra .= " and ( created > '$mindate' or edited > '$mindate' ) "; - $limit = ""; } - else - $limit = " limit 0, 50 "; if($message_id) { $sql_extra .= " and mid = '" . dbesc($message_id) . "' "; @@ -4382,20 +4381,20 @@ function zot_feed($uid,$observer_xchan,$arr) { if(is_sys_channel($uid)) { require_once('include/security.php'); - $r = q("SELECT distinct parent, created from item + $r = q("SELECT parent from item WHERE uid != %d - and uid in (" . stream_perms_api_uids(PERMS_PUBLIC) . ") AND item_restrict = 0 - AND (item_flags & %d)>0 - and item_private = 0 $sql_extra ORDER BY created ASC $limit", + AND item_private = 0 AND item_restrict = 0 AND uid in (" . stream_perms_api_uids(PERMS_PUBLIC,10,1) . ") + AND (item_flags & %d) > 0 + $sql_extra GROUP BY parent ORDER BY created ASC $limit", intval($uid), intval(ITEM_WALL) ); } else { - $r = q("SELECT distinct parent, created from item + $r = q("SELECT parent from item WHERE uid = %d AND item_restrict = 0 - AND (item_flags & %d)>0 - $sql_extra ORDER BY created ASC $limit", + AND (item_flags & %d) > 0 + $sql_extra GROUP BY parent ORDER BY created ASC $limit", intval($uid), intval(ITEM_WALL) ); diff --git a/include/security.php b/include/security.php index e9b41dcf9..c3b0e9763 100644 --- a/include/security.php +++ b/include/security.php @@ -396,13 +396,15 @@ function init_groups_visitor($contact_id) { // will likely be too expensive. // Returns a string list of comma separated channel_ids suitable for direct inclusion in a SQL query -function stream_perms_api_uids($perms = NULL ) { +function stream_perms_api_uids($perms = NULL, $limit = 0, $rand = 0 ) { $perms = is_null($perms) ? (PERMS_SITE|PERMS_NETWORK|PERMS_PUBLIC) : $perms; $ret = array(); + $limit_sql = (($limit) ? " LIMIT " . intval($limit) . " " : ''); + $random_sql = (($rand) ? " ORDER BY " . db_getfunc('RAND') . " " : ''); if(local_channel()) $ret[] = local_channel(); - $r = q("select channel_id from channel where channel_r_stream > 0 and (channel_r_stream & %d)>0 and not (channel_pageflags & %d)>0", + $r = q("select channel_id from channel where channel_r_stream > 0 and ( channel_r_stream & %d )>0 and ( channel_pageflags & %d ) = 0 $random_sql $limit_sql ", intval($perms), intval(PAGE_ADULT|PAGE_CENSORED|PAGE_SYSTEM|PAGE_REMOVED) ); diff --git a/include/text.php b/include/text.php index 86da3ee42..a21d8029f 100644 --- a/include/text.php +++ b/include/text.php @@ -1855,9 +1855,13 @@ function check_webbie($arr) { function ids_to_querystr($arr,$idx = 'id') { $t = array(); - foreach($arr as $x) - $t[] = $x[$idx]; - + if($arr) { + foreach($arr as $x) { + if(! in_array($x[$idx],$t)) { + $t[] = $x[$idx]; + } + } + } return(implode(',', $t)); } -- cgit v1.2.3 From c024668cf226da7211aaa8cdd04293cf00b8901c Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 24 Mar 2015 02:36:45 -0700 Subject: catche edge case of tag "@abcdef +1", which tags the first entry in your abook, regardless of abcdef. This holds true for other similar patterns as well. --- include/diaspora.php | 6 +++--- include/text.php | 21 +++++++++++++++------ 2 files changed, 18 insertions(+), 9 deletions(-) (limited to 'include') diff --git a/include/diaspora.php b/include/diaspora.php index 1e0e48a86..405fa1e40 100755 --- a/include/diaspora.php +++ b/include/diaspora.php @@ -843,7 +843,7 @@ function diaspora_post($importer,$xml,$msg) { // Look for tags and linkify them - $results = linkify_tags(get_app(), $body, $importer['channel_id']); + $results = linkify_tags(get_app(), $body, $importer['channel_id'], true); $datarray['term'] = array(); @@ -1062,7 +1062,7 @@ function diaspora_reshare($importer,$xml,$msg) { $datarray = array(); // Look for tags and linkify them - $results = linkify_tags(get_app(), $body, $importer['channel_id']); + $results = linkify_tags(get_app(), $body, $importer['channel_id'], true); $datarray['term'] = array(); @@ -1397,7 +1397,7 @@ function diaspora_comment($importer,$xml,$msg) { $datarray = array(); // Look for tags and linkify them - $results = linkify_tags(get_app(), $body, $importer['channel_id']); + $results = linkify_tags(get_app(), $body, $importer['channel_id'], true); $datarray['term'] = array(); diff --git a/include/text.php b/include/text.php index a21d8029f..0aba45d14 100644 --- a/include/text.php +++ b/include/text.php @@ -2105,7 +2105,7 @@ function extra_query_args() { * * @return boolean true if replaced, false if not replaced */ -function handle_tag($a, &$body, &$access_tag, &$str_tags, $profile_uid, $tag) { +function handle_tag($a, &$body, &$access_tag, &$str_tags, $profile_uid, $tag, $diaspora = false) { $replaced = false; $r = null; @@ -2173,7 +2173,7 @@ function handle_tag($a, &$body, &$access_tag, &$str_tags, $profile_uid, $tag) { if(strpos($tag,'@') === 0) { // The @! tag will alter permissions - $exclusive = ((strpos($tag,'!') === 1) ? true : false); + $exclusive = ((strpos($tag,'!') === 1 && (! $diaspora)) ? true : false); //is it already replaced? if(strpos($tag,'[zrl=')) @@ -2202,10 +2202,19 @@ function handle_tag($a, &$body, &$access_tag, &$str_tags, $profile_uid, $tag) { // Here we're looking for an address book entry as provided by the auto-completer // of the form something+nnn where nnn is an abook_id or the first chars of xchan_hash - if(strrpos($newname,'+')) { + + // If there's a +nnn in the string make sure there isn't a space preceding it + + $t1 = strpos($newname,' '); + $t2 = strrpos($newname,'+'); + + if($t1 && $t2 && $t1 < $t2) + $t2 = 0; + + if(($t2) && (! $diaspora)) { //get the id - $tagcid = substr($newname,strrpos($newname,'+') + 1); + $tagcid = substr($newname,$t2 + 1); if(strrpos($tagcid,' ')) $tagcid = substr($tagcid,0,strrpos($tagcid,' ')); @@ -2350,7 +2359,7 @@ function handle_tag($a, &$body, &$access_tag, &$str_tags, $profile_uid, $tag) { return array('replaced' => $replaced, 'termtype' => $termtype, 'term' => $newname, 'url' => $url, 'contact' => $r[0]); } -function linkify_tags($a, &$body, $uid) { +function linkify_tags($a, &$body, $uid, $diaspora = false) { $str_tags = ''; $tagged = array(); $results = array(); @@ -2374,7 +2383,7 @@ function linkify_tags($a, &$body, $uid) { if($fullnametagged) continue; - $success = handle_tag($a, $body, $access_tag, $str_tags, ($uid) ? $uid : $a->profile_uid , $tag); + $success = handle_tag($a, $body, $access_tag, $str_tags, ($uid) ? $uid : $a->profile_uid , $tag, $diaspora); $results[] = array('success' => $success, 'access_tag' => $access_tag); if($success['replaced']) $tagged[] = $tag; } -- cgit v1.2.3 From 1821b099dfc92ce59147e1e225c398919df712b6 Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Tue, 24 Mar 2015 10:56:02 +0100 Subject: this query can take quite a while if there were many updates but it has not been called for a long time (eg nobody called mod sharedwithme). might be a good idea to have this in the poller to clean up on a regular basis and call it once more in mod sharedwithme. what do you think? --- include/poller.php | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'include') diff --git a/include/poller.php b/include/poller.php index b70ef75b0..4786188af 100644 --- a/include/poller.php +++ b/include/poller.php @@ -41,6 +41,12 @@ function poller_run($argv, $argc){ // run queue delivery process in the background proc_run('php',"include/queue.php"); + + + // maintenance for mod sharedwithme - check for updated items and remove them + + require_once('include/sharedwithme.php'); + apply_updates(); // expire any expired mail -- cgit v1.2.3 From c21a21be3e85f9e972b81439bfbac5031547104f Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Tue, 24 Mar 2015 11:38:54 +0100 Subject: we only need item mid. some documentation. --- include/attach.php | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) (limited to 'include') diff --git a/include/attach.php b/include/attach.php index 1daa42aef..2ca302949 100644 --- a/include/attach.php +++ b/include/attach.php @@ -976,6 +976,18 @@ function pipe_streams($in, $out) { return $size; } +/** + * @brief Activity for files + * + * @param $channel_id + * @param $object + * @param $allow_cid + * @param $allow_gid + * @param $deny_cid + * @param $deny_gid + * @param $verb + * @param $no_activity + */ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $verb, $no_activity) { require_once('include/items.php'); @@ -1030,7 +1042,7 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $jsonobject = json_encode($object); //check if item for this object exists - $y = q("SELECT * FROM item WHERE verb = '%s' AND obj_type = '%s' AND resource_id = '%s' AND uid = %d LIMIT 1", + $y = q("SELECT mid FROM item WHERE verb = '%s' AND obj_type = '%s' AND resource_id = '%s' AND uid = %d LIMIT 1", dbesc(ACTIVITY_POST), dbesc($objtype), dbesc($object['hash']), @@ -1143,6 +1155,13 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, } +/** + * @brief Create file activity object + * + * @param $channel_id + * @param $hash + * @param $cloudpath + */ function get_file_activity_object($channel_id, $hash, $cloudpath) { $x = q("SELECT creator, filename, filetype, filesize, revision, folder, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid FROM attach WHERE uid = %d AND hash = '%s' LIMIT 1", @@ -1184,6 +1203,15 @@ function get_file_activity_object($channel_id, $hash, $cloudpath) { } +/** + * @brief Returns array of channels which have recursive permission for a file + * + * @param $arr_allow_cid + * @param $arr_allow_gid + * @param $arr_deny_cid + * @param $arr_deny_gid + * @param $folder_hash + */ function recursive_activity_recipients($arr_allow_cid, $arr_allow_gid, $arr_deny_cid, $arr_deny_gid, $folder_hash) { $ret = array(); @@ -1295,6 +1323,12 @@ function recursive_activity_recipients($arr_allow_cid, $arr_allow_gid, $arr_deny return $ret; } + +/** + * @brief Returns members of a group + * + * @param $group_id + */ function in_group($group_id) { $group_members = array(); -- cgit v1.2.3 From 00b3c4c881290427189185cdf4a247285aa79e5b Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 24 Mar 2015 12:40:55 -0700 Subject: sql errors on postgres with yestderday's optimisation --- include/items.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/items.php b/include/items.php index 32e5dcbe5..d1998bd0a 100755 --- a/include/items.php +++ b/include/items.php @@ -4381,7 +4381,7 @@ function zot_feed($uid,$observer_xchan,$arr) { if(is_sys_channel($uid)) { require_once('include/security.php'); - $r = q("SELECT parent from item + $r = q("SELECT parent, created from item WHERE uid != %d AND item_private = 0 AND item_restrict = 0 AND uid in (" . stream_perms_api_uids(PERMS_PUBLIC,10,1) . ") AND (item_flags & %d) > 0 @@ -4391,7 +4391,7 @@ function zot_feed($uid,$observer_xchan,$arr) { ); } else { - $r = q("SELECT parent from item + $r = q("SELECT parent, created from item WHERE uid = %d AND item_restrict = 0 AND (item_flags & %d) > 0 $sql_extra GROUP BY parent ORDER BY created ASC $limit", -- cgit v1.2.3 From 3d600088424d2e1f71c7b5ae7571a8a101e9e8e2 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 24 Mar 2015 15:53:55 -0700 Subject: provide a site-wide expiration policy without loopholes - still need work to reduce the impact of expiration queries. --- include/expire.php | 36 ++++++++++++++++++++++++++++-------- include/identity.php | 4 +--- include/items.php | 2 +- 3 files changed, 30 insertions(+), 12 deletions(-) (limited to 'include') diff --git a/include/expire.php b/include/expire.php index a229bd4ac..8fedf71b5 100644 --- a/include/expire.php +++ b/include/expire.php @@ -7,7 +7,11 @@ function expire_run($argv, $argc){ cli_startup(); - $r = q("select id from item where (item_restrict & %d)>0 and not (item_restrict & %d)>0 and changed < %s - INTERVAL %s", + + // perform final cleanup on previously delete items + + $r = q("select id from item where (item_restrict & %d) > 0 and (item_restrict & %d) = 0 + and changed < %s - INTERVAL %s", intval(ITEM_DELETED), intval(ITEM_PENDING_REMOVE), db_utcnow(), db_quoteinterval('10 DAY') @@ -19,8 +23,9 @@ function expire_run($argv, $argc){ } // physically remove anything that has been deleted for more than two months + // FIXME - this is a wretchedly inefficient query - $r = q("delete from item where ( item_restrict & %d )>0 and changed < %s - INTERVAL %s", + $r = q("delete from item where ( item_restrict & %d ) > 0 and changed < %s - INTERVAL %s", intval(ITEM_PENDING_REMOVE), db_utcnow(), db_quoteinterval('36 DAY') ); @@ -32,12 +37,28 @@ function expire_run($argv, $argc){ logger('expire: start', LOGGER_DEBUG); + $site_expire = get_config('system', 'default_expire_days'); + if(intval($site_expire)) { + $r = q("SELECT channel_id, channel_address, channel_pageflags, channel_expire_days from channel where true"); + } + else { + $r = q("SELECT channel_id, channel_address, channel_pageflags, channel_expire_days from channel where channel_expire_days != 0"); + } - $r = q("SELECT channel_id, channel_address, channel_expire_days from channel where channel_expire_days != 0"); - if($r && count($r)) { + if($r) { foreach($r as $rr) { + + // expire the sys channel separately + if($rr['channel_pageflags'] & PAGE_SYSTEM) + continue; + + // if the site expiration is non-zero and less than person expiration, use that logger('Expire: ' . $rr['channel_address'] . ' interval: ' . $rr['channel_expire_days'], LOGGER_DEBUG); - item_expire($rr['channel_id'],$rr['channel_expire_days']); + item_expire($rr['channel_id'], + ((intval($site_expire) && intval($site_expire) < intval($rr['channel_expire_days'])) + ? $site_expire + : $rr['channel_expire_days']) + ); } } @@ -48,14 +69,13 @@ function expire_run($argv, $argc){ // this should probably just fetch the channel_expire_days from the sys channel, // but there's no convenient way to set it. - $expire_days = get_config('externals','expire_days'); + $expire_days = get_config('system','sys_expire_days'); if($expire_days === false) $expire_days = 30; if($expire_days) - item_expire($x['channel_id'],$expire_days); + item_expire($x['channel_id'],(($site_expire && $site_expire < $expire_days) ? $site_expire : $expire_days)); } - return; } diff --git a/include/identity.php b/include/identity.php index 079c1a245..af6cb74d2 100644 --- a/include/identity.php +++ b/include/identity.php @@ -249,9 +249,7 @@ function create_identity($arr) { } } - - $expire = get_config('system', 'default_expire_days'); - $expire = (($expire===false)? '0': $expire); + $expire = 0; $r = q("insert into channel ( channel_account_id, channel_primary, channel_name, channel_address, channel_guid, channel_guid_sig, diff --git a/include/items.php b/include/items.php index d1998bd0a..a1515ad88 100755 --- a/include/items.php +++ b/include/items.php @@ -3922,7 +3922,7 @@ function item_expire($uid,$days) { $expire_network_only = 1; - $sql_extra = ((intval($expire_network_only)) ? " AND not (item_flags & " . intval(ITEM_WALL) . ")>0 " : ""); + $sql_extra = ((intval($expire_network_only)) ? " AND not (item_flags & " . intval(ITEM_WALL) . ") > 0 " : ""); $r = q("SELECT * FROM `item` WHERE `uid` = %d -- cgit v1.2.3 From 1f427e0e5b3a5526625e90d43746c89953ab493a Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 24 Mar 2015 16:30:14 -0700 Subject: make the log message reflect what's really happening --- include/expire.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'include') diff --git a/include/expire.php b/include/expire.php index 8fedf71b5..9ef0f7b69 100644 --- a/include/expire.php +++ b/include/expire.php @@ -53,7 +53,9 @@ function expire_run($argv, $argc){ continue; // if the site expiration is non-zero and less than person expiration, use that - logger('Expire: ' . $rr['channel_address'] . ' interval: ' . $rr['channel_expire_days'], LOGGER_DEBUG); + logger('Expire: ' . $rr['channel_address'] . ' interval: ' . ((intval($site_expire) && intval($site_expire) < intval($rr['channel_expire_days'])) + ? $site_expire + : $rr['channel_expire_days']), LOGGER_DEBUG); item_expire($rr['channel_id'], ((intval($site_expire) && intval($site_expire) < intval($rr['channel_expire_days'])) ? $site_expire -- cgit v1.2.3 From 63b8020969434756a7b966ae615c28bf7680f2f8 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 24 Mar 2015 17:09:42 -0700 Subject: more work on expiration, make system limits useful - even in retrospect --- include/expire.php | 34 +++++++++++++++++++++++++--------- include/items.php | 6 +++++- 2 files changed, 30 insertions(+), 10 deletions(-) (limited to 'include') diff --git a/include/expire.php b/include/expire.php index 9ef0f7b69..e414a6e7d 100644 --- a/include/expire.php +++ b/include/expire.php @@ -38,6 +38,9 @@ function expire_run($argv, $argc){ logger('expire: start', LOGGER_DEBUG); $site_expire = get_config('system', 'default_expire_days'); + + logger('site_expire: ' . $site_expire); + if(intval($site_expire)) { $r = q("SELECT channel_id, channel_address, channel_pageflags, channel_expire_days from channel where true"); } @@ -52,15 +55,18 @@ function expire_run($argv, $argc){ if($rr['channel_pageflags'] & PAGE_SYSTEM) continue; + if(intval($site_expire) && (intval($site_expire) < intval($rr['channel_expire_days'])) || + intval($rr['channel_expire_days'] == 0)) { + $expire_days = $site_expire; + } + else { + $expire_days = $rr['channel_expire_days']; + } + + // if the site expiration is non-zero and less than person expiration, use that - logger('Expire: ' . $rr['channel_address'] . ' interval: ' . ((intval($site_expire) && intval($site_expire) < intval($rr['channel_expire_days'])) - ? $site_expire - : $rr['channel_expire_days']), LOGGER_DEBUG); - item_expire($rr['channel_id'], - ((intval($site_expire) && intval($site_expire) < intval($rr['channel_expire_days'])) - ? $site_expire - : $rr['channel_expire_days']) - ); + logger('Expire: ' . $rr['channel_address'] . ' interval: ' . $expire_days, LOGGER_DEBUG); + item_expire($rr['channel_id'], $expire_days); } } @@ -74,8 +80,18 @@ function expire_run($argv, $argc){ $expire_days = get_config('system','sys_expire_days'); if($expire_days === false) $expire_days = 30; + + if(intval($site_expire) && (intval($site_expire) < intval($expire_days))) { + $expire_days = $site_expire; + } + + logger('Expire: sys interval: ' . $expire_days, LOGGER_DEBUG); + if($expire_days) - item_expire($x['channel_id'],(($site_expire && $site_expire < $expire_days) ? $site_expire : $expire_days)); + item_expire($x['channel_id'],$expire_days); + + logger('Expire: sys: done', LOGGER_DEBUG); + } return; diff --git a/include/items.php b/include/items.php index a1515ad88..da0e50c4c 100755 --- a/include/items.php +++ b/include/items.php @@ -3922,6 +3922,10 @@ function item_expire($uid,$days) { $expire_network_only = 1; + $expire_limit = get_config('system','expire_limit'); + if(! intval($expire_limit)) + $expire_limit = 5000; + $sql_extra = ((intval($expire_network_only)) ? " AND not (item_flags & " . intval(ITEM_WALL) . ") > 0 " : ""); $r = q("SELECT * FROM `item` @@ -3930,7 +3934,7 @@ function item_expire($uid,$days) { AND `id` = `parent` $sql_extra AND NOT ( item_flags & %d )>0 - AND (item_restrict = 0 ) ", + AND (item_restrict = 0 ) LIMIT $expire_limit ", intval($uid), db_utcnow(), db_quoteinterval(intval($days).' DAY'), intval(ITEM_RETAINED) -- cgit v1.2.3 From 022305fe8383be238a442efdbd5ba3463d15b7ab Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 24 Mar 2015 20:38:53 -0700 Subject: also allow service classes to set post expiration. These take priority over the site default. --- include/expire.php | 22 ++++++++++++---------- include/items.php | 6 +++--- 2 files changed, 15 insertions(+), 13 deletions(-) (limited to 'include') diff --git a/include/expire.php b/include/expire.php index e414a6e7d..b244e65f5 100644 --- a/include/expire.php +++ b/include/expire.php @@ -41,12 +41,7 @@ function expire_run($argv, $argc){ logger('site_expire: ' . $site_expire); - if(intval($site_expire)) { - $r = q("SELECT channel_id, channel_address, channel_pageflags, channel_expire_days from channel where true"); - } - else { - $r = q("SELECT channel_id, channel_address, channel_pageflags, channel_expire_days from channel where channel_expire_days != 0"); - } + $r = q("SELECT channel_id, channel_address, channel_pageflags, channel_expire_days from channel where true"); if($r) { foreach($r as $rr) { @@ -55,16 +50,23 @@ function expire_run($argv, $argc){ if($rr['channel_pageflags'] & PAGE_SYSTEM) continue; - if(intval($site_expire) && (intval($site_expire) < intval($rr['channel_expire_days'])) || + // service class default (if non-zero) over-rides the site default + + $service_class_expire = service_class_fetch($rr['channel_id'],'expire_days'); + if(intval($service_class_expire)) + $channel_expire = $service_class_expire; + else + $channel_expire = $site_expire; + + if(intval($channel_expire) && (intval($channel_expire) < intval($rr['channel_expire_days'])) || intval($rr['channel_expire_days'] == 0)) { - $expire_days = $site_expire; + $expire_days = $channel_expire; } else { $expire_days = $rr['channel_expire_days']; } - - // if the site expiration is non-zero and less than person expiration, use that + // if the site or service class expiration is non-zero and less than person expiration, use that logger('Expire: ' . $rr['channel_address'] . ' interval: ' . $expire_days, LOGGER_DEBUG); item_expire($rr['channel_id'], $expire_days); } diff --git a/include/items.php b/include/items.php index da0e50c4c..a8947202d 100755 --- a/include/items.php +++ b/include/items.php @@ -3926,15 +3926,15 @@ function item_expire($uid,$days) { if(! intval($expire_limit)) $expire_limit = 5000; - $sql_extra = ((intval($expire_network_only)) ? " AND not (item_flags & " . intval(ITEM_WALL) . ") > 0 " : ""); + $sql_extra = ((intval($expire_network_only)) ? " AND (item_flags & " . intval(ITEM_WALL) . ") = 0 " : ""); $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `created` < %s - INTERVAL %s AND `id` = `parent` $sql_extra - AND NOT ( item_flags & %d )>0 - AND (item_restrict = 0 ) LIMIT $expire_limit ", + AND ( item_flags & %d ) = 0 + AND ( item_restrict = 0 ) LIMIT $expire_limit ", intval($uid), db_utcnow(), db_quoteinterval(intval($days).' DAY'), intval(ITEM_RETAINED) -- cgit v1.2.3 From 49005101c7e83b342ec84ca7277f065c103df4b1 Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Wed, 25 Mar 2015 11:03:37 +0100 Subject: make postgresql happy --- include/sharedwithme.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/sharedwithme.php b/include/sharedwithme.php index 3936dc90f..b01764ad3 100644 --- a/include/sharedwithme.php +++ b/include/sharedwithme.php @@ -3,7 +3,7 @@ function apply_updates() { //check for updated items and remove them - $x = q("SELECT mid, object FROM item WHERE verb = '%s' AND obj_type = '%s' GROUP BY mid", + $x = q("SELECT mid, max(object) AS object FROM item WHERE verb = '%s' AND obj_type = '%s' GROUP BY mid", dbesc(ACTIVITY_UPDATE), dbesc(ACTIVITY_OBJ_FILE) ); -- cgit v1.2.3 From e33da588bddad9269aa7ab9cdc8cb1ab49d1e9cd Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 25 Mar 2015 15:32:49 -0700 Subject: comanche: move 'webpage' declaration to the first parser pass so it is set when content loads. --- include/comanche.php | 15 ++++++++------- include/text.php | 4 ++-- 2 files changed, 10 insertions(+), 9 deletions(-) (limited to 'include') diff --git a/include/comanche.php b/include/comanche.php index 1ddabb693..71ffe99b8 100644 --- a/include/comanche.php +++ b/include/comanche.php @@ -79,22 +79,23 @@ function comanche_parser(&$a, $s, $pass = 0) { if($cnt) $a->layout['theme'] = trim($matches[1]); - } - else { - $cnt = preg_match_all("/\[region=(.*?)\](.*?)\[\/region\]/ism", $s, $matches, PREG_SET_ORDER); + $cnt = preg_match_all("/\[webpage\](.*?)\[\/webpage\]/ism", $s, $matches, PREG_SET_ORDER); if($cnt) { + // only the last webpage definition is used if there is more than one foreach($matches as $mtch) { - $a->layout['region_' . $mtch[1]] = comanche_region($a,$mtch[2]); + $a->layout['webpage'] = comanche_webpage($a,$mtch[1]); } } - $cnt = preg_match_all("/\[webpage\](.*?)\[\/webpage\]/ism", $s, $matches, PREG_SET_ORDER); + } + else { + $cnt = preg_match_all("/\[region=(.*?)\](.*?)\[\/region\]/ism", $s, $matches, PREG_SET_ORDER); if($cnt) { - // only the last webpage definition is used if there is more than one foreach($matches as $mtch) { - $a->layout['webpage'] = comanche_webpage($a,$mtch[1]); + $a->layout['region_' . $mtch[1]] = comanche_region($a,$mtch[2]); } } + } } diff --git a/include/text.php b/include/text.php index 0aba45d14..75125c606 100644 --- a/include/text.php +++ b/include/text.php @@ -1309,13 +1309,13 @@ function generate_map($coord) { $coord = str_replace(array(',','/',' '),array(' ',' ',' '),$coord); $arr = array('lat' => trim(substr($coord,0,strpos($coord,' '))), 'lon' => trim(substr($coord,strpos($coord,' ')+1)), 'html' => ''); call_hooks('generate_map',$arr); - return $arr['html']; + return (($arr['html']) ? $arr['html'] : $coord); } function generate_named_map($location) { $arr = array('location' => $location, 'html' => ''); call_hooks('generate_named_map',$arr); - return $arr['html']; + return (($arr['html']) ? $arr['html'] : $location); } -- cgit v1.2.3 From 47292c612c5a2a6d3819ca3c415fa2d99ab2ee7f Mon Sep 17 00:00:00 2001 From: friendica Date: Thu, 26 Mar 2015 18:03:39 -0700 Subject: provide ways to over-ride the datetime pickers --- include/conversation.php | 2 ++ include/datetime.php | 2 ++ 2 files changed, 4 insertions(+) (limited to 'include') diff --git a/include/conversation.php b/include/conversation.php index 8a834f339..4018ced28 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -1158,6 +1158,8 @@ function status_editor($a, $x, $popup = false) { $preview = ''; $defexpire = ((($z = get_pconfig($x['profile_uid'], 'system', 'default_post_expire')) && (! $webpage)) ? $z : ''); + if($defexpire) + $defexpire = datetime_convert('UTC',date_default_timezone_get(),$defexpire,'Y-m-d H:i'); $cipher = get_pconfig($x['profile_uid'], 'system', 'default_cipher'); if(! $cipher) diff --git a/include/datetime.php b/include/datetime.php index a387d84c4..5cab5889d 100644 --- a/include/datetime.php +++ b/include/datetime.php @@ -175,6 +175,8 @@ function timesel($format, $h, $m, $id='timepicker') { * set maximum date from picker with id $maxfrom (none by default) */ function datetimesel($format, $min, $max, $default, $id = 'datetimepicker', $pickdate = true, $picktime = true, $minfrom = '', $maxfrom = '',$required = false) { + + // Once browser support is better this could probably be replaced with native HTML5 date picker $o = ''; -- cgit v1.2.3 From 0aba609ad408faabe72826a006b8af0fe15a3c2f Mon Sep 17 00:00:00 2001 From: friendica Date: Sat, 28 Mar 2015 14:53:00 -0700 Subject: issue #941 --- include/crypto.php | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) (limited to 'include') diff --git a/include/crypto.php b/include/crypto.php index ab083cfaa..a4ce2cf98 100644 --- a/include/crypto.php +++ b/include/crypto.php @@ -300,7 +300,6 @@ function salmon_key($pubkey) { // used in Friendica 'RINO'. This function is messy and should be retired. -if(! function_exists('aes_decrypt')) { function aes_decrypt($val,$ky) { $key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; @@ -310,10 +309,10 @@ function aes_decrypt($val,$ky) $enc = MCRYPT_RIJNDAEL_128; $dec = @mcrypt_decrypt($enc, $key, $val, $mode, @mcrypt_create_iv( @mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM ) ); return rtrim($dec,(( ord(substr($dec,strlen($dec)-1,1))>=0 and ord(substr($dec, strlen($dec)-1,1))<=16)? chr(ord( substr($dec,strlen($dec)-1,1))):null)); -}} +} + -if(! function_exists('aes_encrypt')) { function aes_encrypt($val,$ky) { $key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; @@ -323,6 +322,14 @@ function aes_encrypt($val,$ky) $enc=MCRYPT_RIJNDAEL_128; $val=str_pad($val, (16*(floor(strlen($val) / 16)+(strlen($val) % 16==0?2:1))), chr(16-(strlen($val) % 16))); return mcrypt_encrypt($enc, $key, $val, $mode, mcrypt_create_iv( mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM)); -}} +} +function z_obscure($s) { + return json_encode(crypto_encapsulate($s,get_config('system','pubkey'))); +} +function z_unobscure($s) { + if(strpos($s,"{\"") !== 0) + return $s; + return crypto_unencapsulate(json_decode($s,true),get_config('system','prvkey')); +} -- cgit v1.2.3 From 1e4490079b5257a8a90064eb986e16825391421d Mon Sep 17 00:00:00 2001 From: friendica Date: Sat, 28 Mar 2015 18:45:58 -0700 Subject: issue #938 --- include/items.php | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/items.php b/include/items.php index a8947202d..4246dd41f 100755 --- a/include/items.php +++ b/include/items.php @@ -4383,13 +4383,19 @@ function zot_feed($uid,$observer_xchan,$arr) { $items = array(); + // FIXME + + if(ACTIVE_DBTYPE == DBTYPE_POSTGRES) { + return array(); + } + if(is_sys_channel($uid)) { require_once('include/security.php'); $r = q("SELECT parent, created from item WHERE uid != %d AND item_private = 0 AND item_restrict = 0 AND uid in (" . stream_perms_api_uids(PERMS_PUBLIC,10,1) . ") AND (item_flags & %d) > 0 - $sql_extra GROUP BY parent ORDER BY created ASC $limit", + $sql_extra GROUP BY parent, created ORDER BY created ASC $limit", intval($uid), intval(ITEM_WALL) ); @@ -4398,7 +4404,7 @@ function zot_feed($uid,$observer_xchan,$arr) { $r = q("SELECT parent, created from item WHERE uid = %d AND item_restrict = 0 AND (item_flags & %d) > 0 - $sql_extra GROUP BY parent ORDER BY created ASC $limit", + $sql_extra GROUP BY parent, created ORDER BY created ASC $limit", intval($uid), intval(ITEM_WALL) ); -- cgit v1.2.3 From 76a6739b93c1c8f08dd95a45235dd89fb4c507af Mon Sep 17 00:00:00 2001 From: friendica Date: Sat, 28 Mar 2015 18:47:28 -0700 Subject: remove bogus grouping from fix for #938 --- include/items.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/items.php b/include/items.php index 4246dd41f..ef269b9c4 100755 --- a/include/items.php +++ b/include/items.php @@ -4395,7 +4395,7 @@ function zot_feed($uid,$observer_xchan,$arr) { WHERE uid != %d AND item_private = 0 AND item_restrict = 0 AND uid in (" . stream_perms_api_uids(PERMS_PUBLIC,10,1) . ") AND (item_flags & %d) > 0 - $sql_extra GROUP BY parent, created ORDER BY created ASC $limit", + $sql_extra GROUP BY parent ORDER BY created ASC $limit", intval($uid), intval(ITEM_WALL) ); @@ -4404,7 +4404,7 @@ function zot_feed($uid,$observer_xchan,$arr) { $r = q("SELECT parent, created from item WHERE uid = %d AND item_restrict = 0 AND (item_flags & %d) > 0 - $sql_extra GROUP BY parent, created ORDER BY created ASC $limit", + $sql_extra GROUP BY parent ORDER BY created ASC $limit", intval($uid), intval(ITEM_WALL) ); -- cgit v1.2.3 From 42c820029e3680a4c3d4c882b1859f4af582ac36 Mon Sep 17 00:00:00 2001 From: Klaus Weidenbach Date: Sun, 29 Mar 2015 21:13:00 +0200 Subject: Fixed two wrong variable usages in event.php. I just checked the code, not the functionality. --- include/event.php | 123 +++++++++++++++++++++++++++++------------------------- 1 file changed, 65 insertions(+), 58 deletions(-) (limited to 'include') diff --git a/include/event.php b/include/event.php index 1ed541d99..05f01535c 100644 --- a/include/event.php +++ b/include/event.php @@ -1,6 +1,14 @@ -' . "\r\n"; - $o .= '

      ' . bbcode($ev['summary']) . '

      ' . "\r\n"; $o .= '

      ' . bbcode($ev['description']) . '

      ' . "\r\n"; $o .= '

      ' . t('Starts:') . ' ' . (($ev['adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(), $ev['start'] , $bd_format )) @@ -38,15 +45,15 @@ function format_event_html($ev) { if(strlen($ev['location'])) $o .= '

      ' . t('Location:') . ' ' - . bbcode($ev['location']) + . bbcode($ev['location']) . '

      ' . "\r\n"; $o .= '' . "\r\n"; + return $o; } - function ical_wrapper($ev) { if(! ((is_array($ev)) && count($ev))) @@ -56,7 +63,7 @@ function ical_wrapper($ev) { $o .= "\nVERSION:2.0"; $o .= "\nMETHOD:PUBLISH"; $o .= "\nPRODID:-//" . get_config('system','sitename') . "//" . RED_PLATFORM . "//" . strtoupper(get_app()->language). "\n"; - if(array_key_exists('start',$ev)) + if(array_key_exists('start', $ev)) $o .= format_event_ical($ev); else { foreach($ev as $e) { @@ -84,13 +91,15 @@ function format_event_ical($ev) { if($ev['description']) $o .= "\nDESCRIPTION:" . format_ical_text($ev['description']); $o .= "\nEND:VEVENT\n"; + return $o; } -function format_ical_text($s) { +function format_ical_text($s) { require_once('include/bbcode.php'); require_once('include/html2plain.php'); + return(wordwrap(html2plain(bbcode($s)),72,"\n ",true)); } @@ -117,16 +126,16 @@ function format_event_bbcode($ev) { if($ev['adjust']) $o .= '[event-adjust]' . $ev['adjust'] . '[/event-adjust]'; - return $o; - } + function bbtovcal($s) { $o = ''; $ev = bbtoevent($s); if($ev['description']) $o = format_event_html($ev); + return $o; } @@ -154,27 +163,41 @@ function bbtoevent($s) { if(preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is",$s,$match)) $ev['adjust'] = $match[1]; $ev['nofinish'] = (((x($ev, 'start') && $ev['start']) && (!x($ev, 'finish') || !$ev['finish'])) ? 1 : 0); - return $ev; + return $ev; } - +/** + * @brief Sorts the given array of events by date. + * + * @see ev_compare() + * @param array $arr + * @return sorted array + */ function sort_by_date($arr) { - if(is_array($arr)) - usort($arr,'ev_compare'); + if (is_array($arr)) + usort($arr, 'ev_compare'); + return $arr; } - -function ev_compare($a,$b) { +/** + * @brief Compare function for events. + * + * @see sort_by_date() + * @param array $a + * @param array $b + * @return number return values like strcmp() + */ +function ev_compare($a, $b) { $date_a = (($a['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$a['start']) : $a['start']); $date_b = (($b['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$b['start']) : $b['start']); - if($date_a === $date_b) - return strcasecmp($a['description'],$b['description']); - - return strcmp($date_a,$date_b); + if ($date_a === $date_b) + return strcasecmp($a['description'], $b['description']); + + return strcmp($date_a, $date_b); } @@ -182,11 +205,9 @@ function event_store_event($arr) { $arr['created'] = (($arr['created']) ? $arr['created'] : datetime_convert()); $arr['edited'] = (($arr['edited']) ? $arr['edited'] : datetime_convert()); - $arr['type'] = (($arr['type']) ? $arr['type'] : 'event' ); + $arr['type'] = (($arr['type']) ? $arr['type'] : 'event' ); $arr['event_xchan'] = (($arr['event_xchan']) ? $arr['event_xchan'] : ''); - - // Existing event being modified if($arr['id'] || $arr['event_hash']) { @@ -206,7 +227,6 @@ function event_store_event($arr) { ); } - if(! $r) return false; @@ -216,7 +236,7 @@ function event_store_event($arr) { } $hash = $r[0]['event_hash']; - + // The event changed. Update it. $r = q("UPDATE `event` SET @@ -251,14 +271,12 @@ function event_store_event($arr) { intval($r[0]['id']), intval($arr['uid']) ); - } - else { + } else { - // New event. Store it. + // New event. Store it. $hash = random_string(); - $r = q("INSERT INTO event ( uid,aid,event_xchan,event_hash,created,edited,start,finish,summary,description,location,type, adjust,nofinish,allow_cid,allow_gid,deny_cid,deny_gid) VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' ) ", @@ -280,7 +298,6 @@ function event_store_event($arr) { dbesc($arr['allow_gid']), dbesc($arr['deny_cid']), dbesc($arr['deny_gid']) - ); } @@ -292,7 +309,6 @@ function event_store_event($arr) { return $r[0]; return false; - } function event_addtocal($item_id, $uid) { @@ -339,22 +355,21 @@ function event_addtocal($item_id, $uid) { intval($item['id']), intval($channel['channel_id']) ); + return true; } } + return false; } - -function event_store_item($arr,$event) { +function event_store_item($arr, $event) { require_once('include/datetime.php'); require_once('include/items.php'); require_once('include/bbcode.php'); - $a = get_app(); - $item = null; if($arr['mid'] && $arr['uid']) { @@ -370,28 +385,28 @@ function event_store_item($arr,$event) { $item_arr = array(); $prefix = ''; - $birthday = false; +// $birthday = false; if($event['type'] === 'birthday') { $prefix = t('This event has been added to your calendar.'); - $birthday = true; +// $birthday = true; // The event is created on your own site by the system, but appears to belong // to the birthday person. It also isn't propagated - so we need to prevent // folks from trying to comment on it. If you're looking at this and trying to // fix it, you'll need to completely change the way birthday events are created - // and send them out from the source. This has its own issues. + // and send them out from the source. This has its own issues. $item_arr['comment_policy'] = 'none'; } $r = q("SELECT * FROM item left join xchan on author_xchan = xchan_hash WHERE resource_id = '%s' AND resource_type = 'event' and uid = %d LIMIT 1", - dbesc($event['event_hash']), + dbesc($event['event_hash']), intval($arr['uid']) ); if($r) { - $obj = json_encode(array( + $object = json_encode(array( 'type' => ACTIVITY_OBJ_EVENT, 'id' => z_root() . '/event/' . $r[0]['resource_id'], 'title' => $arr['summary'], @@ -424,8 +439,7 @@ function event_store_item($arr,$event) { intval($arr['uid']) ); - - $s = q("delete from term where oid = %d and otype = %d", + q("delete from term where oid = %d and otype = %d", intval($r[0]['id']), intval(TERM_OBJ_POST) ); @@ -442,21 +456,19 @@ function event_store_item($arr,$event) { dbesc($t['url']) ); } - } + } $item_id = $r[0]['id']; call_hooks('event_updated', $event['id']); + return $item_id; - } - else { + } else { $z = q("select * from channel where channel_id = %d limit 1", intval($arr['uid']) ); - $private = (($arr['allow_cid'] || $arr['allow_gid'] || $arr['deny_cid'] || $arr['deny_gid']) ? 1 : 0); - if($item) { $item_arr['id'] = $item['id']; @@ -469,8 +481,7 @@ function event_store_item($arr,$event) { $item_flags |= ITEM_WALL; $item_flags |= ITEM_ORIGIN; } - $item_arr['item_flags'] = $item_flags; - + $item_arr['item_flags'] = $item_flags; } if(! $arr['mid']) @@ -482,7 +493,6 @@ function event_store_item($arr,$event) { $item_arr['mid'] = $arr['mid']; $item_arr['parent_mid'] = $arr['mid']; - $item_arr['owner_xchan'] = (($wall) ? $z[0]['channel_hash'] : $arr['event_xchan']); $item_arr['author_xchan'] = $arr['event_xchan']; $item_arr['title'] = $arr['summary']; @@ -493,9 +503,8 @@ function event_store_item($arr,$event) { $item_arr['item_private'] = $private; $item_arr['verb'] = ACTIVITY_POST; - - if(array_key_exists('term',$arr)) - $item_arr['term'] = $arr['term']; + if(array_key_exists('term', $arr)) + $item_arr['term'] = $arr['term']; $item_arr['resource_type'] = 'event'; $item_arr['resource_id'] = $event['event_hash']; @@ -512,15 +521,13 @@ function event_store_item($arr,$event) { else $item_arr['plink'] = z_root() . '/display/' . $item_arr['mid']; - $x = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($arr['event_xchan']) ); if($x) { - $item_arr['object'] = json_encode(array( 'type' => ACTIVITY_OBJ_EVENT, - 'id' => z_root() . '/event/' . $hash, + 'id' => z_root() . '/event/' . $event['event_hash'], 'title' => $arr['summary'], 'content' => format_event_bbcode($arr), 'author' => array( @@ -539,7 +546,7 @@ function event_store_item($arr,$event) { $item_id = $res['item_id']; - call_hooks("event_created", $event['id']); + call_hooks('event_created', $event['id']); return $item_id; } -- cgit v1.2.3 From d0361582b0b620064aff90bf88f01d1072b308fe Mon Sep 17 00:00:00 2001 From: Klaus Weidenbach Date: Sun, 22 Mar 2015 00:06:08 +0100 Subject: Correcting reported Doxygen syntax warnings. Fixed wrong Doxygen syntax and add some of the available FIXME to Doxygen documentation. Updated Doxygen configuration to add also all capital letter tags. Adding some more Doxygen documentation. --- include/ITemplateEngine.php | 21 +- include/account.php | 91 +++-- include/attach.php | 116 +++--- include/comanche.php | 36 +- include/config.php | 29 +- include/conversation.php | 8 +- include/datetime.php | 452 +++++++++++---------- include/dir_fns.php | 212 +++++----- include/directory.php | 30 +- include/enotify.php | 196 +++++----- include/expire.php | 59 ++- include/identity.php | 427 ++++++++++---------- include/items.php | 862 +++++++++++++++++++---------------------- include/language.php | 93 +++-- include/network.php | 99 +++-- include/permissions.php | 28 +- include/photos.php | 117 +++--- include/plugin.php | 44 ++- include/template_processor.php | 540 +++++++++++++------------- include/text.php | 331 +++++++++------- include/zot.php | 793 ++++++++++++++++++------------------- 21 files changed, 2318 insertions(+), 2266 deletions(-) (limited to 'include') diff --git a/include/ITemplateEngine.php b/include/ITemplateEngine.php index 53c1845f4..7bd559a63 100755 --- a/include/ITemplateEngine.php +++ b/include/ITemplateEngine.php @@ -1,11 +1,10 @@ - false, 'message' => ''); - // The only validation we perform by default is pure Javascript to + // The only validation we perform by default is pure Javascript to // check minimum length and that both entered passwords match. - // Use hooked functions to perform complexity requirement checks. + // Use hooked functions to perform complexity requirement checks. $arr = array('password' => $password, 'result' => $result); call_hooks('check_account_password', $arr); return $arr['result']; - } function check_account_invite($invite_code) { @@ -75,7 +78,6 @@ function check_account_invite($invite_code) { call_hooks('check_account_invite', $arr); return $arr['result']; - } function check_account_admin($arr) { @@ -109,7 +111,7 @@ function create_account($arr) { $flags = ((x($arr,'account_flags')) ? intval($arr['account_flags']) : ACCOUNT_OK); $roles = ((x($arr,'account_roles')) ? intval($arr['account_roles']) : 0 ); $expires = ((x($arr,'expires')) ? intval($arr['expires']) : NULL_DATE); - + $default_service_class = get_config('system','default_service_class'); if($default_service_class === false) @@ -132,16 +134,16 @@ function create_account($arr) { // allow the admin_email account to be admin, but only if it's the first account. $c = account_total(); - if(($c === 0) && (check_account_admin($arr))) + if (($c === 0) && (check_account_admin($arr))) $roles |= ACCOUNT_ROLE_ADMIN; - // Ensure that there is a host keypair. + // Ensure that there is a host keypair. - if((! get_config('system','pubkey')) && (! get_config('system','prvkey'))) { - $hostkey = new_keypair(4096); - set_config('system','pubkey',$hostkey['pubkey']); - set_config('system','prvkey',$hostkey['prvkey']); - } + if ((! get_config('system', 'pubkey')) && (! get_config('system', 'prvkey'))) { + $hostkey = new_keypair(4096); + set_config('system', 'pubkey', $hostkey['pubkey']); + set_config('system', 'prvkey', $hostkey['prvkey']); + } $invite_result = check_account_invite($invite_code); if($invite_result['error']) { @@ -180,7 +182,6 @@ function create_account($arr) { dbesc($roles), dbesc($expires), dbesc($default_service_class) - ); if(! $r) { logger('create_account: DB INSERT failed.'); @@ -195,7 +196,7 @@ function create_account($arr) { if($r && count($r)) { $result['account'] = $r[0]; } - else { + else { logger('create_account: could not retrieve newly created account'); } @@ -215,8 +216,8 @@ function create_account($arr) { $result['success'] = true; $result['email'] = $email; $result['password'] = $password; - return $result; + return $result; } @@ -255,7 +256,6 @@ function verify_email_address($arr) { logger('send_reg_approval_email: failed to ' . $admin['email'] . 'account_id: ' . $arr['account']['account_id']); return $res; - } @@ -292,7 +292,6 @@ function send_reg_approval_email($arr) { $details = (($ip) ? $ip . ' [' . gethostbyaddr($ip) . ']' : '[unknown or stealth IP]'); - $delivered = 0; foreach($admins as $admin) { @@ -346,11 +345,14 @@ function send_verification_email($email,$password) { return($res ? true : false); } - +/** + * @brief Allows a user registration. + * + * @param string $hash + * @return array|boolean + */ function user_allow($hash) { - $a = get_app(); - $ret = array('success' => false); $register = q("SELECT * FROM `register` WHERE `hash` = '%s' LIMIT 1", @@ -363,7 +365,7 @@ function user_allow($hash) { $account = q("SELECT * FROM account WHERE account_id = %d LIMIT 1", intval($register[0]['uid']) ); - + if(! $account) return $ret; @@ -381,7 +383,7 @@ function user_allow($hash) { intval(ACCOUNT_PENDING), intval($register[0]['uid']) ); - + push_lang($register[0]['language']); $email_tpl = get_intltext_template("register_open_eml.tpl"); @@ -402,18 +404,23 @@ function user_allow($hash) { pop_lang(); - if($res) { + if ($res) { info( t('Account approved.') . EOL ); return true; - } - + } } -// This does not have to go through user_remove() and save the nickname -// permanently against re-registration, as the person was not yet -// allowed to have friends on this system - +/** + * @brief Denies a user registration. + * + * This does not have to go through user_remove() and save the nickname + * permanently against re-registration, as the person was not yet + * allowed to have friends on this system + * + * @param string $hash + * @return boolean + */ function user_deny($hash) { $register = q("SELECT * FROM register WHERE hash = '%s' LIMIT 1", @@ -426,7 +433,7 @@ function user_deny($hash) { $account = q("SELECT account_id, account_email FROM account WHERE account_id = %d LIMIT 1", intval($register[0]['uid']) ); - + if(! $account) return false; @@ -438,15 +445,14 @@ function user_deny($hash) { dbesc($register[0]['id']) ); notice( sprintf(t('Registration revoked for %s'), $account[0]['account_email']) . EOL); + return true; - + } function user_approve($hash) { - $a = get_app(); - $ret = array('success' => false); $register = q("SELECT * FROM `register` WHERE `hash` = '%s' and password = 'verify' LIMIT 1", @@ -459,7 +465,7 @@ function user_approve($hash) { $account = q("SELECT * FROM account WHERE account_id = %d LIMIT 1", intval($register[0]['uid']) ); - + if(! $account) return $ret; @@ -482,21 +488,16 @@ function user_approve($hash) { intval(ACCOUNT_UNVERIFIED), intval($register[0]['uid']) ); - + info( t('Account verified. Please login.') . EOL ); return true; - } - - - - /** - * @function downgrade_accounts() - * Checks for accounts that have past their expiration date. + * @brief Checks for accounts that have past their expiration date. + * * If the account has a service class which is not the site default, * the service class is reset to the site default and expiration reset to never. * If the account has no service class it is expired and subsequently disabled. @@ -506,8 +507,6 @@ function user_approve($hash) { * not the job of this function, but this can be implemented by plugin if desired. * Default behaviour is to stop allowing additional resources to be consumed. */ - - function downgrade_accounts() { $r = q("select * from account where not ( account_flags & %d )>0 @@ -604,7 +603,7 @@ function service_class_allows($uid, $property, $usage = false) { * * @param int $aid The account_id to check * @param string $property The service class property to check for - * @param int|boolean $usage, (optional) The value to check against + * @param int|boolean $usage (optional) The value to check against * @return boolean */ function account_service_class_allows($aid, $property, $usage = false) { diff --git a/include/attach.php b/include/attach.php index 2ca302949..560313d8b 100644 --- a/include/attach.php +++ b/include/attach.php @@ -1,10 +1,10 @@ false); - if(! perm_is_allowed($channel_id,$observer, 'read_storage')) { + if(! perm_is_allowed($channel_id, $observer, 'read_storage')) { $ret['message'] = t('Permission denied.'); return $ret; } @@ -219,8 +218,9 @@ function attach_list_files($channel_id, $observer, $hash = '', $filename = '', $ * * This could exhaust memory so most useful only when immediately sending the data. * - * @param $hash - * @param $rev + * @param string $hash + * @param int $rev Revision + * @return array */ function attach_by_hash($hash, $rev = 0) { @@ -234,7 +234,6 @@ function attach_by_hash($hash, $rev = 0) { elseif($rev) $sql_extra = " and revision = " . intval($rev) . " "; - $r = q("SELECT uid FROM attach WHERE hash = '%s' $sql_extra LIMIT 1", dbesc($hash) ); @@ -270,9 +269,9 @@ function attach_by_hash($hash, $rev = 0) { /** * @brief Find an attachment by hash and revision. - * + * * Returns the entire attach structure excluding data. - * + * * @see attach_by_hash() * @param $hash * @param $rev revision default 0 @@ -561,7 +560,7 @@ function z_readdir($channel_id, $observer_hash, $pathname, $parent_hash = '') { } else $paths = array($pathname); - + $r = q("select id, aid, uid, hash, creator, filename, filetype, filesize, revision, folder, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid from attach where id = %d and folder = '%s' and filename = '%s' and (flags & %d )>0 " . permissions_sql($channel_id), intval($channel_id), dbesc($parent_hash), @@ -579,24 +578,22 @@ function z_readdir($channel_id, $observer_hash, $pathname, $parent_hash = '') { } /** - * @function attach_mkdir($channel,$observer_hash,$arr); - * * @brief Create directory. * * @param array $channel channel array of owner * @param string $observer_hash hash of current observer * @param array $arr parameter array to fulfil request - * Required: - * $arr['filename'] - * $arr['folder'] // hash of parent directory, empty string for root directory - * Optional: - * $arr['hash'] // precumputed hash for this node - * $arr['allow_cid'] - * $arr['allow_gid'] - * $arr['deny_cid'] - * $arr['deny_gid'] + * - Required: + * * \e string \b filename + * * \e string \b folder hash of parent directory, empty string for root directory + * - Optional: + * * \e string \b hash precumputed hash for this node + * * \e tring \b allow_cid + * * \e string \b allow_gid + * * \e string \b deny_cid + * * \e string \b deny_gid + * @return array */ - function attach_mkdir($channel, $observer_hash, $arr = null) { $ret = array('success' => false); @@ -720,13 +717,13 @@ function attach_mkdir($channel, $observer_hash, $arr = null) { /** * @brief Changes permissions of a file. * - * @param $channel_id - * @param $resource - * @param $allow_cid - * @param $allow_gid - * @param $deny_cid - * @param $deny_gid - * @param $recurse + * @param int $channel_id + * @param array $resource + * @param string $allow_cid + * @param string $allow_gid + * @param string $deny_cid + * @param string $deny_gid + * @param boolean $recurse (optional) default false */ function attach_change_permissions($channel_id, $resource, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $recurse = false) { @@ -836,7 +833,6 @@ function attach_delete($channel_id, $resource) { ); file_activity($channel_id, $object, $object['allow_cid'], $object['allow_gid'], $object['deny_cid'], $object['deny_gid'], 'update', $no_activity=false); - } /** @@ -844,8 +840,8 @@ function attach_delete($channel_id, $resource) { * * @warning This function cannot be used with mod/dav as it always returns a * path valid under mod/cloud. - * - * @param array assoziative array with: + * + * @param array $arr assoziative array with: * * \e int \b uid the channel's uid * * \e string \b folder * * \e string \b filename @@ -973,20 +969,21 @@ function pipe_streams($in, $out) { $size = 0; while (!feof($in)) $size += fwrite($out, fread($in, 8192)); + return $size; } /** - * @brief Activity for files + * @brief Activity for files. * - * @param $channel_id - * @param $object - * @param $allow_cid - * @param $allow_gid - * @param $deny_cid - * @param $deny_gid - * @param $verb - * @param $no_activity + * @param int $channel_id + * @param array $object + * @param string $allow_cid + * @param string $allow_gid + * @param string $deny_cid + * @param string $deny_gid + * @param string $verb + * @param boolean $no_activity */ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $verb, $no_activity) { @@ -1028,7 +1025,6 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, //filter out receivers which do not have permission to view filestorage $arr_allow_cid = check_list_permissions($channel_id, $arr_allow_cid, 'view_storage'); - } $mid = item_message_id(); @@ -1109,7 +1105,6 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $update = false; //notice( t('File activity updated') . EOL); - } if($no_activity) { @@ -1152,15 +1147,14 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, //(($verb === 'post') ? notice( t('File activity posted') . EOL) : notice( t('File activity dropped') . EOL)); return; - } /** * @brief Create file activity object * - * @param $channel_id - * @param $hash - * @param $cloudpath + * @param int $channel_id + * @param string $hash + * @param string $cloudpath */ function get_file_activity_object($channel_id, $hash, $cloudpath) { @@ -1199,8 +1193,8 @@ function get_file_activity_object($channel_id, $hash, $cloudpath) { 'deny_cid' => $x[0]['deny_cid'], 'deny_gid' => $x[0]['deny_gid'] ); - return $object; + return $object; } /** diff --git a/include/comanche.php b/include/comanche.php index 71ffe99b8..62bfd0ddc 100644 --- a/include/comanche.php +++ b/include/comanche.php @@ -101,7 +101,7 @@ function comanche_parser(&$a, $s, $pass = 0) { } -function comanche_menu($name,$class = '') { +function comanche_menu($name, $class = '') { $channel_id = comanche_get_channel_id(); if($channel_id) { $m = menu_fetch($name,$channel_id, get_observer_hash()); @@ -111,20 +111,23 @@ function comanche_menu($name,$class = '') { function comanche_replace_region($match) { $a = get_app(); - if(array_key_exists($match[1], $a->page)) { + if (array_key_exists($match[1], $a->page)) { return $a->page[$match[1]]; } } /** - * @function comanche_get_channel_id() - * Returns the channel_id of the profile owner of the page, or the local_channel if there is no profile owner. - * Otherwise returns 0 - */ - + * @brief Returns the channel_id of the profile owner of the page. + * + * Returns the channel_id of the profile owner of the page, or the local_channel + * if there is no profile owner. Otherwise returns 0. + * + * @return channel_id + */ function comanche_get_channel_id() { $channel_id = ((is_array(get_app()->profile)) ? get_app()->profile['profile_uid'] : 0); - if((! $channel_id) && (local_channel())) + + if ((! $channel_id) && (local_channel())) $channel_id = local_channel(); return $channel_id; @@ -173,23 +176,26 @@ function comanche_webpage(&$a,$s) { } -// Widgets will have to get any operational arguments from the session, -// the global app environment, or config storage until we implement argument passing - - +/** + * Widgets will have to get any operational arguments from the session, the + * global app environment, or config storage until we implement argument passing + * + * @param string $name + * @param string $text + */ function comanche_widget($name, $text) { $vars = array(); $matches = array(); $cnt = preg_match_all("/\[var=(.*?)\](.*?)\[\/var\]/ism", $text, $matches, PREG_SET_ORDER); - if($cnt) { - foreach($matches as $mtch) { + if ($cnt) { + foreach ($matches as $mtch) { $vars[$mtch[1]] = $mtch[2]; } } $func = 'widget_' . trim($name); - if(function_exists($func)) + if (function_exists($func)) return $func($vars); } diff --git a/include/config.php b/include/config.php index b459e2c7d..c94d25eb8 100644 --- a/include/config.php +++ b/include/config.php @@ -3,8 +3,7 @@ * @file include/config.php * @brief Arbitrary configuration storage. * - * Note: - * Please do not store booleans - convert to 0/1 integer values + * @note Please do not store booleans - convert to 0/1 integer values. * The get_?config() functions return boolean false for keys that are unset, * and this could lead to subtle bugs. * @@ -18,19 +17,20 @@ * - pconfig is used for channel specific configurations and takes a * channel_id as identifier. It stores for example which features are * enabled per channel. The storage is of size MEDIUMTEXT. - * @code $var = get_pconfig(local_channel(), 'category', 'key');@endcode + * @code{.php} $var = get_pconfig(local_channel(), 'category', 'key');@endcode * - xconfig is the same as pconfig, except that it uses xchan as * an identifier. This is for example for people who do not have a local account. * The storage is of size MEDIUMTEXT. - * @code $observer = $a->get_observer_hash(); + * @code{.php} + * $observer = $a->get_observer_hash(); * if ($observer) { * $var = get_xconfig($observer, 'category', 'key'); * }@endcode * * - get_config() and set_config() can also be done through the command line tool - * @ref util/config + * @ref util/config.md "util/config" * - get_pconfig() and set_pconfig() can also be done through the command line tool - * @ref util/pconfig and takes a channel_id as first argument. + * @ref util/pconfig.md "util/pconfig" and takes a channel_id as first argument. * */ @@ -123,7 +123,7 @@ function get_config_from_storage($family, $key) { * * Stores a config value ($value) in the category ($family) under the key ($key). * - * Please do not store booleans - convert to 0/1 integer values! + * @note Please do not store booleans - convert to 0/1 integer values! * * @param string $family * The category of the configuration value @@ -272,14 +272,16 @@ function get_pconfig($uid, $family, $key, $instore = false) { * Stores a config value ($value) in the category ($family) under the key ($key) * for the channel_id $uid. * - * Please do not store booleans - convert to 0/1 integer values! + * @note Please do not store booleans - convert to 0/1 integer values! * * @param string $uid * The channel_id * @param string $family * The category of the configuration value * @param string $key - * The configuration key to query + * The configuration key to set + * @param string $value + * The value to store * @return mixed Stored $value or false */ function set_pconfig($uid, $family, $key, $value) { @@ -315,6 +317,7 @@ function set_pconfig($uid, $family, $key, $value) { ); if($ret) return $value; + return $ret; } @@ -339,6 +342,7 @@ function set_pconfig($uid, $family, $key, $value) { if($ret) return $value; + return $ret; } @@ -360,13 +364,14 @@ function del_pconfig($uid, $family, $key) { global $a; $ret = false; - if(x($a->config[$uid][$family], $key)) + if (x($a->config[$uid][$family], $key)) unset($a->config[$uid][$family][$key]); $ret = q("DELETE FROM pconfig WHERE uid = %d AND cat = '%s' AND k = '%s'", intval($uid), dbesc($family), dbesc($key) ); + return $ret; } @@ -448,7 +453,7 @@ function get_xconfig($xchan, $family, $key) { * Stores a config value ($value) in the category ($family) under the key ($key) * for the observer's $xchan hash. * - * Please do not store booleans - convert to 0/1 integer values! + * @note Please do not store booleans - convert to 0/1 integer values! * * @param string $xchan * The observer's hash @@ -456,6 +461,8 @@ function get_xconfig($xchan, $family, $key) { * The category of the configuration value * @param string $key * The configuration key to set + * @param string $value + * The value to store * @return mixed Stored $value or false */ function set_xconfig($xchan, $family, $key, $value) { diff --git a/include/conversation.php b/include/conversation.php index 4018ced28..042d01b3e 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -1044,7 +1044,6 @@ function builtin_activity_puller($item, &$conv_responses) { return; } } - } @@ -1053,7 +1052,7 @@ function builtin_activity_puller($item, &$conv_responses) { * * @param int $cnt number of people who like/dislike the item * @param array $arr array of pre-linked names of likers/dislikers - * @param string $typ eone of 'like, 'dislike' + * @param string $type one of 'like, 'dislike' * @param int $id item id * @return string formatted text */ @@ -1146,7 +1145,6 @@ function status_editor($a, $x, $popup = false) { '$expireswhen' => t('Expires YYYY-MM-DD HH:MM') )); - $tpl = get_markup_template('jot.tpl'); $jotplugins = ''; @@ -1461,8 +1459,8 @@ function network_tabs() { if ($no_active=='active' && x($_GET,'order')) { switch($_GET['order']){ - case 'post': $postord_active = 'active'; $no_active=''; break; - case 'comment' : $all_active = 'active'; $no_active=''; break; + case 'post': $postord_active = 'active'; $no_active=''; break; + case 'comment' : $all_active = 'active'; $no_active=''; break; } } diff --git a/include/datetime.php b/include/datetime.php index 5cab5889d..b0167edb2 100644 --- a/include/datetime.php +++ b/include/datetime.php @@ -1,54 +1,71 @@ - 1) { + if (count($ex) > 1) { $continent = t($ex[0]); - if(count($ex) > 2) - $city = substr($value,strpos($value,'/')+1); + if (count($ex) > 2) + $city = substr($value, strpos($value, '/')+1); else $city = $ex[1]; - } - else { + } else { $city = $ex[0]; $continent = t('Miscellaneous'); } $city = str_replace('_', ' ', t($city)); - if(!x($continents,$ex[0])) $continents[$ex[0]] = array(); + if (!x($continents, $ex[0])) $continents[$ex[0]] = array(); $continents[$continent][$value] = $city; } + return $continents; } -// General purpose date parse/convert function. -// $from = source timezone -// $to = dest timezone -// $s = some parseable date/time string -// $fmt = output format - - +/** + * @brief General purpose date parse/convert function. + * + * @param string $from source timezone + * @param string $to dest timezone + * @param string $s some parseable date/time string + * @param string $fmt output format recognised from php's DateTime class + * http://www.php.net/manual/en/datetime.format.php + * @return string + */ function datetime_convert($from = 'UTC', $to = 'UTC', $s = 'now', $fmt = "Y-m-d H:i:s") { // Defaults to UTC if nothing is set, but throws an exception if set to empty string. @@ -68,44 +85,46 @@ function datetime_convert($from = 'UTC', $to = 'UTC', $s = 'now', $fmt = "Y-m-d if(substr($s,0,10) == '0000-00-00') { $d = new DateTime($s . ' + 32 days', new DateTimeZone('UTC')); - return str_replace('1','0',$d->format($fmt)); + return str_replace('1', '0', $d->format($fmt)); } try { $from_obj = new DateTimeZone($from); - } - catch(Exception $e) { + } catch(Exception $e) { $from_obj = new DateTimeZone('UTC'); } try { $d = new DateTime($s, $from_obj); - } - catch(Exception $e) { + } catch(Exception $e) { logger('datetime_convert: exception: ' . $e->getMessage()); $d = new DateTime('now', $from_obj); } try { $to_obj = new DateTimeZone($to); - } - catch(Exception $e) { + } catch(Exception $e) { $to_obj = new DateTimeZone('UTC'); } $d->setTimeZone($to_obj); + return($d->format($fmt)); } -// wrapper for date selector, tailored for use in birthday fields - +/** + * @brief Wrapper for date selector, tailored for use in birthday fields. + * + * @param string $dob Date of Birth + * @return string + */ function dob($dob) { - list($year,$month,$day) = sscanf($dob,'%4d-%2d-%2d'); - $f = get_config('system','birthday_input_format'); - if(! $f) + list($year, $month, $day) = sscanf($dob, '%4d-%2d-%2d'); + $f = get_config('system', 'birthday_input_format'); + if (! $f) $f = 'ymd'; - if($dob === '0000-00-00') + if ($dob === '0000-00-00') $value = ''; else $value = (($year) ? datetime_convert('UTC','UTC',$dob,'Y-m-d') : datetime_convert('UTC','UTC',$dob,'m-d')); @@ -120,7 +139,6 @@ function dob($dob) { return $o; } - /** * returns a date selector * @param $format @@ -135,7 +153,7 @@ function dob($dob) { * id and name of datetimepicker (defaults to "datetimepicker") */ function datesel($format, $min, $max, $default, $id = 'datepicker') { - return datetimesel($format,$min,$max,$default,$id,true,false, '',''); + return datetimesel($format, $min, $max, $default, $id,true, false, '', ''); } /** @@ -154,7 +172,8 @@ function timesel($format, $h, $m, $id='timepicker') { } /** - * returns a datetime selector + * @brief Returns a datetime selector. + * * @param $format * format string, e.g. 'ymd' or 'mdy'. Not currently supported * @param $min @@ -163,23 +182,25 @@ function timesel($format, $h, $m, $id='timepicker') { * unix timestap of maximum date * @param $default * unix timestamp of default date - * @param $id + * @param string $id * id and name of datetimepicker (defaults to "datetimepicker") - * @param $pickdate + * @param boolean $pickdate * true to show date picker (default) - * @param $picktime + * @param boolean $picktime * true to show time picker (default) * @param $minfrom * set minimum date from picker with id $minfrom (none by default) * @param $maxfrom * set maximum date from picker with id $maxfrom (none by default) + * @param boolean $required default false + * @return string Parsed HTML output. + * + * @todo Once browser support is better this could probably be replaced with + * native HTML5 date picker. */ -function datetimesel($format, $min, $max, $default, $id = 'datetimepicker', $pickdate = true, $picktime = true, $minfrom = '', $maxfrom = '',$required = false) { +function datetimesel($format, $min, $max, $default, $id = 'datetimepicker', $pickdate = true, $picktime = true, $minfrom = '', $maxfrom = '', $required = false) { - - // Once browser support is better this could probably be replaced with native HTML5 date picker $o = ''; - $dateformat = ''; if($pickdate) $dateformat .= 'Y-m-d'; @@ -188,7 +209,7 @@ function datetimesel($format, $min, $max, $default, $id = 'datetimepicker', $pic $minjs = $min ? ",minDate: new Date({$min->getTimestamp()}*1000), yearStart: " . $min->format('Y') : ''; $maxjs = $max ? ",maxDate: new Date({$max->getTimestamp()}*1000), yearEnd: " . $max->format('Y') : ''; - + $input_text = $default ? 'value="' . date($dateformat, $default->getTimestamp()) . '"' : ''; $defaultdatejs = $default ? ",defaultDate: new Date({$default->getTimestamp()}*1000)" : ''; @@ -214,31 +235,39 @@ function datetimesel($format, $min, $max, $default, $id = 'datetimepicker', $pic $o .= (($required) ? '*' : ''); $o .= ''; $o .= ""; + return $o; } -// implements "3 seconds ago" etc. -// based on $posted_date, (UTC). -// Results relative to current timezone -// Limited to range of timestamps - - -function relative_date($posted_date,$format = null) { +/** + * @brief Returns a relative date string. + * + * Implements "3 seconds ago" etc. + * Based on $posted_date, (UTC). + * Results relative to current timezone. + * Limited to range of timestamps. + * + * @param string $posted_date + * @param string $format (optional) parsed with sprintf() + * %1$d %2$s ago, e.g. 22 hours ago, 1 minute ago + * @return string with relative date + */ +function relative_date($posted_date, $format = null) { - $localtime = datetime_convert('UTC',date_default_timezone_get(),$posted_date); + $localtime = datetime_convert('UTC', date_default_timezone_get(), $posted_date); $abs = strtotime($localtime); - - if (is_null($posted_date) || $posted_date === NULL_DATE || $abs === False) { - return t('never'); + + if (is_null($posted_date) || $posted_date === NULL_DATE || $abs === false) { + return t('never'); } $etime = time() - $abs; - + if ($etime < 1) { return t('less than a second ago'); } - + $a = array( 12 * 30 * 24 * 60 * 60 => array( t('year'), t('years')), 30 * 24 * 60 * 60 => array( t('month'), t('months')), 7 * 24 * 60 * 60 => array( t('week'), t('weeks')), @@ -247,231 +276,256 @@ function relative_date($posted_date,$format = null) { 60 => array( t('minute'), t('minutes')), 1 => array( t('second'), t('seconds')) ); - + foreach ($a as $secs => $str) { $d = $etime / $secs; if ($d >= 1) { $r = round($d); - // translators - e.g. 22 hours ago, 1 minute ago - if(! $format) - $format = t('%1$d %2$s ago'); - return sprintf( $format,$r, (($r == 1) ? $str[0] : $str[1])); - } - } -} - + if (! $format) + $format = t('%1$d %2$s ago', 'e.g. 22 hours ago, 1 minute ago'); + return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1])); + } + } +} -// Returns age in years, given a date of birth, -// the timezone of the person whose date of birth is provided, -// and the timezone of the person viewing the result. -// Why? Bear with me. Let's say I live in Mittagong, Australia, and my -// birthday is on New Year's. You live in San Bruno, California. -// When exactly are you going to see my age increase? -// A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start -// celebrating and become a year older. If you wish me happy birthday -// on January 1 (San Bruno time), you'll be a day late. - -function age($dob,$owner_tz = '',$viewer_tz = '') { - if(! intval($dob)) +/** + * @brief Returns timezone correct age in years. + * + * Returns the age in years, given a date of birth, the timezone of the person + * whose date of birth is provided, and the timezone of the person viewing the + * result. + * + * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday + * is on New Year's. You live in San Bruno, California. + * When exactly are you going to see my age increase? + * + * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating + * and become a year older. If you wish me happy birthday on January 1 + * (San Bruno time), you'll be a day late. + * + * @param string $dob Date of Birth + * @param string $owner_tz (optional) timezone of the person of interest + * @param string $viewer_tz (optional) timezone of the person viewing + * @return number + */ +function age($dob, $owner_tz = '', $viewer_tz = '') { + if (! intval($dob)) return 0; - if(! $owner_tz) + if (! $owner_tz) $owner_tz = date_default_timezone_get(); - if(! $viewer_tz) + if (! $viewer_tz) $viewer_tz = date_default_timezone_get(); - $birthdate = datetime_convert('UTC',$owner_tz,$dob . ' 00:00:00+00:00','Y-m-d'); - list($year,$month,$day) = explode("-",$birthdate); - $year_diff = datetime_convert('UTC',$viewer_tz,'now','Y') - $year; - $curr_month = datetime_convert('UTC',$viewer_tz,'now','m'); - $curr_day = datetime_convert('UTC',$viewer_tz,'now','d'); + $birthdate = datetime_convert('UTC', $owner_tz, $dob . ' 00:00:00+00:00','Y-m-d'); + list($year,$month,$day) = explode("-", $birthdate); + $year_diff = datetime_convert('UTC', $viewer_tz, 'now', 'Y') - $year; + $curr_month = datetime_convert('UTC', $viewer_tz, 'now', 'm'); + $curr_day = datetime_convert('UTC', $viewer_tz, 'now', 'd'); - if(($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) + if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) $year_diff--; + return $year_diff; } +/** + * @brief Get days of a month in a given year. + * + * Returns number of days in the month of the given year. + * $m = 1 is 'January' to match human usage. + * + * @param int $y year + * @param int $m month (1=January, 12=December) + * @return int number of days in the given month + */ +function get_dim($y, $m) { + $dim = array( 0, + 31, 28, 31, 30, 31, 30, + 31, 31, 30, 31, 30, 31 + ); + if ($m != 2) + return $dim[$m]; -// Get days in month -// get_dim($year, $month); -// returns number of days. -// $month[1] = 'January'; -// to match human usage. - - -function get_dim($y,$m) { + if (((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0)) + return 29; - $dim = array( 0, - 31, 28, 31, 30, 31, 30, - 31, 31, 30, 31, 30, 31); - - if($m != 2) - return $dim[$m]; - if(((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0)) - return 29; - return $dim[2]; + return $dim[2]; } +/** + * @brief Returns the first day in month for a given month, year. + * + * Months start at 1. + * + * @param int $y Year + * @param int $m Month (1=January, 12=December) + * @return day 0 = Sunday through 6 = Saturday + */ +function get_first_dim($y, $m) { + $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m)); -// Returns the first day in month for a given month, year -// get_first_dim($year,$month) -// returns 0 = Sunday through 6 = Saturday -// Months start at 1. - - -function get_first_dim($y,$m) { - $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m)); - return datetime_convert('UTC','UTC',$d,'w'); + return datetime_convert('UTC', 'UTC', $d, 'w'); } -// output a calendar for the given month, year. -// if $links are provided (array), e.g. $links[12] => 'http://mylink' , -// date 12 will be linked appropriately. Today's date is also noted by -// altering td class. -// Months count from 1. - - -// TODO: provide (prev,next) links, define class variations for different size calendars - -function cal($y = 0,$m = 0, $links = false, $class='') { - +/** + * @brief Output a calendar for the given month, year. + * + * If $links are provided (array), e.g. $links[12] => 'http://mylink' , + * date 12 will be linked appropriately. Today's date is also noted by + * altering td class. + * Months count from 1. + * + * @param number $y Year + * @param number $m Month + * @param string $links (default false) + * @param string $class + * @return string + * + * @todo provide (prev,next) links, define class variations for different size calendars + */ +function cal($y = 0, $m = 0, $links = false, $class='') { // month table - start at 1 to match human usage. $mtab = array(' ', - 'January','February','March', - 'April','May','June', - 'July','August','September', - 'October','November','December' - ); + 'January','February','March', + 'April','May','June', + 'July','August','September', + 'October','November','December' + ); $thisyear = datetime_convert('UTC',date_default_timezone_get(),'now','Y'); $thismonth = datetime_convert('UTC',date_default_timezone_get(),'now','m'); - if(! $y) + if (! $y) $y = $thisyear; - if(! $m) + if (! $m) $m = intval($thismonth); - $dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); - $f = get_first_dim($y,$m); - $l = get_dim($y,$m); - $d = 1; - $dow = 0; - $started = false; + $dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); + $f = get_first_dim($y, $m); + $l = get_dim($y, $m); + $d = 1; + $dow = 0; + $started = false; - if(($y == $thisyear) && ($m == $thismonth)) - $tddate = intval(datetime_convert('UTC',date_default_timezone_get(),'now','j')); + if (($y == $thisyear) && ($m == $thismonth)) + $tddate = intval(datetime_convert('UTC',date_default_timezone_get(),'now','j')); $str_month = day_translate($mtab[$m]); - $o = ''; - $o .= ""; - for($a = 0; $a < 7; $a ++) - $o .= ''; - $o .= ''; - - while($d <= $l) { - if(($dow == $f) && (! $started)) - $started = true; - $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : ''); - $o .= "'; - $dow ++; - if(($dow == 7) && ($d <= $l)) { - $dow = 0; - $o .= ''; - } - } - if($dow) - for($a = $dow; $a < 7; $a ++) - $o .= ''; - $o .= '
      $str_month $y
      ' . mb_substr(day_translate($dn[$a]),0,3,'UTF-8') . '
      "; - $day = str_replace(' ',' ',sprintf('%2.2d', $d)); - if($started) { - if(is_array($links) && isset($links[$d])) - $o .= "$day"; - else - $o .= $day; - $d ++; - } - else - $o .= ' '; - $o .= '
       
      '."\r\n"; - - return $o; -} + $o = ''; + $o .= ""; + for ($a = 0; $a < 7; $a ++) + $o .= ''; + + $o .= ''; + + while ($d <= $l) { + if (($dow == $f) && (! $started)) + $started = true; + + $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : ''); + $o .= "'; + $dow ++; + if (($dow == 7) && ($d <= $l)) { + $dow = 0; + $o .= ''; + } + } + if ($dow) + for ($a = $dow; $a < 7; $a ++) + $o .= ''; + + $o .= '
      $str_month $y
      ' . mb_substr(day_translate($dn[$a]),0,3,'UTF-8') . '
      "; + $day = str_replace(' ',' ',sprintf('%2.2d', $d)); + if ($started) { + if (is_array($links) && isset($links[$d])) + $o .= "$day"; + else + $o .= $day; + + $d ++; + } else { + $o .= ' '; + } + + $o .= '
       
      '."\r\n"; + return $o; +} /** - * Return the next birthday, converted from the owner's timezone to UTC. + * @brief Return the next birthday, converted from the owner's timezone to UTC. + * * This makes it globally portable. * If the provided birthday lacks a month and or day, return an empty string. * A missing year is acceptable. + * + * @param string $dob Date of Birth + * @param string $tz Timezone + * @param string $format + * @return string */ +function z_birthday($dob, $tz, $format="Y-m-d H:i:s") { - -function z_birthday($dob,$tz,$format="Y-m-d H:i:s") { - - if(! strlen($tz)) + if (! strlen($tz)) $tz = 'UTC'; $birthday = ''; $tmp_dob = substr($dob,5); $tmp_d = substr($dob,8); - if(intval($tmp_dob) && intval($tmp_d)) { + if (intval($tmp_dob) && intval($tmp_d)) { $y = datetime_convert($tz,$tz,'now','Y'); $bd = $y . '-' . $tmp_dob . ' 00:00'; $t_dob = strtotime($bd); $now = strtotime(datetime_convert($tz,$tz,'now')); - if($t_dob < $now) + if ($t_dob < $now) $bd = $y + 1 . '-' . $tmp_dob . ' 00:00'; + $birthday = datetime_convert($tz,'UTC',$bd,$format); } return $birthday; - } /** + * @brief Create a birthday event for any connections with a birthday in the next 1-2 weeks. * - * Create a birthday event for any connections with a birthday in the next 1-2 weeks. * Update the year so that we don't create another event until next year. - * */ - - function update_birthdays() { require_once('include/event.php'); require_once('include/permissions.php'); - $r = q("SELECT * FROM abook left join xchan on abook_xchan = xchan_hash + $r = q("SELECT * FROM abook left join xchan on abook_xchan = xchan_hash WHERE abook_dob > %s + interval %s and abook_dob < %s + interval %s", db_utcnow(), db_quoteinterval('7 day'), db_utcnow(), db_quoteinterval('14 day') - ); - if($r) { - foreach($r as $rr) { - - if(! perm_is_allowed($rr['abook_channel'],$rr['xchan_hash'],'send_stream')) + ); + if ($r) { + foreach ($r as $rr) { + if (! perm_is_allowed($rr['abook_channel'], $rr['xchan_hash'], 'send_stream')) continue; $ev = array(); $ev['uid'] = $rr['abook_channel']; $ev['account'] = $rr['abook_account']; $ev['event_xchan'] = $rr['xchan_hash']; - $ev['start'] = datetime_convert('UTC','UTC', $rr['abook_dob']); - $ev['finish'] = datetime_convert('UTC','UTC', $rr['abook_dob'] . ' + 1 day '); + $ev['start'] = datetime_convert('UTC', 'UTC', $rr['abook_dob']); + $ev['finish'] = datetime_convert('UTC', 'UTC', $rr['abook_dob'] . ' + 1 day '); $ev['adjust'] = 1; - $ev['summary'] = sprintf( t('%1$s\'s birthday'), $rr['xchan_name']); - $ev['description'] = sprintf( t('Happy Birthday %1$s'), + $ev['summary'] = sprintf( t('%1$s\'s birthday'), $rr['xchan_name']); + $ev['description'] = sprintf( t('Happy Birthday %1$s'), '[zrl=' . $rr['xchan_url'] . ']' . $rr['xchan_name'] . '[/zrl]') ; $ev['type'] = 'birthday'; - + $z = event_store_event($ev); - if($z) { - $item_id = event_store_item($ev,$z); + if ($z) { + $item_id = event_store_item($ev, $z); q("update abook set abook_dob = '%s' where abook_id = %d", - dbesc(intval($rr['abook_dob']) + 1 . substr($rr['abook_dob'],4)), + dbesc(intval($rr['abook_dob']) + 1 . substr($rr['abook_dob'], 4)), intval($rr['abook_id']) ); } diff --git a/include/dir_fns.php b/include/dir_fns.php index 4c6c40f15..d1e26b637 100644 --- a/include/dir_fns.php +++ b/include/dir_fns.php @@ -1,14 +1,23 @@ - $preferred); } +/** + * Directories may come and go over time. We will need to check that our + * directory server is still valid occasionally, and reset to something that + * is if our directory has gone offline for any reason + */ function check_upstream_directory() { - /** - * Directories may come and go over time. We will need to check that our - * directory server is still valid occasionally, and reset to something that - * is if our directory has gone offline for any reason - */ - - $directory = get_config('system','directory_server'); + $directory = get_config('system', 'directory_server'); // it's possible there is no directory server configured and the local hub is being used. // If so, default to preserving the absence of a specific server setting. - $isadir = true; + $isadir = true; - if($directory) { + if ($directory) { $h = parse_url($directory); - if($h) { + if ($h) { $x = zot_finger('[system]@' . $h['host']); - if($x['success']) { - $j = json_decode($x['body'],true); - if(array_key_exists('site',$j) && array_key_exists('directory_mode',$j['site'])) { - if($j['site']['directory_mode'] === 'normal') { + if ($x['success']) { + $j = json_decode($x['body'], true); + if (array_key_exists('site', $j) && array_key_exists('directory_mode', $j['site'])) { + if ($j['site']['directory_mode'] === 'normal') { $isadir = false; } } @@ -60,9 +68,8 @@ function check_upstream_directory() { } } - if(! $isadir) - set_config('system','directory_server',''); - return; + if (! $isadir) + set_config('system', 'directory_server', ''); } function get_globaldir_setting($observer) { @@ -95,12 +102,8 @@ function get_safemode_setting($observer) { } /** - * @function dir_sort_links() - * Called by the directory_sort widget + * @brief Called by the directory_sort widget. */ - - - function dir_sort_links() { $safe_mode = 1; @@ -110,7 +113,7 @@ function dir_sort_links() { $safe_mode = get_safemode_setting($observer); $globaldir = get_globaldir_setting($observer); - // Build urls without order and pubforums so it's easy to tack on the changed value + // Build urls without order and pubforums so it's easy to tack on the changed value // Probably there's an easier way to do this $current_order = (($_REQUEST['order']) ? $_REQUEST['order'] : 'date'); @@ -145,38 +148,34 @@ function dir_sort_links() { '$pubforums' => array('pubforums', t('Public Forums Only'),(x($_REQUEST,'pubforums') ? $_REQUEST['pubforums'] : ''),'','',' onchange=\'window.location.href="' . $forumsurl . '&pubforums="+(this.checked ? 1 : 0)\''), '$globaldir' => array('globaldir', t('This Website Only'), 1-intval($globaldir),'','',' onchange=\'window.location.href="' . $forumsurl . '&global="+(this.checked ? 0 : 1)\''), )); + return $o; } - /** - * @function sync_directories($mode) - * - * @param int $mode; + * @brief Checks the directory mode of this hub. * * Checks the directory mode of this hub to see if it is some form of directory server. If it is, * get the directory realm of this hub. Fetch a list of all other directory servers in this realm and request * a directory sync packet. This will contain both directory updates and new ratings. Store these all in the DB. * In the case of updates, we will query each of them asynchronously from a poller task. Ratings are stored - * directly if the rater's signature matches. + * directly if the rater's signature matches. * + * @param int $dirmode; */ - - function sync_directories($dirmode) { - if($dirmode == DIRECTORY_MODE_STANDALONE || $dirmode == DIRECTORY_MODE_NORMAL) + if ($dirmode == DIRECTORY_MODE_STANDALONE || $dirmode == DIRECTORY_MODE_NORMAL) return; $realm = get_directory_realm(); - if($realm == DIRECTORY_REALM) { + if ($realm == DIRECTORY_REALM) { $r = q("select * from site where (site_flags & %d) > 0 and site_url != '%s' and ( site_realm = '%s' or site_realm = '') ", intval(DIRECTORY_MODE_PRIMARY|DIRECTORY_MODE_SECONDARY), dbesc(z_root()), dbesc($realm) ); - } - else { + } else { $r = q("select * from site where (site_flags & %d) > 0 and site_url != '%s' and site_realm like '%s' ", intval(DIRECTORY_MODE_PRIMARY|DIRECTORY_MODE_SECONDARY), dbesc(z_root()), @@ -185,9 +184,9 @@ function sync_directories($dirmode) { } // If there are no directory servers, setup the fallback master - // FIXME - what to do if we're in a different realm? + /** @FIXME What to do if we're in a different realm? */ - if((! $r) && (z_root() != DIRECTORY_FALLBACK_MASTER)) { + if ((! $r) && (z_root() != DIRECTORY_FALLBACK_MASTER)) { $r = array(); $r[] = array( 'site_url' => DIRECTORY_FALLBACK_MASTER, @@ -211,32 +210,30 @@ function sync_directories($dirmode) { intval(DIRECTORY_MODE_PRIMARY|DIRECTORY_MODE_SECONDARY), dbesc(z_root()) ); - - } - if(! $r) + } + if (! $r) return; - foreach($r as $rr) { - if(! $rr['site_directory']) + foreach ($r as $rr) { + if (! $rr['site_directory']) continue; logger('sync directories: ' . $rr['site_directory']); // for brand new directory servers, only load the last couple of days. // It will take about a month for a new directory to obtain the full current repertoire of channels. - // FIXME - go back and pick up earlier ratings if this is a new directory server. These do not get refreshed. + /** @FIXME Go back and pick up earlier ratings if this is a new directory server. These do not get refreshed. */ $token = get_config('system','realm_token'); - $syncdate = (($rr['site_sync'] === NULL_DATE) ? datetime_convert('UTC','UTC','now - 2 days') : $rr['site_sync']); $x = z_fetch_url($rr['site_directory'] . '?f=&sync=' . urlencode($syncdate) . (($token) ? '&t=' . $token : '')); - if(! $x['success']) + if (! $x['success']) continue; $j = json_decode($x['body'],true); - if(!($j['transactions']) || ($j['ratings'])) + if (!($j['transactions']) || ($j['ratings'])) continue; q("update site set site_sync = '%s' where site_url = '%s'", @@ -246,17 +243,18 @@ function sync_directories($dirmode) { logger('sync_directories: ' . $rr['site_url'] . ': ' . print_r($j,true), LOGGER_DATA); - if(is_array($j['transactions']) && count($j['transactions'])) { - foreach($j['transactions'] as $t) { + if (is_array($j['transactions']) && count($j['transactions'])) { + foreach ($j['transactions'] as $t) { $r = q("select * from updates where ud_guid = '%s' limit 1", dbesc($t['transaction_id']) ); if($r) continue; + $ud_flags = 0; - if(is_array($t['flags']) && in_array('deleted',$t['flags'])) + if (is_array($t['flags']) && in_array('deleted',$t['flags'])) $ud_flags |= UPDATE_FLAGS_DELETED; - if(is_array($t['flags']) && in_array('forced',$t['flags'])) + if (is_array($t['flags']) && in_array('forced',$t['flags'])) $ud_flags |= UPDATE_FLAGS_FORCED; $z = q("insert into updates ( ud_hash, ud_guid, ud_date, ud_flags, ud_addr ) @@ -269,42 +267,41 @@ function sync_directories($dirmode) { ); } } - if(is_array($j['ratings']) && count($j['ratings'])) { - foreach($j['ratings'] as $rr) { + if (is_array($j['ratings']) && count($j['ratings'])) { + foreach ($j['ratings'] as $rr) { $x = q("select * from xlink where xlink_xchan = '%s' and xlink_link = '%s' and xlink_static = 1", dbesc($rr['channel']), dbesc($rr['target']) ); - if($x && $x[0]['xlink_updated'] >= $rr['edited']) + if ($x && $x[0]['xlink_updated'] >= $rr['edited']) continue; // Ratings are signed by the rater. We need to verify before we can accept it. - // TODO - queue or defer if the xchan is not yet present on our site + /** @TODO Queue or defer if the xchan is not yet present on our site */ $y = q("select xchan_pubkey from xchan where xchan_hash = '%s' limit 1", dbesc($rr['channel']) ); - if(! $y) { + if (! $y) { logger('key unavailable on this site for ' . $rr['channel']); continue; } - if(! rsa_verify($rr['target'] . '.' . $rr['rating'] . '.' . $rr['rating_text'], base64url_decode($rr['signature']),$y[0]['xchan_pubkey'])) { - logger('failed to verify rating'); + if (! rsa_verify($rr['target'] . '.' . $rr['rating'] . '.' . $rr['rating_text'], base64url_decode($rr['signature']),$y[0]['xchan_pubkey'])) { + logger('failed to verify rating'); continue; } - if($x) { + if ($x) { $z = q("update xlink set xlink_rating = %d, xlink_rating_text = '%s', xlink_sig = '%s', xlink_updated = '%s' where xlink_id = %d", intval($rr['rating']), dbesc($rr['rating_text']), dbesc($rr['signature']), dbesc(datetime_convert()), intval($x[0]['xlink_id']) - ); - logger('rating updated'); - } - else { - $z = q("insert into xlink ( xlink_xchan, xlink_link, xlink_rating, xlink_rating_text, xlink_sig, xlink_updated, xlink_static ) values( '%s', '%s', %d, '%s', '%s', '%s', 1 ) ", + ); + logger('rating updated'); + } else { + $z = q("insert into xlink ( xlink_xchan, xlink_link, xlink_rating, xlink_rating_text, xlink_sig, xlink_updated, xlink_static ) values( '%s', '%s', %d, '%s', '%s', '%s', 1 ) ", dbesc($rr['channel']), dbesc($rr['target']), intval($rr['rating']), @@ -321,50 +318,51 @@ function sync_directories($dirmode) { /** - * $function update_directory_entry($ud) + * @brief * - * @param array $ud; // Entry from update table - * Given an update record, probe the channel, grab a zot-info packet and refresh/sync the data + * Given an update record, probe the channel, grab a zot-info packet and refresh/sync the data. * - * Ignore updating records marked as deleted + * Ignore updating records marked as deleted. * - * If successful, - * sets ud_last in the DB to the current datetime for this reddress/webbie + * If successful, sets ud_last in the DB to the current datetime for this + * reddress/webbie. + * + * @param array $ud Entry from update table */ - function update_directory_entry($ud) { logger('update_directory_entry: ' . print_r($ud,true), LOGGER_DATA); - if($ud['ud_addr'] && (! ($ud['ud_flags'] & UPDATE_FLAGS_DELETED))) { + if ($ud['ud_addr'] && (! ($ud['ud_flags'] & UPDATE_FLAGS_DELETED))) { $success = false; - $x = zot_finger($ud['ud_addr'],''); - if($x['success']) { - $j = json_decode($x['body'],true); - if($j) + $x = zot_finger($ud['ud_addr'], ''); + if ($x['success']) { + $j = json_decode($x['body'], true); + if ($j) $success = true; - $y = import_xchan($j,0,$ud); + + $y = import_xchan($j, 0, $ud); } - if(! $success) { - $r = q("update updates set ud_last = '%s' where ud_addr = '%s'", + if (! $success) { + q("update updates set ud_last = '%s' where ud_addr = '%s'", dbesc(datetime_convert()), dbesc($ud['ud_addr']) ); } } - } /** - * @function local_dir_update($uid,$force) - * push local channel updates to a local directory server - * This is called from include/directory.php if a profile is to be pushed - * to the directory and the local hub in this case is any kind of directory server. + * @brief Push local channel updates to a local directory server. * + * This is called from include/directory.php if a profile is to be pushed to the + * directory and the local hub in this case is any kind of directory server. + * + * @param int $uid + * @param boolean $force */ - -function local_dir_update($uid,$force) { +function local_dir_update($uid, $force) { logger('local_dir_update: uid: ' . $uid, LOGGER_DEBUG); @@ -375,12 +373,12 @@ function local_dir_update($uid,$force) { $profile = array(); $profile['encoding'] = 'zot'; - if($p) { + if ($p) { $hash = $p[0]['channel_hash']; $profile['description'] = $p[0]['pdesc']; $profile['birthday'] = $p[0]['dob']; - if($age = age($p[0]['dob'],$p[0]['channel_timezone'],'')) + if ($age = age($p[0]['dob'],$p[0]['channel_timezone'],'')) $profile['age'] = $age; $profile['gender'] = $p[0]['gender']; @@ -394,14 +392,15 @@ function local_dir_update($uid,$force) { $profile['homepage'] = $p[0]['homepage']; $profile['hometown'] = $p[0]['hometown']; - if($p[0]['keywords']) { + if ($p[0]['keywords']) { $tags = array(); - $k = explode(' ',$p[0]['keywords']); - if($k) - foreach($k as $kk) - if(trim($kk)) + $k = explode(' ', $p[0]['keywords']); + if ($k) + foreach ($k as $kk) + if (trim($kk)) $tags[] = trim($kk); - if($tags) + + if ($tags) $profile['keywords'] = $tags; } @@ -414,26 +413,23 @@ function local_dir_update($uid,$force) { ); // Be careful - XCHAN_FLAGS_HIDDEN should evaluate to 1 - if(($r[0]['xchan_flags'] & XCHAN_FLAGS_HIDDEN) != $hidden) + if (($r[0]['xchan_flags'] & XCHAN_FLAGS_HIDDEN) != $hidden) $new_flags = $r[0]['xchan_flags'] ^ XCHAN_FLAGS_HIDDEN; else $new_flags = $r[0]['xchan_flags']; - - if($new_flags != $r[0]['xchan_flags']) { + if ($new_flags != $r[0]['xchan_flags']) { $r = q("update xchan set xchan_flags = %d where xchan_hash = '%s'", intval($new_flags), dbesc($p[0]['channel_hash']) ); - } $address = $p[0]['channel_address'] . '@' . get_app()->get_hostname(); - if(perm_is_allowed($uid,'','view_profile')) { - import_directory_profile($hash,$profile,$address,0); - } - else { + if (perm_is_allowed($uid, '', 'view_profile')) { + import_directory_profile($hash, $profile, $address, 0); + } else { // they may have made it private $r = q("delete from xprof where xprof_hash = '%s'", dbesc($hash) @@ -445,7 +441,5 @@ function local_dir_update($uid,$force) { } $ud_hash = random_string() . '@' . get_app()->get_hostname(); - update_modtime($hash,$ud_hash,$p[0]['channel_address'] . '@' . get_app()->get_hostname(),(($force) ? UPDATE_FLAGS_FORCED : UPDATE_FLAGS_UPDATED)); - + update_modtime($hash, $ud_hash, $p[0]['channel_address'] . '@' . get_app()->get_hostname(),(($force) ? UPDATE_FLAGS_FORCED : UPDATE_FLAGS_UPDATED)); } - diff --git a/include/directory.php b/include/directory.php index 801d4ec8e..9ab1d805b 100644 --- a/include/directory.php +++ b/include/directory.php @@ -1,14 +1,23 @@ -0 limit 1", dbesc($params['to_xchan']), intval(PAGE_REMOVED) ); } - if($x & $y) { + if ($x & $y) { $sender = $x[0]; $recip = $y[0]; - } - else { + } else { logger('notification: no sender or recipient.'); logger('sender: ' . $params['from_xchan']); logger('recip: ' . $params['to_xchan']); @@ -55,10 +72,10 @@ function notification($params) { $additional_mail_header = ""; - if(array_key_exists('item',$params)) { + if (array_key_exists('item', $params)) { require_once('include/conversation.php'); // if it's a normal item... - if(array_key_exists('verb',$params['item'])) { + if (array_key_exists('verb', $params['item'])) { // localize_item() alters the original item so make a copy first $i = $params['item']; logger('calling localize'); @@ -66,13 +83,11 @@ function notification($params) { $title = $i['title']; $body = $i['body']; $private = (($i['item_private']) || ($i['item_flags'] & ITEM_OBSCURED)); - } - else { + } else { $title = $params['item']['title']; $body = $params['item']['body']; } - } - else { + } else { $title = $body = ''; } @@ -80,7 +95,7 @@ function notification($params) { // e.g. "your post", "David's photo", etc. $possess_desc = t('%s '); - if($params['type'] == NOTIFY_MAIL) { + if ($params['type'] == NOTIFY_MAIL) { logger('notification: mail'); $subject = sprintf( t('[Red:Notify] New mail received at %s'),$sitename); @@ -92,28 +107,27 @@ function notification($params) { $itemlink = $siteurl . '/mail/' . $params['item']['id']; } - if($params['type'] == NOTIFY_COMMENT) { + if ($params['type'] == NOTIFY_COMMENT) { // logger("notification: params = " . print_r($params, true), LOGGER_DEBUG); $itemlink = $params['link']; - // ignore like/unlike activity on posts - they probably require a sepearate notification preference - if(array_key_exists('item',$params) && (! visible_activity($params['item']))) + if (array_key_exists('item',$params) && (! visible_activity($params['item']))) return; $parent_mid = $params['parent_mid']; // Check to see if there was already a notify for this post. // If so don't create a second notification - + $p = null; $p = q("select id from notify where link = '%s' and uid = %d limit 1", dbesc($params['link']), intval($recip['channel_id']) ); - if($p) { + if ($p) { logger('notification: comment already notified'); pop_lang(); return; @@ -182,26 +196,26 @@ function notification($params) { $subject = sprintf( t('[Red:Notify] %s posted to your profile wall') , $sender['xchan_name']); $preamble = sprintf( t('%1$s, %2$s posted to your profile wall at %3$s') , $recip['channel_name'], $sender['xchan_name'], $sitename); - + $epreamble = sprintf( t('%1$s, %2$s posted to [zrl=%3$s]your wall[/zrl]') , $recip['channel_name'], '[zrl=' . $sender['xchan_url'] . ']' . $sender['xchan_name'] . '[/zrl]', $params['link']); - + $sitelink = t('Please visit %s to view and/or reply to the conversation.'); $tsitelink = sprintf( $sitelink, $siteurl ); $hsitelink = sprintf( $sitelink, '' . $sitename . ''); $itemlink = $params['link']; } - if($params['type'] == NOTIFY_TAGSELF) { + if ($params['type'] == NOTIFY_TAGSELF) { $p = null; $p = q("select id from notify where link = '%s' and uid = %d limit 1", dbesc($params['link']), intval($recip['channel_id']) ); - if($p) { + if ($p) { logger('enotify: tag: already notified about this post'); pop_lang(); return; @@ -220,8 +234,7 @@ function notification($params) { $itemlink = $params['link']; } - if($params['type'] == NOTIFY_POKE) { - + if ($params['type'] == NOTIFY_POKE) { $subject = sprintf( t('[Red:Notify] %1$s poked you') , $sender['xchan_name']); $preamble = sprintf( t('%1$s, %2$s poked you at %3$s') , $recip['channel_name'], $sender['xchan_name'], $sitename); $epreamble = sprintf( t('%1$s, %2$s [zrl=%2$s]poked you[/zrl].') , @@ -239,7 +252,7 @@ function notification($params) { $itemlink = $params['link']; } - if($params['type'] == NOTIFY_TAGSHARE) { + if ($params['type'] == NOTIFY_TAGSHARE) { $subject = sprintf( t('[Red:Notify] %s tagged your post') , $sender['xchan_name']); $preamble = sprintf( t('%1$s, %2$s tagged your post at %3$s') , $recip['channel_name'],$sender['xchan_name'], $sitename); $epreamble = sprintf( t('%1$s, %2$s tagged [zrl=%3$s]your post[/zrl]') , @@ -253,7 +266,7 @@ function notification($params) { $itemlink = $params['link']; } - if($params['type'] == NOTIFY_INTRO) { + if ($params['type'] == NOTIFY_INTRO) { $subject = sprintf( t('[Red:Notify] Introduction received')); $preamble = sprintf( t('%1$s, you\'ve received an new connection request from \'%2$s\' at %3$s'), $recip['channel_name'], $sender['xchan_name'], $sitename); $epreamble = sprintf( t('%1$s, you\'ve received [zrl=%2$s]a new connection request[/zrl] from %3$s.'), @@ -268,7 +281,7 @@ function notification($params) { $itemlink = $params['link']; } - if($params['type'] == NOTIFY_SUGGEST) { + if ($params['type'] == NOTIFY_SUGGEST) { $subject = sprintf( t('[Red:Notify] Friend suggestion received')); $preamble = sprintf( t('%1$s, you\'ve received a friend suggestion from \'%2$s\' at %3$s'), $recip['channel_name'], $sender['xchan_name'], $sitename); $epreamble = sprintf( t('%1$s, you\'ve received [zrl=%2$s]a friend suggestion[/zrl] for %3$s from %4$s.'), @@ -276,7 +289,7 @@ function notification($params) { $itemlink, '[zrl=' . $params['item']['url'] . ']' . $params['item']['name'] . '[/zrl]', '[zrl=' . $sender['xchan_url'] . ']' . $sender['xchan_name'] . '[/zrl]'); - + $body = t('Name:') . ' ' . $params['item']['name'] . "\n"; $body .= t('Photo:') . ' ' . $params['item']['photo'] . "\n"; $body .= sprintf( t('You may visit their profile at %s'),$params['item']['url']); @@ -287,27 +300,27 @@ function notification($params) { $itemlink = $params['link']; } - if($params['type'] == NOTIFY_CONFIRM) { - + if ($params['type'] == NOTIFY_CONFIRM) { + // ? } - if($params['type'] == NOTIFY_SYSTEM) { - + if ($params['type'] == NOTIFY_SYSTEM) { + // ? } $h = array( - 'params' => $params, + 'params' => $params, 'subject' => $subject, - 'preamble' => $preamble, - 'epreamble' => $epreamble, - 'body' => $body, + 'preamble' => $preamble, + 'epreamble' => $epreamble, + 'body' => $body, 'sitelink' => $sitelink, 'tsitelink' => $tsitelink, 'hsitelink' => $hsitelink, 'itemlink' => $itemlink ); - - call_hooks('enotify',$h); + + call_hooks('enotify', $h); $subject = $h['subject']; $preamble = $h['preamble']; @@ -319,16 +332,16 @@ function notification($params) { $itemlink = $h['itemlink']; - require_once('include/html2bbcode.php'); + require_once('include/html2bbcode.php'); do { $dups = false; $hash = random_string(); - $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1", + $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1", dbesc($hash)); - if(count($r)) + if (count($r)) $dups = true; - } while($dups == true); + } while ($dups === true); $datarray = array(); @@ -348,10 +361,10 @@ function notification($params) { $datarray['abort'] = false; $datarray['item'] = $params['item']; - + call_hooks('enotify_store', $datarray); - if($datarray['abort']) { + if ($datarray['abort']) { pop_lang(); return; } @@ -365,8 +378,8 @@ function notification($params) { // So easiest solution to hide them from Notices is to mark them as seen right away. // Another option would be to not add them to the DB, and change how emails are handled (probably would be better that way) $always_show_in_notices = get_pconfig($recip['channel_id'],'system','always_show_in_notices'); - if(!$always_show_in_notices) { - if(($params['type'] == NOTIFY_WALL) || ($params['type'] == NOTIFY_MAIL) || ($params['type'] == NOTIFY_INTRO)) { + if (!$always_show_in_notices) { + if (($params['type'] == NOTIFY_WALL) || ($params['type'] == NOTIFY_MAIL) || ($params['type'] == NOTIFY_INTRO)) { $seen = 1; } } @@ -392,9 +405,9 @@ function notification($params) { dbesc($hash), intval($recip['channel_id']) ); - if($r) + if ($r) { $notify_id = $r[0]['id']; - else { + } else { logger('notification not found.'); pop_lang(); return; @@ -405,7 +418,7 @@ function notification($params) { // wretched hack, but we don't want to duplicate all the preamble variations and we also don't want to screw up a translation - if(($a->language === 'en' || (! $a->language)) && strpos($msg,', ')) + if (($a->language === 'en' || (! $a->language)) && strpos($msg,', ')) $msg = substr($msg,strpos($msg,', ')+1); $r = q("update notify set msg = '%s' where id = %d and uid = %d", @@ -413,12 +426,11 @@ function notification($params) { intval($notify_id), intval($datarray['uid']) ); - // send email notification if notification preferences permit require_once('bbcode.php'); - if((intval($recip['channel_notifyflags']) & intval($params['type'])) || $params['type'] == NOTIFY_SYSTEM) { + if ((intval($recip['channel_notifyflags']) & intval($params['type'])) || $params['type'] == NOTIFY_SYSTEM) { logger('notification: sending notification email'); @@ -429,8 +441,6 @@ function notification($params) { return; } - - $textversion = strip_tags(html_entity_decode(bbcode(stripslashes(str_replace(array("\\r", "\\n"), array( "", "\n"), $body))),ENT_QUOTES,'UTF-8')); $htmlversion = bbcode(stripslashes(str_replace(array("\\r","\\n"), array("","
      \n"),$body))); @@ -450,7 +460,6 @@ function notification($params) { unset($_SESSION['zid_override']); unset($_SESSION['zrl_override']); - $datarray = array(); $datarray['banner'] = $banner; $datarray['product'] = $product; @@ -485,13 +494,13 @@ function notification($params) { $private_activity = false; - if(! $datarray['email_secure']) { - switch($params['type']) { + if (! $datarray['email_secure']) { + switch ($params['type']) { case NOTIFY_WALL: case NOTIFY_TAGSELF: case NOTIFY_POKE: case NOTIFY_COMMENT: - if(! $private) + if (! $private) break; $private_activity = true; case NOTIFY_MAIL: @@ -503,11 +512,12 @@ function notification($params) { } } - if($private_activity - && intval(get_pconfig($datarray['uid'],'system','ignore_private_notifications'))) { + if ($private_activity + && intval(get_pconfig($datarray['uid'], 'system', 'ignore_private_notifications'))) { + pop_lang(); return; - } + } // load the template for private message notifications $tpl = get_markup_template('email_notify_html.tpl'); @@ -525,13 +535,13 @@ function notification($params) { '$hitemlink' => $datarray['hitemlink'], '$thanks' => $datarray['thanks'], '$site_admin' => $datarray['site_admin'], - '$title' => $datarray['title'], - '$htmlversion' => $datarray['htmlversion'], + '$title' => $datarray['title'], + '$htmlversion' => $datarray['htmlversion'], )); - + // load the template for private message notifications $tpl = get_markup_template('email_notify_text.tpl'); - $email_text_body = replace_macros($tpl,array( + $email_text_body = replace_macros($tpl, array( '$banner' => $datarray['banner'], '$product' => $datarray['product'], '$preamble' => $datarray['preamble'], @@ -545,8 +555,8 @@ function notification($params) { '$titemlink' => $datarray['titemlink'], '$thanks' => $datarray['thanks'], '$site_admin' => $datarray['site_admin'], - '$title' => $datarray['title'], - '$textversion' => $datarray['textversion'], + '$title' => $datarray['title'], + '$textversion' => $datarray['textversion'], )); // logger('text: ' . $email_text_body); @@ -570,41 +580,48 @@ function notification($params) { } +/** + * @brief A class for sending email notifications. + * + * @fixme Class names start mostly with capital letter to distinguish them easier. + */ class enotify { /** - * Send a multipart/alternative message with Text and HTML versions + * @brief Send a multipart/alternative message with Text and HTML versions. * - * @param fromName name of the sender - * @param fromEmail email fo the sender - * @param replyTo replyTo address to direct responses - * @param toEmail destination email address - * @param messageSubject subject of the message - * @param htmlVersion html version of the message - * @param textVersion text only version of the message - * @param additionalMailHeader additions to the smtp mail header + * @param array $params an assoziative array with: + * * \e string \b fromName name of the sender + * * \e string \b fromEmail email of the sender + * * \e string \b replyTo replyTo address to direct responses + * * \e string \b toEmail destination email address + * * \e string \b messageSubject subject of the message + * * \e string \b htmlVersion html version of the message + * * \e string \b textVersion text only version of the message + * * \e string \b additionalMailHeader additions to the smtp mail header */ static public function send($params) { $fromName = email_header_encode(html_entity_decode($params['fromName'],ENT_QUOTES,'UTF-8'),'UTF-8'); $messageSubject = email_header_encode(html_entity_decode($params['messageSubject'],ENT_QUOTES,'UTF-8'),'UTF-8'); - + // generate a mime boundary - $mimeBoundary =rand(0,9)."-" - .rand(10000000000,9999999999)."-" - .rand(10000000000,9999999999)."=:" - .rand(10000,99999); + $mimeBoundary = rand(0, 9) . "-" + .rand(10000000000, 9999999999) . "-" + .rand(10000000000, 9999999999) . "=:" + .rand(10000, 99999); // generate a multipart/alternative message header $messageHeader = $params['additionalMailHeader'] . - "From: $fromName <{$params['fromEmail']}>\n" . + "From: $fromName <{$params['fromEmail']}>\n" . "Reply-To: $fromName <{$params['replyTo']}>\n" . "MIME-Version: 1.0\n" . "Content-Type: multipart/alternative; boundary=\"{$mimeBoundary}\""; // assemble the final multipart message body with the text and html types included - $textBody = chunk_split(base64_encode($params['textVersion'])); - $htmlBody = chunk_split(base64_encode($params['htmlVersion'])); + $textBody = chunk_split(base64_encode($params['textVersion'])); + $htmlBody = chunk_split(base64_encode($params['htmlVersion'])); + $multipartMessageBody = "--" . $mimeBoundary . "\n" . // plain text section "Content-Type: text/plain; charset=UTF-8\n" . @@ -618,12 +635,11 @@ class enotify { // send the message $res = mail( - $params['toEmail'], // send to address + $params['toEmail'], // send to address $messageSubject, // subject - $multipartMessageBody, // message body + $multipartMessageBody, // message body $messageHeader // message headers ); logger("notification: enotify::send returns " . $res, LOGGER_DEBUG); } -} - +} \ No newline at end of file diff --git a/include/expire.php b/include/expire.php index b244e65f5..e5d456896 100644 --- a/include/expire.php +++ b/include/expire.php @@ -1,4 +1,7 @@ - 0 and (item_restrict & %d) = 0 + $r = q("select id from item where (item_restrict & %d) > 0 and (item_restrict & %d) = 0 and changed < %s - INTERVAL %s", intval(ITEM_DELETED), intval(ITEM_PENDING_REMOVE), db_utcnow(), db_quoteinterval('10 DAY') ); - if($r) { - foreach($r as $rr) { - drop_item($rr['id'],false,DROPITEM_PHASE2); + if ($r) { + foreach ($r as $rr) { + drop_item($rr['id'], false, DROPITEM_PHASE2); } } // physically remove anything that has been deleted for more than two months - // FIXME - this is a wretchedly inefficient query + /** @FIXME - this is a wretchedly inefficient query */ $r = q("delete from item where ( item_restrict & %d ) > 0 and changed < %s - INTERVAL %s", intval(ITEM_PENDING_REMOVE), db_utcnow(), db_quoteinterval('36 DAY') ); - // make this optional as it could have a performance impact on large sites + /** @FIXME make this optional as it could have a performance impact on large sites */ - if(intval(get_config('system','optimize_items'))) + if (intval(get_config('system', 'optimize_items'))) q("optimize table item"); logger('expire: start', LOGGER_DEBUG); - + $site_expire = get_config('system', 'default_expire_days'); logger('site_expire: ' . $site_expire); $r = q("SELECT channel_id, channel_address, channel_pageflags, channel_expire_days from channel where true"); - if($r) { - foreach($r as $rr) { + if ($r) { + foreach ($r as $rr) { // expire the sys channel separately - if($rr['channel_pageflags'] & PAGE_SYSTEM) + if ($rr['channel_pageflags'] & PAGE_SYSTEM) continue; // service class default (if non-zero) over-rides the site default - $service_class_expire = service_class_fetch($rr['channel_id'],'expire_days'); - if(intval($service_class_expire)) + $service_class_expire = service_class_fetch($rr['channel_id'], 'expire_days'); + if (intval($service_class_expire)) $channel_expire = $service_class_expire; else $channel_expire = $site_expire; - if(intval($channel_expire) && (intval($channel_expire) < intval($rr['channel_expire_days'])) || + if (intval($channel_expire) && (intval($channel_expire) < intval($rr['channel_expire_days'])) || intval($rr['channel_expire_days'] == 0)) { $expire_days = $channel_expire; - } - else { + } else { $expire_days = $rr['channel_expire_days']; } @@ -72,34 +73,30 @@ function expire_run($argv, $argc){ } } - $x = get_sys_channel(); - if($x) { + if ($x) { // this should probably just fetch the channel_expire_days from the sys channel, // but there's no convenient way to set it. - $expire_days = get_config('system','sys_expire_days'); - if($expire_days === false) + $expire_days = get_config('system', 'sys_expire_days'); + if ($expire_days === false) $expire_days = 30; - if(intval($site_expire) && (intval($site_expire) < intval($expire_days))) { + if (intval($site_expire) && (intval($site_expire) < intval($expire_days))) { $expire_days = $site_expire; } logger('Expire: sys interval: ' . $expire_days, LOGGER_DEBUG); - if($expire_days) - item_expire($x['channel_id'],$expire_days); + if ($expire_days) + item_expire($x['channel_id'], $expire_days); logger('Expire: sys: done', LOGGER_DEBUG); - } - - return; } -if (array_search(__file__,get_included_files())===0){ - expire_run($argv,$argc); - killme(); +if (array_search(__file__, get_included_files()) === 0){ + expire_run($argv, $argc); + killme(); } diff --git a/include/identity.php b/include/identity.php index af6cb74d2..7884c04d2 100644 --- a/include/identity.php +++ b/include/identity.php @@ -1,27 +1,29 @@ - boolean true if creating a new channel is allowed for this account - * 'message' => if success is false, optional error text + * @returns assoziative array with: + * * \e boolean \b success boolean true if creating a new channel is allowed for this account + * * \e string \b message (optional) if success is false, optional error text + * * \e int \b total_identities */ - - function identity_check_service_class($account_id) { - $ret = array('success' => false, $message => ''); - + $ret = array('success' => false, 'message' => ''); + $r = q("select count(channel_id) as total from channel where channel_account_id = %d and not ( channel_pageflags & %d )>0 ", intval($account_id), intval(PAGE_REMOVED) @@ -30,68 +32,67 @@ function identity_check_service_class($account_id) { $ret['total_identities'] = 0; $ret['message'] = t('Unable to obtain identity information from database'); return $ret; - } + } $ret['total_identities'] = intval($r[0]['total']); - if(! account_service_class_allows($account_id,'total_identities',$r[0]['total'])) { - $result['message'] .= upgrade_message(); - return $result; + if (! account_service_class_allows($account_id, 'total_identities', $r[0]['total'])) { + $ret['message'] .= upgrade_message(); + return $ret; } $ret['success'] = true; + return $ret; } /** - * @function validate_channelname($name) - * Determine if the channel name is allowed when creating a new channel. + * @brief Determine if the channel name is allowed when creating a new channel. + * * This action is pluggable. + * We're currently only checking for an empty name or one that exceeds our + * storage limit (255 chars). 255 chars is probably going to create a mess on + * some pages. + * Plugins can set additional policies such as full name requirements, character + * sets, multi-byte length, etc. * * @param string $name * * @returns nil return if name is valid, or string describing the error state. - * - * We're currently only checking for an empty name or one that exceeds our storage limit (255 chars). - * 255 chars is probably going to create a mess on some pages. - * Plugins can set additional policies such as full name requirements, character sets, multi-byte - * length, etc. - * */ - function validate_channelname($name) { - if(! $name) + if (! $name) return t('Empty name'); - if(strlen($name) > 255) + + if (strlen($name) > 255) return t('Name too long'); + $arr = array('name' => $name); - call_hooks('validate_channelname',$arr); - if(x($arr,'message')) + call_hooks('validate_channelname', $arr); + + if (x($arr, 'message')) return $arr['message']; - return; } /** - * @function create_sys_channel() - * Create a system channel - which has no account attached + * @brief Create a system channel - which has no account attached. * */ - function create_sys_channel() { - if(get_sys_channel()) + if (get_sys_channel()) return; - // Ensure that there is a host keypair. + // Ensure that there is a host keypair. - if((! get_config('system','pubkey')) && (! get_config('system','prvkey'))) { + if ((! get_config('system', 'pubkey')) && (! get_config('system', 'prvkey'))) { require_once('include/crypto.php'); - $hostkey = new_keypair(4096); - set_config('system','pubkey',$hostkey['pubkey']); - set_config('system','prvkey',$hostkey['prvkey']); - } + $hostkey = new_keypair(4096); + set_config('system', 'pubkey', $hostkey['pubkey']); + set_config('system', 'prvkey', $hostkey['prvkey']); + } create_identity(array( 'account_id' => 'xxx', // This will create an identity with an (integer) account_id of 0, but account_id is required @@ -103,63 +104,79 @@ function create_sys_channel() { )); } + +/** + * @brief Returns the sys channel. + * + * @return array|boolean + */ function get_sys_channel() { $r = q("select * from channel left join xchan on channel_hash = xchan_hash where (channel_pageflags & %d)>0 limit 1", intval(PAGE_SYSTEM) ); - if($r) + + if ($r) return $r[0]; + return false; } + +/** + * @brief Checks if $channel_id is sys channel. + * + * @param int $channel_id + * @return boolean + */ function is_sys_channel($channel_id) { $r = q("select channel_pageflags from channel where channel_id = %d limit 1", intval($channel_id) ); - if(($r) && ($r[0]['channel_pageflags'] & PAGE_SYSTEM)) + + if (($r) && ($r[0]['channel_pageflags'] & PAGE_SYSTEM)) return true; + return false; } /** - * @channel_total() - * Return the total number of channels on this site. No filtering is performed except to check PAGE_REMOVED + * @brief Return the total number of channels on this site. * - * @returns int - * on error returns boolean false + * No filtering is performed except to check PAGE_REMOVED. * + * @returns int|booleean + * on error returns boolean false */ - function channel_total() { $r = q("select channel_id from channel where not ( channel_pageflags & %d )>0", intval(PAGE_REMOVED) ); - if(is_array($r)) + if (is_array($r)) return count($r); + return false; } /** - * @function create_identity($arr) - * Create a new channel - * Also creates the related xchan, hubloc, profile, and "self" abook records, and an - * empty "Friends" group/collection for the new channel + * @brief Create a new channel. + * + * Also creates the related xchan, hubloc, profile, and "self" abook records, + * and an empty "Friends" group/collection for the new channel. * - * @param array $arr - * 'name' => full name of channel - * 'nickname' => "email/url-compliant" nickname - * 'account_id' => account_id to attach with this channel - * [other identity fields as desired] + * @param array $arr assoziative array with: + * * \e string \b name full name of channel + * * \e string \b nickname "email/url-compliant" nickname + * * \e int \b account_id to attach with this channel + * * [other identity fields as desired] * * @returns array * 'success' => boolean true or false * 'message' => optional error text if success is false * 'channel' => if successful the created channel array */ - function create_identity($arr) { $a = get_app(); @@ -176,7 +193,6 @@ function create_identity($arr) { // save this for auto_friending $total_identities = $ret['total_identities']; - $nick = mb_strtolower(trim($arr['nickname'])); if(! $nick) { $ret['message'] = t('Nickname is required.'); @@ -205,7 +221,6 @@ function create_identity($arr) { $guid = zot_new_uid($nick); $key = new_keypair(4096); - $sig = base64url_encode(rsa_sign($guid,$key['prvkey'])); $hash = make_xchan_hash($guid,$sig); @@ -221,9 +236,6 @@ function create_identity($arr) { if(array_key_exists('primary', $arr)) $primary = intval($arr['primary']); - - $perms_sql = ''; - $role_permissions = null; $global_perms = get_perms(); @@ -269,7 +281,6 @@ function create_identity($arr) { intval($expire), dbesc($a->timezone) ); - $r = q("select * from channel where channel_account_id = %d and channel_guid = '%s' limit 1", @@ -281,7 +292,7 @@ function create_identity($arr) { $ret['message'] = t('Unable to retrieve created identity'); return $ret; } - + $ret['channel'] = $r[0]; if(intval($arr['account_id'])) @@ -307,7 +318,6 @@ function create_identity($arr) { if(! $r) logger('create_identity: Unable to store hub location'); - $newuid = $ret['channel']['channel_id']; $r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_guid_sig, xchan_pubkey, xchan_photo_l, xchan_photo_m, xchan_photo_s, xchan_addr, xchan_url, xchan_follow, xchan_connurl, xchan_name, xchan_network, xchan_photo_date, xchan_name_date, xchan_flags ) values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)", @@ -329,9 +339,8 @@ function create_identity($arr) { intval($xchanflags) ); - // Not checking return value. + // Not checking return value. // It's ok for this to fail if it's an imported channel, and therefore the hash is a duplicate - $r = q("INSERT INTO profile ( aid, uid, profile_guid, profile_name, is_default, publish, name, photo, thumb) VALUES ( %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s') ", @@ -418,37 +427,31 @@ function create_identity($arr) { } call_hooks('register_account', $newuid); - + proc_run('php','include/directory.php', $ret['channel']['channel_id']); } $ret['success'] = true; return $ret; - } - /** - * @function set_default_login_identity($account_id, $channel_id, $force = true) - * Set default channel to be used on login + * @brief Set default channel to be used on login. * * @param int $account_id * login account * @param int $channel_id * channel id to set as default for this account - * @param boolean force + * @param boolean $force * if true, set this default unconditionally * if $force is false only do this if there is no existing default - * - * @returns nil */ - -function set_default_login_identity($account_id,$channel_id,$force = true) { +function set_default_login_identity($account_id, $channel_id, $force = true) { $r = q("select account_default_channel from account where account_id = %d limit 1", intval($account_id) ); - if($r) { - if((intval($r[0]['account_default_channel']) == 0) || ($force)) { + if ($r) { + if ((intval($r[0]['account_default_channel']) == 0) || ($force)) { $r = q("update account set account_default_channel = %d where account_id = %d", intval($channel_id), intval($account_id) @@ -458,8 +461,7 @@ function set_default_login_identity($account_id,$channel_id,$force = true) { } /** - * @function identity_basic_export($channel_id,$items = false) - * Create an array representing the important channel information + * @brief Create an array representing the important channel information * which would be necessary to create a nomadic identity clone. This includes * most channel resources and connection information with the exception of content. * @@ -470,9 +472,7 @@ function set_default_login_identity($account_id,$channel_id,$force = true) { * * @returns array * See function for details - * */ - function identity_basic_export($channel_id, $items = false) { /* @@ -536,7 +536,6 @@ function identity_basic_export($channel_id, $items = false) { if($r) $ret['config'] = $r; - $r = q("select type, data from photo where scale = 4 and profile = 1 and uid = %d limit 1", intval($channel_id) ); @@ -563,11 +562,9 @@ function identity_basic_export($channel_id, $items = false) { if($r) $ret['obj'] = $r; - if(! $items) return $ret; - $r = q("select likes.*, item.mid from likes left join item on likes.iid = item.id where likes.channel_id = %d", intval($channel_id) ); @@ -575,17 +572,16 @@ function identity_basic_export($channel_id, $items = false) { if($r) $ret['likes'] = $r; - $r = q("select item_id.*, item.mid from item_id left join item on item_id.iid = item.id where item_id.uid = %d", intval($channel_id) ); - + if($r) - $ret['item_id'] = $r; + $ret['item_id'] = $r; - $key = get_config('system','prvkey'); + //$key = get_config('system','prvkey'); - // warning: this may run into memory limits on smaller systems + /** @warning this may run into memory limits on smaller systems */ $r = q("select * from item where (item_flags & %d)>0 and not (item_restrict & %d)>0 and uid = %d", intval(ITEM_WALL), @@ -598,25 +594,17 @@ function identity_basic_export($channel_id, $items = false) { $r = fetch_post_tags($r,true); foreach($r as $rr) $ret['item'][] = encode_item($rr,true); - } - return $ret; + return $ret; } - /** + * @brief Loads a profile into the App structure. * - * @function : profile_load(&$a, $nickname, $profile) - * Generate - * @param App $a - * @param string $nickname - * @param string $profile - * - * Summary: Loads a profile into the App structure. - * The function requires a writeable copy of the main App structure, and the nickname - * of a valid channel. + * The function requires a writeable copy of the main App structure, and the + * nickname of a valid channel. * * Permissions of the current observer are checked. If a restricted profile is available * to the current observer, that will be loaded instead of the channel default profile. @@ -625,9 +613,10 @@ function identity_basic_export($channel_id, $items = false) { * * The channel default theme is also selected for use, unless over-riden elsewhere. * + * @param[in,out] App &$a + * @param string $nickname + * @param string $profile */ - - function profile_load(&$a, $nickname, $profile = '') { logger('profile_load: ' . $nickname . (($profile) ? ' profile: ' . $profile : '')); @@ -635,7 +624,7 @@ function profile_load(&$a, $nickname, $profile = '') { $user = q("select channel_id from channel where channel_address = '%s' limit 1", dbesc($nickname) ); - + if(! $user) { logger('profile error: ' . $a->query_string, LOGGER_DEBUG); notice( t('Requested channel is not available.') . EOL ); @@ -683,7 +672,6 @@ function profile_load(&$a, $nickname, $profile = '') { ); } - if(! $p) { logger('profile error: ' . $a->query_string, LOGGER_DEBUG); notice( t('Requested profile is not available.') . EOL ); @@ -729,10 +717,11 @@ function profile_load(&$a, $nickname, $profile = '') { $p[0]['picdate'] = $z[0]['xchan_photo_date']; $p[0]['reddress'] = str_replace('@','@',$z[0]['xchan_addr']); } - + // fetch user tags if this isn't the default profile if(! $p[0]['is_default']) { + /** @BUG $profile_uid is undefinded for this query, so should not work. */ $x = q("select `keywords` from `profile` where uid = %d and `is_default` = 1 limit 1", intval($profile_uid) ); @@ -744,7 +733,6 @@ function profile_load(&$a, $nickname, $profile = '') { $keywords = str_replace(array('#',',',' ',',,'),array('',' ',',',','),$p[0]['keywords']); if(strlen($keywords) && $can_view_profile) $a->page['htmlhead'] .= '' . "\r\n" ; - } $a->profile = $p[0]; @@ -756,7 +744,6 @@ function profile_load(&$a, $nickname, $profile = '') { if($can_view_profile) { $online = get_online_status($nickname); $a->profile['online_status'] = $online['result']; - } if(local_channel()) { @@ -764,7 +751,7 @@ function profile_load(&$a, $nickname, $profile = '') { $_SESSION['mobile_theme'] = $a->profile['channel_mobile_theme']; } - /** + /* * load/reload current theme info */ @@ -776,36 +763,34 @@ function profile_load(&$a, $nickname, $profile = '') { // if (file_exists($theme_info_file)){ // require_once($theme_info_file); // } - - return; } -function profile_create_sidebar(&$a,$connect = true) { +/** + * @brief + * + * @param App &$a + * @param boolean $connect + */ +function profile_create_sidebar(&$a, $connect = true) { - $block = (((get_config('system','block_public')) && (! local_channel()) && (! remote_channel())) ? true : false); + $block = (((get_config('system', 'block_public')) && (! local_channel()) && (! remote_channel())) ? true : false); - $a->set_widget('profile',profile_sidebar($a->profile, $block, $connect)); - return; + $a->set_widget('profile', profile_sidebar($a->profile, $block, $connect)); } - /** + * @brief Formats a profile for display in the sidebar. * - * Function: profile_sidebar - * - * Formats a profile for display in the sidebar. * It is very difficult to templatise the HTML completely * because of all the conditional logic. * - * @parameter: array $profile + * @param array $profile + * @param int $block + * @param boolean $show_connect * - * Returns HTML string stuitable for sidebar inclusion + * @return HTML string suitable for sidebar inclusion * Exceptions: Returns empty string if passed $profile is wrong type or not populated - * */ - - - function profile_sidebar($profile, $block = 0, $show_connect = true) { $a = get_app(); @@ -814,14 +799,12 @@ function profile_sidebar($profile, $block = 0, $show_connect = true) { $o = ''; $location = false; - $address = false; $pdesc = true; $reddress = true; if((! is_array($profile)) && (! count($profile))) return $o; - head_set_icon($profile['thumb']); $is_owner = (($profile['uid'] == local_channel()) ? true : false); @@ -849,13 +832,11 @@ function profile_sidebar($profile, $block = 0, $show_connect = true) { // show edit profile to yourself if($is_owner) { - $profile['menu'] = array( 'chg_photo' => t('Change profile photo'), 'entries' => array(), ); - $multi_profiles = feature_enabled(local_channel(), 'multi_profiles'); if($multi_profiles) { $profile['edit'] = array($a->get_baseurl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles')); @@ -863,10 +844,9 @@ function profile_sidebar($profile, $block = 0, $show_connect = true) { } else $profile['edit'] = array($a->get_baseurl() . '/profiles/' . $profile['id'], t('Edit Profile'),'',t('Edit Profile')); - + $r = q("SELECT * FROM `profile` WHERE `uid` = %d", local_channel()); - if($r) { foreach($r as $rr) { @@ -899,21 +879,21 @@ function profile_sidebar($profile, $block = 0, $show_connect = true) { $marital = ((x($profile,'marital') == 1) ? t('Status:') : False); $homepage = ((x($profile,'homepage') == 1) ? t('Homepage:') : False); $profile['online'] = (($profile['online_status'] === 'online') ? t('Online Now') : False); -logger('online: ' . $profile['online']); + logger('online: ' . $profile['online']); if(! perm_is_allowed($profile['uid'],((is_array($observer)) ? $observer['xchan_hash'] : ''),'view_profile')) { $block = true; } if(($profile['hidewall'] && (! local_channel()) && (! remote_channel())) || $block ) { - $location = $reddress = $pdesc = $gender = $marital = $homepage = $online = False; + $location = $reddress = $pdesc = $gender = $marital = $homepage = False; } $firstname = ((strpos($profile['channel_name'],' ')) ? trim(substr($profile['channel_name'],0,strpos($profile['channel_name'],' '))) : $profile['channel_name']); $lastname = (($firstname === $profile['channel_name']) ? '' : trim(substr($profile['channel_name'],strlen($firstname)))); - $diaspora = array( + $diaspora = array( 'podloc' => z_root(), 'searchable' => (($block) ? 'false' : 'true'), 'nickname' => $profile['channel_address'], @@ -970,9 +950,9 @@ logger('online: ' . $profile['online']); } -// FIXME or remove - - +/** + * @FIXME or remove + */ function get_birthdays() { $a = get_app(); @@ -1030,7 +1010,6 @@ logger('online: ' . $profile['online']); $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . t('[today]') : ''); $rr['startime'] = Null; $rr['today'] = $today; - } } } @@ -1044,14 +1023,13 @@ logger('online: ' . $profile['online']); '$events' => $r, '$lbr' => '{', // raw brackets mess up if/endif macro processing '$rbr' => '}' - )); } -// FIXME - - +/** + * @FIXME + */ function get_events() { require_once('include/bbcode.php'); @@ -1085,7 +1063,6 @@ logger('online: ' . $profile['online']); } $classtoday = (($istoday) ? 'event-today' : ''); - foreach($r as &$rr) { if($rr['adjust']) $md = datetime_convert('UTC',$a->timezone,$rr['start'],'Y/m'); @@ -1132,19 +1109,19 @@ function advanced_profile(&$a) { if($a->profile['name']) { $tpl = get_markup_template('profile_advanced.tpl'); - + $profile = array(); - + $profile['fullname'] = array( t('Full Name:'), $a->profile['name'] ) ; - + if($a->profile['gender']) $profile['gender'] = array( t('Gender:'), $a->profile['gender'] ); - + $ob_hash = get_observer_hash(); if($ob_hash && perm_is_allowed($a->profile['profile_uid'],$ob_hash,'post_like')) { $profile['canlike'] = true; $profile['likethis'] = t('Like this channel'); $profile['profile_guid'] = $a->profile['profile_guid']; - } + } $likers = q("select liker, xchan.* from likes left join xchan on liker = xchan_hash where channel_id = %d and target_type = '%s' and verb = '%s'", intval($a->profile['profile_uid']), @@ -1175,19 +1152,19 @@ function advanced_profile(&$a) { : day_translate(datetime_convert('UTC','UTC','2001-' . substr($a->profile['dob'],5) . ' 00:00 +00:00',$short_bd_format))); } $profile['birthday'] = array( t('Birthday:'), $val); - } - if($age = age($a->profile['dob'],$a->profile['timezone'],'')) $profile['age'] = array( t('Age:'), $age ); - - - if($a->profile['marital']) $profile['marital'] = array( t('Status:'), $a->profile['marital']); + if($age = age($a->profile['dob'],$a->profile['timezone'],'')) + $profile['age'] = array( t('Age:'), $age ); + if($a->profile['marital']) + $profile['marital'] = array( t('Status:'), $a->profile['marital']); - if($a->profile['with']) $profile['marital']['with'] = bbcode($a->profile['with']); + if($a->profile['with']) + $profile['marital']['with'] = bbcode($a->profile['with']); if(strlen($a->profile['howlong']) && $a->profile['howlong'] !== NULL_DATE) { - $profile['howlong'] = relative_date($a->profile['howlong'], t('for %1$d %2$s')); + $profile['howlong'] = relative_date($a->profile['howlong'], t('for %1$d %2$s')); } if($a->profile['sexual']) $profile['sexual'] = array( t('Sexual Preference:'), $a->profile['sexual'] ); @@ -1243,54 +1220,55 @@ function advanced_profile(&$a) { // logger('mod_profile: things: ' . print_r($things,true), LOGGER_DATA); - return replace_macros($tpl, array( - '$title' => t('Profile'), + return replace_macros($tpl, array( + '$title' => t('Profile'), '$canlike' => (($profile['canlike'])? true : false), '$likethis' => t('Like this thing'), - '$profile' => $profile, + '$profile' => $profile, '$things' => $things - )); - } + )); + } return ''; } - - function get_my_url() { - if(x($_SESSION,'zrl_override')) + if(x($_SESSION, 'zrl_override')) return $_SESSION['zrl_override']; - if(x($_SESSION,'my_url')) + if(x($_SESSION, 'my_url')) return $_SESSION['my_url']; + return false; } function get_my_address() { - if(x($_SESSION,'zid_override')) + if(x($_SESSION, 'zid_override')) return $_SESSION['zid_override']; - if(x($_SESSION,'my_address')) + if(x($_SESSION, 'my_address')) return $_SESSION['my_address']; + return false; } /** - * @function zid_init(&$a) - * If somebody arrives at our site using a zid, add their xchan to our DB if we don't have it already. - * And if they aren't already authenticated here, attempt reverse magic auth. + * @brief + * + * If somebody arrives at our site using a zid, add their xchan to our DB if we don't have it already. + * And if they aren't already authenticated here, attempt reverse magic auth. + * + * @param App &$a * * @hooks 'zid_init' * string 'zid' - their zid * string 'url' - the destination url - * */ - function zid_init(&$a) { $tmp_str = get_my_address(); if(validate_email($tmp_str)) { proc_run('php','include/gprobe.php',bin2hex($tmp_str)); $arr = array('zid' => $tmp_str, 'url' => $a->cmd); - call_hooks('zid_init',$arr); + call_hooks('zid_init',$arr); if(! local_channel()) { $r = q("select * from hubloc where hubloc_addr = '%s' order by hubloc_connected desc limit 1", dbesc($tmp_str) @@ -1312,8 +1290,8 @@ function zid_init(&$a) { } /** - * @function zid($s,$address = '') - * Adds a zid parameter to a url + * @brief Adds a zid parameter to a url. + * * @param string $s * The url to accept the zid * @param boolean $address @@ -1325,31 +1303,33 @@ function zid_init(&$a) { * string zid - urlencoded zid * string result - the return string we calculated, change it if you want to return something else */ - - function zid($s,$address = '') { - if(! strlen($s) || strpos($s,'zid=')) + if (! strlen($s) || strpos($s,'zid=')) return $s; + $has_params = ((strpos($s,'?')) ? true : false); - $num_slashes = substr_count($s,'/'); - if(! $has_params) - $has_params = ((strpos($s,'&')) ? true : false); + $num_slashes = substr_count($s, '/'); + if (! $has_params) + $has_params = ((strpos($s, '&')) ? true : false); + $achar = strpos($s,'?') ? '&' : '?'; $mine = get_my_url(); $myaddr = (($address) ? $address : get_my_address()); - // FIXME checking against our own channel url is no longer reliable. We may have a lot - // of urls attached to out channel. Should probably match against our site, since we - // will not need to remote authenticate on our own site anyway. + /** @FIXME checking against our own channel url is no longer reliable. We may have a lot + * of urls attached to out channel. Should probably match against our site, since we + * will not need to remote authenticate on our own site anyway. + */ - if($mine && $myaddr && (! link_compare($mine,$s))) + if ($mine && $myaddr && (! link_compare($mine,$s))) $zurl = $s . (($num_slashes >= 3) ? '' : '/') . $achar . 'zid=' . urlencode($myaddr); else $zurl = $s; $arr = array('url' => $s, 'zid' => urlencode($myaddr), 'result' => $zurl); call_hooks('zid', $arr); + return $arr['result']; } @@ -1369,55 +1349,45 @@ function get_theme_uid() { $x = get_sys_channel(); if($x) return $x['channel_id']; - } + } + return $uid; } /** -* @function get_default_profile_photo($size = 175) -* Retrieves the path of the default_profile_photo for this system -* with the specified size. +* @brief Retrieves the path of the default_profile_photo for this system +* with the specified size. +* * @param int $size -* one of (175, 80, 48) +* one of (175, 80, 48) * @returns string -* */ - function get_default_profile_photo($size = 175) { - $scheme = get_config('system','default_profile_photo'); - if(! $scheme) - $scheme = 'rainbow_man'; - return 'images/default_profile_photos/' . $scheme . '/' . $size . '.png'; -} + $scheme = get_config('system','default_profile_photo'); + if(! $scheme) + $scheme = 'rainbow_man'; + return 'images/default_profile_photos/' . $scheme . '/' . $size . '.png'; +} /** + * @brief Test whether a given identity is NOT a member of the Red Matrix. * - * @function is_foreigner($s) - * Test whether a given identity is NOT a member of the Red Matrix * @param string $s; * xchan_hash of the identity in question - * * @returns boolean true or false - * */ - function is_foreigner($s) { - return((strpbrk($s,'.:@')) ? true : false); + return((strpbrk($s, '.:@')) ? true : false); } - /** + * @brief Test whether a given identity is a member of the Red Matrix. * - * @function is_member($s) - * Test whether a given identity is a member of the Red Matrix * @param string $s; * xchan_hash of the identity in question - * * @returns boolean true or false - * */ - function is_member($s) { return((is_foreigner($s)) ? false : true); } @@ -1464,8 +1434,8 @@ function remote_online_status($webbie) { if($j) $result = (($j['result']) ? $j['result'] : false); } - return $result; + return $result; } @@ -1477,17 +1447,20 @@ function get_channel_by_nick($nick) { } - +/** + * @brief + * + * @return string + */ function identity_selector() { - if(local_channel()) { + if (local_channel()) { $r = q("select channel.*, xchan.* from channel left join xchan on channel.channel_hash = xchan.xchan_hash where channel.channel_account_id = %d and (channel_pageflags & %d) = 0 order by channel_name ", intval(get_account_id()), intval(PAGE_REMOVED) ); - if(count($r) > 1) { - $selected_channel = null; - $account = get_app()->get_account(); - $o = replace_macros(get_markup_template('channel_id_select.tpl'),array( + if (count($r) > 1) { + //$account = get_app()->get_account(); + $o = replace_macros(get_markup_template('channel_id_select.tpl'), array( '$channels' => $r, '$selected' => local_channel() )); @@ -1507,6 +1480,7 @@ function is_public_profile() { $channel = get_app()->get_channel(); if($channel && $channel['channel_r_profile'] == PERMS_PUBLIC) return true; + return false; } @@ -1522,7 +1496,6 @@ function get_profile_fields_basic($filter = 0) { $x[$f] = 1; return $x; - } @@ -1536,6 +1509,7 @@ function get_profile_fields_advanced($filter = 0) { if($basic) foreach($basic as $f => $v) $x[$f] = $v; + if($profile_fields_advanced) foreach($profile_fields_advanced as $f) $x[$f] = 1; @@ -1544,28 +1518,26 @@ function get_profile_fields_advanced($filter = 0) { } /** - * @function notifications_off($channel_id) - * Clear notifyflags for a channel - most likely during bulk import of content or other activity that is likely - * to generate huge amounts of undesired notifications. + * @brief Clear notifyflags for a channel. + * + * Most likely during bulk import of content or other activity that is likely + * to generate huge amounts of undesired notifications. + * * @param int $channel_id * The channel to disable notifications for * @returns int * Current notification flag value. Send this to notifications_on() to restore the channel settings when finished * with the activity requiring notifications_off(); */ - - - function notifications_off($channel_id) { $r = q("select channel_notifyflags from channel where channel_id = %d limit 1", intval($channel_id) ); - $x = q("update channel set channel_notifyflags = 0 where channel_id = %d", + q("update channel set channel_notifyflags = 0 where channel_id = %d", intval($channel_id) ); return intval($r[0]['channel_notifyflags']); - } @@ -1586,5 +1558,6 @@ function get_channel_default_perms($uid) { ); if($r) return $r[0]['abook_my_perms']; + return 0; } diff --git a/include/items.php b/include/items.php index ef269b9c4..4b83ce3e3 100755 --- a/include/items.php +++ b/include/items.php @@ -1,4 +1,7 @@ -0 ", @@ -84,7 +93,7 @@ function collect_recipients($item,&$private_envelope) { switch($policy) { case 'net': case 'aut': - case 'sit': + case 'sit': case 'any': case 'con': if($rr['xchan_network'] != 'zot') @@ -103,7 +112,6 @@ function collect_recipients($item,&$private_envelope) { } } - // This is a somewhat expensive operation but important. // Don't send this item to anybody who isn't allowed to see it @@ -129,7 +137,6 @@ function collect_recipients($item,&$private_envelope) { $recipients[] = $item['owner_xchan']; return $recipients; - } /** @@ -139,30 +146,35 @@ function collect_recipients($item,&$private_envelope) { * They can still be addressed individually. * Networks may need to be added or removed from this list as circumstances change. * - * Update: this may need to be the default, which will force people to opt-in to sending stuff - * privately to insecure platforms. + * Update: this may need to be the default, which will force people to opt-in to + * sending stuff privately to insecure platforms. + * + * @param int $channel_id + * @param array $arr + * @return array containing the sane xchan_hashes */ - -function filter_insecure($channel_id,$arr) { +function filter_insecure($channel_id, $arr) { $insecure_nets = " and not xchan_network in ('diaspora', 'friendica-over-diaspora') "; $ret = array(); - if((! intval(get_config($channel_id,'system','filter_insecure_collections'))) || (! $arr)) + if((! intval(get_config($channel_id, 'system', 'filter_insecure_collections'))) || (! $arr)) return $arr; $str = ''; foreach($arr as $rr) { if(strlen($str)) $str .= ','; + $str .= "'" . dbesc($rr) . "'"; } - $r = q("select xchan_hash from xchan where xchan_hash in ($str) $insecure_nets "); + $r = q("select xchan_hash from xchan where xchan_hash in ($str) $insecure_nets"); if($r) { foreach($r as $rr) { $ret[] = $rr['xchan_hash']; } } + return $ret; } @@ -173,12 +185,13 @@ function comments_are_now_closed($item) { if($d > $item['comments_closed']) return true; } + return false; } /** - * @function can_comment_on_post($observer_xchan,$item); + * @brief * * This function examines the comment_policy attached to an item and decides if the current observer has * sufficient privileges to comment. This will normally be called on a remote site where perm_is_allowed() @@ -187,16 +200,18 @@ function comments_are_now_closed($item) { * If it is, you should be able to use perm_is_allowed( ... 'post_comments'), and if it isn't you need to call * can_comment_on_post() * We also check the comments_closed date/time on the item if this is set. + * + * @param string $observer_xchan + * @param array $item + * @return boolean */ - -function can_comment_on_post($observer_xchan,$item) { +function can_comment_on_post($observer_xchan, $item) { // logger('can_comment_on_post: comment_policy: ' . $item['comment_policy'], LOGGER_DEBUG); if(! $observer_xchan) return false; - if($item['comment_policy'] === 'none') return false; @@ -205,6 +220,7 @@ function can_comment_on_post($observer_xchan,$item) { if($observer_xchan === $item['author_xchan'] || $observer_xchan === $item['owner_xchan']) return true; + switch($item['comment_policy']) { case 'self': if($observer_xchan === $item['author_xchan'] || $observer_xchan === $item['owner_xchan']) @@ -233,36 +249,36 @@ function can_comment_on_post($observer_xchan,$item) { return true; if(strstr($item['comment_policy'],'site:') && strstr($item['comment_policy'],get_app()->get_hostname())) return true; - + return false; } /** - * @function add_source_route($iid,$hash) - * Adds $hash to the item source route specified by $iid - * @param integer $iid - * item['id'] of target item - * @param string $hash - * xchan_hash of the channel that sent the item - * Modifies item pointed to by $iid + * @brief Adds $hash to the item source route specified by $iid. * * $item['route'] contains a comma-separated list of xchans that sent the current message, * somewhat analogous to the * Received: header line in email. We can use this to perform * loop detection and to avoid sending a particular item to any "upstream" sender (they - * already have a copy because they sent it to us). + * already have a copy because they sent it to us). + * + * Modifies item in the database pointed to by $iid. * + * @param integer $iid + * item['id'] of target item + * @param string $hash + * xchan_hash of the channel that sent the item */ - -function add_source_route($iid,$hash) { +function add_source_route($iid, $hash) { // logger('add_source_route ' . $iid . ' ' . $hash, LOGGER_DEBUG); if((! $iid) || (! $hash)) return; + $r = q("select route from item where id = %d limit 1", intval($iid) ); if($r) { - $new_route = (($r[0]['route']) ? $r[0]['route'] . ',' : '') . $hash; + $new_route = (($r[0]['route']) ? $r[0]['route'] . ',' : '') . $hash; q("update item set route = '%s' where id = %d", (dbesc($new_route)), intval($iid) @@ -271,17 +287,17 @@ function add_source_route($iid,$hash) { } - /** - * @function red_zrl_callback - * preg_match function when fixing 'naked' links in mod item.php - * Check if we've got a hubloc for the site and use a zrl if we do, a url if we don't. - * Remove any existing zid= param which may have been pasted by mistake - and will have - * the author's credentials. zid's are dynamic and can't really be passed around like - * that. + * @brief preg_match function when fixing 'naked' links in mod item.php. + * + * Check if we've got a hubloc for the site and use a zrl if we do, a url if we don't. + * Remove any existing zid= param which may have been pasted by mistake - and will have + * the author's credentials. zid's are dynamic and can't really be passed around like + * that. + * + * @param array $matches + * @return string */ - - function red_zrl_callback($matches) { require_once('include/hubloc.php'); $zrl = is_matrix_url($matches[2]); @@ -296,19 +312,24 @@ function red_zrl_callback($matches) { $matches[1] = ''; if($zrl) return $matches[1] . '#^[zrl=' . $matches[2] . ']' . $matches[2] . '[/zrl]'; + return $matches[1] . '#^[url=' . $matches[2] . ']' . $matches[2] . '[/url]'; } - -// If we've got a url or zrl tag with a naked url somewhere in the link text, -// escape it with quotes unless the naked url is a linked photo. - +/** + * If we've got a url or zrl tag with a naked url somewhere in the link text, + * escape it with quotes unless the naked url is a linked photo. + * + * @param array $matches + * @return string + */ function red_escape_zrl_callback($matches) { // Uncertain why the url/zrl forms weren't picked up by the non-greedy regex. - if((strpos($matches[3],'zmg') !== false) || (strpos($matches[3],'img') !== false) || (strpos($matches[3],'zrl') !== false) || (strpos($matches[3],'url') !== false)) + if((strpos($matches[3], 'zmg') !== false) || (strpos($matches[3], 'img') !== false) || (strpos($matches[3],'zrl') !== false) || (strpos($matches[3],'url') !== false)) return $matches[0]; + return '[' . $matches[1] . 'rl' . $matches[2] . ']' . $matches[3] . '"' . $matches[4] . '"' . $matches[5] . '[/' . $matches[6] . 'rl]'; } @@ -318,7 +339,6 @@ function red_escape_codeblock($m) { function red_unescape_codeblock($m) { return '[' . $m[2] . base64_decode($m[1]) . '[/' . $m[2] . ']'; - } @@ -334,28 +354,23 @@ function red_zrlify_img_callback($matches) { if($zrl) return '[zmg' . $matches[1] . ']' . $matches[2] . '[/zmg]'; + return $matches[0]; } - - /** - * @function post_activity_item($arr) - * - * post an activity - * - * @param array $arr + * @brief Post an activity. * * In its simplest form one needs only to set $arr['body'] to post a note to the logged in channel's wall. * Much more complex activities can be created. Permissions are checked. No filtering, tag expansion * or other processing is performed. * - * @returns array - * 'success' => true or false - * 'activity' => the resulting activity if successful + * @param array $arr + * @returns array + * * \e boolean \b success true or false + * * \e array \b activity the resulting activity if successful */ - function post_activity_item($arr) { $ret = array('success' => false); @@ -369,14 +384,13 @@ function post_activity_item($arr) { $arr['item_flags'] = ITEM_ORIGIN; else $arr['item_flags'] = ITEM_ORIGIN | ITEM_WALL | ITEM_THREAD_TOP; - } - + } $channel = get_app()->get_channel(); $observer = get_app()->get_observer(); - $arr['aid'] = ((x($arr,'aid')) ? $arr['aid'] : $channel['channel_account_id']); - $arr['uid'] = ((x($arr,'uid')) ? $arr['uid'] : $channel['channel_id']); + $arr['aid'] = ((x($arr,'aid')) ? $arr['aid'] : $channel['channel_account_id']); + $arr['uid'] = ((x($arr,'uid')) ? $arr['uid'] : $channel['channel_id']); if(! perm_is_allowed($arr['uid'],$observer['xchan_hash'],(($is_comment) ? 'post_comments' : 'post_wall'))) { $ret['message'] = t('Permission denied'); @@ -410,19 +424,18 @@ function post_activity_item($arr) { $arr['body'] = json_encode(crypto_encapsulate($arr['body'],$key)); } - $arr['mid'] = ((x($arr,'mid')) ? $arr['mid'] : item_message_id()); - $arr['parent_mid'] = ((x($arr,'parent_mid')) ? $arr['parent_mid'] : $arr['mid']); - $arr['thr_parent'] = ((x($arr,'thr_parent')) ? $arr['thr_parent'] : $arr['mid']); + $arr['mid'] = ((x($arr,'mid')) ? $arr['mid'] : item_message_id()); + $arr['parent_mid'] = ((x($arr,'parent_mid')) ? $arr['parent_mid'] : $arr['mid']); + $arr['thr_parent'] = ((x($arr,'thr_parent')) ? $arr['thr_parent'] : $arr['mid']); - $arr['owner_xchan'] = ((x($arr,'owner_xchan')) ? $arr['owner_xchan'] : $channel['channel_hash']); - $arr['author_xchan'] = ((x($arr,'author_xchan')) ? $arr['author_xchan'] : $observer['xchan_hash']); + $arr['owner_xchan'] = ((x($arr,'owner_xchan')) ? $arr['owner_xchan'] : $channel['channel_hash']); + $arr['author_xchan'] = ((x($arr,'author_xchan')) ? $arr['author_xchan'] : $observer['xchan_hash']); - $arr['verb'] = ((x($arr,'verb')) ? $arr['verb'] : ACTIVITY_POST); - $arr['obj_type'] = ((x($arr,'obj_type')) ? $arr['obj_type'] : ACTIVITY_OBJ_NOTE); + $arr['verb'] = ((x($arr,'verb')) ? $arr['verb'] : ACTIVITY_POST); + $arr['obj_type'] = ((x($arr,'obj_type')) ? $arr['obj_type'] : ACTIVITY_OBJ_NOTE); if($is_comment) $arr['obj_type'] = ACTIVITY_OBJ_COMMENT; - $arr['allow_cid'] = ((x($arr,'allow_cid')) ? $arr['allow_cid'] : $channel['channel_allow_cid']); $arr['allow_gid'] = ((x($arr,'allow_gid')) ? $arr['allow_gid'] : $channel['channel_allow_gid']); $arr['deny_cid'] = ((x($arr,'deny_cid')) ? $arr['deny_cid'] : $channel['channel_deny_cid']); @@ -430,7 +443,6 @@ function post_activity_item($arr) { $arr['comment_policy'] = map_scope($channel['channel_w_comment']); - if ((! $arr['plink']) && ($arr['item_flags'] & ITEM_THREAD_TOP)) { $arr['plink'] = z_root() . '/channel/' . $channel['channel_address'] . '/?f=&mid=' . $arr['mid']; } @@ -447,7 +459,6 @@ function post_activity_item($arr) { return $ret; } - $post = item_store($arr); if($post['success']) $post_id = $post['item_id']; @@ -465,15 +476,15 @@ function post_activity_item($arr) { } return $ret; - } /** - * @function get_public_feed($channel,$params) - * generate an Atom feed + * @brief Generate an Atom feed. + * + * @param array $channel + * @param array $params */ - -function get_public_feed($channel,$params) { +function get_public_feed($channel, $params) { $type = 'xml'; $begin = NULL_DATE; @@ -494,7 +505,7 @@ function get_public_feed($channel,$params) { $params['direction'] = ((x($params,'direction')) ? $params['direction'] : 'desc'); $params['pages'] = ((x($params,'pages')) ? intval($params['pages']) : 0); $params['top'] = ((x($params,'top')) ? intval($params['top']) : 0); - + switch($params['type']) { case 'json': header("Content-type: application/atom+json"); @@ -505,24 +516,26 @@ function get_public_feed($channel,$params) { break; } - - return get_feed_for($channel,get_observer_hash(),$params); + return get_feed_for($channel, get_observer_hash(), $params); } - - - +/** + * @brief + * + * @param array $channel + * @param string $observer_hash + * @param array $params + * @return string + */ function get_feed_for($channel, $observer_hash, $params) { if(! channel) http_status_exit(401); - if($params['pages']) { if(! perm_is_allowed($channel['channel_id'],$observer_hash,'view_pages')) http_status_exit(403); - } - else { + } else { if(! perm_is_allowed($channel['channel_id'],$observer_hash,'view_stream')) http_status_exit(403); } @@ -538,7 +551,6 @@ function get_feed_for($channel, $observer_hash, $params) { 'top' => $params['top'] ), $channel, $observer_hash, CLIENT_MODE_NORMAL, get_app()->module); - $feed_template = get_markup_template('atom_feed.tpl'); $atom = ''; @@ -571,7 +583,8 @@ function get_feed_for($channel, $observer_hash, $params) { if($item['item_private']) continue; - $atom .= atom_entry($item,$type,null,$owner,true); + /** @BUG $owner is undefined in this call */ + $atom .= atom_entry($item, $type, null, $owner, true); } } @@ -604,11 +617,11 @@ function construct_activity_object($item) { if($r->title) $o .= '' . xmlify($r->title) . '' . "\r\n"; if($r->links) { - // FIXME!! + /** @FIXME!! */ if(substr($r->link,0,1) === '<') { $r->link = preg_replace('/\/','',$r->link); $o .= $r->link; - } + } else $o .= '' . "\r\n"; } @@ -635,7 +648,7 @@ function construct_activity_target($item) { if($r->title) $o .= '' . xmlify($r->title) . '' . "\r\n"; if($r->links) { - // FIXME !!! + /** @FIXME !!! */ if(substr($r->link,0,1) === '<') { if(strstr($r->link,'&') && (! strstr($r->link,'&'))) $r->link = str_replace('&','&', $r->link); @@ -654,12 +667,15 @@ function construct_activity_target($item) { return ''; } -/* limit_body_size() +/** + * @brief Limit lenght on imported system messages. + * + * The purpose of this function is to apply system message length limits to + * imported messages without including any embedded photos in the length. * - * The purpose of this function is to apply system message length limits to - * imported messages without including any embedded photos in the length + * @param string $body + * @return string|unknown */ - function limit_body_size($body) { $maxlen = get_max_import_size(); @@ -671,7 +687,6 @@ function limit_body_size($body) { $orig_body = $body; $new_body = ''; $textlen = 0; - $max_found = false; $img_start = strpos($orig_body, '[img'); $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false); @@ -700,7 +715,6 @@ function limit_body_size($body) { $new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start); } else { - if( ($textlen + $img_end) > $maxlen ) { if($textlen < $maxlen) { $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen); @@ -836,12 +850,8 @@ function get_item_elements($x) { $arr['item_flags'] = 0; - if(array_key_exists('flags',$x) && in_array('consensus',$x['flags'])) $arr['item_flags'] |= ITEM_CONSENSUS; - - - if(array_key_exists('flags',$x) && in_array('deleted',$x['flags'])) $arr['item_restrict'] |= ITEM_DELETED; if(array_key_exists('flags',$x) && in_array('hidden',$x['flags'])) @@ -868,7 +878,6 @@ function get_item_elements($x) { return array(); } - if($arr['sig']) { $r = q("select xchan_pubkey from xchan where xchan_hash = '%s' limit 1", dbesc($arr['author_xchan']) @@ -885,7 +894,6 @@ function get_item_elements($x) { // and we need plaintext to do that. - if(intval($arr['item_private'])) { $arr['item_flags'] = $arr['item_flags'] | ITEM_OBSCURED; if($arr['title']) @@ -914,7 +922,6 @@ function get_item_elements($x) { } return $arr; - } @@ -998,7 +1005,6 @@ function import_author_rss($x) { } return false; - } function import_author_unknown($x) { @@ -1043,7 +1049,6 @@ function import_author_unknown($x) { } return false; - } function encode_item($item,$mirror = false) { @@ -1150,7 +1155,6 @@ function encode_item($item,$mirror = false) { logger('encode_item: ' . print_r($x,true), LOGGER_DATA); return $x; - } @@ -1174,7 +1178,7 @@ function map_scope($scope,$strip = false) { default: return 'contacts'; } -} +} function translate_scope($scope) { if(! $scope || $scope === 'public') @@ -1269,12 +1273,16 @@ function decode_tags($t) { } return $ret; } - return ''; + return ''; } -// santise a potentially complex array - +/** + * @brief Santise a potentially complex array. + * + * @param array $arr + * @return array|string + */ function activity_sanitise($arr) { if($arr) { if(is_array($arr)) { @@ -1291,11 +1299,16 @@ function activity_sanitise($arr) { return htmlspecialchars($arr, ENT_COMPAT,'UTF-8', false); } } + return ''; } -// sanitise a simple linear array - +/** + * @brief Sanitise a simple linear array. + * + * @param array $arr + * @return array|string + */ function array_sanitise($arr) { if($arr) { $ret = array(); @@ -1304,6 +1317,7 @@ function array_sanitise($arr) { } return $ret; } + return ''; } @@ -1326,7 +1340,7 @@ function encode_item_flags($item) { $ret[] = 'consensus'; if($item['item_private']) $ret[] = 'private'; - + return $ret; } @@ -1419,7 +1433,6 @@ function get_mail_elements($x) { return array(); return $arr; - } @@ -1448,15 +1461,17 @@ function get_profile_elements($x) { $arr['keywords'] = (($x['keywords'] && is_array($x['keywords'])) ? array_sanitise($x['keywords']) : array()); return $arr; - } +/** + * @param object $feed + * @param array $item + * @param[out] array $author + * @return multitype:multitype: string NULL number Ambigous Ambigous Ambigous , multitype:multitype:string unknown > multitype:NULL unknown + */ +function get_atom_elements($feed, $item, &$author) { - -function get_atom_elements($feed,$item,&$author) { - - - $best_photo = array(); + //$best_photo = array(); $res = array(); @@ -1531,7 +1546,7 @@ function get_atom_elements($feed,$item,&$author) { if($rawmedia && $rawmedia[0]['attribs']['']['url']) { $author['author_photo'] = strip_tags(unxmlify($rawmedia[0]['attribs']['']['url'])); } - } + } // No photo/profile-link on the item - look at the feed level @@ -1573,9 +1588,9 @@ function get_atom_elements($feed,$item,&$author) { $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info'); if($apps && $apps[0]['attribs']['']['source']) { $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source'])); - } + } - /** + /* * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it. */ @@ -1593,10 +1608,8 @@ function get_atom_elements($feed,$item,&$author) { // create a term table item for them. For now just make sure they stay as links. $res['body'] = preg_replace('/\[bookmark(.*?)\](.*?)\[\/bookmark\]/','[url$1]$2[/url]',$res['body']); - } - $res['body'] = limit_body_size($res['body']); // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust @@ -1620,8 +1633,6 @@ function get_atom_elements($feed,$item,&$author) { $res['body'] = purify_html($res['body']); $res['body'] = @html2bbcode($res['body']); - - } elseif(! $have_real_body) { @@ -1652,7 +1663,6 @@ function get_atom_elements($feed,$item,&$author) { ); } - $private = $item->get_item_tags(NAMESPACE_DFRN,'private'); if($private && intval($private[0]['data']) > 0) $res['item_private'] = ((intval($private[0]['data'])) ? 1 : 0); @@ -1663,12 +1673,10 @@ function get_atom_elements($feed,$item,&$author) { if($rawlocation) $res['location'] = unxmlify($rawlocation[0]['data']); - $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published'); if($rawcreated) $res['created'] = unxmlify($rawcreated[0]['data']); - $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated'); if($rawedited) $res['edited'] = unxmlify($rawedited[0]['data']); @@ -1735,7 +1743,7 @@ function get_atom_elements($feed,$item,&$author) { } // translate OStatus unfollow to activity streams if it happened to get selected - + if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow')) $res['verb'] = ACTIVITY_UNFOLLOW; @@ -1765,7 +1773,7 @@ function get_atom_elements($feed,$item,&$author) { 'url' => $termurl, 'term' => $termterm, ); - } + } } } @@ -1790,6 +1798,7 @@ function get_atom_elements($feed,$item,&$author) { $title = ' '; if(! $type) $type = 'application/octet-stream'; + $res['attach'][] = array('href' => $link, 'length' => $len, 'type' => $type, 'title' => $title ); } } @@ -1817,10 +1826,8 @@ function get_atom_elements($feed,$item,&$author) { // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events $obj['orig'] = xmlify($body); if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) { - $body = purify_html($body); $body = html2bbcode($body); - } $obj['content'] = $body; @@ -1838,7 +1845,7 @@ function get_atom_elements($feed,$item,&$author) { if($child[NAMESPACE_ACTIVITY]['obj_type'][0]['data']) { $res['tgt_type'] = $child[NAMESPACE_ACTIVITY]['obj_type'][0]['data']; $obj['type'] = $child[NAMESPACE_ACTIVITY]['obj_type'][0]['data']; - } + } if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data']) $obj['id'] = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data']; if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) @@ -1849,13 +1856,12 @@ function get_atom_elements($feed,$item,&$author) { $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']; if(! $body) $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data']; + // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events $obj['orig'] = xmlify($body); if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) { - $body = purify_html($body); $body = html2bbcode($body); - } $obj['content'] = $body; @@ -1896,6 +1902,7 @@ function encode_rel_links($links) { $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" '; $o .= ' />' . "\n" ; } + return xmlify($o); } @@ -1915,7 +1922,7 @@ function item_store($arr,$allow_exec = false) { return $ret; } - $uplinked_comment = false; + //$uplinked_comment = false; // If a page layout is provided, ensure it exists and belongs to us. @@ -1955,8 +1962,6 @@ function item_store($arr,$allow_exec = false) { $arr['item_private'] = ((x($arr,'item_private')) ? intval($arr['item_private']) : 0 ); $arr['item_flags'] = ((x($arr,'item_flags')) ? intval($arr['item_flags']) : 0 ); - - // only detect language if we have text content, and if the post is private but not yet // obscured, make it so. @@ -1966,7 +1971,6 @@ function item_store($arr,$allow_exec = false) { // apply the input filter here - if it is obscured it has been filtered already $arr['body'] = z_input_filter($arr['uid'],$arr['body'],$arr['mimetype']); - if(local_channel() && (! $arr['sig'])) { $channel = get_app()->get_channel(); if($channel['channel_hash'] === $arr['author_xchan']) { @@ -1995,7 +1999,6 @@ function item_store($arr,$allow_exec = false) { if($arr['body']) $arr['body'] = json_encode(crypto_encapsulate($arr['body'],$key)); } - } if((x($arr,'object')) && is_array($arr['object'])) { @@ -2042,13 +2045,12 @@ function item_store($arr,$allow_exec = false) { $arr['public_policy'] = ((x($arr,'public_policy')) ? notags(trim($arr['public_policy'])) : '' ); $arr['comment_policy'] = ((x($arr,'comment_policy')) ? notags(trim($arr['comment_policy'])) : 'contacts' ); - + $arr['item_unseen'] = ((array_key_exists('item_unseen',$arr)) ? intval($arr['item_unseen']) : 1); if($arr['comment_policy'] == 'none') $arr['item_flags'] = $arr['item_flags'] | ITEM_NOCOMMENT; - // handle time travelers // Allow a bit of fudge in case somebody just has a slightly slow/fast clock @@ -2062,8 +2064,6 @@ function item_store($arr,$allow_exec = false) { if(! $arr['plink']) $arr['plink'] = $arr['llink']; - - if($arr['parent_mid'] === $arr['mid']) { $parent_id = 0; $parent_deleted = 0; @@ -2134,13 +2134,12 @@ function item_store($arr,$allow_exec = false) { if($r[0]['item_flags'] & ITEM_WALL) $arr['item_flags'] = $arr['item_flags'] | ITEM_WALL; - // An uplinked comment might arrive with a downstream owner. // Fix it. if($r[0]['owner_xchan'] !== $arr['owner_xchan']) { $arr['owner_xchan'] = $r[0]['owner_xchan']; - $uplinked_comment = true; +// $uplinked_comment = true; } // if the parent is private, force privacy for the entire conversation @@ -2164,8 +2163,7 @@ function item_store($arr,$allow_exec = false) { if($parent_deleted) $arr['item_restrict'] = $arr['item_restrict'] | ITEM_DELETED; - - + $r = q("SELECT `id` FROM `item` WHERE `mid` = '%s' AND `uid` = %d LIMIT 1", dbesc($arr['mid']), intval($arr['uid']) @@ -2270,7 +2268,7 @@ function item_store($arr,$allow_exec = false) { } $arr['term'] = $terms; - } + } call_hooks('post_remote_end',$arr); @@ -2337,7 +2335,7 @@ function item_store_update($arr,$allow_exec = false) { logger('item_store_update: original post not found: ' . $orig_post_id); $ret['message'] = 'no original'; return $ret; - } + } // override the unseen flag with the original @@ -2350,13 +2348,12 @@ function item_store_update($arr,$allow_exec = false) { if($orig[0]['item_flags'] & ITEM_OBSCURED) $orig[0]['item_flags'] = $orig[0]['item_flags'] ^ ITEM_OBSCURED; - $arr['item_flags'] = intval($arr['item_flags']) | $orig[0]['item_flags']; $arr['item_restrict'] = intval($arr['item_restrict']) | $orig[0]['item_restrict']; - if(array_key_exists('edit',$arr)) - unset($arr['edit']); + unset($arr['edit']); + $arr['mimetype'] = ((x($arr,'mimetype')) ? notags(trim($arr['mimetype'])) : 'text/bbcode'); if(($arr['mimetype'] == 'application/x-php') && (! $allow_exec)) { @@ -2365,19 +2362,19 @@ function item_store_update($arr,$allow_exec = false) { return $ret; } - if(! ($arr['item_flags'] & ITEM_OBSCURED)) { + if(! ($arr['item_flags'] & ITEM_OBSCURED)) { $arr['lang'] = detect_language($arr['body']); - // apply the input filter here - if it is obscured it has been filtered already - $arr['body'] = z_input_filter($arr['uid'],$arr['body'],$arr['mimetype']); - - if(local_channel() && (! $arr['sig'])) { - $channel = get_app()->get_channel(); - if($channel['channel_hash'] === $arr['author_xchan']) { - $arr['sig'] = base64url_encode(rsa_sign($arr['body'],$channel['channel_prvkey'])); - $arr['item_flags'] |= ITEM_VERIFIED; - } - } + // apply the input filter here - if it is obscured it has been filtered already + $arr['body'] = z_input_filter($arr['uid'],$arr['body'],$arr['mimetype']); + + if(local_channel() && (! $arr['sig'])) { + $channel = get_app()->get_channel(); + if($channel['channel_hash'] === $arr['author_xchan']) { + $arr['sig'] = base64url_encode(rsa_sign($arr['body'],$channel['channel_prvkey'])); + $arr['item_flags'] |= ITEM_VERIFIED; + } + } $allowed_languages = get_pconfig($arr['uid'],'system','allowed_languages'); @@ -2392,17 +2389,15 @@ function item_store_update($arr,$allow_exec = false) { $arr = $translate['item']; } if($arr['item_private']) { - $key = get_config('system','pubkey'); - $arr['item_flags'] = $arr['item_flags'] | ITEM_OBSCURED; - if($arr['title']) - $arr['title'] = json_encode(crypto_encapsulate($arr['title'],$key)); - if($arr['body']) - $arr['body'] = json_encode(crypto_encapsulate($arr['body'],$key)); - } - + $key = get_config('system','pubkey'); + $arr['item_flags'] = $arr['item_flags'] | ITEM_OBSCURED; + if($arr['title']) + $arr['title'] = json_encode(crypto_encapsulate($arr['title'],$key)); + if($arr['body']) + $arr['body'] = json_encode(crypto_encapsulate($arr['body'],$key)); + } } - if((x($arr,'object')) && is_array($arr['object'])) { activity_sanitise($arr['object']); $arr['object'] = json_encode($arr['object']); @@ -2418,7 +2413,6 @@ function item_store_update($arr,$allow_exec = false) { $arr['attach'] = json_encode($arr['attach']); } - unset($arr['id']); unset($arr['uid']); unset($arr['aid']); @@ -2465,15 +2459,13 @@ function item_store_update($arr,$allow_exec = false) { $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : $orig[0]['app']); // $arr['item_restrict'] = ((x($arr,'item_restrict')) ? intval($arr['item_restrict']) : $orig[0]['item_restrict'] ); // $arr['item_flags'] = ((x($arr,'item_flags')) ? intval($arr['item_flags']) : $orig[0]['item_flags'] ); - + $arr['sig'] = ((x($arr,'sig')) ? $arr['sig'] : ''); $arr['layout_mid'] = ((array_key_exists('layout_mid',$arr)) ? dbesc($arr['layout_mid']) : $orig[0]['layout_mid'] ); $arr['public_policy'] = ((x($arr,'public_policy')) ? notags(trim($arr['public_policy'])) : $orig[0]['public_policy'] ); $arr['comment_policy'] = ((x($arr,'comment_policy')) ? notags(trim($arr['comment_policy'])) : $orig[0]['comment_policy'] ); - - call_hooks('post_remote_update',$arr); if(x($arr,'cancel')) { @@ -2495,11 +2487,11 @@ function item_store_update($arr,$allow_exec = false) { logger('item_store_update: ' . print_r($arr,true), LOGGER_DATA); $str = ''; - foreach($arr as $k => $v) { - if($str) - $str .= ","; - $str .= " `" . $k . "` = '" . $v . "' "; - } + foreach($arr as $k => $v) { + if($str) + $str .= ","; + $str .= " `" . $k . "` = '" . $v . "' "; + } $r = dbq("update `item` set " . $str . " where id = " . $orig_post_id ); @@ -2530,7 +2522,7 @@ function item_store_update($arr,$allow_exec = false) { } $arr['term'] = $terms; - } + } call_hooks('post_remote_update_end',$arr); @@ -2568,8 +2560,9 @@ function store_diaspora_comment_sig($datarray, $channel, $parent_item, $post_id, $signed_text = $datarray['mid'] . ';' . $parent_item['mid'] . ';' . $signed_body . ';' . $diaspora_handle; + /** @FIXME $uprvkey is undefined, do we still need this if-statement? */ if( $uprvkey !== false ) - $authorsig = base64_encode(rsa_sign($signed_text,$channel['channel_prvkey'],'sha256')); + $authorsig = base64_encode(rsa_sign($signed_text, $channel['channel_prvkey'], 'sha256')); else $authorsig = ''; @@ -2630,7 +2623,6 @@ function send_status_notifications($post_id,$item) { $link = get_app()->get_baseurl() . '/display/' . $item['mid']; - $y = q("select id from notify where link = '%s' and uid = %d limit 1", dbesc($link), intval($item['uid']) @@ -2641,50 +2633,50 @@ function send_status_notifications($post_id,$item) { if(! $notify) return; + require_once('include/enotify.php'); notification(array( 'type' => NOTIFY_COMMENT, 'from_xchan' => $item['author_xchan'], 'to_xchan' => $r[0]['channel_hash'], 'item' => $item, - 'link' => $link, + 'link' => $link, 'verb' => ACTIVITY_POST, 'otype' => 'item', 'parent' => $parent, 'parent_mid' => $item['parent_mid'] )); - return; } - - - - function get_item_contact($item,$contacts) { if(! count($contacts) || (! is_array($item))) return false; + foreach($contacts as $contact) { if($contact['id'] == $item['contact-id']) { return $contact; break; // NOTREACHED } } + return false; } - -function tag_deliver($uid,$item_id) { - - // Called when we deliver things that might be tagged in ways that require delivery processing. - // Handles community tagging of posts and also look for mention tags - // and sets up a second delivery chain if appropriate - - $a = get_app(); +/** + * @brief Called when we deliver things that might be tagged in ways that require delivery processing. + * + * Handles community tagging of posts and also look for mention tags and sets up + * a second delivery chain if appropriate. + * + * @param int $uid + * @param int $item_id + */ +function tag_deliver($uid, $item_id) { $mention = false; - /** + /* * Fetch stuff we need - a channel and an item */ @@ -2693,7 +2685,7 @@ function tag_deliver($uid,$item_id) { ); if(! $u) return; - + $i = q("select * from item where id = %d and uid = %d limit 1", intval($item_id), intval($uid) @@ -2713,8 +2705,7 @@ function tag_deliver($uid,$item_id) { return; } - - /** + /* * Seems like a good place to plug in a poke notification. */ @@ -2722,7 +2713,7 @@ function tag_deliver($uid,$item_id) { $poke_notify = true; if(($item['obj_type'] == "") || ($item['obj_type'] !== ACTIVITY_OBJ_PERSON) || (! $item['object'])) - $poke_notify = false; + $poke_notify = false; $obj = json_decode_plus($item['object']); if($obj) { @@ -2732,7 +2723,6 @@ function tag_deliver($uid,$item_id) { if($item['item_restrict'] & ITEM_DELETED) $poke_notify = false; - $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1)); if($poke_notify) { require_once('include/enotify.php'); @@ -2749,7 +2739,7 @@ function tag_deliver($uid,$item_id) { } } - /** + /* * Do community tagging */ @@ -2783,7 +2773,7 @@ function tag_deliver($uid,$item_id) { dbesc(datetime_convert()), dbesc($j_tgt['id']), intval($u[0]['channel_id']) - ); + ); proc_run('php','include/notifier.php','edit_post',$p[0]['id']); } } @@ -2793,7 +2783,7 @@ function tag_deliver($uid,$item_id) { logger('tag_deliver: tag permission denied for ' . $u[0]['channel_address']); } - /** + /* * A "union" is a message which our channel has sourced from another channel. * This sets up a second delivery chain just like forum tags do. * Find out if this is a source-able post. @@ -2819,11 +2809,10 @@ function tag_deliver($uid,$item_id) { } - /** + /* * Now we've got those out of the way. Let's see if this is a post that's tagged for re-delivery */ - $terms = get_terms_oftype($item['term'],TERM_MENTION); if($terms) @@ -2833,20 +2822,20 @@ function tag_deliver($uid,$item_id) { if($terms) { foreach($terms as $term) { - if(link_compare($term['url'],$link)) { + if(link_compare($term['url'],$link)) { $mention = true; break; } } - } + } if($mention) { logger('tag_deliver: mention found for ' . $u[0]['channel_name']); - + $r = q("update item set item_flags = ( item_flags | %d ) where id = %d", intval(ITEM_MENTIONSME), intval($item_id) - ); + ); // At this point we've determined that the person receiving this post was mentioned in it or it is a union. // Now let's check if this mention was inside a reshare so we don't spam a forum @@ -2866,6 +2855,7 @@ function tag_deliver($uid,$item_id) { $tagged = false; $plustagged = false; + $matches = array(); $pattern = '/@\!?\[zrl\=' . preg_quote($term['url'],'/') . '\]' . preg_quote($term['term'],'/') . '\[\/zrl\]/'; if(preg_match($pattern,$body,$matches)) @@ -2898,7 +2888,7 @@ function tag_deliver($uid,$item_id) { $arr = array('channel_id' => $uid, 'item' => $item, 'body' => $body); call_hooks('tagged',$arr); - /** + /* * Kill two birds with one stone. As long as we're here, send a mention notification. */ @@ -2926,7 +2916,6 @@ function tag_deliver($uid,$item_id) { logger('tag_delivery denied for uid ' . $uid . ' and xchan ' . $item['author_xchan']); return; } - } if((! $mention) && (! $union)) { @@ -2948,25 +2937,18 @@ function tag_deliver($uid,$item_id) { logger('tag_deliver: creating second delivery chain.'); start_delivery_chain($u[0],$item,$item_id,null); - } /** - * @function tgroup_check($uid,$item) + * @brief This function is called pre-deliver to see if a post matches the criteria to be tag delivered. * - * This function is called pre-deliver to see if a post matches the criteria to be tag delivered. * We don't actually do anything except check that it matches the criteria. * This is so that the channel with tag_delivery enabled can receive the post even if they turn off * permissions for the sender to send their stream. tag_deliver() can't be called until the post is actually stored. * By then it would be too late to reject it. */ - - - function tgroup_check($uid,$item) { - $a = get_app(); - $mention = false; // check that the message originated elsewhere and is a top-level post @@ -2980,6 +2962,7 @@ function tgroup_check($uid,$item) { ); if($r) return true; + return false; } if(! perm_is_allowed($uid,$item['author_xchan'],'tag_deliver')) @@ -3001,13 +2984,12 @@ function tgroup_check($uid,$item) { if($terms) { foreach($terms as $term) { - if(link_compare($term['url'],$link)) { + if(link_compare($term['url'],$link)) { $mention = true; break; } } - } - + } if($mention) { logger('tgroup_check: mention found for ' . $u[0]['channel_name']); @@ -3029,12 +3011,12 @@ function tgroup_check($uid,$item) { $body = preg_replace('/\[share(.*?)\[\/share\]/','',$body); - // $pattern = '/@\!?\[zrl\=' . preg_quote($term['url'],'/') . '\]' . preg_quote($term['term'] . '+','/') . '\[\/zrl\]/'; $pattern = '/@\!?\[zrl\=([^\]]*?)\]((?:.(?!\[zrl\=))*?)\+\[\/zrl\]/'; $found = false; + $matches = array(); if(preg_match_all($pattern,$body,$matches,PREG_SET_ORDER)) { $max_forums = get_config('system','max_tagged_forums'); @@ -3059,7 +3041,6 @@ function tgroup_check($uid,$item) { } return true; - } /** @@ -3067,10 +3048,13 @@ function tgroup_check($uid,$item) { * receiving the post. This starts the second delivery chain, by resetting permissions and ensuring * that ITEM_UPLINK is set on the parent post, and storing the current owner_xchan as the source_xchan. * We'll become the new owner. If called without $parent, this *is* the parent post. + * + * @param array $channel + * @param array $item + * @param int $item_id + * @param boolean $parent */ - -function start_delivery_chain($channel,$item,$item_id,$parent) { - +function start_delivery_chain($channel, $item, $item_id, $parent) { // Change this copy of the post to a forum head message and deliver to all the tgroup members // also reset all the privacy bits to the forum default permissions @@ -3093,7 +3077,6 @@ function start_delivery_chain($channel,$item,$item_id,$parent) { if(! $parent) $flag_bits = $flag_bits | ITEM_ORIGIN; - // unset the nocomment bit if it's there. if($flag_bits & ITEM_NOCOMMENT) @@ -3113,7 +3096,7 @@ function start_delivery_chain($channel,$item,$item_id,$parent) { $r = q("update item set source_xchan = owner_xchan where id = %d", intval($item_id) ); - } + } $title = $item['title']; $body = $item['body']; @@ -3155,39 +3138,28 @@ function start_delivery_chain($channel,$item,$item_id,$parent) { intval($item_id) ); - - if($r) proc_run('php','include/notifier.php','tgroup',$item_id); else - logger('start_delivery_chain: failed to update item'); - - return; + logger('start_delivery_chain: failed to update item'); } - - /** - * @function check_item_source($uid,$item) - * @param $uid - * @param $item + * @brief * - * @description * Checks to see if this item owner is referenced as a source for this channel and if the post * matches the rules for inclusion in this channel. Returns true if we should create a second delivery * chain and false if none of the rules apply, or if the item is private. + * + * @param int $uid + * @param array $item */ - - -function check_item_source($uid,$item) { - - +function check_item_source($uid, $item) { $r = q("select * from source where src_channel_id = %d and ( src_xchan = '%s' or src_xchan = '*' ) limit 1", intval($uid), dbesc(($item['source_xchan']) ? $item['source_xchan'] : $item['owner_xchan']) ); - if(! $r) return false; @@ -3196,18 +3168,15 @@ function check_item_source($uid,$item) { dbesc($item['owner_xchan']) ); - if(! $x) return false; - if(! ($x[0]['abook_their_perms'] & PERMS_A_REPUBLISH)) return false; if($item['item_private'] && (! ($x[0]['abook_flags'] & ABOOK_FLAG_FEED))) return false; - if($r[0]['src_channel_xchan'] === $item['owner_xchan']) return false; @@ -3218,6 +3187,7 @@ function check_item_source($uid,$item) { $text = prepare_text($item['body'],$item['mimetype']); $text = html2plain($text); + /** @BUG $items is undefined, should this be $item? */ $tags = ((count($items['term'])) ? $items['term'] : false); $words = explode("\n",$r[0]['src_patt']); @@ -3232,12 +3202,11 @@ function check_item_source($uid,$item) { return true; } } + return false; } - - function mail_store($arr) { if(! $arr['channel_id']) { @@ -3262,7 +3231,6 @@ function mail_store($arr) { $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : ''); $arr['mail_flags'] = ((x($arr,'mail_flags')) ? intval($arr['mail_flags']) : 0 ); - if(! $arr['parent_mid']) { logger('mail_store: missing parent'); @@ -3328,9 +3296,9 @@ function mail_store($arr) { 'type' => NOTIFY_MAIL, 'item' => $arr, 'verb' => ACTIVITY_POST, - 'otype' => 'mail' + 'otype' => 'mail' ); - + notification($notif_params); } @@ -3338,35 +3306,35 @@ function mail_store($arr) { return $current_post; } - /** + * @brief Process atom feed and update anything/everything we might need to update. * - * consume_feed - process atom feed and update anything/everything we might need to update - * - * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds. - * - * $importer = the contact_record (joined to user_record) of the local user who owns this relationship. - * It is this person's stuff that is going to be updated. - * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity - * from an external network and MAY create an appropriate contact record. Otherwise, we MUST - * have a contact record. * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or * might not) try and subscribe to it. * $datedir sorts in reverse order - * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been - * imported prior to its children being seen in the stream unless we are certain - * of how the feed is arranged/ordered. - * With $pass = 1, we only pull parent items out of the stream. - * With $pass = 2, we only pull children (comments/likes). + * + * @param array $xml + * The (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds. + * @param $importer + * The contact_record (joined to user_record) of the local user who owns this + * relationship. It is this person's stuff that is going to be updated. + * @param $contact + * The person who is sending us stuff. If not set, we MAY be processing a "follow" activity + * from an external network and MAY create an appropriate contact record. Otherwise, we MUST + * have a contact record. + * @param int $pass by default ($pass = 0) we cannot guarantee that a parent item has been + * imported prior to its children being seen in the stream unless we are certain + * of how the feed is arranged/ordered. + * * With $pass = 1, we only pull parent items out of the stream. + * * With $pass = 2, we only pull children (comments/likes). * * So running this twice, first with pass 1 and then with pass 2 will do the right * thing regardless of feed ordering. This won't be adequate in a fully-threaded * model where comments can have sub-threads. That would require some massive sorting * to get all the feed items into a mostly linear ordering, and might still require - * recursion. + * recursion. */ - -function consume_feed($xml,$importer,&$contact,$pass = 0) { +function consume_feed($xml, $importer, &$contact, $pass = 0) { require_once('library/simplepie/simplepie.inc'); @@ -3403,7 +3371,6 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) { $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s'); } - if($deleted && is_array($contact)) { $r = q("SELECT * from item where mid = '%s' and author_xchan = '%s' and uid = %d limit 1", dbesc(base64url_encode($mid)), @@ -3418,7 +3385,7 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) { logger('consume_feed: deleting item ' . $item['id'] . ' mid=' . base64url_decode($item['mid']), LOGGER_DEBUG); drop_item($item['id'],false); } - } + } } } } @@ -3449,7 +3416,6 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) { if($pass == 1) continue; - // Have we seen it? If not, import it. $item_id = base64url_encode($item->get_id()); @@ -3469,15 +3435,12 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) { $x = import_author_unknown(array('name' => $author['author_name'],'url' => $author['author_link'],'photo' => array('src' => $author['author_photo']))); if($x) $datarray['author_xchan'] = $x; - } if(! $datarray['author_xchan']) $datarray['author_xchan'] = $contact['xchan_hash']; - $datarray['owner_xchan'] = $contact['xchan_hash']; - $r = q("SELECT edited FROM item WHERE mid = '%s' AND uid = %d LIMIT 1", dbesc($item_id), intval($importer['channel_id']) @@ -3501,15 +3464,12 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) { $datarray['parent_mid'] = $parent_mid; $datarray['uid'] = $importer['channel_id']; - - logger('consume_feed: ' . print_r($datarray,true),LOGGER_DATA); $xx = item_store($datarray); $r = $xx['item_id']; continue; } - else { // Head post of a conversation. Have we seen it? If not, import it. @@ -3538,15 +3498,12 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) { $x = import_author_unknown(array('name' => $author['author_name'],'url' => $author['author_link'],'photo' => array('src' => $author['author_photo']))); if($x) $datarray['author_xchan'] = $x; - } if(! $datarray['author_xchan']) $datarray['author_xchan'] = $contact['xchan_hash']; - $datarray['owner_xchan'] = $contact['xchan_hash']; - $r = q("SELECT edited FROM item WHERE mid = '%s' AND uid = %d LIMIT 1", dbesc($item_id), intval($importer['channel_id']) @@ -3568,7 +3525,6 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) { continue; } - $datarray['parent_mid'] = $item_id; $datarray['uid'] = $importer['channel_id']; @@ -3581,24 +3537,18 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) { logger('consume_feed: author ' . print_r($author,true),LOGGER_DEBUG); - logger('consume_feed: ' . print_r($datarray,true),LOGGER_DATA); $xx = item_store($datarray); $r = $xx['item_id']; continue; - } } } - - } function update_feed_item($uid,$datarray) { - logger('update_feed_item: not implemented! ' . $uid . ' ' . print_r($datarray,true), LOGGER_DATA); - } @@ -3608,6 +3558,7 @@ function handle_feed($uid,$abook_id,$url) { $channel = channelx_by_n($uid); if(! $channel) return; + $x = q("select * from abook left join xchan on abook_xchan = xchan_hash where abook_id = %d and abook_channel = %d limit 1", dbesc($abook_id), intval($uid) @@ -3629,13 +3580,13 @@ function atom_author($tag,$name,$uri,$h,$w,$type,$photo) { $o = ''; if(! $tag) return $o; + $name = xmlify($name); $uri = xmlify($uri); $h = intval($h); $w = intval($w); $photo = xmlify($photo); - $o .= "<$tag>\r\n"; $o .= "$name\r\n"; $o .= "$uri\r\n"; @@ -3645,13 +3596,12 @@ function atom_author($tag,$name,$uri,$h,$w,$type,$photo) { call_hooks('atom_author', $o); $o .= "\r\n"; + return $o; } function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) { - $a = get_app(); - if(! $item['parent']) return; @@ -3664,7 +3614,6 @@ function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) { else $body = $item['body']; - $o = "\r\n\r\n\r\n"; if(is_array($author)) @@ -3698,11 +3647,9 @@ function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) { if(($item['item_private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) $o .= '' . (($item['item_private']) ? $item['item_private'] : 1) . '' . "\r\n"; - if($item['app']) $o .= '' . "\r\n"; - $verb = construct_verb($item); $o .= '' . xmlify($verb) . '' . "\r\n"; $actobj = construct_activity_object($item); @@ -3730,7 +3677,7 @@ function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) { call_hooks('atom_entry', $o); $o .= '' . "\r\n"; - + return $o; } @@ -3753,7 +3700,6 @@ function fix_private_photos($s, $uid, $item = null, $cid = 0) { logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG); - if(stristr($image , $site . '/photo/')) { // Only embed locally hosted photos $replace = false; @@ -3815,7 +3761,7 @@ function fix_private_photos($s, $uid, $item = null, $cid = 0) { } } } - } + } $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/zmg]'; $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/zmg]')); @@ -3836,6 +3782,7 @@ function fix_private_photos($s, $uid, $item = null, $cid = 0) { function has_permissions($obj) { if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != '')) return true; + return false; } @@ -3858,10 +3805,15 @@ function compare_permissions($obj1,$obj2) { return false; } -// returns an array of contact-ids that are allowed to see this object - +/** + * @brief Returns an array of contact-ids that are allowed to see this object. + * + * @param object $obj + * @return array + */ function enumerate_permissions($obj) { require_once('include/group.php'); + $allow_people = expand_acl($obj['allow_cid']); $allow_groups = expand_groups(expand_acl($obj['allow_gid'])); $deny_people = expand_acl($obj['deny_cid']); @@ -3869,6 +3821,7 @@ function enumerate_permissions($obj) { $recipients = array_unique(array_merge($allow_people,$allow_groups)); $deny = array_unique(array_merge($deny_people,$deny_groups)); $recipients = array_diff($recipients,$deny); + return $recipients; } @@ -3885,6 +3838,7 @@ function item_getfeedtags($item) { $ret[] = array('@',$term['url'],$term['term']); } } + return $ret; } @@ -3905,11 +3859,11 @@ function item_getfeedattach($item) { } } } + return $ret; } - function item_expire($uid,$days) { if((! $uid) || ($days < 1)) @@ -3970,7 +3924,6 @@ function item_expire($uid,$days) { } // proc_run('php',"include/notifier.php","expire","$uid"); - } function retain_item($id) { @@ -4012,7 +3965,6 @@ function drop_items($items) { function drop_item($id,$interactive = true,$stage = DROPITEM_NORMAL,$force = false) { - $a = get_app(); // locate item to be deleted @@ -4057,7 +4009,6 @@ function drop_item($id,$interactive = true,$stage = DROPITEM_NORMAL,$force = fal intval($item['id']) ); - $arr = array('item' => $item, 'interactive' => $interactive, 'stage' => $stage); call_hooks('drop_item', $arr ); @@ -4089,7 +4040,6 @@ function drop_item($id,$interactive = true,$stage = DROPITEM_NORMAL,$force = fal proc_run('php','include/notifier.php','drop',$notify_id); goaway($a->get_baseurl() . '/' . $_SESSION['return_url']); - } else { if(! $interactive) @@ -4097,14 +4047,20 @@ function drop_item($id,$interactive = true,$stage = DROPITEM_NORMAL,$force = fal notice( t('Permission denied.') . EOL); goaway($a->get_baseurl() . '/' . $_SESSION['return_url']); } - } -// This function does not check for permission and does not send notifications and does not check recursion. -// It merely destroys all resources associated with an item. -// Please do not use without a suitable wrapper. - -function delete_item_lowlevel($item,$stage = DROPITEM_NORMAL,$force = false) { +/** + * @warning This function does not check for permission and does not send + * notifications and does not check recursion. + * It merely destroys all resources associated with an item. + * Please do not use without a suitable wrapper. + * + * @param array $item + * @param int $stage + * @param boolean $force + * @return boolean + */ +function delete_item_lowlevel($item, $stage = DROPITEM_NORMAL, $force = false) { $linked_item = (($item['resource_id']) ? true : false); @@ -4152,7 +4108,6 @@ function delete_item_lowlevel($item,$stage = DROPITEM_NORMAL,$force = false) { break; } - // immediately remove any undesired profile likes. q("delete from likes where iid = %d and channel_id = %d", @@ -4160,7 +4115,6 @@ function delete_item_lowlevel($item,$stage = DROPITEM_NORMAL,$force = false) { intval($item['uid']) ); - // network deletion request. Keep the message structure so that we can deliver delete notifications. // Come back after several days (or perhaps a month) to do the lowlevel delete (DROPITEM_PHASE2). @@ -4182,7 +4136,7 @@ function delete_item_lowlevel($item,$stage = DROPITEM_NORMAL,$force = false) { intval(TERM_OBJ_POST) ); - // FIXME remove notifications for this item + /** @FIXME remove notifications for this item */ return true; } @@ -4203,6 +4157,7 @@ function first_post_date($uid,$wall = false) { // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA); return substr(datetime_convert('',date_default_timezone_get(),$r[0]['created']),0,10); } + return false; } @@ -4210,15 +4165,19 @@ function first_post_date($uid,$wall = false) { * modified posted_dates() {below} to arrange the list in years, which we'll eventually * use to make a menu of years with collapsible sub-menus for the months instead of the * current flat list of all representative dates. + * + * @param int $uid + * @param unknown $wall + * @param unknown $mindate + * @return array */ - -function list_post_dates($uid,$wall,$mindate) { +function list_post_dates($uid, $wall, $mindate) { $dnow = datetime_convert('',date_default_timezone_get(),'now','Y-m-d'); if($mindate) - $dthen = datetime_convert('',date_default_timezone_get(),$mindate); + $dthen = datetime_convert('',date_default_timezone_get(), $mindate); else - $dthen = first_post_date($uid,$wall); + $dthen = first_post_date($uid, $wall); if(! $dthen) return array(); @@ -4245,6 +4204,7 @@ function list_post_dates($uid,$wall,$mindate) { $ret[$dyear][] = array($str,$end_month,$start_month); $dnow = datetime_convert('','',$dnow . ' -1 month', 'Y-m-d'); } + return $ret; } @@ -4307,7 +4267,6 @@ function fetch_post_tags($items,$link = false) { ); } - for($x = 0; $x < count($items); $x ++) { if($tags) { foreach($tags as $t) { @@ -4338,7 +4297,6 @@ function fetch_post_tags($items,$link = false) { function zot_feed($uid,$observer_xchan,$arr) { - $result = array(); $mindate = null; $message_id = null; @@ -4351,9 +4309,9 @@ function zot_feed($uid,$observer_xchan,$arr) { $message_id = $arr['message_id']; } - if(! $mindate) $mindate = NULL_DATE; + $mindate = dbesc($mindate); logger('zot_feed: requested for uid ' . $uid . ' from observer ' . $observer_xchan, LOGGER_DEBUG); @@ -4383,7 +4341,7 @@ function zot_feed($uid,$observer_xchan,$arr) { $items = array(); - // FIXME + /** @FIXME fix this part for PostgreSQL */ if(ACTIVE_DBTYPE == DBTYPE_POSTGRES) { return array(); @@ -4426,12 +4384,10 @@ function zot_feed($uid,$observer_xchan,$arr) { $items = fetch_post_tags($items); require_once('include/conversation.php'); $items = conv_sort($items,'ascending'); - } else $items = array(); - logger('zot_feed: number items: ' . count($items),LOGGER_DEBUG); foreach($items as $item) @@ -4452,13 +4408,13 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C $sql_nets = ''; $sql_options = ''; $sql_extra2 = ''; - $sql_extra3 = ''; + $sql_extra3 = ''; $def_acl = ''; $item_uids = ' true '; - + if ($arr['uid']) $uid= $arr['uid']; - + if($channel) { $uid = $channel['channel_id']; $uidhash = $channel['channel_hash']; @@ -4470,65 +4426,64 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C if($arr['wall']) $sql_options .= " and (item_flags & " . intval(ITEM_WALL) . ")>0 "; - + $sql_extra = " AND item.parent IN ( SELECT parent FROM item WHERE (item_flags & " . intval(ITEM_THREAD_TOP) . ")>0 $sql_options ) "; - + if($arr['since_id']) - $sql_extra .= " and item.id > " . $since_id . " "; - - if($arr['gid'] && $uid) { - $r = q("SELECT * FROM `groups` WHERE id = %d AND uid = %d LIMIT 1", - intval($arr['group']), - intval($uid) - ); - if(! $r) { + $sql_extra .= " and item.id > " . $since_id . " "; + + if($arr['gid'] && $uid) { + $r = q("SELECT * FROM `groups` WHERE id = %d AND uid = %d LIMIT 1", + intval($arr['group']), + intval($uid) + ); + if(! $r) { $result['message'] = t('Collection not found.'); return $result; - } + } $contact_str = ''; - $contacts = group_get_members($group); - if($contacts) { + /** @FIXME $group is undefined */ + $contacts = group_get_members($group); + if ($contacts) { foreach($contacts as $c) { if($contact_str) $contact_str .= ','; - $contact_str .= "'" . $c['xchan'] . "'"; + + $contact_str .= "'" . $c['xchan'] . "'"; } - } - else { + } else { $contact_str = ' 0 '; $result['message'] = t('Collection is empty.'); return $result; - } + } - $sql_extra = " AND item.parent IN ( SELECT DISTINCT parent FROM item WHERE true $sql_options AND (( author_xchan IN ( $contact_str ) OR owner_xchan in ( $contact_str)) or allow_gid like '" . protect_sprintf('%<' . dbesc($r[0]['hash']) . '>%') . "' ) and id = parent and item_restrict = 0 ) "; + $sql_extra = " AND item.parent IN ( SELECT DISTINCT parent FROM item WHERE true $sql_options AND (( author_xchan IN ( $contact_str ) OR owner_xchan in ( $contact_str)) or allow_gid like '" . protect_sprintf('%<' . dbesc($r[0]['hash']) . '>%') . "' ) and id = parent and item_restrict = 0 ) "; $x = group_rec_byhash($uid,$r[0]['hash']); $result['headline'] = sprintf( t('Collection: %s'),$x['name']); + } + elseif($arr['cid'] && $uid) { - } - elseif($arr['cid'] && $uid) { - - $r = q("SELECT abook.*, xchan.* from abook left join xchan on abook_xchan = xchan_hash where abook_id = %d and abook_channel = %d and not ( abook_flags & " . intval(ABOOK_FLAG_BLOCKED) . ")>0 limit 1", + $r = q("SELECT abook.*, xchan.* from abook left join xchan on abook_xchan = xchan_hash where abook_id = %d and abook_channel = %d and not ( abook_flags & " . intval(ABOOK_FLAG_BLOCKED) . ")>0 limit 1", intval($arr['cid']), intval(local_channel()) - ); - if($r) { - $sql_extra = " AND item.parent IN ( SELECT DISTINCT parent FROM item WHERE true $sql_options AND uid = " . intval($arr['uid']) . " AND ( author_xchan = '" . dbesc($r[0]['abook_xchan']) . "' or owner_xchan = '" . dbesc($r[0]['abook_xchan']) . "' ) and item_restrict = 0 ) "; + ); + if ($r) { + $sql_extra = " AND item.parent IN ( SELECT DISTINCT parent FROM item WHERE true $sql_options AND uid = " . intval($arr['uid']) . " AND ( author_xchan = '" . dbesc($r[0]['abook_xchan']) . "' or owner_xchan = '" . dbesc($r[0]['abook_xchan']) . "' ) and item_restrict = 0 ) "; $result['headline'] = sprintf( t('Connection: %s'),$r[0]['xchan_name']); - } - else { + } else { $result['message'] = t('Connection not found.'); return $result; - } - } + } + } - if($arr['datequery']) { - $sql_extra3 .= protect_sprintf(sprintf(" AND item.created <= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$arr['datequery'])))); - } - if($arr['datequery2']) { - $sql_extra3 .= protect_sprintf(sprintf(" AND item.created >= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$arr['datequery2'])))); - } + if ($arr['datequery']) { + $sql_extra3 .= protect_sprintf(sprintf(" AND item.created <= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$arr['datequery'])))); + } + if ($arr['datequery2']) { + $sql_extra3 .= protect_sprintf(sprintf(" AND item.created >= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$arr['datequery2'])))); + } if(! array_key_exists('nouveau',$arr)) { $sql_extra2 = " AND item.parent = item.id "; @@ -4542,37 +4497,33 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C $sql_extra .= sprintf(" AND item.body like '%s' ", dbesc(protect_sprintf('%' . $arr['search'] . '%')) ); - } - - if(strlen($arr['file'])) { - $sql_extra .= term_query('item',$arr['files'],TERM_FILE); - } - - if($arr['conv'] && $channel) { - $sql_extra .= sprintf(" AND parent IN (SELECT distinct parent from item where ( author_xchan like '%s' or ( item_flags & %d )>0)) ", - dbesc(protect_sprintf($uidhash)), - intval(ITEM_MENTIONSME) - ); - } - + } - if(($client_mode & CLIENT_MODE_UPDATE) && (! ($client_mode & CLIENT_MODE_LOAD))) { + if (strlen($arr['file'])) { + $sql_extra .= term_query('item',$arr['files'],TERM_FILE); + } - // only setup pagination on initial page view - $pager_sql = ''; + if ($arr['conv'] && $channel) { + $sql_extra .= sprintf(" AND parent IN (SELECT distinct parent from item where ( author_xchan like '%s' or ( item_flags & %d )>0)) ", + dbesc(protect_sprintf($uidhash)), + intval(ITEM_MENTIONSME) + ); + } - } - else { - $itemspage = (($channel) ? get_pconfig($uid,'system','itemspage') : 20); - $a->set_pager_itemspage(((intval($itemspage)) ? $itemspage : 20)); - $pager_sql = sprintf(" LIMIT %d OFFSET %d ", intval(get_app()->pager['itemspage']), intval(get_app()->pager['start'])); - } + if (($client_mode & CLIENT_MODE_UPDATE) && (! ($client_mode & CLIENT_MODE_LOAD))) { + // only setup pagination on initial page view + $pager_sql = ''; + } else { + $itemspage = (($channel) ? get_pconfig($uid,'system','itemspage') : 20); + $a->set_pager_itemspage(((intval($itemspage)) ? $itemspage : 20)); + $pager_sql = sprintf(" LIMIT %d OFFSET %d ", intval(get_app()->pager['itemspage']), intval(get_app()->pager['start'])); + } - if(isset($arr['start']) && isset($arr['records'])) - $pager_sql = sprintf(" LIMIT %d OFFSET %d ", intval($arr['records']), intval($arr['start'])); + if (isset($arr['start']) && isset($arr['records'])) + $pager_sql = sprintf(" LIMIT %d OFFSET %d ", intval($arr['records']), intval($arr['start'])); - if(array_key_exists('cmin',$arr) || array_key_exists('cmax',$arr)) { - if(($arr['cmin'] != 0) || ($arr['cmax'] != 99)) { + if (array_key_exists('cmin',$arr) || array_key_exists('cmax',$arr)) { + if (($arr['cmin'] != 0) || ($arr['cmax'] != 99)) { // Not everybody who shows up in the network stream will be in your address book. // By default those that aren't are assumed to have closeness = 99; but this isn't @@ -4581,33 +4532,32 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C $sql_nets .= " AND "; - if($arr['cmax'] == 99) + if ($arr['cmax'] == 99) $sql_nets .= " ( "; $sql_nets .= "( abook.abook_closeness >= " . intval($arr['cmin']) . " "; $sql_nets .= " AND abook.abook_closeness <= " . intval($arr['cmax']) . " ) "; - if($cmax == 99) + if ($cmax == 99) $sql_nets .= " OR abook.abook_closeness IS NULL ) "; - } + } } - $simple_update = (($client_mode & CLIENT_MODE_UPDATE) ? " and ( item.item_unseen = 1 ) " : ''); - if($client_mode & CLIENT_MODE_LOAD) - $simple_update = ''; + $simple_update = (($client_mode & CLIENT_MODE_UPDATE) ? " and ( item.item_unseen = 1 ) " : ''); + if ($client_mode & CLIENT_MODE_LOAD) + $simple_update = ''; - $start = dba_timer(); + //$start = dba_timer(); require_once('include/security.php'); $sql_extra .= item_permissions_sql($channel['channel_id']); - if($arr['pages']) + if ($arr['pages']) $item_restrict = " AND (item_restrict & " . ITEM_WEBPAGE . ") "; else $item_restrict = " AND item_restrict = 0 "; - - if($arr['nouveau'] && ($client_mode & CLIENT_MODE_LOAD) && $channel) { - // "New Item View" - show all items unthreaded in reverse created date order + if ($arr['nouveau'] && ($client_mode & CLIENT_MODE_LOAD) && $channel) { + // "New Item View" - show all items unthreaded in reverse created date order $items = q("SELECT item.*, item.id AS item_id FROM item WHERE $item_uids $item_restrict @@ -4616,22 +4566,21 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C ORDER BY item.received DESC $pager_sql " ); - require_once('include/items.php'); + require_once('include/items.php'); - xchan_query($items); + xchan_query($items); - $items = fetch_post_tags($items,true); - } - else { + $items = fetch_post_tags($items,true); + } else { - // Normal conversation view + // Normal conversation view - if($arr['order'] === 'post') + if($arr['order'] === 'post') $ordering = "created"; - else + else $ordering = "commented"; - if(($client_mode & CLIENT_MODE_LOAD) || ($client_mode == CLIENT_MODE_NORMAL)) { + if(($client_mode & CLIENT_MODE_LOAD) || ($client_mode == CLIENT_MODE_NORMAL)) { // Fetch a page full of parent items for this page @@ -4657,48 +4606,46 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C ); } - $first = dba_timer(); + //$first = dba_timer(); - // Then fetch all the children of the parents that are on this page + // Then fetch all the children of the parents that are on this page - if($r) { + if($r) { - $parents_str = ids_to_querystr($r,'item_id'); + $parents_str = ids_to_querystr($r,'item_id'); if($arr['top']) $sql_extra = ' and id = parent ' . $sql_extra; - $items = q("SELECT item.*, item.id AS item_id FROM item - WHERE $item_uids $item_restrict - AND item.parent IN ( %s ) - $sql_extra ", - dbesc($parents_str) - ); + $items = q("SELECT item.*, item.id AS item_id FROM item + WHERE $item_uids $item_restrict + AND item.parent IN ( %s ) + $sql_extra ", + dbesc($parents_str) + ); - $second = dba_timer(); + $second = dba_timer(); - xchan_query($items); + xchan_query($items); - $third = dba_timer(); + //$third = dba_timer(); - $items = fetch_post_tags($items,true); + $items = fetch_post_tags($items,true); - $fourth = dba_timer(); + //$fourth = dba_timer(); require_once('include/conversation.php'); - $items = conv_sort($items,$ordering); - - //logger('items: ' . print_r($items,true)); + $items = conv_sort($items,$ordering); - } - else { - $items = array(); - } + //logger('items: ' . print_r($items,true)); + } else { + $items = array(); + } - if($parents_str && $arr['mark_seen']) - $update_unseen = ' AND parent IN ( ' . dbesc($parents_str) . ' )'; - // FIXME finish mark unseen sql - } + if($parents_str && $arr['mark_seen']) + $update_unseen = ' AND parent IN ( ' . dbesc($parents_str) . ' )'; + /** @FIXME finish mark unseen sql */ + } return $items; } @@ -4719,7 +4666,7 @@ function update_remote_id($channel,$post_id,$webpage,$pagetitle,$namespace,$remo $pagetitle = $remote_id; } - if($page_type) { + if($page_type) { // store page info as an alternate message_id so we can access it via // https://sitename/page/$channelname/$pagetitle @@ -4747,17 +4694,17 @@ function update_remote_id($channel,$post_id,$webpage,$pagetitle,$namespace,$remo ); } } - } - /** - * change access control for item with message_id $mid and channel_id $uid + * @brief Change access control for item with message_id $mid and channel_id $uid. + * + * @param string $xchan_hash + * @param string $mid + * @param int $uid */ - - -function item_add_cid($xchan_hash,$mid,$uid) { +function item_add_cid($xchan_hash, $mid, $uid) { $r = q("select id from item where mid = '%s' and uid = %d and allow_cid like '%s'", dbesc($mid), intval($uid), @@ -4809,27 +4756,28 @@ function set_linkified_perms($linkified, &$str_contact_allow, &$str_group_allow, } if(strpos($access_tag,'cid:') === 0) { $str_contact_allow .= '<' . substr($access_tag,4) . '>'; - $access_tag = ''; + $access_tag = ''; } elseif(strpos($access_tag,'gid:') === 0) { $str_group_allow .= '<' . substr($access_tag,4) . '>'; - $access_tag = ''; + $access_tag = ''; } } } } - -/* - * We can't trust ITEM_ORIGIN to tell us if this is a local comment +/** + * We can't trust ITEM_ORIGIN to tell us if this is a local comment * which needs to be relayed, because it was misconfigured at one point for several * months and set for some remote items (in alternate delivery chains). This could * cause looping, so use this hackish but accurate method. + * + * @param array $item + * @return boolean */ - - function comment_local_origin($item) { - if(stripos($item['mid'],get_app()->get_hostname()) && ($item['parent'] != $item['id'])) + if(stripos($item['mid'], get_app()->get_hostname()) && ($item['parent'] != $item['id'])) return true; - return false; + + return false; } diff --git a/include/language.php b/include/language.php index ec5fa84fa..1e8528dc1 100644 --- a/include/language.php +++ b/include/language.php @@ -1,8 +1,8 @@ language = $a->langsave; } - -// load string translation table for alternate language - +/** + * @brief Load string translation table for alternate language. + * + * @param string $lang language code in 2-letter ISO 639-1 (en, de, fr) format + * @param boolean $install (optional) default false + */ function load_translation_table($lang, $install = false) { global $a; @@ -139,14 +142,13 @@ function load_translation_table($lang, $install = false) { if(file_exists("view/local-$lang/strings.php")) { include("view/local-$lang/strings.php"); } - } /** - * @brief translate string if translation exists. + * @brief Translate string if translation exists. * * @param string $s string that should get translated - * @param string $ctx optional context to appear in po file + * @param string $ctx (optional) context to appear in po file * @return translated string if exists, otherwise return $s * */ @@ -154,37 +156,53 @@ function t($s, $ctx = '') { global $a; $cs = $ctx ? '__ctx:' . $ctx . '__ ' . $s : $s; - if(x($a->strings, $cs)) { + if (x($a->strings, $cs)) { $t = $a->strings[$cs]; + return is_array($t) ? $t[0] : $t; } + return $s; } - +/** + * @brief + * + * @param string $singular + * @param string $plural + * @param int $count + * @param string $ctx + * @return string + */ function tt($singular, $plural, $count, $ctx = ''){ $a = get_app(); - $cs = $ctx?"__ctx:".$ctx."__ ".$singular:$singular; - if(x($a->strings,$cs)) { + $cs = $ctx ? "__ctx:" . $ctx . "__ " . $singular : $singular; + if (x($a->strings,$cs)) { $t = $a->strings[$cs]; $f = 'string_plural_select_' . str_replace('-', '_', $a->language); - if(! function_exists($f)) + if (! function_exists($f)) $f = 'string_plural_select_default'; + $k = $f($count); + return is_array($t) ? $t[$k] : $t; } - - if ($count != 1){ + + if ($count != 1) { return $plural; } else { return $singular; } } -// provide a fallback which will not collide with -// a function defined in any language file - +/** + * @brief Provide a fallback which will not collide with a function defined in + * any language file. + * + * @param int $n + * @return boolean + */ function string_plural_select_default($n) { return ($n != 1); } @@ -200,25 +218,25 @@ function string_plural_select_default($n) { * returned through config['system']['language_detect_min_confidence']. * * @see http://pear.php.net/package/Text_LanguageDetect - * @param s A string to examine + * @param string $s A string to examine * @return Language code in 2-letter ISO 639-1 (en, de, fr) format */ function detect_language($s) { require_once('Text/LanguageDetect.php'); $min_length = get_config('system', 'language_detect_min_length'); - if($min_length === false) + if ($min_length === false) $min_length = LANGUAGE_DETECT_MIN_LENGTH; $min_confidence = get_config('system', 'language_detect_min_confidence'); - if($min_confidence === false) + if ($min_confidence === false) $min_confidence = LANGUAGE_DETECT_MIN_CONFIDENCE; // embedded apps have long base64 strings which will trip up the detector. $naked_body = preg_replace('/\[app\](.*?)\[\/app\]/','',$s); // strip off bbcode $naked_body = preg_replace('/\[(.+?)\]/', '', $naked_body); - if(mb_strlen($naked_body) < intval($min_length)) { + if (mb_strlen($naked_body) < intval($min_length)) { logger('string length less than ' . intval($min_length), LOGGER_DATA); return ''; } @@ -233,11 +251,11 @@ function detect_language($s) { logger('detect language exception: ' . $e->getMessage(), LOGGER_DATA); } - if((! $lng) || (! (x($lng,'language')))) { + if ((! $lng) || (! (x($lng,'language')))) { return ''; } - if($lng['confidence'] < (float) $min_confidence) { + if ($lng['confidence'] < (float) $min_confidence) { logger('detect language: confidence less than ' . (float) $min_confidence, LOGGER_DATA); return ''; } @@ -251,38 +269,37 @@ function detect_language($s) { * By default we use the localized language name. You can switch the result * to any language with the optional 2nd parameter $l. * - * $s and $l should be in 2-letter ISO 639-1 format + * $s and $l should be in 2-letter ISO 639-1 format. * * If nothing could be looked up it returns $s. * - * @param $s Language code to look up - * @param $l (optional) In which language to return the name + * @param string $s Language code to look up + * @param string $l (optional) In which language to return the name * @return string with the language name, or $s if unrecognized + * + * @todo include CommerceGuys\Intl through composer like SabreDAV. */ require_once(__DIR__ . '/../library/intl/vendor/autoload.php'); use CommerceGuys\Intl\Language\LanguageRepository; function get_language_name($s, $l = null) { // get() expects the second part to be in upper case - if(strpos($s,'-') !== false) $s = substr($s,0,2) . strtoupper(substr($s,2)); - if($l !== null && strpos($l,'-') !== false) $l = substr($l,0,2) . strtoupper(substr($l,2)); + if (strpos($s, '-') !== false) $s = substr($s, 0, 2) . strtoupper(substr($s, 2)); + if ($l !== null && strpos($l, '-') !== false) $l = substr($l, 0, 2) . strtoupper(substr($l, 2)); $languageRepository = new LanguageRepository; // Sometimes intl doesn't like the second part at all ... try { $language = $languageRepository->get($s, $l); - } - catch(CommerceGuys\Intl\Exception\UnknownLanguageException $e) { - $s = substr($s,0,2); - if($l !== null) $l = substr($s,0,2); + } catch(CommerceGuys\Intl\Exception\UnknownLanguageException $e) { + $s = substr($s, 0, 2); + if($l !== null) $l = substr($s, 0, 2); try { $language = $languageRepository->get($s, $l); - } - catch(CommerceGuys\Intl\Exception\UnknownLanguageException $e) { + } catch (CommerceGuys\Intl\Exception\UnknownLanguageException $e) { return $s; // Give up } - } + } return $language->getName(); } - diff --git a/include/network.php b/include/network.php index 6aefc0b30..a0782692e 100644 --- a/include/network.php +++ b/include/network.php @@ -1,33 +1,39 @@ - supply Accept: header with 'accept_content' as the value - * 'timeout' => int seconds, default system config value or 60 seconds - * 'http_auth' => username:password - * 'novalidate' => do not validate SSL certs, default is to validate using our CA list - * 'nobody' => only return the header - * - * @returns array - * 'return_code' => HTTP return code or 0 if timeout or failure - * 'success' => boolean true (if HTTP 2xx result) or false - * 'header' => HTTP headers - * 'body' => fetched content + * @param array $opts (optional parameters) assoziative array with: + * * \b accept_content => supply Accept: header with 'accept_content' as the value + * * \b timeout => int seconds, default system config value or 60 seconds + * * \b http_auth => username:password + * * \b novalidate => do not validate SSL certs, default is to validate using our CA list + * * \b nobody => only return the header + * + * @return array an assoziative array with: + * * \e int \b return_code => HTTP return code or 0 if timeout or failure + * * \e boolean \b success => boolean true (if HTTP 2xx result) or false + * * \e string \b header => HTTP headers + * * \e string \b body => fetched content */ - function z_fetch_url($url, $binary = false, $redirects = 0, $opts = array()) { $ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => ""); @@ -129,14 +135,15 @@ function z_fetch_url($url, $binary = false, $redirects = 0, $opts = array()) { if(x($opts,'debug')) { $ret['debug'] = $curl_info; } - + @curl_close($ch); return($ret); } /** - * @function z_post_url + * @brief + * * @param string $url * URL to post * @param mixed $params @@ -151,17 +158,15 @@ function z_fetch_url($url, $binary = false, $redirects = 0, $opts = array()) { * 'timeout' => int seconds, default system config value or 60 seconds * 'http_auth' => username:password * 'novalidate' => do not validate SSL certs, default is to validate using our CA list - * - * @returns array - * 'return_code' => HTTP return code or 0 if timeout or failure - * 'success' => boolean true (if HTTP 2xx result) or false - * 'header' => HTTP headers - * 'body' => fetched content + * @return array an assoziative array with: + * * \e int \b return_code => HTTP return code or 0 if timeout or failure + * * \e boolean \b success => boolean true (if HTTP 2xx result) or false + * * \e string \b header => HTTP headers + * * \e string \b body => content + * * \e string \b debug => from curl_info() */ - - function z_post_url($url,$params, $redirects = 0, $opts = array()) { - + $ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => ""); $ch = curl_init($url); @@ -257,24 +262,35 @@ function z_post_url($url,$params, $redirects = 0, $opts = array()) { logger('z_post_url: debug: ' . print_r($curl_info,true), LOGGER_DATA); } - $ret['body'] = substr($s,strlen($header)); + $ret['body'] = substr($s, strlen($header)); $ret['header'] = $header; if(x($opts,'debug')) { $ret['debug'] = $curl_info; } - curl_close($ch); return($ret); } +/** + * @brief Like z_post_url() but with an application/json HTTP header. + * + * Add a "Content-Type: application/json" HTTP-header to $opts and call z_post_url(). + * + * @see z_post_url() + * + * @param string $url + * @param array $params + * @param number $redirects default 0 + * @param array $opts (optional) curl options + * @return z_post_url() + */ +function z_post_url_json($url, $params, $redirects = 0, $opts = array()) { -function z_post_url_json($url,$params,$redirects = 0, $opts = array()) { + $opts = array_merge($opts, array('headers' => array('Content-Type: application/json'))); - $opts = array_merge($opts,array('headers' => array('Content-Type: application/json'))); return z_post_url($url,json_encode($params),$redirects,$opts); - } @@ -305,22 +321,19 @@ function xml_status($st, $message = '') { } /** - * @function http_status_exit - * - * Send HTTP status header and exit + * @brief Send HTTP status header and exit. + * * @param int $val * integer HTTP status result value * @param string $msg * optional message * @returns (does not return, process is terminated) */ +function http_status_exit($val, $msg = '') { -function http_status_exit($val,$msg = '') { - - $err = ''; - if($val >= 400) + if ($val >= 400) $msg = (($msg) ? $msg : 'Error'); - if($val >= 200 && $val < 300) + if ($val >= 200 && $val < 300) $msg = (($msg) ? $msg : 'OK'); logger('http_status_exit ' . $val . ' ' . $msg); diff --git a/include/permissions.php b/include/permissions.php index 4d7def346..82145066b 100644 --- a/include/permissions.php +++ b/include/permissions.php @@ -1,6 +1,6 @@ array('forum' => t('Mostly Public'), 'forum_restricted' => t('Restricted'), 'forum_private' => t('Private')), t('Feed Republish') => array('feed' => t('Mostly Public'), 'feed_restricted' => t('Restricted')), t('Special Purpose') => array('soapbox' => t('Celebrity/Soapbox'), 'repository' => t('Group Repository')), - t('Other') => array('custom' => t('Custom/Expert Mode'))); + t('Other') => array('custom' => t('Custom/Expert Mode')) + ); return $roles; } diff --git a/include/photos.php b/include/photos.php index c4d5a33aa..1672e310a 100644 --- a/include/photos.php +++ b/include/photos.php @@ -1,10 +1,21 @@ - false); @@ -18,12 +29,12 @@ function photo_upload($channel, $observer, $args) { call_hooks('photo_upload_begin', $args); - /** + /* * Determine the album to use */ - $album = $args['album']; - $newalbum = $args['newalbum']; + $album = $args['album']; + $newalbum = $args['newalbum']; logger('photo_upload: album= ' . $album . ' newalbum= ' . $newalbum , LOGGER_DEBUG); @@ -44,8 +55,7 @@ function photo_upload($channel, $observer, $args) { $str_group_deny = perms2str(((is_array($args['group_deny'])) ? $args['group_deny'] : explode(',',$args['group_deny']))); $str_contact_deny = perms2str(((is_array($args['contact_deny'])) ? $args['contact_deny'] : explode(',',$args['contact_deny']))); - - if($args['data']) { + if ($args['data']) { // allow an import from a binary string representing the image. // This bypasses the upload step and max size limit checking @@ -56,23 +66,21 @@ function photo_upload($channel, $observer, $args) { // this is going to be deleted if it exists $src = '/tmp/deletemenow'; $type = $args['type']; - } - else { + } else { $f = array('src' => '', 'filename' => '', 'filesize' => 0, 'type' => ''); call_hooks('photo_upload_file',$f); - if(x($f,'src') && x($f,'filesize')) { + if (x($f,'src') && x($f,'filesize')) { $src = $f['src']; $filename = $f['filename']; $filesize = $f['filesize']; $type = $f['type']; - } - else { - $src = $_FILES['userfile']['tmp_name']; - $filename = basename($_FILES['userfile']['name']); - $filesize = intval($_FILES['userfile']['size']); - $type = $_FILES['userfile']['type']; + } else { + $src = $_FILES['userfile']['tmp_name']; + $filename = basename($_FILES['userfile']['name']); + $filesize = intval($_FILES['userfile']['size']); + $type = $_FILES['userfile']['type']; } if (! $type) @@ -82,14 +90,14 @@ function photo_upload($channel, $observer, $args) { $maximagesize = get_config('system','maximagesize'); - if(($maximagesize) && ($filesize > $maximagesize)) { + if (($maximagesize) && ($filesize > $maximagesize)) { $ret['message'] = sprintf ( t('Image exceeds website size limit of %lu bytes'), $maximagesize); @unlink($src); call_hooks('photo_upload_end',$ret); return $ret; } - if(! $filesize) { + if (! $filesize) { $ret['message'] = t('Image file is empty.'); @unlink($src); call_hooks('photo_post_end',$ret); @@ -101,14 +109,13 @@ function photo_upload($channel, $observer, $args) { $imagedata = @file_get_contents($src); } - $r = q("select sum(size) as total from photo where aid = %d and scale = 0 ", intval($account_id) ); $limit = service_class_fetch($channel_id,'photo_upload_limit'); - if(($r) && ($limit !== false) && (($r[0]['total'] + strlen($imagedata)) > $limit)) { + if (($r) && ($limit !== false) && (($r[0]['total'] + strlen($imagedata)) > $limit)) { $ret['message'] = upgrade_message(); @unlink($src); call_hooks('photo_post_end',$ret); @@ -117,7 +124,7 @@ function photo_upload($channel, $observer, $args) { $ph = photo_factory($imagedata, $type); - if(! $ph->is_valid()) { + if (! $ph->is_valid()) { $ret['message'] = t('Unable to process image'); logger('photo_upload: unable to process image'); @unlink($src); @@ -127,13 +134,12 @@ function photo_upload($channel, $observer, $args) { $exif = $ph->orient($src); - @unlink($src); $max_length = get_config('system','max_image_length'); - if(! $max_length) + if (! $max_length) $max_length = MAX_IMAGE_LENGTH; - if($max_length > 0) + if ($max_length > 0) $ph->scaleImage($max_length); $width = $ph->getWidth(); @@ -144,7 +150,7 @@ function photo_upload($channel, $observer, $args) { $photo_hash = (($args['resource_id']) ? $args['resource_id'] : photo_new_resource()); $visitor = ''; - if($channel['channel_hash'] !== $observer['xchan_hash']) + if ($channel['channel_hash'] !== $observer['xchan_hash']) $visitor = $observer['xchan_hash']; $errors = false; @@ -163,7 +169,6 @@ function photo_upload($channel, $observer, $args) { if($args['description']) $p['description'] = $args['description']; - $r1 = $ph->save($p); if(! $r1) $errors = true; @@ -214,8 +219,6 @@ function photo_upload($channel, $observer, $args) { } } - - $item_flags = ITEM_WALL|ITEM_ORIGIN|ITEM_THREAD_TOP; $item_restrict = (($visible) ? ITEM_VISIBLE : ITEM_HIDDEN); $title = ''; @@ -263,10 +266,9 @@ function photo_upload($channel, $observer, $args) { $tag = '[zmg]'; } - - $arr['body'] = '[zrl=' . z_root() . '/photos/' . $channel['channel_address'] . '/image/' . $photo_hash . ']' - . $tag . z_root() . "/photo/{$photo_hash}-{$smallest}.".$ph->getExt() . '[/zmg]' - . '[/zrl]'; + $arr['body'] = '[zrl=' . z_root() . '/photos/' . $channel['channel_address'] . '/image/' . $photo_hash . ']' + . $tag . z_root() . "/photo/{$photo_hash}-{$smallest}.".$ph->getExt() . '[/zmg]' + . '[/zrl]'; $result = item_store($arr); $item_id = $result['item_id']; @@ -304,7 +306,7 @@ function photos_albums_list($channel, $observer) { if(! perm_is_allowed($channel_id, $observer_xchan, 'view_photos')) return false; - // FIXME - create a permissions SQL which works on arbitrary observers and channels, regardless of login or web status + /** @FIXME create a permissions SQL which works on arbitrary observers and channels, regardless of login or web status */ $sql_extra = permissions_sql($channel_id); @@ -327,7 +329,8 @@ function photos_albums_list($channel, $observer) { 'total' => $album['total'], 'url' => z_root() . '/photos/' . $channel['channel_address'] . '/album/' . bin2hex($album['album']), 'urlencode' => urlencode($album['album']), - 'bin2hex' => bin2hex($album['album'])); + 'bin2hex' => bin2hex($album['album']) + ); $ret['albums'][] = $entry; } } @@ -360,11 +363,19 @@ function photos_album_widget($channelx,$observer,$albums = null) { ? t('Upload New Photos') : '') )); } + return $o; } - -function photos_list_photos($channel,$observer,$album = '') { +/** + * @brief + * + * @param array $channel + * @param array $observer + * @param string $album default empty + * @return boolean|array + */ +function photos_list_photos($channel, $observer, $album = '') { $channel_id = $channel['channel_id']; $observer_xchan = (($observer) ? $observer['xchan_hash'] : ''); @@ -384,7 +395,7 @@ function photos_list_photos($channel,$observer,$album = '') { intval(PHOTO_NORMAL), intval(PHOTO_PROFILE) ); - + if($r) { for($x = 0; $x < count($r); $x ++) { $r[$x]['src'] = z_root() . '/photo/' . $r[$x]['resource_id'] . '-' . $r[$x]['scale']; @@ -416,6 +427,7 @@ function photos_album_exists($channel_id, $album) { * @brief Renames a photo album in a channel. * * @todo Do we need to check if new album name already exists? + * * @param int $channel_id id of the channel * @param string $oldname The name of the album to rename * @param string $newname The new name of the album @@ -429,25 +441,31 @@ function photos_album_rename($channel_id, $oldname, $newname) { ); } +/** + * @brief + * + * @param int $channel_id + * @param string $album + * @param string $remote_xchan + * @return string|boolean + */ +function photos_album_get_db_idstr($channel_id, $album, $remote_xchan = '') { -function photos_album_get_db_idstr($channel_id,$album,$remote_xchan = '') { - - if($remote_xchan) { + if ($remote_xchan) { $r = q("SELECT distinct resource_id as from photo where xchan = '%s' and uid = %d and album = '%s' ", dbesc($remote_xchan), intval($channel_id), dbesc($album) ); - } - else { + } else { $r = q("SELECT distinct resource_id from photo where uid = %d and album = '%s' ", intval($channel_id), dbesc($album) ); } - if($r) { + if ($r) { $arr = array(); - foreach($r as $rr) { + foreach ($r as $rr) { $arr[] = "'" . dbesc($rr['resource_id']) . "'" ; } $str = implode(',',$arr); @@ -457,6 +475,15 @@ function photos_album_get_db_idstr($channel_id,$album,$remote_xchan = '') { return false; } +/** + * @brief Creates a new photo item. + * + * @param array $channel + * @param string $creator_hash + * @param array $photo + * @param boolean $visible default false + * @return int item_id + */ function photos_create_item($channel, $creator_hash, $photo, $visible = false) { // Create item container @@ -506,7 +533,6 @@ function getGps($exifCoord, $hemi) { $flip = ($hemi == 'W' or $hemi == 'S') ? -1 : 1; return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600))); - } function gps2Num($coordPart) { @@ -521,4 +547,3 @@ function gps2Num($coordPart) { return floatval($parts[0]) / floatval($parts[1]); } - diff --git a/include/plugin.php b/include/plugin.php index b6cfc8d89..4d8405b62 100755 --- a/include/plugin.php +++ b/include/plugin.php @@ -7,13 +7,12 @@ require_once("include/smarty.php"); + /** * @brief unloads an addon. * * @param string $plugin name of the addon - * @return void */ - function unload_plugin($plugin){ logger("Addons: unloading " . $plugin, LOGGER_DEBUG); @@ -28,9 +27,8 @@ function unload_plugin($plugin){ * @brief uninstalls an addon. * * @param string $plugin name of the addon - * @return bool + * @return boolean */ - function uninstall_plugin($plugin) { unload_plugin($plugin); @@ -70,7 +68,7 @@ function install_plugin($plugin) { $plugin_admin = (function_exists($plugin . '_plugin_admin') ? 1 : 0); - $r = q("INSERT INTO `addon` (`name`, `installed`, `timestamp`, `plugin_admin`) VALUES ( '%s', 1, %d , %d ) ", + q("INSERT INTO `addon` (`name`, `installed`, `timestamp`, `plugin_admin`) VALUES ( '%s', 1, %d , %d ) ", dbesc($plugin), intval($t), $plugin_admin @@ -196,6 +194,7 @@ function register_hook($hook, $file, $function, $priority = 0) { dbesc($function), dbesc($priority) ); + return $r; } @@ -206,7 +205,7 @@ function register_hook($hook, $file, $function, $priority = 0) { * @param string $hook the name of the hook * @param string $file the name of the file that hooks into * @param string $function the name of the function that the hook called - * @return mixed + * @return array */ function unregister_hook($hook, $file, $function) { $r = q("DELETE FROM hook WHERE hook = '%s' AND `file` = '%s' AND `function` = '%s'", @@ -214,6 +213,7 @@ function unregister_hook($hook, $file, $function) { dbesc($file), dbesc($function) ); + return $r; } @@ -243,8 +243,7 @@ function load_hooks() { } /** - * - * @function insert_hook($hook,$fn) + * @brief Inserts a hook into a page request. * * Insert a short-lived hook into the running page request. * Hooks are normally persistent so that they can be called @@ -255,9 +254,9 @@ function load_hooks() { * which will not persist beyond the life of this page request * or the current process. * - * @param string $hook; + * @param string $hook * name of hook to attach callback - * @param string $fn; + * @param string $fn * function name of callback handler */ function insert_hook($hook, $fn) { @@ -305,9 +304,10 @@ function call_hooks($name, &$data = null) { /** - * @brief parse plugin comment in search of plugin infos. + * @brief Parse plugin comment in search of plugin infos. * * like + * \code * * Name: Plugin * * Description: A plugin which plugs in * * Version: 1.2.3 @@ -315,7 +315,7 @@ function call_hooks($name, &$data = null) { * * Author: Jane * * Compat: Red [(version)], Friendica [(version)] * * - * + *\endcode * @param string $plugin the name of the plugin * @return array with the plugin information */ @@ -363,9 +363,10 @@ function get_plugin_info($plugin){ /** - * @brief parse theme comment in search of theme infos. + * @brief Parse theme comment in search of theme infos. * * like + * \code * * Name: My Theme * * Description: My Cool Theme * * Version: 1.2.3 @@ -373,7 +374,7 @@ function get_plugin_info($plugin){ * * Maintainer: Jane * * Compat: Friendica [(version)], Red [(version)] * * - * + * \endcode * @param string $theme the name of the theme * @return array */ @@ -456,13 +457,11 @@ function get_theme_screenshot($theme) { return($a->get_baseurl() . '/images/blank.png'); } - /** - * @brief add CSS to + * @brief add CSS to \ * * @param string $src * @param string $media change media attribute (default to 'screen') - * @return void */ function head_add_css($src, $media = 'screen') { get_app()->css_sources[] = array($src, $media); @@ -471,21 +470,23 @@ function head_add_css($src, $media = 'screen') { function head_remove_css($src, $media = 'screen') { $a = get_app(); $index = array_search(array($src, $media), $a->css_sources); - if($index !== false) + if ($index !== false) unset($a->css_sources[$index]); } function head_get_css() { $str = ''; $sources = get_app()->css_sources; - if(count($sources)) - foreach($sources as $source) + if (count($sources)) { + foreach ($sources as $source) $str .= format_css_if_exists($source); + } + return $str; } function format_css_if_exists($source) { - if(strpos($source[0], '/') !== false) + if (strpos($source[0], '/') !== false) $path = $source[0]; else $path = theme_include($source[0]); @@ -592,6 +593,7 @@ function theme_include($file, $root = '') { if(file_exists($p)) return $p; } + return ''; } diff --git a/include/template_processor.php b/include/template_processor.php index 74acc9c67..d2bf283e3 100755 --- a/include/template_processor.php +++ b/include/template_processor.php @@ -1,305 +1,307 @@ 5.3, not certain how to code around it for unit tests -// case PREG_BAD_UTF8_OFFSET_ERROR: echo('PREG_BAD_UTF8_OFFSET_ERROR'); break; - default: - //die("Unknown preg error."); - return; - } - echo "
      ";
      -			debug_print_backtrace();
      -			die();
      +//			case PREG_BAD_UTF8_OFFSET_ERROR: echo('PREG_BAD_UTF8_OFFSET_ERROR'); break;
      +			default:
      +				//die("Unknown preg error.");
      +				return;
       		}
      -		
      -		
      -		private function _push_stack(){
      -			$this->stack[] = array($this->r, $this->nodes);
      -		}
      -		private function _pop_stack(){
      -			list($this->r, $this->nodes) = array_pop($this->stack);
      -			
      -		}
      -		
      -		private function _get_var($name, $retNoKey=false){
      -			$keys = array_map('trim',explode(".",$name));
      -			if ($retNoKey && !array_key_exists($keys[0], $this->r)) return KEY_NOT_EXISTS;
      -			$val = $this->r;
      -			foreach($keys as $k) {
      -				$val = (isset($val[$k]) ? $val[$k] : null);
      -			}
      -			return template_escape($val);
      +		echo "
      ";
      +		debug_print_backtrace();
      +		die();
      +	}
      +
      +	private function _push_stack() {
      +		$this->stack[] = array($this->r, $this->nodes);
      +	}
      +
      +	private function _pop_stack(){
      +		list($this->r, $this->nodes) = array_pop($this->stack);
      +	}
      +
      +	private function _get_var($name, $retNoKey=false) {
      +		$keys = array_map('trim',explode(".",$name));
      +		if ($retNoKey && !array_key_exists($keys[0], $this->r))
      +			return KEY_NOT_EXISTS;
      +
      +		$val = $this->r;
      +		foreach($keys as $k) {
      +			$val = (isset($val[$k]) ? $val[$k] : null);
       		}
      -		
      -		/**
      -		 * IF node
      -		 * 
      -		 * {{ if <$var> }}...[{{ else }} ...] {{ endif }}
      -		 * {{ if <$var>== }}...[{{ else }} ...]{{ endif }}
      -		 * {{ if <$var>!= }}...[{{ else }} ...]{{ endif }}
      -		 */
      -		private function _replcb_if($args){
      -			if (strpos($args[2],"==")>0){
      -				list($a,$b) = array_map("trim",explode("==",$args[2]));
      -				$a = $this->_get_var($a);
      -				if ($b[0]=="$") $b =  $this->_get_var($b);
      -				$val = ($a == $b);
      -			} else if (strpos($args[2],"!=")>0){
      -				list($a,$b) = array_map("trim", explode("!=",$args[2]));
      -				$a = $this->_get_var($a);
      -				if ($b[0]=="$") $b =  $this->_get_var($b);
      -				$val = ($a != $b);
      -			} else {
      -				$val = $this->_get_var($args[2]);
      -			}
      -			$x = preg_split("|{{ *else *}}|", $args[3]);
      -			return ( ($val) ? $x[0] : (isset($x[1]) ? $x[1] : ""));
      +
      +		return template_escape($val);
      +	}
      +
      +	/**
      +	 * IF node
      +	 * \code
      +	 * {{ if <$var> }}...[{{ else }} ...] {{ endif }}
      +	 * {{ if <$var>== }}...[{{ else }} ...]{{ endif }}
      +	 * {{ if <$var>!= }}...[{{ else }} ...]{{ endif }}
      +	 * \endcode
      +	 */
      +	private function _replcb_if($args) {
      +		if (strpos($args[2],"==")>0){
      +			list($a,$b) = array_map("trim",explode("==",$args[2]));
      +			$a = $this->_get_var($a);
      +			if ($b[0]=="$") $b =  $this->_get_var($b);
      +			$val = ($a == $b);
      +		} else if (strpos($args[2],"!=")>0){
      +			list($a,$b) = array_map("trim", explode("!=",$args[2]));
      +			$a = $this->_get_var($a);
      +			if ($b[0]=="$") $b =  $this->_get_var($b);
      +			$val = ($a != $b);
      +		} else {
      +			$val = $this->_get_var($args[2]);
       		}
      -		
      -		/**
      -		 * FOR node
      -		 * 
      -		 * {{ for <$var> as $name }}...{{ endfor }}
      -		 * {{ for <$var> as $key=>$name }}...{{ endfor }}
      -		 */
      -		private function _replcb_for($args){
      -			$m = array_map('trim', explode(" as ", $args[2]));
      -			$x = explode("=>",$m[1]);
      -			if (count($x) == 1) {
      -				$varname = $x[0];
      -				$keyname = "";
      -			} else {
      -				list($keyname, $varname) = $x;
      -			}
      -			if ($m[0]=="" || $varname=="" || is_null($varname)) die("template error: 'for ".$m[0]." as ".$varname."'") ;
      -			//$vals = $this->r[$m[0]];
      -			$vals = $this->_get_var($m[0]);
      -			$ret="";
      -			if (!is_array($vals)) return $ret; 
      -			foreach ($vals as $k=>$v){
      -				$this->_push_stack();
      -				$r = $this->r;
      -				$r[$varname] = $v;
      -				if ($keyname!='') $r[$keyname] = (($k === 0) ? '0' : $k);
      -				$ret .=  $this->replace($args[3], $r);
      -				$this->_pop_stack();
      -			}
      -			return $ret;
      +		$x = preg_split("|{{ *else *}}|", $args[3]);
      +
      +		return ( ($val) ? $x[0] : (isset($x[1]) ? $x[1] : ""));
      +	}
      +
      +	/**
      +	 * FOR node
      +	 * \code
      +	 * {{ for <$var> as $name }}...{{ endfor }}
      +	 * {{ for <$var> as $key=>$name }}...{{ endfor }}
      +	 * \endcode
      +	 */
      +	private function _replcb_for($args) {
      +		$m = array_map('trim', explode(" as ", $args[2]));
      +		$x = explode("=>",$m[1]);
      +		if (count($x) == 1) {
      +			$varname = $x[0];
      +			$keyname = "";
      +		} else {
      +			list($keyname, $varname) = $x;
       		}
      +		if ($m[0]=="" || $varname=="" || is_null($varname)) die("template error: 'for ".$m[0]." as ".$varname."'") ;
      +		//$vals = $this->r[$m[0]];
      +		$vals = $this->_get_var($m[0]);
      +		$ret="";
      +		if (!is_array($vals)) return $ret;
       
      -		/**
      -		 * INC node
      -		 * 
      -		 * {{ inc  [with $var1=$var2] }}{{ endinc }}
      -		 */
      -		private function _replcb_inc($args){
      -			if (strpos($args[2],"with")) {
      -				list($tplfile, $newctx) = array_map('trim', explode("with",$args[2]));
      -			} else {
      -				$tplfile = trim($args[2]);
      -				$newctx = null;
      -			}
      -			
      -			if ($tplfile[0]=="$") $tplfile = $this->_get_var($tplfile);
      -			
      +		foreach ($vals as $k=>$v){
       			$this->_push_stack();
       			$r = $this->r;
      -			if (!is_null($newctx)) {
      -				list($a,$b) = array_map('trim', explode("=",$newctx));
      -				$r[$a] = $this->_get_var($b); 
      -			}
      -			$this->nodes = Array();
      -			$tpl = get_markup_template($tplfile);
      -			$ret = $this->replace($tpl, $r);
      +			$r[$varname] = $v;
      +			if ($keyname!='') $r[$keyname] = (($k === 0) ? '0' : $k);
      +			$ret .=  $this->replace($args[3], $r);
       			$this->_pop_stack();
      -			return $ret;
      -			
       		}
      -		
      -		/**
      -		 * DEBUG node
      -		 * 
      -		 * {{ debug $var [$var [$var [...]]] }}{{ enddebug }}
      -		 * 
      -		 * replace node with 
      var_dump($var, $var, ...);
      - */ - private function _replcb_debug($args){ - $vars = array_map('trim', explode(" ",$args[2])); - $vars[] = $args[1]; - - $ret = "
      ";
      -			foreach ($vars as $var){
      -				$ret .= htmlspecialchars(var_export( $this->_get_var($var), true ));
      -				$ret .= "\n";
      -			}
      -			$ret .= "
      "; - return $ret; + + return $ret; + } + + /** + * INC node + * \code + * {{ inc [with $var1=$var2] }}{{ endinc }} + * \endcode + */ + private function _replcb_inc($args) { + if (strpos($args[2],"with")) { + list($tplfile, $newctx) = array_map('trim', explode("with",$args[2])); + } else { + $tplfile = trim($args[2]); + $newctx = null; } - private function _replcb_node($m) { - $node = $this->nodes[$m[1]]; - if (method_exists($this, "_replcb_".$node[1])){ - $s = call_user_func(array($this, "_replcb_".$node[1]), $node); - } else { - $s = ""; - } - $s = preg_replace_callback('/\|\|([0-9]+)\|\|/', array($this, "_replcb_node"), $s); - return $s; + if ($tplfile[0]=="$") $tplfile = $this->_get_var($tplfile); + + $this->_push_stack(); + $r = $this->r; + if (!is_null($newctx)) { + list($a,$b) = array_map('trim', explode("=",$newctx)); + $r[$a] = $this->_get_var($b); + } + $this->nodes = Array(); + $tpl = get_markup_template($tplfile); + $ret = $this->replace($tpl, $r); + $this->_pop_stack(); + + return $ret; + } + + /** + * DEBUG node + * \code + * {{ debug $var [$var [$var [...]]] }}{{ enddebug }} + * \endcode + * replace node with
      var_dump($var, $var, ...);
      + */ + private function _replcb_debug($args) { + $vars = array_map('trim', explode(" ",$args[2])); + $vars[] = $args[1]; + + $ret = "
      ";
      +		foreach ($vars as $var){
      +			$ret .= htmlspecialchars(var_export( $this->_get_var($var), true ));
      +			$ret .= "\n";
       		}
      -						
      -		private function _replcb($m){
      -			//var_dump(array_map('htmlspecialchars', $m));
      -			$this->done = false;	
      -			$this->nodes[] = (array) $m;
      -			return "||". (count($this->nodes)-1) ."||";
      +		$ret .= "
      "; + + return $ret; + } + + private function _replcb_node($m) { + $node = $this->nodes[$m[1]]; + if (method_exists($this, "_replcb_".$node[1])){ + $s = call_user_func(array($this, "_replcb_".$node[1]), $node); + } else { + $s = ""; } - - private function _build_nodes($s){ - $this->done = false; - while (!$this->done){ - $this->done=true; - $s = preg_replace_callback('|{{ *([a-z]*) *([^}]*)}}([^{]*({{ *else *}}[^{]*)?){{ *end\1 *}}|', array($this, "_replcb"), $s); - if ($s==Null) $this->_preg_error(); - } - //({{ *else *}}[^{]*)? - krsort($this->nodes); - return $s; + $s = preg_replace_callback('/\|\|([0-9]+)\|\|/', array($this, "_replcb_node"), $s); + + return $s; + } + + private function _replcb($m) { + //var_dump(array_map('htmlspecialchars', $m)); + $this->done = false; + $this->nodes[] = (array) $m; + + return "||". (count($this->nodes)-1) ."||"; + } + + private function _build_nodes($s) { + $this->done = false; + while (!$this->done) { + $this->done=true; + $s = preg_replace_callback('|{{ *([a-z]*) *([^}]*)}}([^{]*({{ *else *}}[^{]*)?){{ *end\1 *}}|', array($this, "_replcb"), $s); + if ($s==Null) $this->_preg_error(); } - - - private function var_replace($s){ - $m = array(); - /** regexp: - * \$ literal $ - * (\[)? optional open square bracket - * ([a-zA-Z0-9-_]+\.?)+ var name, followed by optional - * dot, repeated at least 1 time - * (?(1)\]) if there was opened square bracket - * (subgrup 1), match close bracket - */ - if (preg_match_all('/\$(\[)?([a-zA-Z0-9-_]+\.?)+(?(1)\])/', $s,$m)){ - foreach($m[0] as $var){ - - $exp = str_replace(array("[", "]"), array("", ""), $var); - $exptks = explode("|", $exp); - - $varn = $exptks[0]; - unset($exptks[0]); - $val = $this->_get_var($varn, true); - if ($val != KEY_NOT_EXISTS) { - /* run filters */ - /* - * Filter are in form of: - * filtername:arg:arg:arg - * - * "filtername" is function name - * "arg"s are optional, var value is appended to the end - * if one "arg"==='x' , is replaced with var value - * - * examples: - * $item.body|htmlspecialchars // escape html chars - * $item.body|htmlspecialchars|strtoupper // escape html and uppercase result - * $item.created|date:%Y %M %j // format date (created is a timestamp) - * $item.body|str_replace:cat:dog // replace all "cat" with "dog" - * $item.body|str_replace:cat:dog:x:1 // replace one "cat" with "dog" - - */ - foreach ($exptks as $filterstr) { - $filter = explode(":", $filterstr); - $filtername = $filter[0]; - unset($filter[0]); - $valkey = array_search("x", $filter); - if ($valkey === false) { - $filter[] = $val; - } else { - $filter[$valkey] = $val; - } - if (function_exists($filtername)) { - $val = call_user_func_array($filtername, $filter); - } - } - $s = str_replace($var, $val, $s); + //({{ *else *}}[^{]*)? + krsort($this->nodes); + + return $s; + } + private function var_replace($s) { + $m = array(); + /** regexp: + * \$ literal $ + * (\[)? optional open square bracket + * ([a-zA-Z0-9-_]+\.?)+ var name, followed by optional + * dot, repeated at least 1 time + * (?(1)\]) if there was opened square bracket + * (subgrup 1), match close bracket + */ + if (preg_match_all('/\$(\[)?([a-zA-Z0-9-_]+\.?)+(?(1)\])/', $s,$m)) { + foreach ($m[0] as $var) { + $exp = str_replace(array("[", "]"), array("", ""), $var); + $exptks = explode("|", $exp); + + $varn = $exptks[0]; + unset($exptks[0]); + $val = $this->_get_var($varn, true); + if ($val != KEY_NOT_EXISTS) { + /* run filters */ + /* + * Filter are in form of: + * filtername:arg:arg:arg + * + * "filtername" is function name + * "arg"s are optional, var value is appended to the end + * if one "arg"==='x' , is replaced with var value + * + * examples: + * $item.body|htmlspecialchars // escape html chars + * $item.body|htmlspecialchars|strtoupper // escape html and uppercase result + * $item.created|date:%Y %M %j // format date (created is a timestamp) + * $item.body|str_replace:cat:dog // replace all "cat" with "dog" + * $item.body|str_replace:cat:dog:x:1 // replace one "cat" with "dog" + */ + foreach ($exptks as $filterstr) { + $filter = explode(":", $filterstr); + $filtername = $filter[0]; + unset($filter[0]); + $valkey = array_search("x", $filter); + if ($valkey === false) { + $filter[] = $val; + } else { + $filter[$valkey] = $val; + } + if (function_exists($filtername)) { + $val = call_user_func_array($filtername, $filter); + } } + $s = str_replace($var, $val, $s); } } - - return $s; - } - - private function replace($s,$r) { - $this->replace_macros($s, $r); - } - - // TemplateEngine interface - public function replace_macros($s, $r) { - $this->r = $r; - - $s = $this->_build_nodes($s); - - $s = preg_replace_callback('/\|\|([0-9]+)\|\|/', array($this, "_replcb_node"), $s); - if ($s==Null) $this->_preg_error(); - - // remove comments block - $s = preg_replace('/{#[^#]*#}/', "" , $s); - - $t2 = dba_timer(); - - // replace strings recursively (limit to 10 loops) - $os = ""; $count=0; - while(($os !== $s) && $count<10){ - $os=$s; $count++; - $s = $this->var_replace($s); - } - return $s; } - public function get_markup_template($file, $root='') { - $template_file = theme_include($file, $root); - if ($template_file) { - $content = file_get_contents($template_file); - } - return $content; - } + return $s; } - + private function replace($s, $r) { + $this->replace_macros($s, $r); + } + // TemplateEngine interface + public function replace_macros($s, $r) { + $this->r = $r; + $s = $this->_build_nodes($s); -function template_escape($s) { + $s = preg_replace_callback('/\|\|([0-9]+)\|\|/', array($this, "_replcb_node"), $s); + if ($s == Null) + $this->_preg_error(); - return str_replace(array('$','{{'),array('!_Doll^Ars1Az_!','!_DoubLe^BraceS4Rw_!'),$s); + // remove comments block + $s = preg_replace('/{#[^#]*#}/', "" , $s); + //$t2 = dba_timer(); -} + // replace strings recursively (limit to 10 loops) + $os = ""; + $count=0; + while (($os !== $s) && $count<10) { + $os=$s; + $count++; + $s = $this->var_replace($s); + } -function template_unescape($s) { + return $s; + } - return str_replace(array('!_Doll^Ars1Az_!','!_DoubLe^BraceS4Rw_!'),array('$','{{'),$s); + public function get_markup_template($file, $root='') { + $template_file = theme_include($file, $root); + if ($template_file) { + $content = file_get_contents($template_file); + } + return $content; + } +} +function template_escape($s) { + return str_replace(array('$','{{'),array('!_Doll^Ars1Az_!','!_DoubLe^BraceS4Rw_!'),$s); +} + +function template_unescape($s) { + return str_replace(array('!_Doll^Ars1Az_!','!_DoubLe^BraceS4Rw_!'),array('$','{{'),$s); } diff --git a/include/text.php b/include/text.php index 75125c606..664d5f83d 100644 --- a/include/text.php +++ b/include/text.php @@ -1,18 +1,26 @@ - replace) * @return string substituted string */ -function replace_macros($s,$r) { +function replace_macros($s, $r) { $a = get_app(); $arr = array('template' => $s, 'params' => $r); @@ -24,40 +32,38 @@ function replace_macros($s,$r) { return $output; } - -// random string, there are 86 characters max in text mode, 128 for hex -// output is urlsafe - -define('RANDOM_STRING_HEX', 0x00 ); -define('RANDOM_STRING_TEXT', 0x01 ); - - -function random_string($size = 64,$type = RANDOM_STRING_HEX) { +/** + * @brief Generates a random string. + * + * @param number $size + * @param int $type + * @return string + */ +function random_string($size = 64, $type = RANDOM_STRING_HEX) { // generate a bit of entropy and run it through the whirlpool $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false)); $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n","",base64url_encode($s,true)) : $s); - return(substr($s,0,$size)); + + return(substr($s, 0, $size)); } /** - * This is our primary input filter. + * @brief This is our primary input filter. * * The high bit hack only involved some old IE browser, forget which (IE5/Mac?) * that had an XSS attack vector due to stripping the high-bit on an 8-bit character * after cleansing, and angle chars with the high bit set could get through as markup. - * + * * This is now disabled because it was interfering with some legitimate unicode sequences * and hopefully there aren't a lot of those browsers left. * * Use this on any text input where angle chars are not valid or permitted * They will be replaced with safer brackets. This may be filtered further - * if these are not allowed either. + * if these are not allowed either. * * @param string $string Input string * @return string Filtered string */ - - function notags($string) { return(str_replace(array("<",">"), array('[',']'), $string)); @@ -105,7 +111,6 @@ function z_input_filter($channel_id,$s,$type = 'text/bbcode') { return purify_html($s); return escape_tags($s); - } @@ -114,39 +119,38 @@ function purify_html($s) { require_once('library/HTMLPurifier.auto.php'); require_once('include/html2bbcode.php'); -// FIXME this function has html output, not bbcode - so safely purify these -// $s = html2bb_video($s); -// $s = oembed_html2bbcode($s); +/** + * @FIXME this function has html output, not bbcode - so safely purify these + * $s = html2bb_video($s); + * $s = oembed_html2bbcode($s); + */ $config = HTMLPurifier_Config::createDefault(); $config->set('Cache.DefinitionImpl', null); $config->set('Attr.EnableID', true); $purifier = new HTMLPurifier($config); + return $purifier->purify($s); } - - -// generate a string that's random, but usually pronounceable. -// used to generate initial passwords - - /** - * generate a string that's random, but usually pronounceable. - * used to generate initial passwords + * @brief generate a string that's random, but usually pronounceable. + * + * Used to generate initial passwords. + * * @param int $len * @return string */ function autoname($len) { - if($len <= 0) + if ($len <= 0) return ''; $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u'); - if(mt_rand(0,5) == 4) + if (mt_rand(0, 5) == 4) $vowels[] = 'y'; $cons = array( @@ -178,8 +182,8 @@ function autoname($len) { $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr', 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh'); - $start = mt_rand(0,2); - if($start == 0) + $start = mt_rand(0, 2); + if ($start == 0) $table = $vowels; else $table = $cons; @@ -190,33 +194,30 @@ function autoname($len) { $r = mt_rand(0,count($table) - 1); $word .= $table[$r]; - if($table == $vowels) - $table = array_merge($cons,$midcons); + if ($table == $vowels) + $table = array_merge($cons, $midcons); else $table = $vowels; - } $word = substr($word,0,$len); - foreach($noend as $noe) { - if((strlen($word) > 2) && (substr($word,-2) == $noe)) { + foreach ($noend as $noe) { + if ((strlen($word) > 2) && (substr($word,-2) == $noe)) { $word = substr($word,0,-1); break; } } - if(substr($word,-1) == 'q') - $word = substr($word,0,-1); + if (substr($word, -1) == 'q') + $word = substr($word, 0, -1); + return $word; } -// escape text ($str) for XML transport -// returns escaped text. - - /** - * escape text ($str) for XML transport + * @brief escape text ($str) for XML transport + * * @param string $str * @return string Escaped text. */ @@ -228,7 +229,6 @@ function xmlify($str) { $char = mb_substr($str,$x,1); switch( $char ) { - case "\r" : break; case "&" : @@ -252,9 +252,10 @@ function xmlify($str) { default : $buffer .= $char; break; - } + } } $buffer = trim($buffer); + return($buffer); } @@ -268,10 +269,12 @@ function unxmlify($s) { return $ret; } -// convenience wrapper, reverse the operation "bin2hex" - -// This is a built-in function in php >= 5.4 - +/** + * Convenience wrapper, reverse the operation "bin2hex" + * This is a built-in function in php >= 5.4 + * + * @FIXME We already have php >= 5.4 requirements, so can we remove this? + */ if(! function_exists('hex2bin')) { function hex2bin($s) { if(! (is_string($s) && strlen($s))) @@ -381,14 +384,16 @@ function alt_pager(&$a, $i, $more = '', $less = '') { } -// Turn user/group ACLs stored as angle bracketed text into arrays - - +/** + * @brief Turn user/group ACLs stored as angle bracketed text into arrays. + * + * turn string array of angle-bracketed elements into string array + * e.g. "<123xyz><246qyo>" => array(123xyz,246qyo,sxo33e); + * + * @param string $s + * @return array + */ function expand_acl($s) { - - // turn string array of angle-bracketed elements into string array - // e.g. "<123xyz><246qyo>" => array(123xyz,246qyo,sxo33e); - $ret = array(); if(strlen($s)) { @@ -399,34 +404,41 @@ function expand_acl($s) { $ret[] = $aa; } } + return $ret; } -// Used to wrap ACL elements in angle brackets for storage - - +/** + * @brief Used to wrap ACL elements in angle brackets for storage. + * + * @param[in,out] array &$item + */ function sanitise_acl(&$item) { - if(strlen($item)) + if (strlen($item)) $item = '<' . notags(trim($item)) . '>'; else unset($item); } - -// Convert an ACL array to a storable string - +/** + * @brief Convert an ACL array to a storable string. + * + * @param array $p + * @return array + */ function perms2str($p) { $ret = ''; - if(is_array($p)) + if (is_array($p)) $tmp = $p; else - $tmp = explode(',',$p); + $tmp = explode(',', $p); - if(is_array($tmp)) { - array_walk($tmp,'sanitise_acl'); - $ret = implode('',$tmp); + if (is_array($tmp)) { + array_walk($tmp, 'sanitise_acl'); + $ret = implode('', $tmp); } + return $ret; } @@ -858,51 +870,48 @@ function valid_email($x){ return false; } - /** + * @brief Replace naked text hyperlink with HTML formatted hyperlink. * - * Function: linkify - * - * Replace naked text hyperlink with HTML formatted hyperlink - * + * @param string $s + * @param boolean $me (optional) default false + * @return string */ - - -function linkify($s,$me = false) { +function linkify($s, $me = false) { $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\@\~\#\'\%\$\!\+\,\@]*)/", (($me) ? ' $1' : ' $1'), $s); $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s); + return($s); } - /** - * @function sslify($s) - * Replace media element using http url with https to a local redirector if using https locally - * @param string $s + * @brief Replace media element using http url with https to a local redirector + * if using https locally. * * Looks for HTML tags containing src elements that are http when we're viewing an https page * Typically this throws an insecure content violation in the browser. So we redirect them * to a local redirector which uses https and which redirects to the selected content * + * @param string $s * @returns string */ function sslify($s) { - if(strpos(z_root(),'https:') === false) + if (strpos(z_root(),'https:') === false) return $s; $matches = null; $cnt = preg_match_all("/\<(.*?)src=\"(http\:.*?)\"(.*?)\>/",$s,$matches,PREG_SET_ORDER); - if($cnt) { - foreach($matches as $match) { - $filename = basename( parse_url($match[2],PHP_URL_PATH) ); + if ($cnt) { + foreach ($matches as $match) { + $filename = basename( parse_url($match[2], PHP_URL_PATH) ); $s = str_replace($match[2],z_root() . '/sslify/' . $filename . '?f=&url=' . urlencode($match[2]),$s); } } + return $s; } - function get_poke_verbs() { // index is present tense verb // value is array containing past tense verb, translation of present, translation of past @@ -1033,47 +1042,42 @@ function list_smilies() { $params = array('texts' => $texts, 'icons' => $icons); call_hooks('smilie', $params); + return $params; } /** - * - * Function: smilies - * - * Description: - * Replaces text emoticons with graphical images - * - * @Parameter: string $s - * - * Returns string + * @brief Replaces text emoticons with graphical images. * * It is expected that this function will be called using HTML text. * We will escape text between HTML pre and code blocks, and HTML attributes * (such as urls) from being processed. - * + * * At a higher level, the bbcode [nosmile] tag can be used to prevent this * function from being executed by the prepare_text() routine when preparing - * bbcode source for HTML display + * bbcode source for HTML display. * + * @param string $s + * @param boolean $sample (optional) default false + * @return string */ function smilies($s, $sample = false) { - if(intval(get_config('system','no_smilies')) - || (local_channel() && intval(get_pconfig(local_channel(),'system','no_smilies')))) + if(intval(get_config('system', 'no_smilies')) + || (local_channel() && intval(get_pconfig(local_channel(), 'system', 'no_smilies')))) return $s; - $s = preg_replace_callback('{<(pre|code)>.*?}ism','smile_shield',$s); - $s = preg_replace_callback('/<[a-z]+ .*?>/ism','smile_shield',$s); + $s = preg_replace_callback('{<(pre|code)>.*?}ism', 'smile_shield', $s); + $s = preg_replace_callback('/<[a-z]+ .*?>/ism', 'smile_shield', $s); $params = list_smilies(); $params['string'] = $s; - if($sample) { + if ($sample) { $s = '
      '; - for($x = 0; $x < count($params['texts']); $x ++) { + for ($x = 0; $x < count($params['texts']); $x ++) { $s .= '
      ' . $params['texts'][$x] . '
      ' . $params['icons'][$x] . '
      '; } - } - else { + } else { $params['string'] = preg_replace_callback('/<(3+)/','preg_heart',$params['string']); $s = str_replace($params['texts'],$params['icons'],$params['string']); } @@ -1083,6 +1087,12 @@ function smilies($s, $sample = false) { return $s; } +/** + * @brief + * + * @param array $m + * @return string + */ function smile_shield($m) { return ''; } @@ -1091,16 +1101,22 @@ function smile_unshield($m) { return base64url_decode($m[1]); } -// expand <3333 to the correct number of hearts - +/** + * @brief Expand <3333 to the correct number of hearts. + * + * @param array $x + */ function preg_heart($x) { $a = get_app(); - if(strlen($x[1]) == 1) + if (strlen($x[1]) == 1) return $x[0]; + $t = ''; for($cnt = 0; $cnt < strlen($x[1]); $cnt ++) $t .= '<3'; + $r = str_replace($x[0],$t,$x[0]); + return $r; } @@ -1118,27 +1134,33 @@ function day_translate($s) { return $ret; } - - +/** + * @brief normalises a string. + * + * @param string $url + * @return string + */ function normalise_link($url) { - $ret = str_replace(array('https:','//www.'), array('http:','//'), $url); - return(rtrim($ret,'/')); + $ret = str_replace(array('https:', '//www.'), array('http:', '//'), $url); + + return(rtrim($ret, '/')); } /** + * @brief Compare two URLs to see if they are the same. * - * Compare two URLs to see if they are the same, but ignore - * slight but hopefully insignificant differences such as if one - * is https and the other isn't, or if one is www.something and - * the other isn't - and also ignore case differences. + * But ignore slight but hopefully insignificant differences such as if one + * is https and the other isn't, or if one is www.something and the other + * isn't - and also ignore case differences. * - * Return true if the URLs match, otherwise false. + * @see normalis_link() * + * @param string $a + * @param string $b + * @return true if the URLs match, otherwise false */ - - -function link_compare($a,$b) { - if(strcasecmp(normalise_link($a),normalise_link($b)) === 0) +function link_compare($a, $b) { + if (strcasecmp(normalise_link($a), normalise_link($b)) === 0) return true; return false; @@ -1167,8 +1189,10 @@ function theme_attachments(&$item) { $icon = ''; $icontype = substr($r['type'],0,strpos($r['type'],'/')); - // FIXME This should probably be a giant "if" statement in the template so that we don't have icon names - // embedded in php code + /** + * @FIXME This should probably be a giant "if" statement in the + * template so that we don't have icon names embedded in php code. + */ switch($icontype) { case 'video': @@ -1394,11 +1418,14 @@ function prepare_body(&$item,$attach = false) { return $prep_arr['html']; } - -// Given a text string, convert from bbcode to html and add smilie icons. - - -function prepare_text($text,$content_type = 'text/bbcode') { +/** + * @brief Given a text string, convert from bbcode to html and add smilie icons. + * + * @param string $text + * @param sting $content_type + * @return string + */ +function prepare_text($text, $content_type = 'text/bbcode') { switch($content_type) { case 'text/plain': @@ -1451,19 +1478,21 @@ function prepare_text($text,$content_type = 'text/bbcode') { /** * zidify_callback() and zidify_links() work together to turn any HTML a tags with class="zrl" into zid links - * These will typically be generated by a bbcode '[zrl]' tag. This is done inside prepare_text() rather than bbcode() + * These will typically be generated by a bbcode '[zrl]' tag. This is done inside prepare_text() rather than bbcode() * because the latter is used for general purpose conversions and the former is used only when preparing text for * immediate display. - * + * * Issues: Currently the order of HTML parameters in the text is somewhat rigid and inflexible. - * We assume it looks like and will not work if zrl and href appear in a different order. + * We assume it looks like \ and will not work if zrl and href appear in a different order. + * + * @param array $match + * @return string */ - - function zidify_callback($match) { $is_zid = ((feature_enabled(local_channel(),'sendzid')) || (strpos($match[1],'zrl')) ? true : false); $replace = '' . "\n" ; } } @@ -2094,15 +2126,16 @@ function extra_query_args() { } /** - * This function removes the tag $tag from the text $body and replaces it with - * the appropiate link. - * - * @param unknown_type $body the text to replace the tag in - * @param unknown_type $access_tag - used to return tag ACL exclusions e.g. @!foo - * @param unknown_type $str_tags string to add the tag to - * @param unknown_type $profile_uid - * @param unknown_type $tag the tag to replace + * @brief This function removes the tag $tag from the text $body and replaces it + * with the appropiate link. * + * @param App $a + * @param[in,out] string &$body the text to replace the tag in + * @param[in,out] string &$access_tag used to return tag ACL exclusions e.g. @!foo + * @param[in,out] string &$str_tags string to add the tag to + * @param int $profile_uid + * @param string $tag the tag to replace + * @param boolean $diaspora default false * @return boolean true if replaced, false if not replaced */ function handle_tag($a, &$body, &$access_tag, &$str_tags, $profile_uid, $tag, $diaspora = false) { diff --git a/include/zot.php b/include/zot.php index 99a787cd9..28a2e8957 100644 --- a/include/zot.php +++ b/include/zot.php @@ -1,110 +1,113 @@ -0 order by hubloc_url ", dbesc($hash), intval(HUBLOC_FLAGS_DELETED) ); + return $ret; } /** + * @brief Builds a zot notification packet. * - * @function zot_build_packet($channel,$type = 'notify',$recipients = null, $remote_key = null, $secret = null) - * builds a zot notification packet that you can either - * store in the queue with a message array or call zot_zot to immediately - * zot it to the other side - * - * @param array $channel => sender channel structure - * @param string $type => packet type: one of 'ping', 'pickup', 'purge', 'refresh', 'force_refresh', 'notify', 'auth_check' - * @param array $recipients => envelope information, array ( 'guid' => string, 'guid_sig' => string ); empty for public posts - * @param string $remote_key => optional public site key of target hub used to encrypt entire packet - * NOTE: remote_key and encrypted packets are required for 'auth_check' packets, optional for all others - * @param string $secret => random string, required for packets which require verification/callback - * e.g. 'pickup', 'purge', 'notify', 'auth_check'. Packet types 'ping', 'force_refresh', and 'refresh' do not require verification + * Builds a zot notification packet that you can either store in the queue with + * a message array or call zot_zot to immediately zot it to the other side. * + * @param array $channel + * sender channel structure + * @param string $type + * packet type: one of 'ping', 'pickup', 'purge', 'refresh', 'force_refresh', 'notify', 'auth_check' + * @param array $recipients + * envelope information, array ( 'guid' => string, 'guid_sig' => string ); empty for public posts + * @param string $remote_key + * optional public site key of target hub used to encrypt entire packet + * NOTE: remote_key and encrypted packets are required for 'auth_check' packets, optional for all others + * @param string $secret + * random string, required for packets which require verification/callback + * e.g. 'pickup', 'purge', 'notify', 'auth_check'. Packet types 'ping', 'force_refresh', and 'refresh' do not require verification + * @param string $extra * @returns string json encoded zot packet */ - -function zot_build_packet($channel,$type = 'notify',$recipients = null, $remote_key = null, $secret = null, $extra = null) { +function zot_build_packet($channel, $type = 'notify', $recipients = null, $remote_key = null, $secret = null, $extra = null) { $data = array( 'type' => $type, @@ -118,84 +121,76 @@ function zot_build_packet($channel,$type = 'notify',$recipients = null, $remote_ 'version' => ZOT_REVISION ); - if($recipients) { - for($x = 0; $x < count($recipients); $x ++) + if ($recipients) { + for ($x = 0; $x < count($recipients); $x ++) unset($recipients[$x]['hash']); $data['recipients'] = $recipients; } - if($secret) { + if ($secret) { $data['secret'] = $secret; $data['secret_sig'] = base64url_encode(rsa_sign($secret,$channel['channel_prvkey'])); } - if($extra) { - foreach($extra as $k => $v) + if ($extra) { + foreach ($extra as $k => $v) $data[$k] = $v; } - logger('zot_build_packet: ' . print_r($data,true), LOGGER_DATA); // Hush-hush ultra top-secret mode - if($remote_key) { + if ($remote_key) { $data = crypto_encapsulate(json_encode($data),$remote_key); } return json_encode($data); } - /** - * @function: zot_zot - * @param: string $url - * @param: array $data + * @brief + * + * @see z_post_url() * - * @returns: array => see z_post_url for returned data format + * @param string $url + * @param array $data + * @return array see z_post_url() for returned data format */ - - - -function zot_zot($url,$data) { - return z_post_url($url,array('data' => $data)); +function zot_zot($url, $data) { + return z_post_url($url, array('data' => $data)); } /** - * @function: zot_finger + * @brief Look up information about channel. * - * Look up information about channel - * @param: string $webbie - * does not have to be host qualified e.g. 'foo' is treated as 'foo@thishub' - * @param: array $channel + * @param string $webbie + * does not have to be host qualified e.g. 'foo' is treated as 'foo\@thishub' + * @param array $channel * (optional), if supplied permissions will be enumerated specifically for $channel - * @param: boolean $autofallback + * @param boolean $autofallback * fallback/failover to http if https connection cannot be established. Default is true. * - * @returns: array => see z_post_url and mod/zfinger.php + * @return array see z_post_url() and \ref mod/zfinger.php */ +function zot_finger($webbie, $channel = null, $autofallback = true) { - -function zot_finger($webbie,$channel = null,$autofallback = true) { - - - if(strpos($webbie,'@') === false) { + if (strpos($webbie,'@') === false) { $address = $webbie; $host = get_app()->get_hostname(); - } - else { + } else { $address = substr($webbie,0,strpos($webbie,'@')); $host = substr($webbie,strpos($webbie,'@')+1); } $xchan_addr = $address . '@' . $host; - if((! $address) || (! $xchan_addr)) { + if ((! $address) || (! $xchan_addr)) { logger('zot_finger: no address :' . $webbie); return array('success' => false); - } + } logger('using xchan_addr: ' . $xchan_addr, LOGGER_DATA); - + // potential issue here; the xchan_addr points to the primary hub. // The webbie we were called with may not, so it might not be found // unless we query for hubloc_addr instead of xchan_addr @@ -207,26 +202,24 @@ function zot_finger($webbie,$channel = null,$autofallback = true) { intval(HUBLOC_FLAGS_PRIMARY) ); - if($r) { + if ($r) { $url = $r[0]['hubloc_url']; - if($r[0]['hubloc_network'] && $r[0]['hubloc_network'] !== 'zot') { + if ($r[0]['hubloc_network'] && $r[0]['hubloc_network'] !== 'zot') { logger('zot_finger: alternate network: ' . $webbie); logger('url: '.$url.', net: '.var_export($r[0]['hubloc_network'],true), LOGGER_DATA); return array('success' => false); - } - } - else { + } + } else { $url = 'https://' . $host; } - $rhs = '/.well-known/zot-info'; $https = ((strpos($url,'https://') === 0) ? true : false); logger('zot_finger: ' . $address . ' at ' . $url, LOGGER_DEBUG); - if($channel) { + if ($channel) { $postvars = array( 'address' => $address, 'target' => $channel['channel_guid'], @@ -236,88 +229,85 @@ function zot_finger($webbie,$channel = null,$autofallback = true) { $result = z_post_url($url . $rhs,$postvars); - - if((! $result['success']) && ($autofallback)) { - if($https) { + if ((! $result['success']) && ($autofallback)) { + if ($https) { logger('zot_finger: https failed. falling back to http'); $result = z_post_url('http://' . $host . $rhs,$postvars); } } - } - else { + } else { $rhs .= '?f=&address=' . urlencode($address); $result = z_fetch_url($url . $rhs); - if((! $result['success']) && ($autofallback)) { - if($https) { + if ((! $result['success']) && ($autofallback)) { + if ($https) { logger('zot_finger: https failed. falling back to http'); $result = z_fetch_url('http://' . $host . $rhs); } } } - - if(! $result['success']) - logger('zot_finger: no results'); - return $result; + if (! $result['success']) + logger('zot_finger: no results'); + return $result; } /** - * @function: zot_refresh($them, $channel = null, $force = false) + * @brief Refreshes after permission changed or friending, etc. + * + * zot_refresh is typically invoked when somebody has changed permissions of a channel and they are notified + * to fetch new permissions via a finger/discovery operation. This may result in a new connection + * (abook entry) being added to a local channel and it may result in auto-permissions being granted. + * + * Friending in zot is accomplished by sending a refresh packet to a specific channel which indicates a + * permission change has been made by the sender which affects the target channel. The hub controlling + * the target channel does targetted discovery (a zot-finger request requesting permissions for the local + * channel). These are decoded here, and if necessary and abook structure (addressbook) is created to store + * the permissions assigned to this channel. + * + * Initially these abook structures are created with a 'pending' flag, so that no reverse permissions are + * implied until this is approved by the owner channel. A channel can also auto-populate permissions in + * return and send back a refresh packet of its own. This is used by forum and group communication channels + * so that friending and membership in the channel's "club" is automatic. * - * zot_refresh is typically invoked when somebody has changed permissions of a channel and they are notified - * to fetch new permissions via a finger/discovery operation. This may result in a new connection - * (abook entry) being added to a local channel and it may result in auto-permissions being granted. - * - * Friending in zot is accomplished by sending a refresh packet to a specific channel which indicates a - * permission change has been made by the sender which affects the target channel. The hub controlling - * the target channel does targetted discovery (a zot-finger request requesting permissions for the local - * channel). These are decoded here, and if necessary and abook structure (addressbook) is created to store - * the permissions assigned to this channel. - * - * Initially these abook structures are created with a 'pending' flag, so that no reverse permissions are - * implied until this is approved by the owner channel. A channel can also auto-populate permissions in - * return and send back a refresh packet of its own. This is used by forum and group communication channels - * so that friending and membership in the channel's "club" is automatic. - * * @param array $them => xchan structure of sender * @param array $channel => local channel structure of target recipient, required for "friending" operations + * @param array $force default false * - * @returns boolean true if successful, else false + * @returns boolean true if successful, else false */ +function zot_refresh($them, $channel = null, $force = false) { -function zot_refresh($them,$channel = null, $force = false) { - - if(array_key_exists('xchan_network',$them) && ($them['xchan_network'] !== 'zot')) { + if (array_key_exists('xchan_network', $them) && ($them['xchan_network'] !== 'zot')) { logger('zot_refresh: not got zot. ' . $them['xchan_name']); return true; } logger('zot_refresh: them: ' . print_r($them,true), LOGGER_DATA); - if($channel) + if ($channel) logger('zot_refresh: channel: ' . print_r($channel,true), LOGGER_DATA); $url = null; - if($them['hubloc_url']) + if ($them['hubloc_url']) { $url = $them['hubloc_url']; - else { + } else { $r = q("select hubloc_url, hubloc_flags from hubloc where hubloc_hash = '%s'", dbesc($them['xchan_hash']) ); - if($r) { - foreach($r as $rr) { - if($rr['hubloc_flags'] & HUBLOC_FLAGS_PRIMARY) { + if ($r) { + foreach ($r as $rr) { + if ($rr['hubloc_flags'] & HUBLOC_FLAGS_PRIMARY) { $url = $rr['hubloc_url']; break; } } - if(! $url) + if (! $url) $url = $r[0]['hubloc_url']; } } - if(! $url) { + if (! $url) { logger('zot_refresh: no url'); return false; } @@ -330,12 +320,13 @@ function zot_refresh($them,$channel = null, $force = false) { $postvars['key'] = $channel['channel_pubkey']; } - if(array_key_exists('xchan_addr',$them) && $them['xchan_addr']) + if (array_key_exists('xchan_addr',$them) && $them['xchan_addr']) $postvars['address'] = $them['xchan_addr']; - if(array_key_exists('xchan_hash',$them) && $them['xchan_hash']) + if (array_key_exists('xchan_hash',$them) && $them['xchan_hash']) $postvars['guid_hash'] = $them['xchan_hash']; - if(array_key_exists('xchan_guid',$them) && $them['xchan_guid'] + if (array_key_exists('xchan_guid',$them) && $them['xchan_guid'] && array_key_exists('xchan_guid_sig',$them) && $them['xchan_guid_sig']) { + $postvars['guid'] = $them['xchan_guid']; $postvars['guid_sig'] = $them['xchan_guid_sig']; } @@ -343,19 +334,19 @@ function zot_refresh($them,$channel = null, $force = false) { $rhs = '/.well-known/zot-info'; $result = z_post_url($url . $rhs,$postvars); - + logger('zot_refresh: zot-info: ' . print_r($result,true), LOGGER_DATA); - if($result['success']) { + if ($result['success']) { $j = json_decode($result['body'],true); - if(! (($j) && ($j['success']))) { + if (! (($j) && ($j['success']))) { logger('zot_refresh: result not decodable'); return false; } - $x = import_xchan($j,(($force) ? UPDATE_FLAGS_FORCED : UPDATE_FLAGS_UPDATED)); + $x = import_xchan($j, (($force) ? UPDATE_FLAGS_FORCED : UPDATE_FLAGS_UPDATED)); if(! $x['success']) return false; @@ -415,7 +406,7 @@ function zot_refresh($them,$channel = null, $force = false) { $next_birthday = $r[0]['abook_dob']; $current_abook_connected = (($r[0]['abook_flags'] & ABOOK_FLAG_UNCONNECTED) ? 0 : 1); - + $y = q("update abook set abook_their_perms = %d, abook_dob = '%s' where abook_xchan = '%s' and abook_channel = %d and not (abook_flags & %d) > 0 ", @@ -430,8 +421,8 @@ function zot_refresh($them,$channel = null, $force = false) { // if they are in your address book but you aren't in theirs, and/or this does not // match your current connected state setting, toggle it. - // FIXME: uncoverted to postgres - // FIXME: when this was enabled, all contacts became unconnected. Currently disabled intentionally + /** @FIXME uncoverted to postgres */ + /** @FIXME when this was enabled, all contacts became unconnected. Currently disabled intentionally */ // $y1 = q("update abook set abook_flags = (abook_flags ^ %d) // where abook_xchan = '%s' and abook_channel = %d // and not (abook_flags & %d) limit 1", @@ -505,7 +496,7 @@ function zot_refresh($them,$channel = null, $force = false) { 'type' => NOTIFY_INTRO, 'from_xchan' => $x['hash'], 'to_xchan' => $channel['channel_hash'], - 'link' => z_root() . '/connedit/' . $new_connection[0]['abook_id'], + 'link' => z_root() . '/connedit/' . $new_connection[0]['abook_id'], )); } @@ -514,7 +505,6 @@ function zot_refresh($them,$channel = null, $force = false) { || (! ($new_connection[0]['abook_flags'] & ABOOK_FLAG_PENDING)) ) proc_run('php','include/onepoll.php',$new_connection[0]['abook_id']); } - } } } @@ -524,25 +514,22 @@ function zot_refresh($them,$channel = null, $force = false) { } /** - * @function: zot_gethub + * @brief Look up if channel is known and previously verified. * - * A guid and a url, both signed by the sender, distinguish a known sender at a known location - * This function looks these up to see if the channel is known and therefore previously verified. - * If not, we will need to verify it. + * A guid and a url, both signed by the sender, distinguish a known sender at a + * known location. + * This function looks these up to see if the channel is known and therefore + * previously verified. If not, we will need to verify it. * - * @param array $arr - * $arr must contain: - * string $arr['guid'] => guid of conversant - * string $arr['guid_sig'] => guid signed with conversant's private key - * string $arr['url'] => URL of the origination hub of this communication - * string $arr['url_sig'] => URL signed with conversant's private key - * + * @param array $arr an assoziative array which must contain: + * * \e string \b guid => guid of conversant + * * \e string \b guid_sig => guid signed with conversant's private key + * * \e string \b url => URL of the origination hub of this communication + * * \e string \b url_sig => URL signed with conversant's private key * - * @returns: array => hubloc record + * @returns array|null null if site is blacklisted or not found, otherwise an + * array with an hubloc record */ - - - function zot_gethub($arr) { if($arr['guid'] && $arr['guid_sig'] && $arr['url'] && $arr['url_sig']) { @@ -581,26 +568,23 @@ function zot_gethub($arr) { } /** - * @function zot_register_hub($arr) + * @brief Registers an unknown hup. * - * A communication has been received which has an unknown (to us) sender. - * Perform discovery based on our calculated hash of the sender at the origination address. - * This will fetch the discovery packet of the sender, which contains the public key we - * need to verify our guid and url signatures. + * A communication has been received which has an unknown (to us) sender. + * Perform discovery based on our calculated hash of the sender at the + * origination address. This will fetch the discovery packet of the sender, + * which contains the public key we need to verify our guid and url signatures. * - * @param array $arr - * $arr must contain: - * string $arr['guid'] => guid of conversant - * string $arr['guid_sig'] => guid signed with conversant's private key - * string $arr['url'] => URL of the origination hub of this communication - * string $arr['url_sig'] => URL signed with conversant's private key - * + * @param array $arr an assoziative array which must contain: + * * \e string \b guid => guid of conversant + * * \e string \b guid_sig => guid signed with conversant's private key + * * \e string \b url => URL of the origination hub of this communication + * * \e string \b url_sig => URL signed with conversant's private key * - * @returns array => 'success' (boolean true or false) - * 'message' (optional error string only if success is false) + * @returns array an assoziative array with: + * * \b success boolean true or false + * * \b message (optional) error string only if success is false */ - - function zot_register_hub($arr) { $result = array('success' => false); @@ -640,15 +624,14 @@ function zot_register_hub($arr) { } } } + return $result; } - /** - * @function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED) - * Takes an associative array of a fetched discovery packet and updates + * @brief Takes an associative array of a fetched discovery packet and updates * all internal data structures which need to be updated as a result. - * + * * @param array $arr => json_decoded discovery packet * @param int $ud_flags * Determines whether to create a directory update record if any changes occur, default is UPDATE_FLAGS_UPDATED @@ -659,13 +642,12 @@ function zot_register_hub($arr) { * If set [typically by update_directory_entry()] indicates a specific update table row and more particularly * contains a particular address (ud_addr) which needs to be updated in that table. * - * @returns array => 'success' (boolean true or false) - * 'message' (optional error string only if success is false) + * @return associative array + * * \e boolean \b success boolean true or false + * * \e string \b message (optional) error string only if success is false */ - function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { - call_hooks('import_xchan', $arr); $ret = array('success' => false); @@ -700,11 +682,11 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { $r = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($xchan_hash) - ); + ); if(! array_key_exists('connect_url', $arr)) - $arr['connect_url'] = ''; - + $arr['connect_url'] = ''; + if(strpos($arr['address'],'/') !== false) $arr['address'] = substr($arr['address'],0,strpos($arr['address'],'/')); @@ -713,14 +695,13 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { $import_photos = true; // if we import an entry from a site that's not ours and either or both of us is off the grid - hide the entry. - // TODO: check if we're the same directory realm, which would mean we are allowed to see it + /** @TODO: check if we're the same directory realm, which would mean we are allowed to see it */ $dirmode = get_config('system','directory_mode'); if((($arr['site']['directory_mode'] === 'standalone') || ($dirmode & DIRECTORY_MODE_STANDALONE)) && ($arr['site']['url'] != z_root())) $arr['searchable'] = false; - $hidden = (1 - intval($arr['searchable'])); // Be careful - XCHAN_FLAGS_HIDDEN should evaluate to 1 @@ -770,11 +751,9 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { $what .= 'xchan '; $changed = true; } - } - else { + } else { $import_photos = true; - if((($arr['site']['directory_mode'] === 'standalone') || ($dirmode & DIRECTORY_MODE_STANDALONE)) && ($arr['site']['url'] != z_root())) $arr['searchable'] = false; @@ -789,7 +768,7 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { $new_flags |= XCHAN_FLAGS_SELFCENSORED; if(array_key_exists('deleted',$arr) && $arr['deleted']) $new_flags |= XCHAN_FLAGS_DELETED; - + $x = q("insert into xchan ( xchan_hash, xchan_guid, xchan_guid_sig, xchan_pubkey, xchan_photo_mimetype, xchan_photo_l, xchan_addr, xchan_url, xchan_connurl, xchan_follow, xchan_connpage, xchan_name, xchan_network, xchan_photo_date, xchan_name_date, xchan_flags) values ( '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d) ", @@ -813,11 +792,9 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { $what .= 'new_xchan'; $changed = true; + } - } - - - if($import_photos) { + if ($import_photos) { require_once('include/photo/photo_driver.php'); @@ -826,9 +803,9 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { $local = q("select channel_account_id, channel_id from channel where channel_hash = '%s' limit 1", dbesc($xchan_hash) ); - if($local) { - $ph = z_fetch_url($arr['photo'],true); - if($ph['success']) { + if ($local) { + $ph = z_fetch_url($arr['photo'], true); + if ($ph['success']) { import_channel_photo($ph['body'], $arr['photo_mimetype'], $local[0]['channel_account_id'],$local[0]['channel_id']); // reset the names in case they got messed up when we had a bug in this function $photos = array( @@ -839,12 +816,11 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { false ); } + } else { + $photos = import_profile_photo($arr['photo'], $xchan_hash); } - else { - $photos = import_profile_photo($arr['photo'],$xchan_hash); - } - if($photos) { - if($photos[4]) { + if ($photos) { + if ($photos[4]) { // importing the photo failed somehow. Leave the photo_date alone so we can try again at a later date. // This often happens when somebody joins the matrix with a bad cert. $r = q("update xchan set xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' @@ -855,8 +831,7 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { dbesc($photos[3]), dbesc($xchan_hash) ); - } - else { + } else { $r = q("update xchan set xchan_photo_date = '%s', xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' where xchan_hash = '%s'", dbescdate(datetime_convert('UTC','UTC',$arr['photo_updated'])), @@ -875,8 +850,7 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { // what we are missing for true hub independence is for any changes in the primary hub to // get reflected not only in the hublocs, but also to update the URLs and addr in the appropriate xchan - - $s = sync_locations($arr,$arr); + $s = sync_locations($arr, $arr); if($s) { if($s['change_message']) @@ -915,8 +889,7 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { $what .= 'profile '; $changed = true; } - } - else { + } else { logger('import_xchan: profile not available - hiding'); // they may have made it private $r = q("delete from xprof where xprof_hash = '%s'", @@ -935,7 +908,6 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { $changed = true; } } - if(($changed) || ($ud_flags == UPDATE_FLAGS_FORCED)) { $guid = random_string() . '@' . get_app()->get_hostname(); @@ -956,60 +928,52 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { $ret['hash'] = $xchan_hash; } - - logger('import_xchan: result: ' . print_r($ret,true), LOGGER_DATA); return $ret; } /** - * @function zot_process_response($hub,$arr,$outq) { - * Called immediately after sending a zot message which is using queue processing - * Updates the queue item according to the response result and logs any information - * returned to aid communications troubleshooting. + * @brief Called immediately after sending a zot message which is using queue processing. + * + * Updates the queue item according to the response result and logs any information + * returned to aid communications troubleshooting. * * @param string $hub - url of site we just contacted * @param array $arr - output of z_post_url() * @param array $outq - The queue structure attached to this request - * - * @returns nothing */ +function zot_process_response($hub, $arr, $outq) { - -function zot_process_response($hub,$arr,$outq) { - - if(! $arr['success']) { + if (! $arr['success']) { logger('zot_process_response: failed: ' . $hub); return; } - $x = json_decode($arr['body'],true); + $x = json_decode($arr['body'], true); - if(! $x) { + if (! $x) { logger('zot_process_response: No json from ' . $hub); logger('zot_process_response: headers: ' . print_r($arr['header'],true), LOGGER_DATA); } // update the timestamp for this site - $r = q("update site set site_update = '%s' where site_url = '%s'", + q("update site set site_update = '%s' where site_url = '%s'", dbesc(datetime_convert()), dbesc(dirname($hub)) ); - // synchronous message types are handled immediately // async messages remain in the queue until processed. - if(intval($outq['outq_async'])) { - $r = q("update outq set outq_delivered = 1, outq_updated = '%s' where outq_hash = '%s' and outq_channel = %d", + if (intval($outq['outq_async'])) { + q("update outq set outq_delivered = 1, outq_updated = '%s' where outq_hash = '%s' and outq_channel = %d", dbesc(datetime_convert()), dbesc($outq['outq_hash']), intval($outq['outq_channel']) ); - } - else { - $r = q("delete from outq where outq_hash = '%s' and outq_channel = %d", + } else { + q("delete from outq where outq_hash = '%s' and outq_channel = %d", dbesc($outq['outq_hash']), intval($outq['outq_channel']) ); @@ -1019,19 +983,20 @@ function zot_process_response($hub,$arr,$outq) { } /** - * @function zot_fetch($arr) + * @brief + * + * We received a notification packet (in mod/post.php) that a message is waiting for us, and we've verified the sender. + * Now send back a pickup message, using our message tracking ID ($arr['secret']), which we will sign with our site private key. + * The entire pickup message is encrypted with the remote site's public key. + * If everything checks out on the remote end, we will receive back a packet containing one or more messages, + * which will be processed and delivered before this function ultimately returns. + * + * @see zot_import() * - * We received a notification packet (in mod/post.php) that a message is waiting for us, and we've verified the sender. - * Now send back a pickup message, using our message tracking ID ($arr['secret']), which we will sign with our site private key. - * The entire pickup message is encrypted with the remote site's public key. - * If everything checks out on the remote end, we will receive back a packet containing one or more messages, - * which will be processed and delivered before this function ultimately returns. - * * @param array $arr * decrypted and json decoded notify packet from remote site + * @return array from zot_import() */ - - function zot_fetch($arr) { logger('zot_fetch: ' . print_r($arr,true), LOGGER_DATA); @@ -1054,31 +1019,36 @@ function zot_fetch($arr) { ); $datatosend = json_encode(crypto_encapsulate(json_encode($data),$ret_hub['hubloc_sitekey'])); - + $fetch = zot_zot($url,$datatosend); $result = zot_import($fetch, $arr['sender']['url']); + return $result; } /** - * @function zot_import + * @brief Process incoming array of messages. * * Process an incoming array of messages which were obtained via pickup, and * import, update, delete as directed. - * - * @param array $arr => 'pickup' structure returned from remote site - * @param string $sender_url => the url specified by the sender in the initial communication - * we will verify the sender and url in each returned message structure and also verify - * that all the messages returned match the site url that we are currently processing. - * - * The message types handled here are 'activity' (e.g. posts), 'mail' , 'profile', 'location', - * and 'channel_sync' - * - * @returns array => array ( [0] => string $channel_hash, [1] => string $delivery_status, [2] => string $address ) - * suitable for logging remotely, enumerating the processing results of each message/recipient combination. - * + * + * The message types handled here are 'activity' (e.g. posts), 'mail' , + * 'profile', 'location' and 'channel_sync'. + * + * @param array $arr + * 'pickup' structure returned from remote site + * @param string $sender_url + * the url specified by the sender in the initial communication. + * We will verify the sender and url in each returned message structure and + * also verify that all the messages returned match the site url that we are + * currently processing. + * + * @returns array + * suitable for logging remotely, enumerating the processing results of each message/recipient combination + * * [0] => \e string $channel_hash + * * [1] => \e string $delivery_status + * * [2] => \e string $address */ - function zot_import($arr, $sender_url) { $data = json_decode($arr['body'],true); @@ -1168,7 +1138,7 @@ function zot_import($arr, $sender_url) { } } - logger('public post'); + logger('public post'); // Public post. look for any site members who are or may be accepting posts from this sender // and who are allowed to see them based on the sender's permissions @@ -1190,7 +1160,6 @@ function zot_import($arr, $sender_url) { $i['message']['flags'] = array(); if(! in_array('private',$i['message']['flags'])) $i['message']['flags'][] = 'private'; - } } @@ -1215,8 +1184,8 @@ function zot_import($arr, $sender_url) { logger('zot_import: no deliveries on this site'); continue; } - - if($i['message']) { + + if($i['message']) { if($i['message']['type'] === 'activity') { $arr = get_item_elements($i['message']); @@ -1230,7 +1199,6 @@ function zot_import($arr, $sender_url) { $relay = ((array_key_exists('flags',$i['message']) && in_array('relay',$i['message']['flags'])) ? true : false); $result = process_delivery($i['notify']['sender'],$arr,$deliveries,$relay,false,$message_request); - } elseif($i['message']['type'] === 'mail') { $arr = get_mail_elements($i['message']); @@ -1238,9 +1206,7 @@ function zot_import($arr, $sender_url) { logger('Mail received: ' . print_r($arr,true), LOGGER_DATA); logger('Mail recipients: ' . print_r($deliveries,true), LOGGER_DATA); - $result = process_mail_delivery($i['notify']['sender'],$arr,$deliveries); - } elseif($i['message']['type'] === 'profile') { $arr = get_profile_elements($i['message']); @@ -1249,9 +1215,7 @@ function zot_import($arr, $sender_url) { logger('Profile recipients: ' . print_r($deliveries,true), LOGGER_DATA); $result = process_profile_delivery($i['notify']['sender'],$arr,$deliveries); - } - elseif($i['message']['type'] === 'channel_sync') { // $arr = get_channelsync_elements($i['message']); @@ -1270,31 +1234,34 @@ function zot_import($arr, $sender_url) { $result = process_location_delivery($i['notify']['sender'],$arr,$deliveries); } - } if($result){ - $return = array_merge($return,$result); + $return = array_merge($return, $result); } } } return $return; - } // A public message with no listed recipients can be delivered to anybody who -// has PERMS_NETWORK for that type of post, PERMS_AUTHED (in-network senders are +// has PERMS_NETWORK for that type of post, PERMS_AUTHED (in-network senders are // by definition authenticated) or PERMS_SITE and is one the same // site, or PERMS_SPECIFIC and the sender is a contact who is granted // permissions via their connection permissions in the address book. // Here we take a given message and construct a list of hashes of everybody -// on the site that we should try and deliver to. +// on the site that we should try and deliver to. // Some of these will be rejected, but this gives us a place to start. +/** + * @brief + * + * @param array $msg + * @return NULL|array + */ function public_recips($msg) { - require_once('include/identity.php'); $check_mentions = false; @@ -1363,7 +1330,6 @@ function public_recips($msg) { or ( " . $col . " & " . intval(PERMS_PUBLIC) . ") > 0 or ( " . $col . " & " . intval(PERMS_AUTHED) . ") > 0 ) "; - $r = q("select channel_hash as hash from channel $sql or channel_hash = '%s' and ( channel_pageflags & " . intval(PAGE_REMOVED) . " ) = 0 ", dbesc($msg['notify']['sender']['hash']) @@ -1514,7 +1480,6 @@ function allowed_public_recips($msg) { return $results; } - return array(); } @@ -1544,7 +1509,6 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque continue; } - $channel = $r[0]; // allow public postings to the sys channel regardless of permissions, but not @@ -1763,7 +1727,6 @@ function remove_community_tag($sender,$arr,$uid) { return; logger('remove_community_tag: invoked'); - if(! get_pconfig($uid,'system','blocktags')) { logger('remove_community tag: permission denied.'); @@ -1806,8 +1769,8 @@ function remove_community_tag($sender,$arr,$uid) { logger('remove_community_tag: no parent message'); return; } - - $x = q("delete from term where uid = %d and oid = %d and otype = %d and type = %d and term = '%s' and url = '%s'", + + q("delete from term where uid = %d and oid = %d and otype = %d and type = %d and term = '%s' and url = '%s'", intval($uid), intval($r[0]['id']), intval(TERM_OBJ_POST), @@ -1815,8 +1778,6 @@ function remove_community_tag($sender,$arr,$uid) { dbesc($i['object']['title']), dbesc(get_rel_link($i['object']['link'],'alternate')) ); - - return; } function update_imported_item($sender,$item,$uid) { @@ -1826,12 +1787,20 @@ function update_imported_item($sender,$item,$uid) { logger('update_imported_item: failed: ' . $x['message']); else logger('update_imported_item'); - } -function delete_imported_item($sender,$item,$uid,$relay) { +/** + * @brief Deletes an imported item. + * + * @param array $sender + * @param array $item + * @param int $uid + * @param unknown $relay + * @return boolean|int post_id + */ +function delete_imported_item($sender, $item, $uid, $relay) { - logger('delete_imported_item invoked',LOGGER_DEBUG); + logger('delete_imported_item invoked', LOGGER_DEBUG); $ownership_valid = false; $item_found = false; @@ -1841,13 +1810,13 @@ function delete_imported_item($sender,$item,$uid,$relay) { dbesc($item['mid']), intval($uid) ); - if($r) { - if($r[0]['author_xchan'] === $sender['hash'] || $r[0]['owner_xchan'] === $sender['hash'] || $r[0]['source_xchan'] === $sender['hash']) + if ($r) { + if ($r[0]['author_xchan'] === $sender['hash'] || $r[0]['owner_xchan'] === $sender['hash'] || $r[0]['source_xchan'] === $sender['hash']) $ownership_valid = true; + $post_id = $r[0]['id']; $item_found = true; - } - else { + } else { // perhaps the item is still in transit and the delete notification got here before the actual item did. Store it with the deleted flag set. // item_store() won't try to deliver any notifications or start delivery chains if this flag is set. @@ -1855,22 +1824,24 @@ function delete_imported_item($sender,$item,$uid,$relay) { // But this will ensure that if the (undeleted) original post comes in at a later date, we'll reject it because it will have an older timestamp. logger('delete received for non-existent item - storing item data.'); - if($arr['author_xchan'] === $sender['hash'] || $arr['owner_xchan'] === $sender['hash'] || $arr['source_xchan'] === $sender['hash']) { + + /** @BUG $arr is undefined here, so this is dead code */ + if ($arr['author_xchan'] === $sender['hash'] || $arr['owner_xchan'] === $sender['hash'] || $arr['source_xchan'] === $sender['hash']) { $ownership_valid = true; $item_result = item_store($arr); $post_id = $item_result['item_id']; } } - if($ownership_valid == false) { + if ($ownership_valid === false) { logger('delete_imported_item: failed: ownership issue'); return false; } - if($item_found) { - if($r[0]['item_restrict'] & ITEM_DELETED) { + if ($item_found) { + if ($r[0]['item_restrict'] & ITEM_DELETED) { logger('delete_imported_item: item was already deleted'); - if(! $relay) + if (! $relay) return false; // This is a bit hackish, but may have to suffice until the notification/delivery loop is optimised @@ -1879,9 +1850,9 @@ function delete_imported_item($sender,$item,$uid,$relay) { // code path downstream can relay it again (causing a loop). Since it's already gone it's not coming // back, and we aren't going to (or shouldn't at any rate) delete it again in the future - so losing // this information from the metadata should have no other discernible impact. - - if(($r[0]['id'] != $r[0]['parent']) && ($r[0]['item_flags'] & ITEM_ORIGIN)) { - $x = q("update item set item_flags = %d where id = %d and uid = %d", + + if (($r[0]['id'] != $r[0]['parent']) && ($r[0]['item_flags'] & ITEM_ORIGIN)) { + q("update item set item_flags = %d where id = %d and uid = %d", intval($r[0]['item_flags'] ^ ITEM_ORIGIN), intval($r[0]['id']), intval($r[0]['uid']) @@ -1889,14 +1860,13 @@ function delete_imported_item($sender,$item,$uid,$relay) { } } - require_once('include/items.php'); // Use phased deletion to set the deleted flag, call both tag_deliver and the notifier to notify downstream channels // and then clean up after ourselves with a cron job after several days to do the delete_item_lowlevel() (DROPITEM_PHASE2). - drop_item($post_id,false, DROPITEM_PHASE1); - tag_deliver($uid,$post_id); + drop_item($post_id, false, DROPITEM_PHASE1); + tag_deliver($uid, $post_id); } return $post_id; @@ -1904,17 +1874,13 @@ function delete_imported_item($sender,$item,$uid,$relay) { function process_mail_delivery($sender,$arr,$deliveries) { - $result = array(); - if($sender['hash'] != $arr['from_xchan']) { logger('process_mail_delivery: sender is not mail author'); return; } - - foreach($deliveries as $d) { $r = q("select * from channel where channel_hash = '%s' limit 1", dbesc($d['hash']) @@ -1946,7 +1912,7 @@ function process_mail_delivery($sender,$arr,$deliveries) { $result[] = array($d['hash'],'mail recalled',$channel['channel_name'],$arr['mid']); logger('mail_recalled'); } - else { + else { $result[] = array($d['hash'],'duplicate mail received',$channel['channel_name'],$arr['mid']); logger('duplicate mail received'); } @@ -1974,7 +1940,6 @@ function process_rating_delivery($sender,$arr) { dbesc($sender['hash']) ); - if((! $z) || (! rsa_verify($arr['target'] . '.' . $arr['rating'] . '.' . $arr['rating_text'], base64url_decode($arr['signature']),$z[0]['xchan_pubkey']))) { logger('failed to verify rating'); return; @@ -2012,7 +1977,6 @@ function process_rating_delivery($sender,$arr) { ); logger('rating created'); } - return; } @@ -2080,7 +2044,6 @@ function sync_locations($sender,$arr,$absolute = false) { continue; } - for($x = 0; $x < count($xisting); $x ++) { if(($xisting[$x]['hubloc_url'] === $location['url']) && ($xisting[$x]['hubloc_sitekey'] === $location['sitekey'])) { @@ -2250,7 +2213,7 @@ function sync_locations($sender,$arr,$absolute = false) { ); if($r) hubloc_change_primary($r[0]); - } + } } // get rid of any hubs we have for this channel which weren't reported. @@ -2275,17 +2238,23 @@ function sync_locations($sender,$arr,$absolute = false) { $ret['changed'] = $changed; return $ret; - } - +/** + * @brief Returns an array with all known distinct hubs for this channel. + * + * @see zot_get_hublocs() + * @param array $channel an assoziative array which must contain + * * \e string \b channel_hash the hash of the channel + * @return array an array with assoziated arrays + */ function zot_encode_locations($channel) { $ret = array(); $x = zot_get_hublocs($channel['channel_hash']); - if($x && count($x)) { - foreach($x as $hub) { - if(! ($hub['hubloc_flags'] & HUBLOC_FLAGS_UNVERIFIED)) { + if ($x && count($x)) { + foreach ($x as $hub) { + if (! ($hub['hubloc_flags'] & HUBLOC_FLAGS_UNVERIFIED)) { $ret[] = array( 'host' => $hub['hubloc_host'], 'address' => $hub['hubloc_addr'], @@ -2299,24 +2268,25 @@ function zot_encode_locations($channel) { } } } + return $ret; } - - - -/* - * @function import_directory_profile +/** + * @brief Imports a directory profile. * - * @returns boolean $updated if something changed - * + * @param string $hash + * @param array $profile + * @param string $addr + * @param number $ud_flags + * @param number $suppress_update default 0 + * @return boolean $updated if something changed */ - -function import_directory_profile($hash,$profile,$addr,$ud_flags = UPDATE_FLAGS_UPDATED, $suppress_update = 0) { +function import_directory_profile($hash, $profile, $addr, $ud_flags = UPDATE_FLAGS_UPDATED, $suppress_update = 0) { logger('import_directory_profile', LOGGER_DEBUG); - if(! $hash) + if (! $hash) return false; $arr = array(); @@ -2337,11 +2307,11 @@ function import_directory_profile($hash,$profile,$addr,$ud_flags = UPDATE_FLAGS_ $arr['xprof_hometown'] = (($profile['hometown']) ? htmlspecialchars($profile['hometown'], ENT_COMPAT,'UTF-8',false) : ''); $clean = array(); - if(array_key_exists('keywords',$profile) and is_array($profile['keywords'])) { + if (array_key_exists('keywords', $profile) and is_array($profile['keywords'])) { import_directory_keywords($hash,$profile['keywords']); - foreach($profile['keywords'] as $kw) { - $kw = trim(htmlspecialchars($kw,ENT_COMPAT,'UTF-8',false)); - $kw = trim($kw,','); + foreach ($profile['keywords'] as $kw) { + $kw = trim(htmlspecialchars($kw,ENT_COMPAT, 'UTF-8', false)); + $kw = trim($kw, ','); $clean[] = $kw; } } @@ -2352,48 +2322,47 @@ function import_directory_profile($hash,$profile,$addr,$ud_flags = UPDATE_FLAGS_ // These are not translated, so the German "erwachsenen" keyword will not censor the directory profile. Only the English form - "adult". - if(in_arrayi('nsfw',$clean) || in_arrayi('adult',$clean)) { + if (in_arrayi('nsfw', $clean) || in_arrayi('adult', $clean)) { q("update xchan set xchan_flags = (xchan_flags | %d) where xchan_hash = '%s'", intval(XCHAN_FLAGS_SELFCENSORED), dbesc($hash) ); } - $r = q("select * from xprof where xprof_hash = '%s' limit 1", dbesc($hash) ); - - if($arr['xprof_age'] > 150) + + if ($arr['xprof_age'] > 150) $arr['xprof_age'] = 150; - if($arr['xprof_age'] < 0) + if ($arr['xprof_age'] < 0) $arr['xprof_age'] = 0; - - if($r) { + + if ($r) { $update = false; - foreach($r[0] as $k => $v) { - if((array_key_exists($k,$arr)) && ($arr[$k] != $v)) { + foreach ($r[0] as $k => $v) { + if ((array_key_exists($k,$arr)) && ($arr[$k] != $v)) { logger('import_directory_profile: update ' . $k . ' => ' . $arr[$k]); $update = true; break; } } - if($update) { - $x = q("update xprof set + if ($update) { + q("update xprof set xprof_desc = '%s', xprof_dob = '%s', - xprof_age = %d, + xprof_age = %d, xprof_gender = '%s', xprof_marital = '%s', xprof_sexual = '%s', xprof_locale = '%s', xprof_region = '%s', xprof_postcode = '%s', - xprof_country = '%s', - xprof_about = '%s', - xprof_homepage = '%s', - xprof_hometown = '%s', - xprof_keywords = '%s' + xprof_country = '%s', + xprof_about = '%s', + xprof_homepage = '%s', + xprof_hometown = '%s', + xprof_keywords = '%s' where xprof_hash = '%s'", dbesc($arr['xprof_desc']), dbesc($arr['xprof_dob']), @@ -2412,11 +2381,10 @@ function import_directory_profile($hash,$profile,$addr,$ud_flags = UPDATE_FLAGS_ dbesc($arr['xprof_hash']) ); } - } - else { + } else { $update = true; logger('import_directory_profile: new profile '); - $x = q("insert into xprof (xprof_hash, xprof_desc, xprof_dob, xprof_age, xprof_gender, xprof_marital, xprof_sexual, xprof_locale, xprof_region, xprof_postcode, xprof_country, xprof_about, xprof_homepage, xprof_hometown, xprof_keywords) values ('%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s') ", + q("insert into xprof (xprof_hash, xprof_desc, xprof_dob, xprof_age, xprof_gender, xprof_marital, xprof_sexual, xprof_locale, xprof_region, xprof_postcode, xprof_country, xprof_about, xprof_homepage, xprof_hometown, xprof_keywords) values ('%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s') ", dbesc($arr['xprof_hash']), dbesc($arr['xprof_desc']), dbesc($arr['xprof_dob']), @@ -2438,8 +2406,9 @@ function import_directory_profile($hash,$profile,$addr,$ud_flags = UPDATE_FLAGS_ $d = array('xprof' => $arr, 'profile' => $profile, 'update' => $update); call_hooks('import_directory_profile', $d); - if(($d['update']) && (! $suppress_update)) + if (($d['update']) && (! $suppress_update)) update_modtime($arr['xprof_hash'],random_string() . '@' . get_app()->get_hostname(), $addr, $ud_flags); + return $d['update']; } @@ -2528,7 +2497,6 @@ function import_site($arr,$pubkey) { $site_directory = 0; if($arr['directory_mode'] == 'normal') $site_directory = DIRECTORY_MODE_NORMAL; - if($arr['directory_mode'] == 'primary') $site_directory = DIRECTORY_MODE_PRIMARY; if($arr['directory_mode'] == 'secondary') @@ -2536,9 +2504,6 @@ function import_site($arr,$pubkey) { if($arr['directory_mode'] == 'standalone') $site_directory = DIRECTORY_MODE_STANDALONE; - - - $register_policy = 0; if($arr['register_policy'] == 'closed') $register_policy = REGISTER_CLOSED; @@ -2569,16 +2534,16 @@ function import_site($arr,$pubkey) { if(! $x['success']) $access_policy = ACCESS_PRIVATE; } - + $directory_url = htmlspecialchars($arr['directory_url'],ENT_COMPAT,'UTF-8',false); $url = htmlspecialchars(strtolower($arr['url']),ENT_COMPAT,'UTF-8',false); $sellpage = htmlspecialchars($arr['sellpage'],ENT_COMPAT,'UTF-8',false); $site_location = htmlspecialchars($arr['location'],ENT_COMPAT,'UTF-8',false); $site_realm = htmlspecialchars($arr['realm'],ENT_COMPAT,'UTF-8',false); - // You can have one and only one primary directory per realm. + // You can have one and only one primary directory per realm. // Downgrade any others claiming to be primary. As they have - // flubbed up this badly already, don't let them be directory servers at all. + // flubbed up this badly already, don't let them be directory servers at all. if(($site_directory === DIRECTORY_MODE_PRIMARY) && ($site_realm === get_directory_realm()) @@ -2586,7 +2551,6 @@ function import_site($arr,$pubkey) { $site_directory = DIRECTORY_MODE_NORMAL; } - if($exists) { if(($siterecord['site_flags'] != $site_directory) || ($siterecord['site_access'] != $access_policy) @@ -2644,11 +2608,9 @@ function import_site($arr,$pubkey) { } return $update; - } - /** * Send a zot packet to all hubs where this channel is duplicated, refreshing * such things as personal settings, channel permissions, address book updates, etc. @@ -2714,7 +2676,7 @@ function build_sync_packet($uid = 0, $packet = null, $groups_changed = false) { $info['config'] = $settings; } } - + if($channel) { $info['channel'] = array(); foreach($channel as $k => $v) { @@ -2775,23 +2737,20 @@ function build_sync_packet($uid = 0, $packet = null, $groups_changed = false) { if($interval) @time_sleep_until(microtime(true) + (float) $interval); } - - } function process_channel_sync_delivery($sender,$arr,$deliveries) { -// FIXME - this will sync red structures (channel, pconfig and abook). Eventually we need to make this application agnostic. - + /** @FIXME this will sync red structures (channel, pconfig and abook). Eventually we need to make this application agnostic. */ $result = array(); - - foreach($deliveries as $d) { + + foreach ($deliveries as $d) { $r = q("select * from channel where channel_hash = '%s' limit 1", dbesc($d['hash']) ); - if(! $r) { + if (! $r) { $result[] = array($d['hash'],'not found'); continue; } @@ -2801,7 +2760,6 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { $max_friends = service_class_fetch($channel['channel_id'],'total_channels'); $max_feeds = account_service_class_fetch($channel['channel_account_id'],'total_feeds'); - if($channel['channel_hash'] != $sender['hash']) { logger('process_channel_sync_delivery: possible forgery. Sender ' . $sender['hash'] . ' is not ' . $channel['channel_hash']); $result[] = array($d['hash'],'channel mismatch',$channel['channel_name'],''); @@ -2832,8 +2790,6 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { } } - - if(array_key_exists('abook',$arr) && is_array($arr['abook']) && count($arr['abook'])) { $total_friends = 0; $total_feeds = 0; @@ -2922,7 +2878,7 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { } if($max_feeds !== false && ($clean['abook_flags'] & ABOOK_FLAG_FEED) && $total_feeds > $max_feeds) { logger('process_channel_sync_delivery: total_feeds service class limit exceeded'); - continue; + continue; } q("insert into abook ( abook_xchan, abook_channel ) values ('%s', %d ) ", dbesc($clean['abook_xchan']), @@ -2931,7 +2887,7 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { $total_friends ++; if($clean['abook_flags'] & ABOOK_FLAG_FEED) $total_feeds ++; - } + } if(count($clean)) { foreach($clean as $k => $v) { @@ -2975,7 +2931,7 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { if(intval($cl['deleted']) && (! intval($y['deleted']))) { q("delete from group_member where gid = %d", intval($y['id']) - ); + ); } } } @@ -3095,7 +3051,7 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { if(! $x) { q("insert into profile ( profile_guid, aid, uid ) values ('%s', %d, %d)", dbesc($profile['profile_guid']), - intval($channel['channel_account_id']), + intval($channel['channel_account_id']), intval($channel['channel_id']) ); $x = q("select * from profile where profile_guid = '%s' and uid = %d limit 1", @@ -3109,9 +3065,12 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { foreach($profile as $k => $v) { if(in_array($k,$disallowed)) continue; + $clean[$k] = $v; - // TODO - check if these are allowed, otherwise we'll error - // We also need to import local photos if a custom photo is selected + /** + * @TODO check if these are allowed, otherwise we'll error + * We also need to import local photos if a custom photo is selected + */ } if(count($clean)) { foreach($clean as $k => $v) { @@ -3121,49 +3080,58 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { } } } - - $result[] = array($d['hash'],'channel sync updated',$channel['channel_name'],''); - + $result[] = array($d['hash'],'channel sync updated',$channel['channel_name'],''); } + return $result; } // We probably should make rpost discoverable. - + function get_rpost_path($observer) { if(! $observer) return ''; + $parsed = parse_url($observer['xchan_url']); - return $parsed['scheme'] . '://' . $parsed['host'] . (($parsed['port']) ? ':' . $parsed['port'] : '') . '/rpost?f='; + return $parsed['scheme'] . '://' . $parsed['host'] . (($parsed['port']) ? ':' . $parsed['port'] : '') . '/rpost?f='; } + +/** + * @brief + * + * @param array $x + * @return boolean|string return false or a hash + */ function import_author_zot($x) { - $hash = make_xchan_hash($x['guid'],$x['guid_sig']); + $hash = make_xchan_hash($x['guid'], $x['guid_sig']); $r = q("select hubloc_url from hubloc where hubloc_guid = '%s' and hubloc_guid_sig = '%s' and (hubloc_flags & %d)>0 limit 1", dbesc($x['guid']), dbesc($x['guid_sig']), intval(HUBLOC_FLAGS_PRIMARY) ); - if($r) { + if ($r) { logger('import_author_zot: in cache', LOGGER_DEBUG); return $hash; } logger('import_author_zot: entry not in cache - probing: ' . print_r($x,true), LOGGER_DEBUG); - - $them = array('hubloc_url' => $x['url'],'xchan_guid' => $x['guid'], 'xchan_guid_sig' => $x['guid_sig']); - if(zot_refresh($them)) + + $them = array('hubloc_url' => $x['url'], 'xchan_guid' => $x['guid'], 'xchan_guid_sig' => $x['guid_sig']); + if (zot_refresh($them)) return $hash; + return false; } /** - * @function zot_process_message_request($data) - * If a site receives a comment to a post but finds they have no parent to attach it with, they + * @brief Process a message request. + * + * If a site receives a comment to a post but finds they have no parent to attach it with, they * may send a 'request' packet containing the message_id of the missing parent. This is the handler * for that packet. We will create a message_list array of the entire conversation starting with * the missing parent and invoke delivery to the sender of the packet. @@ -3173,20 +3141,21 @@ function import_author_zot($x) { * processed/delivered in order. * * Called from mod/post.php - */ - - + * + * @param array $data + * @return array + */ function zot_process_message_request($data) { $ret = array('success' => false); - if(! $data['message_id']) { + if (! $data['message_id']) { $ret['message'] = 'no message_id'; logger('no message_id'); return $ret; } $sender = $data['sender']; - $sender_hash = make_xchan_hash($sender['guid'],$sender['guid_sig']); + $sender_hash = make_xchan_hash($sender['guid'], $sender['guid_sig']); /* * Find the local channel in charge of this post (the first and only recipient of the request packet) @@ -3197,7 +3166,7 @@ function zot_process_message_request($data) { $c = q("select * from channel left join xchan on channel_hash = xchan_hash where channel_hash = '%s' limit 1", dbesc($recip_hash) ); - if(! $c) { + if (! $c) { logger('recipient channel not found.'); $ret['message'] .= 'recipient not found.' . EOL; return $ret; @@ -3209,7 +3178,7 @@ function zot_process_message_request($data) { $messages = zot_feed($c[0]['channel_id'],$sender_hash,array('message_id' => $data['message_id'])); - if($messages) { + if ($messages) { $env_recips = null; $r = q("select hubloc_guid, hubloc_url, hubloc_sitekey, hubloc_network, hubloc_flags, hubloc_callback, hubloc_host @@ -3219,20 +3188,18 @@ function zot_process_message_request($data) { intval(HUBLOC_FLAGS_DELETED), intval(HUBLOC_OFFLINE) ); - if(! $r) { + if (! $r) { logger('no hubs'); return $ret; } $hubs = $r; - $hublist = array(); - $keys = array(); - $private = ((array_key_exists('flags',$messages[0]) && in_array('private',$messages[0]['flags'])) ? true : false); + $private = ((array_key_exists('flags', $messages[0]) && in_array('private',$messages[0]['flags'])) ? true : false); if($private) - $env_recips = array('guid' => $sender['guid'],'guid_sig' => $sender['guid_sig'],'hash' => $sender_hash); + $env_recips = array('guid' => $sender['guid'], 'guid_sig' => $sender['guid_sig'], 'hash' => $sender_hash); $data_packet = json_encode(array('message_list' => $messages)); - + foreach($hubs as $hub) { $hash = random_string(); @@ -3260,10 +3227,10 @@ function zot_process_message_request($data) { * invoke delivery to send out the notify packet */ - proc_run('php','include/deliver.php',$hash); + proc_run('php', 'include/deliver.php', $hash); } - } $ret['success'] = true; + return $ret; } -- cgit v1.2.3 From 505e5e90b26fa398e08b6fcad266b7f0ac759bd2 Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 29 Mar 2015 16:05:08 -0700 Subject: fix os_mkdir --- include/RedDAV/RedBrowser.php | 2 ++ include/RedDAV/RedDirectory.php | 1 + include/attach.php | 2 +- 3 files changed, 4 insertions(+), 1 deletion(-) (limited to 'include') diff --git a/include/RedDAV/RedBrowser.php b/include/RedDAV/RedBrowser.php index e651562ec..56d18ded6 100644 --- a/include/RedDAV/RedBrowser.php +++ b/include/RedDAV/RedBrowser.php @@ -95,6 +95,7 @@ class RedBrowser extends DAV\Browser\Plugin { '{DAV:}getlastmodified', ), 1); + $parent = $this->server->tree->getNodeForPath($path); $parentpath = array(); @@ -167,6 +168,7 @@ class RedBrowser extends DAV\Browser\Plugin { $fullPath = DAV\URLUtil::encodePath('/' . trim($this->server->getBaseUri() . ($path ? $path . '/' : '') . $name, '/')); + $displayName = isset($file[200]['{DAV:}displayname']) ? $file[200]['{DAV:}displayname'] : $name; $displayName = $this->escapeHTML($displayName); diff --git a/include/RedDAV/RedDirectory.php b/include/RedDAV/RedDirectory.php index 68186d21b..922be378d 100644 --- a/include/RedDAV/RedDirectory.php +++ b/include/RedDAV/RedDirectory.php @@ -49,6 +49,7 @@ class RedDirectory extends DAV\Node implements DAV\ICollection, DAV\IQuota { * @param RedBasicAuth &$auth_plugin */ public function __construct($ext_path, &$auth_plugin) { +// $ext_path = urldecode($ext_path); //logger('directory ' . $ext_path, LOGGER_DATA); $this->ext_path = $ext_path; // remove "/cloud" from the beginning of the path diff --git a/include/attach.php b/include/attach.php index 2ca302949..f9206851e 100644 --- a/include/attach.php +++ b/include/attach.php @@ -706,7 +706,7 @@ function attach_mkdir($channel, $observer_hash, $arr = null) { ); } else { - logger('attach_mkdir: ' . mkdir . ' ' . $path . 'failed.'); + logger('attach_mkdir: ' . mkdir . ' ' . $path . ' failed.'); $ret['message'] = t('mkdir failed.'); } } -- cgit v1.2.3 From f01757f0c26a9fed2a307c71dc1a6a41d4b17e3e Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 29 Mar 2015 16:44:26 -0700 Subject: move some lesser used features to plugins --- include/features.php | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) (limited to 'include') diff --git a/include/features.php b/include/features.php index 3a1752052..4121880a4 100644 --- a/include/features.php +++ b/include/features.php @@ -46,9 +46,6 @@ function get_features() { array('nav_channel_select', t('Navigation Channel Select'), t('Change channels directly from within the navigation dropdown menu'),false), array('photo_location', t('Photo Location'), t('If location data is available on uploaded photos, link this to a map.'),false), - - //FIXME - needs a description, but how the hell do we explain this to normals? - array('sendzid', t('Extended Identity Sharing'), t('Share your identity with all websites on the internet. When disabled, identity is only shared with sites in the matrix.'),false), array('expert', t('Expert Mode'), t('Enable Expert Mode to provide advanced configuration options'),false), array('premium_channel', t('Premium Channel'), t('Allows you to set restrictions and terms on those that connect with your channel'),false), ), @@ -62,7 +59,7 @@ function get_features() { array('channel_sources', t('Channel Sources'), t('Automatically import channel content from other channels or feeds'),false), array('content_encrypt', t('Even More Encryption'), t('Allow optional encryption of content end-to-end with a shared secret key'),false), array('consensus_tools', t('Enable voting tools'), t('Provide a class of post which others can vote on'),false), - array('adult_photo_flagging', t('Flag Adult Photos'), t('Provide photo edit option to hide adult photos from default album view'),false), + ), // Network Tools -- cgit v1.2.3 From c29d3fc08ae4b5df72c3958ac790a56815413051 Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 29 Mar 2015 18:42:05 -0700 Subject: mod_connections ajax failure see http://stackoverflow.com/questions/14347611/jquery-client-side-template-syntax-error-unrecognized-expression --- include/diaspora.php | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) (limited to 'include') diff --git a/include/diaspora.php b/include/diaspora.php index 405fa1e40..75eac7681 100755 --- a/include/diaspora.php +++ b/include/diaspora.php @@ -698,6 +698,57 @@ function diaspora_request($importer,$xml) { return; } + +//FIXME +/* + if(feature_enabled($channel['channel_id'],'premium_channel')) { + $myaddr = $importer['channel_address'] . '@' . get_app()->get_hostname(); + $cnv = random_string(); + $mid = random_string(); + + $msg = t('You have started sharing with a Redmatrix premium channel.'); + $msg .= t('Redmatrix premium channels are not available for sharing with Diaspora members. This sharing request has been blocked.') . "\r"; + $msg .= t('Please do not reply to this message, as this channel is not sharing with you and any reply will not be seen by the recipient.') . "\r"; + + $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C'); + $signed_text = $mid . ';' . $cnv . ';' . $msg . ';' + . $created . ';' . $myaddr . ';' . $cnv; + + $sig = base64_encode(rsa_sign($signed_text,$importer['channel_prvkey'],'sha256')); + + $conv = array( + 'guid' => xmlify($cnv), + 'subject' => xmlify(t('Sharing request failed.')), + 'created_at' => xmlify($created), + 'diaspora_handle' => xmlify($myaddr), + 'participant_handles' => xmlify($myaddr . ';' . $sender_handle) + ); + + $msg = array( + 'guid' => xmlify($mid), + 'parent_guid' => xmlify($cnv), + 'parent_author_signature' => xmlify($sig), + 'author_signature' => xmlify($sig), + 'text' => xmlify($msg), + 'created_at' => xmlify($created), + 'diaspora_handle' => xmlify($myaddr), + 'conversation_guid' => xmlify($cnv) + ); + + $conv['messages'] = array($msg); + $tpl = get_markup_template('diaspora_conversation.tpl'); + $xmsg = replace_macros($tpl, array('$conv' => $conv)); + + $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$importer,$ret,$importer['channel_prvkey'],$ret['xchan_pubkey'],false))); + + diaspora_transmit($importer,$ret,$slap,false); + return; + } + +*/ +// End FIXME + + $role = get_pconfig($channel['channel_id'],'system','permissions_role'); if($role) { $x = get_role_perms($role); -- cgit v1.2.3 From cff7696e984576718f48bd9fcdd2ecff0e7d7d73 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 30 Mar 2015 00:51:03 -0700 Subject: change "create new collection" to iconic, document the account table --- include/group.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/group.php b/include/group.php index 70668a355..19bdf03f9 100644 --- a/include/group.php +++ b/include/group.php @@ -297,7 +297,7 @@ function group_side($every="connections",$each="group",$edit = false, $group_id $o = replace_macros($tpl, array( '$title' => t('Collections'), '$edittext' => t('Edit collection'), - '$createtext' => t('Create a new collection'), + '$createtext' => t('New collection'), '$ungrouped' => (($every === 'contacts') ? t('Channels not in any collection') : ''), '$groups' => $groups, '$add' => t('add'), -- cgit v1.2.3 From c98de445281e1a819581f96d0919eb5da307c62c Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 31 Mar 2015 20:01:37 -0700 Subject: more logging for onepoll --- include/onepoll.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/onepoll.php b/include/onepoll.php index ee90fbdb1..66b000934 100644 --- a/include/onepoll.php +++ b/include/onepoll.php @@ -125,7 +125,7 @@ function onepoll_run($argv, $argc){ if(($x) && ($x['success'])) { $total = 0; - logger('onepoll: feed update ' . $contact['xchan_name']); + logger('onepoll: feed update ' . $contact['xchan_name'] . ' ' . $feedurl); $j = json_decode($x['body'],true); if($j['success'] && $j['messages']) { -- cgit v1.2.3 From 6f78d7a85d0371dc7fb72acb3a85217005400f91 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 31 Mar 2015 21:06:48 -0700 Subject: fix regdir --- include/poller.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/poller.php b/include/poller.php index 4786188af..bc48c3f00 100644 --- a/include/poller.php +++ b/include/poller.php @@ -174,7 +174,7 @@ function poller_run($argv, $argc){ ); $dirmode = intval(get_config('system','directory_mode')); - if($dirmode === DIRECTORY_MODE_SECONDARY) { + if($dirmode === DIRECTORY_MODE_SECONDARY || $dirmode === DIRECTORY_MODE_PRIMARY) { logger('regdir: ' . print_r(z_fetch_url(get_directory_primary() . '/regdir?f=&url=' . urlencode(z_root()) . '&realm=' . urlencode(get_directory_realm())),true)); } -- cgit v1.2.3 From 6199af6a790016254b3af3cebd334902469f86ec Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 1 Apr 2015 01:07:38 -0700 Subject: revert iconic change to collection list widget --- include/group.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/group.php b/include/group.php index 19bdf03f9..fe55ec23f 100644 --- a/include/group.php +++ b/include/group.php @@ -297,7 +297,7 @@ function group_side($every="connections",$each="group",$edit = false, $group_id $o = replace_macros($tpl, array( '$title' => t('Collections'), '$edittext' => t('Edit collection'), - '$createtext' => t('New collection'), + '$createtext' => t('Add new collection'), '$ungrouped' => (($every === 'contacts') ? t('Channels not in any collection') : ''), '$groups' => $groups, '$add' => t('add'), -- cgit v1.2.3 From 41e755222544ee0733098db20cecad5ffe6319fb Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 1 Apr 2015 12:30:03 -0700 Subject: open bbcode tag --- include/bbcode.php | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'include') diff --git a/include/bbcode.php b/include/bbcode.php index 6f7ef8973..e97a96f87 100644 --- a/include/bbcode.php +++ b/include/bbcode.php @@ -668,6 +668,17 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { "
      " . $t_wrote . "
      $2
      ", $Text); + + $endlessloop = 0; + while ((strpos($Text, "[/open]")!== false) and (strpos($Text, "[open=") !== false) and (++$endlessloop < 20)) { + $rnd = mt_rand(); + $Text = preg_replace("/\[open=(.*?)\](.*?)\[\/open\]/ism", + "
      $1
      $2
      ", + $Text); + } + + + // Declare the format for [quote] layout $QuoteLayout = '
      $1
      '; -- cgit v1.2.3 From c2517eca56a032c33208a786dc2734919e31c8e6 Mon Sep 17 00:00:00 2001 From: jeroenpraat Date: Thu, 2 Apr 2015 02:23:26 +0200 Subject: Update/fix Dutch and removing an ugly space --- include/ItemObject.php | 2 +- include/conversation.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/ItemObject.php b/include/ItemObject.php index 4fc01e6d4..d5601edf5 100644 --- a/include/ItemObject.php +++ b/include/ItemObject.php @@ -309,7 +309,7 @@ class Item extends BaseObject { 'title_tosource' => get_pconfig($conv->get_profile_owner(),'system','title_tosource'), 'ago' => relative_date($item['created']), 'app' => $item['app'], - 'str_app' => sprintf( t(' from %s'), $item['app']), + 'str_app' => sprintf( t('from %s'), $item['app']), 'isotime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'c'), 'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'), 'editedtime' => (($item['edited'] != $item['created']) ? sprintf( t('last edited: %s'), datetime_convert('UTC', date_default_timezone_get(), $item['edited'], 'r')) : ''), diff --git a/include/conversation.php b/include/conversation.php index 042d01b3e..67f3afde0 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -713,7 +713,7 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $ 'text' => strip_tags($body), 'ago' => relative_date($item['created']), 'app' => $item['app'], - 'str_app' => sprintf( t(' from %s'), $item['app']), + 'str_app' => sprintf( t('from %s'), $item['app']), 'isotime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'c'), 'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'), 'editedtime' => (($item['edited'] != $item['created']) ? sprintf( t('last edited: %s'), datetime_convert('UTC', date_default_timezone_get(), $item['edited'], 'r')) : ''), -- cgit v1.2.3 From 754ac2cff72b0d9d5d9b389740cc8946ed1e40b2 Mon Sep 17 00:00:00 2001 From: Klaus Weidenbach Date: Mon, 6 Apr 2015 23:51:30 +0200 Subject: Fix Design Tool navigation for sys channel. Fix creating menu for sys channel. --- include/text.php | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) (limited to 'include') diff --git a/include/text.php b/include/text.php index 664d5f83d..fefe67c4e 100644 --- a/include/text.php +++ b/include/text.php @@ -1258,15 +1258,19 @@ function format_categories(&$item,$writeable) { return $s; } -// Add any hashtags which weren't mentioned in the message body, e.g. community tags - +/** + * @brief Add any hashtags which weren't mentioned in the message body, e.g. community tags + * + * @param[in] array &$item + * @return string HTML link of hashtag + */ function format_hashtags(&$item) { - $s = ''; - $terms = get_terms_oftype($item['term'],TERM_HASHTAG); + + $terms = get_terms_oftype($item['term'], TERM_HASHTAG); if($terms) { foreach($terms as $t) { - $term = htmlspecialchars($t['term'],ENT_COMPAT,'UTF-8',false) ; + $term = htmlspecialchars($t['term'], ENT_COMPAT, 'UTF-8', false) ; if(! trim($term)) continue; if(strpos($item['body'], $t['url'])) @@ -1278,6 +1282,7 @@ function format_hashtags(&$item) { $s .= '#
      ' . $term . ''; } } + return $s; } @@ -1301,6 +1306,7 @@ function format_mentions(&$item) { $s .= '@' . $term . ''; } } + return $s; } @@ -2065,7 +2071,11 @@ function json_decode_plus($s) { return $x; } - +/** + * @brief Creates navigation menu for webpage, layout, blocks, menu sites. + * + * @return string + */ function design_tools() { $channel = get_app()->get_channel(); -- cgit v1.2.3 From 3a3563a4b1673cdd86fdba01985ccfea98ab8b0e Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 6 Apr 2015 19:00:13 -0700 Subject: commit 59828593c broke some important poco stuff, looks like the cat might have climbed over the keyboard and deleted something that wasn't intended to be deleted. --- include/socgraph.php | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) (limited to 'include') diff --git a/include/socgraph.php b/include/socgraph.php index 7f03f8696..acebec419 100644 --- a/include/socgraph.php +++ b/include/socgraph.php @@ -180,6 +180,26 @@ function poco_load($xchan = '', $url = null) { } $total ++; + + + $r = q("select * from xlink where xlink_xchan = '%s' and xlink_link = '%s' and xlink_static = 0 limit 1", + dbesc($xchan), + dbesc($hash) + ); + + if(! $r) { + q("insert into xlink ( xlink_xchan, xlink_link, xlink_updated, xlink_static ) values ( '%s', '%s', '%s', 0 ) ", + dbesc($xchan), + dbesc($hash), + dbesc(datetime_convert()) + ); + } + else { + q("update xlink set xlink_updated = '%s' where xlink_id = %d", + dbesc(datetime_convert()), + intval($r[0]['xlink_id']) + ); + } } logger("poco_load: loaded $total entries",LOGGER_DEBUG); -- cgit v1.2.3 From 3c05af6553ae1bef3a59c5f58aa7551021e34363 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 6 Apr 2015 21:26:40 -0700 Subject: make open tag work correctly for multiple invocations in the same text --- include/bbcode.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) (limited to 'include') diff --git a/include/bbcode.php b/include/bbcode.php index e97a96f87..5ee3d5d5e 100644 --- a/include/bbcode.php +++ b/include/bbcode.php @@ -291,6 +291,12 @@ function bb_map_location($match) { return str_replace($match[0],'
      ' . generate_named_map($match[1]) . '
      ', $match[0]); } +function bbopentag($match) { + $rnd = mt_rand(); + return "
      " . $match[1] . "
      " . $match[2] . "
      "; +} + + function bb_sanitize_style($input) { //whitelist property limits (0 = no limitation) @@ -672,9 +678,7 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { $endlessloop = 0; while ((strpos($Text, "[/open]")!== false) and (strpos($Text, "[open=") !== false) and (++$endlessloop < 20)) { $rnd = mt_rand(); - $Text = preg_replace("/\[open=(.*?)\](.*?)\[\/open\]/ism", - "
      $1
      $2
      ", - $Text); + $Text = preg_replace_callback("/\[open=(.*?)\](.*?)\[\/open\]/ism",'bbopentag',$Text); } -- cgit v1.2.3 From 1162af4c0da4998d484240f2e65195d7996e5d8c Mon Sep 17 00:00:00 2001 From: Habeas Codice Date: Tue, 7 Apr 2015 05:42:47 -0700 Subject: "PHP Strict Standards: Only variables should be passed by reference" --- include/RedDAV/RedBrowser.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'include') diff --git a/include/RedDAV/RedBrowser.php b/include/RedDAV/RedBrowser.php index 56d18ded6..31c2c1e45 100644 --- a/include/RedDAV/RedBrowser.php +++ b/include/RedDAV/RedBrowser.php @@ -271,8 +271,9 @@ class RedBrowser extends DAV\Browser\Plugin { '$nick' => $this->auth->getCurrentUser() )); - get_app()->page['content'] = $html; - load_pdl(get_app()); + $a = get_app(); + $a->page['content'] = $html; + load_pdl($a); $theme_info_file = "view/theme/" . current_theme() . "/php/theme.php"; if (file_exists($theme_info_file)){ @@ -282,7 +283,7 @@ class RedBrowser extends DAV\Browser\Plugin { $func(get_app()); } } - construct_page(get_app()); + construct_page($a); } /** -- cgit v1.2.3 From dbb3cda9a65f1687de730efb477a098e39358e71 Mon Sep 17 00:00:00 2001 From: Habeas Codice Date: Tue, 7 Apr 2015 05:45:24 -0700 Subject: missed one --- include/RedDAV/RedBrowser.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/RedDAV/RedBrowser.php b/include/RedDAV/RedBrowser.php index 31c2c1e45..a0330d7cc 100644 --- a/include/RedDAV/RedBrowser.php +++ b/include/RedDAV/RedBrowser.php @@ -280,7 +280,7 @@ class RedBrowser extends DAV\Browser\Plugin { require_once($theme_info_file); if (function_exists(str_replace('-', '_', current_theme()) . '_init')) { $func = str_replace('-', '_', current_theme()) . '_init'; - $func(get_app()); + $func($a); } } construct_page($a); -- cgit v1.2.3 From f03a937c4ea73e47e48592a5ba0d051c535c51d3 Mon Sep 17 00:00:00 2001 From: Klaus Weidenbach Date: Tue, 7 Apr 2015 22:39:42 +0200 Subject: Renamed some functions to match other names in bbcode.php. Some documentation. Removed unused variables. Removed empty spaces at line endings. --- include/bbcode.php | 402 ++++++++++++++++++++++++++++------------------------- 1 file changed, 211 insertions(+), 191 deletions(-) (limited to 'include') diff --git a/include/bbcode.php b/include/bbcode.php index 5ee3d5d5e..e79e709da 100644 --- a/include/bbcode.php +++ b/include/bbcode.php @@ -1,28 +1,33 @@ -type=="error") return $match[0]; + if ($o->type == 'error') + return $match[0]; $html = oembed_format_object($o); return $html; } function tryzrlaudio($match) { - $link = $match[1]; $zrl = is_matrix_url($link); if($zrl) $link = zid($link); - return ''; + + return ''; } function tryzrlvideo($match) { @@ -30,8 +35,8 @@ function tryzrlvideo($match) { $zrl = is_matrix_url($link); if($zrl) $link = zid($link); - return ''; + return ''; } // [noparse][i]italic[/i][/noparse] turns into @@ -39,11 +44,12 @@ function tryzrlvideo($match) { // to hide them from parser. function bb_spacefy($st) { - $whole_match = $st[0]; - $captured = $st[1]; - $spacefied = preg_replace("/\[(.*?)\]/", "[ $1 ]", $captured); - $new_str = str_replace($captured, $spacefied, $whole_match); - return $new_str; + $whole_match = $st[0]; + $captured = $st[1]; + $spacefied = preg_replace("/\[(.*?)\]/", "[ $1 ]", $captured); + $new_str = str_replace($captured, $spacefied, $whole_match); + + return $new_str; } // The previously spacefied [noparse][ i ]italic[ /i ][/noparse], @@ -51,10 +57,11 @@ function bb_spacefy($st) { // returning [i]italic[/i] function bb_unspacefy_and_trim($st) { - $whole_match = $st[0]; - $captured = $st[1]; - $unspacefied = preg_replace("/\[ (.*?)\ ]/", "[$1]", $captured); - return $unspacefied; + //$whole_match = $st[0]; + $captured = $st[1]; + $unspacefied = preg_replace("/\[ (.*?)\ ]/", "[$1]", $captured); + + return $unspacefied; } @@ -103,8 +110,8 @@ function bb_extract_images($body) { function bb_replace_images($body, $images) { $newbody = $body; - $cnt = 0; + if(! $images) return $newbody; @@ -119,10 +126,15 @@ function bb_replace_images($body, $images) { return $newbody; } - - +/** + * @brief Parses crypt BBCode. + * + * @param array $match + * @return string HTML code + */ function bb_parse_crypt($match) { + $matches = array(); $attributes = $match[1]; $algorithm = ""; @@ -137,7 +149,6 @@ function bb_parse_crypt($match) { $hint = ""; - preg_match("/hint='(.*?)'/ism", $attributes, $matches); if ($matches[1] != "") $hint = $matches[1]; @@ -147,36 +158,42 @@ function bb_parse_crypt($match) { $x = random_string(); - $Text = '
      ' . t('Encrypted content') . '

      '; + $Text = '
      ' . t('Encrypted content') . '

      '; return $Text; - } function bb_parse_app($match) { require_once('include/apps.php'); $app = app_decode($match[1]); - if($app) + if ($app) return app_render($app); - } function bb_parse_element($match) { $j = json_decode(base64url_decode($match[1]),true); - if($j) { + if ($j) { $o = EOL . '' . t('Install design element: ') . $j['pagetitle'] . '' . EOL; } + return $o; } +/** + * @brief Returns an QR-code image from a value given in $match[1]. + * + * @param array $match + * @return string HTML img with QR-code of $match[1] + */ function bb_qr($match) { return '' . t('QR code') . ''; -} +} function bb_ShareAttributes($match) { + $matches = array(); $attributes = $match[1]; $author = ""; @@ -204,13 +221,14 @@ function bb_ShareAttributes($match) { if ($matches[1] != "") $posted = $matches[1]; + // message_id is never used, do we still need it? $message_id = ""; preg_match("/message_id='(.*?)'/ism", $attributes, $matches); if ($matches[1] != "") $message_id = $matches[1]; - // FIXME - this should really be a wall-item-ago so it will get updated on the client + /** @FIXME - this should really be a wall-item-ago so it will get updated on the client */ $reldate = (($posted) ? relative_date($posted) : ''); $headline = '
      '; @@ -230,24 +248,30 @@ function bb_ShareAttributes($match) { $text = $headline . '
      ' . trim($match[2]) . '
      '; - return($text); + return $text; } function bb_location($match) { // not yet implemented } -function bbiframe($match) { +/** + * @brief Returns an iframe from $match[1]. + * + * @param array $match + * @return string HTML iframe with content of $match[1] + */ +function bb_iframe($match) { $a = get_app(); - - $sandbox = ((strpos($match[1],get_app()->get_hostname())) ? ' sandbox="allow-scripts" ' : ''); + $sandbox = ((strpos($match[1], $a->get_hostname())) ? ' sandbox="allow-scripts" ' : ''); return ''; } function bb_ShareAttributesSimple($match) { + $matches = array(); $attributes = $match[1]; $author = ""; @@ -268,16 +292,16 @@ function bb_ShareAttributesSimple($match) { if ($matches[1] != "") $profile = $matches[1]; - $text = "
      ".html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8').' '.$author.": div class=\"reshared-content\">" .$match[2]."
      "; + $text = '
      ' . html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8') . ' ' . $author . ': div class="reshared-content">' . $match[2] . '
      '; return($text); } function rpost_callback($match) { if ($match[2]) { - return str_replace($match[0],get_rpost_path(get_app()->get_observer()) . '&title=' . urlencode($match[2]) . '&body=' . urlencode($match[3]),$match[0]); + return str_replace($match[0], get_rpost_path(get_app()->get_observer()) . '&title=' . urlencode($match[2]) . '&body=' . urlencode($match[3]), $match[0]); } else { - return str_replace($match[0],get_rpost_path(get_app()->get_observer()) . '&body=' . urlencode($match[3]),$match[0]); + return str_replace($match[0], get_rpost_path(get_app()->get_observer()) . '&body=' . urlencode($match[3]), $match[0]); } } @@ -291,52 +315,59 @@ function bb_map_location($match) { return str_replace($match[0],'
      ' . generate_named_map($match[1]) . '
      ', $match[0]); } -function bbopentag($match) { - $rnd = mt_rand(); - return "
      " . $match[1] . "
      " . $match[2] . "
      "; +function bb_opentag($match) { + $rnd = mt_rand(); + return "
      " . $match[1] . "
      " . $match[2] . "
      "; } - - +/** + * @brief Sanitize style properties from BBCode to HTML. + * + * @param array $input + * @return string A HTML span tag with the styles. + */ function bb_sanitize_style($input) { - //whitelist property limits (0 = no limitation) - $w = array( // color properties - "color" => 0, - "background-color" => 0, + // whitelist array: property => limits (0 = no limitation) + $w = array( + // color properties + "color" => 0, + "background-color" => 0, // box properties - "padding" => array("px"=>100, "%"=>0, "em"=>2, "ex"=>2, "mm"=>0, "cm"=>0, "in"=>0, "pt"=>0, "pc"=>0), - "margin" => array("px"=>100, "%"=>0, "em"=>2, "ex"=>2, "mm"=>0, "cm"=>0, "in"=>0, "pt"=>0, "pc"=>0), - "border" => array("px"=>100, "%"=>0, "em"=>2, "ex"=>2, "mm"=>0, "cm"=>0, "in"=>0, "pt"=>0, "pc"=>0), - "float" => 0, - "clear" => 0, + "padding" => array("px"=>100, "%"=>0, "em"=>2, "ex"=>2, "mm"=>0, "cm"=>0, "in"=>0, "pt"=>0, "pc"=>0), + "margin" => array("px"=>100, "%"=>0, "em"=>2, "ex"=>2, "mm"=>0, "cm"=>0, "in"=>0, "pt"=>0, "pc"=>0), + "border" => array("px"=>100, "%"=>0, "em"=>2, "ex"=>2, "mm"=>0, "cm"=>0, "in"=>0, "pt"=>0, "pc"=>0), + "float" => 0, + "clear" => 0, // text properties - "text-decoration" => 0, - + "text-decoration" => 0, ); + $css = array(); $css_string = $input[1]; - $a = explode(';',$css_string); + $a = explode(';', $css_string); + foreach($a as $parts){ list($k, $v) = explode(':', $parts); - $css[ trim($k) ] = trim($v); + $css[ trim($k) ] = trim($v); } // sanitize properties $b = array_merge(array_diff_key($css, $w), array_diff_key($w, $css)); $css = array_diff_key($css, $b); + $css_string_san = ''; - foreach($css as $key => $value) { - if($w[$key] != null) { - foreach($w[$key] as $limit_key => $limit_value) { + foreach ($css as $key => $value) { + if ($w[$key] != null) { + foreach ($w[$key] as $limit_key => $limit_value) { //sanitize values - if(strpos($value, $limit_key)) { + if (strpos($value, $limit_key)) { $value = preg_replace_callback( "/(\S.*?)$limit_key/ism", function($match) use($limit_value, $limit_key) { - if($match[1] > $limit_value) { + if ($match[1] > $limit_value) { return $limit_value . $limit_key; } else { - return $match[1] . $limit_key; + return $match[1] . $limit_key; } }, $value @@ -346,19 +377,20 @@ function bb_sanitize_style($input) { } $css_string_san .= $key . ":" . $value ."; "; } - return "" . $input[2] . ""; + + return '' . $input[2] . ''; } // BBcode 2 HTML was written by WAY2WEB.net // extended to work with Mistpark/Friendica/Red - Mike Macgirvin -function bbcode($Text,$preserve_nl = false, $tryoembed = true) { +function bbcode($Text, $preserve_nl = false, $tryoembed = true) { $a = get_app(); - // Move all spaces out of the tags + // Move all spaces out of the tags // ....Uhm why? - // This is basically doing a trim() on the stuff in between tags, but it messes up + // This is basically doing a trim() on the stuff in between tags, but it messes up // carefully crafted bbcode and especially other pre-formatted code. // Commenting out until we come up with a use case where it's needed. Then let's try and // special case rather than a heavy-handed approach like this. @@ -399,7 +431,7 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { $Text = preg_replace("/\[observer\=0\](.*?)\[\/observer\]/ism", '$1', $Text); $Text = preg_replace("/\[rpost(=.*?)?\](.*?)\[\/rpost\]/ism", '', $Text); } - } + } $channel = $a->get_channel(); if (strpos($Text,'[/channel]') !== false) { @@ -410,7 +442,7 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { $Text = preg_replace("/\[channel\=1\].*?\[\/channel\]/ism", '', $Text); $Text = preg_replace("/\[channel\=0\](.*?)\[\/channel\]/ism", '$1', $Text); } - } + } $x = bb_extract_images($Text); @@ -419,14 +451,14 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { $Text = str_replace(array('[baseurl]','[sitename]'),array(z_root(),get_config('system','sitename')),$Text); - + // Replace any html brackets with HTML Entities to prevent executing HTML or script // Don't use strip_tags here because it breaks [url] search by replacing & with amp $Text = str_replace("<", "<", $Text); $Text = str_replace(">", ">", $Text); - + // Convert new line chars to html
      tags // nlbr seems to be hopelessly messed up @@ -434,14 +466,14 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { // We'll emulate it. - $Text = str_replace("\r\n","\n", $Text); - $Text = str_replace(array("\r","\n"), array('
      ','
      '), $Text); + $Text = str_replace("\r\n", "\n", $Text); + $Text = str_replace(array("\r", "\n"), array('
      ', '
      '), $Text); - if($preserve_nl) - $Text = str_replace(array("\n","\r"), array('',''),$Text); + if ($preserve_nl) + $Text = str_replace(array("\n", "\r"), array('', ''), $Text); - $Text = str_replace(array("\t"," "),array("    ","  "),$Text); + $Text = str_replace(array("\t", " "), array("    ", "  "), $Text); // Set up the parameters for a URL search string $URLSearchString = "^\[\]"; @@ -459,20 +491,18 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { $Text = str_replace('[observer.name]',$s1 . $observer['xchan_name'] . $s2, $Text); $Text = str_replace('[observer.address]',$s1 . $observer['xchan_addr'] . $s2, $Text); $Text = str_replace('[observer.webname]',$s1 . substr($observer['xchan_addr'],0,strpos($observer['xchan_addr'],'@')) . $s2, $Text); - $Text = str_replace('[observer.photo]',$s1 . '[zmg]'.$observer['xchan_photo_l'].'[/zmg]' . $s2, $Text); + $Text = str_replace('[observer.photo]',$s1 . '[zmg]'.$observer['xchan_photo_l'].'[/zmg]' . $s2, $Text); } else { $Text = str_replace('[observer.baseurl]', '', $Text); $Text = str_replace('[observer.url]','', $Text); $Text = str_replace('[observer.name]','', $Text); $Text = str_replace('[observer.address]','', $Text); $Text = str_replace('[observer.webname]','',$Text); - $Text = str_replace('[observer.photo]','', $Text); + $Text = str_replace('[observer.photo]','', $Text); } - - // Perform URL Search $urlchars = '[a-zA-Z0-9\:\/\-\?\&\;\.\=\@\_\~\#\%\$\!\+\,\@]'; @@ -482,32 +512,31 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { } if (strpos($Text,'[/qr]') !== false) { - $Text = preg_replace_callback("/\[qr\](.*?)\[\/qr\]/ism","bb_qr",$Text); + $Text = preg_replace_callback("/\[qr\](.*?)\[\/qr\]/ism", 'bb_qr', $Text); } - if (strpos($Text,'[/share]') !== false) { - $Text = preg_replace_callback("/\[share(.*?)\](.*?)\[\/share\]/ism","bb_ShareAttributes",$Text); + $Text = preg_replace_callback("/\[share(.*?)\](.*?)\[\/share\]/ism", 'bb_ShareAttributes', $Text); } if($tryoembed) { if (strpos($Text,'[/url]') !== false) { - $Text = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism",'tryoembed',$Text); + $Text = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism", 'tryoembed', $Text); } - } + } if (strpos($Text,'[/url]') !== false) { - $Text = preg_replace("/\#\^\[url\]([$URLSearchString]*)\[\/url\]/ism", '#^$1', $Text); + $Text = preg_replace("/\#\^\[url\]([$URLSearchString]*)\[\/url\]/ism", '#^$1', $Text); $Text = preg_replace("/\#\^\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#^$2', $Text); $Text = preg_replace("/\[url\]([$URLSearchString]*)\[\/url\]/ism", '$1', $Text); $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$2', $Text); - } + } if (strpos($Text,'[/zrl]') !== false) { - $Text = preg_replace("/\#\^\[zrl\]([$URLSearchString]*)\[\/zrl\]/ism", '#^$1', $Text); - $Text = preg_replace("/\#\^\[zrl\=([$URLSearchString]*)\](.*?)\[\/zrl\]/ism", '#^$2', $Text); + $Text = preg_replace("/\#\^\[zrl\]([$URLSearchString]*)\[\/zrl\]/ism", '#^$1', $Text); + $Text = preg_replace("/\#\^\[zrl\=([$URLSearchString]*)\](.*?)\[\/zrl\]/ism", '#^$2', $Text); $Text = preg_replace("/\[zrl\]([$URLSearchString]*)\[\/zrl\]/ism", '$1', $Text); $Text = preg_replace("/\[zrl\=([$URLSearchString]*)\](.*?)\[\/zrl\]/ism", '$2', $Text); - } + } // Perform MAIL Search - if (strpos($Text,'[/mail]') !== false) { + if (strpos($Text,'[/mail]') !== false) { $Text = preg_replace("/\[mail\]([$MAILSearchString]*)\[\/mail\]/", '$1', $Text); $Text = preg_replace("/\[mail\=([$MAILSearchString]*)\](.*?)\[\/mail\]/", '$2', $Text); } @@ -515,54 +544,52 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { // leave open the posibility of [map=something] // this is replaced in prepare_body() which has knowledge of the item location - if (strpos($Text,'[/map]') !== false) { - $Text = preg_replace_callback("/\[map\](.*?)\[\/map\]/ism",'bb_map_location',$Text); + if (strpos($Text,'[/map]') !== false) { + $Text = preg_replace_callback("/\[map\](.*?)\[\/map\]/ism", 'bb_map_location', $Text); } - - if (strpos($Text,'[map=') !== false) { - $Text = preg_replace_callback("/\[map=(.*?)\]/ism",'bb_map_coords',$Text); + if (strpos($Text,'[map=') !== false) { + $Text = preg_replace_callback("/\[map=(.*?)\]/ism", 'bb_map_coords', $Text); } - - if (strpos($Text,'[map]') !== false) { + if (strpos($Text,'[map]') !== false) { $Text = preg_replace("/\[map\]/", '
      ', $Text); } // Check for bold text - if (strpos($Text,'[b]') !== false) { - $Text = preg_replace("(\[b\](.*?)\[\/b\])ism",'$1',$Text); + if (strpos($Text,'[b]') !== false) { + $Text = preg_replace("(\[b\](.*?)\[\/b\])ism", '$1', $Text); } // Check for Italics text - if (strpos($Text,'[i]') !== false) { - $Text = preg_replace("(\[i\](.*?)\[\/i\])ism",'$1',$Text); + if (strpos($Text,'[i]') !== false) { + $Text = preg_replace("(\[i\](.*?)\[\/i\])ism", '$1', $Text); } // Check for Underline text - if (strpos($Text,'[u]') !== false) { - $Text = preg_replace("(\[u\](.*?)\[\/u\])ism",'$1',$Text); + if (strpos($Text,'[u]') !== false) { + $Text = preg_replace("(\[u\](.*?)\[\/u\])ism", '$1', $Text); } // Check for strike-through text if (strpos($Text,'[s]') !== false) { - $Text = preg_replace("(\[s\](.*?)\[\/s\])ism",'$1',$Text); + $Text = preg_replace("(\[s\](.*?)\[\/s\])ism", '$1', $Text); } // Check for over-line text - if (strpos($Text,'[o]') !== false) { - $Text = preg_replace("(\[o\](.*?)\[\/o\])ism",'$1',$Text); + if (strpos($Text,'[o]') !== false) { + $Text = preg_replace("(\[o\](.*?)\[\/o\])ism", '$1', $Text); } - if (strpos($Text,'[sup]') !== false) { - $Text = preg_replace("(\[sup\](.*?)\[\/sup\])ism",'$1',$Text); + if (strpos($Text,'[sup]') !== false) { + $Text = preg_replace("(\[sup\](.*?)\[\/sup\])ism", '$1', $Text); } - if (strpos($Text,'[sub]') !== false) { - $Text = preg_replace("(\[sub\](.*?)\[\/sub\])ism",'$1',$Text); + if (strpos($Text,'[sub]') !== false) { + $Text = preg_replace("(\[sub\](.*?)\[\/sub\])ism", '$1', $Text); } - + // Check for colored text - if (strpos($Text,'[/color]') !== false) { - $Text = preg_replace("(\[color=(.*?)\](.*?)\[\/color\])ism","$2",$Text); + if (strpos($Text,'[/color]') !== false) { + $Text = preg_replace("(\[color=(.*?)\](.*?)\[\/color\])ism", "$2", $Text); } // Check for sized text - // [size=50] --> font-size: 50px (with the unit). - if (strpos($Text,'[/size]') !== false) { - $Text = preg_replace("(\[size=(\d*?)\](.*?)\[\/size\])ism","$2",$Text); - $Text = preg_replace("(\[size=(.*?)\](.*?)\[\/size\])ism","$2",$Text); + // [size=50] --> font-size: 50px (with the unit). + if (strpos($Text,'[/size]') !== false) { + $Text = preg_replace("(\[size=(\d*?)\](.*?)\[\/size\])ism", "$2", $Text); + $Text = preg_replace("(\[size=(.*?)\](.*?)\[\/size\])ism", "$2", $Text); } // Check for h1 if (strpos($Text,'[h1]') !== false) { @@ -590,16 +617,15 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { } // Check for table of content without params if (strpos($Text,'[toc]') !== false) { - $Text = preg_replace("/\[toc\]/ism",'
        ',$Text); + $Text = preg_replace("/\[toc\]/ism",'
          ',$Text); } // Check for table of content with params if (strpos($Text,'[toc') !== false) { $Text = preg_replace("/\[toc([^\]]+?)\]/ism",'',$Text); - } // Check for centered text - if (strpos($Text,'[/center]') !== false) { - $Text = preg_replace("(\[center\](.*?)\[\/center\])ism","
          $1
          ",$Text); + if (strpos($Text,'[/center]') !== false) { + $Text = preg_replace("(\[center\](.*?)\[\/center\])ism", "
          $1
          ", $Text); } // Check for list text $Text = str_replace("[*]", "
        • ", $Text); @@ -608,52 +634,54 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { $endlessloop = 0; while ((((strpos($Text, "[/list]") !== false) && (strpos($Text, "[list") !== false)) || - ((strpos($Text, "[/ol]") !== false) && (strpos($Text, "[ol]") !== false)) || - ((strpos($Text, "[/ul]") !== false) && (strpos($Text, "[ul]") !== false)) || - ((strpos($Text, "[/li]") !== false) && (strpos($Text, "[li]") !== false))) && (++$endlessloop < 20)) { - $Text = preg_replace("/\[list\](.*?)\[\/list\]/ism", '
            $1
          ' ,$Text); - $Text = preg_replace("/\[list=\](.*?)\[\/list\]/ism", '
            $1
          ' ,$Text); - $Text = preg_replace("/\[list=1\](.*?)\[\/list\]/ism", '
            $1
          ' ,$Text); - $Text = preg_replace("/\[list=((?-i)i)\](.*?)\[\/list\]/ism",'
            $2
          ' ,$Text); - $Text = preg_replace("/\[list=((?-i)I)\](.*?)\[\/list\]/ism", '
            $2
          ' ,$Text); - $Text = preg_replace("/\[list=((?-i)a)\](.*?)\[\/list\]/ism", '
            $2
          ' ,$Text); - $Text = preg_replace("/\[list=((?-i)A)\](.*?)\[\/list\]/ism", '
            $2
          ' ,$Text); - $Text = preg_replace("/\[ul\](.*?)\[\/ul\]/ism", '
            $1
          ' ,$Text); - $Text = preg_replace("/\[ol\](.*?)\[\/ol\]/ism", '
            $1
          ' ,$Text); - $Text = preg_replace("/\[li\](.*?)\[\/li\]/ism", '
        • $1
        • ' ,$Text); - } - if (strpos($Text,'[th]') !== false) { - $Text = preg_replace("/\[th\](.*?)\[\/th\]/sm", '$1' ,$Text); + ((strpos($Text, "[/ol]") !== false) && (strpos($Text, "[ol]") !== false)) || + ((strpos($Text, "[/ul]") !== false) && (strpos($Text, "[ul]") !== false)) || + ((strpos($Text, "[/li]") !== false) && (strpos($Text, "[li]") !== false))) && (++$endlessloop < 20)) { + $Text = preg_replace("/\[list\](.*?)\[\/list\]/ism", '
            $1
          ', $Text); + $Text = preg_replace("/\[list=\](.*?)\[\/list\]/ism", '
            $1
          ', $Text); + $Text = preg_replace("/\[list=1\](.*?)\[\/list\]/ism", '
            $1
          ', $Text); + $Text = preg_replace("/\[list=((?-i)i)\](.*?)\[\/list\]/ism",'
            $2
          ', $Text); + $Text = preg_replace("/\[list=((?-i)I)\](.*?)\[\/list\]/ism", '
            $2
          ', $Text); + $Text = preg_replace("/\[list=((?-i)a)\](.*?)\[\/list\]/ism", '
            $2
          ', $Text); + $Text = preg_replace("/\[list=((?-i)A)\](.*?)\[\/list\]/ism", '
            $2
          ', $Text); + $Text = preg_replace("/\[ul\](.*?)\[\/ul\]/ism", '
            $1
          ', $Text); + $Text = preg_replace("/\[ol\](.*?)\[\/ol\]/ism", '
            $1
          ', $Text); + $Text = preg_replace("/\[li\](.*?)\[\/li\]/ism", '
        • $1
        • ', $Text); + } + if (strpos($Text,'[th]') !== false) { + $Text = preg_replace("/\[th\](.*?)\[\/th\]/sm", '$1', $Text); } if (strpos($Text,'[td]') !== false) { - $Text = preg_replace("/\[td\](.*?)\[\/td\]/sm", '$1' ,$Text); + $Text = preg_replace("/\[td\](.*?)\[\/td\]/sm", '$1', $Text); } - if (strpos($Text,'[tr]') !== false) { - $Text = preg_replace("/\[tr\](.*?)\[\/tr\]/sm", '$1' ,$Text); + if (strpos($Text,'[tr]') !== false) { + $Text = preg_replace("/\[tr\](.*?)\[\/tr\]/sm", '$1', $Text); } - if (strpos($Text,'[/table]') !== false) { - $Text = preg_replace("/\[table\](.*?)\[\/table\]/sm", '$1
          ' ,$Text); - $Text = preg_replace("/\[table border=1\](.*?)\[\/table\]/sm", '$1
          ' ,$Text); - $Text = preg_replace("/\[table border=0\](.*?)\[\/table\]/sm", '$1
          ' ,$Text); + if (strpos($Text,'[/table]') !== false) { + $Text = preg_replace("/\[table\](.*?)\[\/table\]/sm", '$1
          ', $Text); + $Text = preg_replace("/\[table border=1\](.*?)\[\/table\]/sm", '$1
          ', $Text); + $Text = preg_replace("/\[table border=0\](.*?)\[\/table\]/sm", '$1
          ', $Text); } - $Text = str_replace('
          ',"\n",$Text); - $Text = str_replace('[hr]','
          ', $Text); + $Text = str_replace('
          ', "\n", $Text); + $Text = str_replace('[hr]', '
          ', $Text); // This is actually executed in prepare_body() - $Text = str_replace('[nosmile]','',$Text); + $Text = str_replace('[nosmile]', '', $Text); // Check for font change text - if (strpos($Text,'[/font]') !== false) { - $Text = preg_replace("/\[font=(.*?)\](.*?)\[\/font\]/sm","$2",$Text); + if (strpos($Text,'[/font]') !== false) { + $Text = preg_replace("/\[font=(.*?)\](.*?)\[\/font\]/sm", "$2", $Text); } - // Declare the format for [code] layout + // Declare the format for [code] layout $CodeLayout = '$1'; + // Check for [code] text - if (strpos($Text,'[code]') !== false) { - $Text = preg_replace("/\[code\](.*?)\[\/code\]/ism","$CodeLayout", $Text); + if (strpos($Text,'[code]') !== false) { + $Text = preg_replace("/\[code\](.*?)\[\/code\]/ism", "$CodeLayout", $Text); } + // Declare the format for [spoiler] layout $SpoilerLayout = '
          $1
          '; @@ -661,7 +689,7 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { // handle nested quotes $endlessloop = 0; while ((strpos($Text, "[/spoiler]") !== false) and (strpos($Text, "[spoiler]") !== false) and (++$endlessloop < 20)) - $Text = preg_replace("/\[spoiler\](.*?)\[\/spoiler\]/ism","$SpoilerLayout", $Text); + $Text = preg_replace("/\[spoiler\](.*?)\[\/spoiler\]/ism", "$SpoilerLayout", $Text); // Check for [spoiler=Author] text @@ -677,12 +705,10 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { $endlessloop = 0; while ((strpos($Text, "[/open]")!== false) and (strpos($Text, "[open=") !== false) and (++$endlessloop < 20)) { - $rnd = mt_rand(); - $Text = preg_replace_callback("/\[open=(.*?)\](.*?)\[\/open\]/ism",'bbopentag',$Text); + $Text = preg_replace_callback("/\[open=(.*?)\](.*?)\[\/open\]/ism", 'bb_opentag', $Text); } - // Declare the format for [quote] layout $QuoteLayout = '
          $1
          '; @@ -690,7 +716,7 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { // handle nested quotes $endlessloop = 0; while ((strpos($Text, "[/quote]") !== false) and (strpos($Text, "[quote]") !== false) and (++$endlessloop < 20)) - $Text = preg_replace("/\[quote\](.*?)\[\/quote\]/ism","$QuoteLayout", $Text); + $Text = preg_replace("/\[quote\](.*?)\[\/quote\]/ism", "$QuoteLayout", $Text); // Check for [quote=Author] text @@ -754,9 +780,9 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { } // crypt - if (strpos($Text,'[/crypt]') !== false) { + if (strpos($Text,'[/crypt]') !== false) { $x = random_string(); - $Text = preg_replace("/\[crypt\](.*?)\[\/crypt\]/ism",'
          ' . t('Encrypted content') . '
          ', $Text); + $Text = preg_replace("/\[crypt\](.*?)\[\/crypt\]/ism",'
          ' . t('Encrypted content') . '
          ', $Text); $Text = preg_replace_callback("/\[crypt (.*?)\](.*?)\[\/crypt\]/ism", 'bb_parse_crypt', $Text); } @@ -768,32 +794,30 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { $Text = preg_replace_callback("/\[element\](.*?)\[\/element\]/ism",'bb_parse_element', $Text); } - // html5 video and audio - if (strpos($Text,'[/video]') !== false) { + if (strpos($Text,'[/video]') !== false) { $Text = preg_replace_callback("/\[video\](.*?\.(ogg|ogv|oga|ogm|webm|mp4|mpeg|mpg))\[\/video\]/ism", 'tryzrlvideo', $Text); } - if (strpos($Text,'[/audio]') !== false) { + if (strpos($Text,'[/audio]') !== false) { $Text = preg_replace_callback("/\[audio\](.*?\.(ogg|ogv|oga|ogm|webm|mp4|mp3|opus))\[\/audio\]/ism", 'tryzrlaudio', $Text); } - if (strpos($Text,'[/zvideo]') !== false) { + if (strpos($Text,'[/zvideo]') !== false) { $Text = preg_replace_callback("/\[zvideo\](.*?\.(ogg|ogv|oga|ogm|webm|mp4|mpeg|mpg))\[\/zvideo\]/ism", 'tryzrlvideo', $Text); } - if (strpos($Text,'[/zaudio]') !== false) { + if (strpos($Text,'[/zaudio]') !== false) { $Text = preg_replace_callback("/\[zaudio\](.*?\.(ogg|ogv|oga|ogm|webm|mp4|mp3|opus))\[\/zaudio\]/ism", 'tryzrlaudio', $Text); } // Try to Oembed if ($tryoembed) { - - if (strpos($Text,'[/video]') !== false) { + if (strpos($Text,'[/video]') !== false) { $Text = preg_replace_callback("/\[video\](.*?)\[\/video\]/ism", 'tryoembed', $Text); } if (strpos($Text,'[/audio]') !== false) { $Text = preg_replace_callback("/\[audio\](.*?)\[\/audio\]/ism", 'tryoembed', $Text); } - if (strpos($Text,'[/zvideo]') !== false) { + if (strpos($Text,'[/zvideo]') !== false) { $Text = preg_replace_callback("/\[zvideo\](.*?)\[\/zvideo\]/ism", 'tryoembed', $Text); } if (strpos($Text,'[/zaudio]') !== false) { @@ -816,43 +840,40 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { $Text = preg_replace("/\[zaudio\](.*?)\[\/zaudio\]/", '$1', $Text); } - - - if ($tryoembed){ if (strpos($Text,'[/iframe]') !== false) { - $Text = preg_replace_callback("/\[iframe\](.*?)\[\/iframe\]/ism", 'bbiframe', $Text); + $Text = preg_replace_callback("/\[iframe\](.*?)\[\/iframe\]/ism", 'bb_iframe', $Text); } - } - else { + } else { if (strpos($Text,'[/iframe]') !== false) { $Text = preg_replace("/\[iframe\](.*?)\[\/iframe\]/ism", '$1', $Text); } } + // Youtube extensions if (strpos($Text,'[youtube]') !== false) { if ($tryoembed) { - $Text = preg_replace_callback("/\[youtube\](https?:\/\/www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", 'tryoembed', $Text); - $Text = preg_replace_callback("/\[youtube\](www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", 'tryoembed', $Text); - $Text = preg_replace_callback("/\[youtube\](https?:\/\/youtu.be\/.*?)\[\/youtube\]/ism",'tryoembed',$Text); + $Text = preg_replace_callback("/\[youtube\](https?:\/\/www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", 'tryoembed', $Text); + $Text = preg_replace_callback("/\[youtube\](www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", 'tryoembed', $Text); + $Text = preg_replace_callback("/\[youtube\](https?:\/\/youtu.be\/.*?)\[\/youtube\]/ism", 'tryoembed', $Text); } - $Text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/watch\?v\=(.*?)\[\/youtube\]/ism",'[youtube]$1[/youtube]',$Text); - $Text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/embed\/(.*?)\[\/youtube\]/ism",'[youtube]$1[/youtube]',$Text); - $Text = preg_replace("/\[youtube\]https?:\/\/youtu.be\/(.*?)\[\/youtube\]/ism",'[youtube]$1[/youtube]',$Text); + $Text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/watch\?v\=(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $Text); + $Text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/embed\/(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $Text); + $Text = preg_replace("/\[youtube\]https?:\/\/youtu.be\/(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $Text); if ($tryoembed) - $Text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", '', $Text); - else + $Text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", '', $Text); + else $Text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", "http://www.youtube.com/watch?v=$1", $Text); } if (strpos($Text,'[vimeo]') !== false) { if ($tryoembed) { - $Text = preg_replace_callback("/\[vimeo\](https?:\/\/player.vimeo.com\/video\/[0-9]+).*?\[\/vimeo\]/ism",'tryoembed',$Text); - $Text = preg_replace_callback("/\[vimeo\](https?:\/\/vimeo.com\/[0-9]+).*?\[\/vimeo\]/ism",'tryoembed',$Text); + $Text = preg_replace_callback("/\[vimeo\](https?:\/\/player.vimeo.com\/video\/[0-9]+).*?\[\/vimeo\]/ism", 'tryoembed', $Text); + $Text = preg_replace_callback("/\[vimeo\](https?:\/\/vimeo.com\/[0-9]+).*?\[\/vimeo\]/ism", 'tryoembed', $Text); } - $Text = preg_replace("/\[vimeo\]https?:\/\/player.vimeo.com\/video\/([0-9]+)(.*?)\[\/vimeo\]/ism",'[vimeo]$1[/vimeo]',$Text); - $Text = preg_replace("/\[vimeo\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/vimeo\]/ism",'[vimeo]$1[/vimeo]',$Text); + $Text = preg_replace("/\[vimeo\]https?:\/\/player.vimeo.com\/video\/([0-9]+)(.*?)\[\/vimeo\]/ism", '[vimeo]$1[/vimeo]', $Text); + $Text = preg_replace("/\[vimeo\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/vimeo\]/ism", '[vimeo]$1[/vimeo]', $Text); if ($tryoembed) $Text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism", '', $Text); @@ -871,7 +892,7 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { // Summary (e.g. title) is required, earlier revisions only required description (in addition to // start which is always required). Allow desc with a missing summary for compatibility. - if((x($ev,'desc') || x($ev,'summary')) && x($ev,'start')) { + if ((x($ev,'desc') || x($ev,'summary')) && x($ev,'start')) { $sub = format_event_html($ev); $Text = preg_replace("/\[event\-summary\](.*?)\[\/event\-summary\]/ism",'',$Text); @@ -885,26 +906,25 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) { // Unhide all [noparse] contained bbtags unspacefying them // and triming the [noparse] tag. if (strpos($Text,'[noparse]') !== false) { - $Text = preg_replace_callback("/\[noparse\](.*?)\[\/noparse\]/ism", 'bb_unspacefy_and_trim',$Text); + $Text = preg_replace_callback("/\[noparse\](.*?)\[\/noparse\]/ism", 'bb_unspacefy_and_trim', $Text); } if (strpos($Text,'[nobb]') !== false) { - $Text = preg_replace_callback("/\[nobb\](.*?)\[\/nobb\]/ism", 'bb_unspacefy_and_trim',$Text); + $Text = preg_replace_callback("/\[nobb\](.*?)\[\/nobb\]/ism", 'bb_unspacefy_and_trim', $Text); } if (strpos($Text,'[pre]') !== false) { - $Text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", 'bb_unspacefy_and_trim',$Text); + $Text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", 'bb_unspacefy_and_trim', $Text); } - $Text = preg_replace('/\[\&\;([#a-z0-9]+)\;\]/','&$1;',$Text); + $Text = preg_replace('/\[\&\;([#a-z0-9]+)\;\]/', '&$1;', $Text); // fix any escaped ampersands that may have been converted into links - $Text = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$Text); + $Text = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism", '<$1$2=$3&$4>', $Text); - $Text = preg_replace("/\<(.*?)(src|href)=\"[^zhfm#](.*?)\>/ism",'<$1$2="">',$Text); + $Text = preg_replace("/\<(.*?)(src|href)=\"[^zhfm#](.*?)\>/ism", '<$1$2="">', $Text); - $Text = bb_replace_images($Text,$saved_images); + $Text = bb_replace_images($Text, $saved_images); - call_hooks('bbcode',$Text); + call_hooks('bbcode', $Text); return $Text; } - -- cgit v1.2.3 From 37afc8184751556107a23910be094c80990901dd Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 8 Apr 2015 17:54:52 -0700 Subject: update features, allow sys account page deletion --- include/items.php | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'include') diff --git a/include/items.php b/include/items.php index 4b83ce3e3..1078103dc 100755 --- a/include/items.php +++ b/include/items.php @@ -3994,6 +3994,11 @@ function drop_item($id,$interactive = true,$stage = DROPITEM_NORMAL,$force = fal if(local_channel() && local_channel() == $item['uid']) $ok_to_delete = true; + // sys owned item, requires site admin to delete + $sys = get_sys_channel(); + if(is_site_admin() && $sys['channel_id'] == $item['uid']) + $ok_to_delete = true; + // author deletion $observer = $a->get_observer(); if($observer && $observer['xchan_hash'] && ($observer['xchan_hash'] === $item['author_xchan'])) -- cgit v1.2.3 From 7bec4b313a7a553e6df3e24289cf894f3d70a94e Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 8 Apr 2015 23:05:36 -0700 Subject: system channel always has allow_code privileges --- include/text.php | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) (limited to 'include') diff --git a/include/text.php b/include/text.php index fefe67c4e..1f383d8b3 100644 --- a/include/text.php +++ b/include/text.php @@ -101,12 +101,18 @@ function z_input_filter($channel_id,$s,$type = 'text/bbcode') { $r = q("select account_id, account_roles, channel_pageflags from account left join channel on channel_account_id = account_id where channel_id = %d limit 1", intval($channel_id) ); - if($r && (($r[0]['account_roles'] & ACCOUNT_ROLE_ALLOWCODE) || ($r[0]['channel_pageflags'] & PAGE_ALLOWCODE))) { - if(local_channel() && (get_account_id() == $r[0]['account_id'])) { + if($r) { + if($r[0]['channel_pageflags'] & PAGE_SYSTEM) { return $s; } + else { + if(($r[0]['account_roles'] & ACCOUNT_ROLE_ALLOWCODE) || ($r[0]['channel_pageflags'] & PAGE_ALLOWCODE)) { + if(local_channel() && (get_account_id() == $r[0]['account_id'])) { + return $s; + } + } + } } - if($type === 'text/html') return purify_html($s); @@ -1618,10 +1624,17 @@ function mimetype_select($channel_id, $current = 'text/bbcode') { ); if($r) { - if(($r[0]['account_roles'] & ACCOUNT_ROLE_ALLOWCODE) || ($r[0]['channel_pageflags'] & PAGE_ALLOWCODE)) { - if(local_channel() && get_account_id() == $r[0]['account_id']) - $x[] = 'application/x-php'; + if($r[0]['channel_pageflags'] & PAGE_SYSTEM) { + $x[] = 'application/x-php'; } + else { + if(($r[0]['account_roles'] & ACCOUNT_ROLE_ALLOWCODE) || ($r[0]['channel_pageflags'] & PAGE_ALLOWCODE)) { + if(local_channel() && get_account_id() == $r[0]['account_id']) { + $x[] = 'application/x-php'; + } + } + } + } $o = t('Page content type: '); -- cgit v1.2.3 From 4289c8adb2ae9e09a2ebce301c8c6869fd831246 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 8 Apr 2015 23:12:39 -0700 Subject: fix selector when sys channel active --- include/text.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'include') diff --git a/include/text.php b/include/text.php index 1f383d8b3..ef38c03d7 100644 --- a/include/text.php +++ b/include/text.php @@ -98,6 +98,13 @@ function z_input_filter($channel_id,$s,$type = 'text/bbcode') { return escape_tags($s); if($type == 'text/plain') return escape_tags($s); + + $a = get_app(); + if($a->is_sys) { + $sys = get_sys_channel(); + $channel_id = $sys['channel_id']; + } + $r = q("select account_id, account_roles, channel_pageflags from account left join channel on channel_account_id = account_id where channel_id = %d limit 1", intval($channel_id) ); @@ -1611,6 +1618,12 @@ function layout_select($channel_id, $current = '') { function mimetype_select($channel_id, $current = 'text/bbcode') { + $a = get_app(); + if($a->is_sys) { + $sys = get_sys_channel(); + $channel_id = $sys['channel_id']; + } + $x = array( 'text/bbcode', 'text/html', -- cgit v1.2.3 From 4fd80304a55d7edb1a558ff1fdcbff795fa12302 Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 8 Apr 2015 23:20:28 -0700 Subject: that didn't work out well - let's do this instead --- include/text.php | 43 ++++++++++++++++--------------------------- 1 file changed, 16 insertions(+), 27 deletions(-) (limited to 'include') diff --git a/include/text.php b/include/text.php index ef38c03d7..5666998f0 100644 --- a/include/text.php +++ b/include/text.php @@ -101,25 +101,20 @@ function z_input_filter($channel_id,$s,$type = 'text/bbcode') { $a = get_app(); if($a->is_sys) { - $sys = get_sys_channel(); - $channel_id = $sys['channel_id']; + return $s; } $r = q("select account_id, account_roles, channel_pageflags from account left join channel on channel_account_id = account_id where channel_id = %d limit 1", intval($channel_id) ); if($r) { - if($r[0]['channel_pageflags'] & PAGE_SYSTEM) { - return $s; - } - else { - if(($r[0]['account_roles'] & ACCOUNT_ROLE_ALLOWCODE) || ($r[0]['channel_pageflags'] & PAGE_ALLOWCODE)) { - if(local_channel() && (get_account_id() == $r[0]['account_id'])) { - return $s; - } + if(($r[0]['account_roles'] & ACCOUNT_ROLE_ALLOWCODE) || ($r[0]['channel_pageflags'] & PAGE_ALLOWCODE)) { + if(local_channel() && (get_account_id() == $r[0]['account_id'])) { + return $s; } } } + if($type === 'text/html') return purify_html($s); @@ -1618,12 +1613,6 @@ function layout_select($channel_id, $current = '') { function mimetype_select($channel_id, $current = 'text/bbcode') { - $a = get_app(); - if($a->is_sys) { - $sys = get_sys_channel(); - $channel_id = $sys['channel_id']; - } - $x = array( 'text/bbcode', 'text/html', @@ -1631,23 +1620,23 @@ function mimetype_select($channel_id, $current = 'text/bbcode') { 'text/plain' ); - $r = q("select account_id, account_roles, channel_pageflags from account left join channel on account_id = channel_account_id where - channel_id = %d limit 1", - intval($channel_id) - ); + $a = get_app(); + if($a->is_sys) { + $x[] = 'application/x-php'; + } + else { + $r = q("select account_id, account_roles, channel_pageflags from account left join channel on account_id = channel_account_id where + channel_id = %d limit 1", + intval($channel_id) + ); - if($r) { - if($r[0]['channel_pageflags'] & PAGE_SYSTEM) { - $x[] = 'application/x-php'; - } - else { + if($r) { if(($r[0]['account_roles'] & ACCOUNT_ROLE_ALLOWCODE) || ($r[0]['channel_pageflags'] & PAGE_ALLOWCODE)) { if(local_channel() && get_account_id() == $r[0]['account_id']) { $x[] = 'application/x-php'; } } - } - + } } $o = t('Page content type: '); -- cgit v1.2.3 From 7e7678364b9e89337612d7879e7f5cbb0792b35b Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Thu, 9 Apr 2015 10:53:37 +0200 Subject: make jRange behave again --- include/widgets.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/widgets.php b/include/widgets.php index 243c4a25e..e84c029d2 100644 --- a/include/widgets.php +++ b/include/widgets.php @@ -431,7 +431,7 @@ function widget_affinity($arr) { '$coworkers' => t('Co-workers'), '$oldfriends' => t('Former Friends'), '$acquaintances' => t('Acquaintances'), - '$world' => t('Everybody') + '$world' => t('All') )); $arr = array('html' => $x); call_hooks('main_slider',$arr); @@ -968,4 +968,4 @@ function widget_pubsites() { if(get_app()->poi) return; return ''; -} \ No newline at end of file +} -- cgit v1.2.3 From fdd6508019ebc369e3904a0637c98bf4727e76f3 Mon Sep 17 00:00:00 2001 From: Klaus Weidenbach Date: Fri, 10 Apr 2015 00:28:23 +0200 Subject: Some documentation and whitespaces at line endings. --- include/items.php | 391 ++++++++++++++++++++++---------------- include/zot.php | 548 ++++++++++++++++++++++++++++++++---------------------- 2 files changed, 557 insertions(+), 382 deletions(-) (limited to 'include') diff --git a/include/items.php b/include/items.php index 1078103dc..e08aab85a 100755 --- a/include/items.php +++ b/include/items.php @@ -3,6 +3,9 @@ * @file include/items.php */ +/** @todo deprecated in newer SabreDAV releases Sabre\HTTP\URLUtil */ +use Sabre\DAV\URLUtil; + require_once('include/bbcode.php'); require_once('include/oembed.php'); require_once('include/crypto.php'); @@ -34,9 +37,9 @@ function collect_recipients($item, &$private_envelope) { $recipients = array_unique(array_merge($allow_people,$allow_groups)); - // if you specifically deny somebody but haven't allowed anybody, we'll allow everybody in your + // if you specifically deny somebody but haven't allowed anybody, we'll allow everybody in your // address book minus the denied connections. The post is still private and can't be seen publicly - // as that would allow the denied person to see the post by logging out. + // as that would allow the denied person to see the post by logging out. if((! $item['allow_cid']) && (! $item['allow_gid'])) { $r = q("select * from abook where abook_channel = %d and not (abook_flags & %d)>0 ", @@ -66,12 +69,12 @@ function collect_recipients($item, &$private_envelope) { } else { - // if the post is marked private but there are no recipients and public_policy/scope = self, + // if the post is marked private but there are no recipients and public_policy/scope = self, // only add the author and owner as recipients. The ACL for the post may live on the hub of // a different clone. We need to get the post to that hub. // The post may be private by virtue of not being visible to anybody on the internet, - // but there are no envelope recipients, so set this to false. Delivery is controlled + // but there are no envelope recipients, so set this to false. Delivery is controlled // by the directives in $item['public_policy']. $private_envelope = false; @@ -117,11 +120,11 @@ function collect_recipients($item, &$private_envelope) { $recipients = check_list_permissions($item['uid'],$recipients,'view_stream'); - // remove any upstream recipients from our list. + // remove any upstream recipients from our list. // If it is ourself we'll add it back in a second. - // This should prevent complex delivery chains from getting overly complex by not + // This should prevent complex delivery chains from getting overly complex by not // sending to anybody who is on our list of those who sent it to us. - + if($item['route']) { $route = explode(',',$item['route']); if(count($route)) { @@ -131,7 +134,7 @@ function collect_recipients($item, &$private_envelope) { } // add ourself just in case we have nomadic clones that need to get a copy. - + $recipients[] = $item['author_xchan']; if($item['owner_xchan'] != $item['author_xchan']) $recipients[] = $item['owner_xchan']; @@ -197,9 +200,9 @@ function comments_are_now_closed($item) { * sufficient privileges to comment. This will normally be called on a remote site where perm_is_allowed() * will not be suitable because the post owner does not have a local channel_id. * Generally we should look at the item - in particular the author['book_flags'] and see if ABOOK_FLAG_SELF is set. - * If it is, you should be able to use perm_is_allowed( ... 'post_comments'), and if it isn't you need to call + * If it is, you should be able to use perm_is_allowed( ... 'post_comments'), and if it isn't you need to call * can_comment_on_post() - * We also check the comments_closed date/time on the item if this is set. + * We also check the comments_closed date/time on the item if this is set. * * @param string $observer_xchan * @param array $item @@ -227,9 +230,9 @@ function can_comment_on_post($observer_xchan, $item) { return true; break; case 'public': - // We don't allow public comments yet, until a policy - // for dealing with anonymous comments is in place with - // a means to moderate comments. Until that time, return + // We don't allow public comments yet, until a policy + // for dealing with anonymous comments is in place with + // a means to moderate comments. Until that time, return // false. return false; break; @@ -256,9 +259,9 @@ function can_comment_on_post($observer_xchan, $item) { /** * @brief Adds $hash to the item source route specified by $iid. * - * $item['route'] contains a comma-separated list of xchans that sent the current message, + * $item['route'] contains a comma-separated list of xchans that sent the current message, * somewhat analogous to the * Received: header line in email. We can use this to perform - * loop detection and to avoid sending a particular item to any "upstream" sender (they + * loop detection and to avoid sending a particular item to any "upstream" sender (they * already have a copy because they sent it to us). * * Modifies item in the database pointed to by $iid. @@ -363,7 +366,7 @@ function red_zrlify_img_callback($matches) { * @brief Post an activity. * * In its simplest form one needs only to set $arr['body'] to post a note to the logged in channel's wall. - * Much more complex activities can be created. Permissions are checked. No filtering, tag expansion + * Much more complex activities can be created. Permissions are checked. No filtering, tag expansion * or other processing is performed. * * @param array $arr @@ -441,7 +444,7 @@ function post_activity_item($arr) { $arr['deny_cid'] = ((x($arr,'deny_cid')) ? $arr['deny_cid'] : $channel['channel_deny_cid']); $arr['deny_gid'] = ((x($arr,'deny_gid')) ? $arr['deny_gid'] : $channel['channel_deny_gid']); - $arr['comment_policy'] = map_scope($channel['channel_w_comment']); + $arr['comment_policy'] = map_scope($channel['channel_w_comment']); if ((! $arr['plink']) && ($arr['item_flags'] & ITEM_THREAD_TOP)) { $arr['plink'] = z_root() . '/channel/' . $channel['channel_address'] . '/?f=&mid=' . $arr['mid']; @@ -459,7 +462,7 @@ function post_activity_item($arr) { return $ret; } - $post = item_store($arr); + $post = item_store($arr); if($post['success']) $post_id = $post['item_id']; @@ -595,10 +598,17 @@ function get_feed_for($channel, $observer_hash, $params) { return $atom; } - +/** + * @brief + * + * @param array $item an associative array with + * * \b string \b verb + * @return string item's verb if set, default ACTIVITY_POST see boot.php + */ function construct_verb($item) { - if($item['verb']) + if ($item['verb']) return $item['verb']; + return ACTIVITY_POST; } @@ -632,7 +642,7 @@ function construct_activity_object($item) { } return ''; -} +} function construct_activity_target($item) { @@ -654,13 +664,15 @@ function construct_activity_target($item) { $r->link = str_replace('&','&', $r->link); $r->link = preg_replace('/\/','',$r->link); $o .= $r->link; - } + } else $o .= '' . "\r\n"; } if($r->content) $o .= '' . xmlify(bbcode($r->content)) . '' . "\r\n"; + $o .= '' . "\r\n"; + return $o; } @@ -674,7 +686,7 @@ function construct_activity_target($item) { * imported messages without including any embedded photos in the length. * * @param string $body - * @return string|unknown + * @return string */ function limit_body_size($body) { @@ -800,15 +812,15 @@ function get_item_elements($x) { if($arr['edited'] > datetime_convert()) $arr['edited'] = datetime_convert(); - $arr['expires'] = ((x($x,'expires') && $x['expires']) - ? datetime_convert('UTC','UTC',$x['expires']) + $arr['expires'] = ((x($x,'expires') && $x['expires']) + ? datetime_convert('UTC','UTC',$x['expires']) : NULL_DATE); - $arr['commented'] = ((x($x,'commented') && $x['commented']) - ? datetime_convert('UTC','UTC',$x['commented']) + $arr['commented'] = ((x($x,'commented') && $x['commented']) + ? datetime_convert('UTC','UTC',$x['commented']) : $arr['created']); - $arr['comments_closed'] = ((x($x,'comments_closed') && $x['comments_closed']) - ? datetime_convert('UTC','UTC',$x['comments_closed']) + $arr['comments_closed'] = ((x($x,'comments_closed') && $x['comments_closed']) + ? datetime_convert('UTC','UTC',$x['comments_closed']) : NULL_DATE); $arr['title'] = (($x['title']) ? htmlspecialchars($x['title'], ENT_COMPAT,'UTF-8',false) : ''); @@ -891,7 +903,7 @@ function get_item_elements($x) { // if it's a private post, encrypt it in the DB. // We have to do that here because we need to cleanse the input and prevent bad stuff from getting in, - // and we need plaintext to do that. + // and we need plaintext to do that. if(intval($arr['item_private'])) { @@ -918,7 +930,6 @@ function get_item_elements($x) { $arr['item_restrict'] = $x['item_restrict']; $arr['item_flags'] = $x['item_flags']; $arr['attach'] = $x['attach']; - } return $arr; @@ -949,10 +960,17 @@ function import_author_xchan($x) { return(($y) ? $y : false); } - +/** + * @brief Imports an author from Diaspora. + * + * @param array $x an associative array with + * * \e string \b address + * @return boolean|string false on error, otherwise xchan_hash of the new entry + */ function import_author_diaspora($x) { if(! $x['address']) return false; + if(discover_by_webbie($x['address'])) { $r = q("select xchan_hash from xchan where xchan_addr = '%s' limit 1", dbesc($x['address']) @@ -960,12 +978,20 @@ function import_author_diaspora($x) { if($r) return $r[0]['xchan_hash']; } + return false; } - +/** + * @brief Imports an author from a RSS feed. + * + * @param array $x an associative array with + * * \e string \b url + * * \e string \b name + * * \e string \b guid + * @return boolean|string + */ function import_author_rss($x) { - if(! $x['url']) return false; @@ -978,7 +1004,7 @@ function import_author_rss($x) { } $name = trim($x['name']); - $r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_url, xchan_name, xchan_network ) + $r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_url, xchan_name, xchan_network ) values ( '%s', '%s', '%s', '%s', '%s' )", dbesc($x['guid']), dbesc($x['guid']), @@ -986,13 +1012,15 @@ function import_author_rss($x) { dbesc(($name) ? $name : t('(Unknown)')), dbesc('rss') ); + if($r && $x['photo']) { $photos = import_profile_photo($x['photo']['src'],$x['url']); if($photos) { + /** @bug $arr is undefined in this SQL query */ $r = q("update xchan set xchan_photo_date = '%s', xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' where xchan_url = '%s' and xchan_network = 'rss'", - dbesc(datetime_convert('UTC','UTC',$arr['photo_updated'])), + dbesc(datetime_convert('UTC', 'UTC', $arr['photo_updated'])), dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), @@ -1022,7 +1050,7 @@ function import_author_unknown($x) { $name = trim($x['name']); - $r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_url, xchan_name, xchan_network ) + $r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_url, xchan_name, xchan_network ) values ( '%s', '%s', '%s', '%s', '%s' )", dbesc($x['url']), dbesc($x['url']), @@ -1035,6 +1063,7 @@ function import_author_unknown($x) { $photos = import_profile_photo($x['photo']['src'],$x['url']); if($photos) { + /** @bug $arr is undefined in this SQL query */ $r = q("update xchan set xchan_photo_date = '%s', xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' where xchan_url = '%s' and xchan_network = 'unknown'", dbesc(datetime_convert('UTC','UTC',$arr['photo_updated'])), dbesc($photos[0]), @@ -1082,7 +1111,7 @@ function encode_item($item,$mirror = false) { $item['body'] = crypto_unencapsulate(json_decode_plus($item['body']),$key); } - // If we're trying to backup an item so that it's recoverable or for export/imprt, + // If we're trying to backup an item so that it's recoverable or for export/imprt, // add all the attributes we need to recover it if($mirror) { @@ -1157,8 +1186,14 @@ function encode_item($item,$mirror = false) { return $x; } - -function map_scope($scope,$strip = false) { +/** + * @brief + * + * @param int $scope + * @param boolean $strip (optional) default false + * @return string + */ +function map_scope($scope, $strip = false) { switch($scope) { case 0: return 'self'; @@ -1180,6 +1215,12 @@ function map_scope($scope,$strip = false) { } } +/** + * @brief Returns a descriptive text for a given $scope. + * + * @param string $scope + * @return string translated string describing the scope + */ function translate_scope($scope) { if(! $scope || $scope === 'public') return t('Visible to anybody on the internet.'); @@ -1199,9 +1240,15 @@ function translate_scope($scope) { return t('Visible to specific connections.'); } +/** + * @brief + * + * @param array $xchan + * @return array an associative array + */ function encode_item_xchan($xchan) { - $ret = array(); + $ret['name'] = $xchan['xchan_name']; $ret['address'] = $xchan['xchan_addr']; $ret['url'] = (($xchan['hubloc_url']) ? $xchan['hubloc_url'] : $xchan['xchan_url']); @@ -1209,11 +1256,12 @@ function encode_item_xchan($xchan) { $ret['photo'] = array('mimetype' => $xchan['xchan_photo_mimetype'], 'src' => $xchan['xchan_photo_m']); $ret['guid'] = $xchan['xchan_guid']; $ret['guid_sig'] = $xchan['xchan_guid_sig']; + return $ret; } function encode_item_terms($terms) { - $ret = array(); + $ret = array(); $allowed_export_terms = array( TERM_UNKNOWN, TERM_HASHTAG, TERM_MENTION, TERM_CATEGORY, TERM_BOOKMARK ); @@ -1223,22 +1271,38 @@ function encode_item_terms($terms) { $ret[] = array('tag' => $term['term'], 'url' => $term['url'], 'type' => termtype($term['type'])); } } + return $ret; } +/** + * @brief + * + * @param int $t + * @return string + */ function termtype($t) { $types = array('unknown','hashtag','mention','category','private_category','file','search','thing','bookmark'); + return(($types[$t]) ? $types[$t] : 'unknown'); } +/** + * @brief + * + * @param array $t + * @return array|string empty string or array containing associative arrays with + * * \e string \b term + * * \e string \b url + * * \e int \b type + */ function decode_tags($t) { - if($t) { $ret = array(); foreach($t as $x) { $tag = array(); - $tag['term'] = htmlspecialchars($x['tag'], ENT_COMPAT,'UTF-8',false); - $tag['url'] = htmlspecialchars($x['url'], ENT_COMPAT,'UTF-8',false); + $tag['term'] = htmlspecialchars($x['tag'], ENT_COMPAT, 'UTF-8', false); + $tag['url'] = htmlspecialchars($x['url'], ENT_COMPAT, 'UTF-8', false); switch($x['type']) { case 'hashtag': $tag['type'] = TERM_HASHTAG; @@ -1271,6 +1335,7 @@ function decode_tags($t) { } $ret[] = $tag; } + return $ret; } @@ -1291,12 +1356,12 @@ function activity_sanitise($arr) { if(is_array($x)) $ret[$k] = activity_sanitise($x); else - $ret[$k] = htmlspecialchars($x, ENT_COMPAT,'UTF-8',false); + $ret[$k] = htmlspecialchars($x, ENT_COMPAT, 'UTF-8', false); } return $ret; } else { - return htmlspecialchars($arr, ENT_COMPAT,'UTF-8', false); + return htmlspecialchars($arr, ENT_COMPAT, 'UTF-8', false); } } @@ -1458,7 +1523,7 @@ function get_profile_elements($x) { $arr['postcode'] = (($x['postcode']) ? htmlspecialchars($x['postcode'], ENT_COMPAT,'UTF-8',false) : ''); $arr['country'] = (($x['country']) ? htmlspecialchars($x['country'], ENT_COMPAT,'UTF-8',false) : ''); - $arr['keywords'] = (($x['keywords'] && is_array($x['keywords'])) ? array_sanitise($x['keywords']) : array()); + $arr['keywords'] = (($x['keywords'] && is_array($x['keywords'])) ? array_sanitise($x['keywords']) : array()); return $arr; } @@ -1476,7 +1541,7 @@ function get_atom_elements($feed, $item, &$author) { $res = array(); $found_author = $item->get_author(); - if($found_author) { + if($found_author) { $author['author_name'] = unxmlify($found_author->get_name()); $author['author_link'] = unxmlify($found_author->get_link()); $author['author_is_feed'] = false; @@ -1604,7 +1669,7 @@ function get_atom_elements($feed, $item, &$author) { // make sure nobody is trying to sneak some html tags by us $res['body'] = notags(base64url_decode($res['body'])); - // We could probably turn these old Friendica bbcode bookmarks into bookmark tags but we'd have to + // We could probably turn these old Friendica bbcode bookmarks into bookmark tags but we'd have to // create a term table item for them. For now just make sure they stay as links. $res['body'] = preg_replace('/\[bookmark(.*?)\](.*?)\[\/bookmark\]/','[url$1]$2[/url]',$res['body']); @@ -1612,14 +1677,14 @@ function get_atom_elements($feed, $item, &$author) { $res['body'] = limit_body_size($res['body']); - // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust - // the content type. Our own network only emits text normally, though it might have been converted to + // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust + // the content type. Our own network only emits text normally, though it might have been converted to // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will // have to assume it is all html and needs to be purified. - // It doesn't matter all that much security wise - because before this content is used anywhere, we are - // going to escape any tags we find regardless, but this lets us import a limited subset of html from - // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining + // It doesn't matter all that much security wise - because before this content is used anywhere, we are + // going to escape any tags we find regardless, but this lets us import a limited subset of html from + // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining // html. if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) { @@ -1682,7 +1747,7 @@ function get_atom_elements($feed, $item, &$author) { $res['edited'] = unxmlify($rawedited[0]['data']); if((x($res,'edited')) && (! (x($res,'created')))) - $res['created'] = $res['edited']; + $res['created'] = $res['edited']; if(! $res['created']) $res['created'] = $item->get_date('c'); @@ -1783,7 +1848,6 @@ function get_atom_elements($feed, $item, &$author) { $attach = $item->get_enclosures(); if($attach) { $res['attach'] = array(); - $att_arr = array(); foreach($attach as $att) { $len = intval($att->get_length()); $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link())))); @@ -1812,7 +1876,7 @@ function get_atom_elements($feed, $item, &$author) { if($child[NAMESPACE_ACTIVITY]['obj_type'][0]['data']) { $res['obj_type'] = $child[NAMESPACE_ACTIVITY]['obj_type'][0]['data']; $obj['type'] = $child[NAMESPACE_ACTIVITY]['obj_type'][0]['data']; - } + } if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data']) $obj['id'] = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data']; if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) @@ -1906,14 +1970,22 @@ function encode_rel_links($links) { return xmlify($o); } -function item_store($arr,$allow_exec = false) { +/** + * @brief + * + * @param array $arr + * @param boolean $allow_exec (optional) default false + * @return array + * * \e boolean \b success + * * \e int \b item_id + */ +function item_store($arr, $allow_exec = false) { $d = array('item' => $arr, 'allow_exec' => $allow_exec); call_hooks('item_store', $d ); $arr = $d['item']; $allow_exec = $d['allow_exec']; - $ret = array('success' => false, 'item_id' => 0); if(! $arr['uid']) { @@ -1924,7 +1996,7 @@ function item_store($arr,$allow_exec = false) { //$uplinked_comment = false; - // If a page layout is provided, ensure it exists and belongs to us. + // If a page layout is provided, ensure it exists and belongs to us. if(array_key_exists('layout_mid',$arr) && $arr['layout_mid']) { $l = q("select item_restrict from item where mid = '%s' and uid = %d limit 1", @@ -1980,7 +2052,7 @@ function item_store($arr,$allow_exec = false) { } $allowed_languages = get_pconfig($arr['uid'],'system','allowed_languages'); - + if((is_array($allowed_languages)) && ($arr['lang']) && (! array_key_exists($arr['lang'],$allowed_languages))) { $translate = array('item' => $arr, 'from' => $arr['lang'], 'to' => $allowed_languages, 'translated' => false); call_hooks('item_translate', $translate); @@ -2075,7 +2147,7 @@ function item_store($arr,$allow_exec = false) { $comments_closed = $arr['comments_closed']; $arr['item_flags'] = $arr['item_flags'] | ITEM_THREAD_TOP; } - else { + else { // find the parent and snarf the item id and ACL's // and anything else we need to inherit @@ -2112,7 +2184,7 @@ function item_store($arr,$allow_exec = false) { if($r[0]['mid'] != $r[0]['parent_mid']) { $arr['parent_mid'] = $r[0]['parent_mid']; - $z = q("SELECT * FROM `item` WHERE `mid` = '%s' AND `parent_mid` = '%s' AND `uid` = %d + $z = q("SELECT * FROM `item` WHERE `mid` = '%s' AND `parent_mid` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1", dbesc($r[0]['parent_mid']), dbesc($r[0]['parent_mid']), @@ -2132,7 +2204,7 @@ function item_store($arr,$allow_exec = false) { $comments_closed = $r[0]['comments_closed']; if($r[0]['item_flags'] & ITEM_WALL) - $arr['item_flags'] = $arr['item_flags'] | ITEM_WALL; + $arr['item_flags'] = $arr['item_flags'] | ITEM_WALL; // An uplinked comment might arrive with a downstream owner. // Fix it. @@ -2149,7 +2221,7 @@ function item_store($arr,$allow_exec = false) { // Edge case. We host a public forum that was originally posted to privately. // The original author commented, but as this is a comment, the permissions - // weren't fixed up so it will still show the comment as private unless we fix it here. + // weren't fixed up so it will still show the comment as private unless we fix it here. if((intval($r[0]['item_flags']) & ITEM_UPLINK) && (! $r[0]['item_private'])) $arr['item_private'] = 0; @@ -2196,7 +2268,7 @@ function item_store($arr,$allow_exec = false) { if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid) || strlen($public_policy)) $private = 1; else - $private = $arr['item_private']; + $private = $arr['item_private']; $arr['parent'] = $parent_id; $arr['allow_cid'] = $allow_cid; @@ -2211,10 +2283,10 @@ function item_store($arr,$allow_exec = false) { dbesc_array($arr); - $r = dbq("INSERT INTO `item` (`" - . implode("`, `", array_keys($arr)) - . "`) VALUES ('" - . implode("', '", array_values($arr)) + $r = dbq("INSERT INTO `item` (`" + . implode("`, `", array_keys($arr)) + . "`) VALUES ('" + . implode("', '", array_values($arr)) . "')" ); // find the item we just created @@ -2289,7 +2361,7 @@ function item_store($arr,$allow_exec = false) { // If _creating_ a deleted item, don't propagate it further or send out notifications. // We need to store the item details just in case the delete came in before the original post, - // so that we have an item in the DB that's marked deleted and won't store a fresh post + // so that we have an item in the DB that's marked deleted and won't store a fresh post // that isn't aware that we were already told to delete it. if(! ($arr['item_restrict'] & ITEM_DELETED)) { @@ -2377,7 +2449,7 @@ function item_store_update($arr,$allow_exec = false) { } $allowed_languages = get_pconfig($arr['uid'],'system','allowed_languages'); - + if((is_array($allowed_languages)) && ($arr['lang']) && (! array_key_exists($arr['lang'],$allowed_languages))) { $translate = array('item' => $arr, 'from' => $arr['lang'], 'to' => $allowed_languages, 'translated' => false); call_hooks('item_translate', $translate); @@ -2491,7 +2563,7 @@ function item_store_update($arr,$allow_exec = false) { if($str) $str .= ","; $str .= " `" . $k . "` = '" . $v . "' "; - } + } $r = dbq("update `item` set " . $str . " where id = " . $orig_post_id ); @@ -2537,7 +2609,7 @@ function item_store_update($arr,$allow_exec = false) { function store_diaspora_comment_sig($datarray, $channel, $parent_item, $post_id, $walltowall = false) { - // We won't be able to sign Diaspora comments for authenticated visitors + // We won't be able to sign Diaspora comments for authenticated visitors // - we don't have their private key // since Diaspora doesn't handle edits we can only do this for the original text and not update it. @@ -2548,9 +2620,9 @@ function store_diaspora_comment_sig($datarray, $channel, $parent_item, $post_id, if($walltowall) { logger('wall to wall comment',LOGGER_DEBUG); // post will come across with the owner's identity. Throw a preamble onto the post to indicate the true author. - $signed_body = "\n\n" + $signed_body = "\n\n" . '![' . $datarray['author']['xchan_name'] . '](' . $datarray['author']['xchan_photo_m'] . ')' - . '[' . $datarray['author']['xchan_name'] . '](' . $datarray['author']['xchan_url'] . ')' . "\n\n" + . '[' . $datarray['author']['xchan_name'] . '](' . $datarray['author']['xchan_url'] . ')' . "\n\n" . $signed_body; } @@ -2573,7 +2645,7 @@ function store_diaspora_comment_sig($datarray, $channel, $parent_item, $post_id, $r = q("update item set diaspora_meta = '%s' where id = %d", dbesc(json_encode($y)), - intval($post_id) + intval($post_id) ); if(! $r) @@ -2697,7 +2769,7 @@ function tag_deliver($uid, $item_id) { $item = $i[0]; - if(($item['source_xchan']) && ($item['item_flags'] & ITEM_UPLINK) + if(($item['source_xchan']) && ($item['item_flags'] & ITEM_UPLINK) && ($item['item_flags'] & ITEM_THREAD_TOP) && ($item['edited'] != $item['created'])) { // this is an update (edit) to a post which was already processed by us and has a second delivery chain // Just start the second delivery chain to deliver the updated post @@ -2712,7 +2784,7 @@ function tag_deliver($uid, $item_id) { if (stristr($item['verb'],ACTIVITY_POKE)) { $poke_notify = true; - if(($item['obj_type'] == "") || ($item['obj_type'] !== ACTIVITY_OBJ_PERSON) || (! $item['object'])) + if(($item['obj_type'] == "") || ($item['obj_type'] !== ACTIVITY_OBJ_PERSON) || (! $item['object'])) $poke_notify = false; $obj = json_decode_plus($item['object']); @@ -2748,7 +2820,7 @@ function tag_deliver($uid, $item_id) { // We received a community tag activity for a post. // See if we are the owner of the parent item and have given permission to tag our posts. // If so tag the parent post. - + logger('tag_deliver: community tag activity received'); if(($item['owner_xchan'] === $u[0]['channel_hash']) && (! get_pconfig($u[0]['channel_id'],'system','blocktags'))) { @@ -2839,7 +2911,7 @@ function tag_deliver($uid, $item_id) { // At this point we've determined that the person receiving this post was mentioned in it or it is a union. // Now let's check if this mention was inside a reshare so we don't spam a forum - // If it's private we may have to unobscure it momentarily so that we can parse it. + // If it's private we may have to unobscure it momentarily so that we can parse it. $body = ''; @@ -2849,7 +2921,7 @@ function tag_deliver($uid, $item_id) { $body = crypto_unencapsulate(json_decode_plus($item['body']),$key); } else - $body = $item['body']; + $body = $item['body']; $body = preg_replace('/\[share(.*?)\[\/share\]/','',$body); @@ -2858,7 +2930,7 @@ function tag_deliver($uid, $item_id) { $matches = array(); $pattern = '/@\!?\[zrl\=' . preg_quote($term['url'],'/') . '\]' . preg_quote($term['term'],'/') . '\[\/zrl\]/'; - if(preg_match($pattern,$body,$matches)) + if(preg_match($pattern,$body,$matches)) $tagged = true; $pattern = '/@\!?\[zrl\=([^\]]*?)\]((?:.(?!\[zrl\=))*?)\+\[\/zrl\]/'; @@ -2927,9 +2999,9 @@ function tag_deliver($uid, $item_id) { // prevent delivery looping - only proceed // if the message originated elsewhere and is a top-level post - if(($item['item_flags'] & ITEM_WALL) - || ($item['item_flags'] & ITEM_ORIGIN) - || (!($item['item_flags'] & ITEM_THREAD_TOP)) + if(($item['item_flags'] & ITEM_WALL) + || ($item['item_flags'] & ITEM_ORIGIN) + || (!($item['item_flags'] & ITEM_THREAD_TOP)) || ($item['id'] != $item['parent'])) { logger('tag_deliver: item was local or a comment. rejected.'); return; @@ -2945,7 +3017,7 @@ function tag_deliver($uid, $item_id) { * We don't actually do anything except check that it matches the criteria. * This is so that the channel with tag_delivery enabled can receive the post even if they turn off * permissions for the sender to send their stream. tag_deliver() can't be called until the post is actually stored. - * By then it would be too late to reject it. + * By then it would be too late to reject it. */ function tgroup_check($uid,$item) { @@ -3045,8 +3117,8 @@ function tgroup_check($uid,$item) { /** * Sourced and tag-delivered posts are re-targetted for delivery to the connections of the channel - * receiving the post. This starts the second delivery chain, by resetting permissions and ensuring - * that ITEM_UPLINK is set on the parent post, and storing the current owner_xchan as the source_xchan. + * receiving the post. This starts the second delivery chain, by resetting permissions and ensuring + * that ITEM_UPLINK is set on the parent post, and storing the current owner_xchan as the source_xchan. * We'll become the new owner. If called without $parent, this *is* the parent post. * * @param array $channel @@ -3059,7 +3131,7 @@ function start_delivery_chain($channel, $item, $item_id, $parent) { // Change this copy of the post to a forum head message and deliver to all the tgroup members // also reset all the privacy bits to the forum default permissions - $private = (($channel['channel_allow_cid'] || $channel['channel_allow_gid'] + $private = (($channel['channel_allow_cid'] || $channel['channel_allow_gid'] || $channel['channel_deny_cid'] || $channel['channel_deny_gid']) ? 1 : 0); $new_public_policy = map_scope($channel['channel_r_stream'],true); @@ -3070,14 +3142,14 @@ function start_delivery_chain($channel, $item, $item_id, $parent) { $flag_bits = $item['item_flags'] | ITEM_WALL; // The message didn't necessarily originate on this site, (we'll honour it if it did), - // but the parent post of this thread will be reset as a local post, as it is the top of + // but the parent post of this thread will be reset as a local post, as it is the top of // this delivery chain and is coming from this site, regardless of where the original // originated. if(! $parent) $flag_bits = $flag_bits | ITEM_ORIGIN; - // unset the nocomment bit if it's there. + // unset the nocomment bit if it's there. if($flag_bits & ITEM_NOCOMMENT) $flag_bits = $flag_bits ^ ITEM_NOCOMMENT; @@ -3122,7 +3194,7 @@ function start_delivery_chain($channel, $item, $item_id, $parent) { } } - $r = q("update item set item_flags = %d, owner_xchan = '%s', allow_cid = '%s', allow_gid = '%s', + $r = q("update item set item_flags = %d, owner_xchan = '%s', allow_cid = '%s', allow_gid = '%s', deny_cid = '%s', deny_gid = '%s', item_private = %d, public_policy = '%s', comment_policy = '%s', title = '%s', body = '%s' where id = %d", intval($flag_bits), dbesc($channel['channel_hash']), @@ -3147,7 +3219,7 @@ function start_delivery_chain($channel, $item, $item_id, $parent) { /** * @brief * - * Checks to see if this item owner is referenced as a source for this channel and if the post + * Checks to see if this item owner is referenced as a source for this channel and if the post * matches the rules for inclusion in this channel. Returns true if we should create a second delivery * chain and false if none of the rules apply, or if the item is private. * @@ -3214,7 +3286,7 @@ function mail_store($arr) { return 0; } - if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false)) + if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false)) $arr['body'] = escape_tags($arr['body']); if(array_key_exists('attach',$arr) && is_array($arr['attach'])) @@ -3257,10 +3329,10 @@ function mail_store($arr) { logger('mail_store: ' . print_r($arr,true), LOGGER_DATA); - $r = dbq("INSERT INTO mail (`" - . implode("`, `", array_keys($arr)) - . "`) VALUES ('" - . implode("', '", array_values($arr)) + $r = dbq("INSERT INTO mail (`" + . implode("`, `", array_keys($arr)) + . "`) VALUES ('" + . implode("', '", array_values($arr)) . "')" ); // find the item we just created @@ -3309,7 +3381,7 @@ function mail_store($arr) { /** * @brief Process atom feed and update anything/everything we might need to update. * - * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or + * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or * might not) try and subscribe to it. * $datedir sorts in reverse order * @@ -3320,9 +3392,9 @@ function mail_store($arr) { * relationship. It is this person's stuff that is going to be updated. * @param $contact * The person who is sending us stuff. If not set, we MAY be processing a "follow" activity - * from an external network and MAY create an appropriate contact record. Otherwise, we MUST + * from an external network and MAY create an appropriate contact record. Otherwise, we MUST * have a contact record. - * @param int $pass by default ($pass = 0) we cannot guarantee that a parent item has been + * @param int $pass by default ($pass = 0) we cannot guarantee that a parent item has been * imported prior to its children being seen in the stream unless we are certain * of how the feed is arranged/ordered. * * With $pass = 1, we only pull parent items out of the stream. @@ -3426,14 +3498,14 @@ function consume_feed($xml, $importer, &$contact, $pass = 0) { $author['author_name'] = $contact['xchan_name']; if((! x($author,'author_link')) || ($author['author_is_feed'])) $author['author_link'] = $contact['xchan_url']; - if((! x($author,'author_photo'))|| ($author['author_is_feed'])) + if((! x($author,'author_photo'))|| ($author['author_is_feed'])) $author['author_photo'] = $contact['xchan_photo_m']; $datarray['author_xchan'] = ''; if($author['author_link'] != $contact['xchan_url']) { $x = import_author_unknown(array('name' => $author['author_name'],'url' => $author['author_link'],'photo' => array('src' => $author['author_photo']))); - if($x) + if($x) $datarray['author_xchan'] = $x; } if(! $datarray['author_xchan']) @@ -3449,8 +3521,8 @@ function consume_feed($xml, $importer, &$contact, $pass = 0) { // Update content if 'updated' changes if($r) { - if((x($datarray,'edited') !== false) - && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) { + if((x($datarray,'edited') !== false) + && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) { // do not accept (ignore) an earlier edit than one we currently have. if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited']) @@ -3483,7 +3555,7 @@ function consume_feed($xml, $importer, &$contact, $pass = 0) { $author['author_name'] = $contact['xchan_name']; if((! x($author,'author_link')) || ($author['author_is_feed'])) $author['author_link'] = $contact['xchan_url']; - if((! x($author,'author_photo'))|| ($author['author_is_feed'])) + if((! x($author,'author_photo'))|| ($author['author_is_feed'])) $author['author_photo'] = $contact['xchan_photo_m']; } @@ -3496,7 +3568,7 @@ function consume_feed($xml, $importer, &$contact, $pass = 0) { if($author['author_link'] != $contact['xchan_url']) { $x = import_author_unknown(array('name' => $author['author_name'],'url' => $author['author_link'],'photo' => array('src' => $author['author_photo']))); - if($x) + if($x) $datarray['author_xchan'] = $x; } if(! $datarray['author_xchan']) @@ -3512,8 +3584,8 @@ function consume_feed($xml, $importer, &$contact, $pass = 0) { // Update content if 'updated' changes if($r) { - if((x($datarray,'edited') !== false) - && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) { + if((x($datarray,'edited') !== false) + && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) { // do not accept (ignore) an earlier edit than one we currently have. if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited']) @@ -3535,7 +3607,7 @@ function consume_feed($xml, $importer, &$contact, $pass = 0) { $author['owner_avatar'] = $contact['thumb']; } - logger('consume_feed: author ' . print_r($author,true),LOGGER_DEBUG); + logger('consume_feed: author ' . print_r($author,true),LOGGER_DEBUG); logger('consume_feed: ' . print_r($datarray,true),LOGGER_DATA); @@ -3673,7 +3745,7 @@ function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) { // $mentioned = get_mentions($item,$tags); // if($mentioned) // $o .= $mentioned; - + call_hooks('atom_entry', $o); $o .= '' . "\r\n"; @@ -3719,7 +3791,7 @@ function fix_private_photos($s, $uid, $item = null, $cid = 0) { // Check to see if we should replace this photo link with an embedded image // 1. No need to do so if the photo is public // 2. If there's a contact-id provided, see if they're in the access list - // for the photo. If so, embed it. + // for the photo. If so, embed it. // 3. Otherwise, if we have an item, see if the item permissions match the photo // permissions, regardless of order but first check to see if they're an exact // match to save some processing overhead. @@ -3728,7 +3800,7 @@ function fix_private_photos($s, $uid, $item = null, $cid = 0) { if($cid) { $recips = enumerate_permissions($r[0]); if(in_array($cid, $recips)) { - $replace = true; + $replace = true; } } elseif($item) { @@ -3787,7 +3859,7 @@ function has_permissions($obj) { } function compare_permissions($obj1,$obj2) { - // first part is easy. Check that these are exactly the same. + // first part is easy. Check that these are exactly the same. if(($obj1['allow_cid'] == $obj2['allow_cid']) && ($obj1['allow_gid'] == $obj2['allow_gid']) && ($obj1['deny_cid'] == $obj2['deny_cid']) @@ -3882,10 +3954,10 @@ function item_expire($uid,$days) { $sql_extra = ((intval($expire_network_only)) ? " AND (item_flags & " . intval(ITEM_WALL) . ") = 0 " : ""); - $r = q("SELECT * FROM `item` - WHERE `uid` = %d - AND `created` < %s - INTERVAL %s - AND `id` = `parent` + $r = q("SELECT * FROM `item` + WHERE `uid` = %d + AND `created` < %s - INTERVAL %s + AND `id` = `parent` $sql_extra AND ( item_flags & %d ) = 0 AND ( item_restrict = 0 ) LIMIT $expire_limit ", @@ -3956,7 +4028,7 @@ function drop_items($items) { // Delete item with given item $id. $interactive means we're running interactively, and must check // permissions to carry out this act. If it is non-interactive, we are deleting something at the -// system's request and do not check permission. This is very important to know. +// system's request and do not check permission. This is very important to know. // Some deletion requests (those coming from remote sites) must be staged. // $stage = 0 => unstaged @@ -4006,7 +4078,7 @@ function drop_item($id,$interactive = true,$stage = DROPITEM_NORMAL,$force = fal if($ok_to_delete) { - // set the deleted flag immediately on this item just in case the + // set the deleted flag immediately on this item just in case the // hook calls a remote process which loops. We'll delete it properly in a second. $r = q("UPDATE item SET item_restrict = ( item_restrict | %d ) WHERE id = %d", @@ -4034,12 +4106,12 @@ function drop_item($id,$interactive = true,$stage = DROPITEM_NORMAL,$force = fal return 1; // send the notification upstream/downstream as the case may be - // only send notifications to others if this is the owner's wall item. + // only send notifications to others if this is the owner's wall item. - // This isn't optimal. We somehow need to pass to this function whether or not - // to call the notifier, or we need to call the notifier from the calling function. + // This isn't optimal. We somehow need to pass to this function whether or not + // to call the notifier, or we need to call the notifier from the calling function. // We'll rely on the undocumented behaviour that DROPITEM_PHASE1 is (hopefully) only - // set if we know we're going to send delete notifications out to others. + // set if we know we're going to send delete notifications out to others. if((($item['item_flags'] & ITEM_WALL) && ($stage != DROPITEM_PHASE2)) || ($stage == DROPITEM_PHASE1)) proc_run('php','include/notifier.php','drop',$notify_id); @@ -4093,7 +4165,7 @@ function delete_item_lowlevel($item, $stage = DROPITEM_NORMAL, $force = false) { case DROPITEM_NORMAL: default: if($linked_item && ! $force) { - $r = q("UPDATE item SET item_restrict = ( item_restrict | %d ), + $r = q("UPDATE item SET item_restrict = ( item_restrict | %d ), changed = '%s', edited = '%s' WHERE id = %d", intval(ITEM_HIDDEN), dbesc(datetime_convert()), @@ -4113,7 +4185,7 @@ function delete_item_lowlevel($item, $stage = DROPITEM_NORMAL, $force = false) { break; } - // immediately remove any undesired profile likes. + // immediately remove any undesired profile likes. q("delete from likes where iid = %d and channel_id = %d", intval($item['id']), @@ -4167,8 +4239,8 @@ function first_post_date($uid,$wall = false) { } /** - * modified posted_dates() {below} to arrange the list in years, which we'll eventually - * use to make a menu of years with collapsible sub-menus for the months instead of the + * modified posted_dates() {below} to arrange the list in years, which we'll eventually + * use to make a menu of years with collapsible sub-menus for the months instead of the * current flat list of all representative dates. * * @param int $uid @@ -4186,7 +4258,7 @@ function list_post_dates($uid, $wall, $mindate) { if(! $dthen) return array(); - // If it's near the end of a long month, backup to the 28th so that in + // If it's near the end of a long month, backup to the 28th so that in // consecutive loops we'll always get a whole month difference. if(intval(substr($dnow,8)) > 28) @@ -4221,7 +4293,7 @@ function posted_dates($uid,$wall) { if(! $dthen) return array(); - // If it's near the end of a long month, backup to the 28th so that in + // If it's near the end of a long month, backup to the 28th so that in // consecutive loops we'll always get a whole month difference. if(intval(substr($dnow,8)) > 28) @@ -4248,7 +4320,7 @@ function posted_dates($uid,$wall) { function fetch_post_tags($items,$link = false) { $tag_finder = array(); - if($items) { + if($items) { foreach($items as $item) { if(is_array($item)) { if(array_key_exists('item_id',$item)) { @@ -4348,7 +4420,7 @@ function zot_feed($uid,$observer_xchan,$arr) { /** @FIXME fix this part for PostgreSQL */ - if(ACTIVE_DBTYPE == DBTYPE_POSTGRES) { + if(ACTIVE_DBTYPE == DBTYPE_POSTGRES) { return array(); } @@ -4356,8 +4428,8 @@ function zot_feed($uid,$observer_xchan,$arr) { require_once('include/security.php'); $r = q("SELECT parent, created from item WHERE uid != %d - AND item_private = 0 AND item_restrict = 0 AND uid in (" . stream_perms_api_uids(PERMS_PUBLIC,10,1) . ") - AND (item_flags & %d) > 0 + AND item_private = 0 AND item_restrict = 0 AND uid in (" . stream_perms_api_uids(PERMS_PUBLIC,10,1) . ") + AND (item_flags & %d) > 0 $sql_extra GROUP BY parent ORDER BY created ASC $limit", intval($uid), intval(ITEM_WALL) @@ -4366,7 +4438,7 @@ function zot_feed($uid,$observer_xchan,$arr) { else { $r = q("SELECT parent, created from item WHERE uid = %d AND item_restrict = 0 - AND (item_flags & %d) > 0 + AND (item_flags & %d) > 0 $sql_extra GROUP BY parent ORDER BY created ASC $limit", intval($uid), intval(ITEM_WALL) @@ -4376,8 +4448,8 @@ function zot_feed($uid,$observer_xchan,$arr) { if($r) { $parents_str = ids_to_querystr($r,'parent'); $sys_query = ((is_sys_channel($uid)) ? $sql_extra : ''); - - $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` + + $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` WHERE `item`.`item_restrict` = 0 AND `item`.`parent` IN ( %s ) $sys_query ", dbesc($parents_str) @@ -4458,7 +4530,7 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C $contact_str .= "'" . $c['xchan'] . "'"; } } else { - $contact_str = ' 0 '; + $contact_str = ' 0 '; $result['message'] = t('Collection is empty.'); return $result; } @@ -4496,12 +4568,12 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C } if($arr['search']) { - if(strpos($arr['search'],'#') === 0) - $sql_extra .= term_query('item',substr($arr['search'],1),TERM_HASHTAG); - else - $sql_extra .= sprintf(" AND item.body like '%s' ", - dbesc(protect_sprintf('%' . $arr['search'] . '%')) - ); + if(strpos($arr['search'],'#') === 0) + $sql_extra .= term_query('item',substr($arr['search'],1),TERM_HASHTAG); + else + $sql_extra .= sprintf(" AND item.body like '%s' ", + dbesc(protect_sprintf('%' . $arr['search'] . '%')) + ); } if (strlen($arr['file'])) { @@ -4542,6 +4614,7 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C $sql_nets .= "( abook.abook_closeness >= " . intval($arr['cmin']) . " "; $sql_nets .= " AND abook.abook_closeness <= " . intval($arr['cmax']) . " ) "; + /** @fixme dead code, $cmax is undefined */ if ($cmax == 99) $sql_nets .= " OR abook.abook_closeness IS NULL ) "; } @@ -4564,12 +4637,12 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C if ($arr['nouveau'] && ($client_mode & CLIENT_MODE_LOAD) && $channel) { // "New Item View" - show all items unthreaded in reverse created date order - $items = q("SELECT item.*, item.id AS item_id FROM item - WHERE $item_uids $item_restrict - $simple_update - $sql_extra $sql_nets - ORDER BY item.received DESC $pager_sql " - ); + $items = q("SELECT item.*, item.id AS item_id FROM item + WHERE $item_uids $item_restrict + $simple_update + $sql_extra $sql_nets + ORDER BY item.received DESC $pager_sql" + ); require_once('include/items.php'); @@ -4598,7 +4671,7 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C ORDER BY item.$ordering DESC $pager_sql ", intval(ABOOK_FLAG_BLOCKED) ); - + } else { // update @@ -4629,7 +4702,7 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C dbesc($parents_str) ); - $second = dba_timer(); + //$second = dba_timer(); xchan_query($items); @@ -4673,9 +4746,9 @@ function update_remote_id($channel,$post_id,$webpage,$pagetitle,$namespace,$remo if($page_type) { - // store page info as an alternate message_id so we can access it via + // store page info as an alternate message_id so we can access it via // https://sitename/page/$channelname/$pagetitle - // if no pagetitle was given or it couldn't be transliterated into a url, use the first + // if no pagetitle was given or it couldn't be transliterated into a url, use the first // sixteen bytes of the mid - which makes the link portable and not quite as daunting // as the entire mid. If it were the post_id the link would be less portable. @@ -4750,9 +4823,9 @@ function set_linkified_perms($linkified, &$str_contact_allow, &$str_group_allow, if ($first_access_tag && (! get_pconfig($profile_uid,'system','no_private_mention_acl_override'))) { // This is a tough call, hence configurable. The issue is that one can type in a @!privacy mention - // and also have a default ACL (perhaps from viewing a collection) and could be suprised that the + // and also have a default ACL (perhaps from viewing a collection) and could be suprised that the // privacy mention wasn't the only recipient. So the default is to wipe out the existing ACL if a - // private mention is found. This can be over-ridden if you wish private mentions to be in + // private mention is found. This can be over-ridden if you wish private mentions to be in // addition to the current ACL settings. $str_contact_allow = ''; @@ -4775,7 +4848,7 @@ function set_linkified_perms($linkified, &$str_contact_allow, &$str_group_allow, * We can't trust ITEM_ORIGIN to tell us if this is a local comment * which needs to be relayed, because it was misconfigured at one point for several * months and set for some remote items (in alternate delivery chains). This could - * cause looping, so use this hackish but accurate method. + * cause looping, so use this hackish but accurate method. * * @param array $item * @return boolean diff --git a/include/zot.php b/include/zot.php index 28a2e8957..3c7413b5c 100644 --- a/include/zot.php +++ b/include/zot.php @@ -32,6 +32,7 @@ require_once('include/hubloc.php'); */ function zot_new_uid($channel_nick) { $rawstr = z_root() . '/' . $channel_nick . '.' . mt_rand(); + return(base64url_encode(hash('whirlpool', $rawstr, true), true)); } @@ -40,8 +41,9 @@ function zot_new_uid($channel_nick) { * * Generates a portable hash identifier for the channel identified by $guid and * signed with $guid_sig. - * This ID is portable across the network but MUST be calculated locally by - * verifying the signature and can not be trusted as an identity. + * + * @note This ID is portable across the network but MUST be calculated locally + * by verifying the signature and can not be trusted as an identity. * * @param string $guid * @param string $guid_sig @@ -116,7 +118,7 @@ function zot_build_packet($channel, $type = 'notify', $recipients = null, $remot 'guid_sig' => base64url_encode(rsa_sign($channel['channel_guid'],$channel['channel_prvkey'])), 'url' => z_root(), 'url_sig' => base64url_encode(rsa_sign(z_root(),$channel['channel_prvkey'])) - ), + ), 'callback' => '/post', 'version' => ZOT_REVISION ); @@ -124,11 +126,12 @@ function zot_build_packet($channel, $type = 'notify', $recipients = null, $remot if ($recipients) { for ($x = 0; $x < count($recipients); $x ++) unset($recipients[$x]['hash']); + $data['recipients'] = $recipients; } if ($secret) { - $data['secret'] = $secret; + $data['secret'] = $secret; $data['secret_sig'] = base64url_encode(rsa_sign($secret,$channel['channel_prvkey'])); } @@ -195,7 +198,7 @@ function zot_finger($webbie, $channel = null, $autofallback = true) { // The webbie we were called with may not, so it might not be found // unless we query for hubloc_addr instead of xchan_addr - $r = q("select xchan.*, hubloc.* from xchan + $r = q("select xchan.*, hubloc.* from xchan left join hubloc on xchan_hash = hubloc_hash where xchan_addr = '%s' and (hubloc_flags & %d) > 0 limit 1", dbesc($xchan_addr), @@ -257,19 +260,19 @@ function zot_finger($webbie, $channel = null, $autofallback = true) { * @brief Refreshes after permission changed or friending, etc. * * zot_refresh is typically invoked when somebody has changed permissions of a channel and they are notified - * to fetch new permissions via a finger/discovery operation. This may result in a new connection - * (abook entry) being added to a local channel and it may result in auto-permissions being granted. + * to fetch new permissions via a finger/discovery operation. This may result in a new connection + * (abook entry) being added to a local channel and it may result in auto-permissions being granted. * * Friending in zot is accomplished by sending a refresh packet to a specific channel which indicates a * permission change has been made by the sender which affects the target channel. The hub controlling * the target channel does targetted discovery (a zot-finger request requesting permissions for the local * channel). These are decoded here, and if necessary and abook structure (addressbook) is created to store - * the permissions assigned to this channel. + * the permissions assigned to this channel. * - * Initially these abook structures are created with a 'pending' flag, so that no reverse permissions are - * implied until this is approved by the owner channel. A channel can also auto-populate permissions in + * Initially these abook structures are created with a 'pending' flag, so that no reverse permissions are + * implied until this is approved by the owner channel. A channel can also auto-populate permissions in * return and send back a refresh packet of its own. This is used by forum and group communication channels - * so that friending and membership in the channel's "club" is automatic. + * so that friending and membership in the channel's "club" is automatic. * * @param array $them => xchan structure of sender * @param array $channel => local channel structure of target recipient, required for "friending" operations @@ -376,7 +379,7 @@ function zot_refresh($them, $channel = null, $force = false) { if($k === 'connected') { $connected_set = intval($v); continue; - } + } if(($v) && (array_key_exists($k,$global_perms))) { $their_perms = $their_perms | intval($global_perms[$k][1]); } @@ -389,7 +392,7 @@ function zot_refresh($them, $channel = null, $force = false) { intval(ABOOK_FLAG_SELF) ); - if(array_key_exists('profile',$j) && array_key_exists('next_birthday',$j['profile'])) { + if(array_key_exists('profile',$j) && array_key_exists('next_birthday',$j['profile'])) { $next_birthday = datetime_convert('UTC','UTC',$j['profile']['next_birthday']); } else { @@ -398,9 +401,9 @@ function zot_refresh($them, $channel = null, $force = false) { if($r) { - // if the dob is the same as what we have stored (disregarding the year), keep the one + // if the dob is the same as what we have stored (disregarding the year), keep the one // we have as we may have updated the year after sending a notification; and resetting - // to the one we just received would cause us to create duplicated events. + // to the one we just received would cause us to create duplicated events. if(substr($r[0]['abook_dob'],5) == substr($next_birthday,5)) $next_birthday = $r[0]['abook_dob']; @@ -408,7 +411,7 @@ function zot_refresh($them, $channel = null, $force = false) { $current_abook_connected = (($r[0]['abook_flags'] & ABOOK_FLAG_UNCONNECTED) ? 0 : 1); $y = q("update abook set abook_their_perms = %d, abook_dob = '%s' - where abook_xchan = '%s' and abook_channel = %d + where abook_xchan = '%s' and abook_channel = %d and not (abook_flags & %d) > 0 ", intval($their_perms), dbescdate($next_birthday), @@ -420,11 +423,11 @@ function zot_refresh($them, $channel = null, $force = false) { // if(($connected_set === 0 || $connected_set === 1) && ($connected_set !== $current_abook_unconnected)) { // if they are in your address book but you aren't in theirs, and/or this does not - // match your current connected state setting, toggle it. + // match your current connected state setting, toggle it. /** @FIXME uncoverted to postgres */ /** @FIXME when this was enabled, all contacts became unconnected. Currently disabled intentionally */ // $y1 = q("update abook set abook_flags = (abook_flags ^ %d) -// where abook_xchan = '%s' and abook_channel = %d +// where abook_xchan = '%s' and abook_channel = %d // and not (abook_flags & %d) limit 1", // intval(ABOOK_FLAG_UNCONNECTED), // dbesc($x['hash']), @@ -438,7 +441,7 @@ function zot_refresh($them, $channel = null, $force = false) { else { // if we were just granted read stream permission and didn't have it before, try to pull in some posts if((! ($r[0]['abook_their_perms'] & PERMS_R_STREAM)) && ($their_perms & PERMS_R_STREAM)) - proc_run('php','include/onepoll.php',$r[0]['abook_id']); + proc_run('php','include/onepoll.php',$r[0]['abook_id']); } } else { @@ -450,7 +453,7 @@ function zot_refresh($them, $channel = null, $force = false) { } if(! $default_perms) $default_perms = intval(get_pconfig($channel['channel_id'],'system','autoperms')); - + // Keep original perms to check if we need to notify them $previous_perms = get_all_perms($channel['channel_id'],$x['hash']); @@ -493,23 +496,24 @@ function zot_refresh($them, $channel = null, $force = false) { if($new_connection) { require_once('include/enotify.php'); notification(array( - 'type' => NOTIFY_INTRO, - 'from_xchan' => $x['hash'], - 'to_xchan' => $channel['channel_hash'], - 'link' => z_root() . '/connedit/' . $new_connection[0]['abook_id'], + 'type' => NOTIFY_INTRO, + 'from_xchan' => $x['hash'], + 'to_xchan' => $channel['channel_hash'], + 'link' => z_root() . '/connedit/' . $new_connection[0]['abook_id'], )); } if($new_connection && ($their_perms & PERMS_R_STREAM)) { if(($channel['channel_w_stream'] & PERMS_PENDING) || (! ($new_connection[0]['abook_flags'] & ABOOK_FLAG_PENDING)) ) - proc_run('php','include/onepoll.php',$new_connection[0]['abook_id']); + proc_run('php','include/onepoll.php',$new_connection[0]['abook_id']); } } } } return true; } + return false; } @@ -521,7 +525,7 @@ function zot_refresh($them, $channel = null, $force = false) { * This function looks these up to see if the channel is known and therefore * previously verified. If not, we will need to verify it. * - * @param array $arr an assoziative array which must contain: + * @param array $arr an associative array which must contain: * * \e string \b guid => guid of conversant * * \e string \b guid_sig => guid signed with conversant's private key * * \e string \b url => URL of the origination hub of this communication @@ -549,8 +553,8 @@ function zot_gethub($arr) { return null; } - $r = q("select * from hubloc - where hubloc_guid = '%s' and hubloc_guid_sig = '%s' + $r = q("select * from hubloc + where hubloc_guid = '%s' and hubloc_guid_sig = '%s' and hubloc_url = '%s' and hubloc_url_sig = '%s' limit 1", dbesc($arr['guid']), @@ -564,24 +568,25 @@ function zot_gethub($arr) { } } logger('zot_gethub: not found: ' . print_r($arr,true), LOGGER_DEBUG); + return null; } /** * @brief Registers an unknown hup. * - * A communication has been received which has an unknown (to us) sender. + * A communication has been received which has an unknown (to us) sender. * Perform discovery based on our calculated hash of the sender at the * origination address. This will fetch the discovery packet of the sender, * which contains the public key we need to verify our guid and url signatures. * - * @param array $arr an assoziative array which must contain: + * @param array $arr an associative array which must contain: * * \e string \b guid => guid of conversant * * \e string \b guid_sig => guid signed with conversant's private key * * \e string \b url => URL of the origination hub of this communication * * \e string \b url_sig => URL signed with conversant's private key * - * @returns array an assoziative array with: + * @returns array an associative array with * * \b success boolean true or false * * \b message (optional) error string only if success is false */ @@ -604,8 +609,8 @@ function zot_register_hub($arr) { if($x['success']) { $record = json_decode($x['body'],true); - /* - * We now have a key - only continue registration if our signatures are valid + /* + * We now have a key - only continue registration if our signatures are valid * AND the guid and guid sig in the returned packet match those provided in * our current communication. */ @@ -621,7 +626,7 @@ function zot_register_hub($arr) { } else { logger('zot_register_hub: failure to verify returned packet.'); - } + } } } @@ -639,7 +644,7 @@ function zot_register_hub($arr) { * this typically occurs once a month for each channel as part of a scheduled ping to notify the directory * that the channel still exists * @param array $ud_arr - * If set [typically by update_directory_entry()] indicates a specific update table row and more particularly + * If set [typically by update_directory_entry()] indicates a specific update table row and more particularly * contains a particular address (ud_addr) which needs to be updated in that table. * * @return associative array @@ -651,7 +656,7 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { call_hooks('import_xchan', $arr); $ret = array('success' => false); - $dirmode = intval(get_config('system','directory_mode')); + $dirmode = intval(get_config('system','directory_mode')); $changed = false; $what = ''; @@ -697,7 +702,7 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { // if we import an entry from a site that's not ours and either or both of us is off the grid - hide the entry. /** @TODO: check if we're the same directory realm, which would mean we are allowed to see it */ - $dirmode = get_config('system','directory_mode'); + $dirmode = get_config('system','directory_mode'); if((($arr['site']['directory_mode'] === 'standalone') || ($dirmode & DIRECTORY_MODE_STANDALONE)) && ($arr['site']['url'] != z_root())) $arr['searchable'] = false; @@ -725,14 +730,14 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { if($pubforum_changed) $new_flags = $r[0]['xchan_flags'] ^ XCHAN_FLAGS_PUBFORUM; - if(($r[0]['xchan_name_date'] != $arr['name_updated']) - || ($r[0]['xchan_connurl'] != $arr['connections_url']) + if(($r[0]['xchan_name_date'] != $arr['name_updated']) + || ($r[0]['xchan_connurl'] != $arr['connections_url']) || ($r[0]['xchan_flags'] != $new_flags) || ($r[0]['xchan_addr'] != $arr['address']) || ($r[0]['xchan_follow'] != $arr['follow_url']) - || ($r[0]['xchan_connpage'] != $arr['connect_url']) + || ($r[0]['xchan_connpage'] != $arr['connect_url']) || ($r[0]['xchan_url'] != $arr['url'])) { - $r = q("update xchan set xchan_name = '%s', xchan_name_date = '%s', xchan_connurl = '%s', xchan_follow = '%s', + $r = q("update xchan set xchan_name = '%s', xchan_name_date = '%s', xchan_connurl = '%s', xchan_follow = '%s', xchan_connpage = '%s', xchan_flags = %d, xchan_addr = '%s', xchan_url = '%s' where xchan_hash = '%s'", dbesc(($arr['name']) ? $arr['name'] : '-'), @@ -754,8 +759,9 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { } else { $import_photos = true; - if((($arr['site']['directory_mode'] === 'standalone') || ($dirmode & DIRECTORY_MODE_STANDALONE)) -&& ($arr['site']['url'] != z_root())) + if((($arr['site']['directory_mode'] === 'standalone') + || ($dirmode & DIRECTORY_MODE_STANDALONE)) + && ($arr['site']['url'] != z_root())) $arr['searchable'] = false; $hidden = (1 - intval($arr['searchable'])); @@ -822,7 +828,7 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { if ($photos) { if ($photos[4]) { // importing the photo failed somehow. Leave the photo_date alone so we can try again at a later date. - // This often happens when somebody joins the matrix with a bad cert. + // This often happens when somebody joins the matrix with a bad cert. $r = q("update xchan set xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' where xchan_hash = '%s'", dbesc($photos[0]), @@ -847,7 +853,7 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { } } - // what we are missing for true hub independence is for any changes in the primary hub to + // what we are missing for true hub independence is for any changes in the primary hub to // get reflected not only in the hublocs, but also to update the URLs and addr in the appropriate xchan $s = sync_locations($arr, $arr); @@ -870,19 +876,18 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { $other_realm = false; $realm = get_directory_realm(); - if(array_key_exists('site',$arr) - && array_key_exists('realm',$arr['site']) + if(array_key_exists('site',$arr) + && array_key_exists('realm',$arr['site']) && (strpos($arr['site']['realm'],$realm) === false)) $other_realm = true; if($dirmode != DIRECTORY_MODE_NORMAL) { // We're some kind of directory server. However we can only add directory information - // if the entry is in the same realm (or is a sub-realm). Sub-realms are denoted by - // including the parent realm in the name. e.g. 'RED_GLOBAL:foo' would allow an entry to + // if the entry is in the same realm (or is a sub-realm). Sub-realms are denoted by + // including the parent realm in the name. e.g. 'RED_GLOBAL:foo' would allow an entry to // be in directories for the local realm (foo) and also the RED_GLOBAL realm. - if(array_key_exists('profile',$arr) && is_array($arr['profile']) && (! $other_realm)) { $profile_changed = import_directory_profile($xchan_hash,$arr['profile'],$address,$ud_flags, 1); if($profile_changed) { @@ -910,7 +915,7 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { } if(($changed) || ($ud_flags == UPDATE_FLAGS_FORCED)) { - $guid = random_string() . '@' . get_app()->get_hostname(); + $guid = random_string() . '@' . get_app()->get_hostname(); update_modtime($xchan_hash,$guid,$address,$ud_flags); logger('import_xchan: changed: ' . $what,LOGGER_DEBUG); } @@ -987,7 +992,7 @@ function zot_process_response($hub, $arr, $outq) { * * We received a notification packet (in mod/post.php) that a message is waiting for us, and we've verified the sender. * Now send back a pickup message, using our message tracking ID ($arr['secret']), which we will sign with our site private key. - * The entire pickup message is encrypted with the remote site's public key. + * The entire pickup message is encrypted with the remote site's public key. * If everything checks out on the remote end, we will receive back a packet containing one or more messages, * which will be processed and delivered before this function ultimately returns. * @@ -1028,8 +1033,8 @@ function zot_fetch($arr) { /** * @brief Process incoming array of messages. - * - * Process an incoming array of messages which were obtained via pickup, and + * + * Process an incoming array of messages which were obtained via pickup, and * import, update, delete as directed. * * The message types handled here are 'activity' (e.g. posts), 'mail' , @@ -1051,14 +1056,14 @@ function zot_fetch($arr) { */ function zot_import($arr, $sender_url) { - $data = json_decode($arr['body'],true); + $data = json_decode($arr['body'], true); if(! $data) { logger('zot_import: empty body'); return array(); } - if(array_key_exists('iv',$data)) { + if(array_key_exists('iv', $data)) { $data = json_decode(crypto_unencapsulate($data,get_config('system','prvkey')),true); } @@ -1081,7 +1086,7 @@ function zot_import($arr, $sender_url) { logger('zot_import: notify: ' . print_r($i['notify'],true), LOGGER_DATA); - $hub = zot_gethub($i['notify']['sender']); + $hub = zot_gethub($i['notify']['sender']); if((! $hub) || ($hub['hubloc_url'] != $sender_url)) { logger('zot_import: potential forgery: wrong site for sender: ' . $sender_url . ' != ' . print_r($i['notify'],true)); continue; @@ -1117,16 +1122,16 @@ function zot_import($arr, $sender_url) { continue; } - // It's a specifically targetted post. If we were sent a public_scope hint (likely), - // get rid of it so that it doesn't get stored and cause trouble. + // It's a specifically targetted post. If we were sent a public_scope hint (likely), + // get rid of it so that it doesn't get stored and cause trouble. - if(($i) && is_array($i) && array_key_exists('message',$i) && is_array($i['message']) + if(($i) && is_array($i) && array_key_exists('message',$i) && is_array($i['message']) && $i['message']['type'] === 'activity' && array_key_exists('public_scope',$i['message'])) unset($i['message']['public_scope']); $deliveries = $r; - // We found somebody on this site that's in the recipient list. + // We found somebody on this site that's in the recipient list. } else { @@ -1151,12 +1156,12 @@ function zot_import($arr, $sender_url) { } // if the scope is anything but 'public' we're going to store it as private regardless - // of the private flag on the post. + // of the private flag on the post. - if($i['message'] && array_key_exists('public_scope',$i['message']) + if($i['message'] && array_key_exists('public_scope',$i['message']) && $i['message']['public_scope'] !== 'public') { - if(! array_key_exists('flags',$i['message'])) + if(! array_key_exists('flags',$i['message'])) $i['message']['flags'] = array(); if(! in_array('private',$i['message']['flags'])) $i['message']['flags'][] = 'private'; @@ -1223,7 +1228,7 @@ function zot_import($arr, $sender_url) { logger('Channel sync received: ' . print_r($arr,true), LOGGER_DATA); logger('Channel sync recipients: ' . print_r($deliveries,true), LOGGER_DATA); - + $result = process_channel_sync_delivery($i['notify']['sender'],$arr,$deliveries); } elseif($i['message']['type'] === 'location') { @@ -1231,7 +1236,7 @@ function zot_import($arr, $sender_url) { logger('Location message received: ' . print_r($arr,true), LOGGER_DATA); logger('Location message recipients: ' . print_r($deliveries,true), LOGGER_DATA); - + $result = process_location_delivery($i['notify']['sender'],$arr,$deliveries); } } @@ -1244,19 +1249,18 @@ function zot_import($arr, $sender_url) { return $return; } - -// A public message with no listed recipients can be delivered to anybody who -// has PERMS_NETWORK for that type of post, PERMS_AUTHED (in-network senders are -// by definition authenticated) or PERMS_SITE and is one the same -// site, or PERMS_SPECIFIC and the sender is a contact who is granted -// permissions via their connection permissions in the address book. -// Here we take a given message and construct a list of hashes of everybody -// on the site that we should try and deliver to. -// Some of these will be rejected, but this gives us a place to start. - /** * @brief * + * A public message with no listed recipients can be delivered to anybody who + * has PERMS_NETWORK for that type of post, PERMS_AUTHED (in-network senders are + * by definition authenticated) or PERMS_SITE and is one the same site, + * or PERMS_SPECIFIC and the sender is a contact who is granted permissions via + * their connection permissions in the address book. + * Here we take a given message and construct a list of hashes of everybody + * on the site that we should try and deliver to. + * Some of these will be rejected, but this gives us a place to start. + * * @param array $msg * @return NULL|array */ @@ -1281,24 +1285,24 @@ function public_recips($msg) { // notes (below) from when I got this section of code working. You would think that // we only have to find those with the requisite stream or comment permissions, // depending on whether this is a top-level post or a comment - but you would be wrong. - + // ... so public_recips and allowed_public_recips is working so much better - // than before, but was still not quite right. We seem to be getting all the right - // results for top-level posts now, but comments aren't getting through on channels + // than before, but was still not quite right. We seem to be getting all the right + // results for top-level posts now, but comments aren't getting through on channels // for which we've allowed them to send us their stream, but not comment on our posts. - // The reason is we were seeing if they could comment - and we only need to do that if + // The reason is we were seeing if they could comment - and we only need to do that if // we own the post. If they own the post, we only need to check if they can send us their stream. // if this is a comment and it wasn't sent by the post owner, check to see who is allowing them to comment. - // We should have one specific recipient and this step shouldn't be needed unless somebody stuffed up + // We should have one specific recipient and this step shouldn't be needed unless somebody stuffed up // their software. We may need this step to protect us from bad guys intentionally stuffing up their software. // If it is sent by the post owner, we don't need to do this. We only need to see who is receiving the // owner's stream (which was already set above) - as they control the comment permissions, not us. - // Note that by doing this we introduce another bug because some public forums have channel_w_stream + // Note that by doing this we introduce another bug because some public forums have channel_w_stream // permissions set to themselves only. We also need in this function to add these public forums to the - // public recipient list based on if they are tagged or not and have tag permissions. This is complicated - // by the fact that this activity doesn't have the public forum tag. It's the parent activity that + // public recipient list based on if they are tagged or not and have tag permissions. This is complicated + // by the fact that this activity doesn't have the public forum tag. It's the parent activity that // contains the tag. we'll solve that further below. if($msg['notify']['sender']['guid_sig'] != $msg['message']['owner']['guid_sig']) { @@ -1320,17 +1324,18 @@ function public_recips($msg) { // First find those channels who are accepting posts from anybody, or at least // something greater than just their connections. - if($msg['notify']['sender']['url'] === z_root()) - $sql = " where (( " . $col . " & " . intval(PERMS_NETWORK) . " ) > 0 - or ( " . $col . " & " . intval(PERMS_SITE) . " ) > 0 - or ( " . $col . " & " . intval(PERMS_PUBLIC) . ") > 0 + if($msg['notify']['sender']['url'] === z_root()) { + $sql = " where (( " . $col . " & " . intval(PERMS_NETWORK) . " ) > 0 + or ( " . $col . " & " . intval(PERMS_SITE) . " ) > 0 + or ( " . $col . " & " . intval(PERMS_PUBLIC) . ") > 0 or ( " . $col . " & " . intval(PERMS_AUTHED) . ") > 0 ) "; - else - $sql = " where (( " . $col . " & " . intval(PERMS_NETWORK) . " ) > 0 - or ( " . $col . " & " . intval(PERMS_PUBLIC) . ") > 0 + } else { + $sql = " where (( " . $col . " & " . intval(PERMS_NETWORK) . " ) > 0 + or ( " . $col . " & " . intval(PERMS_PUBLIC) . ") > 0 or ( " . $col . " & " . intval(PERMS_AUTHED) . ") > 0 ) "; + } - $r = q("select channel_hash as hash from channel $sql or channel_hash = '%s' + $r = q("select channel_hash as hash from channel $sql or channel_hash = '%s' and ( channel_pageflags & " . intval(PAGE_REMOVED) . " ) = 0 ", dbesc($msg['notify']['sender']['hash']) ); @@ -1341,13 +1346,13 @@ function public_recips($msg) { // Now we have to get a bit dirty. Find every channel that has the sender in their connections (abook) // and is allowing this sender at least at a high level. - $x = q("select channel_hash as hash from channel left join abook on abook_channel = channel_id - where abook_xchan = '%s' and ( channel_pageflags & " . intval(PAGE_REMOVED) . " ) = 0 - and (( " . $col . " & " . intval(PERMS_SPECIFIC) . " ) > 0 and ( abook_my_perms & " . intval($field) . " ) > 0 ) - OR ( " . $col . " & " . intval(PERMS_PENDING) . " ) > 0 + $x = q("select channel_hash as hash from channel left join abook on abook_channel = channel_id + where abook_xchan = '%s' and ( channel_pageflags & " . intval(PAGE_REMOVED) . " ) = 0 + and (( " . $col . " & " . intval(PERMS_SPECIFIC) . " ) > 0 and ( abook_my_perms & " . intval($field) . " ) > 0 ) + OR ( " . $col . " & " . intval(PERMS_PENDING) . " ) > 0 OR (( " . $col . " & " . intval(PERMS_CONTACTS) . " ) > 0 and ( abook_flags & " . intval(ABOOK_FLAG_PENDING) . " ) = 0 ) ", dbesc($msg['notify']['sender']['hash']) - ); + ); if(! $x) $x = array(); @@ -1386,7 +1391,7 @@ function public_recips($msg) { } else { // This is a comment. We need to find any parent with ITEM_UPLINK set. But in fact, let's just return - // everybody that stored a copy of the parent. This way we know we're covered. We'll check the + // everybody that stored a copy of the parent. This way we know we're covered. We'll check the // comment permissions when we deliver them. if($msg['message']['message_top']) { @@ -1395,7 +1400,7 @@ function public_recips($msg) { intval(ITEM_UPLINK) ); if($z) - $r = array_merge($r,$z); + $r = array_merge($r,$z); } } @@ -1404,7 +1409,7 @@ function public_recips($msg) { if($r) { $uniq = array(); - + foreach($r as $rr) { if(! in_array($rr['hash'],$uniq)) $uniq[] = $rr['hash']; @@ -1419,9 +1424,18 @@ function public_recips($msg) { return $r; } -// This is the second part of the above function. We'll find all the channels willing to accept public posts from us, -// then match them against the sender privacy scope and see who in that list that the sender is allowing. - +/** + * @brief + * + * This is the second part of public_recipes(). + * We'll find all the channels willing to accept public posts from us, then + * match them against the sender privacy scope and see who in that list that + * the sender is allowing. + * + * @see public_recipes() + * @param array $msg + * @return array + */ function allowed_public_recips($msg) { logger('allowed_public_recips: ' . print_r($msg,true),LOGGER_DATA); @@ -1431,8 +1445,8 @@ function allowed_public_recips($msg) { // Mail won't have a public scope. // in fact, it's doubtful mail will ever get here since it almost universally - // has a recipient, but in fact we don't require this, so it's technically - // possible to send mail to anybody that's listening. + // has a recipient, but in fact we don't require this, so it's technically + // possible to send mail to anybody that's listening. $recips = public_recips($msg); @@ -1483,12 +1497,21 @@ function allowed_public_recips($msg) { return array(); } - -function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$request = false) { +/** + * @brief + * + * @param array $sender + * @param array $arr + * @param array $deliveries + * @param boolean $relay + * @param boolean $public (optional) default false + * @param boolean $request (optional) default false + * @return array + */ +function process_delivery($sender, $arr, $deliveries, $relay, $public = false, $request = false) { $result = array(); - // We've validated the sender. Now make sure that the sender is the owner or author if(! $public) { @@ -1505,7 +1528,7 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque ); if(! $r) { - $result[] = array($d['hash'],'recipients not found'); + $result[] = array($d['hash'], 'recipients not found'); continue; } @@ -1513,7 +1536,7 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque // allow public postings to the sys channel regardless of permissions, but not // for comments travelling upstream. Wait and catch them on the way down. - // They may have been blocked by the owner. + // They may have been blocked by the owner. if(($channel['channel_pageflags'] & PAGE_SYSTEM) && (! $arr['item_private']) && (! $relay)) { $local_public = true; @@ -1557,7 +1580,7 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque // We are only going to accept comments from this sender if the comment has the same route as the top-level-post, // this is so that permissions mismatches between senders apply to the entire conversation // As a side effect we will also do a preliminary check that we have the top-level-post, otherwise - // processing it is pointless. + // processing it is pointless. $r = q("select route, id from item where mid = '%s' and uid = %d limit 1", dbesc($arr['parent_mid']), @@ -1566,21 +1589,21 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque if(! $r) { $result[] = array($d['hash'],'comment parent not found',$channel['channel_name'] . ' <' . $channel['channel_address'] . '@' . get_app()->get_hostname() . '>',$arr['mid']); - // We don't seem to have a copy of this conversation or at least the parent + // We don't seem to have a copy of this conversation or at least the parent // - so request a copy of the entire conversation to date. - // Don't do this if it's a relay post as we're the ones who are supposed to + // Don't do this if it's a relay post as we're the ones who are supposed to // have the copy and we don't want the request to loop. // Also don't do this if this comment came from a conversation request packet. // It's possible that comments are allowed but posting isn't and that could - // cause a conversation fetch loop. We can detect these packets since they are - // delivered via a 'notify' packet type that has a message_id element in the - // initial zot packet (just like the corresponding 'request' packet type which + // cause a conversation fetch loop. We can detect these packets since they are + // delivered via a 'notify' packet type that has a message_id element in the + // initial zot packet (just like the corresponding 'request' packet type which // makes the request). // We'll also check the send_stream permission - because if it isn't allowed, // the top level post is unlikely to be imported and - // this is just an exercise in futility. + // this is just an exercise in futility. - if((! $relay) && (! $request) && (! $local_public) + if((! $relay) && (! $request) && (! $local_public) && perm_is_allowed($channel['channel_id'],$sender['hash'],'send_stream')) { proc_run('php', 'include/notifier.php', 'request', $channel['channel_id'], $sender['hash'], $arr['parent_mid']); } @@ -1598,7 +1621,7 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque // sent it to us originally. Ignore it if it came from another source // (with potentially different permissions). // only compare the last hop since it could have arrived at the last location any number of ways. - // Always accept empty routes and firehose items (route contains 'undefined') . + // Always accept empty routes and firehose items (route contains 'undefined') . $existing_route = explode(',', $r[0]['route']); $routes = count($existing_route); @@ -1610,7 +1633,7 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque $last_hop = ''; $last_prior_route = ''; } - + if(in_array('undefined',$existing_route) || $last_hop == 'undefined' || $sender['hash'] == 'undefined') $last_hop = ''; @@ -1623,7 +1646,7 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque continue; } - // we'll add sender['hash'] onto this when we deliver it. $last_prior_route now has the previously stored route + // we'll add sender['hash'] onto this when we deliver it. $last_prior_route now has the previously stored route // *except* for the sender['hash'] which would've been the last hop before it got to us. $arr['route'] = $last_prior_route; @@ -1661,11 +1684,11 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque // We already have this post. $item_id = $r[0]['id']; if($r[0]['item_restrict'] & ITEM_DELETED) { - // It was deleted locally. + // It was deleted locally. $result[] = array($d['hash'],'update ignored',$channel['channel_name'] . ' <' . $channel['channel_address'] . '@' . get_app()->get_hostname() . '>',$arr['mid']); continue; - } - // Maybe it has been edited? + } + // Maybe it has been edited? elseif($arr['edited'] > $r[0]['edited']) { $arr['id'] = $r[0]['id']; $arr['uid'] = $channel['channel_id']; @@ -1676,8 +1699,8 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque } else { $result[] = array($d['hash'],'update ignored',$channel['channel_name'] . ' <' . $channel['channel_address'] . '@' . get_app()->get_hostname() . '>',$arr['mid']); - // We need this line to ensure wall-to-wall comments are relayed (by falling through to the relay bit), - // and at the same time not relay any other relayable posts more than once, because to do so is very wasteful. + // We need this line to ensure wall-to-wall comments are relayed (by falling through to the relay bit), + // and at the same time not relay any other relayable posts more than once, because to do so is very wasteful. if(! ($r[0]['item_flags'] & ITEM_ORIGIN)) continue; } @@ -1689,8 +1712,8 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque // if it's a sourced post, call the post_local hooks as if it were // posted locally so that crosspost connectors will be triggered. - if(check_item_source($arr['uid'],$arr)) - call_hooks('post_local',$arr); + if(check_item_source($arr['uid'], $arr)) + call_hooks('post_local', $arr); $item_result = item_store($arr); $item_id = 0; @@ -1713,17 +1736,27 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque } if(! $deliveries) - $result[] = array('','no recipients','',$arr['mid']); + $result[] = array('', 'no recipients', '', $arr['mid']); - logger('process_delivery: local results: ' . print_r($result,true), LOGGER_DEBUG); + logger('process_delivery: local results: ' . print_r($result, true), LOGGER_DEBUG); return $result; } +/** + * @brief + * + * @param array $sender an associative array with + * * \e string \b hash a xchan_hash + * @param array $arr an associative array + * * \e int \b verb + * * \e int \b obj_type + * * \e int \b mid + * @param int $uid + */ +function remove_community_tag($sender, $arr, $uid) { -function remove_community_tag($sender,$arr,$uid) { - - if(! (activity_match($arr['verb'],ACTIVITY_TAG) && ($arr['obj_type'] == ACTIVITY_OBJ_TAGTERM))) + if(! (activity_match($arr['verb'], ACTIVITY_TAG) && ($arr['obj_type'] == ACTIVITY_OBJ_TAGTERM))) return; logger('remove_community_tag: invoked'); @@ -1780,7 +1813,15 @@ function remove_community_tag($sender,$arr,$uid) { ); } -function update_imported_item($sender,$item,$uid) { +/** + * @brief Just calls item_store_update() and logs result. + * + * @see item_store_update() + * @param array $sender (unused) + * @param array $item + * @param int $uid (unused) + */ +function update_imported_item($sender, $item, $uid) { $x = item_store_update($item); if(! $x['item_id']) @@ -1793,9 +1834,10 @@ function update_imported_item($sender,$item,$uid) { * @brief Deletes an imported item. * * @param array $sender + * * \e string \b hash a xchan_hash * @param array $item * @param int $uid - * @param unknown $relay + * @param boolean $relay * @return boolean|int post_id */ function delete_imported_item($sender, $item, $uid, $relay) { @@ -1819,9 +1861,9 @@ function delete_imported_item($sender, $item, $uid, $relay) { } else { // perhaps the item is still in transit and the delete notification got here before the actual item did. Store it with the deleted flag set. - // item_store() won't try to deliver any notifications or start delivery chains if this flag is set. + // item_store() won't try to deliver any notifications or start delivery chains if this flag is set. // This means we won't end up with potentially even more delivery threads trying to push this delete notification. - // But this will ensure that if the (undeleted) original post comes in at a later date, we'll reject it because it will have an older timestamp. + // But this will ensure that if the (undeleted) original post comes in at a later date, we'll reject it because it will have an older timestamp. logger('delete received for non-existent item - storing item data.'); @@ -1846,10 +1888,10 @@ function delete_imported_item($sender, $item, $uid, $relay) { // This is a bit hackish, but may have to suffice until the notification/delivery loop is optimised // a bit further. We're going to strip the ITEM_ORIGIN on this item if it's a comment, because - // it was already deleted, and we're already relaying, and this ensures that no other process or + // it was already deleted, and we're already relaying, and this ensures that no other process or // code path downstream can relay it again (causing a loop). Since it's already gone it's not coming // back, and we aren't going to (or shouldn't at any rate) delete it again in the future - so losing - // this information from the metadata should have no other discernible impact. + // this information from the metadata should have no other discernible impact. if (($r[0]['id'] != $r[0]['parent']) && ($r[0]['item_flags'] & ITEM_ORIGIN)) { q("update item set item_flags = %d where id = %d and uid = %d", @@ -1858,7 +1900,7 @@ function delete_imported_item($sender, $item, $uid, $relay) { intval($r[0]['uid']) ); } - } + } require_once('include/items.php'); @@ -1872,7 +1914,7 @@ function delete_imported_item($sender, $item, $uid, $relay) { return $post_id; } -function process_mail_delivery($sender,$arr,$deliveries) { +function process_mail_delivery($sender, $arr, $deliveries) { $result = array(); @@ -1898,7 +1940,7 @@ function process_mail_delivery($sender,$arr,$deliveries) { $result[] = array($d['hash'],'permission denied',$channel['channel_name'],$arr['mid']); continue; } - + $r = q("select id from mail where mid = '%s' and channel_id = %d limit 1", dbesc($arr['mid']), intval($channel['channel_id']) @@ -1923,13 +1965,20 @@ function process_mail_delivery($sender,$arr,$deliveries) { $arr['channel_id'] = $channel['channel_id']; $item_id = mail_store($arr); $result[] = array($d['hash'],'mail delivered',$channel['channel_name'],$arr['mid']); - } } + return $result; } -function process_rating_delivery($sender,$arr) { +/** + * @brief Processes delivery of rating. + * + * @param array $sender + * * \e string \b hash a xchan_hash + * @param array $arr + */ +function process_rating_delivery($sender, $arr) { logger('process_rating_delivery: ' . print_r($arr,true)); @@ -1948,8 +1997,8 @@ function process_rating_delivery($sender,$arr) { $r = q("select * from xlink where xlink_xchan = '%s' and xlink_link = '%s' and xlink_static = 1 limit 1", dbesc($sender['hash']), dbesc($arr['target']) - ); - + ); + if($r) { if($r[0]['xlink_updated'] >= $arr['edited']) { logger('rating message duplicate'); @@ -1979,8 +2028,16 @@ function process_rating_delivery($sender,$arr) { } } - -function process_profile_delivery($sender,$arr,$deliveries) { +/** + * @brief Processes delivery of profile. + * + * @see import_directory_profile() + * @param array $sender an associative array + * * \e string \b hash a xchan_hash + * @param array $arr + * @param array $deliveries (unused) + */ +function process_profile_delivery($sender, $arr, $deliveries) { logger('process_profile_delivery', LOGGER_DEBUG); @@ -1988,7 +2045,7 @@ function process_profile_delivery($sender,$arr,$deliveries) { dbesc($sender['hash']) ); if($r) - import_directory_profile($sender['hash'],$arr,$r[0]['xchan_addr'], UPDATE_FLAGS_UPDATED, 0); + import_directory_profile($sender['hash'], $arr, $r[0]['xchan_addr'], UPDATE_FLAGS_UPDATED, 0); } function process_location_delivery($sender,$arr,$deliveries) { @@ -2001,23 +2058,31 @@ function process_location_delivery($sender,$arr,$deliveries) { ); if($r) $sender['key'] = $r[0]['xchan_pubkey']; + if(array_key_exists('locations',$arr) && $arr['locations']) { $x = sync_locations($sender,$arr,true); logger('process_location_delivery: results: ' . print_r($x,true), LOGGER_DEBUG); if($x['changed']) { - $guid = random_string() . '@' . get_app()->get_hostname(); + $guid = random_string() . '@' . get_app()->get_hostname(); update_modtime($sender['hash'],$sender['guid'],$arr['locations'][0]['address'],UPDATE_FLAGS_UPDATED); } } } - -function sync_locations($sender,$arr,$absolute = false) { +/** + * @brief Synchronises locations. + * + * @param array $sender + * @param array $arr + * @param boolean $absolute (optional) default false + * @return array + */ +function sync_locations($sender, $arr, $absolute = false) { $ret = array(); if($arr['locations']) { - + $xisting = q("select hubloc_id, hubloc_url, hubloc_sitekey from hubloc where hubloc_hash = '%s'", dbesc($sender['hash']) ); @@ -2045,7 +2110,7 @@ function sync_locations($sender,$arr,$absolute = false) { } for($x = 0; $x < count($xisting); $x ++) { - if(($xisting[$x]['hubloc_url'] === $location['url']) + if(($xisting[$x]['hubloc_url'] === $location['url']) && ($xisting[$x]['hubloc_sitekey'] === $location['sitekey'])) { $xisting[$x]['updated'] = true; } @@ -2061,7 +2126,7 @@ function sync_locations($sender,$arr,$absolute = false) { if(strpos($location['address'],'/') !== false) $location['address'] = substr($location['address'],0,strpos($location['address'],'/')); - // match as many fields as possible in case anything at all changed. + // match as many fields as possible in case anything at all changed. $r = q("select * from hubloc where hubloc_hash = '%s' and hubloc_guid = '%s' and hubloc_guid_sig = '%s' and hubloc_url = '%s' and hubloc_url_sig = '%s' and hubloc_host = '%s' and hubloc_addr = '%s' and hubloc_callback = '%s' and hubloc_sitekey = '%s' ", dbesc($sender['hash']), @@ -2090,7 +2155,7 @@ function sync_locations($sender,$arr,$absolute = false) { ); $current_site = true; } - + // If it is the site we're currently talking to, and it's marked offline, // either we have some bad information - or the thing came back to life. @@ -2110,7 +2175,7 @@ function sync_locations($sender,$arr,$absolute = false) { intval(XCHAN_FLAGS_ORPHAN), dbesc($sender['hash']) ); - } + } // Remove pure duplicates if(count($r) > 1) { @@ -2175,7 +2240,7 @@ function sync_locations($sender,$arr,$absolute = false) { continue; } - // Existing hubs are dealt with. Now let's process any new ones. + // Existing hubs are dealt with. Now let's process any new ones. // New hub claiming to be primary. Make it so by removing any existing primaries. if(intval($location['primary'])) { @@ -2244,9 +2309,9 @@ function sync_locations($sender,$arr,$absolute = false) { * @brief Returns an array with all known distinct hubs for this channel. * * @see zot_get_hublocs() - * @param array $channel an assoziative array which must contain + * @param array $channel an associative array which must contain * * \e string \b channel_hash the hash of the channel - * @return array an array with assoziated arrays + * @return array an array with associative arrays */ function zot_encode_locations($channel) { $ret = array(); @@ -2272,10 +2337,9 @@ function zot_encode_locations($channel) { return $ret; } - /** * @brief Imports a directory profile. - * + * * @param string $hash * @param array $profile * @param string $addr @@ -2319,7 +2383,7 @@ function import_directory_profile($hash, $profile, $addr, $ud_flags = UPDATE_FLA $arr['xprof_keywords'] = implode(' ',$clean); // Self censored, make it so - // These are not translated, so the German "erwachsenen" keyword will not censor the directory profile. Only the English form - "adult". + // These are not translated, so the German "erwachsenen" keyword will not censor the directory profile. Only the English form - "adult". if (in_arrayi('nsfw', $clean) || in_arrayi('adult', $clean)) { @@ -2333,7 +2397,7 @@ function import_directory_profile($hash, $profile, $addr, $ud_flags = UPDATE_FLA dbesc($hash) ); - if ($arr['xprof_age'] > 150) + if ($arr['xprof_age'] > 150) $arr['xprof_age'] = 150; if ($arr['xprof_age'] < 0) $arr['xprof_age'] = 0; @@ -2348,21 +2412,21 @@ function import_directory_profile($hash, $profile, $addr, $ud_flags = UPDATE_FLA } } if ($update) { - q("update xprof set - xprof_desc = '%s', - xprof_dob = '%s', - xprof_age = %d, - xprof_gender = '%s', - xprof_marital = '%s', - xprof_sexual = '%s', - xprof_locale = '%s', - xprof_region = '%s', - xprof_postcode = '%s', - xprof_country = '%s', - xprof_about = '%s', - xprof_homepage = '%s', - xprof_hometown = '%s', - xprof_keywords = '%s' + q("update xprof set + xprof_desc = '%s', + xprof_dob = '%s', + xprof_age = %d, + xprof_gender = '%s', + xprof_marital = '%s', + xprof_sexual = '%s', + xprof_locale = '%s', + xprof_region = '%s', + xprof_postcode = '%s', + xprof_country = '%s', + xprof_about = '%s', + xprof_homepage = '%s', + xprof_hometown = '%s', + xprof_keywords = '%s' where xprof_hash = '%s'", dbesc($arr['xprof_desc']), dbesc($arr['xprof_dob']), @@ -2412,7 +2476,13 @@ function import_directory_profile($hash, $profile, $addr, $ud_flags = UPDATE_FLA return $d['update']; } -function import_directory_keywords($hash,$keywords) { +/** + * @brief + * + * @param string $hash + * @param array $keywords + */ +function import_directory_keywords($hash, $keywords) { $existing = array(); $r = q("select * from xtag where xtag_hash = '%s'", @@ -2426,31 +2496,39 @@ function import_directory_keywords($hash,$keywords) { $clean = array(); foreach($keywords as $kw) { - $kw = trim(htmlspecialchars($kw,ENT_COMPAT,'UTF-8',false)); - $kw = trim($kw,','); + $kw = trim(htmlspecialchars($kw,ENT_COMPAT, 'UTF-8', false)); + $kw = trim($kw, ','); $clean[] = $kw; } foreach($existing as $x) { - if(! in_array($x,$clean)) + if(! in_array($x, $clean)) $r = q("delete from xtag where xtag_hash = '%s' and xtag_term = '%s'", dbesc($hash), dbesc($x) ); } foreach($clean as $x) { - if(! in_array($x,$existing)) + if(! in_array($x, $existing)) { $r = q("insert into xtag ( xtag_hash, xtag_term) values ( '%s' ,'%s' )", dbesc($hash), dbesc($x) ); + } } } +/** + * @brief + * + * @param string $hash + * @param string $guid + * @param string $addr + * @param int $flags (optional) default 0 + */ +function update_modtime($hash, $guid, $addr, $flags = 0) { -function update_modtime($hash,$guid,$addr,$flags = 0) { - - $dirmode = intval(get_config('system','directory_mode')); + $dirmode = intval(get_config('system', 'directory_mode')); if($dirmode == DIRECTORY_MODE_NORMAL) return; @@ -2473,12 +2551,18 @@ function update_modtime($hash,$guid,$addr,$flags = 0) { } } - -function import_site($arr,$pubkey) { +/** + * @brief + * + * @param array $arr + * @param string $pubkey + * @return boolean true if updated or inserted + */ +function import_site($arr, $pubkey) { if( (! is_array($arr)) || (! $arr['url']) || (! $arr['url_sig'])) return false; - if(! rsa_verify($arr['url'],base64url_decode($arr['url_sig']),$pubkey)) { + if(! rsa_verify($arr['url'], base64url_decode($arr['url_sig']), $pubkey)) { logger('import_site: bad url_sig'); return false; } @@ -2545,11 +2629,11 @@ function import_site($arr,$pubkey) { // Downgrade any others claiming to be primary. As they have // flubbed up this badly already, don't let them be directory servers at all. - if(($site_directory === DIRECTORY_MODE_PRIMARY) - && ($site_realm === get_directory_realm()) - && ($arr['url'] != get_directory_primary())) { + if(($site_directory === DIRECTORY_MODE_PRIMARY) + && ($site_realm === get_directory_realm()) + && ($arr['url'] != get_directory_primary())) { $site_directory = DIRECTORY_MODE_NORMAL; - } + } if($exists) { if(($siterecord['site_flags'] != $site_directory) @@ -2614,8 +2698,11 @@ function import_site($arr,$pubkey) { /** * Send a zot packet to all hubs where this channel is duplicated, refreshing * such things as personal settings, channel permissions, address book updates, etc. + * + * @param int $uid + * @param array $packet (optional) default null + * @param boolean $groups_changed (optional) default false */ - function build_sync_packet($uid = 0, $packet = null, $groups_changed = false) { $a = get_app(); @@ -2623,7 +2710,7 @@ function build_sync_packet($uid = 0, $packet = null, $groups_changed = false) { logger('build_sync_packet'); if($packet) - logger('packet: ' . print_r($packet,true),LOGGER_DATA); + logger('packet: ' . print_r($packet, true),LOGGER_DATA); if(! $uid) $uid = local_channel(); @@ -2651,6 +2738,7 @@ function build_sync_packet($uid = 0, $packet = null, $groups_changed = false) { foreach($h as $x) { if($x['hubloc_host'] == $a->get_hostname()) continue; + $synchubs[] = $x; } @@ -2708,10 +2796,9 @@ function build_sync_packet($uid = 0, $packet = null, $groups_changed = false) { ); if($r) $info['collection_members'] = $r; - } - $interval = ((get_config('system','delivery_interval') !== false) + $interval = ((get_config('system','delivery_interval') !== false) ? intval(get_config('system','delivery_interval')) : 2 ); @@ -2733,13 +2820,21 @@ function build_sync_packet($uid = 0, $packet = null, $groups_changed = false) { dbesc(json_encode($info)) ); - proc_run('php','include/deliver.php',$hash); + proc_run('php', 'include/deliver.php', $hash); if($interval) @time_sleep_until(microtime(true) + (float) $interval); } } -function process_channel_sync_delivery($sender,$arr,$deliveries) { +/** + * @brief + * + * @param array $sender + * @param array $arr + * @param array $deliveries + * @return array + */ +function process_channel_sync_delivery($sender, $arr, $deliveries) { /** @FIXME this will sync red structures (channel, pconfig and abook). Eventually we need to make this application agnostic. */ @@ -2784,7 +2879,7 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { } if(count($clean)) { foreach($clean as $k => $v) { - $r = dbq("UPDATE channel set " . dbesc($k) . " = '" . dbesc($v) + $r = dbq("UPDATE channel set " . dbesc($k) . " = '" . dbesc($v) . "' where channel_id = " . intval($channel['channel_id']) ); } } @@ -2813,7 +2908,7 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { if($abook['abook_xchan'] && $abook['entry_deleted']) { logger('process_channel_sync_delivery: removing abook entry for ' . $abook['abook_xchan']); require_once('include/Contact.php'); - + $r = q("select abook_id, abook_flags from abook where abook_xchan = '%s' and abook_channel = %d and not ( abook_flags & %d )>0 limit 1", dbesc($abook['abook_xchan']), intval($channel['channel_id']), @@ -2893,8 +2988,8 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { foreach($clean as $k => $v) { if($k == 'abook_dob') $v = dbescdate($v); - - $r = dbq("UPDATE abook set " . dbesc($k) . " = '" . dbesc($v) + + $r = dbq("UPDATE abook set " . dbesc($k) . " = '" . dbesc($v) . "' where abook_xchan = '" . dbesc($clean['abook_xchan']) . "' and abook_channel = " . intval($channel['channel_id'])); } } @@ -2917,8 +3012,8 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { } } if($found) { - if(($y['name'] != $cl['name']) - || ($y['visible'] != $cl['visible']) + if(($y['name'] != $cl['name']) + || ($y['visible'] != $cl['visible']) || ($y['deleted'] != $cl['deleted'])) { q("update groups set name = '%s', visible = %d, deleted = %d where hash = '%s' and uid = %d", dbesc($cl['name']), @@ -2959,10 +3054,10 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { break; } } - if(! $found_local) { + if(! $found_local) { q("delete from group_member where gid = %d", intval($y['id']) - ); + ); q("update groups set deleted = 1 where id = %d and uid = %d", intval($y['id']), intval($channel['channel_id']) @@ -2979,15 +3074,17 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { // now sync the members - if(array_key_exists('collection_members',$arr) && - is_array($arr['collection_members']) && count($arr['collection_members'])) { + if(array_key_exists('collection_members', $arr) + && is_array($arr['collection_members']) + && count($arr['collection_members'])) { // first sort into groups keyed by the group hash $members = array(); foreach($arr['collection_members'] as $cm) { if(! array_key_exists($cm['collection'],$members)) $members[$cm['collection']] = array(); - $members[$cm['collection']][] = $cm['member']; + + $members[$cm['collection']][] = $cm['member']; } // our group list is already synchronised @@ -3074,7 +3171,7 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { } if(count($clean)) { foreach($clean as $k => $v) { - $r = dbq("UPDATE profile set " . dbesc($k) . " = '" . dbesc($v) + $r = dbq("UPDATE profile set " . dbesc($k) . " = '" . dbesc($v) . "' where profile_guid = '" . dbesc($profile['profile_guid']) . "' and uid = " . intval($channel['channel_id'])); } } @@ -3087,8 +3184,15 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) { return $result; } -// We probably should make rpost discoverable. - +/** + * @brief Returns path to /rpost + * + * @todo We probably should make rpost discoverable. + * + * @param array $observer + * * \e string \b xchan_url + * @return string + */ function get_rpost_path($observer) { if(! $observer) return ''; @@ -3098,7 +3202,6 @@ function get_rpost_path($observer) { return $parsed['scheme'] . '://' . $parsed['host'] . (($parsed['port']) ? ':' . $parsed['port'] : '') . '/rpost?f='; } - /** * @brief * @@ -3127,7 +3230,6 @@ function import_author_zot($x) { return false; } - /** * @brief Process a message request. * @@ -3136,10 +3238,10 @@ function import_author_zot($x) { * for that packet. We will create a message_list array of the entire conversation starting with * the missing parent and invoke delivery to the sender of the packet. * - * include/deliver.php (for local delivery) and mod/post.php (for web delivery) detect the existence of - * this 'message_list' at the destination and split it into individual messages which are - * processed/delivered in order. - * + * include/deliver.php (for local delivery) and mod/post.php (for web delivery) detect the existence of + * this 'message_list' at the destination and split it into individual messages which are + * processed/delivered in order. + * * Called from mod/post.php * * @param array $data @@ -3181,7 +3283,7 @@ function zot_process_message_request($data) { if ($messages) { $env_recips = null; - $r = q("select hubloc_guid, hubloc_url, hubloc_sitekey, hubloc_network, hubloc_flags, hubloc_callback, hubloc_host + $r = q("select hubloc_guid, hubloc_url, hubloc_sitekey, hubloc_network, hubloc_flags, hubloc_callback, hubloc_host from hubloc where hubloc_hash = '%s' and not (hubloc_flags & %d)>0 and not (hubloc_status & %d)>0 ", dbesc($sender_hash), @@ -3208,8 +3310,8 @@ function zot_process_message_request($data) { */ $n = zot_build_packet($c[0],'notify',$env_recips,(($private) ? $hub['hubloc_sitekey'] : null),$hash,array('message_id' => $data['message_id'])); - q("insert into outq ( outq_hash, outq_account, outq_channel, outq_driver, outq_posturl, outq_async, - outq_created, outq_updated, outq_notify, outq_msg ) + q("insert into outq ( outq_hash, outq_account, outq_channel, outq_driver, outq_posturl, outq_async, + outq_created, outq_updated, outq_notify, outq_msg ) values ( '%s', %d, %d, '%s', '%s', %d, '%s', '%s', '%s', '%s' )", dbesc($hash), intval($c[0]['channel_account_id']), -- cgit v1.2.3 From 3fd2e4b716aaf4626b774ac5d808cc4088e6f3f2 Mon Sep 17 00:00:00 2001 From: friendica Date: Thu, 9 Apr 2015 19:51:58 -0700 Subject: program the affinity slider labels --- include/widgets.php | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) (limited to 'include') diff --git a/include/widgets.php b/include/widgets.php index e84c029d2..4a9032a21 100644 --- a/include/widgets.php +++ b/include/widgets.php @@ -420,18 +420,35 @@ function widget_affinity($arr) { $cmin = ((x($_REQUEST,'cmin')) ? intval($_REQUEST['cmin']) : 0); $cmax = ((x($_REQUEST,'cmax')) ? intval($_REQUEST['cmax']) : 99); + if(feature_enabled(local_channel(),'affinity')) { + + $labels = array( + t('Me'), + t('Family'), + t('Friends'), + t('Acquaintances'), + t('All') + ); + call_hooks('affinity_labels',$labels); + $label_str = ''; + + if($labels) { + foreach($labels as $l) { + if($label_str) { + $label_str .= ", '|'"; + $label_str .= ", '" . $l . "'"; + } + else + $label_str .= "'" . $l . "'"; + } + } + $tpl = get_markup_template('main_slider.tpl'); $x = replace_macros($tpl,array( '$val' => $cmin . ',' . $cmax, '$refresh' => t('Refresh'), - '$me' => t('Me'), - '$intimate' => t('Best Friends'), - '$friends' => t('Friends'), - '$coworkers' => t('Co-workers'), - '$oldfriends' => t('Former Friends'), - '$acquaintances' => t('Acquaintances'), - '$world' => t('All') + '$labels' => $label_str, )); $arr = array('html' => $x); call_hooks('main_slider',$arr); -- cgit v1.2.3 From d9807e34e5bfd7cff4dbbb7bfc00e7a4847f8c2e Mon Sep 17 00:00:00 2001 From: friendica Date: Thu, 9 Apr 2015 22:35:04 -0700 Subject: don't warn folks about the webaddress observer tag. We need it in constructed urls. --- include/bbcode.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/bbcode.php b/include/bbcode.php index e79e709da..47a1fd223 100644 --- a/include/bbcode.php +++ b/include/bbcode.php @@ -490,7 +490,7 @@ function bbcode($Text, $preserve_nl = false, $tryoembed = true) { $Text = str_replace('[observer.url]',$observer['xchan_url'], $Text); $Text = str_replace('[observer.name]',$s1 . $observer['xchan_name'] . $s2, $Text); $Text = str_replace('[observer.address]',$s1 . $observer['xchan_addr'] . $s2, $Text); - $Text = str_replace('[observer.webname]',$s1 . substr($observer['xchan_addr'],0,strpos($observer['xchan_addr'],'@')) . $s2, $Text); + $Text = str_replace('[observer.webname]', substr($observer['xchan_addr'],0,strpos($observer['xchan_addr'],'@')), $Text); $Text = str_replace('[observer.photo]',$s1 . '[zmg]'.$observer['xchan_photo_l'].'[/zmg]' . $s2, $Text); } else { $Text = str_replace('[observer.baseurl]', '', $Text); -- cgit v1.2.3 From 5457b417f84f01336b80386346cd19f1613e4811 Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Fri, 10 Apr 2015 14:01:40 +0200 Subject: make r# work better with different font sizes --- include/text.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'include') diff --git a/include/text.php b/include/text.php index 5666998f0..881c694c3 100644 --- a/include/text.php +++ b/include/text.php @@ -1042,9 +1042,9 @@ function list_smilies() { ':facepalm', ':like', ':dislike', - 'red' . urlencode('red#matrix') . 'matrix', - 'red' . urlencode('red#') . 'matrix', - 'redr#matrix' + 'red' . urlencode('red#matrix') . 'matrix', + 'red' . urlencode('red#') . 'matrix', + 'redr#matrix' ); -- cgit v1.2.3 From 8138373973ffae06da9277c78fa4c6ff5e841e6e Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Fri, 10 Apr 2015 14:14:19 +0200 Subject: move style to style.css --- include/text.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'include') diff --git a/include/text.php b/include/text.php index 881c694c3..791254e52 100644 --- a/include/text.php +++ b/include/text.php @@ -1042,9 +1042,9 @@ function list_smilies() { ':facepalm', ':like', ':dislike', - 'red' . urlencode('red#matrix') . 'matrix', - 'red' . urlencode('red#') . 'matrix', - 'redr#matrix' + 'redmatrix', + 'redmatrix', + 'redmatrix' ); -- cgit v1.2.3 From 7c8b9397ae8fc83ce96d9905992f40e6fde4663a Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Sun, 12 Apr 2015 13:13:22 +0200 Subject: reverse file activity logic --- include/attach.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/attach.php b/include/attach.php index 415859b39..2a72c7819 100644 --- a/include/attach.php +++ b/include/attach.php @@ -985,7 +985,7 @@ function pipe_streams($in, $out) { * @param string $verb * @param boolean $no_activity */ -function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $verb, $no_activity) { +function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $verb, $notify) { require_once('include/items.php'); @@ -1107,7 +1107,7 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, //notice( t('File activity updated') . EOL); } - if($no_activity) { + if(! $notify) { return; } -- cgit v1.2.3 From 962fdf08c0f3c83927ed23a1b6f384b2c3d74aae Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Sun, 12 Apr 2015 13:58:04 +0200 Subject: make fs deletion of directories work --- include/attach.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/attach.php b/include/attach.php index 2a72c7819..e624734fa 100644 --- a/include/attach.php +++ b/include/attach.php @@ -812,8 +812,8 @@ function attach_delete($channel_id, $resource) { if($y) { $f = 'store/' . $channel_address . '/' . $y[0]['data']; - if(is_dir($f)) - @rmdir($f); + if(is_dir($y[0]['data'])) + @rmdir($y[0]['data']); elseif(file_exists($f)) unlink($f); } -- cgit v1.2.3 From 70b109702ef20d0ebad027a98964ceae1fb216c3 Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Sun, 12 Apr 2015 14:30:33 +0200 Subject: make dropItem more universal and move delete up in the dropdown menu --- include/attach.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/attach.php b/include/attach.php index e624734fa..e6d6e5f24 100644 --- a/include/attach.php +++ b/include/attach.php @@ -832,7 +832,7 @@ function attach_delete($channel_id, $resource) { intval($channel_id) ); - file_activity($channel_id, $object, $object['allow_cid'], $object['allow_gid'], $object['deny_cid'], $object['deny_gid'], 'update', $no_activity=false); + file_activity($channel_id, $object, $object['allow_cid'], $object['allow_gid'], $object['deny_cid'], $object['deny_gid'], 'update', $notify=0); } /** -- cgit v1.2.3 From 22c3202f22494cbef85eff9bc97d23fb829a66c2 Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Mon, 13 Apr 2015 16:17:10 +0200 Subject: remove widget class from webpage blocks and make titles h2 to match the rest of the matrix --- include/comanche.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/comanche.php b/include/comanche.php index 62bfd0ddc..fcf50d67e 100644 --- a/include/comanche.php +++ b/include/comanche.php @@ -143,7 +143,7 @@ function comanche_block($name) { dbesc($name) ); if($r) { - $o = '
          '; + $o = '
          '; if($r[0]['title']) $o .= '

          ' . $r[0]['title'] . '

          '; -- cgit v1.2.3 From bf2a97147ecef7528e9adbed3cf4a1f3af03ad72 Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Tue, 14 Apr 2015 11:50:21 +0200 Subject: some more on webpages --- include/text.php | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) (limited to 'include') diff --git a/include/text.php b/include/text.php index 791254e52..29654e1fd 100644 --- a/include/text.php +++ b/include/text.php @@ -1595,18 +1595,20 @@ function layout_select($channel_id, $current = '') { intval($channel_id), intval(ITEM_PDL) ); + if($r) { - $o = t('Select a page layout: '); - $o .= ''; } + $o = replace_macros(get_markup_template('field_select_raw.tpl'), array( + '$field' => array('layout_mid', t('Page layout'), $selected, t('You can create your own with the layouts tool'), $options) + )); + return $o; } @@ -1639,13 +1641,14 @@ function mimetype_select($channel_id, $current = 'text/bbcode') { } } - $o = t('Page content type: '); - $o .= ''; + + $o = replace_macros(get_markup_template('field_select_raw.tpl'), array( + '$field' => array('mimetype', t('Page content type'), $selected, t('If unsure select text/bbcode'), $options) + )); return $o; } @@ -2105,7 +2108,7 @@ function design_tools() { $who = $channel['channel_address']; return replace_macros(get_markup_template('design_tools.tpl'), array( - '$title' => t('Design'), + '$title' => t('Design Tools'), '$who' => $who, '$sys' => $sys, '$blocks' => t('Blocks'), -- cgit v1.2.3 From 2001ad94bd16c283b2cc79d8e48646d61acb5a77 Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Tue, 14 Apr 2015 11:59:49 +0200 Subject: dont suggest anything here it explains itself --- include/text.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/text.php b/include/text.php index 29654e1fd..f1f6d41f0 100644 --- a/include/text.php +++ b/include/text.php @@ -1647,7 +1647,7 @@ function mimetype_select($channel_id, $current = 'text/bbcode') { } $o = replace_macros(get_markup_template('field_select_raw.tpl'), array( - '$field' => array('mimetype', t('Page content type'), $selected, t('If unsure select text/bbcode'), $options) + '$field' => array('mimetype', t('Page content type'), $selected, '', $options) )); return $o; -- cgit v1.2.3 From 32acb7f6e1d7b504cb633cb951ed6d722a75182f Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 14 Apr 2015 20:50:38 -0700 Subject: post_activity_item incorrectly setting the obj_type when a valid type was specified --- include/items.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/items.php b/include/items.php index e08aab85a..659d0e350 100755 --- a/include/items.php +++ b/include/items.php @@ -436,7 +436,7 @@ function post_activity_item($arr) { $arr['verb'] = ((x($arr,'verb')) ? $arr['verb'] : ACTIVITY_POST); $arr['obj_type'] = ((x($arr,'obj_type')) ? $arr['obj_type'] : ACTIVITY_OBJ_NOTE); - if($is_comment) + if($is_comment && $arr['obj_type'] === ACTIVITY_OBJ_NOTE)) $arr['obj_type'] = ACTIVITY_OBJ_COMMENT; $arr['allow_cid'] = ((x($arr,'allow_cid')) ? $arr['allow_cid'] : $channel['channel_allow_cid']); -- cgit v1.2.3 From 9942dec09cf5dc2ab4b2644adf3e48808443338b Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 14 Apr 2015 20:52:07 -0700 Subject: match parens --- include/items.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/items.php b/include/items.php index 659d0e350..01f207878 100755 --- a/include/items.php +++ b/include/items.php @@ -436,7 +436,7 @@ function post_activity_item($arr) { $arr['verb'] = ((x($arr,'verb')) ? $arr['verb'] : ACTIVITY_POST); $arr['obj_type'] = ((x($arr,'obj_type')) ? $arr['obj_type'] : ACTIVITY_OBJ_NOTE); - if($is_comment && $arr['obj_type'] === ACTIVITY_OBJ_NOTE)) + if(($is_comment) && ($arr['obj_type'] === ACTIVITY_OBJ_NOTE)) $arr['obj_type'] = ACTIVITY_OBJ_COMMENT; $arr['allow_cid'] = ((x($arr,'allow_cid')) ? $arr['allow_cid'] : $channel['channel_allow_cid']); -- cgit v1.2.3 From 834044b15bf4cd3f436f065449cbc0ed76b4de93 Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Wed, 15 Apr 2015 09:20:27 +0200 Subject: title=>name --- include/conversation.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/conversation.php b/include/conversation.php index 67f3afde0..05898cfce 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -1171,7 +1171,7 @@ function status_editor($a, $x, $popup = false) { '$action' => $a->get_baseurl(true) . '/item', '$share' => (x($x,'button') ? $x['button'] : t('Share')), '$webpage' => $webpage, - '$placeholdpagetitle' => ((x($x,'ptlabel')) ? $x['ptlabel'] : t('Page link title')), + '$placeholdpagetitle' => ((x($x,'ptlabel')) ? $x['ptlabel'] : t('Page link name')), '$pagetitle' => (x($x,'pagetitle') ? $x['pagetitle'] : ''), '$id_select' => $id_select, '$id_seltext' => t('Post as'), -- cgit v1.2.3 From 32f79374b0e1a6d21204d8a51f2c3c60b28c95ca Mon Sep 17 00:00:00 2001 From: friendica Date: Wed, 15 Apr 2015 22:07:20 -0700 Subject: don't show directory keywords widget if globaldir setting is off --- include/taxonomy.php | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'include') diff --git a/include/taxonomy.php b/include/taxonomy.php index 4333cdf03..fa540ac56 100644 --- a/include/taxonomy.php +++ b/include/taxonomy.php @@ -275,6 +275,11 @@ function catblock($uid,$count = 0,$authors = '',$flags = 0,$restrict = 0,$type = function dir_tagblock($link,$r) { $o = ''; + $observer = get_observer_hash(); + if(! get_globaldir_setting($observer)) + return $o; + + if(! $r) $r = get_app()->data['directory_keywords']; -- cgit v1.2.3 From 9addc4581edf594996151eaf514927d271f04da5 Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Thu, 16 Apr 2015 23:26:11 +0200 Subject: provide a separate input field for rpost attachments --- include/conversation.php | 1 + 1 file changed, 1 insertion(+) (limited to 'include') diff --git a/include/conversation.php b/include/conversation.php index 05898cfce..cdb7807b6 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -1208,6 +1208,7 @@ function status_editor($a, $x, $popup = false) { '$shortpermset' => t('permissions'), '$ptyp' => (($notes_cid) ? 'note' : 'wall'), '$content' => ((x($x,'body')) ? htmlspecialchars($x['body'], ENT_COMPAT,'UTF-8') : ''), + '$attachment' => ((x($x, 'attachment')) ? $x['attachment'] : ''), '$post_id' => '', '$baseurl' => $a->get_baseurl(true), '$defloc' => $x['default_location'], -- cgit v1.2.3 From 61e4ee753dd0e823c47a5cf2e485f7f69fb4d125 Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Fri, 17 Apr 2015 11:20:22 +0200 Subject: allow jot to be displayed expanded, remove deprected datetimepicker js and some random fixes --- include/conversation.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'include') diff --git a/include/conversation.php b/include/conversation.php index cdb7807b6..5ae2250a8 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -1233,7 +1233,8 @@ function status_editor($a, $x, $popup = false) { '$encrypt' => t('Encrypt text'), '$cipher' => $cipher, '$expiryModalOK' => t('OK'), - '$expiryModalCANCEL' => t('Cancel') + '$expiryModalCANCEL' => t('Cancel'), + '$expanded' => ((x($x, 'expanded')) ? $x['expanded'] : false), )); if ($popup === true) { -- cgit v1.2.3 From e1b90535638ba766d569237e8e48c400aa003725 Mon Sep 17 00:00:00 2001 From: friendica Date: Fri, 17 Apr 2015 20:22:10 -0700 Subject: add last post to api/account/verify_credentials --- include/api.php | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 60 insertions(+), 5 deletions(-) (limited to 'include') diff --git a/include/api.php b/include/api.php index 3ac8ddbda..ff6e41fcd 100644 --- a/include/api.php +++ b/include/api.php @@ -412,7 +412,7 @@ require_once('include/items.php'); 'notifications' => false, 'following' => '', #XXX: fix me 'verified' => true, #XXX: fix me - 'status' => array() + 'status' => api_get_status($uinfo[0]['xchan_hash']) ); return $ret; @@ -473,7 +473,7 @@ require_once('include/items.php'); 'profile_use_background_image' => false, 'verified' => true, #XXX: fix me 'followers' => '', #XXX: fix me - 'status' => array() + 'status' => api_get_status($item['author_xchan']) ); return $ret; @@ -807,13 +807,66 @@ require_once('include/items.php'); api_register_func('api/red/item/new','red_item_new', true); + function api_get_status($xchan_hash) { + require_once('include/security.php'); + $lastwall = q("SELECT * from item where + item_private = 0 and item_restrict = 0 + and author_xchan = '%s' + and allow_cid = '' and allow_gid = '' and deny_cid = '' and deny_gid = '' + and verb = '%s' + and uid in ( " . stream_perms_api_uids() . " ) + order by created desc limit 1", + dbesc($xchan_hash), + dbesc(ACTIVITY_POST) + ); + if($lastwall){ + $lastwall = $lastwall[0]; + + $in_reply_to_status_id = ''; + $in_reply_to_user_id = ''; + $in_reply_to_screen_name = ''; + if($lastwall['author_xchan'] != $lastwall['owner_xchan']) { + $w = q("select * from abook left join xchan on abook_xchan = xchan_hash where + xchan_hash = '%s' limit 1", + dbesc($lastwall['owner_xchan']) + ); + if($w) { + $in_reply_to_user_id = $w[0]['abook_id']; + $in_reply_to_screen_name = substr($w[0]['xchan_addr'],0,strpos($w[0]['xchan_addr'],'@')); + } + } + + if ($lastwall['parent']!=$lastwall['id']) { + $in_reply_to_status_id=$lastwall['thr_parent']; + if(! $in_reply_to_user_id) { + $in_reply_to_user_id = $user_info['id']; + $in_reply_to_screen_name = $user_info['screen_name']; + } + } + unobscure($lastwall); + $status_info = array( + 'text' => html2plain(prepare_text($lastwall['body'],$lastwall['mimetype']), 0), + 'truncated' => false, + 'created_at' => api_date($lastwall['created']), + 'in_reply_to_status_id' => $in_reply_to_status_id, + 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'), + 'id' => ($lastwall['id']), + 'in_reply_to_user_id' => $in_reply_to_user_id, + 'in_reply_to_screen_name' => $in_reply_to_screen_name, + 'geo' => '', + 'favorited' => false, + 'coordinates' => $lastwall['coord'], + 'place' => $lastwall['location'], + 'contributors' => '' + ); - - - + } + + return $status_info; + } function api_status_show(&$a, $type){ $user_info = api_get_user($a); @@ -876,6 +929,8 @@ require_once('include/items.php'); ); $status_info['user'] = $user_info; } + if($u) + return $status_info; return api_apply_template("status", $type, array('$status' => $status_info)); -- cgit v1.2.3 From 0ce8572fef170d5d920287d8328b27c79e819c4a Mon Sep 17 00:00:00 2001 From: friendica Date: Fri, 17 Apr 2015 23:04:58 -0700 Subject: remove failed experiment --- include/api.php | 2 -- 1 file changed, 2 deletions(-) (limited to 'include') diff --git a/include/api.php b/include/api.php index ff6e41fcd..c2687f3e4 100644 --- a/include/api.php +++ b/include/api.php @@ -929,8 +929,6 @@ require_once('include/items.php'); ); $status_info['user'] = $user_info; } - if($u) - return $status_info; return api_apply_template("status", $type, array('$status' => $status_info)); -- cgit v1.2.3 From 0883512e30af10ea7ed0f461afc8236a828e7d2b Mon Sep 17 00:00:00 2001 From: friendica Date: Sat, 18 Apr 2015 17:40:44 -0700 Subject: log this since we may need it to track down failures --- include/api.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/api.php b/include/api.php index c2687f3e4..e4b28bc54 100644 --- a/include/api.php +++ b/include/api.php @@ -667,6 +667,7 @@ require_once('include/items.php'); $a->argv[1] = $user_info['screen_name']; $_REQUEST['silent']='1'; //tell wall_upload function to return img info instead of echo + $_FILES['userfile'] = $_FILES['media']; require_once('mod/wall_attach.php'); $posted = wall_attach_post($a); @@ -755,8 +756,8 @@ require_once('include/items.php'); $_FILES['userfile'] = $_FILES['media']; // upload the image if we have one $_REQUEST['silent']='1'; //tell wall_upload function to return img info instead of echo - require_once('mod/wall_upload.php'); - $media = wall_upload_post($a); + require_once('mod/wall_attach.php'); + $media = wall_attach_post($a); if(strlen($media)>0) $_REQUEST['body'] .= "\n\n".$media; } -- cgit v1.2.3 From dd5b97639edfb5d562ced806e27e64a6bab556b8 Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Sun, 19 Apr 2015 13:25:05 +0200 Subject: Introduce wrap variable in comanche blocks (if set to none the block will not be wrapped in a div), fix menu item permissions (it was not possible to set them visible for everybody) and a typo --- include/comanche.php | 18 +++++++++++++++--- include/menu.php | 52 ++++++++-------------------------------------------- 2 files changed, 23 insertions(+), 47 deletions(-) (limited to 'include') diff --git a/include/comanche.php b/include/comanche.php index fcf50d67e..e0d3af985 100644 --- a/include/comanche.php +++ b/include/comanche.php @@ -133,7 +133,19 @@ function comanche_get_channel_id() { return $channel_id; } -function comanche_block($name) { +function comanche_block($s) { + $var = array(); + $matches = array(); + $name = $s; + + $cnt = preg_match_all("/\[var=(.*?)\](.*?)\[\/var\]/ism", $s, $matches, PREG_SET_ORDER); + if($cnt) { + foreach($matches as $mtch) { + $var[$mtch[1]] = $mtch[2]; + $name = str_replace($mtch[0], '', $name); + } + } + $o = ''; $channel_id = comanche_get_channel_id(); @@ -143,12 +155,12 @@ function comanche_block($name) { dbesc($name) ); if($r) { - $o = '
          '; + $o .= (($var['wrap'] == 'none') ? '' : '
          '); if($r[0]['title']) $o .= '

          ' . $r[0]['title'] . '

          '; $o .= prepare_text($r[0]['body'], $r[0]['mimetype']); - $o .= '
          '; + $o .= (($var['wrap'] == 'none') ? '' : '
          '); } } diff --git a/include/menu.php b/include/menu.php index 81e986132..fe62d8d32 100644 --- a/include/menu.php +++ b/include/menu.php @@ -227,31 +227,10 @@ function menu_add_item($menu_id, $uid, $arr) { $channel = get_app()->get_channel(); } - if (($channel) - && (! $arr['contact_allow']) - && (! $arr['group_allow']) - && (! $arr['contact_deny']) - && (! $arr['group_deny'])) { - $str_group_allow = $channel['channel_allow_gid']; - $str_contact_allow = $channel['channel_allow_cid']; - $str_group_deny = $channel['channel_deny_gid']; - $str_contact_deny = $channel['channel_deny_cid']; - } - else { - - // use the posted permissions - - $str_group_allow = perms2str($arr['group_allow']); - $str_contact_allow = perms2str($arr['contact_allow']); - $str_group_deny = perms2str($arr['group_deny']); - $str_contact_deny = perms2str($arr['contact_deny']); - } - -// unused -// $allow_cid = perms2str($arr['allow_cid']); -// $allow_gid = perms2str($arr['allow_gid']); -// $deny_cid = perms2str($arr['deny_cid']); -// $deny_gid = perms2str($arr['deny_gid']); + $str_group_allow = perms2str($arr['group_allow']); + $str_contact_allow = perms2str($arr['contact_allow']); + $str_group_deny = perms2str($arr['group_deny']); + $str_contact_deny = perms2str($arr['contact_deny']); $r = q("insert into menu_item ( mitem_link, mitem_desc, mitem_flags, allow_cid, allow_gid, deny_cid, deny_gid, mitem_channel_id, mitem_menu_id, mitem_order ) values ( '%s', '%s', %d, '%s', '%s', '%s', '%s', %d, %d, %d ) ", dbesc($mitem_link), @@ -283,25 +262,10 @@ function menu_edit_item($menu_id, $uid, $arr) { $channel = get_app()->get_channel(); } - if ((! $arr['contact_allow']) - && (! $arr['group_allow']) - && (! $arr['contact_deny']) - && (! $arr['group_deny'])) { - $str_group_allow = $channel['channel_allow_gid']; - $str_contact_allow = $channel['channel_allow_cid']; - $str_group_deny = $channel['channel_deny_gid']; - $str_contact_deny = $channel['channel_deny_cid']; - } - else { - - // use the posted permissions - - $str_group_allow = perms2str($arr['group_allow']); - $str_contact_allow = perms2str($arr['contact_allow']); - $str_group_deny = perms2str($arr['group_deny']); - $str_contact_deny = perms2str($arr['contact_deny']); - } - + $str_group_allow = perms2str($arr['group_allow']); + $str_contact_allow = perms2str($arr['contact_allow']); + $str_group_deny = perms2str($arr['group_deny']); + $str_contact_deny = perms2str($arr['contact_deny']); $r = q("update menu_item set mitem_link = '%s', mitem_desc = '%s', mitem_flags = %d, allow_cid = '%s', allow_gid = '%s', deny_cid = '%s', deny_gid = '%s', mitem_order = %d where mitem_channel_id = %d and mitem_menu_id = %d and mitem_id = %d", dbesc($mitem_link), -- cgit v1.2.3 From 71117628bc0cba92b75caea46379b45c64c2cf43 Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Sun, 19 Apr 2015 15:22:50 +0200 Subject: attach an id to menues, allow $menu_title to be empty, if no custom menu class is provided use default redbasic classes --- include/menu.php | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) (limited to 'include') diff --git a/include/menu.php b/include/menu.php index fe62d8d32..b4f4555a5 100644 --- a/include/menu.php +++ b/include/menu.php @@ -25,6 +25,7 @@ function menu_fetch($name,$uid,$observer_xchan) { } function menu_render($menu, $class='', $edit = false) { + if(! $menu) return ''; @@ -40,6 +41,7 @@ function menu_render($menu, $class='', $edit = false) { '$menu' => $menu['menu'], '$class' => $class, '$edit' => (($edit) ? t("Edit") : ''), + '$id' => $menu['menu']['menu_id'], '$items' => $menu['items'] )); } @@ -60,14 +62,13 @@ function menu_fetch_id($menu_id,$channel_id) { function menu_create($arr) { - $menu_name = trim(escape_tags($arr['menu_name'])); $menu_desc = trim(escape_tags($arr['menu_desc'])); $menu_flags = intval($arr['menu_flags']); - - if(! $menu_desc) - $menu_desc = $menu_name; + //allow menu_desc (title) to be empty + //if(! $menu_desc) + // $menu_desc = $menu_name; if(! $menu_name) return false; @@ -144,8 +145,9 @@ function menu_edit($arr) { $menu_desc = trim(escape_tags($arr['menu_desc'])); $menu_flags = intval($arr['menu_flags']); - if(! $menu_desc) - $menu_desc = $menu_name; + //allow menu_desc (title) to be empty + //if(! $menu_desc) + // $menu_desc = $menu_name; if(! $menu_name) return false; -- cgit v1.2.3 From 01efda6850db9347351f290da6026d6cbc0abe49 Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 19 Apr 2015 13:41:12 -0700 Subject: api - unobscure mail --- include/api.php | 8 ++++---- include/text.php | 11 +++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) (limited to 'include') diff --git a/include/api.php b/include/api.php index e4b28bc54..4b413a835 100644 --- a/include/api.php +++ b/include/api.php @@ -1588,7 +1588,7 @@ require_once('include/items.php'); return($as); } - function api_format_messages($item, $recipient, $sender) { + function api_format_message($item, $recipient, $sender) { // standard meta information $ret = array( 'id' => $item['id'], @@ -1600,7 +1600,7 @@ require_once('include/items.php'); 'recipient_screen_name' => $recipient['screen_name'], 'recipient' => $recipient, ); - unobscure($item); + unobscure_mail($item); //don't send title to regular StatusNET requests to avoid confusing these apps if (x($_GET, 'getText')) { $ret['title'] = $item['title'] ; @@ -1963,7 +1963,7 @@ require_once('include/items.php'); if ($id>-1) { $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id)); - $ret = api_format_messages($r[0], $recipient, $sender); + $ret = api_format_message($r[0], $recipient, $sender); } else { $ret = array("error"=>$id); @@ -2028,7 +2028,7 @@ require_once('include/items.php'); $sender = $user_info; } - $ret[]=api_format_messages($item, $recipient, $sender); + $ret[]=api_format_message($item, $recipient, $sender); } } diff --git a/include/text.php b/include/text.php index f1f6d41f0..f8a990f58 100644 --- a/include/text.php +++ b/include/text.php @@ -1188,6 +1188,17 @@ function unobscure(&$item) { } } +function unobscure_mail(&$item) { + if(array_key_exists('mail_flags',$item) && ($item['mail_flags'] & MAIL_OBSCURED)) { + $key = get_config('system','prvkey'); + if($item['title']) + $item['title'] = crypto_unencapsulate(json_decode_plus($item['title']),$key); + if($item['body']) + $item['body'] = crypto_unencapsulate(json_decode_plus($item['body']),$key); + } +} + + function theme_attachments(&$item) { $arr = json_decode_plus($item['attach']); -- cgit v1.2.3 From 6511d5ee2c6a29a4e49fc2202df61e144ec37686 Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 19 Apr 2015 17:39:17 -0700 Subject: some api cleanup --- include/api.php | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) (limited to 'include') diff --git a/include/api.php b/include/api.php index 4b413a835..605c57827 100644 --- a/include/api.php +++ b/include/api.php @@ -267,7 +267,7 @@ require_once('include/items.php'); * Returns user info array. */ - function api_get_user(&$a, $contact_id = Null){ + function api_get_user(&$a, $contact_id = null){ global $called_api; $user = null; $extra_query = ""; @@ -394,7 +394,7 @@ require_once('include/items.php'); 'utc_offset' => "+00:00", 'time_zone' => 'UTC', //$uinfo[0]['timezone'], 'geo_enabled' => false, - 'statuses_count' => intval($countitms), #XXX: fix me + 'statuses_count' => intval($countitms), //#XXX: fix me 'lang' => get_app()->language, 'description' => (($profile) ? $profile[0]['pdesc'] : ''), 'followers_count' => intval($countfollowers), @@ -410,10 +410,13 @@ require_once('include/items.php'); 'profile_background_tile' => false, 'profile_use_background_image' => false, 'notifications' => false, - 'following' => '', #XXX: fix me - 'verified' => true, #XXX: fix me - 'status' => api_get_status($uinfo[0]['xchan_hash']) + 'following' => '', // #XXX: fix me + 'verified' => true // #XXX: fix me ); + + $x = api_get_status($uinfo[0]['xchan_hash']); + if($x) + $ret['status'] = $x; return $ret; @@ -446,12 +449,12 @@ require_once('include/items.php'); 'description' => '', 'profile_image_url' => $item['author']['xchan_photo_m'], 'url' => $item['author']['xchan_url'], - 'protected' => false, # + 'protected' => false, 'followers_count' => 0, 'friends_count' => 0, 'created_at' => '', 'favourites_count' => 0, - 'utc_offset' => 0, #XXX: fix me + 'utc_offset' => 0, // #XXX: fix me 'time_zone' => '', //$uinfo[0]['timezone'], 'statuses_count' => 0, 'following' => 1, @@ -460,7 +463,7 @@ require_once('include/items.php'); 'uid' => 0, 'contact_url' => 0, 'geo_enabled' => false, - 'lang' => 'en', #XXX: fix me + 'lang' => 'en', // #XXX: fix me 'contributors_enabled' => false, 'follow_request_sent' => false, 'profile_background_color' => 'cfe8f6', @@ -471,9 +474,8 @@ require_once('include/items.php'); 'profile_background_image_url' => '', 'profile_background_tile' => false, 'profile_use_background_image' => false, - 'verified' => true, #XXX: fix me - 'followers' => '', #XXX: fix me - 'status' => api_get_status($item['author_xchan']) + 'verified' => true, // #XXX: fix me + 'followers' => '' // #XXX: fix me ); return $ret; @@ -1638,6 +1640,8 @@ require_once('include/items.php'); localize_item($item); $status_user = (($item['author_xchan']==$user_info['guid'])?$user_info: api_item_get_user($a,$item)); + if(array_key_exists('status',$status_user)) + unset($status_user['status']); if($item['parent'] != $item['id']) { $r = q("select id from item where parent= %d and id < %d order by id desc limit 1", -- cgit v1.2.3 From 185ce2da69836a66644bfab4941eba82af19f651 Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 19 Apr 2015 18:14:17 -0700 Subject: assorted fixes to api direct messages --- include/api.php | 66 ++++++++++++++++++++++++++++++--------------------------- 1 file changed, 35 insertions(+), 31 deletions(-) (limited to 'include') diff --git a/include/api.php b/include/api.php index 605c57827..5347d498d 100644 --- a/include/api.php +++ b/include/api.php @@ -267,40 +267,46 @@ require_once('include/items.php'); * Returns user info array. */ - function api_get_user(&$a, $contact_id = null){ + function api_get_user(&$a, $contact_id = null, $contact_xchan = null){ global $called_api; $user = null; $extra_query = ""; - if(!is_null($contact_id)){ - $user=$contact_id; - $extra_query = " AND abook_id = %d "; - } - - if(is_null($user) && x($_GET, 'user_id')) { - $user = intval($_GET['user_id']); - $extra_query = " AND abook_id = %d "; - } - if(is_null($user) && x($_GET, 'screen_name')) { - $user = dbesc($_GET['screen_name']); - $extra_query = " AND xchan_addr like '%s@%%' "; - if (api_user()!==false) - $extra_query .= " AND abook_channel = ".intval(api_user()); + if(! is_null($contact_xchan)) { + $user = local_channel(); + $extra_query = " and abook_xchan = '" . dbesc($contact_xchan) . "' "; } + else { + if(!is_null($contact_id)){ + $user=$contact_id; + $extra_query = " AND abook_id = %d "; + } - if (is_null($user) && argc() > (count($called_api)-1)){ - $argid = count($called_api); - list($user, $null) = explode(".",argv($argid)); - if(is_numeric($user)){ - $user = intval($user); + if(is_null($user) && x($_GET, 'user_id')) { + $user = intval($_GET['user_id']); $extra_query = " AND abook_id = %d "; - } else { - $user = dbesc($user); + } + if(is_null($user) && x($_GET, 'screen_name')) { + $user = dbesc($_GET['screen_name']); $extra_query = " AND xchan_addr like '%s@%%' "; - if (api_user() !== false) + if (api_user()!==false) $extra_query .= " AND abook_channel = ".intval(api_user()); } + + if (is_null($user) && argc() > (count($called_api)-1)){ + $argid = count($called_api); + list($user, $null) = explode(".",argv($argid)); + if(is_numeric($user)){ + $user = intval($user); + $extra_query = " AND abook_id = %d "; + } else { + $user = dbesc($user); + $extra_query = " AND xchan_addr like '%s@%%' "; + if (api_user() !== false) + $extra_query .= " AND abook_channel = ".intval(api_user()); + } + } } if (! $user) { @@ -2021,15 +2027,13 @@ require_once('include/items.php'); $ret = Array(); if($r) { foreach($r as $item) { - if ($box == "inbox" || $item['from-url'] != $profile_url){ - $recipient = $user_info; - // fixme to lookup recipient - $sender = api_get_user($a); - } - elseif ($box == "sentbox" || $item['from-url'] != $profile_url){ - // fixme to lookup recipient - $recipient = api_get_user($a); + if ($item['from_xchan'] == $channel['channel_hash']) { $sender = $user_info; + $recipient = api_get_user($a, null, $item['to_xchan']); + } + else { + $sender = api_get_user($a, null, $item['from_xchan']); + $recipient = $user_info; } $ret[]=api_format_message($item, $recipient, $sender); -- cgit v1.2.3 From f315c55d32e5db0d3e6219bee1da7c7cbd5e217b Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 19 Apr 2015 18:57:12 -0700 Subject: api performance enhancer --- include/api.php | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) (limited to 'include') diff --git a/include/api.php b/include/api.php index 5347d498d..e96ebe2fb 100644 --- a/include/api.php +++ b/include/api.php @@ -824,7 +824,6 @@ require_once('include/items.php'); and author_xchan = '%s' and allow_cid = '' and allow_gid = '' and deny_cid = '' and deny_gid = '' and verb = '%s' - and uid in ( " . stream_perms_api_uids() . " ) order by created desc limit 1", dbesc($xchan_hash), dbesc(ACTIVITY_POST) @@ -889,7 +888,6 @@ require_once('include/items.php'); and author_xchan = '%s' and allow_cid = '' and allow_gid = '' and deny_cid = '' and deny_gid = '' and verb = '%s' - and uid in ( " . stream_perms_api_uids() . " ) order by created desc limit 1", dbesc($user_info['guid']), dbesc(ACTIVITY_POST) @@ -963,7 +961,6 @@ require_once('include/items.php'); and author_xchan = '%s' and allow_cid = '' and allow_gid = '' and deny_cid = '' and deny_gid = '' and verb = '%s' - and uid in ( " . stream_perms_api_uids() . " ) order by created desc limit 1", dbesc($user_info['guid']), dbesc(ACTIVITY_POST) @@ -1109,8 +1106,8 @@ require_once('include/items.php'); if (api_user()===false) return false; $user_info = api_get_user($a); - // get last newtork messages + $sys = get_sys_channel(); // params $count = (x($_REQUEST,'count')?$_REQUEST['count']:20); @@ -1132,7 +1129,7 @@ require_once('include/items.php'); and allow_cid = '' and allow_gid = '' and deny_cid = '' and deny_gid = '' and item_private = 0 - and uid in ( " . stream_perms_api_uids() . " ) + and uid = " . $sys['channel_id'] . " $sql_extra AND id > %d group by mid order by received desc LIMIT %d OFFSET %d ", -- cgit v1.2.3 From d5f4a19a77789a470715836b0974561694f2b08f Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 19 Apr 2015 20:37:24 -0700 Subject: add favorites/create and destroy to api --- include/api.php | 173 ++++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 137 insertions(+), 36 deletions(-) (limited to 'include') diff --git a/include/api.php b/include/api.php index e96ebe2fb..5a33cdc68 100644 --- a/include/api.php +++ b/include/api.php @@ -294,14 +294,14 @@ require_once('include/items.php'); $extra_query .= " AND abook_channel = ".intval(api_user()); } - if (is_null($user) && argc() > (count($called_api)-1)){ + if (is_null($user) && argc() > (count($called_api)-1) && (strstr($a->cmd,'/users'))){ $argid = count($called_api); - list($user, $null) = explode(".",argv($argid)); - if(is_numeric($user)){ - $user = intval($user); + list($xx, $null) = explode(".",argv($argid)); + if(is_numeric($xx)){ + $user = intval($xx); $extra_query = " AND abook_id = %d "; } else { - $user = dbesc($user); + $user = dbesc($xx); $extra_query = " AND xchan_addr like '%s@%%' "; if (api_user() !== false) $extra_query .= " AND abook_channel = ".intval(api_user()); @@ -322,11 +322,13 @@ require_once('include/items.php'); logger('api_user: ' . $extra_query . ', user: ' . $user); // user info + $uinfo = q("SELECT * from abook left join xchan on abook_xchan = xchan_hash WHERE 1 $extra_query", $user ); + if (count($uinfo)==0) { return False; } @@ -423,7 +425,9 @@ require_once('include/items.php'); $x = api_get_status($uinfo[0]['xchan_hash']); if($x) $ret['status'] = $x; - + +// logger('api_get_user: ' . print_r($ret,true)); + return $ret; } @@ -1476,58 +1480,155 @@ require_once('include/items.php'); api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true); + + /** + * Star/unstar an item + * param: id : id of the item + * + * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid + */ + function api_favorites_create_destroy(&$a, $type){ + + logger('favorites_create_destroy'); + + if (api_user()===false) + return false; + + $action = str_replace(".".$type,"",argv(2)); + if (argc() > 3) { + $itemid = intval(argv(3)); + } else { + $itemid = intval($_REQUEST['id']); + } + + $item = q("SELECT * FROM item WHERE id = %d AND uid = %d", + intval($itemid), + intval(api_user()) + ); + + if (! $item) + return false; + + switch($action){ + case "create": + + $flags = $item[0]['item_flags'] | ITEM_STARRED; + + break; + case "destroy": + + $flags = $item[0]['item_flags'] | (~ ITEM_STARRED); + break; + default: + return false; + } + + $r = q("UPDATE item SET item_flags = %d where id = %d and uid = %d", + intval($flags), + intval($itemid), + intval(api_user()) + ); + if(! $r) + return false; + + $item = q("SELECT * FROM item WHERE id = %d AND uid = %d", + intval($itemid), + intval(api_user()) + ); + + xchan_query($item,true); + + + $user_info = api_get_user($a); + $rets = api_format_items($item,$user_info); + $ret = $rets[0]; + + $data = array('$status' => $ret); + switch($type){ + case "atom": + case "rss": + $data = api_rss_extra($a, $data, $user_info); + } + + return api_apply_template("status", $type, $data); + } + + api_register_func('api/favorites/create', 'api_favorites_create_destroy', true); + api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true); + + + function api_favorites(&$a, $type){ - if (api_user()===false) return false; + if (api_user()===false) + return false; $user_info = api_get_user($a); - // in friendica starred item are private - // return favorites only for self - logger('api_favorites: self:' . $user_info['self']); - if ($user_info['self']==0) { - $ret = array(); - } else { + // params + $count = (x($_REQUEST,'count')?$_REQUEST['count']:20); + $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0); + if($page < 0) + $page = 0; + $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0); + $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0); + $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0); + $start = $page*$count; - // params - $count = (x($_GET,'count')?$_GET['count']:20); - $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0); - if ($page<0) $page=0; - - $start = $page*$count; - - $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, - `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`, - `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn_id`, `contact`.`self`, - `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid` - FROM `item`, `contact` - WHERE `item`.`uid` = %d - AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0 - AND `item`.`starred` = 1 - AND `contact`.`id` = `item`.`contact-id` - AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0 - $sql_extra - ORDER BY `item`.`received` DESC LIMIT %d ,%d ", - intval($user_info['uid']), - intval($start), intval($count) - ); + //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false); - $ret = api_format_items($r,$user_info); + $sql_extra = ''; + if ($max_id > 0) + $sql_extra .= ' AND `item`.`id` <= '.intval($max_id); + if ($exclude_replies > 0) + $sql_extra .= ' AND `item`.`parent` = `item`.`id`'; + if (api_user() != $user_info['uid']) { + $observer = get_app()->get_observer(); + require_once('include/permissions.php'); + if(! perm_is_allowed($user_info['uid'],(($observer) ? $observer['xchan_hash'] : ''),'view_stream')) + return ''; + $sql_extra .= " and item_private = 0 "; } + $r = q("SELECT * from item WHERE uid = %d and item_restrict = 0 + and ( item_flags & %d ) > 0 $sql_extra + AND id > %d + ORDER BY received DESC LIMIT %d ,%d ", + intval($user_info['uid']), + intval(ITEM_STARRED), + intval($since_id), + intval($start), + intval($count) + ); + + xchan_query($r,true); + + $ret = api_format_items($r,$user_info); + $data = array('$statuses' => $ret); switch($type){ case "atom": case "rss": $data = api_rss_extra($a, $data, $user_info); + break; + case "as": + $as = api_format_as($a, $ret, $user_info); + $as['title'] = $a->config['sitename']." Home Timeline"; + $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all"; + return($as); + break; } return api_apply_template("timeline", $type, $data); + } api_register_func('api/favorites','api_favorites', true); + + + function api_format_as($a, $ret, $user_info) { $as = array(); -- cgit v1.2.3 From 4383564777c84408880432d2ebd9c5ac73d8afe9 Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 19 Apr 2015 21:39:45 -0700 Subject: doco updates --- include/api.php | 3 --- 1 file changed, 3 deletions(-) (limited to 'include') diff --git a/include/api.php b/include/api.php index 5a33cdc68..b9c4c45a4 100644 --- a/include/api.php +++ b/include/api.php @@ -2200,9 +2200,6 @@ logger('Req: ' . var_export($req,true)); /* Not implemented by now: -favorites -favorites/create -favorites/destroy statuses/retweets_of_me friendships/create friendships/destroy -- cgit v1.2.3 From 9cc8b44579ad0620d79c675b3449461db8d4e732 Mon Sep 17 00:00:00 2001 From: friendica Date: Sun, 19 Apr 2015 23:04:14 -0700 Subject: issue #157, provide default directory sort order --- include/dir_fns.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'include') diff --git a/include/dir_fns.php b/include/dir_fns.php index d1e26b637..ebaa7c427 100644 --- a/include/dir_fns.php +++ b/include/dir_fns.php @@ -116,7 +116,13 @@ function dir_sort_links() { // Build urls without order and pubforums so it's easy to tack on the changed value // Probably there's an easier way to do this - $current_order = (($_REQUEST['order']) ? $_REQUEST['order'] : 'date'); + + $directory_sort_order = get_config('system','directory_sort_order'); + if(! $directory_sort_order) + $directory_sort_order = 'date'; + + + $current_order = (($_REQUEST['order']) ? $_REQUEST['order'] : $directory_sort_order); $url = 'directory?f='; $tmp = array_merge($_GET,$_POST); -- cgit v1.2.3 From 3eeea9d8f04064f26c7e31d590f7bf7ced140367 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 20 Apr 2015 17:02:45 -0700 Subject: force event obj_type on update --- include/event.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'include') diff --git a/include/event.php b/include/event.php index 05f01535c..5926b50f7 100644 --- a/include/event.php +++ b/include/event.php @@ -424,7 +424,7 @@ function event_store_item($arr, $event) { $private = (($arr['allow_cid'] || $arr['allow_gid'] || $arr['deny_cid'] || $arr['deny_gid']) ? 1 : 0); - q("UPDATE item SET title = '%s', body = '%s', object = '%s', allow_cid = '%s', allow_gid = '%s', deny_cid = '%s', deny_gid = '%s', edited = '%s', item_flags = %d, item_private = %d WHERE id = %d AND uid = %d", + q("UPDATE item SET title = '%s', body = '%s', object = '%s', allow_cid = '%s', allow_gid = '%s', deny_cid = '%s', deny_gid = '%s', edited = '%s', item_flags = %d, item_private = %d, obj_type = '%s' WHERE id = %d AND uid = %d", dbesc($arr['summary']), dbesc($prefix . format_event_bbcode($arr)), dbesc($object), @@ -435,6 +435,7 @@ function event_store_item($arr, $event) { dbesc($arr['edited']), intval($r[0]['item_flags']), intval($private), + dbesc(ACTIVITY_OBJ_EVENT), intval($r[0]['id']), intval($arr['uid']) ); -- cgit v1.2.3 From 53339d19a391e66635c21199484f1e4afa7b2ec7 Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 20 Apr 2015 20:14:07 -0700 Subject: issue #176, sender copy of item not obscured if using private mention --- include/items.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'include') diff --git a/include/items.php b/include/items.php index 01f207878..3fb1f3cfe 100755 --- a/include/items.php +++ b/include/items.php @@ -4813,7 +4813,7 @@ function item_remove_cid($xchan_hash,$mid,$uid) { } // Set item permissions based on results obtained from linkify_tags() -function set_linkified_perms($linkified, &$str_contact_allow, &$str_group_allow, $profile_uid, $parent_item = false) { +function set_linkified_perms($linkified, &$str_contact_allow, &$str_group_allow, $profile_uid, $parent_item = false, &$private) { $first_access_tag = true; foreach($linkified as $x) { @@ -4835,10 +4835,12 @@ function set_linkified_perms($linkified, &$str_contact_allow, &$str_group_allow, if(strpos($access_tag,'cid:') === 0) { $str_contact_allow .= '<' . substr($access_tag,4) . '>'; $access_tag = ''; + $private = 1; } elseif(strpos($access_tag,'gid:') === 0) { $str_group_allow .= '<' . substr($access_tag,4) . '>'; $access_tag = ''; + $private = 1; } } } -- cgit v1.2.3 From 6bc2766d79388ce6f813c429348cbc50d9afadaa Mon Sep 17 00:00:00 2001 From: friendica Date: Mon, 20 Apr 2015 20:49:55 -0700 Subject: issue #162 --- include/js_strings.php | 1 + 1 file changed, 1 insertion(+) (limited to 'include') diff --git a/include/js_strings.php b/include/js_strings.php index 84c1d70fb..cae8da5de 100644 --- a/include/js_strings.php +++ b/include/js_strings.php @@ -21,6 +21,7 @@ function js_strings() { '$rating_text' => t('Describe (optional)'), '$submit' => t('Submit'), '$linkurl' => t('Please enter a link URL'), + '$leavethispage' => t('Unsaved changes. Are you sure you wish to leave this page?'), '$t01' => ((t('timeago.prefixAgo') != 'timeago.prefixAgo') ? t('timeago.prefixAgo') : ''), '$t02' => ((t('timeago.prefixFromNow') != 'timeago.prefixFromNow') ? t('timeago.prefixFromNow') : ''), -- cgit v1.2.3 From 2cef6c3ac5689d02ced23d775a804cc879537907 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 21 Apr 2015 21:41:39 -0700 Subject: use PERMS_SPECIFIC for anything that hasn't been specified. This way there's nothing that's "only yourself", and let's you add additional permissions at will rather than be forced to accept the defaults or turn on custom permissions just to give a friend delegation rights or the ability to post photos. --- include/permissions.php | 48 ++++++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 24 deletions(-) (limited to 'include') diff --git a/include/permissions.php b/include/permissions.php index 82145066b..68ff2b3d4 100644 --- a/include/permissions.php +++ b/include/permissions.php @@ -422,12 +422,12 @@ function site_default_perms() { 'post_wall' => PERMS_SPECIFIC, 'post_comments' => PERMS_SPECIFIC, 'post_mail' => PERMS_SPECIFIC, - 'post_photos' => 0, + 'post_photos' => PERMS_SPECIFIC, 'tag_deliver' => PERMS_SPECIFIC, 'chat' => PERMS_SPECIFIC, - 'write_storage' => 0, - 'write_pages' => 0, - 'delegate' => 0, + 'write_storage' => PERMS_SPECIFIC, + 'write_pages' => PERMS_SPECIFIC, + 'delegate' => PERMS_SPECIFIC, 'post_like' => PERMS_NETWORK ); @@ -487,13 +487,13 @@ function get_role_perms($role) { $ret['channel_w_tagwall'] = PERMS_SPECIFIC; $ret['channel_w_comment'] = PERMS_SPECIFIC; $ret['channel_w_mail'] = PERMS_SPECIFIC; - $ret['channel_w_photos'] = 0; + $ret['channel_w_photos'] = PERMS_SPECIFIC; $ret['channel_w_chat'] = PERMS_SPECIFIC; - $ret['channel_a_delegate'] = 0; + $ret['channel_a_delegate'] = PERMS_SPECIFIC; $ret['channel_r_storage'] = PERMS_PUBLIC; - $ret['channel_w_storage'] = 0; + $ret['channel_w_storage'] = PERMS_SPECIFIC; $ret['channel_r_pages'] = PERMS_PUBLIC; - $ret['channel_w_pages'] = 0; + $ret['channel_w_pages'] = PERMS_SPECIFIC; $ret['channel_a_republish'] = PERMS_SPECIFIC; $ret['channel_w_like'] = PERMS_NETWORK; @@ -519,13 +519,13 @@ function get_role_perms($role) { $ret['channel_w_tagwall'] = PERMS_SPECIFIC; $ret['channel_w_comment'] = PERMS_SPECIFIC; $ret['channel_w_mail'] = PERMS_SPECIFIC; - $ret['channel_w_photos'] = 0; + $ret['channel_w_photos'] = PERMS_SPECIFIC; $ret['channel_w_chat'] = PERMS_SPECIFIC; - $ret['channel_a_delegate'] = 0; + $ret['channel_a_delegate'] = PERMS_SPECIFIC; $ret['channel_r_storage'] = PERMS_PUBLIC; - $ret['channel_w_storage'] = 0; + $ret['channel_w_storage'] = PERMS_SPECIFIC; $ret['channel_r_pages'] = PERMS_PUBLIC; - $ret['channel_w_pages'] = 0; + $ret['channel_w_pages'] = PERMS_SPECIFIC; $ret['channel_a_republish'] = PERMS_SPECIFIC; $ret['channel_w_like'] = PERMS_SPECIFIC; @@ -551,13 +551,13 @@ function get_role_perms($role) { $ret['channel_w_tagwall'] = PERMS_SPECIFIC; $ret['channel_w_comment'] = PERMS_SPECIFIC; $ret['channel_w_mail'] = PERMS_SPECIFIC; - $ret['channel_w_photos'] = 0; + $ret['channel_w_photos'] = PERMS_SPECIFIC; $ret['channel_w_chat'] = PERMS_SPECIFIC; - $ret['channel_a_delegate'] = 0; + $ret['channel_a_delegate'] = PERMS_SPECIFIC; $ret['channel_r_storage'] = PERMS_PUBLIC; - $ret['channel_w_storage'] = 0; + $ret['channel_w_storage'] = PERMS_SPECIFIC; $ret['channel_r_pages'] = PERMS_PUBLIC; - $ret['channel_w_pages'] = 0; + $ret['channel_w_pages'] = PERMS_SPECIFIC; $ret['channel_a_republish'] = PERMS_SPECIFIC; $ret['channel_w_like'] = PERMS_SPECIFIC; @@ -679,13 +679,13 @@ function get_role_perms($role) { $ret['channel_w_tagwall'] = PERMS_SPECIFIC; $ret['channel_w_comment'] = PERMS_SPECIFIC; $ret['channel_w_mail'] = PERMS_SPECIFIC; - $ret['channel_w_photos'] = 0; + $ret['channel_w_photos'] = PERMS_SPECIFIC; $ret['channel_w_chat'] = PERMS_SPECIFIC; - $ret['channel_a_delegate'] = 0; + $ret['channel_a_delegate'] = PERMS_SPECIFIC; $ret['channel_r_storage'] = PERMS_PUBLIC; - $ret['channel_w_storage'] = 0; + $ret['channel_w_storage'] = PERMS_SPECIFIC; $ret['channel_r_pages'] = PERMS_PUBLIC; - $ret['channel_w_pages'] = 0; + $ret['channel_w_pages'] = PERMS_SPECIFIC; $ret['channel_a_republish'] = PERMS_NETWORK; $ret['channel_w_like'] = PERMS_NETWORK; @@ -711,13 +711,13 @@ function get_role_perms($role) { $ret['channel_w_tagwall'] = PERMS_SPECIFIC; $ret['channel_w_comment'] = PERMS_SPECIFIC; $ret['channel_w_mail'] = PERMS_SPECIFIC; - $ret['channel_w_photos'] = 0; + $ret['channel_w_photos'] = PERMS_SPECIFIC; $ret['channel_w_chat'] = PERMS_SPECIFIC; - $ret['channel_a_delegate'] = 0; + $ret['channel_a_delegate'] = PERMS_SPECIFIC; $ret['channel_r_storage'] = PERMS_PUBLIC; - $ret['channel_w_storage'] = 0; + $ret['channel_w_storage'] = PERMS_SPECIFIC; $ret['channel_r_pages'] = PERMS_PUBLIC; - $ret['channel_w_pages'] = 0; + $ret['channel_w_pages'] = PERMS_SPECIFIC; $ret['channel_a_republish'] = PERMS_SPECIFIC; $ret['channel_w_like'] = PERMS_NETWORK; -- cgit v1.2.3 From 9e490d022b985f295a0547c8a115c610a77a3a24 Mon Sep 17 00:00:00 2001 From: Mario Vavti Date: Wed, 22 Apr 2015 12:00:15 +0200 Subject: fix webpage perms --- include/conversation.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/conversation.php b/include/conversation.php index 5ae2250a8..19c5bda14 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -1637,7 +1637,7 @@ function profile_tabs($a, $is_owner = false, $nickname = null){ ); } - if ($is_owner && feature_enabled($uid,'webpages')) { + if ($p['write_pages'] && feature_enabled($uid,'webpages')) { $tabs[] = array( 'label' => t('Webpages'), 'url' => $a->get_baseurl() . '/webpages/' . $nickname, -- cgit v1.2.3