diff options
author | Max Kostikov <max@kostikov.co> | 2021-02-20 13:39:54 +0000 |
---|---|---|
committer | Max Kostikov <max@kostikov.co> | 2021-02-20 13:39:54 +0000 |
commit | cc5571687971ddcc097abb5e5c57689005d5b070 (patch) | |
tree | 1b2ed0f46b307f09d109350f777438fd04742905 /include | |
parent | e1d622c49f95aec51e5c1bd521dcd6fe2a9a5372 (diff) | |
parent | ddad4f604b56656086b32992ef98709be2568a37 (diff) | |
download | volse-hubzilla-cc5571687971ddcc097abb5e5c57689005d5b070.tar.gz volse-hubzilla-cc5571687971ddcc097abb5e5c57689005d5b070.tar.bz2 volse-hubzilla-cc5571687971ddcc097abb5e5c57689005d5b070.zip |
Merge branch 'dev' into 'dev'
Dev sync
See merge request kostikov/core!1
Diffstat (limited to 'include')
-rw-r--r-- | include/account.php | 36 | ||||
-rw-r--r-- | include/bbcode.php | 125 | ||||
-rw-r--r-- | include/channel.php | 17 | ||||
-rw-r--r-- | include/conversation.php | 10 | ||||
-rw-r--r-- | include/crypto.php | 159 | ||||
-rw-r--r-- | include/dir_fns.php | 3 | ||||
-rw-r--r-- | include/follow.php | 18 | ||||
-rw-r--r-- | include/help.php | 1 | ||||
-rw-r--r-- | include/html2plain.php | 8 | ||||
-rw-r--r-- | include/items.php | 52 | ||||
-rw-r--r-- | include/message.php | 32 | ||||
-rw-r--r-- | include/nav.php | 341 | ||||
-rw-r--r-- | include/oembed.php | 74 | ||||
-rw-r--r-- | include/plugin.php | 5 | ||||
-rw-r--r-- | include/security.php | 1 | ||||
-rw-r--r-- | include/text.php | 11 | ||||
-rw-r--r-- | include/xchan.php | 13 | ||||
-rw-r--r-- | include/zid.php | 12 | ||||
-rw-r--r-- | include/zot.php | 118 |
19 files changed, 581 insertions, 455 deletions
diff --git a/include/account.php b/include/account.php index bea84cea7..34936c33f 100644 --- a/include/account.php +++ b/include/account.php @@ -4,6 +4,8 @@ * @brief Somme account related functions. */ +use Zotlabs\Lib\Crypto; + require_once('include/config.php'); require_once('include/network.php'); require_once('include/plugin.php'); @@ -26,8 +28,8 @@ function check_account_email($email) { $email = punify($email); $result = array('error' => false, 'message' => ''); - // Caution: empty email isn't counted as an error in this function. - // Check for empty value separately. + // Caution: empty email isn't counted as an error in this function. + // Check for empty value separately. if(! strlen($email)) return $result; @@ -36,7 +38,7 @@ function check_account_email($email) { $result['message'] .= t('Not a valid email address') . EOL; elseif(! allowed_email($email)) $result['message'] = t('Your email domain is not among those allowed on this site'); - else { + else { $r = q("select account_email from account where account_email = '%s' limit 1", dbesc($email) ); @@ -175,7 +177,7 @@ function create_account($arr) { // Ensure that there is a host keypair. if ((! get_config('system', 'pubkey')) && (! get_config('system', 'prvkey'))) { - $hostkey = new_keypair(4096); + $hostkey = Crypto::new_keypair(4096); set_config('system', 'pubkey', $hostkey['pubkey']); set_config('system', 'prvkey', $hostkey['prvkey']); } @@ -306,8 +308,8 @@ function verify_email_address($arr) { ); $res = z_mail( - [ - 'toEmail' => $arr['email'], + [ + 'toEmail' => $arr['email'], 'messageSubject' => sprintf( t('Registration confirmation for %s'), get_config('system','sitename')), 'textVersion' => $email_msg, ] @@ -375,8 +377,8 @@ function send_reg_approval_email($arr) { )); $res = z_mail( - [ - 'toEmail' => $admin['email'], + [ + 'toEmail' => $admin['email'], 'messageSubject' => sprintf( t('Registration request at %s'), get_config('system','sitename')), 'textVersion' => $email_msg, ] @@ -403,7 +405,7 @@ function send_register_success_email($email,$password) { )); $res = z_mail( - [ + [ 'toEmail' => $email, 'messageSubject' => sprintf( t('Registration details for %s'), get_config('system','sitename')), 'textVersion' => $email_msg, @@ -446,7 +448,7 @@ function account_allow($hash) { intval(ACCOUNT_BLOCKED), intval($register[0]['uid']) ); - + q("update account set account_flags = (account_flags & ~%d) where (account_flags & %d)>0 and account_id = %d", intval(ACCOUNT_PENDING), intval(ACCOUNT_PENDING), @@ -466,7 +468,7 @@ function account_allow($hash) { )); $res = z_mail( - [ + [ 'toEmail' => $account[0]['account_email'], 'messageSubject' => sprintf( t('Registration details for %s'), get_config('system','sitename')), 'textVersion' => $email_msg, @@ -556,13 +558,13 @@ function account_approve($hash) { intval(ACCOUNT_BLOCKED), intval($register[0]['uid']) ); - + q("update account set account_flags = (account_flags & ~%d) where (account_flags & %d)>0 and account_id = %d", intval(ACCOUNT_PENDING), intval(ACCOUNT_PENDING), intval($register[0]['uid']) ); - + q("update account set account_flags = (account_flags & ~%d) where (account_flags & %d)>0 and account_id = %d", intval(ACCOUNT_UNVERIFIED), intval(ACCOUNT_UNVERIFIED), @@ -583,7 +585,7 @@ function account_approve($hash) { else { $_SESSION['login_return_url'] = 'new_channel'; authenticate_success($account[0],null,true,true,false,true); - } + } return true; } @@ -592,14 +594,14 @@ function account_approve($hash) { /** * @brief Checks for accounts that have past their expiration date. * - * If the account has a service class which is not the site default, + * 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. * called from include/poller.php as a scheduled task. * * Reclaiming resources which are no longer within the service class limits is - * 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. + * 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() { diff --git a/include/bbcode.php b/include/bbcode.php index e1a5c7e47..5a71ada0c 100644 --- a/include/bbcode.php +++ b/include/bbcode.php @@ -80,7 +80,7 @@ function tryoembed($match) { return $match[0]; $html = oembed_format_object($o); - return $html; + return $html; } @@ -92,7 +92,7 @@ function nakedoembed($match) { // this function no longer performs oembed on naked links // because they author may have created naked links intentionally. // Now it just strips zids on naked links. - + return str_replace($url,$strip_url,$match[0]); } @@ -272,6 +272,26 @@ function bb_parse_crypt($match) { return $Text; } +/** + * @brief Returns raw base64 encoded crypt content. + * + * @param array $match + * @return string + */ +function bb_parse_b64_crypt($match) { + + if(empty($match[2])) + return; + + $r .= '----- ENCRYPTED CONTENT -----' . PHP_EOL; + $r .= $match[2] . PHP_EOL; + $r .= '----- END ENCRYPTED CONTENT -----'; + + return $r; + +} + + function bb_parse_app($match) { $app = Zotlabs\Lib\Apps::app_decode($match[1]); @@ -283,7 +303,7 @@ function bb_svg($match) { $params = str_replace(['<br>', '"'], [ '', '"'],$match[1]); $Text = str_replace([ '[',']' ], [ '<','>' ], $match[2]); - + $output = '<svg' . (($params) ? $params : ' width="100%" height="480" ') . '>' . str_replace(['<br>', '"', ' '], [ '', '"', ' '],$Text) . '</svg>'; $purify = new SvgSanitizer(); @@ -641,24 +661,24 @@ function bb_definitionList($match) { // The bbcode transformation will be: // [*=term-text] description-text => </dd> <dt>term-text<dt><dd> description-text - // then after all replacements have been made, the extra </dd> at the start of the + // then after all replacements have been made, the extra </dd> at the start of the // first line can be removed. HTML5 allows the tag to be missing from the end of the last line. // Using '(?<!\\\)' to allow backslash-escaped closing braces to appear in the term-text. $closeDescriptionTag = "</dd>\n"; $eatLeadingSpaces = '(?: |[ \t])*'; // prevent spaces infront of [*= from adding another line to the previous element $listElements = preg_replace('/^(\n|<br \/>)/', '', $match[2]); // ltrim the first newline $listElements = preg_replace( - '/' . $eatLeadingSpaces . '\[\*=([[:print:]]*?)(?<!\\\)\]/uism', - $closeDescriptionTag . '<dt>$1</dt><dd>', + '/' . $eatLeadingSpaces . '\[\*=([[:print:]]*?)(?<!\\\)\]/uism', + $closeDescriptionTag . '<dt>$1</dt><dd>', $listElements ); // Unescape any \] inside the <dt> tags $listElements = preg_replace_callback('/<dt>(.*?)<\/dt>/ism', 'bb_definitionList_unescapeBraces', $listElements); - + // Remove the extra </dd> at the start of the string, if there is one. $firstOpenTag = strpos($listElements, '<dd>'); $firstCloseTag = strpos($listElements, $closeDescriptionTag); - if ($firstCloseTag !== false && ($firstOpenTag === false || ($firstCloseTag < $firstOpenTag))) { + if ($firstCloseTag !== false && ($firstOpenTag === false || ($firstCloseTag < $firstOpenTag))) { $listElements = preg_replace( '/<\/dd>/ism', '', $listElements, 1); } @@ -802,7 +822,7 @@ function bb_imgoptions($match) { // $Text = preg_replace_callback("/\[([zi])mg([ \=])(.*?)\](.*?)\[\/[zi]mg\]/ism",'bb_imgoptions',$Text); // alt text cannot contain ']' - + // [img|zmg=wwwxhhh float=left|right alt=alt text]url[/img|zmg] $local_match = null; @@ -818,7 +838,7 @@ function bb_imgoptions($match) { if ($x) { $alt = $matches[1]; } - + $x = preg_match("/alt=\"\;(.*?)\"\;/ism", $attributes, $matches); if ($x) { $alt = $matches[1]; @@ -828,7 +848,7 @@ function bb_imgoptions($match) { if ($x) { $width = $matches[1]; } - + $x = preg_match("/width=\"\;(.*?)\"\;/ism", $attributes, $matches); if ($x) { $width = $matches[1]; @@ -838,7 +858,7 @@ function bb_imgoptions($match) { if ($x) { $height = $matches[1]; } - + $x = preg_match("/height=\"\;(.*?)\"\;/ism", $attributes, $matches); if ($x) { $height = $matches[1]; @@ -848,14 +868,14 @@ function bb_imgoptions($match) { if ($x) { $style = $matches[1]; } - + $x = preg_match("/style=\"\;(.*?)\"\;/ism", $attributes, $matches); if ($x) { $style = $matches[1]; } // legacy img options - + if ($match[2] === '=') { // pull out (optional) legacy size declarations first if (preg_match("/([0-9]*)x([0-9]*)/ism",$match[3],$local_match)) { @@ -873,16 +893,16 @@ function bb_imgoptions($match) { $float = 'right'; $match[3] = substr($match[3],$n + 11); } - + // finally alt text which extends to the close of the tag if ((! $alt) && ($n = strpos($match[3],'alt=') !== false)) { $alt = substr($match[3],$n + 4); } // now assemble the resulting img tag from these components - + $output = '<img ' . (($match[1] === 'z') ? 'class="zrl" loading="eager"' : '') . ' '; - + if ($width) { $style .= 'width: 100%; max-width: ' . $width . 'px; '; } @@ -892,13 +912,13 @@ function bb_imgoptions($match) { if ($float) { $style .= 'float: ' . $float . '; '; } - + $output .= (($style) ? 'style="' . $style . '" ' : '') . 'alt="' . htmlentities(($alt) ? $alt : t('Image/photo'),ENT_COMPAT,'UTF-8') . '" '; $output .= 'src="' . $match[4] . '" >'; - + return $output; - + } function bb_code_protect($s) { @@ -914,14 +934,14 @@ function bb_code_unprotect_sub($match) { } function bb_code($match) { - if(strpos($match[0], "<br />")) + if(strpos($match[0], PHP_EOL)) return '<pre><code>' . bb_code_protect(trim($match[1])) . '</code></pre>'; else return '<code class="inline-code">' . bb_code_protect(trim($match[1])) . '</code>'; } function bb_code_options($match) { - if(strpos($match[0], "<br />")) { + if(strpos($match[0], PHP_EOL)) { $class = ""; $pre = true; } else { @@ -935,7 +955,7 @@ function bb_code_options($match) { } if($pre) { return '<pre><code class="'. $class .'" style="'. $style .'">' . bb_code_protect(trim($match[2])) . '</code></pre>'; - } else { + } else { return '<code class="'. $class .'" style="'. $style .'">' . bb_code_protect(trim($match[2])) . '</code>'; } } @@ -949,7 +969,7 @@ function bb_fixtable_lf($match) { // remove extraneous whitespace between table element tags since newlines will all // be converted to '<br />' and turn your neatly crafted tables into a whole lot of // empty space. - + $x = preg_replace("/\]\s+\[/",'][',$match[1]); return '[table]' . $x . '[/table]'; @@ -991,7 +1011,7 @@ function parseIdentityAwareHTML($Text) { } if (strpos($Text,'[pre]') !== false) { $Text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", 'bb_spacefy',$Text); - } + } // process [observer] tags before we do anything else because we might // be stripping away stuff that then doesn't need to be worked on anymore @@ -1012,7 +1032,7 @@ function parseIdentityAwareHTML($Text) { $Text = preg_replace("/\[observer\=0\](.*?)\[\/observer\]/ism", '$1', $Text); $Text = preg_replace("/\[rpost(=.*?)?\](.*?)\[\/rpost\]/ism", '', $Text); } - } + } // replace [observer.baseurl] if ($observer) { $s1 = '<span class="bb_observer" title="' . t('Different viewers will see this text differently') . '">'; @@ -1033,11 +1053,11 @@ function parseIdentityAwareHTML($Text) { $Text = str_replace('[observer.webname]','',$Text); $Text = str_replace('[observer.photo]','', $Text); } - + $Text = str_replace(array('[baseurl]','[sitename]'),array(z_root(),get_config('system','sitename')),$Text); - - // Unhide all [noparse] contained bbtags unspacefying them + + // 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); @@ -1153,23 +1173,8 @@ function bbcode($Text, $options = []) { $Text = preg_replace_callback("/\[table\](.*?)\[\/table\]/ism",'bb_fixtable_lf',$Text); - // Convert new line chars to html <br /> tags - - // nlbr seems to be hopelessly messed up - // $Text = nl2br($Text); - - // We'll emulate it. - - $Text = str_replace("\r\n", "\n", $Text); - $Text = str_replace(array("\r", "\n"), array('<br />', '<br />'), $Text); - - if ($preserve_nl) - $Text = str_replace(array("\n", "\r"), array('', ''), $Text); - - $Text = str_replace(array("\t", " "), array(" ", " "), $Text); - // Check for [code] text if (strpos($Text,'[code]') !== false) { $Text = preg_replace_callback("/\[code\](.*?)\[\/code\]/ism", 'bb_code', $Text); @@ -1219,9 +1224,12 @@ function bbcode($Text, $options = []) { $Text = preg_replace("/([^\]\='".'"'."\;\/]|^|\#\^)(https?\:\/\/$urlchars+)/ismu", '$1<a href="$2" ' . $target . ' rel="nofollow noopener">$2</a>', $Text); } - if (strpos($Text,'[/share]') !== false) { + $count = 0; + while (strpos($Text,'[/share]') !== false && $count < 10) { $Text = preg_replace_callback("/\[share(.*?)\](.*?)\[\/share\]/ism", 'bb_ShareAttributes', $Text); + $count ++; } + if($tryoembed) { if (strpos($Text,'[/url]') !== false) { $Text = preg_replace_callback("/[^\^]\[url\]([$URLSearchString]*)\[\/url\]/ism", 'tryoembed', $Text); @@ -1266,7 +1274,7 @@ function bbcode($Text, $options = []) { $Text = preg_replace("/\[map\]/", '<div class="map"></div>', $Text); } } - + // Check for bold text if (strpos($Text,'[b]') !== false) { $Text = preg_replace("(\[b\](.*?)\[\/b\])ism", '<strong>$1</strong>', $Text); @@ -1392,8 +1400,8 @@ function bbcode($Text, $options = []) { $Text = preg_replace("/\[li\](.*?)\[\/li\]/ism", '<li>$1</li>', $Text); // [dl] tags have an optional [dl terms="bi"] form where bold/italic/underline/mono/large - // etc. style may be specified for the "terms" in the definition list. The quotation marks - // are also optional. The regex looks intimidating, but breaks down as: + // etc. style may be specified for the "terms" in the definition list. The quotation marks + // are also optional. The regex looks intimidating, but breaks down as: // "[dl" <optional-whitespace> <optional-termStyles> "]" <matchGroup2> "[/dl]" // where optional-termStyles are: "terms=" <optional-quote> <matchGroup1> <optional-quote> $Text = preg_replace_callback('/\[dl[[:space:]]*(?:terms=(?:"|")?([a-zA-Z]+)(?:"|")?)?\](.*?)\[\/dl\]/ism', 'bb_definitionList', $Text); @@ -1432,7 +1440,7 @@ function bbcode($Text, $options = []) { if(strpos($Text,'[/summary]') !== false) { - $Text = preg_replace_callback("/^(.*?)\[summary\](.*?)\[\/summary\](.*?)$/ism", 'bb_summary', $Text); + $Text = preg_replace_callback("/^(.*?)\[summary\](.*?)\[\/summary\](.*?)$/is", 'bb_summary', $Text); } // Check for [spoiler] text @@ -1579,7 +1587,7 @@ function bbcode($Text, $options = []) { // If we found an event earlier, strip out all the event code and replace with a reformatted version. // Replace the event-start section with the entire formatted event. The other bbcode is stripped. - // Summary (e.g. title) is required, earlier revisions only required description (in addition to + // 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,'dtstart')) { @@ -1588,7 +1596,7 @@ function bbcode($Text, $options = []) { $sub = str_replace('$',"\0",$sub); - $Text = preg_replace("/\[event\-start\](.*?)\[\/event\-start\]/ism",$sub,$Text); + $Text = preg_replace("/\[event\-start\](.*?)\[\/event\-start\]/ism",$sub,$Text); $Text = preg_replace("/\[event\](.*?)\[\/event\]/ism",'',$Text); $Text = preg_replace("/\[event\-summary\](.*?)\[\/event\-summary\]/ism",'',$Text); @@ -1603,7 +1611,7 @@ function bbcode($Text, $options = []) { } - // Unhide all [noparse] contained bbtags unspacefying them + // 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); @@ -1633,6 +1641,19 @@ function bbcode($Text, $options = []) { $Text = bb_replace_images($Text, $saved_images); + // Convert new line chars to html <br /> tags + + // nlbr seems to be hopelessly messed up + // $Text = nl2br($Text); + + // We'll emulate it. + + $Text = str_replace("\r\n", "\n", $Text); + $Text = str_replace(array("\r", "\n"), array('<br />', '<br />'), $Text); + + if ($preserve_nl) + $Text = str_replace(array("\n", "\r"), array('', ''), $Text); + call_hooks('bbcode', $Text); return $Text; diff --git a/include/channel.php b/include/channel.php index 2d79cd074..08b5ee889 100644 --- a/include/channel.php +++ b/include/channel.php @@ -9,6 +9,7 @@ use Zotlabs\Access\PermissionRoles; use Zotlabs\Access\PermissionLimits; use Zotlabs\Access\Permissions; use Zotlabs\Daemon\Master; +use Zotlabs\Lib\Crypto; use Zotlabs\Lib\System; use Zotlabs\Render\Comanche; use Zotlabs\Lib\Libzot; @@ -107,7 +108,7 @@ function create_sys_channel() { if ((! get_config('system', 'pubkey')) && (! get_config('system', 'prvkey'))) { require_once('include/crypto.php'); - $hostkey = new_keypair(4096); + $hostkey = Crypto::new_keypair(4096); set_config('system', 'pubkey', $hostkey['pubkey']); set_config('system', 'prvkey', $hostkey['prvkey']); } @@ -232,10 +233,10 @@ function create_identity($arr) { } $guid = Libzot::new_uid($nick); - $key = new_keypair(4096); + $key = Crypto::new_keypair(4096); // legacy zot - $zsig = base64url_encode(rsa_sign($guid,$key['prvkey'])); + $zsig = base64url_encode(Crypto::sign($guid,$key['prvkey'])); $zhash = make_xchan_hash($guid,$zsig); // zot6 @@ -345,7 +346,7 @@ function create_identity($arr) { 'hubloc_addr' => channel_reddress($ret['channel']), 'hubloc_primary' => intval($primary), 'hubloc_url' => z_root(), - 'hubloc_url_sig' => base64url_encode(rsa_sign(z_root(),$ret['channel']['channel_prvkey'])), + 'hubloc_url_sig' => base64url_encode(Crypto::sign(z_root(),$ret['channel']['channel_prvkey'])), 'hubloc_host' => App::get_hostname(), 'hubloc_callback' => z_root() . '/post', 'hubloc_sitekey' => get_config('system','pubkey'), @@ -603,9 +604,9 @@ function change_channel_keys($channel) { $stored = []; - $key = new_keypair(4096); + $key = Crypto::new_keypair(4096); - $sig = base64url_encode(rsa_sign($channel['channel_guid'],$key['prvkey'])); + $sig = base64url_encode(Crypto::sign($channel['channel_guid'],$key['prvkey'])); $hash = make_xchan_hash($channel['channel_guid'],$sig); $stored['old_guid'] = $channel['channel_guid']; @@ -614,7 +615,7 @@ function change_channel_keys($channel) { $stored['old_hash'] = $channel['channel_hash']; $stored['new_key'] = $key['pubkey']; - $stored['new_sig'] = base64url_encode(rsa_sign($key['pubkey'],$channel['channel_prvkey'])); + $stored['new_sig'] = base64url_encode(Crypto::sign($key['pubkey'],$channel['channel_prvkey'])); // Save this info for the notifier to collect @@ -651,7 +652,7 @@ function change_channel_keys($channel) { foreach($h as $hv) { $hv['hubloc_guid_sig'] = $sig; $hv['hubloc_hash'] = $hash; - $hv['hubloc_url_sig'] = base64url_encode(rsa_sign(z_root(),$modified['channel_prvkey'])); + $hv['hubloc_url_sig'] = base64url_encode(Crypto::sign(z_root(),$modified['channel_prvkey'])); hubloc_store_lowlevel($hv); } } diff --git a/include/conversation.php b/include/conversation.php index 08d16a413..ae69b7a01 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -923,7 +923,6 @@ function conversation($items, $mode, $update, $page_mode = 'traditional', $prepa // logger('nouveau: ' . print_r($threads,true)); - $o .= replace_macros($page_template, array( '$baseurl' => z_root(), '$photo_item' => $content_html, @@ -935,6 +934,7 @@ function conversation($items, $mode, $update, $page_mode = 'traditional', $prepa '$wait' => t('Loading...'), '$conversation_tools' => t('Conversation Tools'), '$dropping' => ($page_dropping?t('Delete Selected Items'):False), + '$preview' => $preview )); return $o; @@ -1474,7 +1474,9 @@ function hz_status_editor($a, $x, $popup = false) { '$nocomment' => ((array_key_exists('item',$x)) ? $x['item']['item_nocomment'] : 0), '$clearloc' => $clearloc, '$title' => ((x($x, 'title')) ? htmlspecialchars($x['title'], ENT_COMPAT,'UTF-8') : ''), + '$summary' => ((x($x, 'summary')) ? htmlspecialchars($x['summary'], ENT_COMPAT,'UTF-8') : ''), '$placeholdertitle' => ((x($x, 'placeholdertitle')) ? $x['placeholdertitle'] : t('Title (optional)')), + '$placeholdersummary' => ((x($x, 'placeholdersummary')) ? $x['placeholdersummary'] : t('Summary (optional)')), '$catsenabled' => $catsenabled, '$category' => ((x($x, 'category')) ? $x['category'] : ''), '$placeholdercategory' => t('Categories (optional, comma-separated list)'), @@ -1725,13 +1727,11 @@ 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]['count'] = ((x($conv_responses[$v],$item['mid'])) ? $conv_responses[$v][$item['mid']] : 0); $ret[$v]['list'] = ((x($conv_responses[$v],$item['mid'])) ? $conv_responses[$v][$item['mid'] . '-l'] : ''); $ret[$v]['button'] = get_response_button_text($v,$ret[$v]['count']); $ret[$v]['title'] = $conv_responses[$v]['title']; - if($ret[$v]['count'] > MAX_LIKERS) { - $ret[$v]['modal'] = true; - } + $ret[$v]['modal'] = (($ret[$v]['count'] > MAX_LIKERS) ? true : false); } $count = 0; diff --git a/include/crypto.php b/include/crypto.php index e2132337f..40e68a4e7 100644 --- a/include/crypto.php +++ b/include/crypto.php @@ -1,7 +1,7 @@ <?php /** @file */ -use phpseclib\Crypt\RSA; -use phpseclib\Math\BigInteger; +require_once('library/ASNValue.class.php'); +require_once('library/asn1.php'); function rsa_sign($data,$key,$alg = 'sha256') { if(! $key) @@ -163,7 +163,7 @@ function other_encapsulate($data,$pubkey,$alg) { } $result['alg'] = $alg; - $result['key'] = base64url_encode($k,true); + $result['key'] = base64url_encode($k,true); openssl_public_encrypt($iv,$i,$pubkey,$padding); $result['iv'] = base64url_encode($i,true); return $result; @@ -192,7 +192,6 @@ function crypto_methods() { function signing_methods() { - $r = [ 'sha256' ]; call_hooks('signing_methods',$r); return $r; @@ -215,7 +214,7 @@ function aes_encapsulate($data,$pubkey) { logger('aes_encapsulate: RSA failed. ' . print_r($x[0],true)); } $result['alg'] = 'aes256cbc'; - $result['key'] = base64url_encode($k,true); + $result['key'] = base64url_encode($k,true); openssl_public_encrypt($iv,$i,$pubkey); $result['iv'] = base64url_encode($i,true); return $result; @@ -226,9 +225,9 @@ function crypto_unencapsulate($data,$prvkey) { return; $alg = ((is_array($data) && (array_key_exists('encrypted',$data) || array_key_exists('iv',$data))) ? $data['alg'] : ''); - if(! $alg) { + if(! $alg) { return $data; - } + } if($alg === 'aes256cbc') { return aes_unencapsulate($data,$prvkey); @@ -308,69 +307,139 @@ function new_keypair($bits) { } -/** - * @param string $m modulo - * @param string $e exponent - * @return string - */ -function metopem($m, $e) { +function DerToPem($Der, $Private=false) +{ + //Encode: + $Der = base64_encode($Der); + //Split lines: + $lines = str_split($Der, 65); + $body = implode("\n", $lines); + //Get title: + $title = $Private? 'RSA PRIVATE KEY' : 'PUBLIC KEY'; + //Add wrapping: + $result = "-----BEGIN {$title}-----\n"; + $result .= $body . "\n"; + $result .= "-----END {$title}-----\n"; + + return $result; +} + +function DerToRsa($Der) +{ + //Encode: + $Der = base64_encode($Der); + //Split lines: + $lines = str_split($Der, 64); + $body = implode("\n", $lines); + //Get title: + $title = 'RSA PUBLIC KEY'; + //Add wrapping: + $result = "-----BEGIN {$title}-----\n"; + $result .= $body . "\n"; + $result .= "-----END {$title}-----\n"; + + return $result; +} - $rsa = new RSA(); - $rsa->loadKey([ - 'e' => new BigInteger($e, 256), - 'n' => new BigInteger($m, 256) - ]); - return $rsa->getPublicKey(); +function pkcs8_encode($Modulus,$PublicExponent) { + //Encode key sequence + $modulus = new ASNValue(ASNValue::TAG_INTEGER); + $modulus->SetIntBuffer($Modulus); + $publicExponent = new ASNValue(ASNValue::TAG_INTEGER); + $publicExponent->SetIntBuffer($PublicExponent); + $keySequenceItems = array($modulus, $publicExponent); + $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE); + $keySequence->SetSequence($keySequenceItems); + //Encode bit string + $bitStringValue = $keySequence->Encode(); + $bitStringValue = chr(0x00) . $bitStringValue; //Add unused bits byte + $bitString = new ASNValue(ASNValue::TAG_BITSTRING); + $bitString->Value = $bitStringValue; + //Encode body + $bodyValue = "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00" . $bitString->Encode(); + $body = new ASNValue(ASNValue::TAG_SEQUENCE); + $body->Value = $bodyValue; + //Get DER encoded public key: + $PublicDER = $body->Encode(); + return $PublicDER; } -/** - * @param string key - * @return string - */ -function rsatopem($key) { - $rsa = new RSA(); - $rsa->setPublicKey($key); +function pkcs1_encode($Modulus,$PublicExponent) { + //Encode key sequence + $modulus = new ASNValue(ASNValue::TAG_INTEGER); + $modulus->SetIntBuffer($Modulus); + $publicExponent = new ASNValue(ASNValue::TAG_INTEGER); + $publicExponent->SetIntBuffer($PublicExponent); + $keySequenceItems = array($modulus, $publicExponent); + $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE); + $keySequence->SetSequence($keySequenceItems); + //Encode bit string + $bitStringValue = $keySequence->Encode(); + return $bitStringValue; +} - return $rsa->getPublicKey(RSA::PUBLIC_FORMAT_PKCS8); +// http://stackoverflow.com/questions/27568570/how-to-convert-raw-modulus-exponent-to-rsa-public-key-pem-format +function metopem($m,$e) { + $der = pkcs8_encode($m,$e); + $key = DerToPem($der,false); + return $key; } -/** - * @param string key - * @return string - */ -function pemtorsa($key) { - $rsa = new RSA(); - $rsa->setPublicKey($key); +function pubrsatome($key,&$m,&$e) { + require_once('library/asn1.php'); - return $rsa->getPublicKey(RSA::PUBLIC_FORMAT_PKCS1); + $lines = explode("\n",$key); + unset($lines[0]); + unset($lines[count($lines)]); + $x = base64_decode(implode('',$lines)); + $r = ASN_BASE::parseASNString($x); + + $m = base64url_decode($r[0]->asnData[0]->asnData); + $e = base64url_decode($r[0]->asnData[1]->asnData); +} + + +function rsatopem($key) { + pubrsatome($key,$m,$e); + return(metopem($m,$e)); +} + +function pemtorsa($key) { + pemtome($key,$m,$e); + return(metorsa($m,$e)); } -/** - * @param string $key key - * @param string $m reference modulo - * @param string $e reference exponent - */ function pemtome($key,&$m,&$e) { + $lines = explode("\n",$key); + unset($lines[0]); + unset($lines[count($lines)]); + $x = base64_decode(implode('',$lines)); - $rsa = new RSA(); - $rsa->loadKey($key); - $rsa->setPublicKey(); + $r = ASN_BASE::parseASNString($x); - $e = $rsa->modulus->toBytes(); - $m = $rsa->exponent->toBytes(); + $m = base64url_decode($r[0]->asnData[1]->asnData[0]->asnData[0]->asnData); + $e = base64url_decode($r[0]->asnData[1]->asnData[0]->asnData[1]->asnData); +} +function metorsa($m,$e) { + $der = pkcs1_encode($m,$e); + $key = DerToRsa($der); + return $key; } + + function salmon_key($pubkey) { pemtome($pubkey,$m,$e); return 'RSA' . '.' . base64url_encode($m,true) . '.' . base64url_encode($e,true) ; } + function convert_salmon_key($key) { if(strstr($key,',')) diff --git a/include/dir_fns.php b/include/dir_fns.php index 88a1bb74f..8326415ed 100644 --- a/include/dir_fns.php +++ b/include/dir_fns.php @@ -3,6 +3,7 @@ * @file include/dir_fns.php */ +use Zotlabs\Lib\Crypto; use Zotlabs\Lib\Libzot; use Zotlabs\Lib\Webfinger; use Zotlabs\Lib\Zotfinger; @@ -280,7 +281,7 @@ function sync_directories($dirmode) { 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'])) { + if (! Crypto::verify($rr['target'] . '.' . $rr['rating'] . '.' . $rr['rating_text'], base64url_decode($rr['signature']),$y[0]['xchan_pubkey'])) { logger('failed to verify rating'); continue; } diff --git a/include/follow.php b/include/follow.php index a4d382545..64ae8f7f1 100644 --- a/include/follow.php +++ b/include/follow.php @@ -9,6 +9,8 @@ // $return['abook'] Address book entry joined with xchan if successful // $return['message'] error text if success is false. +use Zotlabs\Lib\Crypto; + require_once('include/zot.php'); function new_contact($uid,$url,$channel,$interactive = false, $confirm = false) { @@ -19,7 +21,7 @@ function new_contact($uid,$url,$channel,$interactive = false, $confirm = false) $is_zot = false; $protocol = ''; - + if(substr($url,0,1) === '[') { $x = strpos($url,']'); if($x) { @@ -62,7 +64,7 @@ function new_contact($uid,$url,$channel,$interactive = false, $confirm = false) call_hooks('follow_init', $arr); - if($arr['channel']['success']) + if($arr['channel']['success']) $ret = $arr['channel']; elseif((! $is_http) && ((! $protocol) || (strtolower($protocol) === 'zot'))) $ret = Zotlabs\Zot\Finger::run($url,$channel); @@ -98,11 +100,11 @@ function new_contact($uid,$url,$channel,$interactive = false, $confirm = false) return $result; } } - - + + // do we have an xchan and hubloc? - // If not, create them. + // If not, create them. $x = import_xchan($j); @@ -111,13 +113,13 @@ function new_contact($uid,$url,$channel,$interactive = false, $confirm = false) return $result; } - if(! $x['success']) + if(! $x['success']) return $x; $xchan_hash = $x['hash']; if( array_key_exists('permissions',$j) && array_key_exists('data',$j['permissions'])) { - $permissions = crypto_unencapsulate(array( + $permissions = Crypto::unencapsulate(array( 'data' => $j['permissions']['data'], 'alg' => $j['permissions']['alg'], 'key' => $j['permissions']['key'], @@ -140,7 +142,7 @@ function new_contact($uid,$url,$channel,$interactive = false, $confirm = false) $xchan_hash = ''; $sql_options = (($protocol) ? " and xchan_network = '" . dbesc($protocol) . "' " : ''); - + $r = q("select * from xchan where (xchan_addr = '%s' or xchan_url = '%s') $sql_options ", dbesc($url), diff --git a/include/help.php b/include/help.php index ebf1ccc08..38facb04a 100644 --- a/include/help.php +++ b/include/help.php @@ -285,6 +285,7 @@ function load_context_help() { $path = App::$cmd; $args = App::$argv; $lang = App::$language; + $context_help = ''; if(! isset($lang) || !is_dir('doc/context/' . $lang . '/')) { $lang = 'en'; diff --git a/include/html2plain.php b/include/html2plain.php index fde70bd01..91a1f14cb 100644 --- a/include/html2plain.php +++ b/include/html2plain.php @@ -102,12 +102,14 @@ function html2plain($html, $wraplength = 75, $compact = false) { $message = str_replace("\r", "", $html); + $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8"); - $doc = new DOMDocument(); - $doc->preserveWhiteSpace = false; + if(!$message) + return; - $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8"); + $doc = new DOMDocument(); + $doc->preserveWhiteSpace = false; @$doc->loadHTML($message); $xpath = new DomXPath($doc); diff --git a/include/items.php b/include/items.php index 83108455f..ce1461aba 100644 --- a/include/items.php +++ b/include/items.php @@ -4,6 +4,7 @@ * @brief Items related functions. */ +use Zotlabs\Lib\Crypto; use Zotlabs\Lib\Enotify; use Zotlabs\Lib\MarkdownSoap; use Zotlabs\Lib\MessageFilter; @@ -1652,7 +1653,7 @@ function item_sign(&$item) { if(! $r) return; - $item['sig'] = base64url_encode(rsa_sign($item['body'], $r[0]['channel_prvkey'])); + $item['sig'] = base64url_encode(Crypto::sign($item['body'], $r[0]['channel_prvkey'])); $item['item_verified'] = 1; } @@ -2391,9 +2392,14 @@ function item_store_update($arr, $allow_exec = false, $deliver = true) { logger('item_store_update: ' . print_r($arr,true), LOGGER_DATA); - $str = ''; - foreach($arr as $k => $v) { - if($str) + $columns = db_columns('item'); + $str = ''; + foreach ($arr as $k => $v) { + if (!in_array($k, $columns)) { + continue; + } + + if ($str) $str .= ","; $str .= " " . TQUOT . $k . TQUOT . " = '" . $v . "' "; } @@ -2695,10 +2701,13 @@ function tag_deliver($uid, $item_id) { return; } + /* this should not be required anymore due to the check above if (strpos($item['body'],'[/share]')) { logger('W2W post already shared'); return; } + */ + // group delivery via W2W logger('rewriting W2W post for ' . $u[0]['channel_address']); start_delivery_chain($u[0], $item, $item_id, 0, true, (($item['edited'] != $item['created']) || $item['item_deleted'])); @@ -2971,7 +2980,7 @@ function item_community_tag($channel,$item) { $pitem = $items[0]; $auth = get_iconfig($item,'system','communitytagauth'); if($auth) { - if(rsa_verify('tagauth.' . $item['mid'],base64url_decode($auth),$pitem['owner']['xchan_pubkey']) || rsa_verify('tagauth.' . $item['mid'],base64url_decode($auth),$pitem['author']['xchan_pubkey'])) { + if(Crypto::verify('tagauth.' . $item['mid'],base64url_decode($auth),$pitem['owner']['xchan_pubkey']) || Crypto::verify('tagauth.' . $item['mid'],base64url_decode($auth),$pitem['author']['xchan_pubkey'])) { logger('tag_deliver: tagging the post: ' . $channel['channel_name']); $tag_the_post = true; } @@ -2980,7 +2989,7 @@ function item_community_tag($channel,$item) { if(($pitem['owner_xchan'] === $channel['channel_hash']) && (! intval(get_pconfig($channel['channel_id'],'system','blocktags')))) { logger('tag_deliver: community tag recipient: ' . $channel['channel_name']); $tag_the_post = true; - $sig = rsa_sign('tagauth.' . $item['mid'],$channel['channel_prvkey']); + $sig = Crypto::sign('tagauth.' . $item['mid'],$channel['channel_prvkey']); logger('tag_deliver: setting iconfig for ' . $item['id']); set_iconfig($item['id'],'system','communitytagauth',base64url_encode($sig),1); } @@ -3268,24 +3277,19 @@ function start_delivery_chain($channel, $item, $item_id, $parent, $group = false $arr['item_wall'] = 1; $arr['item_thread_top'] = 1; - if (strpos($item['body'], "[/share]") !== false) { - $pos = strpos($item['body'], "[share"); - $bb = substr($item['body'], $pos); - } else { - $bb = "[share author='" . urlencode($item['author']['xchan_name']). - "' profile='" . $item['author']['xchan_url'] . - "' portable_id='" . $item['author']['xchan_hash'] . - "' avatar='" . $item['author']['xchan_photo_s'] . - "' link='" . $item['plink'] . - "' auth='" . ((in_array($item['author']['xchan_network'], ['zot6','zot'])) ? 'true' : 'false') . - "' posted='" . $item['created'] . - "' message_id='" . $item['mid'] . - "']"; - if($item['title']) - $bb .= '[h3][b]'.$item['title'].'[/b][/h3]'."\r\n"; - $bb .= $item['body']; - $bb .= "[/share]"; - } + $bb = "[share author='" . urlencode($item['author']['xchan_name']). + "' profile='" . $item['author']['xchan_url'] . + "' portable_id='" . $item['author']['xchan_hash'] . + "' avatar='" . $item['author']['xchan_photo_s'] . + "' link='" . $item['plink'] . + "' auth='" . ((in_array($item['author']['xchan_network'], ['zot6','zot'])) ? 'true' : 'false') . + "' posted='" . $item['created'] . + "' message_id='" . $item['mid'] . + "']"; + if($item['title']) + $bb .= '[h3][b]'.$item['title'].'[/b][/h3]'."\r\n"; + $bb .= $item['body']; + $bb .= "[/share]"; $arr['body'] = $bb; $arr['term'] = $item['term']; diff --git a/include/message.php b/include/message.php index 37fe6749d..e6c9ed8ee 100644 --- a/include/message.php +++ b/include/message.php @@ -17,9 +17,9 @@ function mail_prepare_binary($item) { // send a private message - -function send_message($uid = 0, $recipient = '', $body = '', $subject = '', $replyto = '', $expires = NULL_DATE, $mimetype = 'text/bbcode', $raw = false, $sig = '') { + +function send_message($uid = 0, $recipient = '', $body = '', $subject = '', $replyto = '', $expires = NULL_DATE, $mimetype = 'text/bbcode', $raw = false, $sig = '') { $ret = array('success' => false); $is_reply = false; @@ -80,7 +80,7 @@ function send_message($uid = 0, $recipient = '', $body = '', $subject = '', $rep $ret['message'] = t('No recipient provided.'); return $ret; } - + if(! strlen($subject)) $subject = t('[no subject]'); @@ -99,13 +99,13 @@ function send_message($uid = 0, $recipient = '', $body = '', $subject = '', $rep if($r) { $conv_guid = $r[0]['conv_guid']; } - } + } if(! $conv_guid) { // create a new conversation - $retconv = create_conversation($channel,$recipient,$subject); + $retconv = create_conversation($channel,$recipient,$subject); if($retconv) { $conv_guid = $retconv['guid']; } @@ -153,7 +153,7 @@ function send_message($uid = 0, $recipient = '', $body = '', $subject = '', $rep /** * - * When a photo was uploaded into the message using the (profile wall) ajax + * When a photo was uploaded into the message using the (profile wall) ajax * uploader, The permissions are initially set to disallow anybody but the * owner from seeing it. This is because the permissions may not yet have been * set for the post. If it's private, the photo permissions should be set @@ -232,7 +232,7 @@ function send_message($uid = 0, $recipient = '', $body = '', $subject = '', $rep dbesc($image_uri), intval($channel['channel_id']), dbesc('<' . $channel['channel_hash'] . '>') - ); + ); } } @@ -293,7 +293,7 @@ function create_conversation($channel,$recipient,$subject) { dbesc($conv_guid), intval($channel['channel_id']) ); - + return $r[0]; } @@ -308,11 +308,12 @@ function private_messages_list($uid, $mailbox = '', $start = 0, $numitems = 0) { if($numitems) $limit = " LIMIT " . intval($numitems) . " OFFSET " . intval($start); - + if($mailbox !== '') { $x = q("select channel_hash from channel where channel_id = %d limit 1", intval($uid) ); + if(! $x) return array(); @@ -332,10 +333,9 @@ function private_messages_list($uid, $mailbox = '', $start = 0, $numitems = 0) { case 'combined': default: $parents = q("SELECT mail.parent_mid FROM mail LEFT JOIN conv ON mail.conv_guid = conv.guid WHERE mail.mid = mail.parent_mid AND mail.channel_id = %d ORDER BY conv.updated DESC $limit", - dbesc($local_channel) + intval($local_channel) ); break; - } } @@ -346,7 +346,7 @@ function private_messages_list($uid, $mailbox = '', $start = 0, $numitems = 0) { foreach($parents as $parent) { $all = q("SELECT * FROM mail WHERE parent_mid = '%s' AND channel_id = %d ORDER BY created DESC limit 1", dbesc($parent['parent_mid']), - dbesc($local_channel) + intval($local_channel) ); if($all) { @@ -356,7 +356,7 @@ function private_messages_list($uid, $mailbox = '', $start = 0, $numitems = 0) { } } } - else { + elseif($sql) { $r = q($sql); } @@ -477,7 +477,7 @@ function private_messages_drop($channel_id, $messageitem_id, $drop_conversation dbesc($x[0]['conv_guid']), intval($channel_id) ); - } + } $m['mail'] = array(); foreach($z as $zz) { xchan_mail_query($zz); @@ -513,7 +513,7 @@ function private_messages_fetch_conversation($channel_id, $messageitem_id, $upda intval($messageitem_id) ); - if(! $r) + if(! $r) return array(); $messages = q("select * from mail where parent_mid = '%s' and channel_id = %d order by created asc", @@ -559,7 +559,7 @@ function private_messages_fetch_conversation($channel_id, $messageitem_id, $upda intval($channel_id) ); } - + return $messages; } diff --git a/include/nav.php b/include/nav.php index b2a061661..1ad8dad58 100644 --- a/include/nav.php +++ b/include/nav.php @@ -14,39 +14,41 @@ function nav($template = 'default') { * */ - if(!(x(App::$page,'nav'))) - App::$page['nav'] = ''; - + App::$page['nav'] = App::$page['nav'] ?? ''; + App::$page['htmlhead'] = App::$page['htmlhead'] ?? ''; App::$page['htmlhead'] .= '<script>$(document).ready(function() { $("#nav-search-text").search_autocomplete(\'' . z_root() . '/acl' . '\');});</script>'; - $is_owner = (((local_channel()) && ((App::$profile_uid == local_channel()) || (App::$profile_uid == 0))) ? true : false); + $observer = []; + $sitelocation = ''; - if(local_channel()) { - $channel = App::get_channel(); + if (local_channel()) { + $channel = App::get_channel(); $observer = App::get_observer(); - $prof = q("select id from profile where uid = %d and is_default = 1", + + $prof = q("select id from profile where uid = %d and is_default = 1", intval($channel['channel_id']) ); - if(! $_SESSION['delegate']) { + if (empty($_SESSION['delegate'])) { $chans = q("select channel_name, channel_id from channel where channel_account_id = %d and channel_removed = 0 order by channel_name ", intval(get_account_id()) ); } $sitelocation = (($is_owner) ? '' : App::$profile['reddress']); } - elseif(remote_channel()) { - $observer = App::get_observer(); + elseif (remote_channel()) { + $observer = App::get_observer(); $sitelocation = ((App::$profile['reddress']) ? App::$profile['reddress'] : '@' . App::get_hostname()); } require_once('include/conversation.php'); - $nav_apps = []; - $navbar_apps = []; + $nav_apps = []; + $navbar_apps = []; $channel_apps = []; - - $channel_apps[] = channel_apps($is_owner, App::$profile['channel_address']); + + if (isset(App::$profile['channel_address'])) + $channel_apps[] = channel_apps($is_owner, App::$profile['channel_address']); /** @@ -55,117 +57,121 @@ function nav($template = 'default') { * */ - $banner = get_config('system','banner'); + $banner = get_config('system', 'banner'); - if($banner === false) - $banner = get_config('system','sitename'); - - call_hooks('get_banner',$banner); + if ($banner === false) + $banner = get_config('system', 'sitename'); - App::$page['header'] .= replace_macros(get_markup_template('hdr.tpl'), array( + call_hooks('get_banner', $banner); + + App::$page['header'] = App::$page['header'] ?? ''; + App::$page['header'] .= replace_macros(get_markup_template('hdr.tpl'), [ //we could additionally use this to display important system notifications e.g. for updates - )); + ]); // nav links: array of array('href', 'text', 'extra css classes', 'title') $nav = []; - if(can_view_public_stream()) + if (can_view_public_stream()) $nav['pubs'] = true; /** * Display login or logout - */ + */ - $nav['usermenu'] = []; - $userinfo = null; + $nav['usermenu'] = []; $nav['loginmenu'] = []; + $userinfo = []; - if($observer) { + if ($observer) { $userinfo = [ - 'icon' => $observer['xchan_photo_m'].'?rev='.strtotime($observer['xchan_photo_date']), + 'icon' => $observer['xchan_photo_m'] . '?rev=' . strtotime($observer['xchan_photo_date']), 'name' => $observer['xchan_addr'], ]; } - elseif(! $_SESSION['authenticated']) { + elseif (empty($_SESSION['authenticated'])) { $nav['remote_login'] = remote_login(); - $nav['loginmenu'][] = Array('rmagic',t('Remote authentication'),'',t('Click to authenticate to your home hub'),'rmagic_nav_btn'); + $nav['loginmenu'][] = ['rmagic', t('Remote authentication'), '', t('Click to authenticate to your home hub'), 'rmagic_nav_btn']; } - if(local_channel()) { + if (local_channel()) { - if(! $_SESSION['delegate']) { - $nav['manage'] = array('manage', t('Channel Manager'), "", t('Manage your channels'),'manage_nav_btn'); - } - if(Apps::system_app_installed(local_channel(), 'Privacy Groups')) - $nav['group'] = array('group', t('Privacy Groups'),"", t('Manage your privacy groups'),'group_nav_btn'); + if (empty($_SESSION['delegate'])) { + $nav['manage'] = ['manage', t('Channel Manager'), "", t('Manage your channels'), 'manage_nav_btn']; + } + if (Apps::system_app_installed(local_channel(), 'Privacy Groups')) + $nav['group'] = ['group', t('Privacy Groups'), "", t('Manage your privacy groups'), 'group_nav_btn']; - $nav['settings'] = array('settings', t('Settings'),"", t('Account/Channel Settings'),'settings_nav_btn'); + $nav['settings'] = ['settings', t('Settings'), "", t('Account/Channel Settings'), 'settings_nav_btn']; - - if($chans && count($chans) > 1 && feature_enabled(local_channel(),'nav_channel_select')) + + if ($chans && count($chans) > 1 && feature_enabled(local_channel(), 'nav_channel_select')) $nav['channels'] = $chans; - $nav['logout'] = ['logout',t('Logout'), "", t('End this session'),'logout_nav_btn']; - + $nav['logout'] = ['logout', t('Logout'), "", t('End this session'), 'logout_nav_btn']; + // user menu - $nav['usermenu'][] = ['profile/' . $channel['channel_address'], t('View Profile'), ((\App::$nav_sel['raw_name'] == 'Profile') ? 'active' : ''), t('Your profile page'),'profile_nav_btn']; + $nav['usermenu'][] = ['profile/' . $channel['channel_address'], t('View Profile'), ((App::$nav_sel['raw_name'] == 'Profile') ? 'active' : ''), t('Your profile page'), 'profile_nav_btn']; - if(feature_enabled(local_channel(),'multi_profiles')) - $nav['usermenu'][] = ['profiles', t('Edit Profiles'), ((\App::$nav_sel['raw_name'] == 'Profiles') ? 'active' : '') , t('Manage/Edit profiles'),'profiles_nav_btn']; + if (feature_enabled(local_channel(), 'multi_profiles')) + $nav['usermenu'][] = ['profiles', t('Edit Profiles'), ((App::$nav_sel['raw_name'] == 'Profiles') ? 'active' : ''), t('Manage/Edit profiles'), 'profiles_nav_btn']; else - $nav['usermenu'][] = ['profiles/' . $prof[0]['id'], t('Edit Profile'), ((\App::$nav_sel['raw_name'] == 'Profiles') ? 'active' : ''), t('Edit your profile'),'profiles_nav_btn']; + $nav['usermenu'][] = ['profiles/' . $prof[0]['id'], t('Edit Profile'), ((App::$nav_sel['raw_name'] == 'Profiles') ? 'active' : ''), t('Edit your profile'), 'profiles_nav_btn']; } else { - if(! get_account_id()) { - if(App::$module === 'channel') { - $nav['login'] = login(true,'main-login',false,false); - $nav['loginmenu'][] = ['login',t('Login'),'',t('Sign in'),'']; + if (!get_account_id()) { + if (App::$module === 'channel') { + $nav['login'] = login(true, 'main-login', false, false); + $nav['loginmenu'][] = ['login', t('Login'), '', t('Sign in'), '']; } else { - $nav['login'] = login(true,'main-login',false,false); - $nav['loginmenu'][] = ['login',t('Login'),'',t('Sign in'),'login_nav_btn']; + $nav['login'] = login(true, 'main-login', false, false); + $nav['loginmenu'][] = ['login', t('Login'), '', t('Sign in'), 'login_nav_btn']; + App::$page['content'] .= replace_macros(get_markup_template('nav_login.tpl'), - [ - '$nav' => $nav, + [ + '$nav' => $nav, 'userinfo' => $userinfo ] ); } } else - $nav['alogout'] = ['logout',t('Logout'), "", t('End this session'),'logout_nav_btn']; + $nav['alogout'] = ['logout', t('Logout'), "", t('End this session'), 'logout_nav_btn']; } $my_url = get_my_url(); - if(! $my_url) { + if (!$my_url) { $observer = App::get_observer(); - $my_url = (($observer) ? $observer['xchan_url'] : ''); + $my_url = (($observer) ? $observer['xchan_url'] : ''); } $homelink_arr = parse_url($my_url); - $homelink = $homelink_arr['scheme'] . '://' . $homelink_arr['host']; + $scheme = $homelink_arr['scheme'] ?? ''; + $host = $homelink_arr['host'] ?? ''; + $homelink = $scheme . '://' . $host; - if(! $is_owner) { - $nav['rusermenu'] = array( + if (!$is_owner) { + $nav['rusermenu'] = [ $homelink, t('Take me home'), 'logout', ((local_channel()) ? t('Logout') : t('Log me out of this site')) - ); + ]; } - if(((get_config('system','register_policy') == REGISTER_OPEN) || (get_config('system','register_policy') == REGISTER_APPROVE)) && (! $_SESSION['authenticated'])) - $nav['register'] = ['register',t('Register'), "", t('Create an account'),'register_nav_btn']; + if (((get_config('system', 'register_policy') == REGISTER_OPEN) || (get_config('system', 'register_policy') == REGISTER_APPROVE)) && (empty($_SESSION['authenticated']))) + $nav['register'] = ['register', t('Register'), "", t('Create an account'), 'register_nav_btn']; - if(! get_config('system','hide_help')) { - $help_url = z_root() . '/help?f=&cmd=' . App::$cmd; - $context_help = ''; - $enable_context_help = ((intval(get_config('system','enable_context_help')) === 1 || get_config('system','enable_context_help') === false) ? true : false); - if($enable_context_help === true) { + if (!get_config('system', 'hide_help')) { + $help_url = z_root() . '/help?f=&cmd=' . App::$cmd; + $context_help = ''; + $enable_context_help = ((intval(get_config('system', 'enable_context_help')) === 1 || get_config('system', 'enable_context_help') === false) ? true : false); + if ($enable_context_help === true) { require_once('include/help.php'); $context_help = load_context_help(); //point directly to /help if $context_help is empty - this can be removed once we have context help for all modules @@ -174,7 +180,7 @@ function nav($template = 'default') { $nav['help'] = [$help_url, t('Help'), "", t('Help and documentation'), 'help_nav_btn', $context_help, $enable_context_help]; } - switch(App::$module) { + switch (App::$module) { case 'network': $search_form_action = 'network'; break; @@ -190,32 +196,32 @@ function nav($template = 'default') { /** * Admin page */ - if (is_site_admin()) { - $nav['admin'] = array('admin/', t('Admin'), "", t('Site Setup and Configuration'),'admin_nav_btn'); - } + if (is_site_admin()) { + $nav['admin'] = ['admin/', t('Admin'), "", t('Site Setup and Configuration'), 'admin_nav_btn']; + } - $x = array('nav' => $nav, 'usermenu' => $userinfo ); + $x = ['nav' => $nav, 'usermenu' => $userinfo]; call_hooks('nav', $x); - // Not sure the best place to put this on the page. So I'm implementing it but leaving it - // turned off until somebody discovers this and figures out a good location for it. + // Not sure the best place to put this on the page. So I'm implementing it but leaving it + // turned off until somebody discovers this and figures out a good location for it. $powered_by = ''; - $url = ''; + $url = ''; $settings_url = ''; - if(App::$profile_uid && App::$nav_sel['raw_name']) { + if (App::$profile_uid && App::$nav_sel['raw_name']) { $active_app = q("SELECT app_url FROM app WHERE app_channel = %d AND app_name = '%s' LIMIT 1", intval(App::$profile_uid), dbesc(App::$nav_sel['raw_name']) ); - if($active_app) { - if(strpos($active_app[0]['app_url'], ',')) { + if ($active_app) { + if (strpos($active_app[0]['app_url'], ',')) { $urls = explode(',', $active_app[0]['app_url']); - $url = trim($urls[0]); - if($is_owner) + $url = trim($urls[0]); + if ($is_owner) $settings_url = trim($urls[1]); } else { @@ -224,42 +230,39 @@ function nav($template = 'default') { } } - if(! $settings_url && isset(App::$nav_sel['settings_url'])) + if (!$settings_url && isset(App::$nav_sel['settings_url'])) $settings_url = App::$nav_sel['settings_url']; $pinned_list = []; - $syslist = []; //app bin - if($is_owner) { - if(get_pconfig(local_channel(), 'system','import_system_apps') !== datetime_convert('UTC','UTC','now','Y-m-d')) { + if ($is_owner) { + if (get_pconfig(local_channel(), 'system', 'import_system_apps') !== datetime_convert('UTC', 'UTC', 'now', 'Y-m-d')) { Apps::import_system_apps(); - set_pconfig(local_channel(), 'system','import_system_apps', datetime_convert('UTC','UTC','now','Y-m-d')); + set_pconfig(local_channel(), 'system', 'import_system_apps', datetime_convert('UTC', 'UTC', 'now', 'Y-m-d')); } - if(get_pconfig(local_channel(), 'system','force_import_system_apps') !== STD_VERSION) { + if (get_pconfig(local_channel(), 'system', 'force_import_system_apps') !== STD_VERSION) { Apps::import_system_apps(); - set_pconfig(local_channel(), 'system','force_import_system_apps', STD_VERSION); + set_pconfig(local_channel(), 'system', 'force_import_system_apps', STD_VERSION); } - $list = Apps::app_list(local_channel(), false, [ 'nav_pinned_app' ]); - if($list) { - foreach($list as $li) { + $list = Apps::app_list(local_channel(), false, ['nav_pinned_app']); + if ($list) { + foreach ($list as $li) { $pinned_list[] = Apps::app_encode($li); } } Apps::translate_system_apps($pinned_list); - usort($pinned_list,'Zotlabs\\Lib\\Apps::app_name_compare'); - - $pinned_list = Apps::app_order(local_channel(),$pinned_list, 'nav_pinned_app'); - + usort($pinned_list, 'Zotlabs\\Lib\\Apps::app_name_compare'); + $pinned_list = Apps::app_order(local_channel(), $pinned_list, 'nav_pinned_app'); $syslist = []; - $list = Apps::app_list(local_channel(), false, [ 'nav_featured_app' ]); + $list = Apps::app_list(local_channel(), false, ['nav_featured_app']); - if($list) { - foreach($list as $li) { + if ($list) { + foreach ($list as $li) { $syslist[] = Apps::app_encode($li); } } @@ -270,85 +273,83 @@ function nav($template = 'default') { $syslist = Apps::get_system_apps(true); } - usort($syslist,'Zotlabs\\Lib\\Apps::app_name_compare'); - - $syslist = Apps::app_order(local_channel(),$syslist, 'nav_featured_app'); + usort($syslist, 'Zotlabs\\Lib\\Apps::app_name_compare'); + $syslist = Apps::app_order(local_channel(), $syslist, 'nav_featured_app'); - if($pinned_list) { - foreach($pinned_list as $app) { - if(\App::$nav_sel['name'] == $app['name']) + if ($pinned_list) { + foreach ($pinned_list as $app) { + if (App::$nav_sel['name'] == $app['name']) $app['active'] = true; - if($is_owner) { - $navbar_apps[] = Apps::app_render($app,'navbar'); + if ($is_owner) { + $navbar_apps[] = Apps::app_render($app, 'navbar'); } - elseif(! $is_owner && strpos($app['requires'], 'local_channel') === false) { - $navbar_apps[] = Apps::app_render($app,'navbar'); + elseif (!$is_owner && strpos($app['requires'], 'local_channel') === false) { + $navbar_apps[] = Apps::app_render($app, 'navbar'); } } } - - if($syslist) { - foreach($syslist as $app) { - if(\App::$nav_sel['name'] == $app['name']) + if ($syslist) { + foreach ($syslist as $app) { + if (isset(App::$nav_sel['name']) && App::$nav_sel['name'] == $app['name']) $app['active'] = true; - if($is_owner) { - $nav_apps[] = Apps::app_render($app,'nav'); + if ($is_owner) { + $nav_apps[] = Apps::app_render($app, 'nav'); } - elseif(! $is_owner && strpos($app['requires'], 'local_channel') === false) { - $nav_apps[] = Apps::app_render($app,'nav'); + elseif (!$is_owner && isset($app['requires']) && strpos($app['requires'], 'local_channel') === false) { + $nav_apps[] = Apps::app_render($app, 'nav'); } } } - $c = theme_include('navbar_' . purify_filename($template) . '.css'); + $c = theme_include('navbar_' . purify_filename($template) . '.css'); $tpl = get_markup_template('navbar_' . purify_filename($template) . '.tpl'); - if($c && $tpl) { + if ($c && $tpl) { head_add_css('navbar_' . $template . '.css'); } - if(! $tpl) { + if (!$tpl) { $tpl = get_markup_template('navbar_default.tpl'); } - App::$page['nav'] .= replace_macros($tpl, array( - '$baseurl' => z_root(), - '$fulldocs' => t('Help'), - '$sitelocation' => $sitelocation, - '$nav' => $x['nav'], - '$banner' => $banner, + App::$page['nav'] .= replace_macros($tpl, [ + '$baseurl' => z_root(), + '$fulldocs' => t('Help'), + '$sitelocation' => $sitelocation, + '$nav' => $x['nav'], + '$banner' => $banner, '$emptynotifications' => t('Loading'), - '$userinfo' => $x['usermenu'], - '$localuser' => local_channel(), - '$is_owner' => $is_owner, - '$sel' => App::$nav_sel, - '$powered_by' => $powered_by, - '$help' => t('@name, !forum, #tag, ?doc, content'), - '$pleasewait' => t('Please wait...'), - '$nav_apps' => $nav_apps, - '$navbar_apps' => $navbar_apps, - '$channel_menu' => get_pconfig(App::$profile_uid,'system','channel_menu',get_config('system','channel_menu')), - '$channel_thumb' => ((App::$profile) ? App::$profile['thumb'] : ''), - '$channel_apps' => $channel_apps, - '$addapps' => t('Add Apps'), - '$orderapps' => t('Arrange Apps'), - '$sysapps_toggle' => t('Toggle System Apps'), - '$url' => (($url) ? $url : z_root() . '/' . App::$cmd), - '$settings_url' => $settings_url - )); - - if(x($_SESSION, 'reload_avatar') && $observer) { - // The avatar has been changed on the server but the browser doesn't know that, + '$userinfo' => $x['usermenu'], + '$localuser' => local_channel(), + '$is_owner' => $is_owner, + '$sel' => App::$nav_sel, + '$powered_by' => $powered_by, + '$help' => t('@name, !forum, #tag, ?doc, content'), + '$pleasewait' => t('Please wait...'), + '$nav_apps' => $nav_apps, + '$navbar_apps' => $navbar_apps, + '$channel_menu' => get_pconfig(App::$profile_uid, 'system', 'channel_menu', get_config('system', 'channel_menu')), + '$channel_thumb' => ((App::$profile) ? App::$profile['thumb'] : ''), + '$channel_apps' => $channel_apps, + '$addapps' => t('Add Apps'), + '$orderapps' => t('Arrange Apps'), + '$sysapps_toggle' => t('Toggle System Apps'), + '$url' => (($url) ? $url : z_root() . '/' . App::$cmd), + '$settings_url' => $settings_url + ]); + + if (x($_SESSION, 'reload_avatar') && $observer) { + // The avatar has been changed on the server but the browser doesn't know that, // force the browser to reload the image from the server instead of its cache. $tpl = get_markup_template('force_image_reload.tpl'); - App::$page['nav'] .= replace_macros($tpl, array( + App::$page['nav'] .= replace_macros($tpl, [ '$imgUrl' => $observer['xchan_photo_m'] - )); + ]); unset($_SESSION['reload_avatar']); } @@ -358,9 +359,9 @@ function nav($template = 'default') { /* * Set a menu item in navbar as selected - * + * */ -function nav_set_selected($raw_name, $settings_url = ''){ +function nav_set_selected($raw_name, $settings_url = '') { App::$nav_sel['raw_name'] = $raw_name; $item = ['name' => $raw_name]; @@ -368,7 +369,7 @@ function nav_set_selected($raw_name, $settings_url = ''){ App::$nav_sel['name'] = $item['name']; - if($settings_url) + if ($settings_url) App::$nav_sel['settings_url'] = z_root() . '/' . $settings_url; } @@ -376,20 +377,20 @@ function channel_apps($is_owner = false, $nickname = null) { // Don't provide any channel apps if we're running as the sys channel - if(App::$is_sys) + if (App::$is_sys) return ''; $channel = App::get_channel(); - if($channel && is_null($nickname)) + if ($channel && is_null($nickname)) $nickname = $channel['channel_address']; - $uid = ((App::$profile['profile_uid']) ? App::$profile['profile_uid'] : local_channel()); + $uid = ((isset(App::$profile['profile_uid'])) ? App::$profile['profile_uid'] : local_channel()); - if(! get_pconfig($uid, 'system', 'channelapps','1')) - return; + if (!get_pconfig($uid, 'system', 'channelapps', '1')) + return; - if($uid == local_channel()) { + if ($uid == local_channel()) { return; } else { @@ -410,7 +411,7 @@ function channel_apps($is_owner = false, $nickname = null) { $has_webpages = (($r) ? true : false); - if(x($_GET, 'tab')) + if (x($_GET, 'tab')) $tab = notags(trim($_GET['tab'])); $url = z_root() . '/channel/' . $nickname; @@ -427,7 +428,7 @@ function channel_apps($is_owner = false, $nickname = null) { ], ]; - $p = get_all_perms($uid,get_observer_hash()); + $p = get_all_perms($uid, get_observer_hash()); if ($p['view_profile']) { $tabs[] = [ @@ -458,7 +459,7 @@ function channel_apps($is_owner = false, $nickname = null) { ]; } - if($p['view_stream'] && $cal_link) { + if ($p['view_stream'] && $cal_link) { $tabs[] = [ 'label' => t('Calendar'), 'url' => z_root() . $cal_link, @@ -470,13 +471,13 @@ function channel_apps($is_owner = false, $nickname = null) { } - if ($p['chat'] && Apps::system_app_installed($uid,'Chatrooms')) { + if ($p['chat'] && Apps::system_app_installed($uid, 'Chatrooms')) { $has_chats = Chatroom::list_count($uid); if ($has_chats) { $tabs[] = [ 'label' => t('Chatrooms'), 'url' => z_root() . '/chat/' . $nickname, - 'sel' => ((argv(0) == 'chat') ? 'active' : '' ), + 'sel' => ((argv(0) == 'chat') ? 'active' : ''), 'title' => t('Chatrooms'), 'id' => 'chat-tab', 'icon' => 'comments-o' @@ -484,7 +485,7 @@ function channel_apps($is_owner = false, $nickname = null) { } } - $has_bookmarks = menu_list_count(local_channel(),'',MENU_BOOKMARK) + menu_list_count(local_channel(),'',MENU_SYSTEM|MENU_BOOKMARK); + $has_bookmarks = menu_list_count(local_channel(), '', MENU_BOOKMARK) + menu_list_count(local_channel(), '', MENU_SYSTEM | MENU_BOOKMARK); if ($is_owner && $has_bookmarks) { $tabs[] = [ 'label' => t('Bookmarks'), @@ -496,10 +497,10 @@ function channel_apps($is_owner = false, $nickname = null) { ]; } - if($p['view_pages'] && Apps::system_app_installed($uid, 'Cards')) { + if ($p['view_pages'] && Apps::system_app_installed($uid, 'Cards')) { $tabs[] = [ 'label' => t('Cards'), - 'url' => z_root() . '/cards/' . $nickname , + 'url' => z_root() . '/cards/' . $nickname, 'sel' => ((argv(0) == 'cards') ? 'active' : ''), 'title' => t('View Cards'), 'id' => 'cards-tab', @@ -507,10 +508,10 @@ function channel_apps($is_owner = false, $nickname = null) { ]; } - if($p['view_pages'] && Apps::system_app_installed($uid, 'Articles')) { + if ($p['view_pages'] && Apps::system_app_installed($uid, 'Articles')) { $tabs[] = [ 'label' => t('Articles'), - 'url' => z_root() . '/articles/' . $nickname , + 'url' => z_root() . '/articles/' . $nickname, 'sel' => ((argv(0) == 'articles') ? 'active' : ''), 'title' => t('View Articles'), 'id' => 'articles-tab', @@ -519,7 +520,7 @@ function channel_apps($is_owner = false, $nickname = null) { } - if($has_webpages && Apps::system_app_installed($uid, 'Webpages')) { + if ($has_webpages && Apps::system_app_installed($uid, 'Webpages')) { $tabs[] = [ 'label' => t('Webpages'), 'url' => z_root() . '/page/' . $nickname . '/home', @@ -529,7 +530,7 @@ function channel_apps($is_owner = false, $nickname = null) { 'icon' => 'newspaper-o' ]; } - + if ($p['view_wiki'] && Apps::system_app_installed($uid, 'Wiki')) { $tabs[] = [ @@ -542,11 +543,11 @@ function channel_apps($is_owner = false, $nickname = null) { ]; } - $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs); + $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs]; - call_hooks('channel_apps', $arr); + call_hooks('channel_apps', $arr); - return replace_macros(get_markup_template('profile_tabs.tpl'), + return replace_macros(get_markup_template('profile_tabs.tpl'), [ '$tabs' => $arr['tabs'], '$name' => App::$profile['channel_name'], diff --git a/include/oembed.php b/include/oembed.php index 1550eaacf..01cd8945f 100644 --- a/include/oembed.php +++ b/include/oembed.php @@ -14,7 +14,7 @@ function oembed_replacecb($matches){ $j = oembed_fetch_url($result['url']); $s = oembed_format_object($j); - return $s; + return $s; } @@ -52,7 +52,7 @@ function oembed_action($embedurl) { } } } - + $found = false; if(($x = get_config('system','embed_allow'))) { @@ -74,7 +74,7 @@ function oembed_action($embedurl) { } // allow individual members to block something that wasn't blocked already. - // They cannot over-ride the site to allow or change the filtering on an + // They cannot over-ride the site to allow or change the filtering on an // embed that is not allowed by the site admin. if(local_channel()) { @@ -96,7 +96,7 @@ function oembed_action($embedurl) { $arr = array('url' => $embedurl, 'action' => $action); call_hooks('oembed_action',$arr); - logger('action: ' . $arr['action'] . ' url: ' . $arr['url'], LOGGER_DEBUG,LOG_DEBUG); + logger('action: ' . $arr['action'] . ' url: ' . $arr['url'], LOGGER_DEBUG,LOG_DEBUG); return $arr; @@ -122,7 +122,7 @@ function oembed_fetch_url($embedurl){ $noexts = [ '.mp3', '.mp4', '.ogg', '.ogv', '.oga', '.ogm', '.webm', '.opus', '.m4a' ]; - $result = oembed_action($embedurl); + $result = oembed_action($embedurl); $embedurl = $result['url']; $action = $result['action']; @@ -153,7 +153,7 @@ function oembed_fetch_url($embedurl){ 'title' => t('View PDF'), 'type' => 'pdf' ]; - + // set $txt to something so that we don't attempt to fetch what could be a lengthy pdf. $txt = EMPTY_STR; } @@ -165,12 +165,12 @@ function oembed_fetch_url($embedurl){ if ($action !== 'block') { // try oembed autodiscovery $redirects = 0; - $result = z_fetch_url($furl, false, $redirects, + $result = z_fetch_url($furl, false, $redirects, [ - 'timeout' => 30, - 'accept_content' => "text/*", - 'novalidate' => true, - 'session' => ((local_channel() && $zrl) ? true : false) + 'timeout' => 30, + 'accept_content' => "text/*", + 'novalidate' => true, + 'session' => ((local_channel() && $zrl) ? true : false) ] ); @@ -180,7 +180,8 @@ function oembed_fetch_url($embedurl){ logger('fetch failure: ' . $furl); if($html_text) { - $dom = @DOMDocument::loadHTML($html_text); + $dom = new DOMDocument; + @$dom->loadHTML($html_text); if ($dom){ $xpath = new DOMXPath($dom); $attr = "oembed"; @@ -203,7 +204,7 @@ function oembed_fetch_url($embedurl){ logger('fetch failed: ' . $href); break; } - // soundcloud is now using text/json+oembed instead of application/json+oembed, + // soundcloud is now using text/json+oembed instead of application/json+oembed, // others may be also $entries = $xpath->query("//link[@type='text/json+oembed']"); foreach($entries as $e){ @@ -218,18 +219,18 @@ function oembed_fetch_url($embedurl){ } } } - + if ($txt==false || $txt=="") { $x = array('url' => $embedurl,'videowidth' => App::$videowidth); call_hooks('oembed_probe',$x); if(array_key_exists('embed',$x)) $txt = $x['embed']; } - + $txt=trim($txt); if ($txt[0]!="{") $txt='{"type":"error"}'; - + // save in cache if(! get_config('system','oembed_cache_disable')) @@ -252,7 +253,7 @@ function oembed_fetch_url($embedurl){ // some sites wrap their entire embed in an iframe // which we will purify away and which we provide anyway. - // So if we see this, grab the frame src url and use that + // So if we see this, grab the frame src url and use that // as the embed content - which will still need to be purified. if(preg_match('#\<iframe(.*?)src\=[\'\"](.*?)[\'\"]#',$j['html'],$matches)) { @@ -261,16 +262,16 @@ function oembed_fetch_url($embedurl){ } logger('frame src: ' . $j['html'], LOGGER_DATA); - + $j['html'] = purify_html($j['html'],$allow_position); if($j['html'] != $orig) { - logger('oembed html was purified. original: ' . $orig . ' purified: ' . $j['html'], LOGGER_DEBUG, LOG_INFO); + logger('oembed html was purified. original: ' . $orig . ' purified: ' . $j['html'], LOGGER_DEBUG, LOG_INFO); } $orig_len = mb_strlen(preg_replace('/\s+/','',$orig)); $new_len = mb_strlen(preg_replace('/\s+/','',$j['html'])); - if(stripos($orig,'<script') || (! $new_len)) + if(stripos($orig,'<script') || (! $new_len)) $j['type'] = 'error'; elseif($orig_len) { $ratio = $new_len / $orig_len; @@ -292,7 +293,7 @@ function oembed_fetch_url($embedurl){ } - + function oembed_format_object($j){ $embedurl = $j['embedurl']; @@ -308,7 +309,7 @@ function oembed_format_object($j){ $tw = (isset($j['thumbnail_width'])) ? $j['thumbnail_width'] : 200; $th = (isset($j['thumbnail_height'])) ? $j['thumbnail_height'] : 180; $tr = $tw/$th; - + $th=120; $tw = $th*$tr; $tpl=get_markup_template('oembed_video.tpl'); @@ -320,7 +321,7 @@ function oembed_format_object($j){ '$th'=>$th, '$turl'=> $j['thumbnail_url'], )); - + } else { $ret=$jhtml; } @@ -329,7 +330,7 @@ function oembed_format_object($j){ case "photo": { $ret.= "<img width='".$j['width']."' src='".$j['url']."'>"; $ret.="<br>"; - }; break; + }; break; case "link": { if($j['thumbnail_url']) { if(is_matrix_url($embedurl)) { @@ -340,14 +341,14 @@ function oembed_format_object($j){ } //$ret = "<a href='".$embedurl."'>".$j['title']."</a>"; - }; break; + }; break; case 'pdf': { $ret = $j['html']; break; } case "rich": { - // not so safe.. + // not so safe.. if($j['zrl']) { $ret = ((preg_match('/^<div[^>]+>(.*?)<\/div>$/is',$j['html'],$o)) ? $o[1] : $j['html']); } else { @@ -382,7 +383,7 @@ function oembed_iframe($src,$width,$height) { $scroll = ' scrolling="auto" '; } - // try and leave some room for the description line. + // try and leave some room for the description line. $height = intval($height) + 80; $width = intval($width) + 40; @@ -390,8 +391,8 @@ function oembed_iframe($src,$width,$height) { // Make sure any children are sandboxed within their own iframe. - return '<iframe ' . $scroll . 'height="' . $height . '" width="' . $width . '" src="' . $s . '" allowfullscreen frameborder="no" >' - . t('Embedded content') . '</iframe>'; + return '<iframe ' . $scroll . 'height="' . $height . '" width="' . $width . '" src="' . $s . '" allowfullscreen frameborder="no" >' + . t('Embedded content') . '</iframe>'; } @@ -418,7 +419,7 @@ function oe_get_inner_html( $node ) { $innerHTML .= $child->ownerDocument->saveXML( $child ); } return $innerHTML; -} +} /** * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span> @@ -427,17 +428,20 @@ function oe_get_inner_html( $node ) { function oembed_html2bbcode($text) { // start parser only if 'oembed' is in text if (strpos($text, "oembed")){ - + // convert non ascii chars to html entities $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text)); - + // If it doesn't parse at all, just return the text. - $dom = @DOMDocument::loadHTML($html_text); + + $dom = new DOMDocument; + @$dom->loadHTML($html_text); if(! $dom) return $text; + $xpath = new DOMXPath($dom); $attr = "oembed"; - + $xattr = oe_build_xpath("class","oembed"); $entries = $xpath->query("//span[$xattr]"); @@ -449,7 +453,7 @@ function oembed_html2bbcode($text) { return oe_get_inner_html( $dom->getElementsByTagName("body")->item(0) ); } else { return $text; - } + } } diff --git a/include/plugin.php b/include/plugin.php index 269903373..5b041f228 100644 --- a/include/plugin.php +++ b/include/plugin.php @@ -929,8 +929,9 @@ function script_path() { } function head_add_js($src, $priority = 0) { - if(! is_array(App::$js_sources[$priority])) - App::$js_sources[$priority] = array(); + if(isset(App::$js_sources[$priority]) && !is_array(App::$js_sources[$priority])) + App::$js_sources[$priority] = []; + App::$js_sources[$priority][] = $src; } diff --git a/include/security.php b/include/security.php index 40905925f..066b1dcf4 100644 --- a/include/security.php +++ b/include/security.php @@ -18,6 +18,7 @@ function authenticate_success($user_record, $channel = null, $login_initial = fa $_SESSION['addr'] = $_SERVER['REMOTE_ADDR']; $lastlog_updated = false; + $uid_to_load = null; if (x($user_record, 'account_id')) { App::$account = $user_record; diff --git a/include/text.php b/include/text.php index 1e08d136c..b7cc0ba20 100644 --- a/include/text.php +++ b/include/text.php @@ -9,6 +9,7 @@ use Michelf\MarkdownExtra; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\Exception\UnableToBuildUuidException; +use Zotlabs\Lib\Crypto; use Zotlabs\Lib\SvgSanitizer; require_once("include/bbcode.php"); @@ -3248,7 +3249,7 @@ function item_url_replace($channel,&$item,$old,$new,$oldnick = '') { $item['body'] = preg_replace("/(\[zrl=".preg_quote($old,'/')."\/(photo|photos|gallery)\/".$channel['channel_address'].".+\]\[zmg=\d+x\d+\])".preg_quote($old,'/')."\/(.+\[\/zmg\])/", '${1}'.$new.'/${3}', $item['body']); $item['body'] = preg_replace("/".preg_quote($old,'/')."\/(search|\w+\/".$channel['channel_address'].")/", $new.'/${1}', $item['body']); - $item['sig'] = base64url_encode(rsa_sign($item['body'],$channel['channel_prvkey'])); + $item['sig'] = base64url_encode(Crypto::sign($item['body'],$channel['channel_prvkey'])); $item['item_verified'] = 1; $item['plink'] = str_replace($old,$new,$item['plink']); @@ -3881,6 +3882,14 @@ function unserialise($x) { return ((is_array($y)) ? $y : $x); } +function obscurify($s) { + return str_rot47(base64url_encode($s)); +} + +function unobscurify($s) { + return base64url_decode(str_rot47($s)); +} + /** * @brief Remove new lines and tabs from strings. * diff --git a/include/xchan.php b/include/xchan.php index 5de828e7f..07fdb8b47 100644 --- a/include/xchan.php +++ b/include/xchan.php @@ -1,5 +1,6 @@ <?php +use Zotlabs\Lib\Crypto; use Zotlabs\Web\HTTPSig; use Zotlabs\Lib\Libzot; @@ -85,7 +86,7 @@ function xchan_store($arr) { } if($arr['network'] === 'zot') { - if((! $arr['key']) || (! rsa_verify($arr['guid'],base64url_decode($arr['guid_sig']),$arr['key']))) { + if((! $arr['key']) || (! Crypto::verify($arr['guid'],base64url_decode($arr['guid_sig']),$arr['key']))) { logger('Unable to verify signature for ' . $arr['hash']); return false; } @@ -102,7 +103,7 @@ function xchan_store($arr) { if($k === 'photo') { continue; } - + if(in_array($columns,'xchan_' . $k)) $x['xchan_' . $k] = escape_tags($v); } @@ -112,7 +113,7 @@ function xchan_store($arr) { $x['xchan_system'] = false; $result = xchan_store_lowlevel($x); - + if(! $result) return $result; } @@ -207,9 +208,9 @@ function xchan_keychange_acl($table,$column,$oldxchan,$newxchan) { if($r) { foreach($r as $rv) { $z = q("update $table set $allow = '%s', $deny = '%s' where $column = %d", - dbesc(str_replace('<' . $oldxchan['xchan_hash'] . '>', '<' . $newxchan['xchan_hash'] . '>', + dbesc(str_replace('<' . $oldxchan['xchan_hash'] . '>', '<' . $newxchan['xchan_hash'] . '>', $rv[$allow])), - dbesc(str_replace('<' . $oldxchan['xchan_hash'] . '>', '<' . $newxchan['xchan_hash'] . '>', + dbesc(str_replace('<' . $oldxchan['xchan_hash'] . '>', '<' . $newxchan['xchan_hash'] . '>', $rv[$deny])), intval($rv[$column]) ); @@ -243,7 +244,7 @@ function xchan_change_key($oldx,$newx,$data) { 'xprof' => 'xprof_hash', 'xtag' => 'xtag_hash' ]; - + $acls = [ 'channel' => 'channel_id', diff --git a/include/zid.php b/include/zid.php index e24b0035d..75414a691 100644 --- a/include/zid.php +++ b/include/zid.php @@ -58,7 +58,7 @@ function zid($s, $address = '') { $mine_parsed = parse_url($mine); $s_parsed = parse_url($s); - if($mine_parsed['host'] === $s_parsed['host']) + if(isset($mine_parsed['host']) && isset($s_parsed['host']) && $mine_parsed['host'] === $s_parsed['host']) $url_match = true; if ($mine && $myaddr && (! $url_match)) @@ -209,21 +209,21 @@ function red_zrl_callback($matches) { // Catch and exclude trailing punctuation preg_match("/[.,;:!?)]*$/i", $matches[2], $pts); $matches[2] = substr($matches[2], 0, strlen($matches[2])-strlen($pts[0])); - + $zrl = is_matrix_url($matches[2]); - + $t = strip_zids($matches[2]); if($t !== $matches[2]) { $zrl = true; $matches[2] = $t; } - + if($matches[1] === '#^') $matches[1] = ''; - + if($zrl) return $matches[1] . '#^[zrl=' . $matches[2] . ']' . $matches[2] . '[/zrl]' . $pts[0]; - + return $matches[1] . '#^[url=' . $matches[2] . ']' . $matches[2] . '[/url]' . $pts[0]; } diff --git a/include/zot.php b/include/zot.php index d61873ba2..634561fa3 100644 --- a/include/zot.php +++ b/include/zot.php @@ -8,6 +8,7 @@ * */ +use Zotlabs\Lib\Crypto; use Zotlabs\Lib\DReport; use Zotlabs\Lib\Libzot; use Zotlabs\Lib\Activity; @@ -123,15 +124,15 @@ function zot_build_packet($channel, $type = 'notify', $recipients = null, $remot 'type' => $type, 'sender' => [ 'guid' => $channel['channel_guid'], - 'guid_sig' => base64url_encode(rsa_sign($channel['channel_guid'],$channel['channel_prvkey'],$sig_method)), + 'guid_sig' => base64url_encode(Crypto::sign($channel['channel_guid'],$channel['channel_prvkey'],$sig_method)), 'url' => z_root(), - 'url_sig' => base64url_encode(rsa_sign(z_root(),$channel['channel_prvkey'],$sig_method)), + 'url_sig' => base64url_encode(Crypto::sign(z_root(),$channel['channel_prvkey'],$sig_method)), 'sitekey' => get_config('system','pubkey') ], 'callback' => '/post', 'version' => Zotlabs\Lib\System::get_zot_revision(), - 'encryption' => crypto_methods(), - 'signing' => signing_methods() + 'encryption' => Crypto::methods(), + 'signing' => Crypto::signing_methods() ]; if ($recipients) { @@ -143,7 +144,7 @@ function zot_build_packet($channel, $type = 'notify', $recipients = null, $remot if ($secret) { $data['secret'] = preg_replace('/[^0-9a-fA-F]/','',$secret); - $data['secret_sig'] = base64url_encode(rsa_sign($secret,$channel['channel_prvkey'],$sig_method)); + $data['secret_sig'] = base64url_encode(Crypto::sign($secret,$channel['channel_prvkey'],$sig_method)); } if ($extra) { @@ -157,7 +158,7 @@ function zot_build_packet($channel, $type = 'notify', $recipients = null, $remot if($remote_key) { $algorithm = zot_best_algorithm($methods); - $data = crypto_encapsulate(json_encode($data),$remote_key, $algorithm); + $data = Crypto::encapsulate(json_encode($data),$remote_key, $algorithm); } return json_encode($data); @@ -197,15 +198,15 @@ function zot6_build_packet($channel, $type = 'notify', $recipients = null, $msg 'type' => $type, 'sender' => [ 'guid' => $channel['channel_guid'], - 'guid_sig' => base64url_encode(rsa_sign($channel['channel_guid'],$channel['channel_prvkey'],$sig_method)), + 'guid_sig' => base64url_encode(Crypto::sign($channel['channel_guid'],$channel['channel_prvkey'],$sig_method)), 'url' => z_root(), - 'url_sig' => base64url_encode(rsa_sign(z_root(),$channel['channel_prvkey'],$sig_method)), + 'url_sig' => base64url_encode(Crypto::sign(z_root(),$channel['channel_prvkey'],$sig_method)), 'sitekey' => get_config('system','pubkey') ], 'callback' => '/post', 'version' => Zotlabs\Lib\System::get_zot_revision(), - 'encryption' => crypto_methods(), - 'signing' => signing_methods() + 'encryption' => Crypto::methods(), + 'signing' => Crypto::signing_methods() ]; if ($recipients) { @@ -221,7 +222,7 @@ function zot6_build_packet($channel, $type = 'notify', $recipients = null, $msg if ($secret) { $data['secret'] = preg_replace('/[^0-9a-fA-F]/','',$secret); - $data['secret_sig'] = base64url_encode(rsa_sign($secret,$channel['channel_prvkey'],$sig_method)); + $data['secret_sig'] = base64url_encode(Crypto::sign($secret,$channel['channel_prvkey'],$sig_method)); } if ($extra) { @@ -235,7 +236,7 @@ function zot6_build_packet($channel, $type = 'notify', $recipients = null, $msg if($remote_key) { $algorithm = zot_best_algorithm($methods); - $data = crypto_encapsulate(json_encode($data),$remote_key, $algorithm); + $data = Crypto::encapsulate(json_encode($data),$remote_key, $algorithm); } return json_encode($data); @@ -249,7 +250,7 @@ function zot6_build_packet($channel, $type = 'notify', $recipients = null, $msg * * @param string $methods * comma separated list of encryption methods - * @return string first match from our site method preferences crypto_methods() array + * @return string first match from our site method preferences Crypto::methods() array * of a method which is common to both sites; or 'aes256cbc' if no matches are found. */ function zot_best_algorithm($methods) { @@ -272,7 +273,7 @@ function zot_best_algorithm($methods) { if($methods) { $x = explode(',', $methods); if($x) { - $y = crypto_methods(); + $y = Crypto::methods(); if($y) { foreach($y as $yv) { $yv = trim($yv); @@ -443,7 +444,7 @@ function zot_refresh($them, $channel = null, $force = false) { $signed_token = ((is_array($j) && array_key_exists('signed_token',$j)) ? $j['signed_token'] : null); if($signed_token) { - $valid = rsa_verify('token.' . $token,base64url_decode($signed_token),$j['key']); + $valid = Crypto::verify('token.' . $token,base64url_decode($signed_token),$j['key']); if(! $valid) { logger('invalid signed token: ' . $url . $rhs, LOGGER_NORMAL, LOG_ERR); return false; @@ -461,16 +462,18 @@ function zot_refresh($them, $channel = null, $force = false) { if($channel) { if($j['permissions']['data']) { - $permissions = crypto_unencapsulate( + $permissions = Crypto::unencapsulate( [ + 'encrypted' => true, 'data' => $j['permissions']['data'], 'key' => $j['permissions']['key'], 'iv' => $j['permissions']['iv'], 'alg' => $j['permissions']['alg'] ], $channel['channel_prvkey']); - if($permissions) + if($permissions) { $permissions = json_decode($permissions,true); + } logger('decrypted permissions: ' . print_r($permissions,true), LOGGER_DATA, LOG_DEBUG); } else @@ -719,8 +722,8 @@ function zot_register_hub($arr) { */ foreach($sig_methods as $method) { - if((rsa_verify($arr['guid'],base64url_decode($arr['guid_sig']),$record['key'],$method)) - && (rsa_verify($arr['url'],base64url_decode($arr['url_sig']),$record['key'],$method)) + if((Crypto::verify($arr['guid'],base64url_decode($arr['guid_sig']),$record['key'],$method)) + && (Crypto::verify($arr['url'],base64url_decode($arr['url_sig']),$record['key'],$method)) && ($arr['guid'] === $record['guid']) && ($arr['guid_sig'] === $record['guid_sig'])) { $c = import_xchan($record); @@ -790,7 +793,7 @@ function import_xchan($arr, $ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { $verified = false; foreach($sig_methods as $method) { - if(! rsa_verify($arr['guid'],base64url_decode($arr['guid_sig']),$arr['key'],$method)) { + if(! Crypto::verify($arr['guid'],base64url_decode($arr['guid_sig']),$arr['key'],$method)) { logger('Unable to verify channel signature for ' . $arr['address'] . ' using ' . $method); continue; } @@ -925,28 +928,28 @@ function import_xchan($arr, $ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { $local = q("select channel_account_id, channel_id from channel where channel_portable_id = '%s' limit 1", dbesc($xchan_hash) ); - + if($local) { - // @FIXME This should be removed in future when profile photo update by file sync procedure will be applied + // @FIXME This should be removed in future when profile photo update by file sync procedure will be applied // on most hubs in the network // <--- $ph = z_fetch_url($arr['photo'], true); - + if($ph['success']) { - + // Do not fetch already received thumbnails $x = q("SELECT resource_id FROM photo WHERE uid = %d AND imgscale = %d AND filesize = %d LIMIT 1", intval($local[0]['channel_id']), intval(PHOTO_RES_PROFILE_300), strlen($ph['body']) - ); + ); if($x) $hash = $x[0]['resource_id']; else $hash = import_channel_photo($ph['body'], $arr['photo_mimetype'], $local[0]['channel_account_id'], $local[0]['channel_id']); } - + if($hash) { // unless proven otherwise $is_default_profile = 1; @@ -972,7 +975,7 @@ function import_xchan($arr, $ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { } } // ---> - + // reset the names in case they got messed up when we had a bug in this function $photos = array( z_root() . '/photo/profile/l/' . $local[0]['channel_id'], @@ -1128,7 +1131,8 @@ function zot_process_response($hub, $arr, $outq) { if(is_array($x) && array_key_exists('delivery_report',$x) && is_array($x['delivery_report'])) { if(array_key_exists('iv',$x['delivery_report'])) { - $j = crypto_unencapsulate($x['delivery_report'],get_config('system','prvkey')); + $x['delivery_report']['encrypted'] = true; + $j = Crypto::unencapsulate($x['delivery_report'],get_config('system','prvkey')); if($j) { $x['delivery_report'] = json_decode($j,true); } @@ -1253,14 +1257,14 @@ function zot_fetch($arr) { $data = [ 'type' => 'pickup', 'url' => z_root(), - 'callback_sig' => base64url_encode(rsa_sign(z_root() . '/post', get_config('system','prvkey'))), + 'callback_sig' => base64url_encode(Crypto::sign(z_root() . '/post', get_config('system','prvkey'))), 'callback' => z_root() . '/post', 'secret' => $secret, - 'secret_sig' => base64url_encode(rsa_sign($secret, get_config('system','prvkey'))) + 'secret_sig' => base64url_encode(Crypto::sign($secret, get_config('system','prvkey'))) ]; $algorithm = zot_best_algorithm($hub['site_crypto']); - $datatosend = json_encode(crypto_encapsulate(json_encode($data),$hub['hubloc_sitekey'], $algorithm)); + $datatosend = json_encode(Crypto::encapsulate(json_encode($data),$hub['hubloc_sitekey'], $algorithm)); $import = zot_zot($url,$datatosend); @@ -1272,7 +1276,7 @@ function zot_fetch($arr) { $result = zot_import($import, $arr['sender']['url']); if($result) { - $result = crypto_encapsulate(json_encode($result),$hub['hubloc_sitekey'], $algorithm); + $result = Crypto::encapsulate(json_encode($result),$hub['hubloc_sitekey'], $algorithm); return $result; } @@ -1314,7 +1318,8 @@ function zot_import($arr, $sender_url) { } if(array_key_exists('iv', $data)) { - $data = json_decode(crypto_unencapsulate($data,get_config('system','prvkey')),true); + $data['encrypted'] = true; + $data = json_decode(Crypto::unencapsulate($data,get_config('system','prvkey')),true); } if(! is_array($data)) { @@ -1342,7 +1347,8 @@ function zot_import($arr, $sender_url) { $result = null; if(array_key_exists('iv',$i['notify'])) { - $i['notify'] = json_decode(crypto_unencapsulate($i['notify'],get_config('system','prvkey')),true); + $i['notify']['encrypted'] = true; + $i['notify'] = json_decode(Crypto::unencapsulate($i['notify'],get_config('system','prvkey')),true); } logger('Notify: ' . print_r($i['notify'],true), LOGGER_DATA, LOG_DEBUG); @@ -2466,7 +2472,7 @@ 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']))) { + if((! $z) || (! Crypto::verify($arr['target'] . '.' . $arr['rating'] . '.' . $arr['rating_text'], base64url_decode($arr['signature']),$z[0]['xchan_pubkey']))) { logger('failed to verify rating'); return; } @@ -2652,7 +2658,7 @@ function sync_locations($sender, $arr, $absolute = false) { $arr['locations'][0]['primary'] = true; foreach($arr['locations'] as $location) { - if(! rsa_verify($location['url'],base64url_decode($location['url_sig']),$sender['key'])) { + if(! Crypto::verify($location['url'],base64url_decode($location['url_sig']),$sender['key'])) { logger('Unable to verify site signature for ' . $location['url']); $ret['message'] .= sprintf( t('Unable to verify site signature for %s'), $location['url']) . EOL; continue; @@ -3126,7 +3132,7 @@ 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(! Crypto::verify($arr['url'], base64url_decode($arr['url_sig']), $pubkey)) { logger('Bad url_sig'); return false; } @@ -3509,12 +3515,12 @@ function process_channel_sync_delivery($sender, $arr, $deliveries) { if($keychange) { // verify the keychange operation - if(! rsa_verify($arr['channel']['channel_pubkey'],base64url_decode($arr['keychange']['new_sig']),$channel['channel_prvkey'])) { + if(! Crypto::verify($arr['channel']['channel_pubkey'],base64url_decode($arr['keychange']['new_sig']),$channel['channel_prvkey'])) { logger('sync keychange: verification failed'); continue; } - $sig = base64url_encode(rsa_sign($channel['channel_guid'],$arr['channel']['channel_prvkey'])); + $sig = base64url_encode(Crypto::sign($channel['channel_guid'],$arr['channel']['channel_prvkey'])); $hash = make_xchan_hash($channel['channel_guid'],$sig); @@ -3551,7 +3557,7 @@ function process_channel_sync_delivery($sender, $arr, $deliveries) { foreach($h as $hv) { $hv['hubloc_guid_sig'] = $sig; $hv['hubloc_hash'] = $hash; - $hv['hubloc_url_sig'] = base64url_encode(rsa_sign(z_root(),$channel['channel_prvkey'])); + $hv['hubloc_url_sig'] = base64url_encode(Crypto::sign(z_root(),$channel['channel_prvkey'])); hubloc_store_lowlevel($hv); } } @@ -4329,7 +4335,7 @@ function zot_rekey_request($sender,$data) { $xchan = $r[0]; - if(! rsa_verify($data['new_key'],base64url_decode($data['new_sig']),$xchan['xchan_pubkey'])) { + if(! Crypto::verify($data['new_key'],base64url_decode($data['new_sig']),$xchan['xchan_pubkey'])) { json_return_and_die($ret); } @@ -4367,7 +4373,7 @@ function zotinfo($arr) { $feed = ((x($arr,'feed')) ? intval($arr['feed']) : 0); if($ztarget) { - if((! $zkey) || (! $zsig) || (! rsa_verify($ztarget,base64url_decode($zsig),$zkey))) { + if((! $zkey) || (! $zsig) || (! Crypto::verify($ztarget,base64url_decode($zsig),$zkey))) { logger('zfinger: invalid target signature'); $ret['message'] = t("invalid target signature"); return($ret); @@ -4531,7 +4537,7 @@ function zotinfo($arr) { // Communication details if($token) - $ret['signed_token'] = base64url_encode(rsa_sign('token.' . $token,$e['channel_prvkey'],$sig_method)); + $ret['signed_token'] = base64url_encode(Crypto::sign('token.' . $token,$e['channel_prvkey'],$sig_method)); $ret['guid'] = $e['xchan_guid']; @@ -4587,7 +4593,7 @@ function zotinfo($arr) { // because ztarget refers to an xchan and we don't necessarily know the origination // location. - $ret['permissions'] = (($ztarget && $zkey) ? crypto_encapsulate(json_encode($permissions),$zkey) : $permissions); + $ret['permissions'] = (($ztarget && $zkey) ? crypto_encapsulate(json_encode($permissions),$zkey,) : $permissions); if($permissions['view_profile']) $ret['profile'] = $profile; @@ -4622,9 +4628,9 @@ function zot_site_info($channel_key = '') { $ret['site'] = []; $ret['site']['url'] = z_root(); if($channel_key) { - $ret['site']['url_sig'] = base64url_encode(rsa_sign(z_root(),$channel_key,$sig_method)); + $ret['site']['url_sig'] = base64url_encode(Crypto::sign(z_root(),$channel_key,$sig_method)); } - $ret['site']['url_site_sig'] = base64url_encode(rsa_sign(z_root(),$signing_key,$sig_method)); + $ret['site']['url_site_sig'] = base64url_encode(Crypto::sign(z_root(),$signing_key,$sig_method)); $ret['site']['post'] = z_root() . '/post'; $ret['site']['openWebAuth'] = z_root() . '/owa'; $ret['site']['authRedirect'] = z_root() . '/magic'; @@ -4644,8 +4650,8 @@ function zot_site_info($channel_key = '') { $ret['site']['directory_url'] = z_root() . '/dirsearch'; - $ret['site']['encryption'] = crypto_methods(); - $ret['site']['signing'] = signing_methods(); + $ret['site']['encryption'] = Crypto::methods(); + $ret['site']['signing'] = Crypto::signing_methods(); $ret['site']['zot'] = Zotlabs\Lib\System::get_zot_revision(); // hide detailed site information if you're off the grid @@ -4724,7 +4730,7 @@ function check_zotinfo($channel, $locations, &$ret) { // the sys channel must have a location (hubloc) $valid_location = false; if((count($locations) === 1) && ($locations[0]['primary']) && (! $locations[0]['deleted'])) { - if((rsa_verify($locations[0]['url'],base64url_decode($locations[0]['url_sig']),$channel['channel_pubkey'])) + if((Crypto::verify($locations[0]['url'],base64url_decode($locations[0]['url_sig']),$channel['channel_pubkey'])) && ($locations[0]['sitekey'] === get_config('system','pubkey')) && ($locations[0]['url'] === z_root())) $valid_location = true; @@ -4752,7 +4758,7 @@ function check_zotinfo($channel, $locations, &$ret) { 'hubloc_network' => 'zot', 'hubloc_primary' => 1, 'hubloc_url' => z_root(), - 'hubloc_url_sig' => base64url_encode(rsa_sign(z_root(),$channel['channel_prvkey'])), + 'hubloc_url_sig' => base64url_encode(Crypto::sign(z_root(),$channel['channel_prvkey'])), 'hubloc_host' => App::get_hostname(), 'hubloc_callback' => z_root() . '/post', 'hubloc_sitekey' => get_config('system','pubkey'), @@ -4931,7 +4937,7 @@ function zot_reply_ping() { $ret['success'] = true; $ret['site'] = array(); $ret['site']['url'] = z_root(); - $ret['site']['url_sig'] = base64url_encode(rsa_sign(z_root(),get_config('system','prvkey'))); + $ret['site']['url_sig'] = base64url_encode(Crypto::sign(z_root(),get_config('system','prvkey'))); $ret['site']['sitekey'] = get_config('system','pubkey'); json_return_and_die($ret); @@ -4979,10 +4985,10 @@ function zot_reply_pickup($data) { logger('mod_zot: Checking sitekey: ' . $sitekey, LOGGER_DATA, LOG_DEBUG); - if(rsa_verify($data['callback'],base64url_decode($data['callback_sig']),$sitekey)) { + if(Crypto::verify($data['callback'],base64url_decode($data['callback_sig']),$sitekey)) { $forgery = false; } - if(rsa_verify($data['secret'],base64url_decode($data['secret_sig']),$sitekey)) { + if(Crypto::verify($data['secret'],base64url_decode($data['secret_sig']),$sitekey)) { $secret_fail = false; } if((! $forgery) && (! $secret_fail)) @@ -5076,7 +5082,7 @@ function zot_reply_pickup($data) { ); $algorithm = zot_best_algorithm(($x) ? $x[0]['site_crypto'] : ''); - $encrypted = crypto_encapsulate(json_encode($ret),$sitekey,$algorithm); + $encrypted = Crypto::encapsulate(json_encode($ret),$sitekey,$algorithm); json_return_and_die($encrypted); // @FIXME: There is a possibility that the transmission will get interrupted @@ -5133,7 +5139,7 @@ function zot_reply_auth_check($data,$encrypted_packet) { // First verify their signature. We will have obtained a zot-info packet from them as part of the sender // verification. - if ((! $y) || (! rsa_verify($data['secret'], base64url_decode($data['secret_sig']),$y[0]['xchan_pubkey']))) { + if ((! $y) || (! Crypto::verify($data['secret'], base64url_decode($data['secret_sig']),$y[0]['xchan_pubkey']))) { logger('mod_zot: auth_check: sender not found or secret_sig invalid.'); $ret['message'] .= 'sender not found or sig invalid ' . print_r($y,true) . EOL; @@ -5158,7 +5164,7 @@ function zot_reply_auth_check($data,$encrypted_packet) { json_return_and_die($ret); } - $confirm = base64url_encode(rsa_sign($data['secret'] . $recip_hash,$c[0]['channel_prvkey'])); + $confirm = base64url_encode(Crypto::sign($data['secret'] . $recip_hash,$c[0]['channel_prvkey'])); // This additionally checks for forged sites since we already stored the expected result in meta // and we've already verified that this is them via zot_gethub() and that their key signed our token |