psr12 updates

This commit is contained in:
nobody 2021-12-03 10:02:31 +11:00
parent 389b2e5b17
commit f602a393a5
687 changed files with 63552 additions and 62782 deletions

View file

@ -5,5 +5,5 @@ self.addEventListener('install', function(e) {
self.addEventListener('fetch', function(e) { self.addEventListener('fetch', function(e) {
// nothing here yet // nothing here yet
return;
}); });

View file

@ -12,7 +12,8 @@ namespace Zotlabs\Access;
* and @ref ::Zotlabs::Lib::Permcat "Permcat"s individual content ACLs are evaluated. * and @ref ::Zotlabs::Lib::Permcat "Permcat"s individual content ACLs are evaluated.
* These answer the question "Can Joe view *this* album/photo?". * These answer the question "Can Joe view *this* album/photo?".
*/ */
class AccessControl { class AccessControl
{
/** /**
* @brief Allow contacts * @brief Allow contacts
* @var string * @var string
@ -36,7 +37,7 @@ class AccessControl {
/** /**
* @brief Indicates if we are using the default constructor values or * @brief Indicates if we are using the default constructor values or
* values that have been set explicitly. * values that have been set explicitly.
* @var boolean * @var bool
*/ */
private $explicit; private $explicit;
@ -53,14 +54,14 @@ class AccessControl {
* * \e string \b channel_deny_cid => string of denied cids * * \e string \b channel_deny_cid => string of denied cids
* * \e string \b channel_deny_gid => string of denied gids * * \e string \b channel_deny_gid => string of denied gids
*/ */
function __construct($channel) { public function __construct($channel)
if($channel) { {
if ($channel) {
$this->allow_cid = $channel['channel_allow_cid']; $this->allow_cid = $channel['channel_allow_cid'];
$this->allow_gid = $channel['channel_allow_gid']; $this->allow_gid = $channel['channel_allow_gid'];
$this->deny_cid = $channel['channel_deny_cid']; $this->deny_cid = $channel['channel_deny_cid'];
$this->deny_gid = $channel['channel_deny_gid']; $this->deny_gid = $channel['channel_deny_gid'];
} } else {
else {
$this->allow_cid = ''; $this->allow_cid = '';
$this->allow_gid = ''; $this->allow_gid = '';
$this->deny_cid = ''; $this->deny_cid = '';
@ -74,9 +75,10 @@ class AccessControl {
* @brief Get if we are using the default constructor values * @brief Get if we are using the default constructor values
* or values that have been set explicitly. * or values that have been set explicitly.
* *
* @return boolean * @return bool
*/ */
function get_explicit() { public function get_explicit()
{
return $this->explicit; return $this->explicit;
} }
@ -92,9 +94,10 @@ class AccessControl {
* * \e string \b allow_gid => string of allowed gids * * \e string \b allow_gid => string of allowed gids
* * \e string \b deny_cid => string of denied cids * * \e string \b deny_cid => string of denied cids
* * \e string \b deny_gid => string of denied gids * * \e string \b deny_gid => string of denied gids
* @param boolean $explicit (optional) default true * @param bool $explicit (optional) default true
*/ */
function set($arr, $explicit = true) { public function set($arr, $explicit = true)
{
$this->allow_cid = $arr['allow_cid']; $this->allow_cid = $arr['allow_cid'];
$this->allow_gid = $arr['allow_gid']; $this->allow_gid = $arr['allow_gid'];
$this->deny_cid = $arr['deny_cid']; $this->deny_cid = $arr['deny_cid'];
@ -113,7 +116,8 @@ class AccessControl {
* * \e string \b deny_cid => string of denied cids * * \e string \b deny_cid => string of denied cids
* * \e string \b deny_gid => string of denied gids * * \e string \b deny_gid => string of denied gids
*/ */
function get() { public function get()
{
return [ return [
'allow_cid' => $this->allow_cid, 'allow_cid' => $this->allow_cid,
'allow_gid' => $this->allow_gid, 'allow_gid' => $this->allow_gid,
@ -137,9 +141,10 @@ class AccessControl {
* * \e array|string \b group_allow => array with gids or comma-seperated string * * \e array|string \b group_allow => array with gids or comma-seperated string
* * \e array|string \b contact_deny => array with cids or comma-seperated string * * \e array|string \b contact_deny => array with cids or comma-seperated string
* * \e array|string \b group_deny => array with gids or comma-seperated string * * \e array|string \b group_deny => array with gids or comma-seperated string
* @param boolean $explicit (optional) default true * @param bool $explicit (optional) default true
*/ */
function set_from_array($arr, $explicit = true) { public function set_from_array($arr, $explicit = true)
{
$this->allow_cid = perms2str((is_array($arr['contact_allow'])) $this->allow_cid = perms2str((is_array($arr['contact_allow']))
? $arr['contact_allow'] : explode(',', $arr['contact_allow'])); ? $arr['contact_allow'] : explode(',', $arr['contact_allow']));
$this->allow_gid = perms2str((is_array($arr['group_allow'])) $this->allow_gid = perms2str((is_array($arr['group_allow']))
@ -155,10 +160,10 @@ class AccessControl {
/** /**
* @brief Returns true if any access lists component is set. * @brief Returns true if any access lists component is set.
* *
* @return boolean Return true if any of allow_* deny_* values is set. * @return bool Return true if any of allow_* deny_* values is set.
*/ */
function is_private() { public function is_private()
{
return (($this->allow_cid || $this->allow_gid || $this->deny_cid || $this->deny_gid) ? true : false); return (($this->allow_cid || $this->allow_gid || $this->deny_cid || $this->deny_gid) ? true : false);
} }
} }

View file

@ -26,7 +26,8 @@ use Zotlabs\Lib\PConfig;
* *
* @see Permissions * @see Permissions
*/ */
class PermissionLimits { class PermissionLimits
{
/** /**
* @brief Get standard permission limits. * @brief Get standard permission limits.
@ -38,16 +39,18 @@ class PermissionLimits {
* *
* @return array * @return array
*/ */
static public function Std_Limits() { public static function Std_Limits()
{
$limits = []; $limits = [];
$perms = Permissions::Perms(); $perms = Permissions::Perms();
foreach($perms as $k => $v) { foreach ($perms as $k => $v) {
if(strstr($k, 'view')) if (strstr($k, 'view')) {
$limits[$k] = PERMS_PUBLIC; $limits[$k] = PERMS_PUBLIC;
else } else {
$limits[$k] = PERMS_SPECIFIC; $limits[$k] = PERMS_SPECIFIC;
} }
}
return $limits; return $limits;
} }
@ -59,7 +62,8 @@ class PermissionLimits {
* @param string $perm * @param string $perm
* @param int $perm_limit one of PERMS_* constants * @param int $perm_limit one of PERMS_* constants
*/ */
static public function Set($channel_id, $perm, $perm_limit) { public static function Set($channel_id, $perm, $perm_limit)
{
PConfig::Set($channel_id, 'perm_limits', $perm, $perm_limit); PConfig::Set($channel_id, 'perm_limits', $perm, $perm_limit);
} }
@ -77,24 +81,25 @@ class PermissionLimits {
* * \b int if $perm is set, return one of PERMS_* constants for this permission, default 0 * * \b int if $perm is set, return one of PERMS_* constants for this permission, default 0
* * \b array with all permission limits, if $perm is not set * * \b array with all permission limits, if $perm is not set
*/ */
static public function Get($channel_id, $perm = '') { public static function Get($channel_id, $perm = '')
{
if (! intval($channel_id)) { if (! intval($channel_id)) {
return false; return false;
} }
if($perm) { if ($perm) {
$x = PConfig::Get($channel_id, 'perm_limits', $perm); $x = PConfig::Get($channel_id, 'perm_limits', $perm);
if($x === false) { if ($x === false) {
$a = [ 'channel_id' => $channel_id, 'permission' => $perm, 'value' => $x ]; $a = [ 'channel_id' => $channel_id, 'permission' => $perm, 'value' => $x ];
call_hooks('permission_limits_get',$a); call_hooks('permission_limits_get', $a);
return intval($a['value']); return intval($a['value']);
} }
return intval($x); return intval($x);
} }
PConfig::Load($channel_id); PConfig::Load($channel_id);
if(array_key_exists($channel_id, App::$config) && array_key_exists('perm_limits', App::$config[$channel_id])) { if (array_key_exists($channel_id, App::$config) && array_key_exists('perm_limits', App::$config[$channel_id])) {
return App::$config[$channel_id]['perm_limits']; return App::$config[$channel_id]['perm_limits'];
} }

View file

@ -7,7 +7,8 @@ namespace Zotlabs\Access;
* *
* @see Permissions * @see Permissions
*/ */
class PermissionRoles { class PermissionRoles
{
/** /**
* @brief PermissionRoles version. * @brief PermissionRoles version.
@ -16,17 +17,19 @@ class PermissionRoles {
* *
* @return number * @return number
*/ */
static public function version() { public static function version()
{
return 3; return 3;
} }
static function role_perms($role) { public static function role_perms($role)
{
$ret = []; $ret = [];
$ret['role'] = $role; $ret['role'] = $role;
switch($role) { switch ($role) {
case 'social': case 'social':
$ret['perms_auto'] = false; $ret['perms_auto'] = false;
$ret['default_collection'] = false; $ret['default_collection'] = false;
@ -146,16 +149,17 @@ class PermissionRoles {
} }
$x = get_config('system','role_perms'); $x = get_config('system', 'role_perms');
// let system settings over-ride any or all // let system settings over-ride any or all
if($x && is_array($x) && array_key_exists($role,$x)) if ($x && is_array($x) && array_key_exists($role, $x)) {
$ret = array_merge($ret,$x[$role]); $ret = array_merge($ret, $x[$role]);
}
/** /**
* @hooks get_role_perms * @hooks get_role_perms
* * \e array * * \e array
*/ */
$x = [ 'role' => $role, 'result' => $ret ]; $x = ['role' => $role, 'result' => $ret];
call_hooks('get_role_perms', $x); call_hooks('get_role_perms', $x);
@ -171,7 +175,8 @@ class PermissionRoles {
* *
* @return array * @return array
*/ */
static public function roles() { public static function roles()
{
$roles = [ $roles = [
t('Social Networking') => [ t('Social Networking') => [
'social' => t('Social - Normal'), 'social' => t('Social - Normal'),
@ -191,9 +196,8 @@ class PermissionRoles {
]; ];
call_hooks('list_permission_roles',$roles); call_hooks('list_permission_roles', $roles);
return $roles; return $roles;
} }
} }

View file

@ -31,7 +31,8 @@ use Zotlabs\Lib as Zlib;
* something different for a specific permission within the given role. * something different for a specific permission within the given role.
* *
*/ */
class Permissions { class Permissions
{
/** /**
* @brief Permissions version. * @brief Permissions version.
@ -40,7 +41,8 @@ class Permissions {
* *
* @return number * @return number
*/ */
static public function version() { public static function version()
{
return 3; return 3;
} }
@ -50,7 +52,8 @@ class Permissions {
* @param string $filter (optional) only passed to hook permissions_list * @param string $filter (optional) only passed to hook permissions_list
* @return array Associative array with permissions and short description. * @return array Associative array with permissions and short description.
*/ */
static public function Perms($filter = '') { public static function Perms($filter = '')
{
$perms = [ $perms = [
'view_stream' => t('Grant viewing access to and delivery of your channel stream and posts'), 'view_stream' => t('Grant viewing access to and delivery of your channel stream and posts'),
@ -88,12 +91,13 @@ class Permissions {
* *
* @return array Associative array with permissions and short description. * @return array Associative array with permissions and short description.
*/ */
static public function BlockedAnonPerms() { public static function BlockedAnonPerms()
{
$res = []; $res = [];
$perms = PermissionLimits::Std_limits(); $perms = PermissionLimits::Std_limits();
foreach($perms as $perm => $limit) { foreach ($perms as $perm => $limit) {
if($limit != PERMS_PUBLIC) { if ($limit != PERMS_PUBLIC) {
$res[] = $perm; $res[] = $perm;
} }
} }
@ -118,20 +122,22 @@ class Permissions {
* @param array $arr * @param array $arr
* @return array * @return array
*/ */
static public function FilledPerms($arr) { public static function FilledPerms($arr)
if(is_null($arr) || (! is_array($arr))) { {
btlogger('FilledPerms: ' . print_r($arr,true)); if (is_null($arr) || (! is_array($arr))) {
btlogger('FilledPerms: ' . print_r($arr, true));
$arr = []; $arr = [];
} }
$everything = self::Perms(); $everything = self::Perms();
$ret = []; $ret = [];
foreach($everything as $k => $v) { foreach ($everything as $k => $v) {
if(in_array($k, $arr)) if (in_array($k, $arr)) {
$ret[$k] = 1; $ret[$k] = 1;
else } else {
$ret[$k] = 0; $ret[$k] = 0;
} }
}
return $ret; return $ret;
} }
@ -147,10 +153,11 @@ class Permissions {
* * \e string \b name the perm name (e.g. view_stream) * * \e string \b name the perm name (e.g. view_stream)
* * \e int \b value the value of the perm (e.g. 1) * * \e int \b value the value of the perm (e.g. 1)
*/ */
static public function OPerms($arr) { public static function OPerms($arr)
{
$ret = []; $ret = [];
if($arr) { if ($arr) {
foreach($arr as $k => $v) { foreach ($arr as $k => $v) {
$ret[] = [ 'name' => $k, 'value' => $v ]; $ret[] = [ 'name' => $k, 'value' => $v ];
} }
} }
@ -161,18 +168,21 @@ class Permissions {
* @brief * @brief
* *
* @param int $channel_id * @param int $channel_id
* @return boolean|array * @return bool|array
*/ */
static public function FilledAutoperms($channel_id) { public static function FilledAutoperms($channel_id)
if(! intval(get_pconfig($channel_id,'system','autoperms'))) {
if (! intval(get_pconfig($channel_id, 'system', 'autoperms'))) {
return false; return false;
}
$arr = []; $arr = [];
$r = q("select * from pconfig where uid = %d and cat = 'autoperms'", $r = q(
"select * from pconfig where uid = %d and cat = 'autoperms'",
intval($channel_id) intval($channel_id)
); );
if($r) { if ($r) {
foreach($r as $rr) { foreach ($r as $rr) {
$arr[$rr['k']] = intval($rr['v']); $arr[$rr['k']] = intval($rr['v']);
} }
} }
@ -184,16 +194,19 @@ class Permissions {
* *
* @param array $p1 The perms that have to exist in $p2 * @param array $p1 The perms that have to exist in $p2
* @param array $p2 The perms to compare against * @param array $p2 The perms to compare against
* @return boolean true if all perms from $p1 exist also in $p2 * @return bool true if all perms from $p1 exist also in $p2
*/ */
static public function PermsCompare($p1, $p2) { public static function PermsCompare($p1, $p2)
foreach($p1 as $k => $v) { {
if(! array_key_exists($k, $p2)) foreach ($p1 as $k => $v) {
if (! array_key_exists($k, $p2)) {
return false; return false;
}
if($p1[$k] != $p2[$k]) if ($p1[$k] != $p2[$k]) {
return false; return false;
} }
}
return true; return true;
} }
@ -206,7 +219,8 @@ class Permissions {
* * \e array \b perms Permission array * * \e array \b perms Permission array
* * \e int \b automatic 0 or 1 * * \e int \b automatic 0 or 1
*/ */
static public function connect_perms($channel_id) { public static function connect_perms($channel_id)
{
$my_perms = []; $my_perms = [];
$permcat = null; $permcat = null;
@ -214,28 +228,28 @@ class Permissions {
// If a default permcat exists, use that // If a default permcat exists, use that
$pc = ((feature_enabled($channel_id,'permcats')) ? get_pconfig($channel_id,'system','default_permcat') : 'default'); $pc = ((feature_enabled($channel_id, 'permcats')) ? get_pconfig($channel_id, 'system', 'default_permcat') : 'default');
if(! in_array($pc, [ '','default' ])) { if (! in_array($pc, [ '','default' ])) {
$pcp = new Zlib\Permcat($channel_id); $pcp = new Zlib\Permcat($channel_id);
$permcat = $pcp->fetch($pc); $permcat = $pcp->fetch($pc);
if($permcat && $permcat['perms']) { if ($permcat && $permcat['perms']) {
foreach($permcat['perms'] as $p) { foreach ($permcat['perms'] as $p) {
$my_perms[$p['name']] = $p['value']; $my_perms[$p['name']] = $p['value'];
} }
} }
} }
$automatic = intval(get_pconfig($channel_id,'system','autoperms')); $automatic = intval(get_pconfig($channel_id, 'system', 'autoperms'));
// look up the permission role to see if it specified auto-connect // look up the permission role to see if it specified auto-connect
// and if there was no permcat or a default permcat, set the perms // and if there was no permcat or a default permcat, set the perms
// from the role // from the role
$role = get_pconfig($channel_id,'system','permissions_role'); $role = get_pconfig($channel_id, 'system', 'permissions_role');
if($role) { if ($role) {
$xx = PermissionRoles::role_perms($role); $xx = PermissionRoles::role_perms($role);
if((! $my_perms) && ($xx['perms_connect'])) { if ((! $my_perms) && ($xx['perms_connect'])) {
$default_perms = $xx['perms_connect']; $default_perms = $xx['perms_connect'];
$my_perms = Permissions::FilledPerms($default_perms); $my_perms = Permissions::FilledPerms($default_perms);
} }
@ -245,9 +259,9 @@ class Permissions {
// it is likely a custom permissions role. First see if there are any // it is likely a custom permissions role. First see if there are any
// automatic permissions. // automatic permissions.
if(! $my_perms) { if (! $my_perms) {
$m = Permissions::FilledAutoperms($channel_id); $m = Permissions::FilledAutoperms($channel_id);
if($m) { if ($m) {
$my_perms = $m; $my_perms = $m;
} }
} }
@ -256,10 +270,10 @@ class Permissions {
// custom perms but they are not automatic. They will be stored in abconfig with // custom perms but they are not automatic. They will be stored in abconfig with
// the channel's channel_hash (the 'self' connection). // the channel's channel_hash (the 'self' connection).
if(! $my_perms) { if (! $my_perms) {
$c = channelx_by_n($channel_id); $c = channelx_by_n($channel_id);
if($c) { if ($c) {
$my_perms = Permissions::FilledPerms(explode(',',get_abconfig($channel_id,$c['channel_hash'],'system','my_perms',EMPTY_STR))); $my_perms = Permissions::FilledPerms(explode(',', get_abconfig($channel_id, $c['channel_hash'], 'system', 'my_perms', EMPTY_STR)));
} }
} }
@ -267,16 +281,16 @@ class Permissions {
} }
static public function serialise($p) { public static function serialise($p)
{
$n = []; $n = [];
if($p) { if ($p) {
foreach($p as $k => $v) { foreach ($p as $k => $v) {
if(intval($v)) { if (intval($v)) {
$n[] = $k; $n[] = $k;
} }
} }
} }
return implode(',',$n); return implode(',', $n);
} }
} }

View file

@ -5,7 +5,7 @@ namespace Zotlabs\Daemon;
class Addon { class Addon {
static public function run($argc,$argv) { public static function run($argc, $argv) {
call_hooks('daemon_addon',$argv); call_hooks('daemon_addon',$argv);

View file

@ -6,7 +6,7 @@ require_once('include/photos.php');
class CacheThumb { class CacheThumb {
static public function run($argc,$argv) { public static function run($argc, $argv) {
if (! $argc == 2) { if (! $argc == 2) {
return; return;

View file

@ -5,7 +5,7 @@ namespace Zotlabs\Daemon;
class Cache_embeds { class Cache_embeds {
static public function run($argc,$argv) { public static function run($argc, $argv) {
if (! $argc == 2) { if (! $argc == 2) {
return; return;

View file

@ -6,7 +6,7 @@ use Zotlabs\Lib\Img_cache;
class Cache_image { class Cache_image {
static public function run($argc,$argv) { public static function run($argc, $argv) {
cli_startup(); cli_startup();
logger('caching: ' . $argv[1] . ' to ' . $argv[2]); logger('caching: ' . $argv[1] . ' to ' . $argv[2]);

View file

@ -5,7 +5,7 @@ namespace Zotlabs\Daemon;
class Channel_purge { class Channel_purge {
static public function run($argc,$argv) { public static function run($argc, $argv) {
cli_startup(); cli_startup();

View file

@ -7,7 +7,7 @@ require_once('include/hubloc.php');
class Checksites { class Checksites {
static public function run($argc,$argv) { public static function run($argc, $argv) {
logger('checksites: start'); logger('checksites: start');

View file

@ -10,7 +10,7 @@ require_once('include/import.php');
class Content_importer { class Content_importer {
static public function run($argc,$argv) { public static function run($argc, $argv) {
cli_startup(); cli_startup();
$page = $argv[1]; $page = $argv[1];

View file

@ -8,7 +8,7 @@ use Zotlabs\Lib\ASCollection;
class Convo { class Convo {
static public function run($argc,$argv) { public static function run($argc, $argv) {
logger('convo invoked: ' . print_r($argv,true)); logger('convo invoked: ' . print_r($argv,true));

View file

@ -6,7 +6,7 @@ use Zotlabs\Lib\Libsync;
class Cron { class Cron {
static public function run($argc,$argv) { public static function run($argc, $argv) {
$maxsysload = intval(get_config('system','maxloadavg')); $maxsysload = intval(get_config('system','maxloadavg'));
if($maxsysload < 1) if($maxsysload < 1)

View file

@ -6,7 +6,7 @@ use Zotlabs\Lib\Libzot;
class Cron_daily { class Cron_daily {
static public function run($argc,$argv) { public static function run($argc, $argv) {
logger('cron_daily: start'); logger('cron_daily: start');

View file

@ -4,7 +4,7 @@ namespace Zotlabs\Daemon;
class Cron_weekly { class Cron_weekly {
static public function run($argc,$argv) { public static function run($argc, $argv) {
/** /**
* Cron Weekly * Cron Weekly

View file

@ -4,7 +4,7 @@ namespace Zotlabs\Daemon;
class Cronhooks { class Cronhooks {
static public function run($argc,$argv){ public static function run($argc, $argv){
logger('cronhooks: start'); logger('cronhooks: start');

View file

@ -12,7 +12,7 @@ use App;
class CurlAuth { class CurlAuth {
static public function run($argc,$argv) { public static function run($argc, $argv) {
if($argc != 2) if($argc != 2)
return; return;

View file

@ -8,7 +8,7 @@ use Zotlabs\Lib\Queue;
class Deliver { class Deliver {
static public function run($argc,$argv) { public static function run($argc, $argv) {
if($argc < 2) if($argc < 2)
return; return;

View file

@ -5,7 +5,7 @@ namespace Zotlabs\Daemon;
class Deliver_hooks { class Deliver_hooks {
static public function run($argc,$argv) { public static function run($argc, $argv) {
if($argc < 2) if($argc < 2)
return; return;

View file

@ -8,7 +8,7 @@ namespace Zotlabs\Daemon;
class Delxitems { class Delxitems {
static public function run($argc,$argv) { public static function run($argc, $argv) {
cli_startup(); cli_startup();

View file

@ -11,7 +11,7 @@ use Zotlabs\Lib\Queue;
class Directory { class Directory {
static public function run($argc,$argv) { public static function run($argc, $argv) {
if ($argc < 2) { if ($argc < 2) {
return; return;

View file

@ -5,7 +5,7 @@ namespace Zotlabs\Daemon;
class Expire { class Expire {
static public function run($argc,$argv){ public static function run($argc, $argv){
cli_startup(); cli_startup();

View file

@ -10,7 +10,7 @@ require_once('include/import.php');
class File_importer { class File_importer {
static public function run($argc,$argv) { public static function run($argc, $argv) {
cli_startup(); cli_startup();

View file

@ -10,7 +10,7 @@ use Zotlabs\Lib\Zotfinger;
class Gprobe { class Gprobe {
static public function run($argc,$argv) { public static function run($argc, $argv) {
if ($argc != 2) { if ($argc != 2) {

View file

@ -5,7 +5,7 @@ namespace Zotlabs\Daemon;
class Importdoc { class Importdoc {
static public function run($argc,$argv) { public static function run($argc, $argv) {
require_once('include/help.php'); require_once('include/help.php');
@ -13,7 +13,7 @@ class Importdoc {
} }
static public function update_docs_dir($s) { public static function update_docs_dir($s) {
$f = basename($s); $f = basename($s);
$d = dirname($s); $d = dirname($s);
if($s === 'doc/html') if($s === 'doc/html')

View file

@ -6,7 +6,7 @@ use Zotlabs\Lib\Libsync;
class Importfile { class Importfile {
static public function run($argc,$argv){ public static function run($argc, $argv){
logger('Importfile: ' . print_r($argv,true)); logger('Importfile: ' . print_r($argv,true));

View file

@ -78,16 +78,16 @@ require_once('include/bbcode.php');
class Notifier { class Notifier {
static public $deliveries = []; public static $deliveries = [];
static public $recipients = []; public static $recipients = [];
static public $env_recips = []; public static $env_recips = [];
static public $packet_type = 'activity'; public static $packet_type = 'activity';
static public $encoding = 'activitystreams'; public static $encoding = 'activitystreams';
static public $encoded_item = null; public static $encoded_item = null;
static public $channel = null; public static $channel = null;
static public $private = false; public static $private = false;
static public function run($argc,$argv) { public static function run($argc, $argv) {
if ($argc < 3) { if ($argc < 3) {
return; return;

View file

@ -7,7 +7,7 @@ use Zotlabs\Lib\Libzotdir;
class Onedirsync { class Onedirsync {
static public function run($argc,$argv) { public static function run($argc, $argv) {
logger('onedirsync: start ' . intval($argv[1])); logger('onedirsync: start ' . intval($argv[1]));

View file

@ -13,7 +13,7 @@ require_once('include/socgraph.php');
class Onepoll { class Onepoll {
static public function run($argc,$argv) { public static function run($argc, $argv) {
logger('onepoll: start'); logger('onepoll: start');

View file

@ -4,7 +4,7 @@ namespace Zotlabs\Daemon;
class Poller { class Poller {
static public function run($argc,$argv) { public static function run($argc, $argv) {
$maxsysload = intval(get_config('system','maxloadavg')); $maxsysload = intval(get_config('system','maxloadavg'));
if($maxsysload < 1) if($maxsysload < 1)

View file

@ -7,7 +7,7 @@ use Zotlabs\Lib as Zlib;
class Queue { class Queue {
static public function run($argc,$argv) { public static function run($argc, $argv) {
if($argc > 1) if($argc > 1)
$queue_id = $argv[1]; $queue_id = $argv[1];

View file

@ -27,7 +27,7 @@ class Run {
'Cron', 'Cron_daily', 'Cron_weekly', 'Delxitems', 'Expire', 'File_importer', 'Importfile' 'Cron', 'Cron_daily', 'Cron_weekly', 'Delxitems', 'Expire', 'File_importer', 'Importfile'
]; ];
static public function Summon($arr) { public static function Summon($arr) {
if (file_exists('maintenance_lock') || file_exists('cache/maintenance_lock')) { if (file_exists('maintenance_lock') || file_exists('cache/maintenance_lock')) {
return; return;
} }
@ -50,7 +50,7 @@ class Run {
proc_run('php','Zotlabs/Daemon/Run.php',$arr); proc_run('php','Zotlabs/Daemon/Run.php',$arr);
} }
static public function Release($argc,$argv) { public static function Release($argc, $argv) {
cli_startup(); cli_startup();
$hookinfo = [ $hookinfo = [

View file

@ -5,7 +5,7 @@ namespace Zotlabs\Daemon;
class Thumbnail { class Thumbnail {
static public function run($argc,$argv) { public static function run($argc, $argv) {
if (! ($argc == 2)) { if (! ($argc == 2)) {
return; return;

View file

@ -5,7 +5,7 @@ namespace Zotlabs\Daemon;
class Xchan_photo { class Xchan_photo {
static public function run($argc,$argv) { public static function run($argc, $argv) {
if ($argc != 3) { if ($argc != 3) {
return; return;

View file

@ -10,7 +10,7 @@ use App;
*/ */
class Hook { class Hook {
static public function register($hook,$file,$function,$version = 1,$priority = 0) { public static function register($hook, $file, $function, $version = 1, $priority = 0) {
if (is_array($function)) { if (is_array($function)) {
$function = serialize($function); $function = serialize($function);
} }
@ -46,7 +46,7 @@ class Hook {
return $r; return $r;
} }
static public function register_array($file,$arr) { public static function register_array($file, $arr) {
if ($arr) { if ($arr) {
foreach ($arr as $k => $v) { foreach ($arr as $k => $v) {
self::register($k,$file,$v); self::register($k,$file,$v);
@ -55,7 +55,7 @@ class Hook {
} }
static public function unregister($hook,$file,$function,$version = 1,$priority = 0) { public static function unregister($hook, $file, $function, $version = 1, $priority = 0) {
if (is_array($function)) { if (is_array($function)) {
$function = serialize($function); $function = serialize($function);
} }
@ -78,7 +78,7 @@ class Hook {
* @param string $file * @param string $file
*/ */
static public function unregister_by_file($file) { public static function unregister_by_file($file) {
$r = q("DELETE FROM hook WHERE file = '%s' ", $r = q("DELETE FROM hook WHERE file = '%s' ",
dbesc($file) dbesc($file)
); );
@ -107,7 +107,7 @@ class Hook {
* @param int $priority * @param int $priority
* currently not implemented in this function, would require the hook array to be resorted * currently not implemented in this function, would require the hook array to be resorted
*/ */
static public function insert($hook, $fn, $version = 0, $priority = 0) { public static function insert($hook, $fn, $version = 0, $priority = 0) {
if (is_array($fn)) { if (is_array($fn)) {
$fn = serialize($fn); $fn = serialize($fn);
} }

View file

@ -3,15 +3,18 @@
namespace Zotlabs\Extend; namespace Zotlabs\Extend;
class Route { class Route
{
static function register($file,$modname) { public static function register($file, $modname)
{
$rt = self::get(); $rt = self::get();
$rt[] = [ $file, $modname ]; $rt[] = [$file, $modname];
self::set($rt); self::set($rt);
} }
static function unregister($file,$modname) { public static function unregister($file, $modname)
{
$rt = self::get(); $rt = self::get();
if ($rt) { if ($rt) {
$n = []; $n = [];
@ -24,7 +27,8 @@ class Route {
} }
} }
static function unregister_by_file($file) { public static function unregister_by_file($file)
{
$rt = self::get(); $rt = self::get();
if ($rt) { if ($rt) {
$n = []; $n = [];
@ -37,12 +41,14 @@ class Route {
} }
} }
static function get() { public static function get()
return get_config('system','routes',[]); {
return get_config('system', 'routes', []);
} }
static function set($r) { public static function set($r)
return set_config('system','routes',$r); {
return set_config('system', 'routes', $r);
} }
} }

View file

@ -3,15 +3,18 @@
namespace Zotlabs\Extend; namespace Zotlabs\Extend;
class Widget { class Widget
{
static function register($file,$widget) { public static function register($file, $widget)
{
$rt = self::get(); $rt = self::get();
$rt[] = [ $file, $widget ]; $rt[] = [$file, $widget];
self::set($rt); self::set($rt);
} }
static function unregister($file,$widget) { public static function unregister($file, $widget)
{
$rt = self::get(); $rt = self::get();
if ($rt) { if ($rt) {
$n = []; $n = [];
@ -24,7 +27,8 @@ class Widget {
} }
} }
static function unregister_by_file($file) { public static function unregister_by_file($file)
{
$rt = self::get(); $rt = self::get();
if ($rt) { if ($rt) {
$n = []; $n = [];
@ -37,11 +41,13 @@ class Widget {
} }
} }
static function get() { public static function get()
return get_config('system','widgets',[]); {
return get_config('system', 'widgets', []);
} }
static function set($r) { public static function set($r)
return set_config('system','widgets',$r); {
return set_config('system', 'widgets', $r);
} }
} }

View file

@ -12,7 +12,8 @@ use Zotlabs\Access\Permissions;
use Zotlabs\Daemon\Run; use Zotlabs\Daemon\Run;
class Friendica { class Friendica
{
private $data; private $data;
private $settings; private $settings;
@ -24,13 +25,15 @@ class Friendica {
private $contacts = null; private $contacts = null;
function __construct($data, $settings) { public function __construct($data, $settings)
{
$this->data = $data; $this->data = $data;
$this->settings = $settings; $this->settings = $settings;
$this->extract(); $this->extract();
} }
function extract() { public function extract()
{
// channel stuff // channel stuff
@ -38,8 +41,8 @@ class Friendica {
'channel_name' => escape_tags($this->data['user']['username']), 'channel_name' => escape_tags($this->data['user']['username']),
'channel_address' => escape_tags($this->data['user']['nickname']), 'channel_address' => escape_tags($this->data['user']['nickname']),
'channel_guid' => escape_tags($this->data['user']['guid']), 'channel_guid' => escape_tags($this->data['user']['guid']),
'channel_guid_sig' => Libzot::sign($this->data['user']['guid'],$this->data['user']['prvkey']), 'channel_guid_sig' => Libzot::sign($this->data['user']['guid'], $this->data['user']['prvkey']),
'channel_hash' => Libzot::make_xchan_hash($this->data['user']['guid'],$this->data['user']['pubkey']), 'channel_hash' => Libzot::make_xchan_hash($this->data['user']['guid'], $this->data['user']['pubkey']),
'channel_prvkey' => $this->data['user']['prvkey'], 'channel_prvkey' => $this->data['user']['prvkey'],
'channel_pubkey' => $this->data['user']['pubkey'], 'channel_pubkey' => $this->data['user']['pubkey'],
'channel_pageflags' => PAGE_NORMAL, 'channel_pageflags' => PAGE_NORMAL,
@ -50,14 +53,14 @@ class Friendica {
$account_id = $this->settings['account_id']; $account_id = $this->settings['account_id'];
$max_identities = account_service_class_fetch($account_id,'total_identities'); $max_identities = account_service_class_fetch($account_id, 'total_identities');
if ($max_identities !== false) { if ($max_identities !== false) {
$r = q("select channel_id from channel where channel_account_id = %d and channel_removed = 0 ", $r = q("select channel_id from channel where channel_account_id = %d and channel_removed = 0 ",
intval($account_id) intval($account_id)
); );
if ($r && count($r) > $max_identities) { if ($r && count($r) > $max_identities) {
notice( sprintf( t('Your service plan only allows %d channels.'), $max_identities) . EOL); notice(sprintf(t('Your service plan only allows %d channels.'), $max_identities) . EOL);
return; return;
} }
} }
@ -65,8 +68,8 @@ class Friendica {
// save channel or die // save channel or die
$channel = import_channel($channel,$this->settings['account_id'],$this->settings['sieze'],$this->settings['newname']); $channel = import_channel($channel, $this->settings['account_id'], $this->settings['sieze'], $this->settings['newname']);
if (! $channel) { if (!$channel) {
logger('no channel'); logger('no channel');
return; return;
} }
@ -92,10 +95,10 @@ class Friendica {
// Friendica folks only have PERMS_AUTHED and "just me" // Friendica folks only have PERMS_AUTHED and "just me"
$post_comments = (($pageflags === 1) ? 0 : PERMS_AUTHED); $post_comments = (($pageflags === 1) ? 0 : PERMS_AUTHED);
PermissionLimits::Set(local_channel(),'post_comments',$post_comments); PermissionLimits::Set(local_channel(), 'post_comments', $post_comments);
PConfig::Set($channel['channel_id'],'system','permissions_role',$permissions_role); PConfig::Set($channel['channel_id'], 'system', 'permissions_role', $permissions_role);
PConfig::Set($channel['channel_id'],'system','use_browser_location', (string) intval($this->data['user']['allow_location'])); PConfig::Set($channel['channel_id'], 'system', 'use_browser_location', (string)intval($this->data['user']['allow_location']));
// find the self contact // find the self contact
@ -110,7 +113,7 @@ class Friendica {
} }
} }
if (! is_array($self_contact)) { if (!is_array($self_contact)) {
logger('self contact not found.'); logger('self contact not found.');
return; return;
} }
@ -126,36 +129,35 @@ class Friendica {
'hubloc_addr' => channel_reddress($channel), 'hubloc_addr' => channel_reddress($channel),
'hubloc_primary' => 1, 'hubloc_primary' => 1,
'hubloc_url' => z_root(), 'hubloc_url' => z_root(),
'hubloc_url_sig' => Libzot::sign(z_root(),$channel['channel_prvkey']), 'hubloc_url_sig' => Libzot::sign(z_root(), $channel['channel_prvkey']),
'hubloc_site_id' => Libzot::make_xchan_hash(z_root(),get_config('system','pubkey')), 'hubloc_site_id' => Libzot::make_xchan_hash(z_root(), get_config('system', 'pubkey')),
'hubloc_host' => App::get_hostname(), 'hubloc_host' => App::get_hostname(),
'hubloc_callback' => z_root() . '/zot', 'hubloc_callback' => z_root() . '/zot',
'hubloc_sitekey' => get_config('system','pubkey'), 'hubloc_sitekey' => get_config('system', 'pubkey'),
'hubloc_network' => 'zot6', 'hubloc_network' => 'zot6',
'hubloc_updated' => datetime_convert() 'hubloc_updated' => datetime_convert()
] ]
); );
if (! $r) { if (!$r) {
logger('Unable to store hub location'); logger('Unable to store hub location');
} }
if ($self_contact['avatar']) { if ($self_contact['avatar']) {
$p = z_fetch_url($self_contact['avatar'],true); $p = z_fetch_url($self_contact['avatar'], true);
if ($p['success']) { if ($p['success']) {
$h = explode("\n",$p['header']); $h = explode("\n", $p['header']);
foreach ($h as $l) { foreach ($h as $l) {
list($k,$v) = array_map("trim", explode(":", trim($l), 2)); list($k, $v) = array_map("trim", explode(":", trim($l), 2));
$hdrs[strtolower($k)] = $v; $hdrs[strtolower($k)] = $v;
} }
if (array_key_exists('content-type', $hdrs)) { if (array_key_exists('content-type', $hdrs)) {
$phototype = $hdrs['content-type']; $phototype = $hdrs['content-type'];
} } else {
else {
$phototype = 'image/jpeg'; $phototype = 'image/jpeg';
} }
import_channel_photo($p['body'],$phototype,$account_id,$channel['channel_id']); import_channel_photo($p['body'], $phototype, $account_id, $channel['channel_id']);
} }
} }
@ -199,10 +201,9 @@ class Friendica {
] ]
); );
if($role_permissions) { if ($role_permissions) {
$myperms = ((array_key_exists('perms_connect',$role_permissions)) ? $role_permissions['perms_connect'] : [] ); $myperms = ((array_key_exists('perms_connect', $role_permissions)) ? $role_permissions['perms_connect'] : []);
} } else {
else {
$x = PermissionRoles::role_perms('social'); $x = PermissionRoles::role_perms('social');
$myperms = $x['perms_connect']; $myperms = $x['perms_connect'];
} }
@ -221,18 +222,18 @@ class Friendica {
$x = Permissions::serialise(Permissions::FilledPerms($myperms)); $x = Permissions::serialise(Permissions::FilledPerms($myperms));
set_abconfig($newuid,$channel['channel_hash'],'system','my_perms',$x); set_abconfig($newuid, $channel['channel_hash'], 'system', 'my_perms', $x);
if(intval($channel['channel_account_id'])) { if (intval($channel['channel_account_id'])) {
// Save our permissions role so we can perhaps call it up and modify it later. // Save our permissions role so we can perhaps call it up and modify it later.
if($role_permissions) { if ($role_permissions) {
if(array_key_exists('online',$role_permissions)) if (array_key_exists('online', $role_permissions))
set_pconfig($newuid,'system','hide_presence',1-intval($role_permissions['online'])); set_pconfig($newuid, 'system', 'hide_presence', 1 - intval($role_permissions['online']));
if(array_key_exists('perms_auto',$role_permissions)) { if (array_key_exists('perms_auto', $role_permissions)) {
$autoperms = intval($role_permissions['perms_auto']); $autoperms = intval($role_permissions['perms_auto']);
set_pconfig($newuid,'system','autoperms',$autoperms); set_pconfig($newuid, 'system', 'autoperms', $autoperms);
} }
} }
@ -240,16 +241,16 @@ class Friendica {
// right away as a default group for new contacts. // right away as a default group for new contacts.
AccessList::add($newuid, t('Friends')); AccessList::add($newuid, t('Friends'));
AccessList::member_add($newuid,t('Friends'),$ret['channel']['channel_hash']); AccessList::member_add($newuid, t('Friends'), $ret['channel']['channel_hash']);
// if our role_permissions indicate that we're using a default collection ACL, add it. // if our role_permissions indicate that we're using a default collection ACL, add it.
if(is_array($role_permissions) && $role_permissions['default_collection']) { if (is_array($role_permissions) && $role_permissions['default_collection']) {
$r = q("select hash from pgrp where uid = %d and gname = '%s' limit 1", $r = q("select hash from pgrp where uid = %d and gname = '%s' limit 1",
intval($newuid), intval($newuid),
dbesc( t('Friends') ) dbesc(t('Friends'))
); );
if($r) { if ($r) {
q("update channel set channel_default_group = '%s', channel_allow_gid = '%s' where channel_id = %d", q("update channel set channel_default_group = '%s', channel_allow_gid = '%s' where channel_id = %d",
dbesc($r[0]['hash']), dbesc($r[0]['hash']),
dbesc('<' . $r[0]['hash'] . '>'), dbesc('<' . $r[0]['hash'] . '>'),
@ -258,8 +259,8 @@ class Friendica {
} }
} }
set_pconfig($channel['channel_id'],'system','photo_path', '%Y/%Y-%m'); set_pconfig($channel['channel_id'], 'system', 'photo_path', '%Y/%Y-%m');
set_pconfig($channel['channel_id'],'system','attach_path','%Y/%Y-%m'); set_pconfig($channel['channel_id'], 'system', 'attach_path', '%Y/%Y-%m');
// auto-follow any of the hub's pre-configured channel choices. // auto-follow any of the hub's pre-configured channel choices.
@ -267,22 +268,22 @@ class Friendica {
// otherwise it could get annoying. Don't make this list too big // otherwise it could get annoying. Don't make this list too big
// or it will impact registration time. // or it will impact registration time.
$accts = get_config('system','auto_follow'); $accts = get_config('system', 'auto_follow');
if(($accts) && (! $total_identities)) { if (($accts) && (!$total_identities)) {
if(! is_array($accts)) if (!is_array($accts))
$accts = array($accts); $accts = array($accts);
foreach($accts as $acct) { foreach ($accts as $acct) {
if(trim($acct)) { if (trim($acct)) {
$f = connect_and_sync($channel,trim($acct)); $f = connect_and_sync($channel, trim($acct));
if($f['success']) { if ($f['success']) {
$can_view_stream = their_perms_contains($channel['channel_id'],$f['abook']['abook_xchan'],'view_stream'); $can_view_stream = their_perms_contains($channel['channel_id'], $f['abook']['abook_xchan'], 'view_stream');
// If we can view their stream, pull in some posts // If we can view their stream, pull in some posts
if(($can_view_stream) || ($f['abook']['xchan_network'] === 'rss')) { if (($can_view_stream) || ($f['abook']['xchan_network'] === 'rss')) {
Run::Summon([ 'Onepoll',$f['abook']['abook_id'] ]); Run::Summon(['Onepoll', $f['abook']['abook_id']]);
} }
} }
} }
@ -303,7 +304,7 @@ class Friendica {
continue; continue;
} }
logger('connecting: ' . $contact['url'], LOGGER_DEBUG); logger('connecting: ' . $contact['url'], LOGGER_DEBUG);
$result = Connect::connect($channel,(($contact['addr']) ? $contact['addr'] : $contact['url'])); $result = Connect::connect($channel, (($contact['addr']) ? $contact['addr'] : $contact['url']));
if ($result['success'] && isset($result['abook'])) { if ($result['success'] && isset($result['abook'])) {
$contact['xchan_hash'] = $result['abook']['abook_xchan']; $contact['xchan_hash'] = $result['abook']['abook_xchan'];
$this->contacts[] = $contact; $this->contacts[] = $contact;
@ -317,11 +318,11 @@ class Friendica {
if (isset($this->data['pconfig']) && is_array($this->data['pconfig'])) { if (isset($this->data['pconfig']) && is_array($this->data['pconfig'])) {
foreach ($this->data['pconfig'] as $pc) { foreach ($this->data['pconfig'] as $pc) {
$entry = [ $entry = [
'cat' => escape_tags(str_replace('.','__',$pc['cat'])), 'cat' => escape_tags(str_replace('.', '__', $pc['cat'])),
'k' => escape_tags(str_replace('.','__',$pc['k'])), 'k' => escape_tags(str_replace('.', '__', $pc['k'])),
'v' => ((preg_match('|^a:[0-9]+:{.*}$|s', $pc['v'])) ? serialise(unserialize($pc['v'])) : $pc['v']), 'v' => ((preg_match('|^a:[0-9]+:{.*}$|s', $pc['v'])) ? serialise(unserialize($pc['v'])) : $pc['v']),
]; ];
PConfig::Set($channel['channel_id'],$entry['cat'],$entry['k'],$entry['v']); PConfig::Set($channel['channel_id'], $entry['cat'], $entry['k'], $entry['v']);
} }
} }
@ -331,16 +332,16 @@ class Friendica {
if ($this->groups) { if ($this->groups) {
foreach ($this->groups as $group) { foreach ($this->groups as $group) {
if (! intval($group['deleted'])) { if (!intval($group['deleted'])) {
AccessList::add($channel['channel_id'], $group['name'], intval($group['visible'])); AccessList::add($channel['channel_id'], $group['name'], intval($group['visible']));
if ($this->members) { if ($this->members) {
foreach ($this->members as $member) { foreach ($this->members as $member) {
if (intval($member['gid']) === intval(AccessList::byname($channel['channel_id'],$group['name']))) { if (intval($member['gid']) === intval(AccessList::byname($channel['channel_id'], $group['name']))) {
$contact_id = $member['contact-id']; $contact_id = $member['contact-id'];
if ($this->contacts) { if ($this->contacts) {
foreach ($this->contacts as $contact) { foreach ($this->contacts as $contact) {
if (intval($contact['id']) === intval($contact_id)) { if (intval($contact['id']) === intval($contact_id)) {
AccessList::member_add($channel['channel_id'],$group['name'],$contact['xchan_hash']); AccessList::member_add($channel['channel_id'], $group['name'], $contact['xchan_hash']);
break; break;
} }
} }
@ -353,9 +354,9 @@ class Friendica {
} }
change_channel($channel['channel_id']); change_channel($channel['channel_id']);
notice( t('Import complete.') . EOL); notice(t('Import complete.') . EOL);
goaway(z_root() . '/stream' ); goaway(z_root() . '/stream');
} }

View file

@ -6,19 +6,19 @@ namespace Zotlabs\Lib;
class AConfig { class AConfig {
static public function Load($account_id) { public static function Load($account_id) {
return XConfig::Load('a_' . $account_id); return XConfig::Load('a_' . $account_id);
} }
static public function Get($account_id,$family,$key,$default = false) { public static function Get($account_id, $family, $key, $default = false) {
return XConfig::Get('a_' . $account_id,$family,$key, $default); return XConfig::Get('a_' . $account_id,$family,$key, $default);
} }
static public function Set($account_id,$family,$key,$value) { public static function Set($account_id, $family, $key, $value) {
return XConfig::Set('a_' . $account_id,$family,$key,$value); return XConfig::Set('a_' . $account_id,$family,$key,$value);
} }
static public function Delete($account_id,$family,$key) { public static function Delete($account_id, $family, $key) {
return XConfig::Delete('a_' . $account_id,$family,$key); return XConfig::Delete('a_' . $account_id,$family,$key);
} }

View file

@ -12,11 +12,8 @@ use Zotlabs\Lib\Activity;
* An optional limit to the number of records returned may also be specified. * An optional limit to the number of records returned may also be specified.
* Use $class->get() to return an array of collection members. * Use $class->get() to return an array of collection members.
*/ */
class ASCollection
{
class ASCollection {
private $channel = null; private $channel = null;
private $nextpage = null; private $nextpage = null;
@ -26,7 +23,8 @@ class ASCollection {
private $history = []; private $history = [];
function __construct($obj, $channel = null, $direction = 0, $limit = 0) { public function __construct($obj, $channel = null, $direction = 0, $limit = 0)
{
$this->channel = $channel; $this->channel = $channel;
$this->direction = $direction; $this->direction = $direction;
@ -37,39 +35,37 @@ class ASCollection {
} }
if (is_string($obj)) { if (is_string($obj)) {
$data = Activity::fetch($obj,$channel); $data = Activity::fetch($obj, $channel);
$this->history[] = $obj; $this->history[] = $obj;
} }
if (! is_array($data)) { if (!is_array($data)) {
return; return;
} }
if (! in_array($data['type'], ['Collection','OrderedCollection'])) { if (!in_array($data['type'], ['Collection', 'OrderedCollection'])) {
return false; return false;
} }
if ($this->direction) { if ($this->direction) {
if (array_key_exists('last',$data) && $data['last']) { if (array_key_exists('last', $data) && $data['last']) {
$this->nextpage = $data['last']; $this->nextpage = $data['last'];
} }
} } else {
else { if (array_key_exists('first', $data) && $data['first']) {
if (array_key_exists('first',$data) && $data['first']) {
$this->nextpage = $data['first']; $this->nextpage = $data['first'];
} }
} }
if (isset($data['items']) && is_array($data['items'])) { if (isset($data['items']) && is_array($data['items'])) {
$this->data = (($this->direction) ? array_reverse($data['items']) : $data['items']); $this->data = (($this->direction) ? array_reverse($data['items']) : $data['items']);
} } elseif (isset($data['orderedItems']) && is_array($data['orderedItems'])) {
elseif (isset($data['orderedItems']) && is_array($data['orderedItems'])) {
$this->data = (($this->direction) ? array_reverse($data['orderedItems']) : $data['orderedItems']); $this->data = (($this->direction) ? array_reverse($data['orderedItems']) : $data['orderedItems']);
} }
if ($limit) { if ($limit) {
if (count($this->data) > $limit) { if (count($this->data) > $limit) {
$this->data = array_slice($this->data,0,$limit); $this->data = array_slice($this->data, 0, $limit);
return; return;
} }
} }
@ -79,13 +75,15 @@ class ASCollection {
} while ($x); } while ($x);
} }
function get() { public function get()
{
return $this->data; return $this->data;
} }
function next() { public function next()
{
if (! $this->nextpage) { if (!$this->nextpage) {
return false; return false;
} }
@ -94,34 +92,33 @@ class ASCollection {
} }
if (is_string($this->nextpage)) { if (is_string($this->nextpage)) {
if (in_array($this->nextpage,$this->history)) { if (in_array($this->nextpage, $this->history)) {
// recursion detected // recursion detected
return false; return false;
} }
$data = Activity::fetch($this->nextpage,$this->channel); $data = Activity::fetch($this->nextpage, $this->channel);
$this->history[] = $this->nextpage; $this->history[] = $this->nextpage;
} }
if (! is_array($data)) { if (!is_array($data)) {
return false; return false;
} }
if (! in_array($data['type'], ['CollectionPage','OrderedCollectionPage'])) { if (!in_array($data['type'], ['CollectionPage', 'OrderedCollectionPage'])) {
return false; return false;
} }
$this->setnext($data); $this->setnext($data);
if (isset($data['items']) && is_array($data['items'])) { if (isset($data['items']) && is_array($data['items'])) {
$this->data = array_merge($this->data,(($this->direction) ? array_reverse($data['items']) : $data['items'])); $this->data = array_merge($this->data, (($this->direction) ? array_reverse($data['items']) : $data['items']));
} } elseif (isset($data['orderedItems']) && is_array($data['orderedItems'])) {
elseif (isset($data['orderedItems']) && is_array($data['orderedItems'])) { $this->data = array_merge($this->data, (($this->direction) ? array_reverse($data['orderedItems']) : $data['orderedItems']));
$this->data = array_merge($this->data,(($this->direction) ? array_reverse($data['orderedItems']) : $data['orderedItems']));
} }
if ($limit) { if ($limit) {
if (count($this->data) > $limit) { if (count($this->data) > $limit) {
$this->data = array_slice($this->data,0,$limit); $this->data = array_slice($this->data, 0, $limit);
$this->nextpage = false; $this->nextpage = false;
return true; return true;
} }
@ -130,26 +127,22 @@ class ASCollection {
return true; return true;
} }
function setnext($data) { public function setnext($data)
{
if ($this->direction) { if ($this->direction) {
if (array_key_exists('prev',$data) && $data['prev']) { if (array_key_exists('prev', $data) && $data['prev']) {
$this->nextpage = $data['prev']; $this->nextpage = $data['prev'];
} } elseif (array_key_exists('first', $data) && $data['first']) {
elseif (array_key_exists('first',$data) && $data['first']) {
$this->nextpage = $data['first']; $this->nextpage = $data['first'];
} } else {
else {
$this->nextpage = false; $this->nextpage = false;
} }
} } else {
else { if (array_key_exists('next', $data) && $data['next']) {
if (array_key_exists('next',$data) && $data['next']) {
$this->nextpage = $data['next']; $this->nextpage = $data['next'];
} } elseif (array_key_exists('last', $data) && $data['last']) {
elseif (array_key_exists('last',$data) && $data['last']) {
$this->nextpage = $data['last']; $this->nextpage = $data['last'];
} } else {
else {
$this->nextpage = false; $this->nextpage = false;
} }
} }

View file

@ -5,7 +5,7 @@ namespace Zotlabs\Lib;
class AbConfig { class AbConfig {
static public function Load($chan,$xhash,$family = '') { public static function Load($chan, $xhash, $family = '') {
if($family) if($family)
$where = sprintf(" and cat = '%s' ",dbesc($family)); $where = sprintf(" and cat = '%s' ",dbesc($family));
$r = q("select * from abconfig where chan = %d and xchan = '%s' $where", $r = q("select * from abconfig where chan = %d and xchan = '%s' $where",
@ -16,7 +16,7 @@ class AbConfig {
} }
static public function Get($chan,$xhash,$family,$key, $default = false) { public static function Get($chan, $xhash, $family, $key, $default = false) {
$r = q("select * from abconfig where chan = %d and xchan = '%s' and cat = '%s' and k = '%s' limit 1", $r = q("select * from abconfig where chan = %d and xchan = '%s' and cat = '%s' and k = '%s' limit 1",
intval($chan), intval($chan),
dbesc($xhash), dbesc($xhash),
@ -30,7 +30,7 @@ class AbConfig {
} }
static public function Set($chan,$xhash,$family,$key,$value) { public static function Set($chan, $xhash, $family, $key, $value) {
$dbvalue = ((is_array($value)) ? serialise($value) : $value); $dbvalue = ((is_array($value)) ? serialise($value) : $value);
$dbvalue = ((is_bool($dbvalue)) ? intval($dbvalue) : $dbvalue); $dbvalue = ((is_bool($dbvalue)) ? intval($dbvalue) : $dbvalue);
@ -60,7 +60,7 @@ class AbConfig {
} }
static public function Delete($chan,$xhash,$family,$key) { public static function Delete($chan, $xhash, $family, $key) {
$r = q("delete from abconfig where chan = %d and xchan = '%s' and cat = '%s' and k = '%s' ", $r = q("delete from abconfig where chan = %d and xchan = '%s' and cat = '%s' and k = '%s' ",
intval($chan), intval($chan),

View file

@ -5,13 +5,15 @@ namespace Zotlabs\Lib;
use Zotlabs\Lib\Libsync; use Zotlabs\Lib\Libsync;
class AccessList { class AccessList
{
static function add($uid,$name,$public = 0) { public static function add($uid, $name, $public = 0)
{
$ret = false; $ret = false;
if ($uid && $name) { if ($uid && $name) {
$r = self::byname($uid,$name); // check for dups $r = self::byname($uid, $name); // check for dups
if ($r !== false) { if ($r !== false) {
// This could be a problem. // This could be a problem.
@ -23,11 +25,11 @@ class AccessList {
$z = q("SELECT * FROM pgrp WHERE id = %d LIMIT 1", $z = q("SELECT * FROM pgrp WHERE id = %d LIMIT 1",
intval($r) intval($r)
); );
if(($z) && $z[0]['deleted']) { if (($z) && $z[0]['deleted']) {
q('UPDATE pgrp SET deleted = 0 WHERE id = %d', intval($z[0]['id'])); q('UPDATE pgrp SET deleted = 0 WHERE id = %d', intval($z[0]['id']));
notice( t('A deleted list with this name was revived. Existing item permissions <strong>may</strong> apply to this list and any future members. If this is not what you intended, please create another list with a different name.') . EOL); notice(t('A deleted list with this name was revived. Existing item permissions <strong>may</strong> apply to this list and any future members. If this is not what you intended, please create another list with a different name.') . EOL);
} }
$hash = self::by_id($uid,$r); $hash = self::by_id($uid, $r);
return $hash; return $hash;
} }
@ -43,13 +45,14 @@ class AccessList {
$ret = $r; $ret = $r;
} }
Libsync::build_sync_packet($uid,null,true); Libsync::build_sync_packet($uid, null, true);
return (($ret) ? $hash : $ret); return (($ret) ? $hash : $ret);
} }
static function remove($uid,$name) { public static function remove($uid, $name)
{
$ret = false; $ret = false;
if ($uid && $name) { if ($uid && $name) {
$r = q("SELECT id, hash FROM pgrp WHERE uid = %d AND gname = '%s' LIMIT 1", $r = q("SELECT id, hash FROM pgrp WHERE uid = %d AND gname = '%s' LIMIT 1",
@ -59,8 +62,7 @@ class AccessList {
if ($r) { if ($r) {
$group_id = $r[0]['id']; $group_id = $r[0]['id'];
$group_hash = $r[0]['hash']; $group_hash = $r[0]['hash'];
} } else {
else {
return false; return false;
} }
@ -112,7 +114,7 @@ class AccessList {
} }
Libsync::build_sync_packet($uid,null,true); Libsync::build_sync_packet($uid, null, true);
return $ret; return $ret;
} }
@ -120,8 +122,9 @@ class AccessList {
// returns the integer id of an access group owned by $uid and named $name // returns the integer id of an access group owned by $uid and named $name
// or false. // or false.
static function byname($uid,$name) { public static function byname($uid, $name)
if (! ($uid && $name)) { {
if (!($uid && $name)) {
return false; return false;
} }
$r = q("SELECT id FROM pgrp WHERE uid = %d AND gname = '%s' LIMIT 1", $r = q("SELECT id FROM pgrp WHERE uid = %d AND gname = '%s' LIMIT 1",
@ -134,8 +137,9 @@ class AccessList {
return false; return false;
} }
static function by_id($uid,$id) { public static function by_id($uid, $id)
if (! ($uid && $id)) { {
if (!($uid && $id)) {
return false; return false;
} }
@ -150,9 +154,9 @@ class AccessList {
} }
public static function rec_byhash($uid, $hash)
static function rec_byhash($uid,$hash) { {
if (! ( $uid && $hash)) { if (!($uid && $hash)) {
return false; return false;
} }
$r = q("SELECT * FROM pgrp WHERE uid = %d AND hash = '%s' LIMIT 1", $r = q("SELECT * FROM pgrp WHERE uid = %d AND hash = '%s' LIMIT 1",
@ -166,12 +170,13 @@ class AccessList {
} }
static function member_remove($uid,$name,$member) { public static function member_remove($uid, $name, $member)
$gid = self::byname($uid,$name); {
if (! $gid) { $gid = self::byname($uid, $name);
if (!$gid) {
return false; return false;
} }
if (! ($uid && $gid && $member)) { if (!($uid && $gid && $member)) {
return false; return false;
} }
$r = q("DELETE FROM pgrp_member WHERE uid = %d AND gid = %d AND xchan = '%s' ", $r = q("DELETE FROM pgrp_member WHERE uid = %d AND gid = %d AND xchan = '%s' ",
@ -180,17 +185,18 @@ class AccessList {
dbesc($member) dbesc($member)
); );
Libsync::build_sync_packet($uid,null,true); Libsync::build_sync_packet($uid, null, true);
return $r; return $r;
} }
static function member_add($uid,$name,$member,$gid = 0) { public static function member_add($uid, $name, $member, $gid = 0)
if (! $gid) { {
$gid = self::byname($uid,$name); if (!$gid) {
$gid = self::byname($uid, $name);
} }
if (! ($gid && $uid && $member)) { if (!($gid && $uid && $member)) {
return false; return false;
} }
@ -203,8 +209,7 @@ class AccessList {
return true; // You might question this, but return true; // You might question this, but
// we indicate success because the group member was in fact created // we indicate success because the group member was in fact created
// -- It was just created at another time // -- It was just created at another time
} } else {
else {
$r = q("INSERT INTO pgrp_member (uid, gid, xchan) $r = q("INSERT INTO pgrp_member (uid, gid, xchan)
VALUES( %d, %d, '%s' ) ", VALUES( %d, %d, '%s' ) ",
intval($uid), intval($uid),
@ -212,20 +217,21 @@ class AccessList {
dbesc($member) dbesc($member)
); );
} }
Libsync::build_sync_packet($uid,null,true); Libsync::build_sync_packet($uid, null, true);
return $r; return $r;
} }
static function members($uid, $gid, $total = false, $start = 0, $records = 0) { public static function members($uid, $gid, $total = false, $start = 0, $records = 0)
{
$ret = []; $ret = [];
if ($records) { if ($records) {
$pager_sql = sprintf(" LIMIT %d OFFSET %d ", intval($records), intval($start)); $pager_sql = sprintf(" LIMIT %d OFFSET %d ", intval($records), intval($start));
} }
// process virtual groups // process virtual groups
if (strpos($gid,':') === 0) { if (strpos($gid, ':') === 0) {
$vg = substr($gid,1); $vg = substr($gid, 1);
switch ($vg) { switch ($vg) {
case '1': case '1':
$sql_extra = EMPTY_STR; $sql_extra = EMPTY_STR;
@ -251,7 +257,7 @@ class AccessList {
intval($uid) intval($uid)
); );
if ($r) { if ($r) {
for($x = 0; $x < count($r); $x ++) { for ($x = 0; $x < count($r); $x++) {
$r[$x]['xchan'] = $r[$x]['abook_xchan']; $r[$x]['xchan'] = $r[$x]['abook_xchan'];
} }
} }
@ -287,7 +293,8 @@ class AccessList {
return $ret; return $ret;
} }
static function members_xchan($uid,$gid) { public static function members_xchan($uid, $gid)
{
$ret = []; $ret = [];
if (intval($gid)) { if (intval($gid)) {
$r = q("SELECT xchan FROM pgrp_member WHERE gid = %d AND uid = %d", $r = q("SELECT xchan FROM pgrp_member WHERE gid = %d AND uid = %d",
@ -303,17 +310,18 @@ class AccessList {
return $ret; return $ret;
} }
static function select($uid,$group = '') { public static function select($uid, $group = '')
{
$grps = []; $grps = [];
$r = q("SELECT * FROM pgrp WHERE deleted = 0 AND uid = %d ORDER BY gname ASC", $r = q("SELECT * FROM pgrp WHERE deleted = 0 AND uid = %d ORDER BY gname ASC",
intval($uid) intval($uid)
); );
$grps[] = [ 'name' => '', 'hash' => '0', 'selected' => '' ]; $grps[] = ['name' => '', 'hash' => '0', 'selected' => ''];
if ($r) { if ($r) {
foreach ($r as $rr) { foreach ($r as $rr) {
$grps[] = [ 'name' => $rr['gname'], 'id' => $rr['hash'], 'selected' => (($group == $rr['hash']) ? 'true' : '') ]; $grps[] = ['name' => $rr['gname'], 'id' => $rr['hash'], 'selected' => (($group == $rr['hash']) ? 'true' : '')];
} }
} }
@ -325,7 +333,8 @@ class AccessList {
} }
static function widget($every="connections",$each="lists",$edit = false, $group_id = 0, $cid = '',$mode = 1) { public static function widget($every = "connections", $each = "lists", $edit = false, $group_id = 0, $cid = '', $mode = 1)
{
$o = ''; $o = '';
@ -336,7 +345,7 @@ class AccessList {
); );
$member_of = []; $member_of = [];
if ($cid) { if ($cid) {
$member_of = self::containing(local_channel(),$cid); $member_of = self::containing(local_channel(), $cid);
} }
if ($r) { if ($r) {
@ -344,9 +353,8 @@ class AccessList {
$selected = (($group_id == $rr['id']) ? ' group-selected' : ''); $selected = (($group_id == $rr['id']) ? ' group-selected' : '');
if ($edit) { if ($edit) {
$groupedit = [ 'href' => "lists/".$rr['id'], 'title' => t('edit') ]; $groupedit = ['href' => "lists/" . $rr['id'], 'title' => t('edit')];
} } else {
else {
$groupedit = null; $groupedit = null;
} }
@ -356,9 +364,9 @@ class AccessList {
'cid' => $cid, 'cid' => $cid,
'text' => $rr['gname'], 'text' => $rr['gname'],
'selected' => $selected, 'selected' => $selected,
'href' => (($mode == 0) ? $each.'?f=&gid='.$rr['id'] : $each."/".$rr['id']) . ((x($_GET,'new')) ? '&new=' . $_GET['new'] : '') . ((x($_GET,'order')) ? '&order=' . $_GET['order'] : ''), 'href' => (($mode == 0) ? $each . '?f=&gid=' . $rr['id'] : $each . "/" . $rr['id']) . ((x($_GET, 'new')) ? '&new=' . $_GET['new'] : '') . ((x($_GET, 'order')) ? '&order=' . $_GET['order'] : ''),
'edit' => $groupedit, 'edit' => $groupedit,
'ismember' => in_array($rr['id'],$member_of), 'ismember' => in_array($rr['id'], $member_of),
]; ];
} }
} }
@ -375,8 +383,9 @@ class AccessList {
} }
static function expand($g) { public static function expand($g)
if (! (is_array($g) && count($g))) { {
if (!(is_array($g) && count($g))) {
return []; return [];
} }
@ -390,13 +399,13 @@ class AccessList {
// zot:abc is all of abc's zot6 connections // zot:abc is all of abc's zot6 connections
// activitypub:abc is all of abc's activitypub connections // activitypub:abc is all of abc's activitypub connections
if (strpos($gv,'connections:') === 0 || strpos($gv,'zot:') === 0 || strpos($gv,'activitypub:') === 0) { if (strpos($gv, 'connections:') === 0 || strpos($gv, 'zot:') === 0 || strpos($gv, 'activitypub:') === 0) {
$sql_extra = EMPTY_STR; $sql_extra = EMPTY_STR;
$channel_hash = substr($gv,strpos($gv,':') + 1); $channel_hash = substr($gv, strpos($gv, ':') + 1);
if (strpos($gv,'zot:') === 0) { if (strpos($gv, 'zot:') === 0) {
$sql_extra = " and xchan_network = 'zot6' "; $sql_extra = " and xchan_network = 'zot6' ";
} }
if (strpos($gv,'activitypub:') === 0) { if (strpos($gv, 'activitypub:') === 0) {
$sql_extra = " and xchan_network = 'activitypub' "; $sql_extra = " and xchan_network = 'activitypub' ";
} }
$r = q("select channel_id from channel where channel_hash = '%s' ", $r = q("select channel_id from channel where channel_hash = '%s' ",
@ -414,14 +423,13 @@ class AccessList {
} }
} }
} }
} } else {
else {
$x[] = $gv; $x[] = $gv;
} }
} }
if ($x) { if ($x) {
stringify_array_elms($x,true); stringify_array_elms($x, true);
$groups = implode(',', $x); $groups = implode(',', $x);
if ($groups) { if ($groups) {
$r = q("SELECT xchan FROM pgrp_member WHERE gid IN ( select id from pgrp where hash in ( $groups ))"); $r = q("SELECT xchan FROM pgrp_member WHERE gid IN ( select id from pgrp where hash in ( $groups ))");
@ -437,7 +445,8 @@ class AccessList {
} }
static function member_of($c) { public static function member_of($c)
{
$r = q("SELECT pgrp.gname, pgrp.id FROM pgrp LEFT JOIN pgrp_member ON pgrp_member.gid = pgrp.id $r = q("SELECT pgrp.gname, pgrp.id FROM pgrp LEFT JOIN pgrp_member ON pgrp_member.gid = pgrp.id
WHERE pgrp_member.xchan = '%s' AND pgrp.deleted = 0 ORDER BY pgrp.gname ASC ", WHERE pgrp_member.xchan = '%s' AND pgrp.deleted = 0 ORDER BY pgrp.gname ASC ",
dbesc($c) dbesc($c)
@ -446,7 +455,8 @@ class AccessList {
return $r; return $r;
} }
static function containing($uid,$c) { public static function containing($uid, $c)
{
$r = q("SELECT gid FROM pgrp_member WHERE uid = %d AND pgrp_member.xchan = '%s' ", $r = q("SELECT gid FROM pgrp_member WHERE uid = %d AND pgrp_member.xchan = '%s' ",
intval($uid), intval($uid),

File diff suppressed because it is too large Load diff

View file

@ -9,9 +9,11 @@ use Zotlabs\Lib\Libsync;
use Zotlabs\Daemon\Run; use Zotlabs\Daemon\Run;
use Zotlabs\Lib\IConfig; use Zotlabs\Lib\IConfig;
class ActivityPub { class ActivityPub
{
static public function notifier_process(&$arr) { public static function notifier_process(&$arr)
{
if ($arr['hub']['hubloc_network'] !== 'activitypub') { if ($arr['hub']['hubloc_network'] !== 'activitypub') {
return; return;
@ -21,18 +23,18 @@ class ActivityPub {
// logger('notifier_array: ' . print_r($arr,true), LOGGER_ALL, LOG_INFO); // logger('notifier_array: ' . print_r($arr,true), LOGGER_ALL, LOG_INFO);
$purge_all = (($arr['packet_type'] === 'purge' && (! intval($arr['private']))) ? true : false); $purge_all = (($arr['packet_type'] === 'purge' && (!intval($arr['private']))) ? true : false);
$signed_msg = null; $signed_msg = null;
if (array_key_exists('target_item',$arr) && is_array($arr['target_item'])) { if (array_key_exists('target_item', $arr) && is_array($arr['target_item'])) {
if (intval($arr['target_item']['item_obscured'])) { if (intval($arr['target_item']['item_obscured'])) {
logger('Cannot send raw data as an activitypub activity.'); logger('Cannot send raw data as an activitypub activity.');
return; return;
} }
$signed_msg = get_iconfig($arr['target_item'],'activitypub','rawmsg'); $signed_msg = get_iconfig($arr['target_item'], 'activitypub', 'rawmsg');
// If we have an activity already stored with an LD-signature // If we have an activity already stored with an LD-signature
// which we are sending downstream, use that signed activity as is. // which we are sending downstream, use that signed activity as is.
@ -41,7 +43,7 @@ class ActivityPub {
// It is unclear if Mastodon supports the federation delivery model. Initial tests were // It is unclear if Mastodon supports the federation delivery model. Initial tests were
// inconclusive and the behaviour varied. // inconclusive and the behaviour varied.
if (($arr['channel']['channel_hash'] !== $arr['target_item']['author_xchan']) && (! $signed_msg)) { if (($arr['channel']['channel_hash'] !== $arr['target_item']['author_xchan']) && (!$signed_msg)) {
logger('relayed post with no signed message'); logger('relayed post with no signed message');
return; return;
} }
@ -55,7 +57,7 @@ class ActivityPub {
'actor' => channel_url($arr['channel']), 'actor' => channel_url($arr['channel']),
'type' => 'Delete', 'type' => 'Delete',
'object' => channel_url($arr['channel']), 'object' => channel_url($arr['channel']),
'to' => [ 'https://www.w3.org/ns/activitystreams#Public' ] 'to' => ['https://www.w3.org/ns/activitystreams#Public']
]; ];
$msg = array_merge(['@context' => [ $msg = array_merge(['@context' => [
@ -64,17 +66,16 @@ class ActivityPub {
Activity::ap_schema() Activity::ap_schema()
]], $ti); ]], $ti);
$msg['signature'] = LDSignatures::sign($msg,$arr['channel']); $msg['signature'] = LDSignatures::sign($msg, $arr['channel']);
logger('ActivityPub_encoded (purge_all): ' . json_encode($msg,JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)); logger('ActivityPub_encoded (purge_all): ' . json_encode($msg, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
$jmsg = json_encode($msg, JSON_UNESCAPED_SLASHES); $jmsg = json_encode($msg, JSON_UNESCAPED_SLASHES);
} } else {
else {
$target_item = $arr['target_item']; $target_item = $arr['target_item'];
if (! $target_item['mid']) { if (!$target_item['mid']) {
return; return;
} }
@ -83,8 +84,7 @@ class ActivityPub {
if ($signed_msg) { if ($signed_msg) {
$jmsg = $signed_msg; $jmsg = $signed_msg;
} } else {
else {
// Rewrite outbound mentions so they match the ActivityPub convention, which // Rewrite outbound mentions so they match the ActivityPub convention, which
// is to pretend that the preferred display name doesn't exist and instead use // is to pretend that the preferred display name doesn't exist and instead use
@ -97,7 +97,7 @@ class ActivityPub {
$ti = Activity::encode_activity($target_item, true); $ti = Activity::encode_activity($target_item, true);
if (! $ti) { if (!$ti) {
return; return;
} }
@ -120,9 +120,9 @@ class ActivityPub {
Activity::ap_schema() Activity::ap_schema()
]], $ti); ]], $ti);
$msg['signature'] = LDSignatures::sign($msg,$arr['channel']); $msg['signature'] = LDSignatures::sign($msg, $arr['channel']);
logger('ActivityPub_encoded: ' . json_encode($msg,JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)); logger('ActivityPub_encoded: ' . json_encode($msg, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
$jmsg = json_encode($msg, JSON_UNESCAPED_SLASHES); $jmsg = json_encode($msg, JSON_UNESCAPED_SLASHES);
} }
@ -141,7 +141,7 @@ class ActivityPub {
dbesc($arr['hub']['hubloc_url']) dbesc($arr['hub']['hubloc_url'])
); );
if (! $r) { if (!$r) {
logger('activitypub_process_outbound: no recipients'); logger('activitypub_process_outbound: no recipients');
return; return;
} }
@ -153,40 +153,38 @@ class ActivityPub {
// They'll reject it if they don't like it. // They'll reject it if they don't like it.
// $single = deliverable_singleton($arr['channel']['channel_id'],$contact); // $single = deliverable_singleton($arr['channel']['channel_id'],$contact);
if (! $arr['normal_mode']) { if (!$arr['normal_mode']) {
continue; continue;
} }
$qi = self::queue_message($jmsg,$arr['channel'],$contact,$target_item['mid']); $qi = self::queue_message($jmsg, $arr['channel'], $contact, $target_item['mid']);
if ($qi) { if ($qi) {
$arr['queued'][] = $qi; $arr['queued'][] = $qi;
} }
continue; continue;
} }
} } else {
else {
// public message // public message
// See if we can deliver all of them at once // See if we can deliver all of them at once
$x = get_xconfig($arr['hub']['hubloc_hash'],'activitypub','collections'); $x = get_xconfig($arr['hub']['hubloc_hash'], 'activitypub', 'collections');
if ($x && $x['sharedInbox']) { if ($x && $x['sharedInbox']) {
logger('using publicInbox delivery for ' . $arr['hub']['hubloc_url'], LOGGER_DEBUG); logger('using publicInbox delivery for ' . $arr['hub']['hubloc_url'], LOGGER_DEBUG);
$contact['hubloc_callback'] = $x['sharedInbox']; $contact['hubloc_callback'] = $x['sharedInbox'];
$qi = self::queue_message($jmsg,$arr['channel'],$contact,$target_item['mid']); $qi = self::queue_message($jmsg, $arr['channel'], $contact, $target_item['mid']);
if ($qi) { if ($qi) {
$arr['queued'][] = $qi; $arr['queued'][] = $qi;
} }
} } else {
else {
$r = q("select * from xchan left join hubloc on xchan_hash = hubloc_hash where hubloc_url = '%s' and xchan_network = 'activitypub' ", $r = q("select * from xchan left join hubloc on xchan_hash = hubloc_hash where hubloc_url = '%s' and xchan_network = 'activitypub' ",
dbesc($arr['hub']['hubloc_url']) dbesc($arr['hub']['hubloc_url'])
); );
if (! $r) { if (!$r) {
logger('activitypub_process_outbound: no recipients'); logger('activitypub_process_outbound: no recipients');
return; return;
} }
@ -195,7 +193,7 @@ class ActivityPub {
// $single = deliverable_singleton($arr['channel']['channel_id'],$contact); // $single = deliverable_singleton($arr['channel']['channel_id'],$contact);
$qi = self::queue_message($jmsg,$arr['channel'],$contact,$target_item['mid']); $qi = self::queue_message($jmsg, $arr['channel'], $contact, $target_item['mid']);
if ($qi) { if ($qi) {
$arr['queued'][] = $qi; $arr['queued'][] = $qi;
} }
@ -208,14 +206,15 @@ class ActivityPub {
} }
static function queue_message($msg,$sender,$recip,$message_id = '') { public static function queue_message($msg, $sender, $recip, $message_id = '')
{
$dest_url = $recip['hubloc_callback']; $dest_url = $recip['hubloc_callback'];
logger('URL: ' . $dest_url, LOGGER_DEBUG); logger('URL: ' . $dest_url, LOGGER_DEBUG);
logger('DATA: ' . jindent($msg), LOGGER_DATA); logger('DATA: ' . jindent($msg), LOGGER_DATA);
if (intval(get_config('system','activitypub_test')) || intval(get_pconfig($sender['channel_id'],'system','activitypub_test'))) { if (intval(get_config('system', 'activitypub_test')) || intval(get_pconfig($sender['channel_id'], 'system', 'activitypub_test'))) {
logger('test mode - delivery disabled'); logger('test mode - delivery disabled');
return false; return false;
} }
@ -233,7 +232,7 @@ class ActivityPub {
'msg' => $msg 'msg' => $msg
]); ]);
if ($message_id && (! get_config('system','disable_dreport'))) { if ($message_id && (!get_config('system', 'disable_dreport'))) {
q("insert into dreport ( dreport_mid, dreport_site, dreport_recip, dreport_result, dreport_time, dreport_xchan, dreport_queue, dreport_log ) values ( '%s','%s','%s','%s','%s','%s','%s','%s' ) ", q("insert into dreport ( dreport_mid, dreport_site, dreport_recip, dreport_result, dreport_time, dreport_xchan, dreport_queue, dreport_log ) values ( '%s','%s','%s','%s','%s','%s','%s','%s' ) ",
dbesc($message_id), dbesc($message_id),
dbesc($dest_url), dbesc($dest_url),
@ -250,17 +249,19 @@ class ActivityPub {
} }
static function permissions_update(&$x) { public static function permissions_update(&$x)
{
if ($x['recipient']['xchan_network'] !== 'activitypub') { if ($x['recipient']['xchan_network'] !== 'activitypub') {
return; return;
} }
self::discover($x['recipient']['xchan_hash'],true); self::discover($x['recipient']['xchan_hash'], true);
$x['success'] = true; $x['success'] = true;
} }
static function permissions_create(&$x) { public static function permissions_create(&$x)
{
// send a follow activity to the followee's inbox // send a follow activity to the followee's inbox
@ -268,13 +269,13 @@ class ActivityPub {
return; return;
} }
$p = Activity::encode_person($x['sender'],false); $p = Activity::encode_person($x['sender'], false);
if (! $p) { if (!$p) {
return; return;
} }
$orig_follow = get_abconfig($x['sender']['channel_id'],$x['recipient']['xchan_hash'],'activitypub','their_follow_id'); $orig_follow = get_abconfig($x['sender']['channel_id'], $x['recipient']['xchan_hash'], 'activitypub', 'their_follow_id');
$orig_follow_type = get_abconfig($x['sender']['channel_id'],$x['recipient']['xchan_hash'],'activitypub','their_follow_type'); $orig_follow_type = get_abconfig($x['sender']['channel_id'], $x['recipient']['xchan_hash'], 'activitypub', 'their_follow_type');
$msg = array_merge(['@context' => [ $msg = array_merge(['@context' => [
ACTIVITYSTREAMS_JSONLD_REV, ACTIVITYSTREAMS_JSONLD_REV,
@ -286,7 +287,7 @@ class ActivityPub {
'type' => (($orig_follow_type) ? $orig_follow_type : 'Follow'), 'type' => (($orig_follow_type) ? $orig_follow_type : 'Follow'),
'actor' => $p, 'actor' => $p,
'object' => $x['recipient']['xchan_hash'], 'object' => $x['recipient']['xchan_hash'],
'to' => [ $x['recipient']['xchan_hash'] ] 'to' => [$x['recipient']['xchan_hash']]
]); ]);
// for Group actors, send both a Follow and a Join because some platforms only support one and there's // for Group actors, send both a Follow and a Join because some platforms only support one and there's
@ -297,11 +298,11 @@ class ActivityPub {
if (intval($x['recipient']['xchan_type']) === XCHAN_TYPE_GROUP) { if (intval($x['recipient']['xchan_type']) === XCHAN_TYPE_GROUP) {
$join_msg = $msg; $join_msg = $msg;
$join_msg['type'] = 'Join'; $join_msg['type'] = 'Join';
$join_msg['signature'] = LDSignatures::sign($join_msg,$x['sender']); $join_msg['signature'] = LDSignatures::sign($join_msg, $x['sender']);
$jmsg2 = json_encode($join_msg, JSON_UNESCAPED_SLASHES); $jmsg2 = json_encode($join_msg, JSON_UNESCAPED_SLASHES);
} }
$msg['signature'] = LDSignatures::sign($msg,$x['sender']); $msg['signature'] = LDSignatures::sign($msg, $x['sender']);
$jmsg = json_encode($msg, JSON_UNESCAPED_SLASHES); $jmsg = json_encode($msg, JSON_UNESCAPED_SLASHES);
$h = q("select * from hubloc where hubloc_hash = '%s' limit 1", $h = q("select * from hubloc where hubloc_hash = '%s' limit 1",
@ -309,12 +310,12 @@ class ActivityPub {
); );
if ($h) { if ($h) {
$qi = self::queue_message($jmsg,$x['sender'],$h[0]); $qi = self::queue_message($jmsg, $x['sender'], $h[0]);
if ($qi) { if ($qi) {
$x['deliveries'] = $qi; $x['deliveries'] = $qi;
} }
if ($join_msg) { if ($join_msg) {
$qi = self::queue_message($jmsg2,$x['sender'],$h[0]); $qi = self::queue_message($jmsg2, $x['sender'], $h[0]);
if ($qi) { if ($qi) {
$x['deliveries'] = $qi; $x['deliveries'] = $qi;
} }
@ -325,7 +326,8 @@ class ActivityPub {
} }
static function permissions_accept(&$x) { public static function permissions_accept(&$x)
{
// send an accept activity to the followee's inbox // send an accept activity to the followee's inbox
@ -335,14 +337,14 @@ class ActivityPub {
// we currently are not handling send of reject follow activities; this is permitted by protocol // we currently are not handling send of reject follow activities; this is permitted by protocol
$accept = get_abconfig($x['recipient']['abook_channel'],$x['recipient']['xchan_hash'],'activitypub','their_follow_id'); $accept = get_abconfig($x['recipient']['abook_channel'], $x['recipient']['xchan_hash'], 'activitypub', 'their_follow_id');
$follow_type = get_abconfig($x['recipient']['abook_channel'],$x['recipient']['xchan_hash'],'activitypub','their_follow_type'); $follow_type = get_abconfig($x['recipient']['abook_channel'], $x['recipient']['xchan_hash'], 'activitypub', 'their_follow_type');
if (! $accept) { if (!$accept) {
return; return;
} }
$p = Activity::encode_person($x['sender'],false); $p = Activity::encode_person($x['sender'], false);
if (! $p) { if (!$p) {
return; return;
} }
@ -361,10 +363,10 @@ class ActivityPub {
'actor' => $x['recipient']['xchan_hash'], 'actor' => $x['recipient']['xchan_hash'],
'object' => z_root() . '/channel/' . $x['sender']['channel_address'] 'object' => z_root() . '/channel/' . $x['sender']['channel_address']
], ],
'to' => [ $x['recipient']['xchan_hash'] ] 'to' => [$x['recipient']['xchan_hash']]
]); ]);
$msg['signature'] = LDSignatures::sign($msg,$x['sender']); $msg['signature'] = LDSignatures::sign($msg, $x['sender']);
$jmsg = json_encode($msg, JSON_UNESCAPED_SLASHES); $jmsg = json_encode($msg, JSON_UNESCAPED_SLASHES);
@ -373,7 +375,7 @@ class ActivityPub {
); );
if ($h) { if ($h) {
$qi = self::queue_message($jmsg,$x['sender'],$h[0]); $qi = self::queue_message($jmsg, $x['sender'], $h[0]);
if ($qi) { if ($qi) {
$x['deliveries'] = $qi; $x['deliveries'] = $qi;
} }
@ -383,28 +385,29 @@ class ActivityPub {
} }
static function contact_remove($channel_id,$abook) { public static function contact_remove($channel_id, $abook)
{
$recip = q("select * from abook left join xchan on abook_xchan = xchan_hash where abook_id = %d", $recip = q("select * from abook left join xchan on abook_xchan = xchan_hash where abook_id = %d",
intval($abook['abook_id']) intval($abook['abook_id'])
); );
if ((! $recip) || $recip[0]['xchan_network'] !== 'activitypub') if ((!$recip) || $recip[0]['xchan_network'] !== 'activitypub')
return; return;
$channel = channelx_by_n($recip[0]['abook_channel']); $channel = channelx_by_n($recip[0]['abook_channel']);
if (! $channel) { if (!$channel) {
return; return;
} }
$p = Activity::encode_person($channel,true,true); $p = Activity::encode_person($channel, true, true);
if (! $p) { if (!$p) {
return; return;
} }
// send an unfollow activity to the followee's inbox // send an unfollow activity to the followee's inbox
$orig_activity = get_abconfig($recip[0]['abook_channel'],$recip[0]['xchan_hash'],'activitypub','follow_id'); $orig_activity = get_abconfig($recip[0]['abook_channel'], $recip[0]['xchan_hash'], 'activitypub', 'follow_id');
if ($orig_activity && $recip[0]['abook_pending']) { if ($orig_activity && $recip[0]['abook_pending']) {
@ -425,12 +428,11 @@ class ActivityPub {
'actor' => $recip[0]['xchan_hash'], 'actor' => $recip[0]['xchan_hash'],
'object' => $p 'object' => $p
], ],
'to' => [ $recip[0]['xchan_hash'] ] 'to' => [$recip[0]['xchan_hash']]
]); ]);
del_abconfig($recip[0]['abook_channel'],$recip[0]['xchan_hash'],'activitypub','follow_id'); del_abconfig($recip[0]['abook_channel'], $recip[0]['xchan_hash'], 'activitypub', 'follow_id');
} } else {
else {
// send an unfollow // send an unfollow
@ -449,11 +451,11 @@ class ActivityPub {
'actor' => $p, 'actor' => $p,
'object' => $recip[0]['xchan_hash'] 'object' => $recip[0]['xchan_hash']
], ],
'to' => [ $recip[0]['xchan_hash'] ] 'to' => [$recip[0]['xchan_hash']]
]); ]);
} }
$msg['signature'] = LDSignatures::sign($msg,$channel); $msg['signature'] = LDSignatures::sign($msg, $channel);
$jmsg = json_encode($msg, JSON_UNESCAPED_SLASHES); $jmsg = json_encode($msg, JSON_UNESCAPED_SLASHES);
@ -462,14 +464,15 @@ class ActivityPub {
); );
if ($h) { if ($h) {
$qi = self::queue_message($jmsg,$channel,$h[0]); $qi = self::queue_message($jmsg, $channel, $h[0]);
if ($qi) { if ($qi) {
Run::Summon([ 'Deliver' , $qi ]); Run::Summon(['Deliver', $qi]);
} }
} }
} }
static function discover($apurl, $force = false) { public static function discover($apurl, $force = false)
{
$person_obj = null; $person_obj = null;
$ap = Activity::fetch($apurl); $ap = Activity::fetch($apurl);
@ -478,8 +481,7 @@ class ActivityPub {
if ($AS->is_valid()) { if ($AS->is_valid()) {
if (ActivityStreams::is_an_actor($AS->type)) { if (ActivityStreams::is_an_actor($AS->type)) {
$person_obj = $AS->data; $person_obj = $AS->data;
} } elseif ($AS->obj && ActivityStreams::is_an_actor($AS->obj['type'])) {
elseif ($AS->obj && ActivityStreams::is_an_actor($AS->obj['type'])) {
$person_obj = $AS->obj; $person_obj = $AS->obj;
} }
} }
@ -487,19 +489,20 @@ class ActivityPub {
if (isset($person_obj)) { if (isset($person_obj)) {
Activity::actor_store($person_obj['id'],$person_obj, $force); Activity::actor_store($person_obj['id'], $person_obj, $force);
return $person_obj['id']; return $person_obj['id'];
} }
return false; return false;
} }
static public function move($src,$dst) { public static function move($src, $dst)
{
if (! ($src && $dst)) { if (!($src && $dst)) {
return; return;
} }
if ($src && ! is_array($src)) { if ($src && !is_array($src)) {
$src = Activity::fetch($src); $src = Activity::fetch($src);
if (is_array($src)) { if (is_array($src)) {
$src_xchan = $src['id']; $src_xchan = $src['id'];
@ -508,26 +511,26 @@ class ActivityPub {
$approvals = null; $approvals = null;
if ($dst && ! is_array($dst)) { if ($dst && !is_array($dst)) {
$dst = Activity::fetch($dst); $dst = Activity::fetch($dst);
if (is_array($dst)) { if (is_array($dst)) {
$dst_xchan = $dst['id']; $dst_xchan = $dst['id'];
if (array_key_exists('alsoKnownAs',$dst)) { if (array_key_exists('alsoKnownAs', $dst)) {
if(! is_array($dst['alsoKnownAs'])) { if (!is_array($dst['alsoKnownAs'])) {
$dst['alsoKnownAs'] = [ $dst['alsoKnownAs'] ]; $dst['alsoKnownAs'] = [$dst['alsoKnownAs']];
} }
$approvals = $dst['alsoKnownAs']; $approvals = $dst['alsoKnownAs'];
} }
} }
} }
if(! ($src_xchan && $dst_xchan)) { if (!($src_xchan && $dst_xchan)) {
return; return;
} }
if ($approvals) { if ($approvals) {
foreach($approvals as $approval) { foreach ($approvals as $approval) {
if($approval === $src_xchan) { if ($approval === $src_xchan) {
$abooks = q("select abook_channel from abook where abook_xchan = '%s'", $abooks = q("select abook_channel from abook where abook_xchan = '%s'",
dbesc($src_xchan) dbesc($src_xchan)
); );
@ -569,11 +572,11 @@ class ActivityPub {
unset($clone['abook_id']); unset($clone['abook_id']);
unset($clone['abook_account']); unset($clone['abook_account']);
unset($clone['abook_channel']); unset($clone['abook_channel']);
$abconfig = load_abconfig($abook['abook_channel'],$clone['abook_xchan']); $abconfig = load_abconfig($abook['abook_channel'], $clone['abook_xchan']);
if ($abconfig) { if ($abconfig) {
$clone['abconfig'] = $abconfig; $clone['abconfig'] = $abconfig;
} }
Libsync::build_sync_packet($abook['abook_channel'], [ 'abook' => [ $clone ] ] ); Libsync::build_sync_packet($abook['abook_channel'], ['abook' => [$clone]]);
} }
} }
} }

View file

@ -10,8 +10,8 @@ use Zotlabs\Web\HTTPSig;
* *
* Parses an ActivityStream JSON string. * Parses an ActivityStream JSON string.
*/ */
class ActivityStreams
class ActivityStreams { {
public $raw = null; public $raw = null;
public $data = null; public $data = null;
@ -43,16 +43,16 @@ class ActivityStreams {
* *
* @param string $string * @param string $string
*/ */
function __construct($string,$hub = null,$client = null) { public function __construct($string, $hub = null, $client = null)
{
$this->raw = $string; $this->raw = $string;
$this->hub = $hub; $this->hub = $hub;
if (is_array($string)) { if (is_array($string)) {
$this->data = $string; $this->data = $string;
$this->raw = json_encode($string,JSON_UNESCAPED_SLASHES); $this->raw = json_encode($string, JSON_UNESCAPED_SLASHES);
} } else {
else {
$this->data = json_decode($string, true); $this->data = json_decode($string, true);
} }
@ -61,13 +61,13 @@ class ActivityStreams {
// verify and unpack JSalmon signature if present // verify and unpack JSalmon signature if present
// This will only be the case for Zot6 packets // This will only be the case for Zot6 packets
if (is_array($this->data) && array_key_exists('signed',$this->data)) { if (is_array($this->data) && array_key_exists('signed', $this->data)) {
$ret = JSalmon::verify($this->data); $ret = JSalmon::verify($this->data);
$tmp = JSalmon::unpack($this->data['data']); $tmp = JSalmon::unpack($this->data['data']);
if ($ret && $ret['success']) { if ($ret && $ret['success']) {
if ($ret['signer']) { if ($ret['signer']) {
logger('Unpacked: ' . json_encode($tmp,JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT),LOGGER_DATA,LOG_DEBUG); logger('Unpacked: ' . json_encode($tmp, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT), LOGGER_DATA, LOG_DEBUG);
$saved = json_encode($this->data,JSON_UNESCAPED_SLASHES); $saved = json_encode($this->data, JSON_UNESCAPED_SLASHES);
$this->data = $tmp; $this->data = $tmp;
$this->data['signer'] = $ret['signer']; $this->data['signer'] = $ret['signer'];
$this->data['signed_data'] = $saved; $this->data['signed_data'] = $saved;
@ -84,7 +84,7 @@ class ActivityStreams {
// Special handling for Mastodon "delete actor" activities which will often fail to verify // Special handling for Mastodon "delete actor" activities which will often fail to verify
// because the key cannot be fetched. We will catch this condition elsewhere. // because the key cannot be fetched. We will catch this condition elsewhere.
if (array_key_exists('type',$this->data) && array_key_exists('actor',$this->data) && array_key_exists('object',$this->data)) { if (array_key_exists('type', $this->data) && array_key_exists('actor', $this->data) && array_key_exists('object', $this->data)) {
if ($this->data['type'] === 'Delete' && $this->data['actor'] === $this->data['object']) { if ($this->data['type'] === 'Delete' && $this->data['actor'] === $this->data['object']) {
$this->deleted = $this->data['actor']; $this->deleted = $this->data['actor'];
$this->valid = false; $this->valid = false;
@ -98,7 +98,7 @@ class ActivityStreams {
if ($this->is_valid()) { if ($this->is_valid()) {
$this->id = $this->get_property_obj('id'); $this->id = $this->get_property_obj('id');
$this->type = $this->get_primary_type(); $this->type = $this->get_primary_type();
$this->actor = $this->get_actor('actor','',''); $this->actor = $this->get_actor('actor', '', '');
$this->obj = $this->get_compound_property('object'); $this->obj = $this->get_compound_property('object');
$this->tgt = $this->get_compound_property('target'); $this->tgt = $this->get_compound_property('target');
$this->origin = $this->get_compound_property('origin'); $this->origin = $this->get_compound_property('origin');
@ -107,49 +107,49 @@ class ActivityStreams {
$this->ldsig = $this->get_compound_property('signature'); $this->ldsig = $this->get_compound_property('signature');
if ($this->ldsig) { if ($this->ldsig) {
$this->signer = $this->get_compound_property('creator',$this->ldsig); $this->signer = $this->get_compound_property('creator', $this->ldsig);
if ($this->signer && is_array($this->signer) && array_key_exists('publicKey',$this->signer) if ($this->signer && is_array($this->signer) && array_key_exists('publicKey', $this->signer)
&& is_array($this->signer['publicKey']) && $this->signer['publicKey']['publicKeyPem']) { && is_array($this->signer['publicKey']) && $this->signer['publicKey']['publicKeyPem']) {
$this->sigok = LDSignatures::verify($this->data,$this->signer['publicKey']['publicKeyPem']); $this->sigok = LDSignatures::verify($this->data, $this->signer['publicKey']['publicKeyPem']);
} }
} }
// Implied create activity required by C2S specification if no object is present // Implied create activity required by C2S specification if no object is present
if (! $this->obj) { if (!$this->obj) {
if (! $client) { if (!$client) {
$this->implied_create = true; $this->implied_create = true;
} }
$this->obj = $this->data; $this->obj = $this->data;
$this->type = 'Create'; $this->type = 'Create';
if (! $this->actor) { if (!$this->actor) {
$this->actor = $this->get_actor('attributedTo',$this->obj); $this->actor = $this->get_actor('attributedTo', $this->obj);
} }
} }
// fetch recursive or embedded activities // fetch recursive or embedded activities
if ($this->obj && is_array($this->obj) && array_key_exists('object',$this->obj)) { if ($this->obj && is_array($this->obj) && array_key_exists('object', $this->obj)) {
$this->obj['object'] = $this->get_compound_property($this->obj['object']); $this->obj['object'] = $this->get_compound_property($this->obj['object']);
} }
// Enumerate and store actors in referenced objects // Enumerate and store actors in referenced objects
if ($this->obj && is_array($this->obj) && $this->obj['actor']) { if ($this->obj && is_array($this->obj) && $this->obj['actor']) {
$this->obj['actor'] = $this->get_actor('actor',$this->obj); $this->obj['actor'] = $this->get_actor('actor', $this->obj);
} }
if ($this->tgt && is_array($this->tgt) && $this->tgt['actor']) { if ($this->tgt && is_array($this->tgt) && $this->tgt['actor']) {
$this->tgt['actor'] = $this->get_actor('actor',$this->tgt); $this->tgt['actor'] = $this->get_actor('actor', $this->tgt);
} }
// Determine if this is a followup or response activity // Determine if this is a followup or response activity
$this->parent_id = $this->get_property_obj('inReplyTo'); $this->parent_id = $this->get_property_obj('inReplyTo');
if ((! $this->parent_id) && is_array($this->obj)) { if ((!$this->parent_id) && is_array($this->obj)) {
$this->parent_id = $this->obj['inReplyTo']; $this->parent_id = $this->obj['inReplyTo'];
} }
if ((! $this->parent_id) && is_array($this->obj)) { if ((!$this->parent_id) && is_array($this->obj)) {
$this->parent_id = $this->obj['id']; $this->parent_id = $this->obj['id'];
} }
} }
@ -158,14 +158,16 @@ class ActivityStreams {
/** /**
* @brief Return if instantiated ActivityStream is valid. * @brief Return if instantiated ActivityStream is valid.
* *
* @return boolean Return true if the JSON string could be decoded. * @return bool Return true if the JSON string could be decoded.
*/ */
function is_valid() { public function is_valid()
{
return $this->valid; return $this->valid;
} }
function set_recips($arr) { public function set_recips($arr)
{
$this->saved_recips = $arr; $this->saved_recips = $arr;
} }
@ -176,19 +178,20 @@ class ActivityStreams {
* @param string $namespace (optional) default empty * @param string $namespace (optional) default empty
* @return array * @return array
*/ */
function collect_recips($base = '', $namespace = '') { public function collect_recips($base = '', $namespace = '')
{
$x = []; $x = [];
$fields = [ 'to', 'cc', 'bto', 'bcc', 'audience']; $fields = ['to', 'cc', 'bto', 'bcc', 'audience'];
foreach ($fields as $f) { foreach ($fields as $f) {
// don't expand these yet // don't expand these yet
$y = $this->get_property_obj($f, $base, $namespace); $y = $this->get_property_obj($f, $base, $namespace);
if ($y) { if ($y) {
if (! is_array($this->raw_recips)) { if (!is_array($this->raw_recips)) {
$this->raw_recips = []; $this->raw_recips = [];
} }
if (! is_array($y)) { if (!is_array($y)) {
$y = [ $y ]; $y = [$y];
} }
$this->raw_recips[$f] = $y; $this->raw_recips[$f] = $y;
$x = array_merge($x, $y); $x = array_merge($x, $y);
@ -200,21 +203,21 @@ class ActivityStreams {
return $x; return $x;
} }
function expand($arr,$base = '',$namespace = '') { public function expand($arr, $base = '', $namespace = '')
{
$ret = []; $ret = [];
// right now use a hardwired recursion depth of 5 // right now use a hardwired recursion depth of 5
for ($z = 0; $z < 5; $z ++) { for ($z = 0; $z < 5; $z++) {
if (is_array($arr) && $arr) { if (is_array($arr) && $arr) {
foreach ($arr as $a) { foreach ($arr as $a) {
if (is_array($a)) { if (is_array($a)) {
$ret[] = $a; $ret[] = $a;
} } else {
else { $x = $this->get_compound_property($a, $base, $namespace);
$x = $this->get_compound_property($a,$base,$namespace);
if ($x) { if ($x) {
$ret = array_merge($ret,$x); $ret = array_merge($ret, $x);
} }
} }
} }
@ -234,16 +237,17 @@ class ActivityStreams {
* @return string|NULL * @return string|NULL
*/ */
function get_namespace($base, $namespace) { public function get_namespace($base, $namespace)
{
if (! $namespace) { if (!$namespace) {
return EMPTY_STR; return EMPTY_STR;
} }
$key = null; $key = null;
foreach ( [ $this->data, $base ] as $b ) { foreach ([$this->data, $base] as $b) {
if (! $b) { if (!$b) {
continue; continue;
} }
@ -256,15 +260,13 @@ class ActivityStreams {
$key = $k; $key = $k;
} }
} }
} } else {
else {
if ($namespace === $ns) { if ($namespace === $ns) {
$key = ''; $key = '';
} }
} }
} }
} } else {
else {
if ($namespace === $b['@context']) { if ($namespace === $b['@context']) {
$key = ''; $key = '';
} }
@ -284,7 +286,8 @@ class ActivityStreams {
* @return NULL|mixed * @return NULL|mixed
*/ */
function get_property_obj($property, $base = '', $namespace = '') { public function get_property_obj($property, $base = '', $namespace = '')
{
$prefix = $this->get_namespace($base, $namespace); $prefix = $this->get_namespace($base, $namespace);
if ($prefix === null) { if ($prefix === null) {
return null; return null;
@ -293,8 +296,8 @@ class ActivityStreams {
$base = (($base) ? $base : $this->data); $base = (($base) ? $base : $this->data);
$propname = (($prefix) ? $prefix . ':' : '') . $property; $propname = (($prefix) ? $prefix . ':' : '') . $property;
if (! is_array($base)) { if (!is_array($base)) {
btlogger('not an array: ' . print_r($base,true)); btlogger('not an array: ' . print_r($base, true));
return null; return null;
} }
@ -310,28 +313,28 @@ class ActivityStreams {
* @return NULL|mixed * @return NULL|mixed
*/ */
function fetch_property($url,$channel = null,$hub = null) { public function fetch_property($url, $channel = null, $hub = null)
return Activity::fetch($url,$channel,$hub); {
return Activity::fetch($url, $channel, $hub);
} }
static function is_an_actor($s) { public static function is_an_actor($s)
if (! $s) { {
if (!$s) {
return false; return false;
} }
return (in_array($s,[ 'Application','Group','Organization','Person','Service' ])); return (in_array($s, ['Application', 'Group', 'Organization', 'Person', 'Service']));
} }
static function is_response_activity($s) { public static function is_response_activity($s)
if (! $s) { {
if (!$s) {
return false; return false;
} }
return (in_array($s, [ 'Like', 'Dislike', 'Flag', 'Block', 'Announce', 'Accept', 'Reject', 'TentativeAccept', 'TentativeReject', 'emojiReaction', 'EmojiReaction', 'EmojiReact' ])); return (in_array($s, ['Like', 'Dislike', 'Flag', 'Block', 'Announce', 'Accept', 'Reject', 'TentativeAccept', 'TentativeReject', 'emojiReaction', 'EmojiReaction', 'EmojiReact']));
} }
/** /**
* @brief * @brief
* *
@ -341,7 +344,8 @@ class ActivityStreams {
* @return NULL|mixed * @return NULL|mixed
*/ */
function get_actor($property,$base='',$namespace = '') { public function get_actor($property, $base = '', $namespace = '')
{
$x = $this->get_property_obj($property, $base, $namespace); $x = $this->get_property_obj($property, $base, $namespace);
if (self::is_url($x)) { if (self::is_url($x)) {
$y = Activity::get_cached_actor($x); $y = Activity::get_cached_actor($x);
@ -350,9 +354,9 @@ class ActivityStreams {
} }
} }
$actor = $this->get_compound_property($property,$base,$namespace,true); $actor = $this->get_compound_property($property, $base, $namespace, true);
if (is_array($actor) && self::is_an_actor($actor['type'])) { if (is_array($actor) && self::is_an_actor($actor['type'])) {
if (array_key_exists('id',$actor) && (! array_key_exists('inbox',$actor))) { if (array_key_exists('id', $actor) && (!array_key_exists('inbox', $actor))) {
$actor = $this->fetch_property($actor['id']); $actor = $this->fetch_property($actor['id']);
} }
return $actor; return $actor;
@ -367,11 +371,12 @@ class ActivityStreams {
* @param string $property * @param string $property
* @param array $base * @param array $base
* @param string $namespace (optional) default empty * @param string $namespace (optional) default empty
* @param boolean $first (optional) default false, if true and result is a sequential array return only the first element * @param bool $first (optional) default false, if true and result is a sequential array return only the first element
* @return NULL|mixed * @return NULL|mixed
*/ */
function get_compound_property($property, $base = '', $namespace = '', $first = false) { public function get_compound_property($property, $base = '', $namespace = '', $first = false)
{
$x = $this->get_property_obj($property, $base, $namespace); $x = $this->get_property_obj($property, $base, $namespace);
if (self::is_url($x)) { if (self::is_url($x)) {
$y = $this->fetch_property($x); $y = $this->fetch_property($x);
@ -383,13 +388,13 @@ class ActivityStreams {
// verify and unpack JSalmon signature if present // verify and unpack JSalmon signature if present
// This may be present in Zot6 packets // This may be present in Zot6 packets
if (is_array($x) && array_key_exists('signed',$x)) { if (is_array($x) && array_key_exists('signed', $x)) {
$ret = JSalmon::verify($x); $ret = JSalmon::verify($x);
$tmp = JSalmon::unpack($x['data']); $tmp = JSalmon::unpack($x['data']);
if ($ret && $ret['success']) { if ($ret && $ret['success']) {
if ($ret['signer']) { if ($ret['signer']) {
logger('Unpacked: ' . json_encode($tmp,JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT),LOGGER_DATA,LOG_DEBUG); logger('Unpacked: ' . json_encode($tmp, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT), LOGGER_DATA, LOG_DEBUG);
$saved = json_encode($x,JSON_UNESCAPED_SLASHES); $saved = json_encode($x, JSON_UNESCAPED_SLASHES);
$x = $tmp; $x = $tmp;
$x['signer'] = $ret['signer']; $x['signer'] = $ret['signer'];
$x['signed_data'] = $saved; $x['signed_data'] = $saved;
@ -399,7 +404,7 @@ class ActivityStreams {
} }
} }
} }
if ($first && is_array($x) && array_key_exists(0,$x)) { if ($first && is_array($x) && array_key_exists(0, $x)) {
return $x[0]; return $x[0];
} }
@ -410,11 +415,12 @@ class ActivityStreams {
* @brief Check if string starts with http. * @brief Check if string starts with http.
* *
* @param string $url * @param string $url
* @return boolean * @return bool
*/ */
static public function is_url($url) { public static function is_url($url)
if (($url) && (! is_array($url)) && ((strpos($url, 'http') === 0) || (strpos($url,'x-zot') === 0) || (strpos($url,'bear') === 0))) { {
if (($url) && (!is_array($url)) && ((strpos($url, 'http') === 0) || (strpos($url, 'x-zot') === 0) || (strpos($url, 'bear') === 0))) {
return true; return true;
} }
@ -429,8 +435,9 @@ class ActivityStreams {
* @return NULL|mixed * @return NULL|mixed
*/ */
function get_primary_type($base = '', $namespace = '') { public function get_primary_type($base = '', $namespace = '')
if (! $base) { {
if (!$base) {
$base = $this->data; $base = $this->data;
} }
$x = $this->get_property_obj('type', $base, $namespace); $x = $this->get_property_obj('type', $base, $namespace);
@ -445,13 +452,15 @@ class ActivityStreams {
return $x; return $x;
} }
function debug() { public function debug()
{
$x = var_export($this, true); $x = var_export($this, true);
return $x; return $x;
} }
static function is_as_request() { public static function is_as_request()
{
$x = getBestSupportedMimeType([ $x = getBestSupportedMimeType([
'application/ld+json;profile="https://www.w3.org/ns/activitystreams"', 'application/ld+json;profile="https://www.w3.org/ns/activitystreams"',
@ -461,6 +470,6 @@ class ActivityStreams {
'application/x-zot-activity+json' 'application/x-zot-activity+json'
]); ]);
return(($x) ? true : false); return (($x) ? true : false);
} }
} }

View file

@ -3,29 +3,33 @@
namespace Zotlabs\Lib; namespace Zotlabs\Lib;
class Api_router { class Api_router
{
static private $routes = []; private static $routes = [];
static function register($path,$fn,$auth_required) { public static function register($path, $fn, $auth_required)
self::$routes[$path] = [ 'func' => $fn, 'auth' => $auth_required ]; {
self::$routes[$path] = ['func' => $fn, 'auth' => $auth_required];
} }
static function find($path) { public static function find($path)
if (array_key_exists($path,self::$routes)) { {
if (array_key_exists($path, self::$routes)) {
return self::$routes[$path]; return self::$routes[$path];
} }
$with_params = dirname($path) . '/[id]'; $with_params = dirname($path) . '/[id]';
if (array_key_exists($with_params,self::$routes)) { if (array_key_exists($with_params, self::$routes)) {
return self::$routes[$with_params]; return self::$routes[$with_params];
} }
return null; return null;
} }
static function dbg() { public static function dbg()
{
return self::$routes; return self::$routes;
} }

File diff suppressed because it is too large Load diff

View file

@ -6,7 +6,8 @@ use Zotlabs\Lib\Libsync;
/** /**
* @brief A class with chatroom related static methods. * @brief A class with chatroom related static methods.
*/ */
class Chatroom { class Chatroom
{
/** /**
* @brief Creates a chatroom. * @brief Creates a chatroom.
* *
@ -16,12 +17,13 @@ class Chatroom {
* * \e boolean \b success - A boolean success status * * \e boolean \b success - A boolean success status
* * \e string \b message - (optional) A string * * \e string \b message - (optional) A string
*/ */
static public function create($channel, $arr) { public static function create($channel, $arr)
{
$ret = array('success' => false); $ret = array('success' => false);
$name = trim($arr['name']); $name = trim($arr['name']);
if(! $name) { if (!$name) {
$ret['message'] = t('Missing room name'); $ret['message'] = t('Missing room name');
return $ret; return $ret;
} }
@ -30,7 +32,7 @@ class Chatroom {
intval($channel['channel_id']), intval($channel['channel_id']),
dbesc($name) dbesc($name)
); );
if($r) { if ($r) {
$ret['message'] = t('Duplicate room name'); $ret['message'] = t('Duplicate room name');
return $ret; return $ret;
} }
@ -38,15 +40,15 @@ class Chatroom {
$r = q("select count(cr_id) as total from chatroom where cr_aid = %d", $r = q("select count(cr_id) as total from chatroom where cr_aid = %d",
intval($channel['channel_account_id']) intval($channel['channel_account_id'])
); );
if($r) if ($r)
$limit = service_class_fetch($channel['channel_id'], 'chatrooms'); $limit = service_class_fetch($channel['channel_id'], 'chatrooms');
if(($r) && ($limit !== false) && ($r[0]['total'] >= $limit)) { if (($r) && ($limit !== false) && ($r[0]['total'] >= $limit)) {
$ret['message'] = upgrade_message(); $ret['message'] = upgrade_message();
return $ret; return $ret;
} }
if(! array_key_exists('expire', $arr)) if (!array_key_exists('expire', $arr))
$arr['expire'] = 120; // minutes, e.g. 2 hours $arr['expire'] = 120; // minutes, e.g. 2 hours
$created = datetime_convert(); $created = datetime_convert();
@ -65,20 +67,21 @@ class Chatroom {
dbesc($arr['deny_gid']) dbesc($arr['deny_gid'])
); );
if($x) if ($x)
$ret['success'] = true; $ret['success'] = true;
return $ret; return $ret;
} }
static public function destroy($channel,$arr) { public static function destroy($channel, $arr)
{
$ret = array('success' => false); $ret = array('success' => false);
if(intval($arr['cr_id'])) if (intval($arr['cr_id']))
$sql_extra = " and cr_id = " . intval($arr['cr_id']) . " "; $sql_extra = " and cr_id = " . intval($arr['cr_id']) . " ";
elseif(trim($arr['cr_name'])) elseif (trim($arr['cr_name']))
$sql_extra = " and cr_name = '" . protect_sprintf(dbesc(trim($arr['cr_name']))) . "' "; $sql_extra = " and cr_name = '" . protect_sprintf(dbesc(trim($arr['cr_name']))) . "' ";
else { else {
$ret['message'] = t('Invalid room specifier.'); $ret['message'] = t('Invalid room specifier.');
@ -88,17 +91,17 @@ class Chatroom {
$r = q("select * from chatroom where cr_uid = %d $sql_extra limit 1", $r = q("select * from chatroom where cr_uid = %d $sql_extra limit 1",
intval($channel['channel_id']) intval($channel['channel_id'])
); );
if(! $r) { if (!$r) {
$ret['message'] = t('Invalid room specifier.'); $ret['message'] = t('Invalid room specifier.');
return $ret; return $ret;
} }
Libsync::build_sync_packet($channel['channel_id'],array('chatroom' => $r)); Libsync::build_sync_packet($channel['channel_id'], array('chatroom' => $r));
q("delete from chatroom where cr_id = %d", q("delete from chatroom where cr_id = %d",
intval($r[0]['cr_id']) intval($r[0]['cr_id'])
); );
if($r[0]['cr_id']) { if ($r[0]['cr_id']) {
q("delete from chatpresence where cp_room = %d", q("delete from chatpresence where cp_room = %d",
intval($r[0]['cr_id']) intval($r[0]['cr_id'])
); );
@ -112,16 +115,17 @@ class Chatroom {
} }
static public function enter($observer_xchan, $room_id, $status, $client) { public static function enter($observer_xchan, $room_id, $status, $client)
{
if(! $room_id || ! $observer_xchan) if (!$room_id || !$observer_xchan)
return; return;
$r = q("select * from chatroom where cr_id = %d limit 1", $r = q("select * from chatroom where cr_id = %d limit 1",
intval($room_id) intval($room_id)
); );
if(! $r) { if (!$r) {
notice( t('Room not found.') . EOL); notice(t('Room not found.') . EOL);
return false; return false;
} }
require_once('include/security.php'); require_once('include/security.php');
@ -131,26 +135,26 @@ class Chatroom {
intval($room_id), intval($room_id),
intval($r[0]['cr_uid']) intval($r[0]['cr_uid'])
); );
if(! $x) { if (!$x) {
notice( t('Permission denied.') . EOL); notice(t('Permission denied.') . EOL);
return false; return false;
} }
$limit = service_class_fetch($r[0]['cr_uid'], 'chatters_inroom'); $limit = service_class_fetch($r[0]['cr_uid'], 'chatters_inroom');
if($limit !== false) { if ($limit !== false) {
$y = q("select count(*) as total from chatpresence where cp_room = %d", $y = q("select count(*) as total from chatpresence where cp_room = %d",
intval($room_id) intval($room_id)
); );
if($y && $y[0]['total'] > $limit) { if ($y && $y[0]['total'] > $limit) {
notice( t('Room is full') . EOL); notice(t('Room is full') . EOL);
return false; return false;
} }
} }
if(intval($x[0]['cr_expire'])) { if (intval($x[0]['cr_expire'])) {
$r = q("delete from chat where created < %s - INTERVAL %s and chat_room = %d", $r = q("delete from chat where created < %s - INTERVAL %s and chat_room = %d",
db_utcnow(), db_utcnow(),
db_quoteinterval( intval($x[0]['cr_expire']) . ' MINUTE' ), db_quoteinterval(intval($x[0]['cr_expire']) . ' MINUTE'),
intval($x[0]['cr_id']) intval($x[0]['cr_id'])
); );
} }
@ -159,7 +163,7 @@ class Chatroom {
dbesc($observer_xchan), dbesc($observer_xchan),
intval($room_id) intval($room_id)
); );
if($r) { if ($r) {
q("update chatpresence set cp_last = '%s' where cp_id = %d and cp_client = '%s'", q("update chatpresence set cp_last = '%s' where cp_id = %d and cp_client = '%s'",
dbesc(datetime_convert()), dbesc(datetime_convert()),
intval($r[0]['cp_id']), intval($r[0]['cp_id']),
@ -181,8 +185,9 @@ class Chatroom {
} }
function leave($observer_xchan, $room_id, $client) { public function leave($observer_xchan, $room_id, $client)
if(! $room_id || ! $observer_xchan) {
if (!$room_id || !$observer_xchan)
return; return;
$r = q("select * from chatpresence where cp_xchan = '%s' and cp_room = %d and cp_client = '%s' limit 1", $r = q("select * from chatpresence where cp_xchan = '%s' and cp_room = %d and cp_client = '%s' limit 1",
@ -190,7 +195,7 @@ class Chatroom {
intval($room_id), intval($room_id),
dbesc($client) dbesc($client)
); );
if($r) { if ($r) {
q("delete from chatpresence where cp_id = %d", q("delete from chatpresence where cp_id = %d",
intval($r[0]['cp_id']) intval($r[0]['cp_id'])
); );
@ -200,7 +205,8 @@ class Chatroom {
} }
static public function roomlist($uid) { public static function roomlist($uid)
{
require_once('include/security.php'); require_once('include/security.php');
$sql_extra = permissions_sql($uid); $sql_extra = permissions_sql($uid);
@ -211,7 +217,8 @@ class Chatroom {
return $r; return $r;
} }
static public function list_count($uid) { public static function list_count($uid)
{
require_once('include/security.php'); require_once('include/security.php');
$sql_extra = permissions_sql($uid); $sql_extra = permissions_sql($uid);
@ -233,11 +240,12 @@ class Chatroom {
* @param string $text * @param string $text
* @return array * @return array
*/ */
static public function message($uid, $room_id, $xchan, $text) { public static function message($uid, $room_id, $xchan, $text)
{
$ret = array('success' => false); $ret = array('success' => false);
if(! $text) if (!$text)
return; return;
$sql_extra = permissions_sql($uid); $sql_extra = permissions_sql($uid);
@ -246,7 +254,7 @@ class Chatroom {
intval($uid), intval($uid),
intval($room_id) intval($room_id)
); );
if(! $r) if (!$r)
return $ret; return $ret;
$arr = [ $arr = [

View file

@ -16,7 +16,7 @@ class Config {
* @param string $family * @param string $family
* The category of the configuration value * The category of the configuration value
*/ */
static public function Load($family) { public static function Load($family) {
if(! array_key_exists($family, App::$config)) if(! array_key_exists($family, App::$config))
App::$config[$family] = []; App::$config[$family] = [];
@ -48,7 +48,7 @@ class Config {
* @return mixed * @return mixed
* Return the set value, or false if the database update failed * Return the set value, or false if the database update failed
*/ */
static public function Set($family, $key, $value) { public static function Set($family, $key, $value) {
// manage array value // manage array value
$dbvalue = ((is_array($value)) ? serialise($value) : $value); $dbvalue = ((is_array($value)) ? serialise($value) : $value);
$dbvalue = ((is_bool($dbvalue)) ? intval($dbvalue) : $dbvalue); $dbvalue = ((is_bool($dbvalue)) ? intval($dbvalue) : $dbvalue);
@ -98,7 +98,7 @@ class Config {
* @param string $default (optional) default false * @param string $default (optional) default false
* @return mixed Return value or false on error or if not set * @return mixed Return value or false on error or if not set
*/ */
static public function Get($family, $key, $default = false) { public static function Get($family, $key, $default = false) {
if((! array_key_exists($family, App::$config)) || (! array_key_exists('config_loaded', App::$config[$family]))) if((! array_key_exists($family, App::$config)) || (! array_key_exists('config_loaded', App::$config[$family])))
self::Load($family); self::Load($family);
@ -124,7 +124,7 @@ class Config {
* The configuration key to delete * The configuration key to delete
* @return mixed * @return mixed
*/ */
static public function Delete($family, $key) { public static function Delete($family, $key) {
$ret = false; $ret = false;
@ -152,7 +152,7 @@ class Config {
* The configuration key to query * The configuration key to query
* @return mixed * @return mixed
*/ */
static private function get_from_storage($family,$key) { private static function get_from_storage($family, $key) {
$ret = q("SELECT * FROM config WHERE cat = '%s' AND k = '%s' LIMIT 1", $ret = q("SELECT * FROM config WHERE cat = '%s' AND k = '%s' LIMIT 1",
dbesc($family), dbesc($family),
dbesc($key) dbesc($key)

View file

@ -7,8 +7,8 @@ use Zotlabs\Access\Permissions;
use Zotlabs\Daemon\Run; use Zotlabs\Daemon\Run;
class Connect
class Connect { {
/** /**
* Takes a $channel and a $url/handle and adds a new connection * Takes a $channel and a $url/handle and adds a new connection
@ -21,35 +21,36 @@ class Connect {
* This function does NOT send sync packets to clones. The caller is responsible for doing this * This function does NOT send sync packets to clones. The caller is responsible for doing this
*/ */
static function connect($channel, $url, $sub_channel = false) { public static function connect($channel, $url, $sub_channel = false)
{
$uid = $channel['channel_id']; $uid = $channel['channel_id'];
if (strpos($url,'@') === false && strpos($url,'/') === false) { if (strpos($url, '@') === false && strpos($url, '/') === false) {
$url = $url . '@' . App::get_hostname(); $url = $url . '@' . App::get_hostname();
} }
$result = [ 'success' => false, 'message' => '' ]; $result = ['success' => false, 'message' => ''];
$my_perms = false; $my_perms = false;
$protocol = ''; $protocol = '';
$ap_allowed = get_config('system','activitypub', ACTIVITYPUB_ENABLED) && get_pconfig($uid,'system','activitypub', ACTIVITYPUB_ENABLED); $ap_allowed = get_config('system', 'activitypub', ACTIVITYPUB_ENABLED) && get_pconfig($uid, 'system', 'activitypub', ACTIVITYPUB_ENABLED);
if (substr($url,0,1) === '[') { if (substr($url, 0, 1) === '[') {
$x = strpos($url,']'); $x = strpos($url, ']');
if ($x) { if ($x) {
$protocol = substr($url,1,$x-1); $protocol = substr($url, 1, $x - 1);
$url = substr($url,$x+1); $url = substr($url, $x + 1);
} }
} }
if (! check_siteallowed($url)) { if (!check_siteallowed($url)) {
$result['message'] = t('Channel is blocked on this site.'); $result['message'] = t('Channel is blocked on this site.');
return $result; return $result;
} }
if (! $url) { if (!$url) {
$result['message'] = t('Channel location missing.'); $result['message'] = t('Channel location missing.');
return $result; return $result;
} }
@ -63,7 +64,7 @@ class Connect {
$total_channels = $r[0]['total']; $total_channels = $r[0]['total'];
} }
if (! service_class_allows($uid,'total_channels',$total_channels)) { if (!service_class_allows($uid, 'total_channels', $total_channels)) {
$result['message'] = upgrade_message(); $result['message'] = upgrade_message();
return $result; return $result;
} }
@ -82,15 +83,15 @@ class Connect {
// reset results to the best record or the first if we don't have the best // reset results to the best record or the first if we don't have the best
// note: this returns a single record and not an array of records // note: this returns a single record and not an array of records
$r = Libzot::zot_record_preferred($r,'xchan_network'); $r = Libzot::zot_record_preferred($r, 'xchan_network');
// ensure there's a valid hubloc for this xchan before proceeding - you cannot connect without it // ensure there's a valid hubloc for this xchan before proceeding - you cannot connect without it
if (in_array($r['xchan_network'], [ 'zot6','activitypub' ])) { if (in_array($r['xchan_network'], ['zot6', 'activitypub'])) {
$h = q("select * from hubloc where hubloc_hash = '%s'", $h = q("select * from hubloc where hubloc_hash = '%s'",
dbesc($r['xchan_hash']) dbesc($r['xchan_hash'])
); );
if (! $h) { if (!$h) {
$r = null; $r = null;
} }
} }
@ -120,13 +121,13 @@ class Connect {
$singleton = false; $singleton = false;
if (! $r) { if (!$r) {
// not in cache - try discovery // not in cache - try discovery
$wf = discover_by_webbie($url,$protocol,false); $wf = discover_by_webbie($url, $protocol, false);
if (! $wf) { if (!$wf) {
$result['message'] = t('Remote channel or protocol unavailable.'); $result['message'] = t('Remote channel or protocol unavailable.');
return $result; return $result;
} }
@ -145,7 +146,7 @@ class Connect {
// convert to a single record (once again preferring a zot solution in the case of multiples) // convert to a single record (once again preferring a zot solution in the case of multiples)
if ($r) { if ($r) {
$r = Libzot::zot_record_preferred($r,'xchan_network'); $r = Libzot::zot_record_preferred($r, 'xchan_network');
} }
} }
@ -159,13 +160,13 @@ class Connect {
// failure case // failure case
if (! $xchan_hash) { if (!$xchan_hash) {
$result['message'] = t('Channel discovery failed.'); $result['message'] = t('Channel discovery failed.');
logger('follow: ' . $result['message']); logger('follow: ' . $result['message']);
return $result; return $result;
} }
if (! check_channelallowed($xchan_hash)) { if (!check_channelallowed($xchan_hash)) {
$result['message'] = t('Channel is blocked on this site.'); $result['message'] = t('Channel is blocked on this site.');
logger('follow: ' . $result['message']); logger('follow: ' . $result['message']);
return $result; return $result;
@ -174,7 +175,7 @@ class Connect {
if ($r['xchan_network'] === 'activitypub') { if ($r['xchan_network'] === 'activitypub') {
if (! $ap_allowed) { if (!$ap_allowed) {
$result['message'] = t('Protocol not supported'); $result['message'] = t('Protocol not supported');
return $result; return $result;
} }
@ -207,7 +208,7 @@ class Connect {
$my_perms = Permissions::serialise($p['perms']); $my_perms = Permissions::serialise($p['perms']);
$profile_assign = get_pconfig($uid,'system','profile_assign',''); $profile_assign = get_pconfig($uid, 'system', 'profile_assign', '');
// See if we are already connected by virtue of having an abook record // See if we are already connected by virtue of having an abook record
@ -223,7 +224,7 @@ class Connect {
// If they are on a non-nomadic network, add them to this location // If they are on a non-nomadic network, add them to this location
if (($singleton) && strpos($abook_instance,z_root()) === false) { if (($singleton) && strpos($abook_instance, z_root()) === false) {
if ($abook_instance) { if ($abook_instance) {
$abook_instance .= ','; $abook_instance .= ',';
} }
@ -242,12 +243,11 @@ class Connect {
intval($r[0]['abook_id']) intval($r[0]['abook_id'])
); );
} }
} } else {
else {
// create a new abook record // create a new abook record
$closeness = get_pconfig($uid,'system','new_abook_closeness',80); $closeness = get_pconfig($uid, 'system', 'new_abook_closeness', 80);
$r = abook_store_lowlevel( $r = abook_store_lowlevel(
[ [
@ -264,7 +264,7 @@ class Connect {
); );
} }
if (! $r) { if (!$r) {
logger('abook creation failed'); logger('abook creation failed');
$result['message'] = t('error saving data'); $result['message'] = t('error saving data');
return $result; return $result;
@ -273,7 +273,7 @@ class Connect {
// Set suitable permissions to the connection // Set suitable permissions to the connection
if ($my_perms) { if ($my_perms) {
set_abconfig($uid,$xchan_hash,'system','my_perms',$my_perms); set_abconfig($uid, $xchan_hash, 'system', 'my_perms', $my_perms);
} }
// fetch the entire record // fetch the entire record
@ -286,19 +286,19 @@ class Connect {
if ($r) { if ($r) {
$result['abook'] = array_shift($r); $result['abook'] = array_shift($r);
Run::Summon([ 'Notifier', 'permissions_create', $result['abook']['abook_id'] ]); Run::Summon(['Notifier', 'permissions_create', $result['abook']['abook_id']]);
} }
$arr = [ 'channel_id' => $uid, 'channel' => $channel, 'abook' => $result['abook'] ]; $arr = ['channel_id' => $uid, 'channel' => $channel, 'abook' => $result['abook']];
call_hooks('follow', $arr); call_hooks('follow', $arr);
/** If there is a default group for this channel, add this connection to it */ /** If there is a default group for this channel, add this connection to it */
if ($default_group) { if ($default_group) {
$g = AccessList::rec_byhash($uid,$default_group); $g = AccessList::rec_byhash($uid, $default_group);
if ($g) { if ($g) {
AccessList::member_add($uid,'',$xchan_hash,$g['id']); AccessList::member_add($uid, '', $xchan_hash, $g['id']);
} }
} }

View file

@ -5,7 +5,7 @@ use Exception;
class Crypto { class Crypto {
static public $openssl_algorithms = [ public static $openssl_algorithms = [
// zot6 nickname, opensslname, keylength, ivlength // zot6 nickname, opensslname, keylength, ivlength
@ -16,7 +16,7 @@ class Crypto {
]; ];
static public function methods() { public static function methods() {
$ret = []; $ret = [];
foreach(self::$openssl_algorithms as $ossl) { foreach(self::$openssl_algorithms as $ossl) {
@ -28,7 +28,7 @@ class Crypto {
} }
static public function signing_methods() { public static function signing_methods() {
$ret = [ 'sha256' ]; $ret = [ 'sha256' ];
call_hooks('signing_methods',$ret); call_hooks('signing_methods',$ret);
@ -37,7 +37,7 @@ class Crypto {
} }
static public function new_keypair($bits) { public static function new_keypair($bits) {
$openssl_options = [ $openssl_options = [
'digest_alg' => 'sha1', 'digest_alg' => 'sha1',
@ -72,7 +72,7 @@ class Crypto {
} }
static public function sign($data,$key,$alg = 'sha256') { public static function sign($data, $key, $alg = 'sha256') {
if (! $key) { if (! $key) {
return false; return false;
@ -84,7 +84,7 @@ class Crypto {
} }
static public function verify($data,$sig,$key,$alg = 'sha256') { public static function verify($data, $sig, $key, $alg = 'sha256') {
if (! $key) { if (! $key) {
return false; return false;
@ -107,7 +107,7 @@ class Crypto {
return (($verify > 0) ? true : false); return (($verify > 0) ? true : false);
} }
static public function encapsulate($data,$pubkey,$alg) { public static function encapsulate($data, $pubkey, $alg) {
if (! ($alg && $pubkey)) { if (! ($alg && $pubkey)) {
return $data; return $data;
@ -164,7 +164,7 @@ class Crypto {
} }
} }
static public function unencapsulate($data,$prvkey) { public static function unencapsulate($data, $prvkey) {
if (! (is_array($data) && array_key_exists('encrypted',$data) && array_key_exists('alg',$data) && $data['alg'])) { if (! (is_array($data) && array_key_exists('encrypted',$data) && array_key_exists('alg',$data) && $data['alg'])) {
logger('not encrypted'); logger('not encrypted');

View file

@ -5,42 +5,43 @@ namespace Zotlabs\Lib;
use App; use App;
class DB_Upgrade { class DB_Upgrade
{
public $config_name = ''; public $config_name = '';
public $func_prefix = ''; public $func_prefix = '';
function __construct($db_revision) { public function __construct($db_revision)
{
$this->config_name = 'db_version'; $this->config_name = 'db_version';
$this->func_prefix = '_'; $this->func_prefix = '_';
$build = get_config('system', 'db_version', 0); $build = get_config('system', 'db_version', 0);
if(! intval($build)) if (!intval($build))
$build = set_config('system', 'db_version', $db_revision); $build = set_config('system', 'db_version', $db_revision);
if($build == $db_revision) { if ($build == $db_revision) {
// Nothing to be done. // Nothing to be done.
return; return;
} } else {
else {
$stored = intval($build); $stored = intval($build);
if(! $stored) { if (!$stored) {
logger('Critical: check_config unable to determine database schema version'); logger('Critical: check_config unable to determine database schema version');
return; return;
} }
$current = intval($db_revision); $current = intval($db_revision);
if($stored < $current) { if ($stored < $current) {
// The last update we performed was $stored. // The last update we performed was $stored.
// Start at $stored + 1 and continue until we have completed $current // Start at $stored + 1 and continue until we have completed $current
for($x = $stored + 1; $x <= $current; $x ++) { for ($x = $stored + 1; $x <= $current; $x++) {
$s = '_' . $x; $s = '_' . $x;
$cls = '\\Zotlabs\Update\\' . $s ; $cls = '\\Zotlabs\Update\\' . $s;
if(! class_exists($cls)) { if (!class_exists($cls)) {
return; return;
} }
@ -54,16 +55,16 @@ class DB_Upgrade {
Config::Load('database'); Config::Load('database');
if(get_config('database', $s)) if (get_config('database', $s))
break; break;
set_config('database',$s, '1'); set_config('database', $s, '1');
$c = new $cls(); $c = new $cls();
$retval = $c->run(); $retval = $c->run();
if($retval != UPDATE_SUCCESS) { if ($retval != UPDATE_SUCCESS) {
$source = t('Source code of failed update: ') . "\n\n" . @file_get_contents('Zotlabs/Update/' . $s . '.php'); $source = t('Source code of failed update: ') . "\n\n" . @file_get_contents('Zotlabs/Update/' . $s . '.php');
@ -87,13 +88,13 @@ class DB_Upgrade {
z_mail( z_mail(
[ [
'toEmail' => App::$config['system']['admin_email'], 'toEmail' => App::$config['system']['admin_email'],
'messageSubject' => sprintf( t('Update Error at %s'), z_root()), 'messageSubject' => sprintf(t('Update Error at %s'), z_root()),
'textVersion' => replace_macros(get_intltext_template('update_fail_eml.tpl'), 'textVersion' => replace_macros(get_intltext_template('update_fail_eml.tpl'),
[ [
'$sitename' => App::$config['system']['sitename'], '$sitename' => App::$config['system']['sitename'],
'$siteurl' => z_root(), '$siteurl' => z_root(),
'$update' => $x, '$update' => $x,
'$error' => sprintf( t('Update %s failed. See error logs.'), $x), '$error' => sprintf(t('Update %s failed. See error logs.'), $x),
'$baseurl' => z_root(), '$baseurl' => z_root(),
'$source' => $source '$source' => $source
] ]
@ -104,9 +105,8 @@ class DB_Upgrade {
//try the logger //try the logger
logger('CRITICAL: Update Failed: ' . $x); logger('CRITICAL: Update Failed: ' . $x);
pop_lang(); pop_lang();
} } else {
else { set_config('database', $s, 'success');
set_config('database',$s, 'success');
} }
} }
} }

View file

@ -1,7 +1,8 @@
<?php <?php
namespace Zotlabs\Lib; namespace Zotlabs\Lib;
class DReport { class DReport
{
private $location; private $location;
private $sender; private $sender;
@ -10,7 +11,8 @@ class DReport {
private $status; private $status;
private $date; private $date;
function __construct($location,$sender,$recipient,$message_id,$status = 'deliver') { public function __construct($location, $sender, $recipient, $message_id, $status = 'deliver')
{
$this->location = $location; $this->location = $location;
$this->sender = $sender; $this->sender = $sender;
$this->recipient = $recipient; $this->recipient = $recipient;
@ -20,21 +22,25 @@ class DReport {
$this->date = datetime_convert(); $this->date = datetime_convert();
} }
function update($status) { public function update($status)
{
$this->status = $status; $this->status = $status;
$this->date = datetime_convert(); $this->date = datetime_convert();
} }
function set_name($name) { public function set_name($name)
{
$this->name = $name; $this->name = $name;
} }
function addto_update($status) { public function addto_update($status)
{
$this->status = $this->status . ' ' . $status; $this->status = $this->status . ' ' . $status;
} }
function set($arr) { public function set($arr)
{
$this->location = $arr['location']; $this->location = $arr['location'];
$this->sender = $arr['sender']; $this->sender = $arr['sender'];
$this->recipient = $arr['recipient']; $this->recipient = $arr['recipient'];
@ -44,7 +50,8 @@ class DReport {
$this->date = $arr['date']; $this->date = $arr['date'];
} }
function get() { public function get()
{
return array( return array(
'location' => $this->location, 'location' => $this->location,
'sender' => $this->sender, 'sender' => $this->sender,
@ -60,12 +67,13 @@ class DReport {
* @brief decide whether to store a returned delivery report * @brief decide whether to store a returned delivery report
* *
* @param array $dr * @param array $dr
* @return boolean * @return bool
*/ */
static function is_storable($dr) { public static function is_storable($dr)
{
if(get_config('system', 'disable_dreport')) if (get_config('system', 'disable_dreport'))
return false; return false;
/** /**
@ -77,12 +85,12 @@ class DReport {
call_hooks('dreport_is_storable', $dr); call_hooks('dreport_is_storable', $dr);
// let plugins accept or reject - if neither, continue on // let plugins accept or reject - if neither, continue on
if(array_key_exists('accept',$dr) && intval($dr['accept'])) if (array_key_exists('accept', $dr) && intval($dr['accept']))
return true; return true;
if(array_key_exists('reject',$dr) && intval($dr['reject'])) if (array_key_exists('reject', $dr) && intval($dr['reject']))
return false; return false;
if(! ($dr['sender'])) if (!($dr['sender']))
return false; return false;
// Is the sender one of our channels? // Is the sender one of our channels?
@ -90,7 +98,7 @@ class DReport {
$c = q("select channel_id from channel where channel_hash = '%s' limit 1", $c = q("select channel_id from channel where channel_hash = '%s' limit 1",
dbesc($dr['sender']) dbesc($dr['sender'])
); );
if(! $c) if (!$c)
return false; return false;
@ -98,15 +106,15 @@ class DReport {
$rxchan = $dr['recipient']; $rxchan = $dr['recipient'];
$pcf = get_pconfig($c[0]['channel_id'],'system','dreport_store_all'); $pcf = get_pconfig($c[0]['channel_id'], 'system', 'dreport_store_all');
if($pcf) if ($pcf)
return true; return true;
// We always add ourself as a recipient to private and relayed posts // We always add ourself as a recipient to private and relayed posts
// So if a remote site says they can't find us, that's no big surprise // So if a remote site says they can't find us, that's no big surprise
// and just creates a lot of extra report noise // and just creates a lot of extra report noise
if(($dr['location'] !== z_root()) && ($dr['sender'] === $rxchan) && ($dr['status'] === 'recipient not found')) if (($dr['location'] !== z_root()) && ($dr['sender'] === $rxchan) && ($dr['status'] === 'recipient not found'))
return false; return false;
// If you have a private post with a recipient list, every single site is going to report // If you have a private post with a recipient list, every single site is going to report
@ -118,14 +126,14 @@ class DReport {
dbesc($rxchan), dbesc($rxchan),
dbesc($dr['location']) dbesc($dr['location'])
); );
if((! $r) && ($dr['status'] === 'recipient not found')) if ((!$r) && ($dr['status'] === 'recipient not found'))
return false; return false;
$r = q("select abook_id from abook where abook_xchan = '%s' and abook_channel = %d limit 1", $r = q("select abook_id from abook where abook_xchan = '%s' and abook_channel = %d limit 1",
dbesc($rxchan), dbesc($rxchan),
intval($c[0]['channel_id']) intval($c[0]['channel_id'])
); );
if($r) if ($r)
return true; return true;
return false; return false;

View file

@ -29,7 +29,7 @@ class Enotify {
*/ */
static public function submit($params) { public static function submit($params) {
logger('notification: entry', LOGGER_DEBUG); logger('notification: entry', LOGGER_DEBUG);
@ -807,7 +807,7 @@ class Enotify {
* * \e string \b textVersion text only version of the message * * \e string \b textVersion text only version of the message
* * \e string \b additionalMailHeader additions to the smtp mail header * * \e string \b additionalMailHeader additions to the smtp mail header
*/ */
static public function send($params) { public static function send($params) {
$params['sent'] = false; $params['sent'] = false;
$params['result'] = false; $params['result'] = false;
@ -862,7 +862,7 @@ class Enotify {
return $res; return $res;
} }
static public function format($item) { public static function format($item) {
$ret = ''; $ret = '';

View file

@ -28,9 +28,11 @@ namespace Zotlabs\Lib;
* *
*/ */
class Hashpath { class Hashpath
{
static function path($url, $prefix = '.', $depth = 1, $mkdir = true) { public static function path($url, $prefix = '.', $depth = 1, $mkdir = true)
{
$hash = hash('sha256', $url); $hash = hash('sha256', $url);
$start = 0; $start = 0;
$slice = 2; $slice = 2;
@ -40,12 +42,11 @@ class Hashpath {
$sluglen = $depth * $slice; $sluglen = $depth * $slice;
do { do {
$slug = substr($hash,$start,$slice); $slug = substr($hash, $start, $slice);
$prefix .= '/' . $slug; $prefix .= '/' . $slug;
$start += $slice; $start += $slice;
$sluglen -= $slice; $sluglen -= $slice;
} } while ($sluglen);
while ($sluglen);
if ($mkdir) { if ($mkdir) {
os_mkdir($prefix, STORAGE_DEFAULT_PERMISSIONS, true); os_mkdir($prefix, STORAGE_DEFAULT_PERMISSIONS, true);

View file

@ -6,11 +6,11 @@ namespace Zotlabs\Lib;
class IConfig { class IConfig {
static public function Load(&$item) { public static function Load(&$item) {
return; return;
} }
static public function Get(&$item, $family, $key, $default = false) { public static function Get(&$item, $family, $key, $default = false) {
$is_item = false; $is_item = false;
@ -76,7 +76,7 @@ class IConfig {
*/ */
static public function Set(&$item, $family, $key, $value, $sharing = false) { public static function Set(&$item, $family, $key, $value, $sharing = false) {
$dbvalue = ((is_array($value)) ? serialise($value) : $value); $dbvalue = ((is_array($value)) ? serialise($value) : $value);
$dbvalue = ((is_bool($dbvalue)) ? intval($dbvalue) : $dbvalue); $dbvalue = ((is_bool($dbvalue)) ? intval($dbvalue) : $dbvalue);
@ -137,7 +137,7 @@ class IConfig {
static public function Delete(&$item, $family, $key) { public static function Delete(&$item, $family, $key) {
$is_item = false; $is_item = false;

View file

@ -4,12 +4,14 @@ namespace Zotlabs\Lib;
use Zotlabs\Lib\Hashpath; use Zotlabs\Lib\Hashpath;
use Zotlabs\Daemon\Run; use Zotlabs\Daemon\Run;
class Img_cache { class Img_cache
{
static $cache_life = 18600 * 7; static public $cache_life = 18600 * 7;
static function get_filename($url, $prefix = '.') { public static function get_filename($url, $prefix = '.')
return Hashpath::path($url,$prefix); {
return Hashpath::path($url, $prefix);
} }
// Check to see if we have this url in our cache // Check to see if we have this url in our cache
@ -17,36 +19,37 @@ class Img_cache {
// If we do not, or the cache file is empty or expired, return false // If we do not, or the cache file is empty or expired, return false
// but attempt to fetch the entry in the background // but attempt to fetch the entry in the background
static function check($url, $prefix = '.') { public static function check($url, $prefix = '.')
{
if (strpos($url,z_root()) !== false) { if (strpos($url, z_root()) !== false) {
return false; return false;
} }
$path = self::get_filename($url,$prefix); $path = self::get_filename($url, $prefix);
if (file_exists($path)) { if (file_exists($path)) {
$t = filemtime($path); $t = filemtime($path);
if ($t && time() - $t >= self::$cache_life) { if ($t && time() - $t >= self::$cache_life) {
Run::Summon( [ 'Cache_image', $url, $path ] ); Run::Summon(['Cache_image', $url, $path]);
return false; return false;
} } else {
else {
return ((filesize($path)) ? true : false); return ((filesize($path)) ? true : false);
} }
} }
// Cache_image invokes url_to_cache() as a background task // Cache_image invokes url_to_cache() as a background task
Run::Summon( [ 'Cache_image', $url, $path ] ); Run::Summon(['Cache_image', $url, $path]);
return false; return false;
} }
static function url_to_cache($url,$file) { public static function url_to_cache($url, $file)
{
$fp = fopen($file,'wb'); $fp = fopen($file, 'wb');
if (! $fp) { if (!$fp) {
logger('failed to open storage file: ' . $file,LOGGER_NORMAL,LOG_ERR); logger('failed to open storage file: ' . $file, LOGGER_NORMAL, LOG_ERR);
return false; return false;
} }
@ -56,14 +59,14 @@ class Img_cache {
// but don't want to rack up too many processes doing so. // but don't want to rack up too many processes doing so.
$redirects = 0; $redirects = 0;
$x = z_fetch_url($url,true,$redirects,[ 'filep' => $fp, 'novalidate' => true, 'timeout' => 120 ]); $x = z_fetch_url($url, true, $redirects, ['filep' => $fp, 'novalidate' => true, 'timeout' => 120]);
fclose($fp); fclose($fp);
if ($x['success'] && file_exists($file)) { if ($x['success'] && file_exists($file)) {
$i = @getimagesize($file); $i = @getimagesize($file);
if ($i && $i[2]) { // looking for non-zero imagetype if ($i && $i[2]) { // looking for non-zero imagetype
Run::Summon( [ 'CacheThumb' , basename($file) ] ); Run::Summon(['CacheThumb', basename($file)]);
return true; return true;
} }
} }

View file

@ -2,21 +2,24 @@
namespace Zotlabs\Lib; namespace Zotlabs\Lib;
class Img_filesize { class Img_filesize
{
private $url; private $url;
function __construct($url) { public function __construct($url)
{
$this->url = $url; $this->url = $url;
} }
function getSize() { public function getSize()
{
$size = null; $size = null;
if(stripos($this->url,z_root() . '/photo') !== false) { if (stripos($this->url, z_root() . '/photo') !== false) {
$size = self::getLocalFileSize($this->url); $size = self::getLocalFileSize($this->url);
} }
if(! $size) { if (!$size) {
$size = getRemoteFileSize($this->url); $size = getRemoteFileSize($this->url);
} }
@ -24,24 +27,25 @@ class Img_filesize {
} }
static function getLocalFileSize($url) { public static function getLocalFileSize($url)
{
$fname = basename($url); $fname = basename($url);
$resolution = 0; $resolution = 0;
if(strpos($fname,'.') !== false) if (strpos($fname, '.') !== false)
$fname = substr($fname,0,strpos($fname,'.')); $fname = substr($fname, 0, strpos($fname, '.'));
if(substr($fname,-2,1) == '-') { if (substr($fname, -2, 1) == '-') {
$resolution = intval(substr($fname,-1,1)); $resolution = intval(substr($fname, -1, 1));
$fname = substr($fname,0,-2); $fname = substr($fname, 0, -2);
} }
$r = q("SELECT filesize FROM photo WHERE resource_id = '%s' AND imgscale = %d LIMIT 1", $r = q("SELECT filesize FROM photo WHERE resource_id = '%s' AND imgscale = %d LIMIT 1",
dbesc($fname), dbesc($fname),
intval($resolution) intval($resolution)
); );
if($r) { if ($r) {
return $r[0]['filesize']; return $r[0]['filesize'];
} }
return null; return null;

View file

@ -4,19 +4,21 @@ namespace Zotlabs\Lib;
use Zotlabs\Web\HTTPSig; use Zotlabs\Web\HTTPSig;
class JSalmon { class JSalmon
{
static function sign($data,$key_id,$key,$data_type = 'application/x-zot+json') { public static function sign($data, $key_id, $key, $data_type = 'application/x-zot+json')
{
$data = base64url_encode(json_encode($data,true),true); // strip padding $data = base64url_encode(json_encode($data, true), true); // strip padding
$encoding = 'base64url'; $encoding = 'base64url';
$algorithm = 'RSA-SHA256'; $algorithm = 'RSA-SHA256';
$data = preg_replace('/\s+/','',$data); $data = preg_replace('/\s+/', '', $data);
// precomputed base64url encoding of data_type, encoding, algorithm concatenated with periods // precomputed base64url encoding of data_type, encoding, algorithm concatenated with periods
$precomputed = '.' . base64url_encode($data_type,true) . '.YmFzZTY0dXJs.UlNBLVNIQTI1Ng'; $precomputed = '.' . base64url_encode($data_type, true) . '.YmFzZTY0dXJs.UlNBLVNIQTI1Ng';
$signature = base64url_encode(Crypto::sign($data . $precomputed, $key), true); $signature = base64url_encode(Crypto::sign($data . $precomputed, $key), true);
@ -34,29 +36,30 @@ class JSalmon {
} }
static function verify($x) { public static function verify($x)
{
logger('verify'); logger('verify');
$ret = [ 'results' => [] ]; $ret = ['results' => []];
if(! is_array($x)) { if (!is_array($x)) {
return false; return false;
} }
if(! ( array_key_exists('signed',$x) && $x['signed'])) { if (!(array_key_exists('signed', $x) && $x['signed'])) {
return false; return false;
} }
$signed_data = preg_replace('/\s+/','',$x['data']) . '.' $signed_data = preg_replace('/\s+/', '', $x['data']) . '.'
. base64url_encode($x['data_type'],true) . '.' . base64url_encode($x['data_type'], true) . '.'
. base64url_encode($x['encoding'],true) . '.' . base64url_encode($x['encoding'], true) . '.'
. base64url_encode($x['alg'],true); . base64url_encode($x['alg'], true);
$key = HTTPSig::get_key(EMPTY_STR,'zot6',base64url_decode($x['sigs']['key_id'])); $key = HTTPSig::get_key(EMPTY_STR, 'zot6', base64url_decode($x['sigs']['key_id']));
logger('key: ' . print_r($key,true)); logger('key: ' . print_r($key, true));
if($key['portable_id'] && $key['public_key']) { if ($key['portable_id'] && $key['public_key']) {
if(Crypto::verify($signed_data,base64url_decode($x['sigs']['value']),$key['public_key'])) { if (Crypto::verify($signed_data, base64url_decode($x['sigs']['value']), $key['public_key'])) {
logger('verified'); logger('verified');
$ret = [ 'success' => true, 'signer' => $key['portable_id'], 'hubloc' => $key['hubloc'] ]; $ret = ['success' => true, 'signer' => $key['portable_id'], 'hubloc' => $key['hubloc']];
} }
} }
@ -64,8 +67,9 @@ class JSalmon {
} }
static function unpack($data) { public static function unpack($data)
return json_decode(base64url_decode($data),true); {
return json_decode(base64url_decode($data), true);
} }

View file

@ -7,114 +7,122 @@ use Zotlabs\Lib\Activity;
require_once('library/jsonld/jsonld.php'); require_once('library/jsonld/jsonld.php');
class LDSignatures { class LDSignatures
{
static function verify($data,$pubkey) { public static function verify($data, $pubkey)
{
$ohash = self::hash(self::signable_options($data['signature'])); $ohash = self::hash(self::signable_options($data['signature']));
$dhash = self::hash(self::signable_data($data)); $dhash = self::hash(self::signable_data($data));
$x = Crypto::verify($ohash . $dhash,base64_decode($data['signature']['signatureValue']), $pubkey); $x = Crypto::verify($ohash . $dhash, base64_decode($data['signature']['signatureValue']), $pubkey);
logger('LD-verify: ' . intval($x)); logger('LD-verify: ' . intval($x));
return $x; return $x;
} }
static function dopplesign(&$data,$channel) { public static function dopplesign(&$data, $channel)
{
// remove for the time being - performance issues // remove for the time being - performance issues
// $data['magicEnv'] = self::salmon_sign($data,$channel); // $data['magicEnv'] = self::salmon_sign($data,$channel);
return self::sign($data,$channel); return self::sign($data, $channel);
} }
static function sign($data,$channel) { public static function sign($data, $channel)
{
$options = [ $options = [
'type' => 'RsaSignature2017', 'type' => 'RsaSignature2017',
'nonce' => random_string(64), 'nonce' => random_string(64),
'creator' => channel_url($channel), 'creator' => channel_url($channel),
'created' => datetime_convert('UTC','UTC', 'now', 'Y-m-d\TH:i:s\Z') 'created' => datetime_convert('UTC', 'UTC', 'now', 'Y-m-d\TH:i:s\Z')
]; ];
$ohash = self::hash(self::signable_options($options)); $ohash = self::hash(self::signable_options($options));
$dhash = self::hash(self::signable_data($data)); $dhash = self::hash(self::signable_data($data));
$options['signatureValue'] = base64_encode(Crypto::sign($ohash . $dhash,$channel['channel_prvkey'])); $options['signatureValue'] = base64_encode(Crypto::sign($ohash . $dhash, $channel['channel_prvkey']));
return $options; return $options;
} }
static function signable_data($data) { public static function signable_data($data)
{
$newdata = []; $newdata = [];
if($data) { if ($data) {
foreach($data as $k => $v) { foreach ($data as $k => $v) {
if(! in_array($k,[ 'signature' ])) { if (!in_array($k, ['signature'])) {
$newdata[$k] = $v; $newdata[$k] = $v;
} }
} }
} }
return json_encode($newdata,JSON_UNESCAPED_SLASHES); return json_encode($newdata, JSON_UNESCAPED_SLASHES);
} }
static function signable_options($options) { public static function signable_options($options)
{
$newopts = [ '@context' => 'https://w3id.org/identity/v1' ]; $newopts = ['@context' => 'https://w3id.org/identity/v1'];
if($options) { if ($options) {
foreach($options as $k => $v) { foreach ($options as $k => $v) {
if(! in_array($k,[ 'type','id','signatureValue' ])) { if (!in_array($k, ['type', 'id', 'signatureValue'])) {
$newopts[$k] = $v; $newopts[$k] = $v;
} }
} }
} }
return json_encode($newopts,JSON_UNESCAPED_SLASHES); return json_encode($newopts, JSON_UNESCAPED_SLASHES);
} }
static function hash($obj) { public static function hash($obj)
{
return hash('sha256',self::normalise($obj)); return hash('sha256', self::normalise($obj));
} }
static function normalise($data) { public static function normalise($data)
if(is_string($data)) { {
if (is_string($data)) {
$data = json_decode($data); $data = json_decode($data);
} }
if(! is_object($data)) if (!is_object($data))
return ''; return '';
jsonld_set_document_loader('jsonld_document_loader'); jsonld_set_document_loader('jsonld_document_loader');
try { try {
$d = jsonld_normalize($data,[ 'algorithm' => 'URDNA2015', 'format' => 'application/nquads' ]); $d = jsonld_normalize($data, ['algorithm' => 'URDNA2015', 'format' => 'application/nquads']);
} } catch (Exception $e) {
catch (Exception $e) {
// Don't log the exception - this can exhaust memory // Don't log the exception - this can exhaust memory
// logger('normalise error:' . print_r($e,true)); // logger('normalise error:' . print_r($e,true));
logger('normalise error: ' . print_r($data,true)); logger('normalise error: ' . print_r($data, true));
} }
return $d; return $d;
} }
static function salmon_sign($data,$channel) { public static function salmon_sign($data, $channel)
{
$arr = $data; $arr = $data;
$data = json_encode($data,JSON_UNESCAPED_SLASHES); $data = json_encode($data, JSON_UNESCAPED_SLASHES);
$data = base64url_encode($data, false); // do not strip padding $data = base64url_encode($data, false); // do not strip padding
$data_type = 'application/activity+json'; $data_type = 'application/activity+json';
$encoding = 'base64url'; $encoding = 'base64url';
$algorithm = 'RSA-SHA256'; $algorithm = 'RSA-SHA256';
$keyhash = base64url_encode(channel_url($channel)); $keyhash = base64url_encode(channel_url($channel));
$data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$data); $data = str_replace(array(" ", "\t", "\r", "\n"), array("", "", "", ""), $data);
// precomputed base64url encoding of data_type, encoding, algorithm concatenated with periods // precomputed base64url encoding of data_type, encoding, algorithm concatenated with periods
$precomputed = '.' . base64url_encode($data_type,false) . '.YmFzZTY0dXJs.UlNBLVNIQTI1Ng=='; $precomputed = '.' . base64url_encode($data_type, false) . '.YmFzZTY0dXJs.UlNBLVNIQTI1Ng==';
$signature = base64url_encode(Crypto::sign($data . $precomputed,$channel['channel_prvkey'])); $signature = base64url_encode(Crypto::sign($data . $precomputed, $channel['channel_prvkey']));
return ([ return ([
'id' => $arr['id'], 'id' => $arr['id'],
@ -129,5 +137,4 @@ class LDSignatures {
} }
} }

View file

@ -3,25 +3,27 @@
namespace Zotlabs\Lib; namespace Zotlabs\Lib;
class LibBlock { class LibBlock
{
static $cache = []; static public $cache = [];
static $empty = []; static public $empty = [];
// This limits the number of DB queries for fetch_by_entity to once per page load. // This limits the number of DB queries for fetch_by_entity to once per page load.
static function fetch_from_cache($channel_id,$entity) { public static function fetch_from_cache($channel_id, $entity)
if (! isset(self::$cache[$channel_id])) { {
if (! isset(self::$empty[$channel_id])) { if (!isset(self::$cache[$channel_id])) {
if (!isset(self::$empty[$channel_id])) {
self::$cache[$channel_id] = self::fetch($channel_id); self::$cache[$channel_id] = self::fetch($channel_id);
if (! self::$cache[$channel_id]) { if (!self::$cache[$channel_id]) {
self::$empty[$channel_id] = true; self::$empty[$channel_id] = true;
} }
} }
} }
if (isset(self::$cache[$channel_id]) && self::$cache[$channel_id] && is_array(self::$cache[$channel_id])) { if (isset(self::$cache[$channel_id]) && self::$cache[$channel_id] && is_array(self::$cache[$channel_id])) {
foreach (self::$cache[$channel_id] as $entry) { foreach (self::$cache[$channel_id] as $entry) {
if (is_array($entry) && strcasecmp($entry['block_entity'],$entity) === 0) { if (is_array($entry) && strcasecmp($entry['block_entity'], $entity) === 0) {
return $entry; return $entry;
} }
} }
@ -30,19 +32,20 @@ class LibBlock {
} }
static function store($arr) { public static function store($arr)
{
$arr['block_entity'] = trim($arr['block_entity']); $arr['block_entity'] = trim($arr['block_entity']);
if (! $arr['block_entity']) { if (!$arr['block_entity']) {
return false; return false;
} }
$arr['block_channel_id'] = ((array_key_exists('block_channel_id',$arr)) ? intval($arr['block_channel_id']) : 0); $arr['block_channel_id'] = ((array_key_exists('block_channel_id', $arr)) ? intval($arr['block_channel_id']) : 0);
$arr['block_type'] = ((array_key_exists('block_type',$arr)) ? intval($arr['block_type']) : BLOCKTYPE_CHANNEL ); $arr['block_type'] = ((array_key_exists('block_type', $arr)) ? intval($arr['block_type']) : BLOCKTYPE_CHANNEL);
$arr['block_comment'] = ((array_key_exists('block_comment',$arr)) ? escape_tags(trim($arr['block_comment'])) : EMPTY_STR); $arr['block_comment'] = ((array_key_exists('block_comment', $arr)) ? escape_tags(trim($arr['block_comment'])) : EMPTY_STR);
if (! intval($arr['block_id'])) { if (!intval($arr['block_id'])) {
$r = q("select * from block where block_channel_id = %d and block_entity = '%s' and block_type = %d limit 1", $r = q("select * from block where block_channel_id = %d and block_entity = '%s' and block_type = %d limit 1",
intval($arr['block_channel_id']), intval($arr['block_channel_id']),
dbesc($arr['block_entity']), dbesc($arr['block_entity']),
@ -61,21 +64,22 @@ class LibBlock {
dbesc($arr['block_comment']), dbesc($arr['block_comment']),
intval($arr['block_id']) intval($arr['block_id'])
); );
} } else {
else { return create_table_from_array('block', $arr);
return create_table_from_array('block',$arr);
} }
} }
static function remove($channel_id,$entity) { public static function remove($channel_id, $entity)
{
return q("delete from block where block_channel_id = %d and block_entity = '%s'", return q("delete from block where block_channel_id = %d and block_entity = '%s'",
intval($channel_id), intval($channel_id),
dbesc($entity) dbesc($entity)
); );
} }
static function fetch_by_id($channel_id,$id) { public static function fetch_by_id($channel_id, $id)
if (! intval($channel_id)) { {
if (!intval($channel_id)) {
return false; return false;
} }
$r = q("select * from block where block_channel_id = %d and block_id = %d ", $r = q("select * from block where block_channel_id = %d and block_id = %d ",
@ -85,17 +89,19 @@ class LibBlock {
} }
static function fetch_by_entity($channel_id,$entity) { public static function fetch_by_entity($channel_id, $entity)
if (! intval($channel_id)) { {
if (!intval($channel_id)) {
return false; return false;
} }
return self::fetch_from_cache($channel_id,$entity); return self::fetch_from_cache($channel_id, $entity);
} }
static function fetch($channel_id,$type = false) { public static function fetch($channel_id, $type = false)
if (! intval($channel_id)) { {
if (!intval($channel_id)) {
return []; return [];
} }

View file

@ -4,8 +4,8 @@ namespace Zotlabs\Lib;
use App; use App;
class Libprofile { class Libprofile
{
/** /**
@ -24,15 +24,16 @@ class Libprofile {
* @param string $profile_guid * @param string $profile_guid
*/ */
static function load($nickname, $profile = '') { public static function load($nickname, $profile = '')
{
// logger('Libprofile::load: ' . $nickname . (($profile) ? ' profile: ' . $profile : '')); // logger('Libprofile::load: ' . $nickname . (($profile) ? ' profile: ' . $profile : ''));
$channel = channelx_by_nick($nickname); $channel = channelx_by_nick($nickname);
if (! $channel) { if (!$channel) {
logger('profile error: ' . App::$query_string, LOGGER_DEBUG); logger('profile error: ' . App::$query_string, LOGGER_DEBUG);
notice( t('Requested channel is not available.') . EOL ); notice(t('Requested channel is not available.') . EOL);
App::$error = 404; App::$error = 404;
return; return;
} }
@ -44,11 +45,11 @@ class Libprofile {
// Can the observer see our profile? // Can the observer see our profile?
require_once('include/permissions.php'); require_once('include/permissions.php');
if (! perm_is_allowed($channel['channel_id'],(($observer) ? $observer['xchan_hash'] : ''),'view_profile')) { if (!perm_is_allowed($channel['channel_id'], (($observer) ? $observer['xchan_hash'] : ''), 'view_profile')) {
$can_view_profile = false; $can_view_profile = false;
} }
if (! $profile) { if (!$profile) {
$r = q("SELECT abook_profile FROM abook WHERE abook_xchan = '%s' and abook_channel = '%d' limit 1", $r = q("SELECT abook_profile FROM abook WHERE abook_xchan = '%s' and abook_channel = '%d' limit 1",
dbesc(($observer) ? $observer['xchan_hash'] : ''), dbesc(($observer) ? $observer['xchan_hash'] : ''),
intval($channel['channel_id']) intval($channel['channel_id'])
@ -66,7 +67,7 @@ class Libprofile {
dbesc($nickname), dbesc($nickname),
dbesc($profile) dbesc($profile)
); );
if (! $p) { if (!$p) {
$p = q("SELECT profile.uid AS profile_uid, profile.*, channel.* FROM profile $p = q("SELECT profile.uid AS profile_uid, profile.*, channel.* FROM profile
LEFT JOIN channel ON profile.uid = channel.channel_id LEFT JOIN channel ON profile.uid = channel.channel_id
WHERE channel.channel_address = '%s' AND profile.id = %d LIMIT 1", WHERE channel.channel_address = '%s' AND profile.id = %d LIMIT 1",
@ -76,7 +77,7 @@ class Libprofile {
} }
} }
if (! $p) { if (!$p) {
$p = q("SELECT profile.uid AS profile_uid, profile.*, channel.* FROM profile $p = q("SELECT profile.uid AS profile_uid, profile.*, channel.* FROM profile
LEFT JOIN channel ON profile.uid = channel.channel_id LEFT JOIN channel ON profile.uid = channel.channel_id
WHERE channel.channel_address = '%s' and channel_removed = 0 WHERE channel.channel_address = '%s' and channel_removed = 0
@ -85,9 +86,9 @@ class Libprofile {
); );
} }
if (! $p) { if (!$p) {
logger('profile error: ' . App::$query_string, LOGGER_DEBUG); logger('profile error: ' . App::$query_string, LOGGER_DEBUG);
notice( t('Requested profile is not available.') . EOL ); notice(t('Requested profile is not available.') . EOL);
App::$error = 404; App::$error = 404;
return; return;
} }
@ -103,7 +104,7 @@ class Libprofile {
$profile_fields_basic = get_profile_fields_basic(); $profile_fields_basic = get_profile_fields_basic();
$profile_fields_advanced = get_profile_fields_advanced(); $profile_fields_advanced = get_profile_fields_advanced();
$advanced = ((feature_enabled(local_channel(),'advanced_profiles')) ? true : false); $advanced = ((feature_enabled(local_channel(), 'advanced_profiles')) ? true : false);
if ($advanced) if ($advanced)
$fields = $profile_fields_advanced; $fields = $profile_fields_advanced;
else else
@ -127,12 +128,12 @@ class Libprofile {
); );
if ($z) { if ($z) {
$p[0]['picdate'] = $z[0]['xchan_photo_date']; $p[0]['picdate'] = $z[0]['xchan_photo_date'];
$p[0]['reddress'] = str_replace('@','&#x40;',unpunify($z[0]['xchan_addr'])); $p[0]['reddress'] = str_replace('@', '&#x40;', unpunify($z[0]['xchan_addr']));
} }
// fetch user tags if this isn't the default profile // fetch user tags if this isn't the default profile
if (! $p[0]['is_default']) { if (!$p[0]['is_default']) {
$x = q("select keywords from profile where uid = %d and is_default = 1 limit 1", $x = q("select keywords from profile where uid = %d and is_default = 1 limit 1",
intval($p[0]['profile_uid']) intval($p[0]['profile_uid'])
); );
@ -141,12 +142,12 @@ class Libprofile {
} }
if ($p[0]['keywords']) { if ($p[0]['keywords']) {
$keywords = str_replace(array('#',',',' ',',,'),array('',' ',',',','),$p[0]['keywords']); $keywords = str_replace(array('#', ',', ' ', ',,'), array('', ' ', ',', ','), $p[0]['keywords']);
if (strlen($keywords) && $can_view_profile) { if (strlen($keywords) && $can_view_profile) {
if (! isset(App::$page['htmlhead'])) { if (!isset(App::$page['htmlhead'])) {
App::$page['htmlhead'] = EMPTY_STR; App::$page['htmlhead'] = EMPTY_STR;
} }
App::$page['htmlhead'] .= '<meta name="keywords" content="' . htmlentities($keywords,ENT_COMPAT,'UTF-8') . '" />' . "\r\n" ; App::$page['htmlhead'] .= '<meta name="keywords" content="' . htmlentities($keywords, ENT_COMPAT, 'UTF-8') . '" />' . "\r\n";
} }
} }
@ -162,7 +163,7 @@ class Libprofile {
} }
if (local_channel()) { if (local_channel()) {
App::$profile['channel_mobile_theme'] = get_pconfig(local_channel(),'system', 'mobile_theme'); App::$profile['channel_mobile_theme'] = get_pconfig(local_channel(), 'system', 'mobile_theme');
$_SESSION['mobile_theme'] = App::$profile['channel_mobile_theme']; $_SESSION['mobile_theme'] = App::$profile['channel_mobile_theme'];
} }
@ -174,7 +175,8 @@ class Libprofile {
} }
static function edit_menu($uid) { public static function edit_menu($uid)
{
$ret = []; $ret = [];
@ -190,20 +192,19 @@ class Libprofile {
$multi_profiles = feature_enabled(local_channel(), 'multi_profiles'); $multi_profiles = feature_enabled(local_channel(), 'multi_profiles');
if ($multi_profiles) { if ($multi_profiles) {
$ret['multi'] = 1; $ret['multi'] = 1;
$ret['edit'] = [ z_root(). '/profiles', t('Edit Profiles'), '', t('Edit') ]; $ret['edit'] = [z_root() . '/profiles', t('Edit Profiles'), '', t('Edit')];
$ret['menu']['cr_new'] = t('Create New Profile'); $ret['menu']['cr_new'] = t('Create New Profile');
} } else {
else { $ret['edit'] = [z_root() . '/profiles/' . $uid, t('Edit Profile'), '', t('Edit')];
$ret['edit'] = [ z_root() . '/profiles/' . $uid, t('Edit Profile'), '', t('Edit') ];
} }
$r = q("SELECT * FROM profile WHERE uid = %d", $r = q("SELECT * FROM profile WHERE uid = %d",
local_channel() local_channel()
); );
if($r) { if ($r) {
foreach($r as $rr) { foreach ($r as $rr) {
if(!($multi_profiles || $rr['is_default'])) if (!($multi_profiles || $rr['is_default']))
continue; continue;
$ret['menu']['entries'][] = [ $ret['menu']['entries'][] = [
@ -230,14 +231,15 @@ class Libprofile {
* *
* @param array $profile * @param array $profile
* @param int $block * @param int $block
* @param boolean $show_connect (optional) default true * @param bool $show_connect (optional) default true
* @param mixed $zcard (optional) default false * @param mixed $zcard (optional) default false
* *
* @return HTML string suitable for sidebar inclusion * @return HTML string suitable for sidebar inclusion
* Exceptions: Returns empty string if passed $profile is wrong type or not populated * Exceptions: Returns empty string if passed $profile is wrong type or not populated
*/ */
static function widget($profile, $block = 0, $show_connect = true, $zcard = false) { public static function widget($profile, $block = 0, $show_connect = true, $zcard = false)
{
$observer = App::get_observer(); $observer = App::get_observer();
@ -246,16 +248,16 @@ class Libprofile {
$pdesc = true; $pdesc = true;
$reddress = true; $reddress = true;
if(! perm_is_allowed($profile['uid'],((is_array($observer)) ? $observer['xchan_hash'] : ''),'view_profile')) { if (!perm_is_allowed($profile['uid'], ((is_array($observer)) ? $observer['xchan_hash'] : ''), 'view_profile')) {
$block = true; $block = true;
} }
if((! is_array($profile)) && (! count($profile))) if ((!is_array($profile)) && (!count($profile)))
return $o; return $o;
head_set_icon($profile['thumb']); head_set_icon($profile['thumb']);
if(is_sys_channel($profile['uid'])) if (is_sys_channel($profile['uid']))
$show_connect = false; $show_connect = false;
$profile['picdate'] = urlencode($profile['picdate']); $profile['picdate'] = urlencode($profile['picdate']);
@ -266,34 +268,34 @@ class Libprofile {
*/ */
call_hooks('profile_sidebar_enter', $profile); call_hooks('profile_sidebar_enter', $profile);
if($show_connect) { if ($show_connect) {
// This will return an empty string if we're already connected. // This will return an empty string if we're already connected.
$connect_url = rconnect_url($profile['uid'],get_observer_hash()); $connect_url = rconnect_url($profile['uid'], get_observer_hash());
$connect = (($connect_url) ? t('Connect') : ''); $connect = (($connect_url) ? t('Connect') : '');
if($connect_url) if ($connect_url)
$connect_url = sprintf($connect_url,urlencode(channel_reddress($profile))); $connect_url = sprintf($connect_url, urlencode(channel_reddress($profile)));
// premium channel - over-ride // premium channel - over-ride
if($profile['channel_pageflags'] & PAGE_PREMIUM) if ($profile['channel_pageflags'] & PAGE_PREMIUM)
$connect_url = z_root() . '/connect/' . $profile['channel_address']; $connect_url = z_root() . '/connect/' . $profile['channel_address'];
} }
if((x($profile,'address') == 1) if ((x($profile, 'address') == 1)
|| (x($profile,'locality') == 1) || (x($profile, 'locality') == 1)
|| (x($profile,'region') == 1) || (x($profile, 'region') == 1)
|| (x($profile,'postal_code') == 1) || (x($profile, 'postal_code') == 1)
|| (x($profile,'country_name') == 1)) || (x($profile, 'country_name') == 1))
$location = t('Location:'); $location = t('Location:');
$profile['homepage'] = linkify($profile['homepage'],true); $profile['homepage'] = linkify($profile['homepage'], true);
$gender = ((x($profile,'gender') == 1) ? t('Gender:') : False); $gender = ((x($profile, 'gender') == 1) ? t('Gender:') : False);
$marital = ((x($profile,'marital') == 1) ? t('Status:') : False); $marital = ((x($profile, 'marital') == 1) ? t('Status:') : False);
$homepage = ((x($profile,'homepage') == 1) ? t('Homepage:') : False); $homepage = ((x($profile, 'homepage') == 1) ? t('Homepage:') : False);
$pronouns = ((x($profile,'pronouns') == 1) ? t('Pronouns:') : False); $pronouns = ((x($profile, 'pronouns') == 1) ? t('Pronouns:') : False);
// zap/osada do not have a realtime chat system at this time so don't show online state // zap/osada do not have a realtime chat system at this time so don't show online state
// $profile['online'] = (($profile['online_status'] === 'online') ? t('Online Now') : False); // $profile['online'] = (($profile['online_status'] === 'online') ? t('Online Now') : False);
@ -301,40 +303,40 @@ class Libprofile {
$profile['online'] = false; $profile['online'] = false;
if(($profile['hidewall'] && (! local_channel()) && (! remote_channel())) || $block ) { if (($profile['hidewall'] && (!local_channel()) && (!remote_channel())) || $block) {
$location = $reddress = $pdesc = $gender = $marital = $homepage = False; $location = $reddress = $pdesc = $gender = $marital = $homepage = False;
} }
if($profile['gender']) { if ($profile['gender']) {
$profile['gender_icon'] = self::gender_icon($profile['gender']); $profile['gender_icon'] = self::gender_icon($profile['gender']);
} }
if($profile['pronouns']) { if ($profile['pronouns']) {
$profile['pronouns_icon'] = self::pronouns_icon($profile['pronouns']); $profile['pronouns_icon'] = self::pronouns_icon($profile['pronouns']);
} }
$firstname = ((strpos($profile['channel_name'],' ')) $firstname = ((strpos($profile['channel_name'], ' '))
? trim(substr($profile['channel_name'],0,strpos($profile['channel_name'],' '))) : $profile['channel_name']); ? trim(substr($profile['channel_name'], 0, strpos($profile['channel_name'], ' '))) : $profile['channel_name']);
$lastname = (($firstname === $profile['channel_name']) ? '' : trim(substr($profile['channel_name'],strlen($firstname)))); $lastname = (($firstname === $profile['channel_name']) ? '' : trim(substr($profile['channel_name'], strlen($firstname))));
$contact_block = contact_block(); $contact_block = contact_block();
$channel_menu = false; $channel_menu = false;
$menu = get_pconfig($profile['uid'],'system','channel_menu'); $menu = get_pconfig($profile['uid'], 'system', 'channel_menu');
if($menu && ! $block) { if ($menu && !$block) {
require_once('include/menu.php'); require_once('include/menu.php');
$m = menu_fetch($menu,$profile['uid'],$observer['xchan_hash']); $m = menu_fetch($menu, $profile['uid'], $observer['xchan_hash']);
if($m) if ($m)
$channel_menu = menu_render($m); $channel_menu = menu_render($m);
} }
$menublock = get_pconfig($profile['uid'],'system','channel_menublock'); $menublock = get_pconfig($profile['uid'], 'system', 'channel_menublock');
if ($menublock && (! $block)) { if ($menublock && (!$block)) {
$comanche = new Comanche(); $comanche = new Comanche();
$channel_menu .= $comanche->block($menublock); $channel_menu .= $comanche->block($menublock);
} }
if($zcard) if ($zcard)
$tpl = get_markup_template('profile_vcard_short.tpl'); $tpl = get_markup_template('profile_vcard_short.tpl');
else else
$tpl = get_markup_template('profile_vcard.tpl'); $tpl = get_markup_template('profile_vcard.tpl');
@ -378,65 +380,68 @@ class Libprofile {
return $arr['entry']; return $arr['entry'];
} }
static function gender_icon($gender) { public static function gender_icon($gender)
{
// logger('gender: ' . $gender); // logger('gender: ' . $gender);
// This can easily get throw off if the observer language is different // This can easily get throw off if the observer language is different
// than the channel owner language. // than the channel owner language.
if(strpos(strtolower($gender),strtolower(t('Female'))) !== false) if (strpos(strtolower($gender), strtolower(t('Female'))) !== false)
return 'venus'; return 'venus';
if(strpos(strtolower($gender),strtolower(t('Male'))) !== false) if (strpos(strtolower($gender), strtolower(t('Male'))) !== false)
return 'mars'; return 'mars';
if(strpos(strtolower($gender),strtolower(t('Trans'))) !== false) if (strpos(strtolower($gender), strtolower(t('Trans'))) !== false)
return 'transgender'; return 'transgender';
if(strpos(strtolower($gender),strtolower(t('Inter'))) !== false) if (strpos(strtolower($gender), strtolower(t('Inter'))) !== false)
return 'transgender'; return 'transgender';
if(strpos(strtolower($gender),strtolower(t('Neuter'))) !== false) if (strpos(strtolower($gender), strtolower(t('Neuter'))) !== false)
return 'neuter'; return 'neuter';
if(strpos(strtolower($gender),strtolower(t('Non-specific'))) !== false) if (strpos(strtolower($gender), strtolower(t('Non-specific'))) !== false)
return 'genderless'; return 'genderless';
return ''; return '';
} }
static function pronouns_icon($pronouns) { public static function pronouns_icon($pronouns)
{
// This can easily get throw off if the observer language is different // This can easily get throw off if the observer language is different
// than the channel owner language. // than the channel owner language.
if(strpos(strtolower($pronouns),strtolower(t('She'))) !== false) if (strpos(strtolower($pronouns), strtolower(t('She'))) !== false)
return 'venus'; return 'venus';
if(strpos(strtolower($pronouns),strtolower(t('Him'))) !== false) if (strpos(strtolower($pronouns), strtolower(t('Him'))) !== false)
return 'mars'; return 'mars';
if(strpos(strtolower($pronouns),strtolower(t('Them'))) !== false) if (strpos(strtolower($pronouns), strtolower(t('Them'))) !== false)
return 'users'; return 'users';
return ''; return '';
} }
static function advanced() { public static function advanced()
{
if(! perm_is_allowed(App::$profile['profile_uid'],get_observer_hash(),'view_profile')) if (!perm_is_allowed(App::$profile['profile_uid'], get_observer_hash(), 'view_profile'))
return ''; return '';
if(App::$profile['fullname']) { if (App::$profile['fullname']) {
$profile_fields_basic = get_profile_fields_basic(); $profile_fields_basic = get_profile_fields_basic();
$profile_fields_advanced = get_profile_fields_advanced(); $profile_fields_advanced = get_profile_fields_advanced();
$advanced = ((feature_enabled(App::$profile['profile_uid'],'advanced_profiles')) ? true : false); $advanced = ((feature_enabled(App::$profile['profile_uid'], 'advanced_profiles')) ? true : false);
if($advanced) if ($advanced)
$fields = $profile_fields_advanced; $fields = $profile_fields_advanced;
else else
$fields = $profile_fields_basic; $fields = $profile_fields_basic;
$clean_fields = []; $clean_fields = [];
if($fields) { if ($fields) {
foreach($fields as $k => $v) { foreach ($fields as $k => $v) {
$clean_fields[] = trim($k); $clean_fields[] = trim($k);
} }
} }
@ -446,9 +451,9 @@ class Libprofile {
$profile = []; $profile = [];
$profile['fullname'] = array( t('Full Name:'), App::$profile['fullname'] ) ; $profile['fullname'] = array(t('Full Name:'), App::$profile['fullname']);
if(App::$profile['gender']) $profile['gender'] = array( t('Gender:'), App::$profile['gender'] ); if (App::$profile['gender']) $profile['gender'] = array(t('Gender:'), App::$profile['gender']);
$ob_hash = get_observer_hash(); $ob_hash = get_observer_hash();
@ -474,100 +479,100 @@ class Libprofile {
// $profile['likers'][] = array('name' => $l['xchan_name'],'photo' => zid($l['xchan_photo_s']), 'url' => zid($l['xchan_url'])); // $profile['likers'][] = array('name' => $l['xchan_name'],'photo' => zid($l['xchan_photo_s']), 'url' => zid($l['xchan_url']));
// } // }
if((App::$profile['dob']) && (App::$profile['dob'] != '0000-00-00')) { if ((App::$profile['dob']) && (App::$profile['dob'] != '0000-00-00')) {
$val = ''; $val = '';
if((substr(App::$profile['dob'],5,2) === '00') || (substr(App::$profile['dob'],8,2) === '00')) if ((substr(App::$profile['dob'], 5, 2) === '00') || (substr(App::$profile['dob'], 8, 2) === '00'))
$val = substr(App::$profile['dob'],0,4); $val = substr(App::$profile['dob'], 0, 4);
$year_bd_format = t('j F, Y'); $year_bd_format = t('j F, Y');
$short_bd_format = t('j F'); $short_bd_format = t('j F');
if(! $val) { if (!$val) {
$val = ((intval(App::$profile['dob'])) $val = ((intval(App::$profile['dob']))
? day_translate(datetime_convert('UTC','UTC',App::$profile['dob'] . ' 00:00 +00:00',$year_bd_format)) ? day_translate(datetime_convert('UTC', 'UTC', App::$profile['dob'] . ' 00:00 +00:00', $year_bd_format))
: day_translate(datetime_convert('UTC','UTC','2001-' . substr(App::$profile['dob'],5) . ' 00:00 +00:00',$short_bd_format))); : day_translate(datetime_convert('UTC', 'UTC', '2001-' . substr(App::$profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)));
} }
$profile['birthday'] = array( t('Birthday:'), $val); $profile['birthday'] = array(t('Birthday:'), $val);
} }
if($age = age(App::$profile['dob'],App::$profile['timezone'],'')) if ($age = age(App::$profile['dob'], App::$profile['timezone'], ''))
$profile['age'] = array( t('Age:'), $age ); $profile['age'] = array(t('Age:'), $age);
if(App::$profile['marital']) if (App::$profile['marital'])
$profile['marital'] = array( t('Status:'), App::$profile['marital']); $profile['marital'] = array(t('Status:'), App::$profile['marital']);
if(App::$profile['partner']) if (App::$profile['partner'])
$profile['marital']['partner'] = zidify_links(bbcode(App::$profile['partner'])); $profile['marital']['partner'] = zidify_links(bbcode(App::$profile['partner']));
if(strlen(App::$profile['howlong']) && App::$profile['howlong'] > NULL_DATE) { if (strlen(App::$profile['howlong']) && App::$profile['howlong'] > NULL_DATE) {
$profile['howlong'] = relative_date(App::$profile['howlong'], t('for %1$d %2$s')); $profile['howlong'] = relative_date(App::$profile['howlong'], t('for %1$d %2$s'));
} }
if(App::$profile['keywords']) { if (App::$profile['keywords']) {
$keywords = str_replace(',',' ', App::$profile['keywords']); $keywords = str_replace(',', ' ', App::$profile['keywords']);
$keywords = str_replace(' ',' ', $keywords); $keywords = str_replace(' ', ' ', $keywords);
$karr = explode(' ', $keywords); $karr = explode(' ', $keywords);
if($karr) { if ($karr) {
for($cnt = 0; $cnt < count($karr); $cnt ++) { for ($cnt = 0; $cnt < count($karr); $cnt++) {
$karr[$cnt] = '<a href="' . z_root() . '/directory/f=&keywords=' . trim($karr[$cnt]) . '">' . $karr[$cnt] . '</a>'; $karr[$cnt] = '<a href="' . z_root() . '/directory/f=&keywords=' . trim($karr[$cnt]) . '">' . $karr[$cnt] . '</a>';
} }
} }
$profile['keywords'] = array( t('Tags:'), implode(' ', $karr)); $profile['keywords'] = array(t('Tags:'), implode(' ', $karr));
} }
if(App::$profile['sexual']) $profile['sexual'] = array( t('Sexual Preference:'), App::$profile['sexual'] ); if (App::$profile['sexual']) $profile['sexual'] = array(t('Sexual Preference:'), App::$profile['sexual']);
if(App::$profile['pronouns']) $profile['pronouns'] = array( t('Pronouns:'), App::$profile['pronouns'] ); if (App::$profile['pronouns']) $profile['pronouns'] = array(t('Pronouns:'), App::$profile['pronouns']);
if(App::$profile['homepage']) $profile['homepage'] = array( t('Homepage:'), linkify(App::$profile['homepage']) ); if (App::$profile['homepage']) $profile['homepage'] = array(t('Homepage:'), linkify(App::$profile['homepage']));
if(App::$profile['hometown']) $profile['hometown'] = array( t('Hometown:'), linkify(App::$profile['hometown']) ); if (App::$profile['hometown']) $profile['hometown'] = array(t('Hometown:'), linkify(App::$profile['hometown']));
if(App::$profile['politic']) $profile['politic'] = array( t('Political Views:'), App::$profile['politic']); if (App::$profile['politic']) $profile['politic'] = array(t('Political Views:'), App::$profile['politic']);
if(App::$profile['religion']) $profile['religion'] = array( t('Religion:'), App::$profile['religion']); if (App::$profile['religion']) $profile['religion'] = array(t('Religion:'), App::$profile['religion']);
if($txt = prepare_text(App::$profile['about'])) $profile['about'] = array( t('About:'), $txt ); if ($txt = prepare_text(App::$profile['about'])) $profile['about'] = array(t('About:'), $txt);
if($txt = prepare_text(App::$profile['interest'])) $profile['interest'] = array( t('Hobbies/Interests:'), $txt); if ($txt = prepare_text(App::$profile['interest'])) $profile['interest'] = array(t('Hobbies/Interests:'), $txt);
if($txt = prepare_text(App::$profile['likes'])) $profile['likes'] = array( t('Likes:'), $txt); if ($txt = prepare_text(App::$profile['likes'])) $profile['likes'] = array(t('Likes:'), $txt);
if($txt = prepare_text(App::$profile['dislikes'])) $profile['dislikes'] = array( t('Dislikes:'), $txt); if ($txt = prepare_text(App::$profile['dislikes'])) $profile['dislikes'] = array(t('Dislikes:'), $txt);
if($txt = prepare_text(App::$profile['contact'])) $profile['contact'] = array( t('Contact information and Social Networks:'), $txt); if ($txt = prepare_text(App::$profile['contact'])) $profile['contact'] = array(t('Contact information and Social Networks:'), $txt);
if($txt = prepare_text(App::$profile['channels'])) $profile['channels'] = array( t('My other channels:'), $txt); if ($txt = prepare_text(App::$profile['channels'])) $profile['channels'] = array(t('My other channels:'), $txt);
if($txt = prepare_text(App::$profile['music'])) $profile['music'] = array( t('Musical interests:'), $txt); if ($txt = prepare_text(App::$profile['music'])) $profile['music'] = array(t('Musical interests:'), $txt);
if($txt = prepare_text(App::$profile['book'])) $profile['book'] = array( t('Books, literature:'), $txt); if ($txt = prepare_text(App::$profile['book'])) $profile['book'] = array(t('Books, literature:'), $txt);
if($txt = prepare_text(App::$profile['tv'])) $profile['tv'] = array( t('Television:'), $txt); if ($txt = prepare_text(App::$profile['tv'])) $profile['tv'] = array(t('Television:'), $txt);
if($txt = prepare_text(App::$profile['film'])) $profile['film'] = array( t('Film/dance/culture/entertainment:'), $txt); if ($txt = prepare_text(App::$profile['film'])) $profile['film'] = array(t('Film/dance/culture/entertainment:'), $txt);
if($txt = prepare_text(App::$profile['romance'])) $profile['romance'] = array( t('Love/Romance:'), $txt); if ($txt = prepare_text(App::$profile['romance'])) $profile['romance'] = array(t('Love/Romance:'), $txt);
if($txt = prepare_text(App::$profile['employment'])) $profile['employment'] = array( t('Work/employment:'), $txt); if ($txt = prepare_text(App::$profile['employment'])) $profile['employment'] = array(t('Work/employment:'), $txt);
if($txt = prepare_text(App::$profile['education'])) $profile['education'] = array( t('School/education:'), $txt ); if ($txt = prepare_text(App::$profile['education'])) $profile['education'] = array(t('School/education:'), $txt);
if(App::$profile['extra_fields']) { if (App::$profile['extra_fields']) {
foreach(App::$profile['extra_fields'] as $f) { foreach (App::$profile['extra_fields'] as $f) {
$x = q("select * from profdef where field_name = '%s' limit 1", $x = q("select * from profdef where field_name = '%s' limit 1",
dbesc($f) dbesc($f)
); );
if($x && $txt = prepare_text(App::$profile[$f])) if ($x && $txt = prepare_text(App::$profile[$f]))
$profile[$f] = array( $x[0]['field_desc'] . ':',$txt); $profile[$f] = array($x[0]['field_desc'] . ':', $txt);
} }
$profile['extra_fields'] = App::$profile['extra_fields']; $profile['extra_fields'] = App::$profile['extra_fields'];
} }
$things = get_things(App::$profile['profile_guid'],App::$profile['profile_uid']); $things = get_things(App::$profile['profile_guid'], App::$profile['profile_uid']);
// logger('mod_profile: things: ' . print_r($things,true), LOGGER_DATA); // logger('mod_profile: things: ' . print_r($things,true), LOGGER_DATA);
@ -576,7 +581,7 @@ class Libprofile {
return replace_macros($tpl, array( return replace_macros($tpl, array(
'$title' => t('Profile'), '$title' => t('Profile'),
'$canlike' => (($profile['canlike'])? true : false), '$canlike' => (($profile['canlike']) ? true : false),
'$likethis' => t('Like this thing'), '$likethis' => t('Like this thing'),
'$export' => t('Export'), '$export' => t('Export'),
'$exportlink' => '', // $exportlink, '$exportlink' => '', // $exportlink,
@ -591,21 +596,4 @@ class Libprofile {
} }
} }

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -10,7 +10,8 @@ use Zotlabs\Lib\Zotfinger;
require_once('include/permissions.php'); require_once('include/permissions.php');
class Libzotdir { class Libzotdir
{
/** /**
@ -19,7 +20,8 @@ class Libzotdir {
* is if our directory has gone offline for any reason * is if our directory has gone offline for any reason
*/ */
static function check_upstream_directory() { public static function check_upstream_directory()
{
$directory = get_config('system', 'directory_server'); $directory = get_config('system', 'directory_server');
@ -30,34 +32,35 @@ class Libzotdir {
if ($directory) { if ($directory) {
$j = Zotfinger::exec($directory); $j = Zotfinger::exec($directory);
if (array_path_exists('data/directory_mode',$j)) { if (array_path_exists('data/directory_mode', $j)) {
if ($j['data']['directory_mode'] === 'normal') { if ($j['data']['directory_mode'] === 'normal') {
$isadir = false; $isadir = false;
} }
} }
} }
if (! $isadir) if (!$isadir)
set_config('system', 'directory_server', ''); set_config('system', 'directory_server', '');
} }
static function get_directory_setting($observer, $setting) { public static function get_directory_setting($observer, $setting)
{
if ($observer) if ($observer)
$ret = get_xconfig($observer, 'directory', $setting); $ret = get_xconfig($observer, 'directory', $setting);
else else
$ret = ((array_key_exists($setting,$_SESSION)) ? intval($_SESSION[$setting]) : false); $ret = ((array_key_exists($setting, $_SESSION)) ? intval($_SESSION[$setting]) : false);
if($ret === false) { if ($ret === false) {
$ret = get_config('directory', $setting); $ret = get_config('directory', $setting);
if($ret === false) { if ($ret === false) {
$ret = (in_array($setting,[ 'globaldir','safemode', 'activedir' ]) ? 1 : 0); $ret = (in_array($setting, ['globaldir', 'safemode', 'activedir']) ? 1 : 0);
} }
} }
if($setting === 'globaldir' && intval(get_config('system','localdir_hide'))) if ($setting === 'globaldir' && intval(get_config('system', 'localdir_hide')))
$ret = 1; $ret = 1;
return $ret; return $ret;
@ -66,7 +69,8 @@ class Libzotdir {
/** /**
* @brief Called by the directory_sort widget. * @brief Called by the directory_sort widget.
*/ */
static function dir_sort_links() { public static function dir_sort_links()
{
$safe_mode = 1; $safe_mode = 1;
@ -77,7 +81,7 @@ class Libzotdir {
$pubforums = self::get_directory_setting($observer, 'chantype'); $pubforums = self::get_directory_setting($observer, 'chantype');
$activedir = self::get_directory_setting($observer, 'activedir'); $activedir = self::get_directory_setting($observer, 'activedir');
$hide_local = intval(get_config('system','localdir_hide')); $hide_local = intval(get_config('system', 'localdir_hide'));
if ($hide_local) { if ($hide_local) {
$globaldir = 1; $globaldir = 1;
} }
@ -85,8 +89,8 @@ class Libzotdir {
// Build urls without order and pubforums so it's easy to tack on the changed value // Build urls without order and pubforums so it's easy to tack on the changed value
// Probably there's an easier way to do this // Probably there's an easier way to do this
$directory_sort_order = get_config('system','directory_sort_order'); $directory_sort_order = get_config('system', 'directory_sort_order');
if (! $directory_sort_order) { if (!$directory_sort_order) {
$directory_sort_order = 'date'; $directory_sort_order = 'date';
} }
@ -95,7 +99,7 @@ class Libzotdir {
$url = 'directory?f='; $url = 'directory?f=';
$tmp = array_merge($_GET,$_POST); $tmp = array_merge($_GET, $_POST);
unset($tmp['suggest']); unset($tmp['suggest']);
unset($tmp['pubforums']); unset($tmp['pubforums']);
unset($tmp['type']); unset($tmp['type']);
@ -110,12 +114,12 @@ class Libzotdir {
$o = replace_macros(get_markup_template('dir_sort_links.tpl'), [ $o = replace_macros(get_markup_template('dir_sort_links.tpl'), [
'$header' => t('Directory Options'), '$header' => t('Directory Options'),
'$forumsurl' => $forumsurl, '$forumsurl' => $forumsurl,
'$safemode' => array('safemode', t('Safe Mode'),$safe_mode,'',array(t('No'), t('Yes')),' onchange=\'window.location.href="' . $forumsurl . '&safe="+(this.checked ? 1 : 0)\''), '$safemode' => array('safemode', t('Safe Mode'), $safe_mode, '', array(t('No'), t('Yes')), ' onchange=\'window.location.href="' . $forumsurl . '&safe="+(this.checked ? 1 : 0)\''),
'$pubforums' => array('pubforums', t('Groups Only'),(($pubforums == 1) ? true : false),'',array(t('No'), t('Yes')),' onchange=\'window.location.href="' . $forumsurl . '&type="+(this.checked ? 1 : 0)\''), '$pubforums' => array('pubforums', t('Groups Only'), (($pubforums == 1) ? true : false), '', array(t('No'), t('Yes')), ' onchange=\'window.location.href="' . $forumsurl . '&type="+(this.checked ? 1 : 0)\''),
// '$collections' => array('collections', t('Collections Only'),(($pubforums == 2) ? true : false),'',array(t('No'), t('Yes')),' onchange=\'window.location.href="' . $forumsurl . '&type="+(this.checked ? 2 : 0)\''), // '$collections' => array('collections', t('Collections Only'),(($pubforums == 2) ? true : false),'',array(t('No'), t('Yes')),' onchange=\'window.location.href="' . $forumsurl . '&type="+(this.checked ? 2 : 0)\''),
'$hide_local' => $hide_local, '$hide_local' => $hide_local,
'$globaldir' => array('globaldir', t('This Website Only'), 1-intval($globaldir),'',array(t('No'), t('Yes')),' onchange=\'window.location.href="' . $forumsurl . '&global="+(this.checked ? 0 : 1)\''), '$globaldir' => array('globaldir', t('This Website Only'), 1 - intval($globaldir), '', array(t('No'), t('Yes')), ' onchange=\'window.location.href="' . $forumsurl . '&global="+(this.checked ? 0 : 1)\''),
'$activedir' => array('activedir', t('Recently Updated'), intval($activedir),'',array(t('No'), t('Yes')),' onchange=\'window.location.href="' . $forumsurl . '&active="+(this.checked ? 1 : 0)\''), '$activedir' => array('activedir', t('Recently Updated'), intval($activedir), '', array(t('No'), t('Yes')), ' onchange=\'window.location.href="' . $forumsurl . '&active="+(this.checked ? 1 : 0)\''),
]); ]);
return $o; return $o;
@ -134,21 +138,21 @@ class Libzotdir {
* @param array $ud Entry from update table * @param array $ud Entry from update table
*/ */
static function update_directory_entry($ud) { public static function update_directory_entry($ud)
{
logger('update_directory_entry: ' . print_r($ud,true), LOGGER_DATA); logger('update_directory_entry: ' . print_r($ud, true), LOGGER_DATA);
if ($ud['ud_addr'] && (! ($ud['ud_flags'] & UPDATE_FLAGS_DELETED))) { if ($ud['ud_addr'] && (!($ud['ud_flags'] & UPDATE_FLAGS_DELETED))) {
$success = false; $success = false;
$href = Webfinger::zot_url(punify($ud['ud_addr'])); $href = Webfinger::zot_url(punify($ud['ud_addr']));
if($href) { if ($href) {
$zf = Zotfinger::exec($href); $zf = Zotfinger::exec($href);
} }
if(is_array($zf) && array_path_exists('signature/signer',$zf) && $zf['signature']['signer'] === $href && intval($zf['signature']['header_valid'])) { if (is_array($zf) && array_path_exists('signature/signer', $zf) && $zf['signature']['signer'] === $href && intval($zf['signature']['header_valid'])) {
$xc = Libzot::import_xchan($zf['data'], 0, $ud); $xc = Libzot::import_xchan($zf['data'], 0, $ud);
} } else {
else {
q("update updates set ud_last = '%s' where ud_addr = '%s'", q("update updates set ud_last = '%s' where ud_addr = '%s'",
dbesc(datetime_convert()), dbesc(datetime_convert()),
dbesc($ud['ud_addr']) dbesc($ud['ud_addr'])
@ -165,10 +169,11 @@ class Libzotdir {
* directory and the local hub in this case is any kind of directory server. * directory and the local hub in this case is any kind of directory server.
* *
* @param int $uid * @param int $uid
* @param boolean $force * @param bool $force
*/ */
static function local_dir_update($uid, $force) { public static function local_dir_update($uid, $force)
{
logger('local_dir_update: uid: ' . $uid, LOGGER_DEBUG); logger('local_dir_update: uid: ' . $uid, LOGGER_DEBUG);
@ -185,7 +190,7 @@ class Libzotdir {
$profile['description'] = $p[0]['pdesc']; $profile['description'] = $p[0]['pdesc'];
$profile['birthday'] = $p[0]['dob']; $profile['birthday'] = $p[0]['dob'];
if ($age = age($p[0]['dob'],$p[0]['channel_timezone'],'')) if ($age = age($p[0]['dob'], $p[0]['channel_timezone'], ''))
$profile['age'] = $age; $profile['age'] = $age;
$profile['gender'] = $p[0]['gender']; $profile['gender'] = $p[0]['gender'];
@ -219,22 +224,21 @@ class Libzotdir {
dbesc($p[0]['channel_hash']) dbesc($p[0]['channel_hash'])
); );
if(intval($r[0]['xchan_hidden']) != $hidden) { if (intval($r[0]['xchan_hidden']) != $hidden) {
$r = q("update xchan set xchan_hidden = %d where xchan_hash = '%s'", $r = q("update xchan set xchan_hidden = %d where xchan_hash = '%s'",
intval($hidden), intval($hidden),
dbesc($p[0]['channel_hash']) dbesc($p[0]['channel_hash'])
); );
} }
$arr = [ 'channel_id' => $uid, 'hash' => $hash, 'profile' => $profile ]; $arr = ['channel_id' => $uid, 'hash' => $hash, 'profile' => $profile];
call_hooks('local_dir_update', $arr); call_hooks('local_dir_update', $arr);
$address = channel_reddress($p[0]); $address = channel_reddress($p[0]);
if (perm_is_allowed($uid, '', 'view_profile')) { if (perm_is_allowed($uid, '', 'view_profile')) {
self::import_directory_profile($hash, $arr['profile'], $address, 0); self::import_directory_profile($hash, $arr['profile'], $address, 0);
} } else {
else {
// they may have made it private // they may have made it private
$r = q("delete from xprof where xprof_hash = '%s'", $r = q("delete from xprof where xprof_hash = '%s'",
dbesc($hash) dbesc($hash)
@ -247,11 +251,10 @@ class Libzotdir {
} }
$ud_hash = random_string() . '@' . App::get_hostname(); $ud_hash = random_string() . '@' . App::get_hostname();
self::update_modtime($hash, $ud_hash, channel_reddress($p[0]),(($force) ? UPDATE_FLAGS_FORCED : UPDATE_FLAGS_UPDATED)); self::update_modtime($hash, $ud_hash, channel_reddress($p[0]), (($force) ? UPDATE_FLAGS_FORCED : UPDATE_FLAGS_UPDATED));
} }
/** /**
* @brief Imports a directory profile. * @brief Imports a directory profile.
* *
@ -260,57 +263,58 @@ class Libzotdir {
* @param string $addr * @param string $addr
* @param number $ud_flags (optional) UPDATE_FLAGS_UPDATED * @param number $ud_flags (optional) UPDATE_FLAGS_UPDATED
* @param number $suppress_update (optional) default 0 * @param number $suppress_update (optional) default 0
* @return boolean $updated if something changed * @return bool $updated if something changed
*/ */
static function import_directory_profile($hash, $profile, $addr, $ud_flags = UPDATE_FLAGS_UPDATED, $suppress_update = 0) { public static function import_directory_profile($hash, $profile, $addr, $ud_flags = UPDATE_FLAGS_UPDATED, $suppress_update = 0)
{
logger('import_directory_profile', LOGGER_DEBUG); logger('import_directory_profile', LOGGER_DEBUG);
if (! $hash) if (!$hash)
return false; return false;
$maxlen = get_max_import_size(); $maxlen = get_max_import_size();
if($maxlen && mb_strlen($profile['about']) > $maxlen) { if ($maxlen && mb_strlen($profile['about']) > $maxlen) {
$profile['about'] = mb_substr($profile['about'],0,$maxlen,'UTF-8'); $profile['about'] = mb_substr($profile['about'], 0, $maxlen, 'UTF-8');
} }
$arr = []; $arr = [];
$arr['xprof_hash'] = $hash; $arr['xprof_hash'] = $hash;
$arr['xprof_dob'] = ((isset($profile['birthday']) && $profile['birthday'] === '0000-00-00') ? $profile['birthday'] : datetime_convert('','',$profile['birthday'],'Y-m-d')); // !!!! check this for 0000 year $arr['xprof_dob'] = ((isset($profile['birthday']) && $profile['birthday'] === '0000-00-00') ? $profile['birthday'] : datetime_convert('', '', $profile['birthday'], 'Y-m-d')); // !!!! check this for 0000 year
$arr['xprof_age'] = (isset($profile['age']) ? intval($profile['age']) : 0); $arr['xprof_age'] = (isset($profile['age']) ? intval($profile['age']) : 0);
$arr['xprof_desc'] = ((isset($profile['description']) && $profile['description']) ? htmlspecialchars($profile['description'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_desc'] = ((isset($profile['description']) && $profile['description']) ? htmlspecialchars($profile['description'], ENT_COMPAT, 'UTF-8', false) : '');
$arr['xprof_gender'] = ((isset($profile['gender']) && $profile['gender']) ? htmlspecialchars($profile['gender'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_gender'] = ((isset($profile['gender']) && $profile['gender']) ? htmlspecialchars($profile['gender'], ENT_COMPAT, 'UTF-8', false) : '');
$arr['xprof_marital'] = ((isset($profile['marital']) && $profile['marital']) ? htmlspecialchars($profile['marital'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_marital'] = ((isset($profile['marital']) && $profile['marital']) ? htmlspecialchars($profile['marital'], ENT_COMPAT, 'UTF-8', false) : '');
$arr['xprof_sexual'] = ((isset($profile['sexual']) && $profile['sexual']) ? htmlspecialchars($profile['sexual'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_sexual'] = ((isset($profile['sexual']) && $profile['sexual']) ? htmlspecialchars($profile['sexual'], ENT_COMPAT, 'UTF-8', false) : '');
$arr['xprof_locale'] = ((isset($profile['locale']) && $profile['locale']) ? htmlspecialchars($profile['locale'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_locale'] = ((isset($profile['locale']) && $profile['locale']) ? htmlspecialchars($profile['locale'], ENT_COMPAT, 'UTF-8', false) : '');
$arr['xprof_region'] = ((isset($profile['region']) && $profile['region']) ? htmlspecialchars($profile['region'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_region'] = ((isset($profile['region']) && $profile['region']) ? htmlspecialchars($profile['region'], ENT_COMPAT, 'UTF-8', false) : '');
$arr['xprof_postcode'] = ((isset($profile['postcode']) && $profile['postcode']) ? htmlspecialchars($profile['postcode'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_postcode'] = ((isset($profile['postcode']) && $profile['postcode']) ? htmlspecialchars($profile['postcode'], ENT_COMPAT, 'UTF-8', false) : '');
$arr['xprof_country'] = ((isset($profile['country']) && $profile['country']) ? htmlspecialchars($profile['country'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_country'] = ((isset($profile['country']) && $profile['country']) ? htmlspecialchars($profile['country'], ENT_COMPAT, 'UTF-8', false) : '');
$arr['xprof_about'] = ((isset($profile['about']) && $profile['about']) ? htmlspecialchars($profile['about'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_about'] = ((isset($profile['about']) && $profile['about']) ? htmlspecialchars($profile['about'], ENT_COMPAT, 'UTF-8', false) : '');
$arr['xprof_pronouns'] = ((isset($profile['pronouns']) && $profile['pronouns']) ? htmlspecialchars($profile['pronouns'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_pronouns'] = ((isset($profile['pronouns']) && $profile['pronouns']) ? htmlspecialchars($profile['pronouns'], ENT_COMPAT, 'UTF-8', false) : '');
$arr['xprof_homepage'] = ((isset($profile['homepage']) && $profile['homepage']) ? htmlspecialchars($profile['homepage'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_homepage'] = ((isset($profile['homepage']) && $profile['homepage']) ? htmlspecialchars($profile['homepage'], ENT_COMPAT, 'UTF-8', false) : '');
$arr['xprof_hometown'] = ((isset($profile['hometown']) && $profile['hometown']) ? htmlspecialchars($profile['hometown'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_hometown'] = ((isset($profile['hometown']) && $profile['hometown']) ? htmlspecialchars($profile['hometown'], ENT_COMPAT, 'UTF-8', false) : '');
$clean = []; $clean = [];
if (array_key_exists('keywords', $profile) and is_array($profile['keywords'])) { if (array_key_exists('keywords', $profile) and is_array($profile['keywords'])) {
self::import_directory_keywords($hash,$profile['keywords']); self::import_directory_keywords($hash, $profile['keywords']);
foreach ($profile['keywords'] as $kw) { foreach ($profile['keywords'] as $kw) {
$kw = trim(htmlspecialchars($kw,ENT_COMPAT, 'UTF-8', false)); $kw = trim(htmlspecialchars($kw, ENT_COMPAT, 'UTF-8', false));
$kw = trim($kw, ','); $kw = trim($kw, ',');
$clean[] = $kw; $clean[] = $kw;
} }
} }
$arr['xprof_keywords'] = implode(' ',$clean); $arr['xprof_keywords'] = implode(' ', $clean);
// Self censored, make it so // Self censored, make it so
// These are not translated, so the German "erwachsenen" keyword will not censor the directory profile. Only the English form - "adult". // These are not translated, so the German "erwachsenen" keyword will not censor the directory profile. Only the English form - "adult".
if(in_arrayi('nsfw',$clean) || in_arrayi('adult',$clean)) { if (in_arrayi('nsfw', $clean) || in_arrayi('adult', $clean)) {
q("update xchan set xchan_selfcensored = 1 where xchan_hash = '%s'", q("update xchan set xchan_selfcensored = 1 where xchan_hash = '%s'",
dbesc($hash) dbesc($hash)
); );
@ -328,7 +332,7 @@ class Libzotdir {
if ($r) { if ($r) {
$update = false; $update = false;
foreach ($r[0] as $k => $v) { foreach ($r[0] as $k => $v) {
if ((array_key_exists($k,$arr)) && ($arr[$k] != $v)) { if ((array_key_exists($k, $arr)) && ($arr[$k] != $v)) {
logger('import_directory_profile: update ' . $k . ' => ' . $arr[$k]); logger('import_directory_profile: update ' . $k . ' => ' . $arr[$k]);
$update = true; $update = true;
break; break;
@ -409,7 +413,7 @@ class Libzotdir {
call_hooks('import_directory_profile', $d); call_hooks('import_directory_profile', $d);
if (($d['update']) && (! $suppress_update)) { if (($d['update']) && (!$suppress_update)) {
self::update_modtime($arr['xprof_hash'], new_uuid(), $addr, $ud_flags); self::update_modtime($arr['xprof_hash'], new_uuid(), $addr, $ud_flags);
} }
@ -428,34 +432,35 @@ class Libzotdir {
* @param array $keywords * @param array $keywords
*/ */
static function import_directory_keywords($hash, $keywords) { public static function import_directory_keywords($hash, $keywords)
{
$existing = []; $existing = [];
$r = q("select * from xtag where xtag_hash = '%s' and xtag_flags = 0", $r = q("select * from xtag where xtag_hash = '%s' and xtag_flags = 0",
dbesc($hash) dbesc($hash)
); );
if($r) { if ($r) {
foreach($r as $rr) foreach ($r as $rr)
$existing[] = $rr['xtag_term']; $existing[] = $rr['xtag_term'];
} }
$clean = []; $clean = [];
foreach($keywords as $kw) { foreach ($keywords as $kw) {
$kw = trim(htmlspecialchars($kw,ENT_COMPAT, 'UTF-8', false)); $kw = trim(htmlspecialchars($kw, ENT_COMPAT, 'UTF-8', false));
$kw = trim($kw, ','); $kw = trim($kw, ',');
$clean[] = $kw; $clean[] = $kw;
} }
foreach($existing as $x) { foreach ($existing as $x) {
if(! in_array($x, $clean)) if (!in_array($x, $clean))
$r = q("delete from xtag where xtag_hash = '%s' and xtag_term = '%s' and xtag_flags = 0", $r = q("delete from xtag where xtag_hash = '%s' and xtag_term = '%s' and xtag_flags = 0",
dbesc($hash), dbesc($hash),
dbesc($x) dbesc($x)
); );
} }
foreach($clean as $x) { foreach ($clean as $x) {
if(! in_array($x, $existing)) { if (!in_array($x, $existing)) {
$r = q("insert into xtag ( xtag_hash, xtag_term, xtag_flags) values ( '%s' ,'%s', 0 )", $r = q("insert into xtag ( xtag_hash, xtag_term, xtag_flags) values ( '%s' ,'%s', 0 )",
dbesc($hash), dbesc($hash),
dbesc($x) dbesc($x)
@ -474,14 +479,15 @@ class Libzotdir {
* @param int $flags (optional) default 0 * @param int $flags (optional) default 0
*/ */
static function update_modtime($hash, $guid, $addr, $flags = 0) { public static function update_modtime($hash, $guid, $addr, $flags = 0)
{
$dirmode = intval(get_config('system', 'directory_mode')); $dirmode = intval(get_config('system', 'directory_mode'));
if($dirmode == DIRECTORY_MODE_NORMAL) if ($dirmode == DIRECTORY_MODE_NORMAL)
return; return;
if($flags) { if ($flags) {
q("insert into updates (ud_hash, ud_guid, ud_date, ud_flags, ud_addr ) values ( '%s', '%s', '%s', %d, '%s' )", q("insert into updates (ud_hash, ud_guid, ud_date, ud_flags, ud_addr ) values ( '%s', '%s', '%s', %d, '%s' )",
dbesc($hash), dbesc($hash),
dbesc($guid), dbesc($guid),
@ -489,8 +495,7 @@ class Libzotdir {
intval($flags), intval($flags),
dbesc($addr) dbesc($addr)
); );
} } else {
else {
q("update updates set ud_flags = ( ud_flags | %d ) where ud_addr = '%s' and (ud_flags & %d) = 0 ", q("update updates set ud_flags = ( ud_flags | %d ) where ud_addr = '%s' and (ud_flags & %d) = 0 ",
intval(UPDATE_FLAGS_UPDATED), intval(UPDATE_FLAGS_UPDATED),
dbesc($addr), dbesc($addr),
@ -500,8 +505,4 @@ class Libzotdir {
} }
} }

View file

@ -18,7 +18,8 @@ require_once("include/html2bbcode.php");
require_once("include/bbcode.php"); require_once("include/bbcode.php");
class Markdown { class Markdown
{
/** /**
* @brief Convert Markdown to bbcode. * @brief Convert Markdown to bbcode.
@ -29,25 +30,26 @@ class Markdown {
* and then clean up a few Diaspora specific constructs. * and then clean up a few Diaspora specific constructs.
* *
* @param string $s The message as Markdown * @param string $s The message as Markdown
* @param boolean $use_zrl default false * @param bool $use_zrl default false
* @param array $options default empty * @param array $options default empty
* @return string The message converted to bbcode * @return string The message converted to bbcode
*/ */
static public function to_bbcode($s, $use_zrl = false, $options = []) { public static function to_bbcode($s, $use_zrl = false, $options = [])
{
if(is_array($s)) { if (is_array($s)) {
btlogger('markdown_to_bb called with array. ' . print_r($s, true), LOGGER_NORMAL, LOG_WARNING); btlogger('markdown_to_bb called with array. ' . print_r($s, true), LOGGER_NORMAL, LOG_WARNING);
return ''; return '';
} }
$s = str_replace("&#xD;","\r",$s); $s = str_replace("&#xD;", "\r", $s);
$s = str_replace("&#xD;\n&gt;","",$s); $s = str_replace("&#xD;\n&gt;", "", $s);
$s = html_entity_decode($s,ENT_COMPAT,'UTF-8'); $s = html_entity_decode($s, ENT_COMPAT, 'UTF-8');
// if empty link text replace with the url // if empty link text replace with the url
$s = preg_replace("/\[\]\((.*?)\)/ism",'[$1]($1)',$s); $s = preg_replace("/\[\]\((.*?)\)/ism", '[$1]($1)', $s);
$x = [ $x = [
'text' => $s, 'text' => $s,
@ -66,35 +68,33 @@ class Markdown {
$s = $x['text']; $s = $x['text'];
// Escaping the hash tags // Escaping the hash tags
$s = preg_replace('/\#([^\s\#])/','&#35;$1',$s); $s = preg_replace('/\#([^\s\#])/', '&#35;$1', $s);
$s = MarkdownExtra::defaultTransform($s); $s = MarkdownExtra::defaultTransform($s);
if($options && $options['preserve_lf']) { if ($options && $options['preserve_lf']) {
$s = str_replace(["\r","\n"],["",'<br>'],$s); $s = str_replace(["\r", "\n"], ["", '<br>'], $s);
} } else {
else { $s = str_replace("\r", "", $s);
$s = str_replace("\r","",$s);
} }
$s = str_replace('&#35;','#',$s); $s = str_replace('&#35;', '#', $s);
$s = html2bbcode($s); $s = html2bbcode($s);
// Convert everything that looks like a link to a link // Convert everything that looks like a link to a link
if($use_zrl) { if ($use_zrl) {
if (strpos($s,'[/img]') !== false) { if (strpos($s, '[/img]') !== false) {
$s = preg_replace_callback("/\[img\](.*?)\[\/img\]/ism", [ '\\Zotlabs\\Lib\\Markdown', 'use_zrl_cb_img'], $s); $s = preg_replace_callback("/\[img\](.*?)\[\/img\]/ism", ['\\Zotlabs\\Lib\\Markdown', 'use_zrl_cb_img'], $s);
$s = preg_replace_callback("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", [ '\\Zotlabs\\Lib\\Markdown', 'use_zrl_cb_img_x' ], $s); $s = preg_replace_callback("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", ['\\Zotlabs\\Lib\\Markdown', 'use_zrl_cb_img_x'], $s);
} }
$s = preg_replace_callback("/([^\]\=\{\/]|^)(https?\:\/\/)([a-zA-Z0-9\pL\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,\@\(\)]+)/ismu", [ '\\Zotlabs\\Lib\\Markdown', 'use_zrl_cb_link'] ,$s); $s = preg_replace_callback("/([^\]\=\{\/]|^)(https?\:\/\/)([a-zA-Z0-9\pL\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,\@\(\)]+)/ismu", ['\\Zotlabs\\Lib\\Markdown', 'use_zrl_cb_link'], $s);
} } else {
else { $s = preg_replace("/([^\]\=\{\/]|^)(https?\:\/\/)([a-zA-Z0-9\pL\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,\@\(\)]+)/ismu", '$1[url=$2$3]$2$3[/url]', $s);
$s = preg_replace("/([^\]\=\{\/]|^)(https?\:\/\/)([a-zA-Z0-9\pL\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,\@\(\)]+)/ismu", '$1[url=$2$3]$2$3[/url]',$s);
} }
// remove duplicate adjacent code tags // remove duplicate adjacent code tags
$s = preg_replace("/(\[code\])+(.*?)(\[\/code\])+/ism","[code]$2[/code]", $s); $s = preg_replace("/(\[code\])+(.*?)(\[\/code\])+/ism", "[code]$2[/code]", $s);
/** /**
* @hooks markdown_to_bb * @hooks markdown_to_bb
@ -105,11 +105,12 @@ class Markdown {
return $s; return $s;
} }
static function use_zrl_cb_link($match) { public static function use_zrl_cb_link($match)
{
$res = ''; $res = '';
$is_zid = is_matrix_url(trim($match[0])); $is_zid = is_matrix_url(trim($match[0]));
if($is_zid) if ($is_zid)
$res = $match[1] . '[zrl=' . $match[2] . $match[3] . ']' . $match[2] . $match[3] . '[/zrl]'; $res = $match[1] . '[zrl=' . $match[2] . $match[3] . ']' . $match[2] . $match[3] . '[/zrl]';
else else
$res = $match[1] . '[url=' . $match[2] . $match[3] . ']' . $match[2] . $match[3] . '[/url]'; $res = $match[1] . '[url=' . $match[2] . $match[3] . ']' . $match[2] . $match[3] . '[/url]';
@ -117,11 +118,12 @@ class Markdown {
return $res; return $res;
} }
static function use_zrl_cb_img($match) { public static function use_zrl_cb_img($match)
{
$res = ''; $res = '';
$is_zid = is_matrix_url(trim($match[1])); $is_zid = is_matrix_url(trim($match[1]));
if($is_zid) if ($is_zid)
$res = '[zmg]' . $match[1] . '[/zmg]'; $res = '[zmg]' . $match[1] . '[/zmg]';
else else
$res = $match[0]; $res = $match[0];
@ -129,11 +131,12 @@ class Markdown {
return $res; return $res;
} }
static function use_zrl_cb_img_x($match) { public static function use_zrl_cb_img_x($match)
{
$res = ''; $res = '';
$is_zid = is_matrix_url(trim($match[3])); $is_zid = is_matrix_url(trim($match[3]));
if($is_zid) if ($is_zid)
$res = '[zmg=' . $match[1] . 'x' . $match[2] . ']' . $match[3] . '[/zmg]'; $res = '[zmg=' . $match[1] . 'x' . $match[2] . ']' . $match[3] . '[/zmg]';
else else
$res = $match[0]; $res = $match[0];
@ -148,7 +151,8 @@ class Markdown {
* @return string * @return string
*/ */
static public function from_bbcode_share($match) { public static function from_bbcode_share($match)
{
$matches = []; $matches = [];
$attributes = $match[1]; $attributes = $match[1];
@ -184,7 +188,7 @@ class Markdown {
if ($matches[1] != "") if ($matches[1] != "")
$message_id = $matches[1]; $message_id = $matches[1];
if(! $message_id) { if (!$message_id) {
preg_match("/guid='(.*?)'/ism", $attributes, $matches); preg_match("/guid='(.*?)'/ism", $attributes, $matches);
if ($matches[1] != "") if ($matches[1] != "")
$message_id = $matches[1]; $message_id = $matches[1];
@ -200,7 +204,7 @@ class Markdown {
// Bob Smith wrote the following post 2 hours ago // Bob Smith wrote the following post 2 hours ago
$fmt = sprintf( t('%1$s wrote the following %2$s %3$s'), $fmt = sprintf(t('%1$s wrote the following %2$s %3$s'),
'[url=' . zid($profile) . ']' . $author . '[/url]', '[url=' . zid($profile) . ']' . $author . '[/url]',
'[url=' . zid($link) . ']' . t('post') . '[/url]', '[url=' . zid($link) . ']' . t('post') . '[/url]',
$reldate $reldate
@ -222,7 +226,8 @@ class Markdown {
* @return string The message converted to Markdown * @return string The message converted to Markdown
*/ */
static public function from_bbcode($Text, $options = []) { public static function from_bbcode($Text, $options = [])
{
/* /*
* Transform #tags, strip off the [url] and replace spaces with underscore * Transform #tags, strip off the [url] and replace spaces with underscore
@ -236,9 +241,9 @@ class Markdown {
// Converting images with size parameters to simple images. Markdown doesn't know it. // Converting images with size parameters to simple images. Markdown doesn't know it.
$Text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $Text); $Text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $Text);
$Text = preg_replace_callback("/\[share(.*?)\](.*?)\[\/share\]/ism", [ '\\Zotlabs\\Lib\\Markdown', 'from_bbcode_share'], $Text); $Text = preg_replace_callback("/\[share(.*?)\](.*?)\[\/share\]/ism", ['\\Zotlabs\\Lib\\Markdown', 'from_bbcode_share'], $Text);
$x = [ 'bbcode' => $Text, 'options' => $options ]; $x = ['bbcode' => $Text, 'options' => $options];
/** /**
* @hooks bb_to_markdown_bb * @hooks bb_to_markdown_bb
@ -250,7 +255,7 @@ class Markdown {
$Text = $x['bbcode']; $Text = $x['bbcode'];
// Convert it to HTML - don't try oembed // Convert it to HTML - don't try oembed
$Text = bbcode($Text, [ 'tryoembed' => false ]); $Text = bbcode($Text, ['tryoembed' => false]);
// Now convert HTML to Markdown // Now convert HTML to Markdown
@ -292,10 +297,11 @@ class Markdown {
* @return string Markdown representation of the given HTML text, empty on error * @return string Markdown representation of the given HTML text, empty on error
*/ */
static public function from_html($html,$options = []) { public static function from_html($html, $options = [])
{
$markdown = ''; $markdown = '';
if(! $options) { if (!$options) {
$options = [ $options = [
'header_style' => 'setext', // Set to 'atx' to output H1 and H2 headers as # Header1 and ## Header2 'header_style' => 'setext', // Set to 'atx' to output H1 and H2 headers as # Header1 and ## Header2
'suppress_errors' => true, // Set to false to show warnings when loading malformed HTML 'suppress_errors' => true, // Set to false to show warnings when loading malformed HTML

View file

@ -22,7 +22,8 @@ namespace Zotlabs\Lib;
* $html = \Michelf\MarkdownExtra::DefaultTransform($markdown); * $html = \Michelf\MarkdownExtra::DefaultTransform($markdown);
* @endcode * @endcode
*/ */
class MarkdownSoap { class MarkdownSoap
{
/** /**
* @var string * @var string
@ -34,12 +35,14 @@ class MarkdownSoap {
private $token; private $token;
function __construct($s) { public function __construct($s)
{
$this->str = $s; $this->str = $s;
$this->token = random_string(20); $this->token = random_string(20);
} }
function clean() { public function clean()
{
$x = $this->extract_code($this->str); $x = $this->extract_code($this->str);
@ -55,68 +58,76 @@ class MarkdownSoap {
/** /**
* @brief Extracts code blocks and privately escapes them from processing. * @brief Extracts code blocks and privately escapes them from processing.
* *
* @param string $s
* @return string
* @see encode_code() * @see encode_code()
* @see putback_code() * @see putback_code()
* *
* @param string $s
* @return string
*/ */
function extract_code($s) { public function extract_code($s)
{
$text = preg_replace_callback('{ $text = preg_replace_callback('{
(?:\n\n|\A\n?) (?:\n\n|\A\n?)
( # $1 = the code block -- one or more lines, starting with a space/tab ( # $1 = the code block -- one or more lines, starting with a space/tab
(?> (?>
[ ]{'.'4'.'} # Lines must start with a tab or a tab-width of spaces [ ]{' . '4' . '} # Lines must start with a tab or a tab-width of spaces
.*\n+ .*\n+
)+ )+
) )
((?=^[ ]{0,'.'4'.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ((?=^[ ]{0,' . '4' . '}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
}xm', }xm',
[ $this , 'encode_code' ], $s); [$this, 'encode_code'], $s);
return $text; return $text;
} }
function encode_code($matches) { public function encode_code($matches)
return $this->token . ';' . base64_encode($matches[0]) . ';' ; {
return $this->token . ';' . base64_encode($matches[0]) . ';';
} }
function decode_code($matches) { public function decode_code($matches)
{
return base64_decode($matches[1]); return base64_decode($matches[1]);
} }
/** /**
* @brief Put back the code blocks. * @brief Put back the code blocks.
* *
* @param string $s
* @return string
* @see extract_code() * @see extract_code()
* @see decode_code() * @see decode_code()
* *
* @param string $s
* @return string
*/ */
function putback_code($s) { public function putback_code($s)
$text = preg_replace_callback('{' . $this->token . '\;(.*?)\;}xm', [ $this, 'decode_code' ], $s); {
$text = preg_replace_callback('{' . $this->token . '\;(.*?)\;}xm', [$this, 'decode_code'], $s);
return $text; return $text;
} }
function purify($s) { public function purify($s)
{
$s = $this->protect_autolinks($s); $s = $this->protect_autolinks($s);
$s = purify_html($s); $s = purify_html($s);
$s = $this->unprotect_autolinks($s); $s = $this->unprotect_autolinks($s);
return $s; return $s;
} }
function protect_autolinks($s) { public function protect_autolinks($s)
{
$s = preg_replace('/\<(https?\:\/\/)(.*?)\>/', '[$1$2]($1$2)', $s); $s = preg_replace('/\<(https?\:\/\/)(.*?)\>/', '[$1$2]($1$2)', $s);
return $s; return $s;
} }
function unprotect_autolinks($s) { public function unprotect_autolinks($s)
{
return $s; return $s;
} }
function escape($s) { public function escape($s)
{
return htmlspecialchars($s, ENT_QUOTES, 'UTF-8', false); return htmlspecialchars($s, ENT_QUOTES, 'UTF-8', false);
} }
@ -126,7 +137,8 @@ class MarkdownSoap {
* @param string $s * @param string $s
* @return string * @return string
*/ */
static public function unescape($s) { public static function unescape($s)
{
return htmlspecialchars_decode($s, ENT_QUOTES); return htmlspecialchars_decode($s, ENT_QUOTES);
} }
} }

View file

@ -6,9 +6,11 @@ use App;
use Zotlabs\Lib\PConfig; use Zotlabs\Lib\PConfig;
class MastAPI { class MastAPI
{
static function format_channel($channel) { public static function format_channel($channel)
{
$p = q("select * from profile where uid = %d and is_default = 1", $p = q("select * from profile where uid = %d and is_default = 1",
intval($channel['channel_id']) intval($channel['channel_id'])
); );
@ -29,7 +31,7 @@ class MastAPI {
dbesc($channel['channel_hash']) dbesc($channel['channel_hash'])
); );
$cover_photo = get_cover_photo($channel['channel_id'],'array'); $cover_photo = get_cover_photo($channel['channel_id'], 'array');
$item_normal = item_normal(); $item_normal = item_normal();
@ -42,14 +44,14 @@ class MastAPI {
); );
$ret = []; $ret = [];
$ret['id'] = (string) $channel['channel_id']; $ret['id'] = (string)$channel['channel_id'];
$ret['username'] = $channel['channel_address']; $ret['username'] = $channel['channel_address'];
$ret['acct'] = $channel['channel_address']; $ret['acct'] = $channel['channel_address'];
$ret['display_name'] = $channel['channel_name']; $ret['display_name'] = $channel['channel_name'];
$ret['locked'] = ((intval(PConfig::Get($channel['channel_id'],'system','autoperms'))) ? false : true ); $ret['locked'] = ((intval(PConfig::Get($channel['channel_id'], 'system', 'autoperms'))) ? false : true);
$ret['discoverable'] = ((1 - intval($channel['xchan_hidden'])) ? true : false); $ret['discoverable'] = ((1 - intval($channel['xchan_hidden'])) ? true : false);
$ret['created_at'] = datetime_convert('UTC','UTC', $a[0]['account_created'], ATOM_TIME); $ret['created_at'] = datetime_convert('UTC', 'UTC', $a[0]['account_created'], ATOM_TIME);
$ret['note'] = bbcode($p[0]['about'], [ 'export' => true ]); $ret['note'] = bbcode($p[0]['about'], ['export' => true]);
$ret['url'] = channel_url($channel); $ret['url'] = channel_url($channel);
$ret['avatar'] = $channel['xchan_photo_l']; $ret['avatar'] = $channel['xchan_photo_l'];
$ret['avatar_static'] = $channel['xchan_photo_l']; $ret['avatar_static'] = $channel['xchan_photo_l'];
@ -60,15 +62,16 @@ class MastAPI {
$ret['followers_count'] = intval($followers[0]['total']); $ret['followers_count'] = intval($followers[0]['total']);
$ret['following_count'] = intval($following[0]['total']); $ret['following_count'] = intval($following[0]['total']);
$ret['statuses_count'] = intval($statuses[0]['total']); $ret['statuses_count'] = intval($statuses[0]['total']);
$ret['last_status_at'] = datetime_convert('UTC','UTC', $channel['lastpost'], ATOM_TIME); $ret['last_status_at'] = datetime_convert('UTC', 'UTC', $channel['lastpost'], ATOM_TIME);
return $ret; return $ret;
} }
static function format_site() { public static function format_site()
{
$register = intval(get_config('system','register_policy')); $register = intval(get_config('system', 'register_policy'));
$u = q("select count(channel_id) as total from channel where channel_removed = 0"); $u = q("select count(channel_id) as total from channel where channel_removed = 0");
$i = q("select count(id) as total from item where item_origin = 1"); $i = q("select count(id) as total from item where item_origin = 1");
@ -81,8 +84,8 @@ class MastAPI {
$ret = []; $ret = [];
$ret['uri'] = z_root(); $ret['uri'] = z_root();
$ret['title'] = System::get_site_name(); $ret['title'] = System::get_site_name();
$ret['description'] = bbcode(get_config('system','siteinfo',''), [ 'export' => true ] ); $ret['description'] = bbcode(get_config('system', 'siteinfo', ''), ['export' => true]);
$ret['email'] = get_config('system','admin_email'); $ret['email'] = get_config('system', 'admin_email');
$ret['version'] = System::get_project_version(); $ret['version'] = System::get_project_version();
$ret['registrations'] = (($register) ? true : false); $ret['registrations'] = (($register) ? true : false);
$ret['approval_required'] = (($register === REGISTER_APPROVE) ? true : false); $ret['approval_required'] = (($register === REGISTER_APPROVE) ? true : false);

View file

@ -7,7 +7,7 @@ namespace Zotlabs\Lib;
class MessageFilter { class MessageFilter {
static public function evaluate($item,$incl,$excl) { public static function evaluate($item, $incl, $excl) {
require_once('include/html2plain.php'); require_once('include/html2plain.php');

View file

@ -6,7 +6,7 @@ namespace Zotlabs\Lib;
class Nodeinfo { class Nodeinfo {
static public function fetch($url) { public static function fetch($url) {
$href = EMPTY_STR; $href = EMPTY_STR;
$m = parse_url($url); $m = parse_url($url);
if ($m['scheme'] && $m['host']) { if ($m['scheme'] && $m['host']) {

View file

@ -30,7 +30,7 @@ class PConfig {
* The channel_id * The channel_id
* @return void|false Nothing or false if $uid is null or false * @return void|false Nothing or false if $uid is null or false
*/ */
static public function Load($uid) { public static function Load($uid) {
if(is_null($uid) || $uid === false) if(is_null($uid) || $uid === false)
return false; return false;
@ -82,7 +82,7 @@ class PConfig {
* Default value to return if key does not exist * Default value to return if key does not exist
* @return mixed Stored value or false if it does not exist * @return mixed Stored value or false if it does not exist
*/ */
static public function Get($uid, $family, $key, $default = false) { public static function Get($uid, $family, $key, $default = false) {
if(is_null($uid) || $uid === false) if(is_null($uid) || $uid === false)
return $default; return $default;
@ -112,7 +112,7 @@ class PConfig {
* The value to store * The value to store
* @return mixed Stored $value or false * @return mixed Stored $value or false
*/ */
static public function Set($uid, $family, $key, $value) { public static function Set($uid, $family, $key, $value) {
// this catches subtle errors where this function has been called // this catches subtle errors where this function has been called
// with local_channel() when not logged in (which returns false) // with local_channel() when not logged in (which returns false)
@ -185,7 +185,7 @@ class PConfig {
* The configuration key to delete * The configuration key to delete
* @return mixed * @return mixed
*/ */
static public function Delete($uid, $family, $key) { public static function Delete($uid, $family, $key) {
if(is_null($uid) || $uid === false) if(is_null($uid) || $uid === false)
return false; return false;

View file

@ -157,7 +157,7 @@ class Permcat {
return $permcats; return $permcats;
} }
static public function find_permcat($arr, $name) { public static function find_permcat($arr, $name) {
if((! $arr) || (! $name)) if((! $arr) || (! $name))
return false; return false;
@ -166,11 +166,11 @@ class Permcat {
return $p['value']; return $p['value'];
} }
static public function update($channel_id, $name, $permarr) { public static function update($channel_id, $name, $permarr) {
PConfig::Set($channel_id, 'permcat', $name, $permarr); PConfig::Set($channel_id, 'permcat', $name, $permarr);
} }
static public function delete($channel_id, $name) { public static function delete($channel_id, $name) {
PConfig::Delete($channel_id, 'permcat', $name); PConfig::Delete($channel_id, 'permcat', $name);
} }

View file

@ -55,7 +55,7 @@ class PermissionDescription {
* default permission. You should pass one of the constants from boot.php - PERMS_PUBLIC, * default permission. You should pass one of the constants from boot.php - PERMS_PUBLIC,
* PERMS_NETWORK etc. * PERMS_NETWORK etc.
* *
* @param integer $perm - a single enumerated constant permission - PERMS_PUBLIC, PERMS_NETWORK etc. * @param int $perm - a single enumerated constant permission - PERMS_PUBLIC, PERMS_NETWORK etc.
* @return a new instance of PermissionDescription * @return a new instance of PermissionDescription
*/ */
public static function fromStandalonePermission($perm) { public static function fromStandalonePermission($perm) {

View file

@ -9,11 +9,13 @@ use Zotlabs\Lib\ActivityStreams;
use Zotlabs\Zot6\Receiver; use Zotlabs\Zot6\Receiver;
use Zotlabs\Zot6\Zot6Handler; use Zotlabs\Zot6\Zot6Handler;
class Queue { class Queue
{
static function update($id, $add_priority = 0) { public static function update($id, $add_priority = 0)
{
logger('queue: requeue item ' . $id,LOGGER_DEBUG); logger('queue: requeue item ' . $id, LOGGER_DEBUG);
// This queue item failed. Perhaps it was rejected. Perhaps the site is dead. // This queue item failed. Perhaps it was rejected. Perhaps the site is dead.
// Since we don't really know, check and see if we've got something else destined // Since we don't really know, check and see if we've got something else destined
@ -24,7 +26,7 @@ class Queue {
$x = q("select outq_created, outq_hash, outq_posturl from outq where outq_hash = '%s' limit 1", $x = q("select outq_created, outq_hash, outq_posturl from outq where outq_hash = '%s' limit 1",
dbesc($id) dbesc($id)
); );
if (! $x) { if (!$x) {
return; return;
} }
@ -40,7 +42,6 @@ class Queue {
} }
$y = q("select min(outq_created) as earliest from outq where outq_posturl = '%s'", $y = q("select min(outq_created) as earliest from outq where outq_posturl = '%s'",
dbesc($x[0]['outq_posturl']) dbesc($x[0]['outq_posturl'])
); );
@ -51,8 +52,8 @@ class Queue {
$might_be_down = false; $might_be_down = false;
if($y) if ($y)
$might_be_down = ((datetime_convert('UTC','UTC',$y[0]['earliest']) < datetime_convert('UTC','UTC','now - 2 days')) ? true : false); $might_be_down = ((datetime_convert('UTC', 'UTC', $y[0]['earliest']) < datetime_convert('UTC', 'UTC', 'now - 2 days')) ? true : false);
// Set all other records for this destination way into the future. // Set all other records for this destination way into the future.
@ -64,17 +65,16 @@ class Queue {
// minutes. // minutes.
$r = q("UPDATE outq SET outq_scheduled = '%s' WHERE outq_posturl = '%s'", $r = q("UPDATE outq SET outq_scheduled = '%s' WHERE outq_posturl = '%s'",
dbesc(datetime_convert('UTC','UTC','now + 5 days')), dbesc(datetime_convert('UTC', 'UTC', 'now + 5 days')),
dbesc($x[0]['outq_posturl']) dbesc($x[0]['outq_posturl'])
); );
$since = datetime_convert('UTC','UTC',$y[0]['earliest']); $since = datetime_convert('UTC', 'UTC', $y[0]['earliest']);
if(($might_be_down) || ($since < datetime_convert('UTC','UTC','now - 12 hour'))) { if (($might_be_down) || ($since < datetime_convert('UTC', 'UTC', 'now - 12 hour'))) {
$next = datetime_convert('UTC','UTC','now + 1 hour'); $next = datetime_convert('UTC', 'UTC', 'now + 1 hour');
} } else {
else { $next = datetime_convert('UTC', 'UTC', 'now + ' . intval($add_priority) . ' minutes');
$next = datetime_convert('UTC','UTC','now + ' . intval($add_priority) . ' minutes');
} }
q("UPDATE outq SET outq_updated = '%s', q("UPDATE outq SET outq_updated = '%s',
@ -90,8 +90,9 @@ class Queue {
} }
static function remove($id,$channel_id = 0) { public static function remove($id, $channel_id = 0)
logger('queue: remove queue item ' . $id,LOGGER_DEBUG); {
logger('queue: remove queue item ' . $id, LOGGER_DEBUG);
$sql_extra = (($channel_id) ? " and outq_channel = " . intval($channel_id) . " " : ''); $sql_extra = (($channel_id) ? " and outq_channel = " . intval($channel_id) . " " : '');
q("DELETE FROM outq WHERE outq_hash = '%s' $sql_extra", q("DELETE FROM outq WHERE outq_hash = '%s' $sql_extra",
@ -100,8 +101,9 @@ class Queue {
} }
static function remove_by_posturl($posturl) { public static function remove_by_posturl($posturl)
logger('queue: remove queue posturl ' . $posturl,LOGGER_DEBUG); {
logger('queue: remove queue posturl ' . $posturl, LOGGER_DEBUG);
q("DELETE FROM outq WHERE outq_posturl = '%s' ", q("DELETE FROM outq WHERE outq_posturl = '%s' ",
dbesc($posturl) dbesc($posturl)
@ -109,9 +111,9 @@ class Queue {
} }
public static function set_delivered($id, $channel = 0)
static function set_delivered($id,$channel = 0) { {
logger('queue: set delivered ' . $id,LOGGER_DEBUG); logger('queue: set delivered ' . $id, LOGGER_DEBUG);
$sql_extra = (($channel_id) ? " and outq_channel = " . intval($channel_id) . " " : ''); $sql_extra = (($channel_id) ? " and outq_channel = " . intval($channel_id) . " " : '');
// Set the next scheduled run date so far in the future that it will be expired // Set the next scheduled run date so far in the future that it will be expired
@ -119,20 +121,20 @@ class Queue {
q("update outq set outq_delivered = 1, outq_updated = '%s', outq_scheduled = '%s' where outq_hash = '%s' $sql_extra ", q("update outq set outq_delivered = 1, outq_updated = '%s', outq_scheduled = '%s' where outq_hash = '%s' $sql_extra ",
dbesc(datetime_convert()), dbesc(datetime_convert()),
dbesc(datetime_convert('UTC','UTC','now + 5 days')), dbesc(datetime_convert('UTC', 'UTC', 'now + 5 days')),
dbesc($id) dbesc($id)
); );
} }
public static function insert($arr)
{
static function insert($arr) { logger('insert: ' . print_r($arr, true), LOGGER_DATA);
logger('insert: ' . print_r($arr,true), LOGGER_DATA);
// do not queue anything with no destination // do not queue anything with no destination
if (! (array_key_exists('posturl',$arr) && trim($arr['posturl']))) { if (!(array_key_exists('posturl', $arr) && trim($arr['posturl']))) {
logger('no destination'); logger('no destination');
return false; return false;
} }
@ -159,8 +161,8 @@ class Queue {
} }
public static function deliver($outq, $immediate = false)
static function deliver($outq, $immediate = false) { {
$base = null; $base = null;
$h = parse_url($outq['outq_posturl']); $h = parse_url($outq['outq_posturl']);
@ -183,17 +185,16 @@ class Queue {
logger('dead site ignored ' . $base); logger('dead site ignored ' . $base);
return; return;
} }
if ($y[0]['site_update'] < datetime_convert('UTC','UTC','now - 1 month')) { if ($y[0]['site_update'] < datetime_convert('UTC', 'UTC', 'now - 1 month')) {
q("update dreport set dreport_log = '%s' where dreport_queue = '%s'", q("update dreport set dreport_log = '%s' where dreport_queue = '%s'",
dbesc('site deferred'), dbesc('site deferred'),
dbesc($outq['outq_hash']) dbesc($outq['outq_hash'])
); );
self::update($outq['outq_hash'],10); self::update($outq['outq_hash'], 10);
logger('immediate delivery deferred for site ' . $base); logger('immediate delivery deferred for site ' . $base);
return; return;
} }
} } else {
else {
// zot sites should all have a site record, unless they've been dead for as long as // zot sites should all have a site record, unless they've been dead for as long as
// your site has existed. Since we don't know for sure what these sites are, // your site has existed. Since we don't know for sure what these sites are,
@ -204,7 +205,7 @@ class Queue {
'site_url' => $base, 'site_url' => $base,
'site_update' => datetime_convert(), 'site_update' => datetime_convert(),
'site_dead' => 0, 'site_dead' => 0,
'site_type' => ((in_array($outq['outq_driver'], [ 'post', 'activitypub' ])) ? SITE_TYPE_NOTZOT : SITE_TYPE_UNKNOWN), 'site_type' => ((in_array($outq['outq_driver'], ['post', 'activitypub'])) ? SITE_TYPE_NOTZOT : SITE_TYPE_UNKNOWN),
'site_crypto' => '' 'site_crypto' => ''
] ]
); );
@ -212,17 +213,17 @@ class Queue {
} }
$arr = array('outq' => $outq, 'base' => $base, 'handled' => false, 'immediate' => $immediate); $arr = array('outq' => $outq, 'base' => $base, 'handled' => false, 'immediate' => $immediate);
call_hooks('queue_deliver',$arr); call_hooks('queue_deliver', $arr);
if($arr['handled']) if ($arr['handled'])
return; return;
// "post" queue driver - used for diaspora and friendica-over-diaspora communications. // "post" queue driver - used for diaspora and friendica-over-diaspora communications.
if($outq['outq_driver'] === 'post') { if ($outq['outq_driver'] === 'post') {
$result = z_post_url($outq['outq_posturl'],$outq['outq_msg']); $result = z_post_url($outq['outq_posturl'], $outq['outq_msg']);
if($result['success'] && $result['return_code'] < 300) { if ($result['success'] && $result['return_code'] < 300) {
logger('deliver: queue post success to ' . $outq['outq_posturl'], LOGGER_DEBUG); logger('deliver: queue post success to ' . $outq['outq_posturl'], LOGGER_DEBUG);
if($base) { if ($base) {
q("update site set site_update = '%s', site_dead = 0 where site_url = '%s' ", q("update site set site_update = '%s', site_dead = 0 where site_url = '%s' ",
dbesc(datetime_convert()), dbesc(datetime_convert()),
dbesc($base) dbesc($base)
@ -239,27 +240,26 @@ class Queue {
// and try to send some more. We're relying on the fact that do_delivery() results in an // and try to send some more. We're relying on the fact that do_delivery() results in an
// immediate delivery otherwise we could get into a queue loop. // immediate delivery otherwise we could get into a queue loop.
if(! $immediate) { if (!$immediate) {
$x = q("select outq_hash from outq where outq_posturl = '%s' and outq_delivered = 0", $x = q("select outq_hash from outq where outq_posturl = '%s' and outq_delivered = 0",
dbesc($outq['outq_posturl']) dbesc($outq['outq_posturl'])
); );
$piled_up = []; $piled_up = [];
if($x) { if ($x) {
foreach($x as $xx) { foreach ($x as $xx) {
$piled_up[] = $xx['outq_hash']; $piled_up[] = $xx['outq_hash'];
} }
} }
if($piled_up) { if ($piled_up) {
// call do_delivery() with the force flag // call do_delivery() with the force flag
do_delivery($piled_up, true); do_delivery($piled_up, true);
} }
} }
} } else {
else {
logger('deliver: queue post returned ' . $result['return_code'] logger('deliver: queue post returned ' . $result['return_code']
. ' from ' . $outq['outq_posturl'],LOGGER_DEBUG); . ' from ' . $outq['outq_posturl'], LOGGER_DEBUG);
self::update($outq['outq_hash'],10); self::update($outq['outq_hash'], 10);
} }
return; return;
} }
@ -267,32 +267,32 @@ class Queue {
if ($outq['outq_driver'] === 'asfetch') { if ($outq['outq_driver'] === 'asfetch') {
$channel = channelx_by_n($outq['outq_channel']); $channel = channelx_by_n($outq['outq_channel']);
if (! $channel) { if (!$channel) {
logger('missing channel: ' . $outq['outq_channel']); logger('missing channel: ' . $outq['outq_channel']);
return; return;
} }
if (! ActivityStreams::is_url($outq['outq_posturl'])) { if (!ActivityStreams::is_url($outq['outq_posturl'])) {
logger('fetch item is not url: ' . $outq['outq_posturl']); logger('fetch item is not url: ' . $outq['outq_posturl']);
self::remove($outq['outq_hash']); self::remove($outq['outq_hash']);
return; return;
} }
$j = Activity::fetch($outq['outq_posturl'],$channel); $j = Activity::fetch($outq['outq_posturl'], $channel);
if ($j) { if ($j) {
$AS = new ActivityStreams($j, null, true); $AS = new ActivityStreams($j, null, true);
if ($AS->is_valid() && isset($AS->data['type'])) { if ($AS->is_valid() && isset($AS->data['type'])) {
if (ActivityStreams::is_an_actor($AS->data['type'])) { if (ActivityStreams::is_an_actor($AS->data['type'])) {
Activity::actor_store($AS->data['id'],$AS->data); Activity::actor_store($AS->data['id'], $AS->data);
} }
if (strpos($AS->data['type'],'Collection') !== false) { if (strpos($AS->data['type'], 'Collection') !== false) {
// we are probably fetching a collection already - and do not support collection recursion at this time // we are probably fetching a collection already - and do not support collection recursion at this time
self::remove($outq['outq_hash']); self::remove($outq['outq_hash']);
return; return;
} }
$item = Activity::decode_note($AS,true); $item = Activity::decode_note($AS, true);
if ($item) { if ($item) {
Activity::store($channel,$channel['channnel_hash'],$AS,$item,true,true); Activity::store($channel, $channel['channnel_hash'], $AS, $item, true, true);
} }
} }
logger('deliver: queue fetch success from ' . $outq['outq_posturl'], LOGGER_DEBUG); logger('deliver: queue fetch success from ' . $outq['outq_posturl'], LOGGER_DEBUG);
@ -302,7 +302,7 @@ class Queue {
// and try to send some more. We're relying on the fact that do_delivery() results in an // and try to send some more. We're relying on the fact that do_delivery() results in an
// immediate delivery otherwise we could get into a queue loop. // immediate delivery otherwise we could get into a queue loop.
if (! $immediate) { if (!$immediate) {
$x = q("select outq_hash from outq where outq_driver = 'asfetch' and outq_channel = %d and outq_delivered = 0", $x = q("select outq_hash from outq where outq_driver = 'asfetch' and outq_channel = %d and outq_delivered = 0",
dbesc($outq['outq_channel']) dbesc($outq['outq_channel'])
); );
@ -314,21 +314,20 @@ class Queue {
} }
} }
if ($piled_up) { if ($piled_up) {
do_delivery($piled_up,true); do_delivery($piled_up, true);
} }
} }
} } else {
else { logger('deliver: queue fetch failed' . ' from ' . $outq['outq_posturl'], LOGGER_DEBUG);
logger('deliver: queue fetch failed' . ' from ' . $outq['outq_posturl'],LOGGER_DEBUG); self::update($outq['outq_hash'], 10);
self::update($outq['outq_hash'],10);
} }
return; return;
} }
if($outq['outq_driver'] === 'activitypub') { if ($outq['outq_driver'] === 'activitypub') {
$channel = channelx_by_n($outq['outq_channel']); $channel = channelx_by_n($outq['outq_channel']);
if (! $channel) { if (!$channel) {
logger('missing channel: ' . $outq['outq_channel']); logger('missing channel: ' . $outq['outq_channel']);
return; return;
} }
@ -338,25 +337,25 @@ class Queue {
$m = parse_url($outq['outq_posturl']); $m = parse_url($outq['outq_posturl']);
$headers = []; $headers = [];
$headers['Content-Type'] = 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"' ; $headers['Content-Type'] = 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"';
$ret = $outq['outq_msg']; $ret = $outq['outq_msg'];
logger('ActivityPub send: ' . jindent($ret), LOGGER_DATA); logger('ActivityPub send: ' . jindent($ret), LOGGER_DATA);
$headers['Date'] = datetime_convert('UTC','UTC', 'now', 'D, d M Y H:i:s \\G\\M\\T'); $headers['Date'] = datetime_convert('UTC', 'UTC', 'now', 'D, d M Y H:i:s \\G\\M\\T');
$headers['Digest'] = HTTPSig::generate_digest_header($ret); $headers['Digest'] = HTTPSig::generate_digest_header($ret);
$headers['Host'] = $m['host']; $headers['Host'] = $m['host'];
$headers['(request-target)'] = 'post ' . get_request_string($outq['outq_posturl']); $headers['(request-target)'] = 'post ' . get_request_string($outq['outq_posturl']);
$xhead = HTTPSig::create_sig($headers,$channel['channel_prvkey'],channel_url($channel)); $xhead = HTTPSig::create_sig($headers, $channel['channel_prvkey'], channel_url($channel));
if(strpos($outq['outq_posturl'],'http') !== 0) { if (strpos($outq['outq_posturl'], 'http') !== 0) {
logger('bad url: ' . $outq['outq_posturl']); logger('bad url: ' . $outq['outq_posturl']);
self::remove($outq['outq_hash']); self::remove($outq['outq_hash']);
} }
$result = z_post_url($outq['outq_posturl'],$outq['outq_msg'],$retries,[ 'headers' => $xhead ]); $result = z_post_url($outq['outq_posturl'], $outq['outq_msg'], $retries, ['headers' => $xhead]);
if($result['success'] && $result['return_code'] < 300) { if ($result['success'] && $result['return_code'] < 300) {
logger('deliver: queue post success to ' . $outq['outq_posturl'], LOGGER_DEBUG); logger('deliver: queue post success to ' . $outq['outq_posturl'], LOGGER_DEBUG);
if($base) { if ($base) {
q("update site set site_update = '%s', site_dead = 0 where site_url = '%s' ", q("update site set site_update = '%s', site_dead = 0 where site_url = '%s' ",
dbesc(datetime_convert()), dbesc(datetime_convert()),
dbesc($base) dbesc($base)
@ -373,31 +372,29 @@ class Queue {
// and try to send some more. We're relying on the fact that do_delivery() results in an // and try to send some more. We're relying on the fact that do_delivery() results in an
// immediate delivery otherwise we could get into a queue loop. // immediate delivery otherwise we could get into a queue loop.
if(! $immediate) { if (!$immediate) {
$x = q("select outq_hash from outq where outq_posturl = '%s' and outq_delivered = 0", $x = q("select outq_hash from outq where outq_posturl = '%s' and outq_delivered = 0",
dbesc($outq['outq_posturl']) dbesc($outq['outq_posturl'])
); );
$piled_up = []; $piled_up = [];
if($x) { if ($x) {
foreach($x as $xx) { foreach ($x as $xx) {
$piled_up[] = $xx['outq_hash']; $piled_up[] = $xx['outq_hash'];
} }
} }
if($piled_up) { if ($piled_up) {
do_delivery($piled_up,true); do_delivery($piled_up, true);
} }
} }
} } else {
else {
if ($result['return_code'] >= 300) { if ($result['return_code'] >= 300) {
q("update dreport set dreport_result = '%s', dreport_time = '%s' where dreport_queue = '%s'", q("update dreport set dreport_result = '%s', dreport_time = '%s' where dreport_queue = '%s'",
dbesc('delivery rejected' . ' ' . $result['return_code']), dbesc('delivery rejected' . ' ' . $result['return_code']),
dbesc(datetime_convert()), dbesc(datetime_convert()),
dbesc($outq['outq_hash']) dbesc($outq['outq_hash'])
); );
} } else {
else {
$dr = q("select * from dreport where dreport_queue = '%s'", $dr = q("select * from dreport where dreport_queue = '%s'",
dbesc($outq['outq_hash']) dbesc($outq['outq_hash'])
); );
@ -409,8 +406,8 @@ class Queue {
); );
} }
} }
logger('deliver: queue post returned ' . $result['return_code'] . ' from ' . $outq['outq_posturl'],LOGGER_DEBUG); logger('deliver: queue post returned ' . $result['return_code'] . ' from ' . $outq['outq_posturl'], LOGGER_DEBUG);
self::update($outq['outq_hash'],10); self::update($outq['outq_hash'], 10);
} }
return; return;
} }
@ -420,58 +417,56 @@ class Queue {
logger('deliver: dest: ' . $outq['outq_posturl'], LOGGER_DEBUG); logger('deliver: dest: ' . $outq['outq_posturl'], LOGGER_DEBUG);
if($outq['outq_posturl'] === z_root() . '/zot') { if ($outq['outq_posturl'] === z_root() . '/zot') {
// local delivery // local delivery
$zot = new Receiver(new Zot6Handler(),$outq['outq_notify']); $zot = new Receiver(new Zot6Handler(), $outq['outq_notify']);
$result = $zot->run(); $result = $zot->run();
logger('returned_json: ' . json_encode($result,JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES), LOGGER_DATA); logger('returned_json: ' . json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOGGER_DATA);
logger('deliver: local zot delivery succeeded to ' . $outq['outq_posturl']); logger('deliver: local zot delivery succeeded to ' . $outq['outq_posturl']);
Libzot::process_response($outq['outq_posturl'],[ 'success' => true, 'body' => json_encode($result) ], $outq); Libzot::process_response($outq['outq_posturl'], ['success' => true, 'body' => json_encode($result)], $outq);
if(! $immediate) { if (!$immediate) {
$x = q("select outq_hash from outq where outq_posturl = '%s' and outq_delivered = 0", $x = q("select outq_hash from outq where outq_posturl = '%s' and outq_delivered = 0",
dbesc($outq['outq_posturl']) dbesc($outq['outq_posturl'])
); );
$piled_up = []; $piled_up = [];
if($x) { if ($x) {
foreach($x as $xx) { foreach ($x as $xx) {
$piled_up[] = $xx['outq_hash']; $piled_up[] = $xx['outq_hash'];
} }
} }
if($piled_up) { if ($piled_up) {
do_delivery($piled_up,true); do_delivery($piled_up, true);
} }
} }
} } else {
else {
logger('remote'); logger('remote');
$channel = null; $channel = null;
if($outq['outq_channel']) { if ($outq['outq_channel']) {
$channel = channelx_by_n($outq['outq_channel'],true); $channel = channelx_by_n($outq['outq_channel'], true);
} }
$host_crypto = null; $host_crypto = null;
if($channel && $base) { if ($channel && $base) {
$h = q("select hubloc_sitekey, site_crypto from hubloc left join site on hubloc_url = site_url where site_url = '%s' and hubloc_network = 'zot6' order by hubloc_id desc limit 1", $h = q("select hubloc_sitekey, site_crypto from hubloc left join site on hubloc_url = site_url where site_url = '%s' and hubloc_network = 'zot6' order by hubloc_id desc limit 1",
dbesc($base) dbesc($base)
); );
if($h) { if ($h) {
$host_crypto = $h[0]; $host_crypto = $h[0];
} }
} }
$msg = $outq['outq_notify']; $msg = $outq['outq_notify'];
$result = Libzot::zot($outq['outq_posturl'],$msg,$channel,$host_crypto); $result = Libzot::zot($outq['outq_posturl'], $msg, $channel, $host_crypto);
if($result['success']) { if ($result['success']) {
logger('deliver: remote zot delivery succeeded to ' . $outq['outq_posturl']); logger('deliver: remote zot delivery succeeded to ' . $outq['outq_posturl']);
Libzot::process_response($outq['outq_posturl'],$result, $outq); Libzot::process_response($outq['outq_posturl'], $result, $outq);
} } else {
else {
$dr = q("select * from dreport where dreport_queue = '%s'", $dr = q("select * from dreport where dreport_queue = '%s'",
dbesc($outq['outq_hash']) dbesc($outq['outq_hash'])
); );
@ -483,8 +478,8 @@ class Queue {
); );
logger('deliver: remote zot delivery failed to ' . $outq['outq_posturl']); logger('deliver: remote zot delivery failed to ' . $outq['outq_posturl']);
logger('deliver: remote zot delivery fail data: ' . print_r($result,true), LOGGER_DATA); logger('deliver: remote zot delivery fail data: ' . print_r($result, true), LOGGER_DATA);
self::update($outq['outq_hash'],10); self::update($outq['outq_hash'], 10);
} }
} }
return; return;

View file

@ -10,19 +10,19 @@ namespace Zotlabs\Lib;
class SConfig { class SConfig {
static public function Load($server_id) { public static function Load($server_id) {
return XConfig::Load('s_' . $server_id); return XConfig::Load('s_' . $server_id);
} }
static public function Get($server_id,$family,$key,$default = false) { public static function Get($server_id, $family, $key, $default = false) {
return XConfig::Get('s_' . $server_id,$family,$key, $default); return XConfig::Get('s_' . $server_id,$family,$key, $default);
} }
static public function Set($server_id,$family,$key,$value) { public static function Set($server_id, $family, $key, $value) {
return XConfig::Set('s_' . $server_id,$family,$key,$value); return XConfig::Set('s_' . $server_id,$family,$key,$value);
} }
static public function Delete($server_id,$family,$key) { public static function Delete($server_id, $family, $key) {
return XConfig::Delete('s_' . $server_id,$family,$key); return XConfig::Delete('s_' . $server_id,$family,$key);
} }

View file

@ -16,82 +16,84 @@ use Zotlabs\Lib\Config;
* @license http://opensource.org/licenses/mit-license.php The MIT License * @license http://opensource.org/licenses/mit-license.php The MIT License
* @package svgsanitizer * @package svgsanitizer
*/ */
class SvgSanitizer
class SvgSanitizer { {
private $xmlDoc; // PHP XML DOMDocument private $xmlDoc; // PHP XML DOMDocument
private $removedattrs = []; private $removedattrs = [];
private static $allowed_functions = [ 'matrix', 'url', 'translate', 'rgb' ]; private static $allowed_functions = ['matrix', 'url', 'translate', 'rgb'];
// defines the allowlist of elements and attributes allowed. // defines the allowlist of elements and attributes allowed.
private static $allowlist = [ private static $allowlist = [
'a' => [ 'class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'mask', 'opacity', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'href', 'xlink:href', 'xlink:title' ], 'a' => ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'mask', 'opacity', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'href', 'xlink:href', 'xlink:title'],
'circle' => [ 'class', 'clip-path', 'clip-rule', 'cx', 'cy', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'mask', 'opacity', 'r', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform' ], 'circle' => ['class', 'clip-path', 'clip-rule', 'cx', 'cy', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'mask', 'opacity', 'r', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'],
'clipPath' => [ 'class', 'clipPathUnits', 'id' ], 'clipPath' => ['class', 'clipPathUnits', 'id'],
'defs' => [ ], 'defs' => [],
'style' => [ 'type' ], 'style' => ['type'],
'desc' => [ ], 'desc' => [],
'ellipse' => [ 'class', 'clip-path', 'clip-rule', 'cx', 'cy', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'mask', 'opacity', 'requiredFeatures', 'rx', 'ry', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform' ], 'ellipse' => ['class', 'clip-path', 'clip-rule', 'cx', 'cy', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'mask', 'opacity', 'requiredFeatures', 'rx', 'ry', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'],
'feGaussianBlur' => [ 'class', 'color-interpolation-filters', 'id', 'requiredFeatures', 'stdDeviation' ], 'feGaussianBlur' => ['class', 'color-interpolation-filters', 'id', 'requiredFeatures', 'stdDeviation'],
'filter' => [ 'class', 'color-interpolation-filters', 'filterRes', 'filterUnits', 'height', 'id', 'primitiveUnits', 'requiredFeatures', 'width', 'x', 'xlink:href', 'y' ], 'filter' => ['class', 'color-interpolation-filters', 'filterRes', 'filterUnits', 'height', 'id', 'primitiveUnits', 'requiredFeatures', 'width', 'x', 'xlink:href', 'y'],
'foreignObject' => [ 'class', 'font-size', 'height', 'id', 'opacity', 'requiredFeatures', 'style', 'transform', 'width', 'x', 'y' ], 'foreignObject' => ['class', 'font-size', 'height', 'id', 'opacity', 'requiredFeatures', 'style', 'transform', 'width', 'x', 'y'],
'g' => [ 'class', 'clip-path', 'clip-rule', 'id', 'display', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'font-family', 'font-size', 'font-style', 'font-weight', 'text-anchor' ], 'g' => ['class', 'clip-path', 'clip-rule', 'id', 'display', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'font-family', 'font-size', 'font-style', 'font-weight', 'text-anchor'],
'image' => [ 'class', 'clip-path', 'clip-rule', 'filter', 'height', 'id', 'mask', 'opacity', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xlink:href', 'xlink:title', 'y' ], 'image' => ['class', 'clip-path', 'clip-rule', 'filter', 'height', 'id', 'mask', 'opacity', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xlink:href', 'xlink:title', 'y'],
'line' => [ 'class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'x1', 'x2', 'y1', 'y2' ], 'line' => ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'x1', 'x2', 'y1', 'y2'],
'linearGradient' => [ 'class', 'id', 'gradientTransform', 'gradientUnits', 'requiredFeatures', 'spreadMethod', 'systemLanguage', 'x1', 'x2', 'xlink:href', 'y1', 'y2' ], 'linearGradient' => ['class', 'id', 'gradientTransform', 'gradientUnits', 'requiredFeatures', 'spreadMethod', 'systemLanguage', 'x1', 'x2', 'xlink:href', 'y1', 'y2'],
'marker' => [ 'id', 'class', 'markerHeight', 'markerUnits', 'markerWidth', 'orient', 'preserveAspectRatio', 'refX', 'refY', 'systemLanguage', 'viewBox' ], 'marker' => ['id', 'class', 'markerHeight', 'markerUnits', 'markerWidth', 'orient', 'preserveAspectRatio', 'refX', 'refY', 'systemLanguage', 'viewBox'],
'mask' => [ 'class', 'height', 'id', 'maskContentUnits', 'maskUnits', 'width', 'x', 'y' ], 'mask' => ['class', 'height', 'id', 'maskContentUnits', 'maskUnits', 'width', 'x', 'y'],
'metadata' => [ 'class', 'id' ], 'metadata' => ['class', 'id'],
'path' => [ 'class', 'clip-path', 'clip-rule', 'd', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform' ], 'path' => ['class', 'clip-path', 'clip-rule', 'd', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'],
'pattern' => [ 'class', 'height', 'id', 'patternContentUnits', 'patternTransform', 'patternUnits', 'requiredFeatures', 'style', 'systemLanguage', 'viewBox', 'width', 'x', 'xlink:href', 'y' ], 'pattern' => ['class', 'height', 'id', 'patternContentUnits', 'patternTransform', 'patternUnits', 'requiredFeatures', 'style', 'systemLanguage', 'viewBox', 'width', 'x', 'xlink:href', 'y'],
'polygon' => [ 'class', 'clip-path', 'clip-rule', 'id', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'class', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'points', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform' ], 'polygon' => ['class', 'clip-path', 'clip-rule', 'id', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'class', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'points', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'],
'polyline' => [ 'class', 'clip-path', 'clip-rule', 'id', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'points', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform' ], 'polyline' => ['class', 'clip-path', 'clip-rule', 'id', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'points', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'],
'radialGradient' => [ 'class', 'cx', 'cy', 'fx', 'fy', 'gradientTransform', 'gradientUnits', 'id', 'r', 'requiredFeatures', 'spreadMethod', 'systemLanguage', 'xlink:href' ], 'radialGradient' => ['class', 'cx', 'cy', 'fx', 'fy', 'gradientTransform', 'gradientUnits', 'id', 'r', 'requiredFeatures', 'spreadMethod', 'systemLanguage', 'xlink:href'],
'rect' => [ 'class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'height', 'id', 'mask', 'opacity', 'requiredFeatures', 'rx', 'ry', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'width', 'x', 'y' ], 'rect' => ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'height', 'id', 'mask', 'opacity', 'requiredFeatures', 'rx', 'ry', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'width', 'x', 'y'],
'stop' => [ 'class', 'id', 'offset', 'requiredFeatures', 'stop-color', 'stop-opacity', 'style', 'systemLanguage' ], 'stop' => ['class', 'id', 'offset', 'requiredFeatures', 'stop-color', 'stop-opacity', 'style', 'systemLanguage'],
'svg' => [ 'class', 'clip-path', 'clip-rule', 'filter', 'id', 'height', 'mask', 'preserveAspectRatio', 'requiredFeatures', 'style', 'systemLanguage', 'viewBox', 'width', 'x', 'xmlns', 'xmlns:se', 'xmlns:xlink', 'y' ], 'svg' => ['class', 'clip-path', 'clip-rule', 'filter', 'id', 'height', 'mask', 'preserveAspectRatio', 'requiredFeatures', 'style', 'systemLanguage', 'viewBox', 'width', 'x', 'xmlns', 'xmlns:se', 'xmlns:xlink', 'y'],
'switch' => [ 'class', 'id', 'requiredFeatures', 'systemLanguage' ], 'switch' => ['class', 'id', 'requiredFeatures', 'systemLanguage'],
'symbol' => [ 'class', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'font-family', 'font-size', 'font-style', 'font-weight', 'id', 'opacity', 'preserveAspectRatio', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'viewBox' ], 'symbol' => ['class', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'font-family', 'font-size', 'font-style', 'font-weight', 'id', 'opacity', 'preserveAspectRatio', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'viewBox'],
'text' => [ 'class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'font-family', 'font-size', 'font-style', 'font-weight', 'id', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'text-anchor', 'transform', 'x', 'xml:space', 'y' ], 'text' => ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'font-family', 'font-size', 'font-style', 'font-weight', 'id', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'text-anchor', 'transform', 'x', 'xml:space', 'y'],
'textPath' => [ 'class', 'id', 'method', 'requiredFeatures', 'spacing', 'startOffset', 'style', 'systemLanguage', 'transform', 'xlink:href' ], 'textPath' => ['class', 'id', 'method', 'requiredFeatures', 'spacing', 'startOffset', 'style', 'systemLanguage', 'transform', 'xlink:href'],
'title' => [ ], 'title' => [],
'tspan' => [ 'class', 'clip-path', 'clip-rule', 'dx', 'dy', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'font-family', 'font-size', 'font-style', 'font-weight', 'id', 'mask', 'opacity', 'requiredFeatures', 'rotate', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'text-anchor', 'textLength', 'transform', 'x', 'xml:space', 'y' ], 'tspan' => ['class', 'clip-path', 'clip-rule', 'dx', 'dy', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'font-family', 'font-size', 'font-style', 'font-weight', 'id', 'mask', 'opacity', 'requiredFeatures', 'rotate', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'text-anchor', 'textLength', 'transform', 'x', 'xml:space', 'y'],
'use' => [ 'class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'height', 'id', 'mask', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'transform', 'width', 'x', 'xlink:href', 'y' ], 'use' => ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'height', 'id', 'mask', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'transform', 'width', 'x', 'xlink:href', 'y'],
]; ];
function __construct() { public function __construct()
$this->xmlDoc = new DOMDocument('1.0','UTF-8'); {
$this->xmlDoc = new DOMDocument('1.0', 'UTF-8');
$this->xmlDoc->preserveWhiteSpace = false; $this->xmlDoc->preserveWhiteSpace = false;
libxml_use_internal_errors(true); libxml_use_internal_errors(true);
} }
// load XML SVG // load XML SVG
function load($file) { public function load($file)
{
$this->xmlDoc->load($file); $this->xmlDoc->load($file);
} }
function loadXML($str) { public function loadXML($str)
if (! $str) { {
if (!$str) {
logger('loadxml: empty input', LOGGER_DEBUG); logger('loadxml: empty input', LOGGER_DEBUG);
return false; return false;
} }
if (! $this->xmlDoc->loadXML($str)) { if (!$this->xmlDoc->loadXML($str)) {
logger('loadxml: ' . print_r(array_slice(libxml_get_errors(),0,Config::Get('system','svg_backtrace_limit',3)),true), LOGGER_DEBUG); logger('loadxml: ' . print_r(array_slice(libxml_get_errors(), 0, Config::Get('system', 'svg_backtrace_limit', 3)), true), LOGGER_DEBUG);
return false; return false;
} }
return true; return true;
} }
function sanitize() public function sanitize()
{ {
// all elements in xml doc // all elements in xml doc
$allElements = $this->xmlDoc->getElementsByTagName('*'); $allElements = $this->xmlDoc->getElementsByTagName('*');
// loop through all elements // loop through all elements
for($i = 0; $i < $allElements->length; $i++) for ($i = 0; $i < $allElements->length; $i++) {
{
$this->removedattrs = []; $this->removedattrs = [];
$currentNode = $allElements->item($i); $currentNode = $allElements->item($i);
@ -102,10 +104,10 @@ class SvgSanitizer {
$allowlist_attr_arr = self::$allowlist[$currentNode->tagName]; $allowlist_attr_arr = self::$allowlist[$currentNode->tagName];
// does element exist in allowlist? // does element exist in allowlist?
if(isset($allowlist_attr_arr)) { if (isset($allowlist_attr_arr)) {
$total = $currentNode->attributes->length; $total = $currentNode->attributes->length;
for($x = 0; $x < $total; $x++) { for ($x = 0; $x < $total; $x++) {
// get attributes name // get attributes name
$attrName = $currentNode->attributes->item($x)->nodeName; $attrName = $currentNode->attributes->item($x)->nodeName;
@ -114,18 +116,17 @@ class SvgSanitizer {
$matches = false; $matches = false;
// check if attribute isn't in allowlist // check if attribute isn't in allowlist
if(! in_array($attrName, $allowlist_attr_arr)) { if (!in_array($attrName, $allowlist_attr_arr)) {
$this->removedattrs[] = $attrName; $this->removedattrs[] = $attrName;
} } // check for disallowed functions
// check for disallowed functions
elseif (preg_match_all('/([a-zA-Z0-9]+)[\s]*\(/', elseif (preg_match_all('/([a-zA-Z0-9]+)[\s]*\(/',
$currentNode->attributes->item($x)->textContent,$matches,PREG_SET_ORDER)) { $currentNode->attributes->item($x)->textContent, $matches, PREG_SET_ORDER)) {
if ($attrName === 'text') { if ($attrName === 'text') {
continue; continue;
} }
foreach ($matches as $match) { foreach ($matches as $match) {
if(! in_array($match[1],self::$allowed_functions)) { if (!in_array($match[1], self::$allowed_functions)) {
logger('queue_remove_function: ' . $match[1],LOGGER_DEBUG); logger('queue_remove_function: ' . $match[1], LOGGER_DEBUG);
$this->removedattrs[] = $attrName; $this->removedattrs[] = $attrName;
} }
} }
@ -138,19 +139,18 @@ class SvgSanitizer {
} }
} }
} } // else remove element
// else remove element
else { else {
logger('remove_node: ' . print_r($currentNode,true)); logger('remove_node: ' . print_r($currentNode, true));
$currentNode->parentNode->removeChild($currentNode); $currentNode->parentNode->removeChild($currentNode);
} }
} }
return true; return true;
} }
function saveSVG() { public function saveSVG()
{
$this->xmlDoc->formatOutput = true; $this->xmlDoc->formatOutput = true;
return($this->xmlDoc->saveXML()); return ($this->xmlDoc->saveXML());
} }
} }

View file

@ -6,19 +6,19 @@ use App;
class System { class System {
static public function get_platform_name() { public static function get_platform_name() {
if(is_array(App::$config) && is_array(App::$config['system']) && array_key_exists('platform_name',App::$config['system'])) if(is_array(App::$config) && is_array(App::$config['system']) && array_key_exists('platform_name',App::$config['system']))
return App::$config['system']['platform_name']; return App::$config['system']['platform_name'];
return PLATFORM_NAME; return PLATFORM_NAME;
} }
static public function get_site_name() { public static function get_site_name() {
if(is_array(App::$config) && is_array(App::$config['system']) && App::$config['system']['sitename']) if(is_array(App::$config) && is_array(App::$config['system']) && App::$config['system']['sitename'])
return App::$config['system']['sitename']; return App::$config['system']['sitename'];
return ''; return '';
} }
static public function get_banner() { public static function get_banner() {
if(is_array(App::$config) && is_array(App::$config['system']) && array_key_exists('banner',App::$config['system']) && App::$config['system']['banner']) { if(is_array(App::$config) && is_array(App::$config['system']) && array_key_exists('banner',App::$config['system']) && App::$config['system']['banner']) {
return App::$config['system']['banner']; return App::$config['system']['banner'];
@ -26,14 +26,14 @@ class System {
return self::get_site_name(); return self::get_site_name();
} }
static public function get_project_icon() { public static function get_project_icon() {
if(is_array(App::$config) && is_array(App::$config['system']) && array_key_exists('icon',App::$config['system'])) { if(is_array(App::$config) && is_array(App::$config['system']) && array_key_exists('icon',App::$config['system'])) {
return App::$config['system']['icon']; return App::$config['system']['icon'];
} }
return z_root() . '/images/' . PLATFORM_NAME . '-64.png'; return z_root() . '/images/' . PLATFORM_NAME . '-64.png';
} }
static public function get_project_favicon() { public static function get_project_favicon() {
if(is_array(App::$config) && is_array(App::$config['system']) && array_key_exists('favicon',App::$config['system'])) { if(is_array(App::$config) && is_array(App::$config['system']) && array_key_exists('favicon',App::$config['system'])) {
return App::$config['system']['favicon']; return App::$config['system']['favicon'];
} }
@ -41,7 +41,7 @@ class System {
} }
static public function get_project_version() { public static function get_project_version() {
if(array_path_exists('system/hide_version', App::$config) && intval(App::$config['system']['hide_version'])) if(array_path_exists('system/hide_version', App::$config) && intval(App::$config['system']['hide_version']))
return ''; return '';
if(is_array(App::$config) && is_array(App::$config['system']) && array_key_exists('std_version',App::$config['system'])) if(is_array(App::$config) && is_array(App::$config['system']) && array_key_exists('std_version',App::$config['system']))
@ -50,63 +50,63 @@ class System {
return self::get_std_version(); return self::get_std_version();
} }
static public function get_update_version() { public static function get_update_version() {
if(is_array(App::$config) && is_array(App::$config['system']) && App::$config['system']['hide_version']) if(is_array(App::$config) && is_array(App::$config['system']) && App::$config['system']['hide_version'])
return EMPTY_STR; return EMPTY_STR;
return DB_UPDATE_VERSION; return DB_UPDATE_VERSION;
} }
static public function get_notify_icon() { public static function get_notify_icon() {
if(is_array(App::$config) && is_array(App::$config['system']) && App::$config['system']['email_notify_icon_url']) if(is_array(App::$config) && is_array(App::$config['system']) && App::$config['system']['email_notify_icon_url'])
return App::$config['system']['email_notify_icon_url']; return App::$config['system']['email_notify_icon_url'];
return self::get_project_icon(); return self::get_project_icon();
} }
static public function get_site_icon() { public static function get_site_icon() {
if(is_array(App::$config) && is_array(App::$config['system']) && isset(App::$config['system']['site_icon_url']) && App::$config['system']['site_icon_url']) if(is_array(App::$config) && is_array(App::$config['system']) && isset(App::$config['system']['site_icon_url']) && App::$config['system']['site_icon_url'])
return App::$config['system']['site_icon_url']; return App::$config['system']['site_icon_url'];
return self::get_project_icon(); return self::get_project_icon();
} }
static public function get_site_favicon() { public static function get_site_favicon() {
if(is_array(App::$config) && is_array(App::$config['system']) && App::$config['system']['site_favicon_url']) if(is_array(App::$config) && is_array(App::$config['system']) && App::$config['system']['site_favicon_url'])
return App::$config['system']['site_favicon_url']; return App::$config['system']['site_favicon_url'];
return self::get_project_favicon(); return self::get_project_favicon();
} }
static public function get_project_link() { public static function get_project_link() {
if(is_array(App::$config) && is_array(App::$config['system']) && App::$config['system']['project_link']) if(is_array(App::$config) && is_array(App::$config['system']) && App::$config['system']['project_link'])
return App::$config['system']['project_link']; return App::$config['system']['project_link'];
return 'https://zotlabs.com/' . PLATFORM_NAME; return 'https://zotlabs.com/' . PLATFORM_NAME;
} }
static public function get_project_srclink() { public static function get_project_srclink() {
if(is_array(App::$config) && is_array(App::$config['system']) && App::$config['system']['project_srclink']) if(is_array(App::$config) && is_array(App::$config['system']) && App::$config['system']['project_srclink'])
return App::$config['system']['project_srclink']; return App::$config['system']['project_srclink'];
return 'https://codeberg.org/zot/' . PLATFORM_NAME; return 'https://codeberg.org/zot/' . PLATFORM_NAME;
} }
static public function ebs() { public static function ebs() {
if(defined('EBSSTATE')) { if(defined('EBSSTATE')) {
return EBSSTATE; return EBSSTATE;
} }
return 'armed'; return 'armed';
} }
static public function get_zot_revision() { public static function get_zot_revision() {
$x = [ 'revision' => ZOT_REVISION ]; $x = [ 'revision' => ZOT_REVISION ];
call_hooks('zot_revision',$x); call_hooks('zot_revision',$x);
return $x['revision']; return $x['revision'];
} }
static public function get_std_version() { public static function get_std_version() {
if(defined('STD_VERSION')) if(defined('STD_VERSION'))
return STD_VERSION; return STD_VERSION;
return '0.0.0'; return '0.0.0';
} }
static public function compatible_project($p) { public static function compatible_project($p) {
if (in_array(strtolower($p),['hubzilla', 'zap', 'red', 'misty', 'mistpark', 'redmatrix', 'osada', 'roadhouse'])) { if (in_array(strtolower($p),['hubzilla', 'zap', 'red', 'misty', 'mistpark', 'redmatrix', 'osada', 'roadhouse'])) {
return true; return true;

View file

@ -4,7 +4,7 @@ namespace Zotlabs\Lib;
class ThreadListener { class ThreadListener {
static public function store($target_id,$portable_id,$ltype = 0) { public static function store($target_id, $portable_id, $ltype = 0) {
$x = self::fetch($target_id,$portable_id,$ltype = 0); $x = self::fetch($target_id,$portable_id,$ltype = 0);
if(! $x) { if(! $x) {
$r = q("insert into listeners ( target_id, portable_id, ltype ) values ( '%s', '%s' , %d ) ", $r = q("insert into listeners ( target_id, portable_id, ltype ) values ( '%s', '%s' , %d ) ",
@ -15,7 +15,7 @@ class ThreadListener {
} }
} }
static public function fetch($target_id,$portable_id,$ltype = 0) { public static function fetch($target_id, $portable_id, $ltype = 0) {
$x = q("select * from listeners where target_id = '%s' and portable_id = '%s' and ltype = %d limit 1", $x = q("select * from listeners where target_id = '%s' and portable_id = '%s' and ltype = %d limit 1",
dbesc($target_id), dbesc($target_id),
dbesc($portable_id), dbesc($portable_id),
@ -27,7 +27,7 @@ class ThreadListener {
return false; return false;
} }
static public function fetch_by_target($target_id,$ltype = 0) { public static function fetch_by_target($target_id, $ltype = 0) {
$x = q("select * from listeners where target_id = '%s' and ltype = %d", $x = q("select * from listeners where target_id = '%s' and ltype = %d",
dbesc($target_id), dbesc($target_id),
intval($ltype) intval($ltype)
@ -36,14 +36,14 @@ class ThreadListener {
return $x; return $x;
} }
static public function delete_by_target($target_id, $ltype = 0) { public static function delete_by_target($target_id, $ltype = 0) {
return q("delete from listeners where target_id = '%s' and ltype = %d", return q("delete from listeners where target_id = '%s' and ltype = %d",
dbesc($target_id), dbesc($target_id),
intval($ltype) intval($ltype)
); );
} }
static public function delete_by_pid($portable_id, $ltype = 0) { public static function delete_by_pid($portable_id, $ltype = 0) {
return q("delete from listeners where portable_id = '%s' and ltype = %d", return q("delete from listeners where portable_id = '%s' and ltype = %d",
dbesc($portable_id), dbesc($portable_id),
intval($ltype) intval($ltype)

View file

@ -3,9 +3,11 @@
namespace Zotlabs\Lib; namespace Zotlabs\Lib;
class Verify { class Verify
{
static function create($type,$channel_id,$token,$meta) { public static function create($type, $channel_id, $token, $meta)
{
return q("insert into verify ( vtype, channel, token, meta, created ) values ( '%s', %d, '%s', '%s', '%s' )", return q("insert into verify ( vtype, channel, token, meta, created ) values ( '%s', %d, '%s', '%s', '%s' )",
dbesc($type), dbesc($type),
intval($channel_id), intval($channel_id),
@ -15,14 +17,15 @@ class Verify {
); );
} }
static function match($type,$channel_id,$token,$meta) { public static function match($type, $channel_id, $token, $meta)
{
$r = q("select id from verify where vtype = '%s' and channel = %d and token = '%s' and meta = '%s' limit 1", $r = q("select id from verify where vtype = '%s' and channel = %d and token = '%s' and meta = '%s' limit 1",
dbesc($type), dbesc($type),
intval($channel_id), intval($channel_id),
dbesc($token), dbesc($token),
dbesc($meta) dbesc($meta)
); );
if($r) { if ($r) {
q("delete from verify where id = %d", q("delete from verify where id = %d",
intval($r[0]['id']) intval($r[0]['id'])
); );
@ -31,13 +34,14 @@ class Verify {
return false; return false;
} }
static function get_meta($type,$channel_id,$token) { public static function get_meta($type, $channel_id, $token)
{
$r = q("select id, meta from verify where vtype = '%s' and channel = %d and token = '%s' limit 1", $r = q("select id, meta from verify where vtype = '%s' and channel = %d and token = '%s' limit 1",
dbesc($type), dbesc($type),
intval($channel_id), intval($channel_id),
dbesc($token) dbesc($token)
); );
if($r) { if ($r) {
q("delete from verify where id = %d", q("delete from verify where id = %d",
intval($r[0]['id']) intval($r[0]['id'])
); );
@ -52,7 +56,8 @@ class Verify {
* @param string $type Verify type * @param string $type Verify type
* @param string $interval SQL compatible time interval * @param string $interval SQL compatible time interval
*/ */
static function purge($type, $interval) { public static function purge($type, $interval)
{
q("delete from verify where vtype = '%s' and created < ( %s - INTERVAL %s )", q("delete from verify where vtype = '%s' and created < ( %s - INTERVAL %s )",
dbesc($type), dbesc($type),
db_utcnow(), db_utcnow(),

View file

@ -6,81 +6,79 @@ namespace Zotlabs\Lib;
* @brief Fetch and return a webfinger for a resource * @brief Fetch and return a webfinger for a resource
* *
* @param string $resource - The resource * @param string $resource - The resource
* @return boolean|string false or associative array from result JSON * @return bool|string false or associative array from result JSON
*/ */
class Webfinger
{
class Webfinger { private static $server = EMPTY_STR;
private static $resource = EMPTY_STR;
static private $server = EMPTY_STR; public static function exec($resource)
static private $resource = EMPTY_STR; {
static function exec($resource) { if (!$resource) {
if (! $resource) {
return false; return false;
} }
self::parse_resource($resource); self::parse_resource($resource);
if (! ( self::$server && self::$resource)) { if (!(self::$server && self::$resource)) {
return false; return false;
} }
if (! check_siteallowed(self::$server)) { if (!check_siteallowed(self::$server)) {
logger('denied: ' . self::$server); logger('denied: ' . self::$server);
return false; return false;
} }
logger('fetching resource: ' . self::$resource . ' from ' . self::$server, LOGGER_DEBUG, LOG_INFO); logger('fetching resource: ' . self::$resource . ' from ' . self::$server, LOGGER_DEBUG, LOG_INFO);
$url = 'https://' . self::$server . '/.well-known/webfinger?f=&resource=' . self::$resource ; $url = 'https://' . self::$server . '/.well-known/webfinger?f=&resource=' . self::$resource;
$counter = 0; $counter = 0;
$s = z_fetch_url($url, false, $counter, [ 'headers' => [ 'Accept: application/jrd+json, */*' ] ]); $s = z_fetch_url($url, false, $counter, ['headers' => ['Accept: application/jrd+json, */*']]);
if ($s['success']) { if ($s['success']) {
$j = json_decode($s['body'], true); $j = json_decode($s['body'], true);
return($j); return ($j);
} }
return false; return false;
} }
static function parse_resource($resource) { public static function parse_resource($resource)
{
self::$resource = urlencode($resource); self::$resource = urlencode($resource);
if (strpos($resource,'http') === 0) { if (strpos($resource, 'http') === 0) {
$m = parse_url($resource); $m = parse_url($resource);
if ($m) { if ($m) {
if ($m['scheme'] !== 'https') { if ($m['scheme'] !== 'https') {
return false; return false;
} }
self::$server = $m['host'] . (($m['port']) ? ':' . $m['port'] : ''); self::$server = $m['host'] . (($m['port']) ? ':' . $m['port'] : '');
} } else {
else {
return false; return false;
} }
} } elseif (strpos($resource, 'tag:') === 0) {
elseif (strpos($resource,'tag:') === 0) { $arr = explode(':', $resource); // split the tag
$arr = explode(':',$resource); // split the tag $h = explode(',', $arr[1]); // split the host,date
$h = explode(',',$arr[1]); // split the host,date
self::$server = $h[0]; self::$server = $h[0];
} } else {
else { $x = explode('@', $resource);
$x = explode('@',$resource); if (!strlen($x[0])) {
if (! strlen($x[0])) {
// e.g. @dan@pixelfed.org // e.g. @dan@pixelfed.org
array_shift($x); array_shift($x);
} }
$username = $x[0]; $username = $x[0];
if (count($x) > 1) { if (count($x) > 1) {
self::$server = $x[1]; self::$server = $x[1];
} } else {
else {
return false; return false;
} }
if (strpos($resource,'acct:') !== 0) { if (strpos($resource, 'acct:') !== 0) {
self::$resource = urlencode('acct:' . $resource); self::$resource = urlencode('acct:' . $resource);
} }
} }
@ -91,14 +89,15 @@ class Webfinger {
* *
*/ */
static function zot_url($resource) { public static function zot_url($resource)
{
$arr = self::exec($resource); $arr = self::exec($resource);
if (is_array($arr) && array_key_exists('links',$arr)) { if (is_array($arr) && array_key_exists('links', $arr)) {
foreach ($arr['links'] as $link) { foreach ($arr['links'] as $link) {
if (array_key_exists('rel',$link) && $link['rel'] === PROTOCOL_ZOT6) { if (array_key_exists('rel', $link) && $link['rel'] === PROTOCOL_ZOT6) {
if (array_key_exists('href',$link) && $link['href'] !== EMPTY_STR) { if (array_key_exists('href', $link) && $link['href'] !== EMPTY_STR) {
return $link['href']; return $link['href'];
} }
} }

View file

@ -36,7 +36,7 @@ class XConfig {
* The observer's hash * The observer's hash
* @return void|false Returns false if xchan is not set * @return void|false Returns false if xchan is not set
*/ */
static public function Load($xchan) { public static function Load($xchan) {
if(! $xchan) if(! $xchan)
return false; return false;
@ -76,10 +76,10 @@ class XConfig {
* The category of the configuration value * The category of the configuration value
* @param string $key * @param string $key
* The configuration key to query * The configuration key to query
* @param boolean $default (optional) default false * @param bool $default (optional) default false
* @return mixed Stored $value or false if it does not exist * @return mixed Stored $value or false if it does not exist
*/ */
static public function Get($xchan, $family, $key, $default = false) { public static function Get($xchan, $family, $key, $default = false) {
if(! $xchan) if(! $xchan)
return $default; return $default;
@ -109,7 +109,7 @@ class XConfig {
* The value to store * The value to store
* @return mixed Stored $value or false * @return mixed Stored $value or false
*/ */
static public function Set($xchan, $family, $key, $value) { public static function Set($xchan, $family, $key, $value) {
// manage array value // manage array value
$dbvalue = ((is_array($value)) ? serialise($value) : $value); $dbvalue = ((is_array($value)) ? serialise($value) : $value);
@ -159,7 +159,7 @@ class XConfig {
* The configuration key to delete * The configuration key to delete
* @return mixed * @return mixed
*/ */
static public function Delete($xchan, $family, $key) { public static function Delete($xchan, $family, $key) {
if(isset(App::$config[$xchan]) && isset(App::$config[$xchan][$family]) && isset(App::$config[$xchan][$family][$key])) if(isset(App::$config[$xchan]) && isset(App::$config[$xchan][$family]) && isset(App::$config[$xchan][$family][$key]))
unset(App::$config[$xchan][$family][$key]); unset(App::$config[$xchan][$family][$key]);

View file

@ -7,7 +7,7 @@ use Zotlabs\Web\HTTPSig;
class ZotURL { class ZotURL {
static public function fetch($url,$channel,$hub = null) { public static function fetch($url, $channel, $hub = null) {
$ret = [ 'success' => false ]; $ret = [ 'success' => false ];
@ -66,7 +66,7 @@ class ZotURL {
} }
static public function is_zoturl($s) { public static function is_zoturl($s) {
if(strpos($url,'x-zot:') === 0) { if(strpos($url,'x-zot:') === 0) {
return true; return true;
@ -75,7 +75,7 @@ class ZotURL {
} }
static public function lookup($portable_id,$hub) { public static function lookup($portable_id, $hub) {
$r = q("select * from hubloc left join site on hubloc_url = site_url where hubloc_hash = '%s' and site_dead = 0 order by hubloc_primary desc", $r = q("select * from hubloc left join site on hubloc_url = site_url where hubloc_hash = '%s' and site_dead = 0 order by hubloc_primary desc",
dbesc($portable_id) dbesc($portable_id)
@ -107,7 +107,7 @@ class ZotURL {
} }
static public function parse_response($arr) { public static function parse_response($arr) {
if(! $arr['success']) { if(! $arr['success']) {
return false; return false;
} }

View file

@ -4,22 +4,24 @@ namespace Zotlabs\Lib;
use Zotlabs\Web\HTTPSig; use Zotlabs\Web\HTTPSig;
class Zotfinger { class Zotfinger
{
static function exec($resource,$channel = null,$verify = true) { public static function exec($resource, $channel = null, $verify = true)
{
if (! $resource) { if (!$resource) {
return false; return false;
} }
$m = parse_url($resource); $m = parse_url($resource);
if ($m['host'] !== punify($m['host'])) { if ($m['host'] !== punify($m['host'])) {
$url = str_replace($m['host'],punify($m['host']),$url); $url = str_replace($m['host'], punify($m['host']), $url);
$m['host'] = punify($m['host']); $m['host'] = punify($m['host']);
} }
$data = json_encode([ 'zot_token' => random_string() ]); $data = json_encode(['zot_token' => random_string()]);
if ($channel && $m) { if ($channel && $m) {
@ -31,16 +33,15 @@ class Zotfinger {
'Host' => $m['host'], 'Host' => $m['host'],
'(request-target)' => 'post ' . get_request_string($resource) '(request-target)' => 'post ' . get_request_string($resource)
]; ];
$h = HTTPSig::create_sig($headers,$channel['channel_prvkey'],channel_url($channel),false); $h = HTTPSig::create_sig($headers, $channel['channel_prvkey'], channel_url($channel), false);
} } else {
else { $h = ['Accept: application/x-zot+json'];
$h = [ 'Accept: application/x-zot+json' ];
} }
$result = []; $result = [];
$redirects = 0; $redirects = 0;
$x = z_post_url($resource,$data,$redirects, [ 'headers' => $h ] ); $x = z_post_url($resource, $data, $redirects, ['headers' => $h]);
if ($x['success']) { if ($x['success']) {
@ -48,10 +49,10 @@ class Zotfinger {
$result['signature'] = HTTPSig::verify($x, EMPTY_STR, 'zot6'); $result['signature'] = HTTPSig::verify($x, EMPTY_STR, 'zot6');
} }
$result['data'] = json_decode($x['body'],true); $result['data'] = json_decode($x['body'], true);
if ($result['data'] && is_array($result['data']) && array_key_exists('encrypted',$result['data']) && $result['data']['encrypted']) { if ($result['data'] && is_array($result['data']) && array_key_exists('encrypted', $result['data']) && $result['data']['encrypted']) {
$result['data'] = json_decode(Crypto::unencapsulate($result['data'],get_config('system','prvkey')),true); $result['data'] = json_decode(Crypto::unencapsulate($result['data'], get_config('system', 'prvkey')), true);
} }
return $result; return $result;

View file

@ -23,18 +23,19 @@ require_once('include/acl_selectors.php');
* keys however this functionality has grown in an ad-hoc manner and has gotten * keys however this functionality has grown in an ad-hoc manner and has gotten
* quite messy over time. * quite messy over time.
*/ */
class Acl extends Controller
{
class Acl extends Controller { public function init()
{
function init() {
// logger('mod_acl: ' . print_r($_REQUEST,true),LOGGER_DATA); // logger('mod_acl: ' . print_r($_REQUEST,true),LOGGER_DATA);
$start = (x($_REQUEST,'start') ? $_REQUEST['start'] : 0); $start = (x($_REQUEST, 'start') ? $_REQUEST['start'] : 0);
$count = (x($_REQUEST,'count') ? $_REQUEST['count'] : 500); $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 500);
$search = (x($_REQUEST,'search') ? $_REQUEST['search'] : ''); $search = (x($_REQUEST, 'search') ? $_REQUEST['search'] : '');
$type = (x($_REQUEST,'type') ? $_REQUEST['type'] : ''); $type = (x($_REQUEST, 'type') ? $_REQUEST['type'] : '');
$noforums = (x($_REQUEST,'n') ? $_REQUEST['n'] : false); $noforums = (x($_REQUEST, 'n') ? $_REQUEST['n'] : false);
// $type = // $type =
@ -58,17 +59,17 @@ class Acl extends Controller {
// parameter. Internally we'll use $search to represent the search text no matter // parameter. Internally we'll use $search to represent the search text no matter
// what request variable it was attached to. // what request variable it was attached to.
if (array_key_exists('query',$_REQUEST)) { if (array_key_exists('query', $_REQUEST)) {
$search = $_REQUEST['query']; $search = $_REQUEST['query'];
} }
if ( (! local_channel()) && (! in_array($type, [ 'x', 'c', 'f' ]))) { if ((!local_channel()) && (!in_array($type, ['x', 'c', 'f']))) {
killme(); killme();
} }
$permitted = []; $permitted = [];
if (in_array($type, [ 'm', 'a', 'f' ])) { if (in_array($type, ['m', 'a', 'f'])) {
// These queries require permission checking. We'll create a simple array of xchan_hash for those with // These queries require permission checking. We'll create a simple array of xchan_hash for those with
// the requisite permissions which we can check against. // the requisite permissions which we can check against.
@ -78,15 +79,14 @@ class Acl extends Controller {
dbesc(($type === 'm') ? '%post_mail%' : '%tag_deliver%') dbesc(($type === 'm') ? '%post_mail%' : '%tag_deliver%')
); );
$permitted = ids_to_array($x,'xchan'); $permitted = ids_to_array($x, 'xchan');
} }
if ($search) { if ($search) {
$sql_extra = " AND pgrp.gname LIKE " . protect_sprintf( "'%" . dbesc($search) . "%'" ) . " "; $sql_extra = " AND pgrp.gname LIKE " . protect_sprintf("'%" . dbesc($search) . "%'") . " ";
// sql_extra2 is typically used when we don't have a local_channel - so we are not search abook_alias // sql_extra2 is typically used when we don't have a local_channel - so we are not search abook_alias
$sql_extra2 = " AND ( xchan_name LIKE " . protect_sprintf( "'%" . dbesc($search) . "%'" ) . " OR xchan_addr LIKE " . protect_sprintf( "'%" . dbesc(punify($search)) . ((strpos($search,'@') === false) ? "%@%'" : "%'")) . ") "; $sql_extra2 = " AND ( xchan_name LIKE " . protect_sprintf("'%" . dbesc($search) . "%'") . " OR xchan_addr LIKE " . protect_sprintf("'%" . dbesc(punify($search)) . ((strpos($search, '@') === false) ? "%@%'" : "%'")) . ") ";
// This horrible mess is needed because position also returns 0 if nothing is found. // This horrible mess is needed because position also returns 0 if nothing is found.
@ -95,17 +95,16 @@ class Acl extends Controller {
// order by LEAST(POSITION($search IN xchan_name),POSITION($search IN xchan_addr)). // order by LEAST(POSITION($search IN xchan_name),POSITION($search IN xchan_addr)).
$order_extra2 = "CASE WHEN xchan_name LIKE " $order_extra2 = "CASE WHEN xchan_name LIKE "
. protect_sprintf( "'%" . dbesc($search) . "%'" ) . protect_sprintf("'%" . dbesc($search) . "%'")
. " then POSITION('" . protect_sprintf(dbesc($search)) . " then POSITION('" . protect_sprintf(dbesc($search))
. "' IN xchan_name) else position('" . protect_sprintf(dbesc(punify($search))) . "' IN xchan_addr) end, "; . "' IN xchan_name) else position('" . protect_sprintf(dbesc(punify($search))) . "' IN xchan_addr) end, ";
$sql_extra3 = "AND ( xchan_addr like " . protect_sprintf( "'%" . dbesc(punify($search)) . "%'" ) . " OR xchan_name like " . protect_sprintf( "'%" . dbesc($search) . "%'" ) . " OR abook_alias like " . protect_sprintf( "'%" . dbesc($search) . "%'" ) . " ) "; $sql_extra3 = "AND ( xchan_addr like " . protect_sprintf("'%" . dbesc(punify($search)) . "%'") . " OR xchan_name like " . protect_sprintf("'%" . dbesc($search) . "%'") . " OR abook_alias like " . protect_sprintf("'%" . dbesc($search) . "%'") . " ) ";
$sql_extra4 = "AND ( xchan_name LIKE " . protect_sprintf( "'%" . dbesc($search) . "%'" ) . " OR xchan_addr LIKE " . protect_sprintf( "'%" . dbesc(punify($search)) . ((strpos($search,'@') === false) ? "%@%'" : "%'")) . " OR abook_alias LIKE " . protect_sprintf( "'%" . dbesc($search) . "%'") . ") "; $sql_extra4 = "AND ( xchan_name LIKE " . protect_sprintf("'%" . dbesc($search) . "%'") . " OR xchan_addr LIKE " . protect_sprintf("'%" . dbesc(punify($search)) . ((strpos($search, '@') === false) ? "%@%'" : "%'")) . " OR abook_alias LIKE " . protect_sprintf("'%" . dbesc($search) . "%'") . ") ";
} } else {
else {
$sql_extra = $sql_extra2 = $sql_extra3 = $sql_extra4 = ""; $sql_extra = $sql_extra2 = $sql_extra3 = $sql_extra4 = "";
} }
@ -139,7 +138,7 @@ class Acl extends Controller {
"name" => $g['gname'], "name" => $g['gname'],
"id" => $g['id'], "id" => $g['id'],
"xid" => $g['hash'], "xid" => $g['hash'],
"uids" => AccessList::members_xchan(local_channel(),$g['id']), "uids" => AccessList::members_xchan(local_channel(), $g['id']),
"link" => '' "link" => ''
]; ];
} }
@ -155,15 +154,14 @@ class Acl extends Controller {
$r = q("SELECT abook_id as id, xchan_hash as hash, xchan_name as name, xchan_photo_s as micro, xchan_url as url, xchan_addr as nick, xchan_type, abook_flags, abook_self $r = q("SELECT abook_id as id, xchan_hash as hash, xchan_name as name, xchan_photo_s as micro, xchan_url as url, xchan_addr as nick, xchan_type, abook_flags, abook_self
FROM abook left join xchan on abook_xchan = xchan_hash FROM abook left join xchan on abook_xchan = xchan_hash
WHERE abook_channel = %d AND abook_blocked = 0 and abook_pending = 0 and xchan_deleted = 0 $sql_extra4 order by xchan_name asc limit $count" , WHERE abook_channel = %d AND abook_blocked = 0 and abook_pending = 0 and xchan_deleted = 0 $sql_extra4 order by xchan_name asc limit $count",
intval(local_channel()) intval(local_channel())
); );
} } else { // Visitors
else { // Visitors
$r = q("SELECT xchan_hash as id, xchan_hash as hash, xchan_name as name, xchan_photo_s as micro, xchan_url as url, xchan_addr as nick, 0 as abook_flags, 0 as abook_self $r = q("SELECT xchan_hash as id, xchan_hash as hash, xchan_name as name, xchan_photo_s as micro, xchan_url as url, xchan_addr as nick, 0 as abook_flags, 0 as abook_self
FROM xchan left join xlink on xlink_link = xchan_hash FROM xchan left join xlink on xlink_link = xchan_hash
WHERE xlink_xchan = '%s' AND xchan_deleted = 0 $sql_extra2 order by $order_extra2 xchan_name asc limit $count" , WHERE xlink_xchan = '%s' AND xchan_deleted = 0 $sql_extra2 order by $order_extra2 xchan_name asc limit $count",
dbesc(get_observer_hash()) dbesc(get_observer_hash())
); );
@ -173,13 +171,12 @@ class Acl extends Controller {
FROM xchan WHERE xchan_deleted = 0 and xchan_network != 'unknown' $sql_extra2 order by $order_extra2 xchan_name asc limit $count" FROM xchan WHERE xchan_deleted = 0 and xchan_network != 'unknown' $sql_extra2 order by $order_extra2 xchan_name asc limit $count"
); );
if ($r2) { if ($r2) {
$r = array_merge($r,$r2); $r = array_merge($r, $r2);
$r = unique_multidim_array($r,'hash'); $r = unique_multidim_array($r, 'hash');
} }
} }
} } elseif ($type == 'm') {
elseif ($type == 'm') {
$r = []; $r = [];
$z = q("SELECT xchan_hash as hash, xchan_name as name, xchan_addr as nick, xchan_photo_s as micro, xchan_url as url $z = q("SELECT xchan_hash as hash, xchan_name as name, xchan_addr as nick, xchan_photo_s as micro, xchan_url as url
@ -192,14 +189,13 @@ class Acl extends Controller {
); );
if ($z) { if ($z) {
foreach ($z as $zz) { foreach ($z as $zz) {
if (in_array($zz['hash'],$permitted)) { if (in_array($zz['hash'], $permitted)) {
$r[] = $zz; $r[] = $zz;
} }
} }
} }
} } elseif ($type == 'a') {
elseif ($type == 'a') {
$r = q("SELECT abook_id as id, xchan_name as name, xchan_hash as hash, xchan_addr as nick, xchan_photo_s as micro, xchan_network as network, xchan_url as url, xchan_addr as attag FROM abook left join xchan on abook_xchan = xchan_hash $r = q("SELECT abook_id as id, xchan_name as name, xchan_hash as hash, xchan_addr as nick, xchan_photo_s as micro, xchan_network as network, xchan_url as url, xchan_addr as attag FROM abook left join xchan on abook_xchan = xchan_hash
WHERE abook_channel = %d WHERE abook_channel = %d
@ -209,8 +205,7 @@ class Acl extends Controller {
intval(local_channel()) intval(local_channel())
); );
} } elseif ($type == 'z') {
elseif ($type == 'z') {
$r = q("SELECT xchan_name as name, xchan_hash as hash, xchan_addr as nick, xchan_photo_s as micro, xchan_network as network, xchan_url as url, xchan_addr as attag FROM xchan left join abook on xchan_hash = abook_xchan $r = q("SELECT xchan_name as name, xchan_hash as hash, xchan_addr as nick, xchan_photo_s as micro, xchan_network as network, xchan_url as url, xchan_addr as attag FROM xchan left join abook on xchan_hash = abook_xchan
WHERE ( abook_channel = %d OR abook_channel IS NULL ) WHERE ( abook_channel = %d OR abook_channel IS NULL )
and xchan_deleted = 0 and xchan_deleted = 0
@ -218,9 +213,7 @@ class Acl extends Controller {
ORDER BY xchan_name ASC ", ORDER BY xchan_name ASC ",
intval(local_channel()) intval(local_channel())
); );
} } elseif ($type == 'x') {
elseif ($type == 'x') {
$contacts = []; $contacts = [];
$r = $this->navbar_complete(); $r = $this->navbar_complete();
if ($r) { if ($r) {
@ -241,15 +234,14 @@ class Acl extends Controller {
'items' => $contacts, 'items' => $contacts,
]; ];
json_return_and_die($o); json_return_and_die($o);
} } else {
else {
$r = []; $r = [];
} }
if ($r) { if ($r) {
foreach ($r as $g) { foreach ($r as $g) {
if (isset($g['network']) && in_array($g['network'],['rss','anon','unknown']) && ($type != 'a')) { if (isset($g['network']) && in_array($g['network'], ['rss', 'anon', 'unknown']) && ($type != 'a')) {
continue; continue;
} }
@ -259,11 +251,11 @@ class Acl extends Controller {
$g['hash'] = urlencode($g['hash']); $g['hash'] = urlencode($g['hash']);
} }
if (! $g['nick']) { if (!$g['nick']) {
$g['nick'] = $g['url']; $g['nick'] = $g['url'];
} }
if (in_array($g['hash'],$permitted) && $type === 'f' && (! $noforums)) { if (in_array($g['hash'], $permitted) && $type === 'f' && (!$noforums)) {
$contacts[] = [ $contacts[] = [
"type" => "c", "type" => "c",
"photo" => "images/twopeople.png", "photo" => "images/twopeople.png",
@ -271,7 +263,7 @@ class Acl extends Controller {
"id" => urlencode($g['id']), "id" => urlencode($g['id']),
"xid" => $g['hash'], "xid" => $g['hash'],
"link" => (($g['nick']) ? $g['nick'] : $g['url']), "link" => (($g['nick']) ? $g['nick'] : $g['url']),
"nick" => substr($g['nick'],0,strpos($g['nick'],'@')), "nick" => substr($g['nick'], 0, strpos($g['nick'], '@')),
"self" => (intval($g['abook_self']) ? 'abook-self' : ''), "self" => (intval($g['abook_self']) ? 'abook-self' : ''),
"taggable" => 'taggable', "taggable" => 'taggable',
"label" => t('network') "label" => t('network')
@ -285,7 +277,7 @@ class Acl extends Controller {
"id" => urlencode($g['id']), "id" => urlencode($g['id']),
"xid" => $g['hash'], "xid" => $g['hash'],
"link" => (($g['nick']) ? $g['nick'] : $g['url']), "link" => (($g['nick']) ? $g['nick'] : $g['url']),
"nick" => ((strpos($g['nick'],'@')) ? substr($g['nick'],0,strpos($g['nick'],'@')) : $g['nick']), "nick" => ((strpos($g['nick'], '@')) ? substr($g['nick'], 0, strpos($g['nick'], '@')) : $g['nick']),
"self" => (intval($g['abook_self']) ? 'abook-self' : ''), "self" => (intval($g['abook_self']) ? 'abook-self' : ''),
"taggable" => '', "taggable" => '',
"label" => '', "label" => '',
@ -306,7 +298,8 @@ class Acl extends Controller {
} }
function navbar_complete() { public function navbar_complete()
{
// logger('navbar_complete'); // logger('navbar_complete');
@ -314,25 +307,25 @@ class Acl extends Controller {
return; return;
} }
$dirmode = intval(get_config('system','directory_mode')); $dirmode = intval(get_config('system', 'directory_mode'));
$search = ((x($_REQUEST,'search')) ? htmlentities($_REQUEST['search'],ENT_COMPAT,'UTF-8',false) : ''); $search = ((x($_REQUEST, 'search')) ? htmlentities($_REQUEST['search'], ENT_COMPAT, 'UTF-8', false) : '');
if (! $search || mb_strlen($search) < 2) { if (!$search || mb_strlen($search) < 2) {
return []; return [];
} }
$star = false; $star = false;
$address = false; $address = false;
if (substr($search,0,1) === '@') { if (substr($search, 0, 1) === '@') {
$search = substr($search,1); $search = substr($search, 1);
} }
if (substr($search,0,1) === '*') { if (substr($search, 0, 1) === '*') {
$star = true; $star = true;
$search = substr($search,1); $search = substr($search, 1);
} }
if (strpos($search,'@') !== false) { if (strpos($search, '@') !== false) {
$address = true; $address = true;
} }
@ -342,7 +335,7 @@ class Acl extends Controller {
$results = []; $results = [];
$count = (x($_REQUEST,'count') ? $_REQUEST['count'] : 100); $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 100);
if ($url) { if ($url) {
$query = $url . '?f='; $query = $url . '?f=';
@ -351,7 +344,7 @@ class Acl extends Controller {
$x = z_fetch_url($query); $x = z_fetch_url($query);
if ($x['success']) { if ($x['success']) {
$t = 0; $t = 0;
$j = json_decode($x['body'],true); $j = json_decode($x['body'], true);
if ($j && $j['results']) { if ($j && $j['results']) {
$results = $j['results']; $results = $j['results'];
} }

View file

@ -10,15 +10,17 @@ use Zotlabs\Lib\LDSignatures;
use Zotlabs\Lib\ThreadListener; use Zotlabs\Lib\ThreadListener;
use App; use App;
class Activity extends Controller { class Activity extends Controller
{
function init() { public function init()
{
if (ActivityStreams::is_as_request()) { if (ActivityStreams::is_as_request()) {
$item_id = argv(1); $item_id = argv(1);
if (! $item_id) { if (!$item_id) {
return; return;
} }
@ -48,10 +50,10 @@ class Activity extends Controller {
$sigdata = HTTPSig::verify(EMPTY_STR); $sigdata = HTTPSig::verify(EMPTY_STR);
if ($sigdata['portable_id'] && $sigdata['header_valid']) { if ($sigdata['portable_id'] && $sigdata['header_valid']) {
$portable_id = $sigdata['portable_id']; $portable_id = $sigdata['portable_id'];
if (! check_channelallowed($portable_id)) { if (!check_channelallowed($portable_id)) {
http_status_exit(403, 'Permission denied'); http_status_exit(403, 'Permission denied');
} }
if (! check_siteallowed($sigdata['signer'])) { if (!check_siteallowed($sigdata['signer'])) {
http_status_exit(403, 'Permission denied'); http_status_exit(403, 'Permission denied');
} }
observer_auth($portable_id); observer_auth($portable_id);
@ -62,8 +64,7 @@ class Activity extends Controller {
if ($ob_authorize) { if ($ob_authorize) {
$sql_extra = " and item.uid = " . intval($token['uid']) . " "; $sql_extra = " and item.uid = " . intval($token['uid']) . " ";
} } else {
else {
$sql_extra = item_permissions_sql(0); $sql_extra = item_permissions_sql(0);
} }
@ -73,7 +74,7 @@ class Activity extends Controller {
dbesc(z_root() . '/item/' . $item_id) dbesc(z_root() . '/item/' . $item_id)
); );
if (! $r) { if (!$r) {
$r = q("select * from item where ( uuid = '%s' or mid = '%s' or mid = '%s' ) $item_normal limit 1", $r = q("select * from item where ( uuid = '%s' or mid = '%s' or mid = '%s' ) $item_normal limit 1",
dbesc($item_id), dbesc($item_id),
dbesc(z_root() . '/activity/' . $item_id), dbesc(z_root() . '/activity/' . $item_id),
@ -86,22 +87,22 @@ class Activity extends Controller {
http_status_exit(404, 'Not found'); http_status_exit(404, 'Not found');
} }
xchan_query($r,true); xchan_query($r, true);
$items = fetch_post_tags($r,false); $items = fetch_post_tags($r, false);
if ($portable_id && (! intval($items[0]['item_private']))) { if ($portable_id && (!intval($items[0]['item_private']))) {
$c = q("select abook_id from abook where abook_channel = %d and abook_xchan = '%s'", $c = q("select abook_id from abook where abook_channel = %d and abook_xchan = '%s'",
intval($items[0]['uid']), intval($items[0]['uid']),
dbesc($portable_id) dbesc($portable_id)
); );
if (! $c) { if (!$c) {
ThreadListener::store(z_root() . '/activity/' . $item_id,$portable_id); ThreadListener::store(z_root() . '/activity/' . $item_id, $portable_id);
} }
} }
$channel = channelx_by_n($items[0]['uid']); $channel = channelx_by_n($items[0]['uid']);
as_return_and_die(ZlibActivity::encode_activity($items[0],true),$channel); as_return_and_die(ZlibActivity::encode_activity($items[0], true), $channel);
} }
@ -109,7 +110,7 @@ class Activity extends Controller {
$item_id = argv(1); $item_id = argv(1);
if (! $item_id) { if (!$item_id) {
http_status_exit(404, 'Not found'); http_status_exit(404, 'Not found');
} }
@ -125,20 +126,20 @@ class Activity extends Controller {
dbesc(z_root() . '/activity/' . $item_id) dbesc(z_root() . '/activity/' . $item_id)
); );
if (! $r) { if (!$r) {
$r = q("select * from item where mid = '%s' $item_normal limit 1", $r = q("select * from item where mid = '%s' $item_normal limit 1",
dbesc(z_root() . '/item/' . $item_id) dbesc(z_root() . '/item/' . $item_id)
); );
if ($r) { if ($r) {
goaway(z_root() . '/item/' . $item_id); goaway(z_root() . '/item/' . $item_id);
} }
http_status_exit(404,'Not found'); http_status_exit(404, 'Not found');
} }
// process an authenticated fetch // process an authenticated fetch
$sigdata = HTTPSig::verify(EMPTY_STR); $sigdata = HTTPSig::verify(EMPTY_STR);
if($sigdata['portable_id'] && $sigdata['header_valid']) { if ($sigdata['portable_id'] && $sigdata['header_valid']) {
$portable_id = $sigdata['portable_id']; $portable_id = $sigdata['portable_id'];
observer_auth($portable_id); observer_auth($portable_id);
@ -157,7 +158,7 @@ class Activity extends Controller {
); );
if ($xchans) { if ($xchans) {
$hashes = ids_to_querystr($xchans,'xchan_hash',true); $hashes = ids_to_querystr($xchans, 'xchan_hash', true);
$i = q("select id as item_id from item where mid = '%s' $item_normal and owner_xchan in ( " . protect_sprintf($hashes) . " ) limit 1", $i = q("select id as item_id from item where mid = '%s' $item_normal and owner_xchan in ( " . protect_sprintf($hashes) . " ) limit 1",
dbesc($r[0]['parent_mid']) dbesc($r[0]['parent_mid'])
); );
@ -170,7 +171,7 @@ class Activity extends Controller {
$sql_extra = item_permissions_sql(0); $sql_extra = item_permissions_sql(0);
if (! $i) { if (!$i) {
$i = q("select id as item_id from item where mid = '%s' $item_normal $sql_extra order by item_wall desc limit 1", $i = q("select id as item_id from item where mid = '%s' $item_normal $sql_extra order by item_wall desc limit 1",
dbesc($r[0]['parent_mid']) dbesc($r[0]['parent_mid'])
); );
@ -179,7 +180,7 @@ class Activity extends Controller {
$bear = ZlibActivity::token_from_request(); $bear = ZlibActivity::token_from_request();
if ($bear) { if ($bear) {
logger('bear: ' . $bear, LOGGER_DEBUG); logger('bear: ' . $bear, LOGGER_DEBUG);
if (! $i) { if (!$i) {
$t = q("select * from iconfig where cat = 'ocap' and k = 'relay' and v = '%s'", $t = q("select * from iconfig where cat = 'ocap' and k = 'relay' and v = '%s'",
dbesc($bear) dbesc($bear)
); );
@ -193,49 +194,49 @@ class Activity extends Controller {
} }
if (! $i) { if (!$i) {
http_status_exit(403,'Forbidden'); http_status_exit(403, 'Forbidden');
} }
$parents_str = ids_to_querystr($i,'item_id'); $parents_str = ids_to_querystr($i, 'item_id');
$items = q("SELECT item.*, item.id AS item_id FROM item WHERE item.parent IN ( %s ) $item_normal ", $items = q("SELECT item.*, item.id AS item_id FROM item WHERE item.parent IN ( %s ) $item_normal ",
dbesc($parents_str) dbesc($parents_str)
); );
if(! $items) { if (!$items) {
http_status_exit(404, 'Not found'); http_status_exit(404, 'Not found');
} }
xchan_query($items,true); xchan_query($items, true);
$items = fetch_post_tags($items,true); $items = fetch_post_tags($items, true);
$observer = App::get_observer(); $observer = App::get_observer();
$parent = $items[0]; $parent = $items[0];
$recips = (($parent['owner']['xchan_network'] === 'activitypub') ? get_iconfig($parent['id'],'activitypub','recips', []) : []); $recips = (($parent['owner']['xchan_network'] === 'activitypub') ? get_iconfig($parent['id'], 'activitypub', 'recips', []) : []);
$to = (($recips && array_key_exists('to',$recips) && is_array($recips['to'])) ? $recips['to'] : null); $to = (($recips && array_key_exists('to', $recips) && is_array($recips['to'])) ? $recips['to'] : null);
$nitems = []; $nitems = [];
foreach($items as $i) { foreach ($items as $i) {
$mids = []; $mids = [];
if(intval($i['item_private'])) { if (intval($i['item_private'])) {
if(! $observer) { if (!$observer) {
continue; continue;
} }
// ignore private reshare, possibly from hubzilla // ignore private reshare, possibly from hubzilla
if($i['verb'] === 'Announce') { if ($i['verb'] === 'Announce') {
if(! in_array($i['thr_parent'],$mids)) { if (!in_array($i['thr_parent'], $mids)) {
$mids[] = $i['thr_parent']; $mids[] = $i['thr_parent'];
} }
continue; continue;
} }
// also ignore any children of the private reshares // also ignore any children of the private reshares
if(in_array($i['thr_parent'],$mids)) { if (in_array($i['thr_parent'], $mids)) {
continue; continue;
} }
if((! $to) || (! in_array($observer['xchan_url'],$to))) { if ((!$to) || (!in_array($observer['xchan_url'], $to))) {
continue; continue;
} }
@ -243,23 +244,23 @@ class Activity extends Controller {
$nitems[] = $i; $nitems[] = $i;
} }
if(! $nitems) if (!$nitems)
http_status_exit(404, 'Not found'); http_status_exit(404, 'Not found');
$chan = channelx_by_n($nitems[0]['uid']); $chan = channelx_by_n($nitems[0]['uid']);
if(! $chan) if (!$chan)
http_status_exit(404, 'Not found'); http_status_exit(404, 'Not found');
if(! perm_is_allowed($chan['channel_id'],get_observer_hash(),'view_stream')) if (!perm_is_allowed($chan['channel_id'], get_observer_hash(), 'view_stream'))
http_status_exit(403, 'Forbidden'); http_status_exit(403, 'Forbidden');
$i = ZlibActivity::encode_item_collection($nitems,'conversation/' . $item_id,'OrderedCollection',true, count($nitems)); $i = ZlibActivity::encode_item_collection($nitems, 'conversation/' . $item_id, 'OrderedCollection', true, count($nitems));
if ($portable_id && (! intval($items[0]['item_private']))) { if ($portable_id && (!intval($items[0]['item_private']))) {
ThreadListener::store(z_root() . '/activity/' . $item_id,$portable_id); ThreadListener::store(z_root() . '/activity/' . $item_id, $portable_id);
} }
if(! $i) if (!$i)
http_status_exit(404, 'Not found'); http_status_exit(404, 'Not found');
$x = array_merge(['@context' => [ $x = array_merge(['@context' => [
@ -269,12 +270,12 @@ class Activity extends Controller {
]], $i); ]], $i);
$headers = []; $headers = [];
$headers['Content-Type'] = 'application/x-zot+json' ; $headers['Content-Type'] = 'application/x-zot+json';
$x['signature'] = LDSignatures::sign($x,$chan); $x['signature'] = LDSignatures::sign($x, $chan);
$ret = json_encode($x, JSON_UNESCAPED_SLASHES); $ret = json_encode($x, JSON_UNESCAPED_SLASHES);
$headers['Digest'] = HTTPSig::generate_digest_header($ret); $headers['Digest'] = HTTPSig::generate_digest_header($ret);
$headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']) . ' ' . $_SERVER['REQUEST_URI']; $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']) . ' ' . $_SERVER['REQUEST_URI'];
$h = HTTPSig::create_sig($headers,$chan['channel_prvkey'],channel_url($chan)); $h = HTTPSig::create_sig($headers, $chan['channel_prvkey'], channel_url($chan));
HTTPSig::set_headers($h); HTTPSig::set_headers($h);
echo $ret; echo $ret;
killme(); killme();
@ -282,7 +283,6 @@ class Activity extends Controller {
} }
goaway(z_root() . '/item/' . argv(1)); goaway(z_root() . '/item/' . argv(1));
} }

View file

@ -18,20 +18,22 @@ use Zotlabs\Lib\Config;
* @brief Admin area. * @brief Admin area.
* *
*/ */
class Admin extends Controller
class Admin extends Controller { {
private $sm = null; private $sm = null;
function __construct() { public function __construct()
{
$this->sm = new SubModule(); $this->sm = new SubModule();
} }
function init() { public function init()
{
logger('admin_init', LOGGER_DEBUG); logger('admin_init', LOGGER_DEBUG);
if (! is_site_admin()) { if (!is_site_admin()) {
logger('admin denied.'); logger('admin denied.');
return; return;
} }
@ -42,11 +44,12 @@ class Admin extends Controller {
} }
function post() { public function post()
{
logger('admin_post', LOGGER_DEBUG); logger('admin_post', LOGGER_DEBUG);
if (! is_site_admin()) { if (!is_site_admin()) {
logger('admin denied.'); logger('admin denied.');
return; return;
} }
@ -62,11 +65,12 @@ class Admin extends Controller {
* @return string * @return string
*/ */
function get() { public function get()
{
logger('admin_content', LOGGER_DEBUG); logger('admin_content', LOGGER_DEBUG);
if (! is_site_admin()) { if (!is_site_admin()) {
logger('admin denied.'); logger('admin denied.');
return login(false); return login(false);
} }
@ -82,18 +86,16 @@ class Admin extends Controller {
if (argc() > 1) { if (argc() > 1) {
$o = $this->sm->call('get'); $o = $this->sm->call('get');
if ($o === false) { if ($o === false) {
notice( t('Item not found.') ); notice(t('Item not found.'));
} }
} } else {
else {
$o = $this->admin_page_summary(); $o = $this->admin_page_summary();
} }
if (is_ajax()) { if (is_ajax()) {
echo $o; echo $o;
killme(); killme();
} } else {
else {
return $o; return $o;
} }
} }
@ -105,7 +107,8 @@ class Admin extends Controller {
* @return string HTML from parsed admin_summary.tpl * @return string HTML from parsed admin_summary.tpl
*/ */
function admin_page_summary() { public function admin_page_summary()
{
// list total user accounts, expirations etc. // list total user accounts, expirations etc.
$accounts = []; $accounts = [];
@ -116,10 +119,10 @@ class Admin extends Controller {
intval(ACCOUNT_BLOCKED) intval(ACCOUNT_BLOCKED)
); );
if ($r) { if ($r) {
$accounts['total'] = [ 'label' => t('Accounts'), 'val' => $r[0]['total'] ]; $accounts['total'] = ['label' => t('Accounts'), 'val' => $r[0]['total']];
$accounts['blocked'] = [ 'label' => t('Blocked accounts'), 'val' => $r[0]['blocked'] ]; $accounts['blocked'] = ['label' => t('Blocked accounts'), 'val' => $r[0]['blocked']];
$accounts['expired'] = [ 'label' => t('Expired accounts'), 'val' => $r[0]['expired'] ]; $accounts['expired'] = ['label' => t('Expired accounts'), 'val' => $r[0]['expired']];
$accounts['expiring'] = [ 'label' => t('Expiring accounts'), 'val' => $r[0]['expiring'] ]; $accounts['expiring'] = ['label' => t('Expiring accounts'), 'val' => $r[0]['expiring']];
} }
// pending registrations // pending registrations
@ -134,15 +137,15 @@ class Admin extends Controller {
$channels = []; $channels = [];
$r = q("SELECT COUNT(*) AS total, COUNT(CASE WHEN channel_primary = 1 THEN 1 ELSE NULL END) AS main, COUNT(CASE WHEN channel_primary = 0 THEN 1 ELSE NULL END) AS clones FROM channel WHERE channel_removed = 0 and channel_system = 0"); $r = q("SELECT COUNT(*) AS total, COUNT(CASE WHEN channel_primary = 1 THEN 1 ELSE NULL END) AS main, COUNT(CASE WHEN channel_primary = 0 THEN 1 ELSE NULL END) AS clones FROM channel WHERE channel_removed = 0 and channel_system = 0");
if ($r) { if ($r) {
$channels['total'] = [ 'label' => t('Channels'), 'val' => $r[0]['total'] ]; $channels['total'] = ['label' => t('Channels'), 'val' => $r[0]['total']];
$channels['main'] = [ 'label' => t('Primary'), 'val' => $r[0]['main'] ]; $channels['main'] = ['label' => t('Primary'), 'val' => $r[0]['main']];
$channels['clones'] = [ 'label' => t('Clones'), 'val' => $r[0]['clones'] ]; $channels['clones'] = ['label' => t('Clones'), 'val' => $r[0]['clones']];
} }
// We can do better, but this is a quick queue status // We can do better, but this is a quick queue status
$r = q("SELECT COUNT(outq_delivered) AS total FROM outq WHERE outq_delivered = 0"); $r = q("SELECT COUNT(outq_delivered) AS total FROM outq WHERE outq_delivered = 0");
$queue = (($r) ? $r[0]['total'] : 0); $queue = (($r) ? $r[0]['total'] : 0);
$queues = [ 'label' => t('Message queues'), 'queue' => $queue ]; $queues = ['label' => t('Message queues'), 'queue' => $queue];
$plugins = []; $plugins = [];
@ -153,8 +156,7 @@ class Admin extends Controller {
} }
} }
sort($plugins); sort($plugins);
} } else {
else {
$plugins = 0; $plugins = 0;
} }
@ -164,10 +166,10 @@ class Admin extends Controller {
$upgrade = EMPTY_STR; $upgrade = EMPTY_STR;
if((! defined('PLATFORM_ARCHITECTURE')) || (PLATFORM_ARCHITECTURE === 'zap')) { if ((!defined('PLATFORM_ARCHITECTURE')) || (PLATFORM_ARCHITECTURE === 'zap')) {
$vrelease = get_repository_version('release'); $vrelease = get_repository_version('release');
$vdev = get_repository_version('dev'); $vdev = get_repository_version('dev');
$upgrade = ((version_compare(STD_VERSION,$vrelease) < 0) ? t('Your software should be updated') : ''); $upgrade = ((version_compare(STD_VERSION, $vrelease) < 0) ? t('Your software should be updated') : '');
} }
$t = get_markup_template('admin_summary.tpl'); $t = get_markup_template('admin_summary.tpl');
@ -176,13 +178,13 @@ class Admin extends Controller {
'$page' => t('Summary'), '$page' => t('Summary'),
'$adminalertmsg' => $alertmsg, '$adminalertmsg' => $alertmsg,
'$queues' => $queues, '$queues' => $queues,
'$accounts' => [ t('Registered accounts'), $accounts ], '$accounts' => [t('Registered accounts'), $accounts],
'$pending' => [ t('Pending registrations'), $pending ], '$pending' => [t('Pending registrations'), $pending],
'$channels' => [ t('Registered channels'), $channels ], '$channels' => [t('Registered channels'), $channels],
'$plugins' => (($plugins) ? [ t('Active addons'), $plugins ] : EMPTY_STR), '$plugins' => (($plugins) ? [t('Active addons'), $plugins] : EMPTY_STR),
'$version' => [ t('Version'), STD_VERSION ], '$version' => [t('Version'), STD_VERSION],
'$vmaster' => [ t('Repository version (release)'), $vrelease ], '$vmaster' => [t('Repository version (release)'), $vrelease],
'$vdev' => [ t('Repository version (dev)'), $vdev ], '$vdev' => [t('Repository version (dev)'), $vdev],
'$upgrade' => $upgrade, '$upgrade' => $upgrade,
'$build' => Config::Get('system', 'db_version') '$build' => Config::Get('system', 'db_version')
]); ]);

View file

@ -3,19 +3,20 @@
namespace Zotlabs\Module\Admin; namespace Zotlabs\Module\Admin;
class Account_edit
{
class Account_edit { public function post()
{
function post() {
$account_id = $_REQUEST['aid']; $account_id = $_REQUEST['aid'];
if(! $account_id) if (!$account_id)
return; return;
$pass1 = trim($_REQUEST['pass1']); $pass1 = trim($_REQUEST['pass1']);
$pass2 = trim($_REQUEST['pass2']); $pass2 = trim($_REQUEST['pass2']);
if($pass1 && $pass2 && ($pass1 === $pass2)) { if ($pass1 && $pass2 && ($pass1 === $pass2)) {
$salt = random_string(32); $salt = random_string(32);
$password_encoded = hash('whirlpool', $salt . $pass1); $password_encoded = hash('whirlpool', $salt . $pass1);
$r = q("update account set account_salt = '%s', account_password = '%s', $r = q("update account set account_salt = '%s', account_password = '%s',
@ -25,8 +26,8 @@ class Account_edit {
dbesc(datetime_convert()), dbesc(datetime_convert()),
intval($account_id) intval($account_id)
); );
if($r) if ($r)
info( sprintf( t('Password changed for account %d.'), $account_id). EOL); info(sprintf(t('Password changed for account %d.'), $account_id) . EOL);
} }
@ -40,23 +41,24 @@ class Account_edit {
intval($account_id) intval($account_id)
); );
if($r) if ($r)
info( t('Account settings updated.') . EOL); info(t('Account settings updated.') . EOL);
goaway(z_root() . '/admin/accounts'); goaway(z_root() . '/admin/accounts');
} }
function get() { public function get()
if(argc() > 2) {
if (argc() > 2)
$account_id = argv(2); $account_id = argv(2);
$x = q("select * from account where account_id = %d limit 1", $x = q("select * from account where account_id = %d limit 1",
intval($account_id) intval($account_id)
); );
if(! $x) { if (!$x) {
notice ( t('Account not found.') . EOL); notice(t('Account not found.') . EOL);
return ''; return '';
} }
@ -64,10 +66,10 @@ class Account_edit {
$a = replace_macros(get_markup_template('admin_account_edit.tpl'), [ $a = replace_macros(get_markup_template('admin_account_edit.tpl'), [
'$account' => $x[0], '$account' => $x[0],
'$title' => t('Account Edit'), '$title' => t('Account Edit'),
'$pass1' => [ 'pass1', t('New Password'), ' ','' ], '$pass1' => ['pass1', t('New Password'), ' ', ''],
'$pass2' => [ 'pass2', t('New Password again'), ' ','' ], '$pass2' => ['pass2', t('New Password again'), ' ', ''],
'$account_language' => [ 'account_language' , t('Account language (for emails)'), $x[0]['account_language'], '', language_list() ], '$account_language' => ['account_language', t('Account language (for emails)'), $x[0]['account_language'], '', language_list()],
'$service_class' => [ 'service_class', t('Service class'), $x[0]['account_service_class'], '' ], '$service_class' => ['service_class', t('Service class'), $x[0]['account_service_class'], ''],
'$submit' => t('Submit'), '$submit' => t('Submit'),
] ]
); );

View file

@ -4,7 +4,8 @@ namespace Zotlabs\Module\Admin;
use App; use App;
class Accounts { class Accounts
{
/** /**
* @brief Handle POST actions on accounts admin page. * @brief Handle POST actions on accounts admin page.
@ -15,11 +16,12 @@ class Accounts {
* *
*/ */
function post() { public function post()
{
$pending = ( x($_POST, 'pending') ? $_POST['pending'] : [] ); $pending = (x($_POST, 'pending') ? $_POST['pending'] : []);
$users = ( x($_POST, 'user') ? $_POST['user'] : [] ); $users = (x($_POST, 'user') ? $_POST['user'] : []);
$blocked = ( x($_POST, 'blocked') ? $_POST['blocked'] : [] ); $blocked = (x($_POST, 'blocked') ? $_POST['blocked'] : []);
check_form_security_token_redirectOnErr('/admin/accounts', 'admin_accounts'); check_form_security_token_redirectOnErr('/admin/accounts', 'admin_accounts');
@ -34,15 +36,15 @@ class Accounts {
intval($users[$i]) intval($users[$i])
); );
} }
notice( sprintf( tt("%s account blocked/unblocked", "%s accounts blocked/unblocked", count($users)), count($users)) ); notice(sprintf(tt("%s account blocked/unblocked", "%s accounts blocked/unblocked", count($users)), count($users)));
} }
// account delete button was submitted // account delete button was submitted
if (x($_POST, 'page_accounts_delete')) { if (x($_POST, 'page_accounts_delete')) {
foreach ($users as $uid){ foreach ($users as $uid) {
account_remove($uid, true, false); account_remove($uid, true, false);
} }
notice( sprintf( tt("%s account deleted", "%s accounts deleted", count($users)), count($users)) ); notice(sprintf(tt("%s account deleted", "%s accounts deleted", count($users)), count($users)));
} }
// registration approved button was submitted // registration approved button was submitted
@ -59,7 +61,7 @@ class Accounts {
} }
} }
goaway(z_root() . '/admin/accounts' ); goaway(z_root() . '/admin/accounts');
} }
/** /**
@ -72,16 +74,17 @@ class Accounts {
* @return string * @return string
*/ */
function get(){ public function get()
{
if (argc() > 2) { if (argc() > 2) {
$uid = argv(3); $uid = argv(3);
$account = q("SELECT * FROM account WHERE account_id = %d", $account = q("SELECT * FROM account WHERE account_id = %d",
intval($uid) intval($uid)
); );
if (! $account) { if (!$account) {
notice( t('Account not found') . EOL); notice(t('Account not found') . EOL);
goaway(z_root() . '/admin/accounts' ); goaway(z_root() . '/admin/accounts');
} }
check_form_security_token_redirectOnErr('/admin/accounts', 'admin_accounts', 't'); check_form_security_token_redirectOnErr('/admin/accounts', 'admin_accounts', 't');
@ -89,9 +92,9 @@ class Accounts {
switch (argv(2)) { switch (argv(2)) {
case 'delete': case 'delete':
// delete user // delete user
account_remove($uid,true,false); account_remove($uid, true, false);
notice( sprintf(t("Account '%s' deleted"), $account[0]['account_email']) . EOL); notice(sprintf(t("Account '%s' deleted"), $account[0]['account_email']) . EOL);
break; break;
case 'block': case 'block':
q("UPDATE account SET account_flags = ( account_flags | %d ) WHERE account_id = %d", q("UPDATE account SET account_flags = ( account_flags | %d ) WHERE account_id = %d",
@ -99,7 +102,7 @@ class Accounts {
intval($uid) intval($uid)
); );
notice( sprintf( t("Account '%s' blocked") , $account[0]['account_email']) . EOL); notice(sprintf(t("Account '%s' blocked"), $account[0]['account_email']) . EOL);
break; break;
case 'unblock': case 'unblock':
q("UPDATE account SET account_flags = ( account_flags & ~ %d ) WHERE account_id = %d", q("UPDATE account SET account_flags = ( account_flags & ~ %d ) WHERE account_id = %d",
@ -107,11 +110,11 @@ class Accounts {
intval($uid) intval($uid)
); );
notice( sprintf( t("Account '%s' unblocked"), $account[0]['account_email']) . EOL); notice(sprintf(t("Account '%s' unblocked"), $account[0]['account_email']) . EOL);
break; break;
} }
goaway(z_root() . '/admin/accounts' ); goaway(z_root() . '/admin/accounts');
} }
/* get pending */ /* get pending */
@ -131,7 +134,7 @@ class Accounts {
$key = (($_REQUEST['key']) ? dbesc($_REQUEST['key']) : 'account_id'); $key = (($_REQUEST['key']) ? dbesc($_REQUEST['key']) : 'account_id');
$dir = 'asc'; $dir = 'asc';
if (array_key_exists('dir',$_REQUEST)) { if (array_key_exists('dir', $_REQUEST)) {
$dir = ((intval($_REQUEST['dir'])) ? 'asc' : 'desc'); $dir = ((intval($_REQUEST['dir'])) ? 'asc' : 'desc');
} }
@ -149,14 +152,14 @@ class Accounts {
); );
if ($users) { if ($users) {
for($x = 0; $x < count($users); $x ++) { for ($x = 0; $x < count($users); $x++) {
$channel_arr = explode(' ',$users[$x]['channels']); $channel_arr = explode(' ', $users[$x]['channels']);
if ($channel_arr) { if ($channel_arr) {
$linked = []; $linked = [];
foreach ( $channel_arr as $c) { foreach ($channel_arr as $c) {
$linked[] = '<a href="' . z_root() . '/channel/' . $c . '">' . $c . '</a>'; $linked[] = '<a href="' . z_root() . '/channel/' . $c . '">' . $c . '</a>';
} }
$users[$x]['channels'] = implode(' ',$linked); $users[$x]['channels'] = implode(' ', $linked);
} }
} }
} }
@ -168,7 +171,7 @@ class Accounts {
'$submit' => t('Submit'), '$submit' => t('Submit'),
'$select_all' => t('select all'), '$select_all' => t('select all'),
'$h_pending' => t('Registrations waiting for confirm'), '$h_pending' => t('Registrations waiting for confirm'),
'$th_pending' => array( t('Request date'), t('Email') ), '$th_pending' => array(t('Request date'), t('Email')),
'$no_pending' => t('No registrations.'), '$no_pending' => t('No registrations.'),
'$approve' => t('Approve'), '$approve' => t('Approve'),
'$deny' => t('Deny'), '$deny' => t('Deny'),
@ -179,13 +182,13 @@ class Accounts {
'$base' => $base, '$base' => $base,
'$h_users' => t('Accounts'), '$h_users' => t('Accounts'),
'$th_users' => [ '$th_users' => [
[ t('ID'), 'account_id' ], [t('ID'), 'account_id'],
[ t('Email'), 'account_email' ], [t('Email'), 'account_email'],
[ t('All Channels'), 'channels' ], [t('All Channels'), 'channels'],
[ t('Register date'), 'account_created' ], [t('Register date'), 'account_created'],
[ t('Last login'), 'account_lastlog' ], [t('Last login'), 'account_lastlog'],
[ t('Expires'), 'account_expires' ], [t('Expires'), 'account_expires'],
[ t('Service Class'), 'account_service_class'] [t('Service Class'), 'account_service_class']
], ],
'$confirm_delete_multi' => t('Selected accounts will be deleted!\n\nEverything these accounts had posted on this site will be permanently deleted!\n\nAre you sure?'), '$confirm_delete_multi' => t('Selected accounts will be deleted!\n\nEverything these accounts had posted on this site will be permanently deleted!\n\nAre you sure?'),
'$confirm_delete' => t('The account {0} will be deleted!\n\nEverything this account has posted on this site will be permanently deleted!\n\nAre you sure?'), '$confirm_delete' => t('The account {0} will be deleted!\n\nEverything this account has posted on this site will be permanently deleted!\n\nAre you sure?'),

View file

@ -7,30 +7,30 @@ use PHPGit\Exception\GitException;
use Zotlabs\Storage\GitRepo; use Zotlabs\Storage\GitRepo;
use Michelf\MarkdownExtra; use Michelf\MarkdownExtra;
class Addons { class Addons
{
/** /**
* @brief * @brief
* *
*/ */
function post() { public function post()
{
if(argc() > 2 && is_file("addon/" . argv(2) . "/" . argv(2) . ".php")) { if (argc() > 2 && is_file("addon/" . argv(2) . "/" . argv(2) . ".php")) {
@include_once("addon/" . argv(2) . "/" . argv(2) . ".php"); @include_once("addon/" . argv(2) . "/" . argv(2) . ".php");
if(function_exists(argv(2).'_plugin_admin_post')) { if (function_exists(argv(2) . '_plugin_admin_post')) {
$func = argv(2) . '_plugin_admin_post'; $func = argv(2) . '_plugin_admin_post';
$func($a); $func($a);
} }
goaway(z_root() . '/admin/addons/' . argv(2) ); goaway(z_root() . '/admin/addons/' . argv(2));
} } elseif (argc() > 2) {
elseif(argc() > 2) { switch (argv(2)) {
switch(argv(2)) {
case 'updaterepo': case 'updaterepo':
if (array_key_exists('repoName', $_REQUEST)) { if (array_key_exists('repoName', $_REQUEST)) {
$repoName = $_REQUEST['repoName']; $repoName = $_REQUEST['repoName'];
} } else {
else {
json_return_and_die(array('message' => 'No repo name provided.', 'success' => false)); json_return_and_die(array('message' => 'No repo name provided.', 'success' => false));
} }
$extendDir = 'cache/git/sys/extend'; $extendDir = 'cache/git/sys/extend';
@ -39,8 +39,7 @@ class Addons {
if (!mkdir($extendDir, 0770, true)) { if (!mkdir($extendDir, 0770, true)) {
logger('Error creating extend folder: ' . $extendDir); logger('Error creating extend folder: ' . $extendDir);
json_return_and_die(array('message' => 'Error creating extend folder: ' . $extendDir, 'success' => false)); json_return_and_die(array('message' => 'Error creating extend folder: ' . $extendDir, 'success' => false));
} } else {
else {
if (!symlink(realpath('extend/addon'), $addonDir)) { if (!symlink(realpath('extend/addon'), $addonDir)) {
logger('Error creating symlink to addon folder: ' . $addonDir); logger('Error creating symlink to addon folder: ' . $addonDir);
json_return_and_die(array('message' => 'Error creating symlink to addon folder: ' . $addonDir, 'success' => false)); json_return_and_die(array('message' => 'Error creating symlink to addon folder: ' . $addonDir, 'success' => false));
@ -247,16 +246,17 @@ class Addons {
* *
* @return string with parsed HTML * @return string with parsed HTML
*/ */
function get() { public function get()
{
/* /*
* Single plugin * Single plugin
*/ */
if (App::$argc == 3){ if (App::$argc == 3) {
$plugin = App::$argv[2]; $plugin = App::$argv[2];
if (!is_file("addon/$plugin/$plugin.php")){ if (!is_file("addon/$plugin/$plugin.php")) {
notice( t("Item not found.") ); notice(t("Item not found."));
return ''; return '';
} }
@ -266,46 +266,46 @@ class Addons {
// disable plugins which are installed but incompatible versions // disable plugins which are installed but incompatible versions
if($enabled && ! $x) { if ($enabled && !$x) {
$enabled = false; $enabled = false;
$idz = array_search($plugin, App::$plugins); $idz = array_search($plugin, App::$plugins);
if ($idz !== false) { if ($idz !== false) {
unset(App::$plugins[$idz]); unset(App::$plugins[$idz]);
uninstall_plugin($plugin); uninstall_plugin($plugin);
set_config("system","addon", implode(", ", App::$plugins)); set_config("system", "addon", implode(", ", App::$plugins));
} }
} }
$info['disabled'] = 1-intval($x); $info['disabled'] = 1 - intval($x);
if (x($_GET,"a") && $_GET['a']=="t"){ if (x($_GET, "a") && $_GET['a'] == "t") {
check_form_security_token_redirectOnErr('/admin/addons', 'admin_addons', 't'); check_form_security_token_redirectOnErr('/admin/addons', 'admin_addons', 't');
$pinstalled = false; $pinstalled = false;
// Toggle plugin status // Toggle plugin status
$idx = array_search($plugin, App::$plugins); $idx = array_search($plugin, App::$plugins);
if ($idx !== false){ if ($idx !== false) {
unset(App::$plugins[$idx]); unset(App::$plugins[$idx]);
uninstall_plugin($plugin); uninstall_plugin($plugin);
$pinstalled = false; $pinstalled = false;
info( sprintf( t("Plugin %s disabled."), $plugin ) ); info(sprintf(t("Plugin %s disabled."), $plugin));
} else { } else {
App::$plugins[] = $plugin; App::$plugins[] = $plugin;
install_plugin($plugin); install_plugin($plugin);
$pinstalled = true; $pinstalled = true;
info( sprintf( t("Plugin %s enabled."), $plugin ) ); info(sprintf(t("Plugin %s enabled."), $plugin));
} }
set_config("system","addon", implode(", ", App::$plugins)); set_config("system", "addon", implode(", ", App::$plugins));
if($pinstalled) { if ($pinstalled) {
@require_once("addon/$plugin/$plugin.php"); @require_once("addon/$plugin/$plugin.php");
if(function_exists($plugin.'_plugin_admin')) if (function_exists($plugin . '_plugin_admin'))
goaway(z_root() . '/admin/addons/' . $plugin); goaway(z_root() . '/admin/addons/' . $plugin);
} }
goaway(z_root() . '/admin/addons' ); goaway(z_root() . '/admin/addons');
} }
// display plugin details // display plugin details
if (in_array($plugin, App::$plugins)){ if (in_array($plugin, App::$plugins)) {
$status = 'on'; $status = 'on';
$action = t('Disable'); $action = t('Disable');
} else { } else {
@ -314,11 +314,11 @@ class Addons {
} }
$readme = null; $readme = null;
if (is_file("addon/$plugin/README.md")){ if (is_file("addon/$plugin/README.md")) {
$readme = file_get_contents("addon/$plugin/README.md"); $readme = file_get_contents("addon/$plugin/README.md");
$readme = MarkdownExtra::defaultTransform($readme); $readme = MarkdownExtra::defaultTransform($readme);
} else if (is_file("addon/$plugin/README")){ } else if (is_file("addon/$plugin/README")) {
$readme = "<pre>". file_get_contents("addon/$plugin/README") ."</pre>"; $readme = "<pre>" . file_get_contents("addon/$plugin/README") . "</pre>";
} }
$admin_form = ''; $admin_form = '';
@ -327,10 +327,10 @@ class Addons {
dbesc($plugin) dbesc($plugin)
); );
if($r) { if ($r) {
@require_once("addon/$plugin/$plugin.php"); @require_once("addon/$plugin/$plugin.php");
if(function_exists($plugin.'_plugin_admin')) { if (function_exists($plugin . '_plugin_admin')) {
$func = $plugin.'_plugin_admin'; $func = $plugin . '_plugin_admin';
$func($a, $admin_form); $func($a, $admin_form);
} }
} }
@ -372,12 +372,12 @@ class Addons {
*/ */
$plugins = []; $plugins = [];
$files = glob('addon/*/'); $files = glob('addon/*/');
if($files) { if ($files) {
foreach($files as $file) { foreach ($files as $file) {
if ($file === 'addon/vendor/') { if ($file === 'addon/vendor/') {
continue; continue;
} }
if (is_dir($file)){ if (is_dir($file)) {
list($tmp, $id) = array_map('trim', explode('/', $file)); list($tmp, $id) = array_map('trim', explode('/', $file));
$info = get_plugin_info($id); $info = get_plugin_info($id);
$enabled = in_array($id, App::$plugins); $enabled = in_array($id, App::$plugins);
@ -385,30 +385,30 @@ class Addons {
// disable plugins which are installed but incompatible versions // disable plugins which are installed but incompatible versions
if($enabled && ! $x) { if ($enabled && !$x) {
$enabled = false; $enabled = false;
$idz = array_search($id, App::$plugins); $idz = array_search($id, App::$plugins);
if ($idz !== false) { if ($idz !== false) {
unset(App::$plugins[$idz]); unset(App::$plugins[$idz]);
uninstall_plugin($id); uninstall_plugin($id);
set_config("system","addon", implode(", ", App::$plugins)); set_config("system", "addon", implode(", ", App::$plugins));
} }
} }
$info['disabled'] = 1-intval($x); $info['disabled'] = 1 - intval($x);
$plugins[] = array( $id, (($enabled)?"on":"off") , $info); $plugins[] = array($id, (($enabled) ? "on" : "off"), $info);
} }
} }
} }
usort($plugins,'self::plugin_sort'); usort($plugins, 'self::plugin_sort');
$allowManageRepos = false; $allowManageRepos = false;
if(is_writable('extend/addon') && is_writable('cache')) { if (is_writable('extend/addon') && is_writable('cache')) {
$allowManageRepos = true; $allowManageRepos = true;
} }
$admin_plugins_add_repo_form= replace_macros( $admin_plugins_add_repo_form = replace_macros(
get_markup_template('admin_plugins_addrepo.tpl'), array( get_markup_template('admin_plugins_addrepo.tpl'), array(
'$post' => 'admin/addons/addrepo', '$post' => 'admin/addons/addrepo',
'$desc' => t('Enter the public git repository URL of the addon repo.'), '$desc' => t('Enter the public git repository URL of the addon repo.'),
@ -429,7 +429,7 @@ class Addons {
$reponames = $this->listAddonRepos(); $reponames = $this->listAddonRepos();
$addonrepos = []; $addonrepos = [];
foreach($reponames as $repo) { foreach ($reponames as $repo) {
$addonrepos[] = array('name' => $repo, 'description' => ''); $addonrepos[] = array('name' => $repo, 'description' => '');
/// @TODO Parse repo info to provide more information about repos /// @TODO Parse repo info to provide more information about repos
} }
@ -459,10 +459,11 @@ class Addons {
)); ));
} }
function listAddonRepos() { public function listAddonRepos()
{
$addonrepos = []; $addonrepos = [];
$addonDir = 'extend/addon/'; $addonDir = 'extend/addon/';
if(is_dir($addonDir)) { if (is_dir($addonDir)) {
if ($handle = opendir($addonDir)) { if ($handle = opendir($addonDir)) {
while (false !== ($entry = readdir($handle))) { while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") { if ($entry != "." && $entry != "..") {
@ -475,8 +476,9 @@ class Addons {
return $addonrepos; return $addonrepos;
} }
static public function plugin_sort($a,$b) { public static function plugin_sort($a, $b)
return(strcmp(strtolower($a[2]['name']),strtolower($b[2]['name']))); {
return (strcmp(strtolower($a[2]['name']), strtolower($b[2]['name'])));
} }
} }

View file

@ -9,48 +9,49 @@ use Zotlabs\Daemon\Run;
* @brief Admin Module for Channels. * @brief Admin Module for Channels.
* *
*/ */
class Channels
class Channels { {
/** /**
* @brief Handle POST actions on channels admin page. * @brief Handle POST actions on channels admin page.
* *
*/ */
function post() { public function post()
{
$channels = ( x($_POST, 'channel') ? $_POST['channel'] : Array() ); $channels = (x($_POST, 'channel') ? $_POST['channel'] : array());
check_form_security_token_redirectOnErr('/admin/channels', 'admin_channels'); check_form_security_token_redirectOnErr('/admin/channels', 'admin_channels');
$xor = db_getfunc('^'); $xor = db_getfunc('^');
if(x($_POST, 'page_channels_block')) { if (x($_POST, 'page_channels_block')) {
foreach($channels as $uid) { foreach ($channels as $uid) {
q("UPDATE channel SET channel_pageflags = ( channel_pageflags $xor %d ) where channel_id = %d", q("UPDATE channel SET channel_pageflags = ( channel_pageflags $xor %d ) where channel_id = %d",
intval(PAGE_CENSORED), intval(PAGE_CENSORED),
intval( $uid ) intval($uid)
); );
Run::Summon( [ 'Directory', $uid, 'nopush' ] ); Run::Summon(['Directory', $uid, 'nopush']);
} }
notice( sprintf( tt("%s channel censored/uncensored", "%s channels censored/uncensored", count($channels)), count($channels)) ); notice(sprintf(tt("%s channel censored/uncensored", "%s channels censored/uncensored", count($channels)), count($channels)));
} }
if(x($_POST, 'page_channels_code')) { if (x($_POST, 'page_channels_code')) {
foreach($channels as $uid) { foreach ($channels as $uid) {
q("UPDATE channel SET channel_pageflags = ( channel_pageflags $xor %d ) where channel_id = %d", q("UPDATE channel SET channel_pageflags = ( channel_pageflags $xor %d ) where channel_id = %d",
intval(PAGE_ALLOWCODE), intval(PAGE_ALLOWCODE),
intval( $uid ) intval($uid)
); );
} }
notice( sprintf( tt("%s channel code allowed/disallowed", "%s channels code allowed/disallowed", count($channels)), count($channels)) ); notice(sprintf(tt("%s channel code allowed/disallowed", "%s channels code allowed/disallowed", count($channels)), count($channels)));
} }
if(x($_POST, 'page_channels_delete')) { if (x($_POST, 'page_channels_delete')) {
foreach($channels as $uid) { foreach ($channels as $uid) {
channel_remove($uid, true); channel_remove($uid, true);
} }
notice( sprintf( tt("%s channel deleted", "%s channels deleted", count($channels)), count($channels)) ); notice(sprintf(tt("%s channel deleted", "%s channels deleted", count($channels)), count($channels)));
} }
goaway(z_root() . '/admin/channels' ); goaway(z_root() . '/admin/channels');
} }
/** /**
@ -58,62 +59,66 @@ class Channels {
* *
* @return string with parsed HTML * @return string with parsed HTML
*/ */
function get() { public function get()
if(argc() > 2) { {
if (argc() > 2) {
$uid = argv(3); $uid = argv(3);
$channel = q("SELECT * FROM channel WHERE channel_id = %d", $channel = q("SELECT * FROM channel WHERE channel_id = %d",
intval($uid) intval($uid)
); );
if(! $channel) { if (!$channel) {
notice( t('Channel not found') . EOL); notice(t('Channel not found') . EOL);
goaway(z_root() . '/admin/channels' ); goaway(z_root() . '/admin/channels');
} }
switch(argv(2)) { switch (argv(2)) {
case "delete":{ case "delete":
{
check_form_security_token_redirectOnErr('/admin/channels', 'admin_channels', 't'); check_form_security_token_redirectOnErr('/admin/channels', 'admin_channels', 't');
// delete channel // delete channel
channel_remove($uid,true); channel_remove($uid, true);
notice( sprintf(t("Channel '%s' deleted"), $channel[0]['channel_name']) . EOL); notice(sprintf(t("Channel '%s' deleted"), $channel[0]['channel_name']) . EOL);
} }
break; break;
case "block":{ case "block":
{
check_form_security_token_redirectOnErr('/admin/channels', 'admin_channels', 't'); check_form_security_token_redirectOnErr('/admin/channels', 'admin_channels', 't');
$pflags = $channel[0]['channel_pageflags'] ^ PAGE_CENSORED; $pflags = $channel[0]['channel_pageflags'] ^ PAGE_CENSORED;
q("UPDATE channel SET channel_pageflags = %d where channel_id = %d", q("UPDATE channel SET channel_pageflags = %d where channel_id = %d",
intval($pflags), intval($pflags),
intval( $uid ) intval($uid)
); );
Run::Summon( [ 'Directory', $uid, 'nopush' ]); Run::Summon(['Directory', $uid, 'nopush']);
notice( sprintf( (($pflags & PAGE_CENSORED) ? t("Channel '%s' censored"): t("Channel '%s' uncensored")) , $channel[0]['channel_name'] . ' (' . $channel[0]['channel_address'] . ')' ) . EOL); notice(sprintf((($pflags & PAGE_CENSORED) ? t("Channel '%s' censored") : t("Channel '%s' uncensored")), $channel[0]['channel_name'] . ' (' . $channel[0]['channel_address'] . ')') . EOL);
} }
break; break;
case "code":{ case "code":
{
check_form_security_token_redirectOnErr('/admin/channels', 'admin_channels', 't'); check_form_security_token_redirectOnErr('/admin/channels', 'admin_channels', 't');
$pflags = $channel[0]['channel_pageflags'] ^ PAGE_ALLOWCODE; $pflags = $channel[0]['channel_pageflags'] ^ PAGE_ALLOWCODE;
q("UPDATE channel SET channel_pageflags = %d where channel_id = %d", q("UPDATE channel SET channel_pageflags = %d where channel_id = %d",
intval($pflags), intval($pflags),
intval( $uid ) intval($uid)
); );
notice( sprintf( (($pflags & PAGE_ALLOWCODE) ? t("Channel '%s' code allowed"): t("Channel '%s' code disallowed")) , $channel[0]['channel_name'] . ' (' . $channel[0]['channel_address'] . ')' ) . EOL); notice(sprintf((($pflags & PAGE_ALLOWCODE) ? t("Channel '%s' code allowed") : t("Channel '%s' code disallowed")), $channel[0]['channel_name'] . ' (' . $channel[0]['channel_address'] . ')') . EOL);
} }
break; break;
default: default:
break; break;
} }
goaway(z_root() . '/admin/channels' ); goaway(z_root() . '/admin/channels');
} }
$key = (($_REQUEST['key']) ? dbesc($_REQUEST['key']) : 'channel_id'); $key = (($_REQUEST['key']) ? dbesc($_REQUEST['key']) : 'channel_id');
$dir = 'asc'; $dir = 'asc';
if(array_key_exists('dir',$_REQUEST)) if (array_key_exists('dir', $_REQUEST))
$dir = ((intval($_REQUEST['dir'])) ? 'asc' : 'desc'); $dir = ((intval($_REQUEST['dir'])) ? 'asc' : 'desc');
$base = z_root() . '/admin/channels?f='; $base = z_root() . '/admin/channels?f=';
@ -122,7 +127,7 @@ class Channels {
/* get channels */ /* get channels */
$total = q("SELECT count(*) as total FROM channel where channel_removed = 0 and channel_system = 0"); $total = q("SELECT count(*) as total FROM channel where channel_removed = 0 and channel_system = 0");
if($total) { if ($total) {
App::set_pager_total($total[0]['total']); App::set_pager_total($total[0]['total']);
App::set_pager_itemspage(100); App::set_pager_itemspage(100);
} }
@ -132,14 +137,14 @@ class Channels {
intval(App::$pager['start']) intval(App::$pager['start'])
); );
if($channels) { if ($channels) {
for($x = 0; $x < count($channels); $x ++) { for ($x = 0; $x < count($channels); $x++) {
if($channels[$x]['channel_pageflags'] & PAGE_CENSORED) if ($channels[$x]['channel_pageflags'] & PAGE_CENSORED)
$channels[$x]['blocked'] = true; $channels[$x]['blocked'] = true;
else else
$channels[$x]['blocked'] = false; $channels[$x]['blocked'] = false;
if($channels[$x]['channel_pageflags'] & PAGE_ALLOWCODE) if ($channels[$x]['channel_pageflags'] & PAGE_ALLOWCODE)
$channels[$x]['allowcode'] = true; $channels[$x]['allowcode'] = true;
else else
$channels[$x]['allowcode'] = false; $channels[$x]['allowcode'] = false;
@ -148,7 +153,7 @@ class Channels {
} }
} }
call_hooks('admin_channels',$channels); call_hooks('admin_channels', $channels);
$o = replace_macros(get_markup_template('admin_channels.tpl'), [ $o = replace_macros(get_markup_template('admin_channels.tpl'), [
// strings // // strings //
@ -165,9 +170,9 @@ class Channels {
'$base' => $base, '$base' => $base,
'$odir' => $odir, '$odir' => $odir,
'$th_channels' => array( '$th_channels' => array(
[ t('UID'), 'channel_id' ], [t('UID'), 'channel_id'],
[ t('Name'), 'channel_name' ], [t('Name'), 'channel_name'],
[ t('Address'), 'channel_address' ]), [t('Address'), 'channel_address']),
'$confirm_delete_multi' => t('Selected channels will be deleted!\n\nEverything that was posted in these channels on this site will be permanently deleted!\n\nAre you sure?'), '$confirm_delete_multi' => t('Selected channels will be deleted!\n\nEverything that was posted in these channels on this site will be permanently deleted!\n\nAre you sure?'),
'$confirm_delete' => t('The channel {0} will be deleted!\n\nEverything that was posted in this channel on this site will be permanently deleted!\n\nAre you sure?'), '$confirm_delete' => t('The channel {0} will be deleted!\n\nEverything that was posted in this channel on this site will be permanently deleted!\n\nAre you sure?'),

View file

@ -25,12 +25,12 @@ require_once('include/photos.php');
* @return void * @return void
* *
*/ */
class Cover_photo
{
public function init()
class Cover_photo { {
if (!is_site_admin()) {
function init() {
if (! is_site_admin()) {
return; return;
} }
@ -45,9 +45,10 @@ class Cover_photo {
* *
*/ */
function post() { public function post()
{
if (! is_site_admin()) { if (!is_site_admin()) {
return; return;
} }
@ -55,24 +56,23 @@ class Cover_photo {
check_form_security_token_redirectOnErr('/admin/cover_photo', 'cover_photo'); check_form_security_token_redirectOnErr('/admin/cover_photo', 'cover_photo');
if ((array_key_exists('cropfinal',$_POST)) && ($_POST['cropfinal'] == 1)) { if ((array_key_exists('cropfinal', $_POST)) && ($_POST['cropfinal'] == 1)) {
// phase 2 - we have finished cropping // phase 2 - we have finished cropping
if (argc() != 3) { if (argc() != 3) {
notice( t('Image uploaded but image cropping failed.') . EOL ); notice(t('Image uploaded but image cropping failed.') . EOL);
return; return;
} }
$image_id = argv(2); $image_id = argv(2);
if (substr($image_id,-2,1) == '-') { if (substr($image_id, -2, 1) == '-') {
$scale = substr($image_id,-1,1); $scale = substr($image_id, -1, 1);
$image_id = substr($image_id,0,-2); $image_id = substr($image_id, 0, -2);
} }
$srcX = intval($_POST['xstart']); $srcX = intval($_POST['xstart']);
$srcY = intval($_POST['ystart']); $srcY = intval($_POST['ystart']);
$srcW = intval($_POST['xfinal']) - $srcX; $srcW = intval($_POST['xfinal']) - $srcX;
@ -92,18 +92,18 @@ class Cover_photo {
if ($r) { if ($r) {
$max_thumb = intval(get_config('system','max_thumbnail',1600)); $max_thumb = intval(get_config('system', 'max_thumbnail', 1600));
$iscaled = false; $iscaled = false;
if (intval($r[0]['height']) > $max_thumb || intval($r[0]['width']) > $max_thumb) { if (intval($r[0]['height']) > $max_thumb || intval($r[0]['width']) > $max_thumb) {
$imagick_path = get_config('system','imagick_convert_path'); $imagick_path = get_config('system', 'imagick_convert_path');
if ($imagick_path && @file_exists($imagick_path) && intval($r[0]['os_storage'])) { if ($imagick_path && @file_exists($imagick_path) && intval($r[0]['os_storage'])) {
$fname = dbunescbin($r[0]['content']); $fname = dbunescbin($r[0]['content']);
$tmp_name = $fname . '-001'; $tmp_name = $fname . '-001';
$newsize = photo_calculate_scale(array_merge(getimagesize($fname),['max' => $max_thumb])); $newsize = photo_calculate_scale(array_merge(getimagesize($fname), ['max' => $max_thumb]));
$cmd = $imagick_path . ' ' . escapeshellarg(PROJECT_BASE . '/' . $fname) . ' -resize ' . $newsize . ' ' . escapeshellarg(PROJECT_BASE . '/' . $tmp_name); $cmd = $imagick_path . ' ' . escapeshellarg(PROJECT_BASE . '/' . $fname) . ' -resize ' . $newsize . ' ' . escapeshellarg(PROJECT_BASE . '/' . $tmp_name);
// logger('imagick thumbnail command: ' . $cmd); // logger('imagick thumbnail command: ' . $cmd);
for ($x = 0; $x < 4; $x ++) { for ($x = 0; $x < 4; $x++) {
exec($cmd); exec($cmd);
if (file_exists($tmp_name)) { if (file_exists($tmp_name)) {
break; break;
@ -112,7 +112,7 @@ class Cover_photo {
if (file_exists($tmp_name)) { if (file_exists($tmp_name)) {
$base_image = $r[0]; $base_image = $r[0];
$gis = getimagesize($tmp_name); $gis = getimagesize($tmp_name);
logger('gis: ' . print_r($gis,true)); logger('gis: ' . print_r($gis, true));
$base_image['width'] = $gis[0]; $base_image['width'] = $gis[0];
$base_image['height'] = $gis[1]; $base_image['height'] = $gis[1];
$base_image['content'] = @file_get_contents($tmp_name); $base_image['content'] = @file_get_contents($tmp_name);
@ -121,7 +121,7 @@ logger('gis: ' . print_r($gis,true));
} }
} }
} }
if (! $iscaled) { if (!$iscaled) {
$base_image = $r[0]; $base_image = $r[0];
$base_image['content'] = (($base_image['os_storage']) ? @file_get_contents(dbunescbin($base_image['content'])) : dbunescbin($base_image['content'])); $base_image['content'] = (($base_image['os_storage']) ? @file_get_contents(dbunescbin($base_image['content'])) : dbunescbin($base_image['content']));
} }
@ -144,7 +144,7 @@ logger('gis: ' . print_r($gis,true));
$scaled_width = $g[0]['width']; $scaled_width = $g[0]['width'];
$scaled_height = $g[0]['height']; $scaled_height = $g[0]['height'];
if ((! $scaled_width) || (! $scaled_height)) { if ((!$scaled_width) || (!$scaled_height)) {
logger('potential divide by zero scaling cover photo'); logger('potential divide by zero scaling cover photo');
return; return;
} }
@ -157,12 +157,12 @@ logger('gis: ' . print_r($gis,true));
intval($channel['channel_id']) intval($channel['channel_id'])
); );
$orig_srcx = ( $base_image['width'] / $scaled_width ) * $srcX; $orig_srcx = ($base_image['width'] / $scaled_width) * $srcX;
$orig_srcy = ( $base_image['height'] / $scaled_height ) * $srcY; $orig_srcy = ($base_image['height'] / $scaled_height) * $srcY;
$orig_srcw = ( $srcW / $scaled_width ) * $base_image['width']; $orig_srcw = ($srcW / $scaled_width) * $base_image['width'];
$orig_srch = ( $srcH / $scaled_height ) * $base_image['height']; $orig_srch = ($srcH / $scaled_height) * $base_image['height'];
$im->cropImageRect(1200,435,$orig_srcx, $orig_srcy, $orig_srcw, $orig_srch); $im->cropImageRect(1200, 435, $orig_srcx, $orig_srcy, $orig_srcw, $orig_srch);
$aid = get_account_id(); $aid = get_account_id();
@ -183,19 +183,19 @@ logger('gis: ' . print_r($gis,true));
$r1 = $im->storeThumbnail($p, PHOTO_RES_COVER_1200); $r1 = $im->storeThumbnail($p, PHOTO_RES_COVER_1200);
$im->doScaleImage(850,310); $im->doScaleImage(850, 310);
$p['imgscale'] = 8; $p['imgscale'] = 8;
$r2 = $im->storeThumbnail($p, PHOTO_RES_COVER_850); $r2 = $im->storeThumbnail($p, PHOTO_RES_COVER_850);
$im->doScaleImage(425,160); $im->doScaleImage(425, 160);
$p['imgscale'] = 9; $p['imgscale'] = 9;
$r3 = $im->storeThumbnail($p, PHOTO_RES_COVER_425); $r3 = $im->storeThumbnail($p, PHOTO_RES_COVER_425);
if ($r1 === false || $r2 === false || $r3 === false) { if ($r1 === false || $r2 === false || $r3 === false) {
// if one failed, delete them all so we can start over. // if one failed, delete them all so we can start over.
notice( t('Image resize failed.') . EOL ); notice(t('Image resize failed.') . EOL);
$x = q("delete from photo where resource_id = '%s' and uid = %d and imgscale >= 7 ", $x = q("delete from photo where resource_id = '%s' and uid = %d and imgscale >= 7 ",
dbesc($base_image['resource_id']), dbesc($base_image['resource_id']),
intval($channel['channel_id']) intval($channel['channel_id'])
@ -203,9 +203,8 @@ logger('gis: ' . print_r($gis,true));
return; return;
} }
} } else
else notice(t('Unable to process image') . EOL);
notice( t('Unable to process image') . EOL);
} }
goaway(z_root() . '/admin'); goaway(z_root() . '/admin');
@ -219,22 +218,21 @@ logger('gis: ' . print_r($gis,true));
$matches = []; $matches = [];
$partial = false; $partial = false;
if (array_key_exists('HTTP_CONTENT_RANGE',$_SERVER)) { if (array_key_exists('HTTP_CONTENT_RANGE', $_SERVER)) {
$pm = preg_match('/bytes (\d*)\-(\d*)\/(\d*)/',$_SERVER['HTTP_CONTENT_RANGE'],$matches); $pm = preg_match('/bytes (\d*)\-(\d*)\/(\d*)/', $_SERVER['HTTP_CONTENT_RANGE'], $matches);
if ($pm) { if ($pm) {
logger('Content-Range: ' . print_r($matches,true)); logger('Content-Range: ' . print_r($matches, true));
$partial = true; $partial = true;
} }
} }
if ($partial) { if ($partial) {
$x = save_chunk($channel,$matches[1],$matches[2],$matches[3]); $x = save_chunk($channel, $matches[1], $matches[2], $matches[3]);
if ($x['partial']) { if ($x['partial']) {
header('Range: bytes=0-' . (($x['length']) ? $x['length'] - 1 : 0)); header('Range: bytes=0-' . (($x['length']) ? $x['length'] - 1 : 0));
json_return_and_die($x); json_return_and_die($x);
} } else {
else {
header('Range: bytes=0-' . (($x['size']) ? $x['size'] - 1 : 0)); header('Range: bytes=0-' . (($x['size']) ? $x['size'] - 1 : 0));
$_FILES['userfile'] = [ $_FILES['userfile'] = [
@ -245,9 +243,8 @@ logger('gis: ' . print_r($gis,true));
'size' => $x['size'] 'size' => $x['size']
]; ];
} }
} } else {
else { if (!array_key_exists('userfile', $_FILES)) {
if (! array_key_exists('userfile',$_FILES)) {
$_FILES['userfile'] = [ $_FILES['userfile'] = [
'name' => $_FILES['files']['name'], 'name' => $_FILES['files']['name'],
'type' => $_FILES['files']['type'], 'type' => $_FILES['files']['type'],
@ -260,9 +257,9 @@ logger('gis: ' . print_r($gis,true));
$res = attach_store($channel, $channel['channel_hash'], '', array('album' => t('Cover Photos'), 'hash' => $hash)); $res = attach_store($channel, $channel['channel_hash'], '', array('album' => t('Cover Photos'), 'hash' => $hash));
logger('attach_store: ' . print_r($res,true),LOGGER_DEBUG); logger('attach_store: ' . print_r($res, true), LOGGER_DEBUG);
json_return_and_die([ 'message' => $hash ]); json_return_and_die(['message' => $hash]);
} }
@ -275,10 +272,11 @@ logger('gis: ' . print_r($gis,true));
*/ */
function get() { public function get()
{
if (! is_site_admin()) { if (!is_site_admin()) {
notice( t('Permission denied.') . EOL ); notice(t('Permission denied.') . EOL);
return; return;
} }
@ -300,7 +298,7 @@ logger('gis: ' . print_r($gis,true));
if (argv(2) === 'use') { if (argv(2) === 'use') {
if (argc() < 4) { if (argc() < 4) {
notice( t('Permission denied.') . EOL ); notice(t('Permission denied.') . EOL);
return; return;
} }
@ -312,8 +310,8 @@ logger('gis: ' . print_r($gis,true));
intval($channel['channel_id']), intval($channel['channel_id']),
dbesc($resource_id) dbesc($resource_id)
); );
if (! $r) { if (!$r) {
notice( t('Photo not available.') . EOL ); notice(t('Photo not available.') . EOL);
return; return;
} }
$havescale = false; $havescale = false;
@ -328,15 +326,14 @@ logger('gis: ' . print_r($gis,true));
intval($channel['channel_id']) intval($channel['channel_id'])
); );
if (! $r) { if (!$r) {
notice( t('Photo not available.') . EOL ); notice(t('Photo not available.') . EOL);
return; return;
} }
if (intval($r[0]['os_storage'])) { if (intval($r[0]['os_storage'])) {
$data = @file_get_contents(dbunescbin($r[0]['content'])); $data = @file_get_contents(dbunescbin($r[0]['content']));
} } else {
else {
$data = dbunescbin($r[0]['content']); $data = dbunescbin($r[0]['content']);
} }
@ -361,13 +358,13 @@ logger('gis: ' . print_r($gis,true));
} }
if(! array_key_exists('imagecrop',App::$data)) { if (!array_key_exists('imagecrop', App::$data)) {
$o .= replace_macros(get_markup_template('admin_cover_photo.tpl'), [ $o .= replace_macros(get_markup_template('admin_cover_photo.tpl'), [
'$user' => $channel['channel_address'], '$user' => $channel['channel_address'],
'$channel_id' => $channel['channel_id'], '$channel_id' => $channel['channel_id'],
'$info' => t('Your cover photo may be visible to anybody on the internet'), '$info' => t('Your cover photo may be visible to anybody on the internet'),
'$existing' => get_cover_photo($channel['channel_id'],'array',PHOTO_RES_COVER_850), '$existing' => get_cover_photo($channel['channel_id'], 'array', PHOTO_RES_COVER_850),
'$lbl_upfile' => t('Upload File:'), '$lbl_upfile' => t('Upload File:'),
'$lbl_profiles' => t('Select a profile:'), '$lbl_profiles' => t('Select a profile:'),
'$title' => t('Change Cover Photo'), '$title' => t('Change Cover Photo'),
@ -391,8 +388,7 @@ logger('gis: ' . print_r($gis,true));
call_hooks('cover_photo_content_end', $o); call_hooks('cover_photo_content_end', $o);
return $o; return $o;
} } else {
else {
$filename = App::$data['imagecrop'] . '-3'; $filename = App::$data['imagecrop'] . '-3';
$resolution = 3; $resolution = 3;
@ -418,9 +414,10 @@ logger('gis: ' . print_r($gis,true));
* *
*/ */
function cover_photo_crop_ui_head($ph, $hash, $smallest){ public function cover_photo_crop_ui_head($ph, $hash, $smallest)
{
$max_length = get_config('system','max_image_length', MAX_IMAGE_LENGTH); $max_length = get_config('system', 'max_image_length', MAX_IMAGE_LENGTH);
if ($max_length > 0) { if ($max_length > 0) {
$ph->scaleImage($max_length); $ph->scaleImage($max_length);

View file

@ -3,98 +3,89 @@
namespace Zotlabs\Module\Admin; namespace Zotlabs\Module\Admin;
class Dbsync
class Dbsync { {
function get() { public function get()
{
$o = ''; $o = '';
if(argc() > 3 && intval(argv(3)) && argv(2) === 'mark') { if (argc() > 3 && intval(argv(3)) && argv(2) === 'mark') {
// remove the old style config if it exists // remove the old style config if it exists
del_config('database', 'update_r' . intval(argv(3))); del_config('database', 'update_r' . intval(argv(3)));
set_config('database', '_' . intval(argv(3)), 'success'); set_config('database', '_' . intval(argv(3)), 'success');
if(intval(get_config('system','db_version')) < intval(argv(3))) if (intval(get_config('system', 'db_version')) < intval(argv(3)))
set_config('system','db_version',intval(argv(3))); set_config('system', 'db_version', intval(argv(3)));
info( t('Update has been marked successful') . EOL); info(t('Update has been marked successful') . EOL);
goaway(z_root() . '/admin/dbsync'); goaway(z_root() . '/admin/dbsync');
} }
if(argc() > 3 && intval(argv(3)) && argv(2) === 'verify') { if (argc() > 3 && intval(argv(3)) && argv(2) === 'verify') {
$s = '_' . intval(argv(3)); $s = '_' . intval(argv(3));
$cls = '\\Zotlabs\Update\\' . $s ; $cls = '\\Zotlabs\Update\\' . $s;
if(class_exists($cls)) { if (class_exists($cls)) {
$c = new $cls(); $c = new $cls();
if(method_exists($c,'verify')) { if (method_exists($c, 'verify')) {
$retval = $c->verify(); $retval = $c->verify();
if($retval === UPDATE_FAILED) { if ($retval === UPDATE_FAILED) {
$o .= sprintf( t('Verification of update %s failed. Check system logs.'), $s); $o .= sprintf(t('Verification of update %s failed. Check system logs.'), $s);
} elseif ($retval === UPDATE_SUCCESS) {
$o .= sprintf(t('Update %s was successfully applied.'), $s);
set_config('database', $s, 'success');
} else
$o .= sprintf(t('Verifying update %s did not return a status. Unknown if it succeeded.'), $s);
} else {
$o .= sprintf(t('Update %s does not contain a verification function.'), $s);
} }
elseif($retval === UPDATE_SUCCESS) { } else
$o .= sprintf( t('Update %s was successfully applied.'), $s); $o .= sprintf(t('Update function %s could not be found.'), $s);
set_config('database',$s, 'success');
}
else
$o .= sprintf( t('Verifying update %s did not return a status. Unknown if it succeeded.'), $s);
}
else {
$o .= sprintf( t('Update %s does not contain a verification function.'), $s );
}
}
else
$o .= sprintf( t('Update function %s could not be found.'), $s);
return $o; return $o;
// remove the old style config if it exists // remove the old style config if it exists
del_config('database', 'update_r' . intval(argv(3))); del_config('database', 'update_r' . intval(argv(3)));
set_config('database', '_' . intval(argv(3)), 'success'); set_config('database', '_' . intval(argv(3)), 'success');
if(intval(get_config('system','db_version')) < intval(argv(3))) if (intval(get_config('system', 'db_version')) < intval(argv(3)))
set_config('system','db_version',intval(argv(3))); set_config('system', 'db_version', intval(argv(3)));
info( t('Update has been marked successful') . EOL); info(t('Update has been marked successful') . EOL);
goaway(z_root() . '/admin/dbsync'); goaway(z_root() . '/admin/dbsync');
} }
if(argc() > 2 && intval(argv(2))) { if (argc() > 2 && intval(argv(2))) {
$x = intval(argv(2)); $x = intval(argv(2));
$s = '_' . $x; $s = '_' . $x;
$cls = '\\Zotlabs\Update\\' . $s ; $cls = '\\Zotlabs\Update\\' . $s;
if(class_exists($cls)) { if (class_exists($cls)) {
$c = new $cls(); $c = new $cls();
$retval = $c->run(); $retval = $c->run();
if($retval === UPDATE_FAILED) { if ($retval === UPDATE_FAILED) {
$o .= sprintf( t('Executing update procedure %s failed. Check system logs.'), $s); $o .= sprintf(t('Executing update procedure %s failed. Check system logs.'), $s);
} } elseif ($retval === UPDATE_SUCCESS) {
elseif($retval === UPDATE_SUCCESS) { $o .= sprintf(t('Update %s was successfully applied.'), $s);
$o .= sprintf( t('Update %s was successfully applied.'), $s); set_config('database', $s, 'success');
set_config('database',$s, 'success'); } else
} $o .= sprintf(t('Update %s did not return a status. It cannot be determined if it was successful.'), $s);
else } else
$o .= sprintf( t('Update %s did not return a status. It cannot be determined if it was successful.'), $s); $o .= sprintf(t('Update function %s could not be found.'), $s);
}
else
$o .= sprintf( t('Update function %s could not be found.'), $s);
return $o; return $o;
} }
$failed = []; $failed = [];
$r = q("select * from config where cat = 'database' "); $r = q("select * from config where cat = 'database' ");
if(count($r)) { if (count($r)) {
foreach($r as $rr) { foreach ($r as $rr) {
$upd = intval(substr($rr['k'],-4)); $upd = intval(substr($rr['k'], -4));
if($rr['v'] === 'success') if ($rr['v'] === 'success')
continue; continue;
$failed[] = $upd; $failed[] = $upd;
} }
} }
if(count($failed)) { if (count($failed)) {
$o = replace_macros(get_markup_template('failed_updates.tpl'),array( $o = replace_macros(get_markup_template('failed_updates.tpl'), array(
'$base' => z_root(), '$base' => z_root(),
'$banner' => t('Failed Updates'), '$banner' => t('Failed Updates'),
'$desc' => '', '$desc' => '',
@ -103,8 +94,7 @@ class Dbsync {
'$apply' => t('Attempt to execute this update step automatically'), '$apply' => t('Attempt to execute this update step automatically'),
'$failed' => $failed '$failed' => $failed
)); ));
} } else {
else {
return '<div class="generic-content-wrapper-styled"><h3>' . t('No failed updates.') . '</h3></div>'; return '<div class="generic-content-wrapper-styled"><h3>' . t('No failed updates.') . '</h3></div>';
} }

View file

@ -3,8 +3,8 @@
namespace Zotlabs\Module\Admin; namespace Zotlabs\Module\Admin;
class Logs { class Logs
{
/** /**
@ -12,21 +12,22 @@ class Logs {
* *
*/ */
function post() { public function post()
{
if (x($_POST, 'page_logs')) { if (x($_POST, 'page_logs')) {
check_form_security_token_redirectOnErr('/admin/logs', 'admin_logs'); check_form_security_token_redirectOnErr('/admin/logs', 'admin_logs');
$logfile = ((x($_POST,'logfile')) ? notags(trim($_POST['logfile'])) : ''); $logfile = ((x($_POST, 'logfile')) ? notags(trim($_POST['logfile'])) : '');
$debugging = ((x($_POST,'debugging')) ? true : false); $debugging = ((x($_POST, 'debugging')) ? true : false);
$loglevel = ((x($_POST,'loglevel')) ? intval(trim($_POST['loglevel'])) : 0); $loglevel = ((x($_POST, 'loglevel')) ? intval(trim($_POST['loglevel'])) : 0);
set_config('system','logfile', $logfile); set_config('system', 'logfile', $logfile);
set_config('system','debugging', $debugging); set_config('system', 'debugging', $debugging);
set_config('system','loglevel', $loglevel); set_config('system', 'loglevel', $loglevel);
} }
info( t('Log settings updated.') ); info(t('Log settings updated.'));
goaway(z_root() . '/admin/logs' ); goaway(z_root() . '/admin/logs');
} }
/** /**
@ -35,9 +36,10 @@ class Logs {
* @return string * @return string
*/ */
function get() { public function get()
{
$log_choices = Array( $log_choices = array(
LOGGER_NORMAL => 'Normal', LOGGER_NORMAL => 'Normal',
LOGGER_TRACE => 'Trace', LOGGER_TRACE => 'Trace',
LOGGER_DEBUG => 'Debug', LOGGER_DEBUG => 'Debug',
@ -51,27 +53,24 @@ class Logs {
$data = ''; $data = '';
if(!file_exists($f)) { if (!file_exists($f)) {
$data = t("Error trying to open <strong>$f</strong> log file.\r\n<br/>Check to see if file $f exist and is $data = t("Error trying to open <strong>$f</strong> log file.\r\n<br/>Check to see if file $f exist and is
readable."); readable.");
} } else {
else {
$fp = fopen($f, 'r'); $fp = fopen($f, 'r');
if(!$fp) { if (!$fp) {
$data = t("Couldn't open <strong>$f</strong> log file.\r\n<br/>Check to see if file $f is readable."); $data = t("Couldn't open <strong>$f</strong> log file.\r\n<br/>Check to see if file $f is readable.");
} } else {
else {
$fstat = fstat($fp); $fstat = fstat($fp);
$size = $fstat['size']; $size = $fstat['size'];
if($size != 0) if ($size != 0) {
{ if ($size > 5000000 || $size < 0)
if($size > 5000000 || $size < 0)
$size = 5000000; $size = 5000000;
$seek = fseek($fp,0-$size,SEEK_END); $seek = fseek($fp, 0 - $size, SEEK_END);
if($seek === 0) { if ($seek === 0) {
$data = escape_tags(fread($fp,$size)); $data = escape_tags(fread($fp, $size));
while(! feof($fp)) while (!feof($fp))
$data .= escape_tags(fread($fp,4096)); $data .= escape_tags(fread($fp, 4096));
} }
} }
fclose($fp); fclose($fp);
@ -85,17 +84,16 @@ class Logs {
'$clear' => t('Clear'), '$clear' => t('Clear'),
'$data' => $data, '$data' => $data,
'$baseurl' => z_root(), '$baseurl' => z_root(),
'$logname' => get_config('system','logfile'), '$logname' => get_config('system', 'logfile'),
// name, label, value, help string, extra data... // name, label, value, help string, extra data...
'$debugging' => array('debugging', t("Debugging"),get_config('system','debugging'), ""), '$debugging' => array('debugging', t("Debugging"), get_config('system', 'debugging'), ""),
'$logfile' => array('logfile', t("Log file"), get_config('system','logfile'), t("Must be writable by web server. Relative to your top-level webserver directory.")), '$logfile' => array('logfile', t("Log file"), get_config('system', 'logfile'), t("Must be writable by web server. Relative to your top-level webserver directory.")),
'$loglevel' => array('loglevel', t("Log level"), get_config('system','loglevel'), "", $log_choices), '$loglevel' => array('loglevel', t("Log level"), get_config('system', 'loglevel'), "", $log_choices),
'$form_security_token' => get_form_security_token('admin_logs'), '$form_security_token' => get_form_security_token('admin_logs'),
)); ));
} }
} }

View file

@ -19,7 +19,8 @@ require_once('include/photo_factory.php');
require_once('include/photos.php'); require_once('include/photos.php');
class Profile_photo { class Profile_photo
{
/* @brief Initalize the profile-photo edit view /* @brief Initalize the profile-photo edit view
@ -28,9 +29,10 @@ class Profile_photo {
* *
*/ */
function init() { public function init()
{
if(! is_site_admin()) { if (!is_site_admin()) {
return; return;
} }
@ -46,9 +48,10 @@ class Profile_photo {
* *
*/ */
function post() { public function post()
{
if (! is_site_admin()) { if (!is_site_admin()) {
return; return;
} }
@ -56,22 +59,22 @@ class Profile_photo {
check_form_security_token_redirectOnErr('/profile_photo', 'profile_photo'); check_form_security_token_redirectOnErr('/profile_photo', 'profile_photo');
if ((array_key_exists('cropfinal',$_POST)) && (intval($_POST['cropfinal']) == 1)) { if ((array_key_exists('cropfinal', $_POST)) && (intval($_POST['cropfinal']) == 1)) {
// logger('crop: ' . print_r($_POST,true)); // logger('crop: ' . print_r($_POST,true));
// phase 2 - we have finished cropping // phase 2 - we have finished cropping
if (argc() != 3) { if (argc() != 3) {
notice( t('Image uploaded but image cropping failed.') . EOL ); notice(t('Image uploaded but image cropping failed.') . EOL);
return; return;
} }
$image_id = argv(2); $image_id = argv(2);
if (substr($image_id,-2,1) == '-') { if (substr($image_id, -2, 1) == '-') {
$scale = substr($image_id,-1,1); $scale = substr($image_id, -1, 1);
$image_id = substr($image_id,0,-2); $image_id = substr($image_id, 0, -2);
} }
// unless proven otherwise // unless proven otherwise
@ -84,7 +87,7 @@ class Profile_photo {
); );
if ($r) { if ($r) {
$profile = array_shift($r); $profile = array_shift($r);
if (! intval($profile['is_default'])) { if (!intval($profile['is_default'])) {
$is_default_profile = 0; $is_default_profile = 0;
} }
} }
@ -107,7 +110,7 @@ class Profile_photo {
$im = photo_factory($base_image['content'], $base_image['mimetype']); $im = photo_factory($base_image['content'], $base_image['mimetype']);
if ($im->is_valid()) { if ($im->is_valid()) {
$im->cropImage(300,$srcX,$srcY,$srcW,$srcH); $im->cropImage(300, $srcX, $srcY, $srcW, $srcH);
$aid = 0; $aid = 0;
@ -140,7 +143,7 @@ class Profile_photo {
if ($r1 === false || $r2 === false || $r3 === false) { if ($r1 === false || $r2 === false || $r3 === false) {
// if one failed, delete them all so we can start over. // if one failed, delete them all so we can start over.
notice( t('Image resize failed.') . EOL ); notice(t('Image resize failed.') . EOL);
$x = q("delete from photo where resource_id = '%s' and uid = %d and imgscale in ( %d, %d, %d ) ", $x = q("delete from photo where resource_id = '%s' and uid = %d and imgscale in ( %d, %d, %d ) ",
dbesc($base_image['resource_id']), dbesc($base_image['resource_id']),
$channel['channel_id'], $channel['channel_id'],
@ -179,13 +182,12 @@ class Profile_photo {
// Similarly, tell the nav bar to bypass the cache and update the avatar image. // Similarly, tell the nav bar to bypass the cache and update the avatar image.
$_SESSION['reload_avatar'] = true; $_SESSION['reload_avatar'] = true;
Config::Set('system','site_icon_url',z_root() . '/photo/profile/m/' . $channel['channel_id']); Config::Set('system', 'site_icon_url', z_root() . '/photo/profile/m/' . $channel['channel_id']);
info( t('Shift-reload the page or clear browser cache if the new photo does not display immediately.') . EOL); info(t('Shift-reload the page or clear browser cache if the new photo does not display immediately.') . EOL);
} } else {
else { notice(t('Unable to process image') . EOL);
notice( t('Unable to process image') . EOL);
} }
} }
@ -204,28 +206,26 @@ class Profile_photo {
if ($_REQUEST['importfile']) { if ($_REQUEST['importfile']) {
$hash = $_REQUEST['importfile']; $hash = $_REQUEST['importfile'];
$importing = true; $importing = true;
} } else {
else {
$matches = []; $matches = [];
$partial = false; $partial = false;
if (array_key_exists('HTTP_CONTENT_RANGE',$_SERVER)) { if (array_key_exists('HTTP_CONTENT_RANGE', $_SERVER)) {
$pm = preg_match('/bytes (\d*)\-(\d*)\/(\d*)/',$_SERVER['HTTP_CONTENT_RANGE'],$matches); $pm = preg_match('/bytes (\d*)\-(\d*)\/(\d*)/', $_SERVER['HTTP_CONTENT_RANGE'], $matches);
if ($pm) { if ($pm) {
logger('Content-Range: ' . print_r($matches,true), LOGGER_DEBUG); logger('Content-Range: ' . print_r($matches, true), LOGGER_DEBUG);
$partial = true; $partial = true;
} }
} }
if ($partial) { if ($partial) {
$x = save_chunk($channel,$matches[1],$matches[2],$matches[3]); $x = save_chunk($channel, $matches[1], $matches[2], $matches[3]);
if ($x['partial']) { if ($x['partial']) {
header('Range: bytes=0-' . (($x['length']) ? $x['length'] - 1 : 0)); header('Range: bytes=0-' . (($x['length']) ? $x['length'] - 1 : 0));
json_return_and_die($x); json_return_and_die($x);
} } else {
else {
header('Range: bytes=0-' . (($x['size']) ? $x['size'] - 1 : 0)); header('Range: bytes=0-' . (($x['size']) ? $x['size'] - 1 : 0));
$_FILES['userfile'] = [ $_FILES['userfile'] = [
@ -236,9 +236,8 @@ class Profile_photo {
'size' => $x['size'] 'size' => $x['size']
]; ];
} }
} } else {
else { if (!array_key_exists('userfile', $_FILES)) {
if (! array_key_exists('userfile',$_FILES)) {
$_FILES['userfile'] = [ $_FILES['userfile'] = [
'name' => $_FILES['files']['name'], 'name' => $_FILES['files']['name'],
'type' => $_FILES['files']['type'], 'type' => $_FILES['files']['type'],
@ -251,9 +250,9 @@ class Profile_photo {
$res = attach_store($channel, $channel['channel_hash'], '', array('album' => t('Profile Photos'), 'hash' => $hash)); $res = attach_store($channel, $channel['channel_hash'], '', array('album' => t('Profile Photos'), 'hash' => $hash));
logger('attach_store: ' . print_r($res,true), LOGGER_DEBUG); logger('attach_store: ' . print_r($res, true), LOGGER_DEBUG);
json_return_and_die([ 'message' => $hash ]); json_return_and_die(['message' => $hash]);
} }
if (($res && intval($res['data']['is_photo'])) || $importing) { if (($res && intval($res['data']['is_photo'])) || $importing) {
@ -262,8 +261,8 @@ class Profile_photo {
intval($channel['channel_hash']) intval($channel['channel_hash'])
); );
if (! $i) { if (!$i) {
notice( t('Image upload failed.') . EOL ); notice(t('Image upload failed.') . EOL);
return; return;
} }
$os_storage = false; $os_storage = false;
@ -281,8 +280,8 @@ class Profile_photo {
$imagedata = (($os_storage) ? @file_get_contents(dbunescbin($imagedata)) : dbunescbin($imagedata)); $imagedata = (($os_storage) ? @file_get_contents(dbunescbin($imagedata)) : dbunescbin($imagedata));
$ph = photo_factory($imagedata, $filetype); $ph = photo_factory($imagedata, $filetype);
if (! $ph->is_valid()) { if (!$ph->is_valid()) {
notice( t('Unable to process image.') . EOL ); notice(t('Unable to process image.') . EOL);
return; return;
} }
@ -301,10 +300,11 @@ class Profile_photo {
*/ */
function get() { public function get()
{
if (! is_site_admin()) { if (!is_site_admin()) {
notice( t('Permission denied.') . EOL ); notice(t('Permission denied.') . EOL);
return; return;
} }
@ -317,12 +317,12 @@ class Profile_photo {
} }
if (argv(2) === 'reset') { if (argv(2) === 'reset') {
Config::Delete('system','site_icon_url'); Config::Delete('system', 'site_icon_url');
} }
if (argv(2) === 'use') { if (argv(2) === 'use') {
if (argc() < 4) { if (argc() < 4) {
notice( t('Permission denied.') . EOL ); notice(t('Permission denied.') . EOL);
return; return;
} }
@ -339,8 +339,7 @@ class Profile_photo {
if (($c) && (count($c) === 1) && (intval($c[0]['is_default']))) { if (($c) && (count($c) === 1) && (intval($c[0]['is_default']))) {
$_REQUEST['profile'] = $c[0]['id']; $_REQUEST['profile'] = $c[0]['id'];
$multi_profiles = false; $multi_profiles = false;
} } else {
else {
$_REQUEST['profile'] = $pf; $_REQUEST['profile'] = $pf;
} }
@ -348,8 +347,8 @@ class Profile_photo {
intval($channel['channel_id']), intval($channel['channel_id']),
dbesc($resource_id) dbesc($resource_id)
); );
if (! $r) { if (!$r) {
notice( t('Photo not available.') . EOL ); notice(t('Photo not available.') . EOL);
return; return;
} }
$havescale = false; $havescale = false;
@ -388,15 +387,14 @@ class Profile_photo {
intval($channel['channel_id']) intval($channel['channel_id'])
); );
if (! $r) { if (!$r) {
notice( t('Photo not available.') . EOL ); notice(t('Photo not available.') . EOL);
return; return;
} }
if (intval($r[0]['os_storage'])) { if (intval($r[0]['os_storage'])) {
$data = @file_get_contents(dbunescbin($r[0]['content'])); $data = @file_get_contents(dbunescbin($r[0]['content']));
} } else {
else {
$data = dbunescbin($r[0]['content']); $data = dbunescbin($r[0]['content']);
} }
@ -421,8 +419,7 @@ class Profile_photo {
if ($multi_profiles) { if ($multi_profiles) {
App::$data['importfile'] = $resource_id; App::$data['importfile'] = $resource_id;
} } else {
else {
$this->profile_photo_crop_ui_head($ph, $hash, $smallest); $this->profile_photo_crop_ui_head($ph, $hash, $smallest);
} }
@ -437,20 +434,20 @@ class Profile_photo {
); );
if ($profiles) { if ($profiles) {
for ($x = 0; $x < count($profiles); $x ++) { for ($x = 0; $x < count($profiles); $x++) {
$profiles[$x]['selected'] = false; $profiles[$x]['selected'] = false;
if ($pf && $profiles[$x]['id'] == $pf) { if ($pf && $profiles[$x]['id'] == $pf) {
$profiles[$x]['selected'] = true; $profiles[$x]['selected'] = true;
} }
if ((! $pf) && $profiles[$x]['is_default']) { if ((!$pf) && $profiles[$x]['is_default']) {
$profiles[$x]['selected'] = true; $profiles[$x]['selected'] = true;
} }
} }
} }
$importing = ((array_key_exists('importfile',App::$data)) ? true : false); $importing = ((array_key_exists('importfile', App::$data)) ? true : false);
if (! array_key_exists('imagecrop', App::$data)) { if (!array_key_exists('imagecrop', App::$data)) {
$tpl = get_markup_template('admin_profile_photo.tpl'); $tpl = get_markup_template('admin_profile_photo.tpl');
@ -482,8 +479,7 @@ class Profile_photo {
call_hooks('profile_photo_content_end', $o); call_hooks('profile_photo_content_end', $o);
return $o; return $o;
} } else {
else {
// present a cropping form // present a cropping form
@ -510,8 +506,9 @@ class Profile_photo {
* *
*/ */
function profile_photo_crop_ui_head($ph, $hash, $smallest) { public function profile_photo_crop_ui_head($ph, $hash, $smallest)
$max_length = get_config('system','max_image_length', MAX_IMAGE_LENGTH); {
$max_length = get_config('system', 'max_image_length', MAX_IMAGE_LENGTH);
if ($max_length > 0) { if ($max_length > 0) {
$ph->scaleImage($max_length); $ph->scaleImage($max_length);

View file

@ -3,50 +3,52 @@
namespace Zotlabs\Module\Admin; namespace Zotlabs\Module\Admin;
class Profs { class Profs
{
function post() { public function post()
{
if(array_key_exists('basic',$_REQUEST)) { if (array_key_exists('basic', $_REQUEST)) {
$arr = explode(',',$_REQUEST['basic']); $arr = explode(',', $_REQUEST['basic']);
array_walk($arr,'array_trim'); array_walk($arr, 'array_trim');
$narr = []; $narr = [];
if(count($arr)) { if (count($arr)) {
foreach($arr as $a) { foreach ($arr as $a) {
if(strlen($a)) { if (strlen($a)) {
$narr[] = $a; $narr[] = $a;
} }
} }
} }
if(! $narr) if (!$narr)
del_config('system','profile_fields_basic'); del_config('system', 'profile_fields_basic');
else else
set_config('system','profile_fields_basic',$narr); set_config('system', 'profile_fields_basic', $narr);
if(array_key_exists('advanced',$_REQUEST)) { if (array_key_exists('advanced', $_REQUEST)) {
$arr = explode(',',$_REQUEST['advanced']); $arr = explode(',', $_REQUEST['advanced']);
array_walk($arr,'array_trim'); array_walk($arr, 'array_trim');
$narr = []; $narr = [];
if(count($arr)) { if (count($arr)) {
foreach($arr as $a) { foreach ($arr as $a) {
if(strlen($a)) { if (strlen($a)) {
$narr[] = $a; $narr[] = $a;
} }
} }
} }
if(! $narr) if (!$narr)
del_config('system','profile_fields_advanced'); del_config('system', 'profile_fields_advanced');
else else
set_config('system','profile_fields_advanced',$narr); set_config('system', 'profile_fields_advanced', $narr);
} }
goaway(z_root() . '/admin/profs'); goaway(z_root() . '/admin/profs');
} }
if(array_key_exists('field_name',$_REQUEST)) { if (array_key_exists('field_name', $_REQUEST)) {
if($_REQUEST['id']) { if ($_REQUEST['id']) {
$r = q("update profdef set field_name = '%s', field_type = '%s', field_desc = '%s' field_help = '%s', field_inputs = '%s' where id = %d", $r = q("update profdef set field_name = '%s', field_type = '%s', field_desc = '%s' field_help = '%s', field_inputs = '%s' where id = %d",
dbesc($_REQUEST['field_name']), dbesc($_REQUEST['field_name']),
dbesc($_REQUEST['field_type']), dbesc($_REQUEST['field_type']),
@ -55,8 +57,7 @@ class Profs {
dbesc($_REQUEST['field_inputs']), dbesc($_REQUEST['field_inputs']),
intval($_REQUEST['id']) intval($_REQUEST['id'])
); );
} } else {
else {
$r = q("insert into profdef ( field_name, field_type, field_desc, field_help, field_inputs ) values ( '%s' , '%s', '%s', '%s', '%s' )", $r = q("insert into profdef ( field_name, field_type, field_desc, field_help, field_inputs ) values ( '%s' , '%s', '%s', '%s', '%s' )",
dbesc($_REQUEST['field_name']), dbesc($_REQUEST['field_name']),
dbesc($_REQUEST['field_type']), dbesc($_REQUEST['field_type']),
@ -73,9 +74,10 @@ class Profs {
goaway(z_root() . '/admin/profs'); goaway(z_root() . '/admin/profs');
} }
function get() { public function get()
{
if((argc() > 3) && argv(2) == 'drop' && intval(argv(3))) { if ((argc() > 3) && argv(2) == 'drop' && intval(argv(3))) {
$r = q("delete from profdef where id = %d", $r = q("delete from profdef where id = %d",
intval(argv(3)) intval(argv(3))
); );
@ -84,33 +86,33 @@ class Profs {
goaway(z_root() . '/admin/profs'); goaway(z_root() . '/admin/profs');
} }
if((argc() > 2) && argv(2) === 'new') { if ((argc() > 2) && argv(2) === 'new') {
return replace_macros(get_markup_template('profdef_edit.tpl'),array( return replace_macros(get_markup_template('profdef_edit.tpl'), array(
'$header' => t('New Profile Field'), '$header' => t('New Profile Field'),
'$field_name' => array('field_name',t('Field nickname'),$_REQUEST['field_name'],t('System name of field')), '$field_name' => array('field_name', t('Field nickname'), $_REQUEST['field_name'], t('System name of field')),
'$field_type' => array('field_type',t('Input type'),(($_REQUEST['field_type']) ? $_REQUEST['field_type'] : 'text'),''), '$field_type' => array('field_type', t('Input type'), (($_REQUEST['field_type']) ? $_REQUEST['field_type'] : 'text'), ''),
'$field_desc' => array('field_desc',t('Field Name'),$_REQUEST['field_desc'],t('Label on profile pages')), '$field_desc' => array('field_desc', t('Field Name'), $_REQUEST['field_desc'], t('Label on profile pages')),
'$field_help' => array('field_help',t('Help text'),$_REQUEST['field_help'],t('Additional info (optional)')), '$field_help' => array('field_help', t('Help text'), $_REQUEST['field_help'], t('Additional info (optional)')),
'$submit' => t('Save') '$submit' => t('Save')
)); ));
} }
if((argc() > 2) && intval(argv(2))) { if ((argc() > 2) && intval(argv(2))) {
$r = q("select * from profdef where id = %d limit 1", $r = q("select * from profdef where id = %d limit 1",
intval(argv(2)) intval(argv(2))
); );
if(! $r) { if (!$r) {
notice( t('Field definition not found') . EOL); notice(t('Field definition not found') . EOL);
goaway(z_root() . '/admin/profs'); goaway(z_root() . '/admin/profs');
} }
return replace_macros(get_markup_template('profdef_edit.tpl'),array( return replace_macros(get_markup_template('profdef_edit.tpl'), array(
'$id' => intval($r[0]['id']), '$id' => intval($r[0]['id']),
'$header' => t('Edit Profile Field'), '$header' => t('Edit Profile Field'),
'$field_name' => array('field_name',t('Field nickname'),$r[0]['field_name'],t('System name of field')), '$field_name' => array('field_name', t('Field nickname'), $r[0]['field_name'], t('System name of field')),
'$field_type' => array('field_type',t('Input type'),$r[0]['field_type'],''), '$field_type' => array('field_type', t('Input type'), $r[0]['field_type'], ''),
'$field_desc' => array('field_desc',t('Field Name'),$r[0]['field_desc'],t('Label on profile pages')), '$field_desc' => array('field_desc', t('Field Name'), $r[0]['field_desc'], t('Label on profile pages')),
'$field_help' => array('field_help',t('Help text'),$r[0]['field_help'],t('Additional info (optional)')), '$field_help' => array('field_help', t('Help text'), $r[0]['field_help'], t('Additional info (optional)')),
'$submit' => t('Save') '$submit' => t('Save')
)); ));
} }
@ -119,11 +121,11 @@ class Profs {
$barr = []; $barr = [];
$fields = get_profile_fields_basic(); $fields = get_profile_fields_basic();
if(! $fields) if (!$fields)
$fields = get_profile_fields_basic(1); $fields = get_profile_fields_basic(1);
if($fields) { if ($fields) {
foreach($fields as $k => $v) { foreach ($fields as $k => $v) {
if($basic) if ($basic)
$basic .= ', '; $basic .= ', ';
$basic .= trim($k); $basic .= trim($k);
$barr[] = trim($k); $barr[] = trim($k);
@ -132,13 +134,13 @@ class Profs {
$advanced = ''; $advanced = '';
$fields = get_profile_fields_advanced(); $fields = get_profile_fields_advanced();
if(! $fields) if (!$fields)
$fields = get_profile_fields_advanced(1); $fields = get_profile_fields_advanced(1);
if($fields) { if ($fields) {
foreach($fields as $k => $v) { foreach ($fields as $k => $v) {
if(in_array(trim($k),$barr)) if (in_array(trim($k), $barr))
continue; continue;
if($advanced) if ($advanced)
$advanced .= ', '; $advanced .= ', ';
$advanced .= trim($k); $advanced .= trim($k);
} }
@ -146,28 +148,28 @@ class Profs {
$all = ''; $all = '';
$fields = get_profile_fields_advanced(1); $fields = get_profile_fields_advanced(1);
if($fields) { if ($fields) {
foreach($fields as $k => $v) { foreach ($fields as $k => $v) {
if($all) if ($all)
$all .= ', '; $all .= ', ';
$all .= trim($k); $all .= trim($k);
} }
} }
$r = q("select * from profdef where true"); $r = q("select * from profdef where true");
if($r) { if ($r) {
foreach($r as $rr) { foreach ($r as $rr) {
if($all) if ($all)
$all .= ', '; $all .= ', ';
$all .= $rr['field_name']; $all .= $rr['field_name'];
} }
} }
$o = replace_macros(get_markup_template('admin_profiles.tpl'),array( $o = replace_macros(get_markup_template('admin_profiles.tpl'), array(
'$title' => t('Profile Fields'), '$title' => t('Profile Fields'),
'$basic' => array('basic',t('Basic Profile Fields'),$basic,''), '$basic' => array('basic', t('Basic Profile Fields'), $basic, ''),
'$advanced' => array('advanced',t('Advanced Profile Fields'),$advanced,t('(In addition to basic fields)')), '$advanced' => array('advanced', t('Advanced Profile Fields'), $advanced, t('(In addition to basic fields)')),
'$all' => $all, '$all' => $all,
'$all_desc' => t('All available fields'), '$all_desc' => t('All available fields'),
'$cust_field_desc' => t('Custom Fields'), '$cust_field_desc' => t('Custom Fields'),
@ -184,7 +186,4 @@ class Profs {
} }
} }

View file

@ -4,29 +4,31 @@ namespace Zotlabs\Module\Admin;
use Zotlabs\Lib\Queue as ZQueue; use Zotlabs\Lib\Queue as ZQueue;
class Queue { class Queue
{
function get() { public function get()
{
$o = ''; $o = '';
$expert = ((array_key_exists('expert',$_REQUEST)) ? intval($_REQUEST['expert']) : 0); $expert = ((array_key_exists('expert', $_REQUEST)) ? intval($_REQUEST['expert']) : 0);
if($_REQUEST['drophub']) { if ($_REQUEST['drophub']) {
hubloc_mark_as_down($_REQUEST['drophub']); hubloc_mark_as_down($_REQUEST['drophub']);
ZQueue::remove_by_posturl($_REQUEST['drophub']); ZQueue::remove_by_posturl($_REQUEST['drophub']);
} }
if($_REQUEST['emptyhub']) { if ($_REQUEST['emptyhub']) {
ZQueue::remove_by_posturl($_REQUEST['emptyhub']); ZQueue::remove_by_posturl($_REQUEST['emptyhub']);
} }
$r = q("select count(outq_posturl) as total, max(outq_priority) as priority, outq_posturl from outq $r = q("select count(outq_posturl) as total, max(outq_priority) as priority, outq_posturl from outq
where outq_delivered = 0 group by outq_posturl order by total desc"); where outq_delivered = 0 group by outq_posturl order by total desc");
for($x = 0; $x < count($r); $x ++) { for ($x = 0; $x < count($r); $x++) {
$r[$x]['eurl'] = urlencode($r[$x]['outq_posturl']); $r[$x]['eurl'] = urlencode($r[$x]['outq_posturl']);
$r[$x]['connected'] = datetime_convert('UTC',date_default_timezone_get(),$r[$x]['connected'],'Y-m-d'); $r[$x]['connected'] = datetime_convert('UTC', date_default_timezone_get(), $r[$x]['connected'], 'Y-m-d');
} }
$o = replace_macros(get_markup_template('admin_queue.tpl'), array( $o = replace_macros(get_markup_template('admin_queue.tpl'), array(
@ -46,6 +48,4 @@ class Queue {
} }
} }

View file

@ -3,125 +3,127 @@
namespace Zotlabs\Module\Admin; namespace Zotlabs\Module\Admin;
class Security { class Security
{
function post() { public function post()
{
check_form_security_token_redirectOnErr('/admin/security', 'admin_security'); check_form_security_token_redirectOnErr('/admin/security', 'admin_security');
$allowed_email = ((x($_POST,'allowed_email')) ? notags(trim($_POST['allowed_email'])) : ''); $allowed_email = ((x($_POST, 'allowed_email')) ? notags(trim($_POST['allowed_email'])) : '');
set_config('system','allowed_email', $allowed_email); set_config('system', 'allowed_email', $allowed_email);
$not_allowed_email = ((x($_POST,'not_allowed_email')) ? notags(trim($_POST['not_allowed_email'])) : ''); $not_allowed_email = ((x($_POST, 'not_allowed_email')) ? notags(trim($_POST['not_allowed_email'])) : '');
set_config('system','not_allowed_email', $not_allowed_email); set_config('system', 'not_allowed_email', $not_allowed_email);
$anonymous_comments = ((x($_POST,'anonymous_comments')) ? intval($_POST['anonymous_comments']) : 0); $anonymous_comments = ((x($_POST, 'anonymous_comments')) ? intval($_POST['anonymous_comments']) : 0);
set_config('system','anonymous_comments', $anonymous_comments); set_config('system', 'anonymous_comments', $anonymous_comments);
$block_public = ((x($_POST,'block_public')) ? True : False); $block_public = ((x($_POST, 'block_public')) ? True : False);
set_config('system','block_public',$block_public); set_config('system', 'block_public', $block_public);
$block_public_search = ((x($_POST,'block_public_search')) ? 1 : 0); $block_public_search = ((x($_POST, 'block_public_search')) ? 1 : 0);
set_config('system','block_public_search',$block_public_search); set_config('system', 'block_public_search', $block_public_search);
$block_public_dir = ((x($_POST,'block_public_directory')) ? True : False); $block_public_dir = ((x($_POST, 'block_public_directory')) ? True : False);
set_config('system', 'block_public_directory', $block_public_dir); set_config('system', 'block_public_directory', $block_public_dir);
$localdir_hide = ((x($_POST,'localdir_hide')) ? 1 : 0); $localdir_hide = ((x($_POST, 'localdir_hide')) ? 1 : 0);
set_config('system','localdir_hide',$localdir_hide); set_config('system', 'localdir_hide', $localdir_hide);
$cloud_noroot = ((x($_POST,'cloud_noroot')) ? 1 : 0); $cloud_noroot = ((x($_POST, 'cloud_noroot')) ? 1 : 0);
set_config('system','cloud_disable_siteroot',1 - $cloud_noroot); set_config('system', 'cloud_disable_siteroot', 1 - $cloud_noroot);
$cloud_disksize = ((x($_POST,'cloud_disksize')) ? 1 : 0); $cloud_disksize = ((x($_POST, 'cloud_disksize')) ? 1 : 0);
set_config('system','cloud_report_disksize',$cloud_disksize); set_config('system', 'cloud_report_disksize', $cloud_disksize);
$thumbnail_security = ((x($_POST,'thumbnail_security')) ? intval($_POST['thumbnail_security']) : 0); $thumbnail_security = ((x($_POST, 'thumbnail_security')) ? intval($_POST['thumbnail_security']) : 0);
set_config('system', 'thumbnail_security' , $thumbnail_security); set_config('system', 'thumbnail_security', $thumbnail_security);
$inline_pdf = ((x($_POST,'inline_pdf')) ? intval($_POST['inline_pdf']) : 0); $inline_pdf = ((x($_POST, 'inline_pdf')) ? intval($_POST['inline_pdf']) : 0);
set_config('system', 'inline_pdf' , $inline_pdf); set_config('system', 'inline_pdf', $inline_pdf);
$ws = $this->trim_array_elems(explode("\n",$_POST['allowed_sites'])); $ws = $this->trim_array_elems(explode("\n", $_POST['allowed_sites']));
set_config('system','allowed_sites',$ws); set_config('system', 'allowed_sites', $ws);
$bs = $this->trim_array_elems(explode("\n",$_POST['denied_sites'])); $bs = $this->trim_array_elems(explode("\n", $_POST['denied_sites']));
set_config('system','denied_sites',$bs); set_config('system', 'denied_sites', $bs);
$wc = $this->trim_array_elems(explode("\n",$_POST['allowed_channels'])); $wc = $this->trim_array_elems(explode("\n", $_POST['allowed_channels']));
set_config('system','allowed_channels',$wc); set_config('system', 'allowed_channels', $wc);
$bc = $this->trim_array_elems(explode("\n",$_POST['denied_channels'])); $bc = $this->trim_array_elems(explode("\n", $_POST['denied_channels']));
set_config('system','denied_channels',$bc); set_config('system', 'denied_channels', $bc);
$ws = $this->trim_array_elems(explode("\n",$_POST['pubstream_allowed_sites'])); $ws = $this->trim_array_elems(explode("\n", $_POST['pubstream_allowed_sites']));
set_config('system','pubstream_allowed_sites',$ws); set_config('system', 'pubstream_allowed_sites', $ws);
$bs = $this->trim_array_elems(explode("\n",$_POST['pubstream_denied_sites'])); $bs = $this->trim_array_elems(explode("\n", $_POST['pubstream_denied_sites']));
set_config('system','pubstream_denied_sites',$bs); set_config('system', 'pubstream_denied_sites', $bs);
$wc = $this->trim_array_elems(explode("\n",$_POST['pubstream_allowed_channels'])); $wc = $this->trim_array_elems(explode("\n", $_POST['pubstream_allowed_channels']));
set_config('system','pubstream_allowed_channels',$wc); set_config('system', 'pubstream_allowed_channels', $wc);
$bc = $this->trim_array_elems(explode("\n",$_POST['pubstream_denied_channels'])); $bc = $this->trim_array_elems(explode("\n", $_POST['pubstream_denied_channels']));
set_config('system','pubstream_denied_channels',$bc); set_config('system', 'pubstream_denied_channels', $bc);
$embed_sslonly = ((x($_POST,'embed_sslonly')) ? True : False); $embed_sslonly = ((x($_POST, 'embed_sslonly')) ? True : False);
set_config('system','embed_sslonly',$embed_sslonly); set_config('system', 'embed_sslonly', $embed_sslonly);
$we = $this->trim_array_elems(explode("\n",$_POST['embed_allow'])); $we = $this->trim_array_elems(explode("\n", $_POST['embed_allow']));
set_config('system','embed_allow',$we); set_config('system', 'embed_allow', $we);
$be = $this->trim_array_elems(explode("\n",$_POST['embed_deny'])); $be = $this->trim_array_elems(explode("\n", $_POST['embed_deny']));
set_config('system','embed_deny',$be); set_config('system', 'embed_deny', $be);
$ts = ((x($_POST,'transport_security')) ? True : False); $ts = ((x($_POST, 'transport_security')) ? True : False);
set_config('system','transport_security_header',$ts); set_config('system', 'transport_security_header', $ts);
$cs = ((x($_POST,'content_security')) ? True : False); $cs = ((x($_POST, 'content_security')) ? True : False);
set_config('system','content_security_policy',$cs); set_config('system', 'content_security_policy', $cs);
goaway(z_root() . '/admin/security'); goaway(z_root() . '/admin/security');
} }
public function get()
{
function get() { $allowedsites = get_config('system', 'allowed_sites');
$allowedsites_str = ((is_array($allowedsites)) ? implode("\n", $allowedsites) : '');
$allowedsites = get_config('system','allowed_sites'); $deniedsites = get_config('system', 'denied_sites');
$allowedsites_str = ((is_array($allowedsites)) ? implode("\n",$allowedsites) : ''); $deniedsites_str = ((is_array($deniedsites)) ? implode("\n", $deniedsites) : '');
$deniedsites = get_config('system','denied_sites');
$deniedsites_str = ((is_array($deniedsites)) ? implode("\n",$deniedsites) : '');
$allowedchannels = get_config('system','allowed_channels'); $allowedchannels = get_config('system', 'allowed_channels');
$allowedchannels_str = ((is_array($allowedchannels)) ? implode("\n",$allowedchannels) : ''); $allowedchannels_str = ((is_array($allowedchannels)) ? implode("\n", $allowedchannels) : '');
$deniedchannels = get_config('system','denied_channels'); $deniedchannels = get_config('system', 'denied_channels');
$deniedchannels_str = ((is_array($deniedchannels)) ? implode("\n",$deniedchannels) : ''); $deniedchannels_str = ((is_array($deniedchannels)) ? implode("\n", $deniedchannels) : '');
$psallowedsites = get_config('system','pubstream_allowed_sites'); $psallowedsites = get_config('system', 'pubstream_allowed_sites');
$psallowedsites_str = ((is_array($psallowedsites)) ? implode("\n",$psallowedsites) : ''); $psallowedsites_str = ((is_array($psallowedsites)) ? implode("\n", $psallowedsites) : '');
$psdeniedsites = get_config('system','pubstream_denied_sites'); $psdeniedsites = get_config('system', 'pubstream_denied_sites');
$psdeniedsites_str = ((is_array($psdeniedsites)) ? implode("\n",$psdeniedsites) : ''); $psdeniedsites_str = ((is_array($psdeniedsites)) ? implode("\n", $psdeniedsites) : '');
$psallowedchannels = get_config('system','pubstream_allowed_channels'); $psallowedchannels = get_config('system', 'pubstream_allowed_channels');
$psallowedchannels_str = ((is_array($psallowedchannels)) ? implode("\n",$psallowedchannels) : ''); $psallowedchannels_str = ((is_array($psallowedchannels)) ? implode("\n", $psallowedchannels) : '');
$psdeniedchannels = get_config('system','pubstream_denied_channels'); $psdeniedchannels = get_config('system', 'pubstream_denied_channels');
$psdeniedchannels_str = ((is_array($psdeniedchannels)) ? implode("\n",$psdeniedchannels) : ''); $psdeniedchannels_str = ((is_array($psdeniedchannels)) ? implode("\n", $psdeniedchannels) : '');
$allowedembeds = get_config('system','embed_allow'); $allowedembeds = get_config('system', 'embed_allow');
$allowedembeds_str = ((is_array($allowedembeds)) ? implode("\n",$allowedembeds) : ''); $allowedembeds_str = ((is_array($allowedembeds)) ? implode("\n", $allowedembeds) : '');
$deniedembeds = get_config('system','embed_deny'); $deniedembeds = get_config('system', 'embed_deny');
$deniedembeds_str = ((is_array($deniedembeds)) ? implode("\n",$deniedembeds) : ''); $deniedembeds_str = ((is_array($deniedembeds)) ? implode("\n", $deniedembeds) : '');
$embed_coop = intval(get_config('system','embed_coop')); $embed_coop = intval(get_config('system', 'embed_coop'));
if((! $allowedembeds) && (! $deniedembeds)) { if ((!$allowedembeds) && (!$deniedembeds)) {
$embedhelp1 = t("By default, unfiltered HTML is allowed in embedded media. This is inherently insecure."); $embedhelp1 = t("By default, unfiltered HTML is allowed in embedded media. This is inherently insecure.");
} }
@ -134,20 +136,20 @@ class Security {
'$title' => t('Administration'), '$title' => t('Administration'),
'$page' => t('Security'), '$page' => t('Security'),
'$form_security_token' => get_form_security_token('admin_security'), '$form_security_token' => get_form_security_token('admin_security'),
'$block_public' => array('block_public', t("Block public"), get_config('system','block_public'), t("Check to block public access to all otherwise public personal pages on this site unless you are currently authenticated.")), '$block_public' => array('block_public', t("Block public"), get_config('system', 'block_public'), t("Check to block public access to all otherwise public personal pages on this site unless you are currently authenticated.")),
'$block_public_search' => array('block_public_search', t("Block public search"), get_config('system','block_public_search', 1), t("Prevent access to search content unless you are currently authenticated.")), '$block_public_search' => array('block_public_search', t("Block public search"), get_config('system', 'block_public_search', 1), t("Prevent access to search content unless you are currently authenticated.")),
'$block_public_dir' => [ 'block_public_directory', t('Block directory from visitors'), get_config('system','block_public_directory',true), t('Only allow authenticated access to directory.') ], '$block_public_dir' => ['block_public_directory', t('Block directory from visitors'), get_config('system', 'block_public_directory', true), t('Only allow authenticated access to directory.')],
'$localdir_hide' => [ 'localdir_hide', t('Hide local directory'), intval(get_config('system','localdir_hide')), t('Only use the global directory') ], '$localdir_hide' => ['localdir_hide', t('Hide local directory'), intval(get_config('system', 'localdir_hide')), t('Only use the global directory')],
'$cloud_noroot' => [ 'cloud_noroot', t('Provide a cloud root directory'), 1 - intval(get_config('system','cloud_disable_siteroot',true)), t('The cloud root directory lists all channel names which provide public files. Otherwise only the names of connections are shown.') ], '$cloud_noroot' => ['cloud_noroot', t('Provide a cloud root directory'), 1 - intval(get_config('system', 'cloud_disable_siteroot', true)), t('The cloud root directory lists all channel names which provide public files. Otherwise only the names of connections are shown.')],
'$cloud_disksize' => [ 'cloud_disksize', t('Show total disk space available to cloud uploads'), intval(get_config('system','cloud_report_disksize')), '' ], '$cloud_disksize' => ['cloud_disksize', t('Show total disk space available to cloud uploads'), intval(get_config('system', 'cloud_report_disksize')), ''],
'$thumbnail_security' => [ 'thumbnail_security', t("Allow SVG thumbnails in file browser"), get_config('system','thumbnail_security',0), t("WARNING: SVG images may contain malicious code.") ], '$thumbnail_security' => ['thumbnail_security', t("Allow SVG thumbnails in file browser"), get_config('system', 'thumbnail_security', 0), t("WARNING: SVG images may contain malicious code.")],
'$inline_pdf' => [ 'inline_pdf', t("Allow embedded (inline) PDF files"), get_config('system','inline_pdf',0), '' ], '$inline_pdf' => ['inline_pdf', t("Allow embedded (inline) PDF files"), get_config('system', 'inline_pdf', 0), ''],
'$anonymous_comments' => [ 'anonymous_comments', t('Permit anonymous comments'), intval(get_config('system','anonymous_comments')), t('Moderation will be performed by channels that select this comment option.') ], '$anonymous_comments' => ['anonymous_comments', t('Permit anonymous comments'), intval(get_config('system', 'anonymous_comments')), t('Moderation will be performed by channels that select this comment option.')],
'$transport_security' => array('transport_security', t('Set "Transport Security" HTTP header'),intval(get_config('system','transport_security_header')),''), '$transport_security' => array('transport_security', t('Set "Transport Security" HTTP header'), intval(get_config('system', 'transport_security_header')), ''),
'$content_security' => array('content_security', t('Set "Content Security Policy" HTTP header'),intval(get_config('system','content_security_policy')),''), '$content_security' => array('content_security', t('Set "Content Security Policy" HTTP header'), intval(get_config('system', 'content_security_policy')), ''),
'$allowed_email' => array('allowed_email', t("Allowed email domains"), get_config('system','allowed_email'), t("Comma separated list of domains which are allowed in email addresses for registrations to this site. Wildcards are accepted. Empty to allow any domains")), '$allowed_email' => array('allowed_email', t("Allowed email domains"), get_config('system', 'allowed_email'), t("Comma separated list of domains which are allowed in email addresses for registrations to this site. Wildcards are accepted. Empty to allow any domains")),
'$not_allowed_email' => array('not_allowed_email', t("Not allowed email domains"), get_config('system','not_allowed_email'), t("Comma separated list of domains which are not allowed in email addresses for registrations to this site. Wildcards are accepted. Empty to allow any domains, unless allowed domains have been defined.")), '$not_allowed_email' => array('not_allowed_email', t("Not allowed email domains"), get_config('system', 'not_allowed_email'), t("Comma separated list of domains which are not allowed in email addresses for registrations to this site. Wildcards are accepted. Empty to allow any domains, unless allowed domains have been defined.")),
'$allowed_sites' => array('allowed_sites', t('Allow communications only from these sites'), $allowedsites_str, t('One site per line. Leave empty to allow communication from anywhere by default')), '$allowed_sites' => array('allowed_sites', t('Allow communications only from these sites'), $allowedsites_str, t('One site per line. Leave empty to allow communication from anywhere by default')),
'$denied_sites' => array('denied_sites', t('Block communications from these sites'), $deniedsites_str, ''), '$denied_sites' => array('denied_sites', t('Block communications from these sites'), $deniedsites_str, ''),
'$allowed_channels' => array('allowed_channels', t('Allow communications only from these channels'), $allowedchannels_str, t('One channel (hash) per line. Leave empty to allow communication from any channel by default')), '$allowed_channels' => array('allowed_channels', t('Allow communications only from these channels'), $allowedchannels_str, t('One channel (hash) per line. Leave empty to allow communication from any channel by default')),
@ -159,7 +161,7 @@ class Security {
'$psdenied_channels' => array('pubstream_denied_channels', t('Block public stream communications from these channels'), $psdeniedchannels_str, ''), '$psdenied_channels' => array('pubstream_denied_channels', t('Block public stream communications from these channels'), $psdeniedchannels_str, ''),
'$embed_sslonly' => array('embed_sslonly',t('Only allow embeds from secure (SSL) websites and links.'), intval(get_config('system','embed_sslonly')),''), '$embed_sslonly' => array('embed_sslonly', t('Only allow embeds from secure (SSL) websites and links.'), intval(get_config('system', 'embed_sslonly')), ''),
'$embed_allow' => array('embed_allow', t('Allow unfiltered embedded HTML content only from these domains'), $allowedembeds_str, t('One site per line. By default embedded content is filtered.')), '$embed_allow' => array('embed_allow', t('Allow unfiltered embedded HTML content only from these domains'), $allowedembeds_str, t('One site per line. By default embedded content is filtered.')),
'$embed_deny' => array('embed_deny', t('Block embedded HTML from these domains'), $deniedembeds_str, ''), '$embed_deny' => array('embed_deny', t('Block embedded HTML from these domains'), $deniedembeds_str, ''),
@ -170,13 +172,14 @@ class Security {
} }
function trim_array_elems($arr) { public function trim_array_elems($arr)
{
$narr = []; $narr = [];
if($arr && is_array($arr)) { if ($arr && is_array($arr)) {
for($x = 0; $x < count($arr); $x ++) { for ($x = 0; $x < count($arr); $x++) {
$y = trim($arr[$x]); $y = trim($arr[$x]);
if($y) if ($y)
$narr[] = $y; $narr[] = $y;
} }
} }

View file

@ -6,19 +6,21 @@ use App;
use Zotlabs\Lib\System; use Zotlabs\Lib\System;
use Zotlabs\Access\PermissionRoles; use Zotlabs\Access\PermissionRoles;
class Site { class Site
{
/** /**
* @brief POST handler for Admin Site Page. * @brief POST handler for Admin Site Page.
* *
*/ */
function post() { public function post()
{
if(! is_site_admin()) { if (!is_site_admin()) {
return; return;
} }
if (! x($_POST, 'page_site')) { if (!x($_POST, 'page_site')) {
return; return;
} }
@ -26,65 +28,65 @@ class Site {
check_form_security_token_redirectOnErr('/admin/site', 'admin_site'); check_form_security_token_redirectOnErr('/admin/site', 'admin_site');
$sitename = ((x($_POST,'sitename')) ? notags(trim($_POST['sitename'])) : App::get_hostname()); $sitename = ((x($_POST, 'sitename')) ? notags(trim($_POST['sitename'])) : App::get_hostname());
$admininfo = ((x($_POST,'admininfo')) ? trim($_POST['admininfo']) : false); $admininfo = ((x($_POST, 'admininfo')) ? trim($_POST['admininfo']) : false);
$siteinfo = ((x($_POST,'siteinfo')) ? trim($_POST['siteinfo']) : ''); $siteinfo = ((x($_POST, 'siteinfo')) ? trim($_POST['siteinfo']) : '');
$language = ((x($_POST,'language')) ? notags(trim($_POST['language'])) : 'en'); $language = ((x($_POST, 'language')) ? notags(trim($_POST['language'])) : 'en');
$theme = ((x($_POST,'theme')) ? notags(trim($_POST['theme'])) : ''); $theme = ((x($_POST, 'theme')) ? notags(trim($_POST['theme'])) : '');
// $theme_mobile = ((x($_POST,'theme_mobile')) ? notags(trim($_POST['theme_mobile'])) : ''); // $theme_mobile = ((x($_POST,'theme_mobile')) ? notags(trim($_POST['theme_mobile'])) : '');
// $site_channel = ((x($_POST,'site_channel')) ? notags(trim($_POST['site_channel'])) : ''); // $site_channel = ((x($_POST,'site_channel')) ? notags(trim($_POST['site_channel'])) : '');
$maximagesize = ((x($_POST,'maximagesize')) ? intval(trim($_POST['maximagesize'])) : 0); $maximagesize = ((x($_POST, 'maximagesize')) ? intval(trim($_POST['maximagesize'])) : 0);
$register_policy = ((x($_POST,'register_policy')) ? intval(trim($_POST['register_policy'])) : 0); $register_policy = ((x($_POST, 'register_policy')) ? intval(trim($_POST['register_policy'])) : 0);
$minimum_age = ((x($_POST,'minimum_age')) ? intval(trim($_POST['minimum_age'])) : 13); $minimum_age = ((x($_POST, 'minimum_age')) ? intval(trim($_POST['minimum_age'])) : 13);
$access_policy = ((x($_POST,'access_policy')) ? intval(trim($_POST['access_policy'])) : 0); $access_policy = ((x($_POST, 'access_policy')) ? intval(trim($_POST['access_policy'])) : 0);
$invite_only = ((x($_POST,'invite_only')) ? True : False); $invite_only = ((x($_POST, 'invite_only')) ? True : False);
$abandon_days = ((x($_POST,'abandon_days')) ? intval(trim($_POST['abandon_days'])) : 0); $abandon_days = ((x($_POST, 'abandon_days')) ? intval(trim($_POST['abandon_days'])) : 0);
$register_text = ((x($_POST,'register_text')) ? notags(trim($_POST['register_text'])) : ''); $register_text = ((x($_POST, 'register_text')) ? notags(trim($_POST['register_text'])) : '');
$site_sellpage = ((x($_POST,'site_sellpage')) ? notags(trim($_POST['site_sellpage'])) : ''); $site_sellpage = ((x($_POST, 'site_sellpage')) ? notags(trim($_POST['site_sellpage'])) : '');
$site_location = ((x($_POST,'site_location')) ? notags(trim($_POST['site_location'])) : ''); $site_location = ((x($_POST, 'site_location')) ? notags(trim($_POST['site_location'])) : '');
$frontpage = ((x($_POST,'frontpage')) ? notags(trim($_POST['frontpage'])) : ''); $frontpage = ((x($_POST, 'frontpage')) ? notags(trim($_POST['frontpage'])) : '');
$firstpage = ((x($_POST,'firstpage')) ? notags(trim($_POST['firstpage'])) : 'profiles'); $firstpage = ((x($_POST, 'firstpage')) ? notags(trim($_POST['firstpage'])) : 'profiles');
$first_page = ((x($_POST,'first_page')) ? notags(trim($_POST['first_page'])) : 'profiles'); $first_page = ((x($_POST, 'first_page')) ? notags(trim($_POST['first_page'])) : 'profiles');
// check value after trim // check value after trim
if(! $first_page) { if (!$first_page) {
$first_page = 'profiles'; $first_page = 'profiles';
} }
$mirror_frontpage = ((x($_POST,'mirror_frontpage')) ? intval(trim($_POST['mirror_frontpage'])) : 0); $mirror_frontpage = ((x($_POST, 'mirror_frontpage')) ? intval(trim($_POST['mirror_frontpage'])) : 0);
$directory_server = ((x($_POST,'directory_server')) ? trim($_POST['directory_server']) : ''); $directory_server = ((x($_POST, 'directory_server')) ? trim($_POST['directory_server']) : '');
$force_publish = ((x($_POST,'publish_all')) ? True : False); $force_publish = ((x($_POST, 'publish_all')) ? True : False);
$open_pubstream = ((x($_POST,'open_pubstream')) ? True : False); $open_pubstream = ((x($_POST, 'open_pubstream')) ? True : False);
$public_stream_mode = ((x($_POST,'public_stream_mode')) ? intval($_POST['public_stream_mode']) : PUBLIC_STREAM_NONE); $public_stream_mode = ((x($_POST, 'public_stream_mode')) ? intval($_POST['public_stream_mode']) : PUBLIC_STREAM_NONE);
$animations = ((x($_POST,'animations')) ? True : False); $animations = ((x($_POST, 'animations')) ? True : False);
$login_on_homepage = ((x($_POST,'login_on_homepage')) ? True : False); $login_on_homepage = ((x($_POST, 'login_on_homepage')) ? True : False);
$enable_context_help = ((x($_POST,'enable_context_help')) ? True : False); $enable_context_help = ((x($_POST, 'enable_context_help')) ? True : False);
$global_directory = ((x($_POST,'directory_submit_url')) ? notags(trim($_POST['directory_submit_url'])) : ''); $global_directory = ((x($_POST, 'directory_submit_url')) ? notags(trim($_POST['directory_submit_url'])) : '');
$no_community_page = !((x($_POST,'no_community_page')) ? True : False); $no_community_page = !((x($_POST, 'no_community_page')) ? True : False);
$default_expire_days = ((array_key_exists('default_expire_days',$_POST)) ? intval($_POST['default_expire_days']) : 0); $default_expire_days = ((array_key_exists('default_expire_days', $_POST)) ? intval($_POST['default_expire_days']) : 0);
$active_expire_days = ((array_key_exists('active_expire_days',$_POST)) ? intval($_POST['active_expire_days']) : 7); $active_expire_days = ((array_key_exists('active_expire_days', $_POST)) ? intval($_POST['active_expire_days']) : 7);
$max_imported_follow = ((x($_POST,'max_imported_follow')) ? intval(trim($_POST['max_imported_follow'])) : MAX_IMPORTED_FOLLOW); $max_imported_follow = ((x($_POST, 'max_imported_follow')) ? intval(trim($_POST['max_imported_follow'])) : MAX_IMPORTED_FOLLOW);
$reply_address = ((array_key_exists('reply_address',$_POST) && trim($_POST['reply_address'])) ? trim($_POST['reply_address']) : 'noreply@' . App::get_hostname()); $reply_address = ((array_key_exists('reply_address', $_POST) && trim($_POST['reply_address'])) ? trim($_POST['reply_address']) : 'noreply@' . App::get_hostname());
$from_email = ((array_key_exists('from_email',$_POST) && trim($_POST['from_email'])) ? trim($_POST['from_email']) : 'Administrator@' . App::get_hostname()); $from_email = ((array_key_exists('from_email', $_POST) && trim($_POST['from_email'])) ? trim($_POST['from_email']) : 'Administrator@' . App::get_hostname());
$from_email_name = ((array_key_exists('from_email_name',$_POST) && trim($_POST['from_email_name'])) ? trim($_POST['from_email_name']) : System::get_site_name()); $from_email_name = ((array_key_exists('from_email_name', $_POST) && trim($_POST['from_email_name'])) ? trim($_POST['from_email_name']) : System::get_site_name());
$verifyssl = ((x($_POST,'verifyssl')) ? True : False); $verifyssl = ((x($_POST, 'verifyssl')) ? True : False);
$proxyuser = ((x($_POST,'proxyuser')) ? notags(trim($_POST['proxyuser'])) : ''); $proxyuser = ((x($_POST, 'proxyuser')) ? notags(trim($_POST['proxyuser'])) : '');
$proxy = ((x($_POST,'proxy')) ? notags(trim($_POST['proxy'])) : ''); $proxy = ((x($_POST, 'proxy')) ? notags(trim($_POST['proxy'])) : '');
$timeout = ((x($_POST,'timeout')) ? intval(trim($_POST['timeout'])) : 60); $timeout = ((x($_POST, 'timeout')) ? intval(trim($_POST['timeout'])) : 60);
$post_timeout = ((x($_POST,'post_timeout')) ? intval(trim($_POST['post_timeout'])) : 90); $post_timeout = ((x($_POST, 'post_timeout')) ? intval(trim($_POST['post_timeout'])) : 90);
$show_like_counts = ((x($_POST,'show_like_counts')) ? intval(trim($_POST['show_like_counts'])) : 0); $show_like_counts = ((x($_POST, 'show_like_counts')) ? intval(trim($_POST['show_like_counts'])) : 0);
$cache_images = ((x($_POST,'cache_images')) ? intval(trim($_POST['cache_images'])) : 0); $cache_images = ((x($_POST, 'cache_images')) ? intval(trim($_POST['cache_images'])) : 0);
$delivery_interval = ((x($_POST,'delivery_interval'))? intval(trim($_POST['delivery_interval'])) : 0); $delivery_interval = ((x($_POST, 'delivery_interval')) ? intval(trim($_POST['delivery_interval'])) : 0);
$delivery_batch_count = ((x($_POST,'delivery_batch_count') && $_POST['delivery_batch_count'] > 0)? intval(trim($_POST['delivery_batch_count'])) : 3); $delivery_batch_count = ((x($_POST, 'delivery_batch_count') && $_POST['delivery_batch_count'] > 0) ? intval(trim($_POST['delivery_batch_count'])) : 3);
$poll_interval = ((x($_POST,'poll_interval')) ? intval(trim($_POST['poll_interval'])) : 0); $poll_interval = ((x($_POST, 'poll_interval')) ? intval(trim($_POST['poll_interval'])) : 0);
$maxloadavg = ((x($_POST,'maxloadavg')) ? intval(trim($_POST['maxloadavg'])) : 50); $maxloadavg = ((x($_POST, 'maxloadavg')) ? intval(trim($_POST['maxloadavg'])) : 50);
// $feed_contacts = ((x($_POST,'feed_contacts')) ? intval($_POST['feed_contacts']) : 0); // $feed_contacts = ((x($_POST,'feed_contacts')) ? intval($_POST['feed_contacts']) : 0);
$ap_contacts = ((x($_POST,'ap_contacts')) ? intval($_POST['ap_contacts']) : 0); $ap_contacts = ((x($_POST, 'ap_contacts')) ? intval($_POST['ap_contacts']) : 0);
$verify_email = ((x($_POST,'verify_email')) ? 1 : 0); $verify_email = ((x($_POST, 'verify_email')) ? 1 : 0);
$imagick_path = ((x($_POST,'imagick_path')) ? trim($_POST['imagick_path']) : ''); $imagick_path = ((x($_POST, 'imagick_path')) ? trim($_POST['imagick_path']) : '');
$force_queue = ((intval($_POST['force_queue']) > 0) ? intval($_POST['force_queue']) : 3000); $force_queue = ((intval($_POST['force_queue']) > 0) ? intval($_POST['force_queue']) : 3000);
$pub_incl = escape_tags(trim($_POST['pub_incl'])); $pub_incl = escape_tags(trim($_POST['pub_incl']));
$pub_excl = escape_tags(trim($_POST['pub_excl'])); $pub_excl = escape_tags(trim($_POST['pub_excl']));
@ -111,29 +113,28 @@ class Site {
set_config('system', 'active_expire_days', $active_expire_days); set_config('system', 'active_expire_days', $active_expire_days);
set_config('system', 'reply_address', $reply_address); set_config('system', 'reply_address', $reply_address);
set_config('system', 'from_email', $from_email); set_config('system', 'from_email', $from_email);
set_config('system', 'from_email_name' , $from_email_name); set_config('system', 'from_email_name', $from_email_name);
set_config('system', 'imagick_convert_path' , $imagick_path); set_config('system', 'imagick_convert_path', $imagick_path);
set_config('system', 'default_permissions_role', $permissions_role); set_config('system', 'default_permissions_role', $permissions_role);
set_config('system', 'show_like_counts', $show_like_counts); set_config('system', 'show_like_counts', $show_like_counts);
set_config('system', 'pubstream_incl',$pub_incl); set_config('system', 'pubstream_incl', $pub_incl);
set_config('system', 'pubstream_excl',$pub_excl); set_config('system', 'pubstream_excl', $pub_excl);
set_config('system', 'max_imported_follow', $max_imported_follow); set_config('system', 'max_imported_follow', $max_imported_follow);
set_config('system', 'animated_avatars', $animations); set_config('system', 'animated_avatars', $animations);
if ($directory_server) { if ($directory_server) {
set_config('system','directory_server',$directory_server); set_config('system', 'directory_server', $directory_server);
} }
if ($admininfo == '') { if ($admininfo == '') {
del_config('system', 'admininfo'); del_config('system', 'admininfo');
} } else {
else {
require_once('include/text.php'); require_once('include/text.php');
linkify_tags($admininfo, local_channel()); linkify_tags($admininfo, local_channel());
set_config('system', 'admininfo', $admininfo); set_config('system', 'admininfo', $admininfo);
} }
set_config('system','siteinfo',$siteinfo); set_config('system', 'siteinfo', $siteinfo);
// sync sitename and siteinfo updates to the system channel // sync sitename and siteinfo updates to the system channel
@ -158,34 +159,34 @@ class Site {
set_config('system', 'language', $language); set_config('system', 'language', $language);
set_config('system', 'theme', $theme); set_config('system', 'theme', $theme);
// set_config('system','site_channel', $site_channel); // set_config('system','site_channel', $site_channel);
set_config('system','maximagesize', $maximagesize); set_config('system', 'maximagesize', $maximagesize);
set_config('system','register_policy', $register_policy); set_config('system', 'register_policy', $register_policy);
set_config('system','minimum_age', $minimum_age); set_config('system', 'minimum_age', $minimum_age);
set_config('system','invitation_only', $invite_only); set_config('system', 'invitation_only', $invite_only);
set_config('system','access_policy', $access_policy); set_config('system', 'access_policy', $access_policy);
set_config('system','account_abandon_days', $abandon_days); set_config('system', 'account_abandon_days', $abandon_days);
set_config('system','register_text', $register_text); set_config('system', 'register_text', $register_text);
set_config('system','publish_all', $force_publish); set_config('system', 'publish_all', $force_publish);
set_config('system','public_stream_mode', $public_stream_mode); set_config('system', 'public_stream_mode', $public_stream_mode);
set_config('system','open_pubstream', $open_pubstream); set_config('system', 'open_pubstream', $open_pubstream);
set_config('system','force_queue_threshold', $force_queue); set_config('system', 'force_queue_threshold', $force_queue);
if ($global_directory == '') { if ($global_directory == '') {
del_config('system', 'directory_submit_url'); del_config('system', 'directory_submit_url');
} else { } else {
set_config('system', 'directory_submit_url', $global_directory); set_config('system', 'directory_submit_url', $global_directory);
} }
set_config('system','no_community_page', $no_community_page); set_config('system', 'no_community_page', $no_community_page);
set_config('system','no_utf', $no_utf); set_config('system', 'no_utf', $no_utf);
set_config('system','verifyssl', $verifyssl); set_config('system', 'verifyssl', $verifyssl);
set_config('system','proxyuser', $proxyuser); set_config('system', 'proxyuser', $proxyuser);
set_config('system','proxy', $proxy); set_config('system', 'proxy', $proxy);
set_config('system','curl_timeout', $timeout); set_config('system', 'curl_timeout', $timeout);
set_config('system','curl_post_timeout', $post_timeout); set_config('system', 'curl_post_timeout', $post_timeout);
info( t('Site settings updated.') . EOL); info(t('Site settings updated.') . EOL);
goaway(z_root() . '/admin/site' ); goaway(z_root() . '/admin/site');
} }
/** /**
@ -194,18 +195,19 @@ class Site {
* @return string with HTML * @return string with HTML
*/ */
function get() { public function get()
{
/* Installed langs */ /* Installed langs */
$lang_choices = []; $lang_choices = [];
$langs = glob('view/*/strings.php'); $langs = glob('view/*/strings.php');
if (is_array($langs) && count($langs)) { if (is_array($langs) && count($langs)) {
if (! in_array('view/en/strings.php',$langs)) if (!in_array('view/en/strings.php', $langs))
$langs[] = 'view/en/'; $langs[] = 'view/en/';
asort($langs); asort($langs);
foreach ($langs as $l) { foreach ($langs as $l) {
$t = explode("/",$l); $t = explode("/", $l);
$lang_choices[$t[1]] = $t[1]; $lang_choices[$t[1]] = $t[1];
} }
} }
@ -221,7 +223,7 @@ class Site {
$info = get_theme_info($f); $info = get_theme_info($f);
$compatible = check_plugin_versions($info); $compatible = check_plugin_versions($info);
if (! $compatible) { if (!$compatible) {
$theme_choices[$f] = $theme_choices_mobile[$f] = sprintf(t('%s - (Incompatible)'), $f); $theme_choices[$f] = $theme_choices_mobile[$f] = sprintf(t('%s - (Incompatible)'), $f);
continue; continue;
} }
@ -237,8 +239,7 @@ class Site {
if ($vars) { if ($vars) {
$theme_choices[$f] = $f . ' (' . $vars . ')'; $theme_choices[$f] = $f . ' (' . $vars . ')';
$theme_choices_mobile[$f] = $f . ' (' . $vars . ')'; $theme_choices_mobile[$f] = $f . ' (' . $vars . ')';
} } else {
else {
$theme_choices[$f] = $f; $theme_choices[$f] = $f;
$theme_choices_mobile[$f] = $f; $theme_choices_mobile[$f] = $f;
} }
@ -246,7 +247,7 @@ class Site {
} }
$dir_choices = null; $dir_choices = null;
$dirmode = get_config('system','directory_mode'); $dirmode = get_config('system', 'directory_mode');
$realm = get_directory_realm(); $realm = get_directory_realm();
// directory server should not be set or settable unless we are a directory client // directory server should not be set or settable unless we are a directory client
@ -287,13 +288,13 @@ class Site {
]; ];
$perm_roles = PermissionRoles::roles(); $perm_roles = PermissionRoles::roles();
$default_role = get_config('system','default_permissions_role','social'); $default_role = get_config('system', 'default_permissions_role', 'social');
$role = [ 'permissions_role' , t('Default permission role for new accounts'), $default_role, t('This role will be used for the first channel created after registration.'),$perm_roles ]; $role = ['permissions_role', t('Default permission role for new accounts'), $default_role, t('This role will be used for the first channel created after registration.'), $perm_roles];
$homelogin = get_config('system','login_on_homepage'); $homelogin = get_config('system', 'login_on_homepage');
$enable_context_help = get_config('system','enable_context_help'); $enable_context_help = get_config('system', 'enable_context_help');
return replace_macros(get_markup_template('admin_site.tpl'), [ return replace_macros(get_markup_template('admin_site.tpl'), [
'$title' => t('Administration'), '$title' => t('Administration'),
@ -305,63 +306,63 @@ class Site {
'$corporate' => t('Policies'), '$corporate' => t('Policies'),
'$advanced' => t('Advanced'), '$advanced' => t('Advanced'),
'$baseurl' => z_root(), '$baseurl' => z_root(),
'$sitename' => [ 'sitename', t("Site name"), htmlspecialchars(get_config('system','sitename', App::get_hostname()), ENT_QUOTES, 'UTF-8'),'' ], '$sitename' => ['sitename', t("Site name"), htmlspecialchars(get_config('system', 'sitename', App::get_hostname()), ENT_QUOTES, 'UTF-8'), ''],
'$admininfo' => [ 'admininfo', t("Administrator Information"), $admininfo, t("Contact information for site administrators. Displayed on siteinfo page. BBCode may be used here.") ], '$admininfo' => ['admininfo', t("Administrator Information"), $admininfo, t("Contact information for site administrators. Displayed on siteinfo page. BBCode may be used here.")],
'$siteinfo' => [ 'siteinfo', t('Site Information'), get_config('system','siteinfo'), t("Publicly visible description of this site. Displayed on siteinfo page. BBCode may be used here.") ], '$siteinfo' => ['siteinfo', t('Site Information'), get_config('system', 'siteinfo'), t("Publicly visible description of this site. Displayed on siteinfo page. BBCode may be used here.")],
'$language' => [ 'language', t("System language"), get_config('system','language','en'), "", $lang_choices ], '$language' => ['language', t("System language"), get_config('system', 'language', 'en'), "", $lang_choices],
'$theme' => [ 'theme', t("System theme"), get_config('system','theme'), t("Default system theme - may be over-ridden by user profiles - <a href='#' id='cnftheme'>change theme settings</a>"), $theme_choices ], '$theme' => ['theme', t("System theme"), get_config('system', 'theme'), t("Default system theme - may be over-ridden by user profiles - <a href='#' id='cnftheme'>change theme settings</a>"), $theme_choices],
// '$theme_mobile' => [ 'theme_mobile', t("Mobile system theme"), get_config('system','mobile_theme'), t("Theme for mobile devices"), $theme_choices_mobile ], // '$theme_mobile' => [ 'theme_mobile', t("Mobile system theme"), get_config('system','mobile_theme'), t("Theme for mobile devices"), $theme_choices_mobile ],
// '$site_channel' => [ 'site_channel', t("Channel to use for this website's static pages"), get_config('system','site_channel'), t("Site Channel") ], // '$site_channel' => [ 'site_channel', t("Channel to use for this website's static pages"), get_config('system','site_channel'), t("Site Channel") ],
'$ap_contacts' => [ 'ap_contacts', t('ActivityPub protocol'),get_config('system','activitypub', ACTIVITYPUB_ENABLED),t('Provides access to software supporting the ActivityPub protocol.') ], '$ap_contacts' => ['ap_contacts', t('ActivityPub protocol'), get_config('system', 'activitypub', ACTIVITYPUB_ENABLED), t('Provides access to software supporting the ActivityPub protocol.')],
'$maximagesize' => [ 'maximagesize', t("Maximum image size"), intval(get_config('system','maximagesize')), t("Maximum size in bytes of uploaded images. Default is 0, which means no limits.") ], '$maximagesize' => ['maximagesize', t("Maximum image size"), intval(get_config('system', 'maximagesize')), t("Maximum size in bytes of uploaded images. Default is 0, which means no limits.")],
'$cache_images' => [ 'cache_images', t('Cache all public images'), intval(get_config('system','cache_images',1)), t('If disabled, proxy non-SSL images, but do not store locally') ], '$cache_images' => ['cache_images', t('Cache all public images'), intval(get_config('system', 'cache_images', 1)), t('If disabled, proxy non-SSL images, but do not store locally')],
'$register_policy' => [ 'register_policy', t("Does this site allow new member registration?"), get_config('system','register_policy'), "", $register_choices ], '$register_policy' => ['register_policy', t("Does this site allow new member registration?"), get_config('system', 'register_policy'), "", $register_choices],
'$invite_only' => [ 'invite_only', t("Invitation only"), get_config('system','invitation_only'), t("Only allow new member registrations with an invitation code. New member registration must be allowed for this to work.") ], '$invite_only' => ['invite_only', t("Invitation only"), get_config('system', 'invitation_only'), t("Only allow new member registrations with an invitation code. New member registration must be allowed for this to work.")],
'$invite_working' => defined('INVITE_WORKING'), '$invite_working' => defined('INVITE_WORKING'),
'$minimum_age' => [ 'minimum_age', t("Minimum age"), (x(get_config('system','minimum_age'))?get_config('system','minimum_age'):13), t("Minimum age (in years) for who may register on this site.") ], '$minimum_age' => ['minimum_age', t("Minimum age"), (x(get_config('system', 'minimum_age')) ? get_config('system', 'minimum_age') : 13), t("Minimum age (in years) for who may register on this site.")],
'$access_policy' => [ 'access_policy', t("Which best describes the types of account offered by this hub?"), get_config('system','access_policy'), t("If a public server policy is selected, this information may be displayed on the public server site list."), $access_choices ], '$access_policy' => ['access_policy', t("Which best describes the types of account offered by this hub?"), get_config('system', 'access_policy'), t("If a public server policy is selected, this information may be displayed on the public server site list."), $access_choices],
'$register_text' => [ 'register_text', t("Register text"), htmlspecialchars(get_config('system','register_text'), ENT_QUOTES, 'UTF-8'), t("Will be displayed prominently on the registration page.") ], '$register_text' => ['register_text', t("Register text"), htmlspecialchars(get_config('system', 'register_text'), ENT_QUOTES, 'UTF-8'), t("Will be displayed prominently on the registration page.")],
'$role' => $role, '$role' => $role,
'$frontpage' => [ 'frontpage', t("Site homepage to show visitors (default: login box)"), get_config('system','frontpage'), t("example: 'public' to show public stream, 'page/sys/home' to show a system webpage called 'home' or 'include:home.html' to include a file.") ], '$frontpage' => ['frontpage', t("Site homepage to show visitors (default: login box)"), get_config('system', 'frontpage'), t("example: 'public' to show public stream, 'page/sys/home' to show a system webpage called 'home' or 'include:home.html' to include a file.")],
'$mirror_frontpage' => [ 'mirror_frontpage', t("Preserve site homepage URL"), get_config('system','mirror_frontpage'), t('Present the site homepage in a frame at the original location instead of redirecting') ], '$mirror_frontpage' => ['mirror_frontpage', t("Preserve site homepage URL"), get_config('system', 'mirror_frontpage'), t('Present the site homepage in a frame at the original location instead of redirecting')],
'$abandon_days' => [ 'abandon_days', t('Accounts abandoned after x days'), get_config('system','account_abandon_days'), t('Will not waste system resources polling external sites for abandonded accounts. Enter 0 for no time limit.') ], '$abandon_days' => ['abandon_days', t('Accounts abandoned after x days'), get_config('system', 'account_abandon_days'), t('Will not waste system resources polling external sites for abandonded accounts. Enter 0 for no time limit.')],
'$block_public_dir' => [ 'block_public_directory', t('Block directory from visitors'), get_config('system','block_public_directory',true), t('Only allow authenticated access to directory.') ], '$block_public_dir' => ['block_public_directory', t('Block directory from visitors'), get_config('system', 'block_public_directory', true), t('Only allow authenticated access to directory.')],
'$verify_email' => [ 'verify_email', t("Verify Email Addresses"), get_config('system','verify_email'), t("Check to verify email addresses used in account registration (recommended).") ], '$verify_email' => ['verify_email', t("Verify Email Addresses"), get_config('system', 'verify_email'), t("Check to verify email addresses used in account registration (recommended).")],
'$force_publish' => [ 'publish_all', t("Force publish in directory"), get_config('system','publish_all'), t("Check to force all profiles on this site to be listed in the site directory.") ], '$force_publish' => ['publish_all', t("Force publish in directory"), get_config('system', 'publish_all'), t("Check to force all profiles on this site to be listed in the site directory.")],
'$public_stream_mode' => [ 'public_stream_mode', t('Public stream'), intval(get_config('system','public_stream_mode',0)), t('Provide a Public stream on your site. This content is unmoderated.'), [ '$public_stream_mode' => ['public_stream_mode', t('Public stream'), intval(get_config('system', 'public_stream_mode', 0)), t('Provide a Public stream on your site. This content is unmoderated.'), [
0 => t('the Public stream is disabled'), 0 => t('the Public stream is disabled'),
1 => t('the Public stream contains public conversations from this site only'), 1 => t('the Public stream contains public conversations from this site only'),
2 => t('the Public stream contains public conversations from anywhere on the internet'), 2 => t('the Public stream contains public conversations from anywhere on the internet'),
]], ]],
'$open_pubstream' => [ 'open_pubstream', t('Allow anybody on the internet to access the Public stream'), get_config('system','open_pubstream',0), t('Default is to only allow viewing by site members. Warning: this content is unmoderated.') ], '$open_pubstream' => ['open_pubstream', t('Allow anybody on the internet to access the Public stream'), get_config('system', 'open_pubstream', 0), t('Default is to only allow viewing by site members. Warning: this content is unmoderated.')],
'$show_like_counts' => [ 'show_like_counts', t('Show numbers of likes and dislikes in conversations'), get_config('system','show_like_counts',1), t('If disabled, the presence of likes and dislikes will be shown, but without totals.') ], '$show_like_counts' => ['show_like_counts', t('Show numbers of likes and dislikes in conversations'), get_config('system', 'show_like_counts', 1), t('If disabled, the presence of likes and dislikes will be shown, but without totals.')],
'$animations' => [ 'animations', t('Permit animated profile photos'), get_config('system','animated_avatars',true), t('Changing this may take several days to work through the system') ], '$animations' => ['animations', t('Permit animated profile photos'), get_config('system', 'animated_avatars', true), t('Changing this may take several days to work through the system')],
'$incl' => [ 'pub_incl',t('Only import Public stream posts with this text'), get_config('system','pubstream_incl'),t('words one per line or #tags or /patterns/ or lang=xx, leave blank to import all posts') ], '$incl' => ['pub_incl', t('Only import Public stream posts with this text'), get_config('system', 'pubstream_incl'), t('words one per line or #tags or /patterns/ or lang=xx, leave blank to import all posts')],
'$excl' => [ 'pub_excl',t('Do not import Public stream posts with this text'), get_config('system','pubstream_excl'),t('words one per line or #tags or /patterns/ or lang=xx, leave blank to import all posts') ], '$excl' => ['pub_excl', t('Do not import Public stream posts with this text'), get_config('system', 'pubstream_excl'), t('words one per line or #tags or /patterns/ or lang=xx, leave blank to import all posts')],
'$max_imported_follow' => [ 'max_imported_follow', t('Maximum number of imported friends of friends'), get_config('system','max_imported_follow', MAX_IMPORTED_FOLLOW), t('Warning: higher numbers will improve the quality of friend suggestions and directory results but can exponentially increase resource usage') ], '$max_imported_follow' => ['max_imported_follow', t('Maximum number of imported friends of friends'), get_config('system', 'max_imported_follow', MAX_IMPORTED_FOLLOW), t('Warning: higher numbers will improve the quality of friend suggestions and directory results but can exponentially increase resource usage')],
'$login_on_homepage' => [ 'login_on_homepage', t("Login on Homepage"),((intval($homelogin) || $homelogin === false) ? 1 : '') , t("Present a login box to visitors on the home page if no other content has been configured.") ], '$login_on_homepage' => ['login_on_homepage', t("Login on Homepage"), ((intval($homelogin) || $homelogin === false) ? 1 : ''), t("Present a login box to visitors on the home page if no other content has been configured.")],
'$enable_context_help' => [ 'enable_context_help', t("Enable context help"),((intval($enable_context_help) === 1 || $enable_context_help === false) ? 1 : 0) , t("Display contextual help for the current page when the help button is pressed.") ], '$enable_context_help' => ['enable_context_help', t("Enable context help"), ((intval($enable_context_help) === 1 || $enable_context_help === false) ? 1 : 0), t("Display contextual help for the current page when the help button is pressed.")],
'$reply_address' => [ 'reply_address', t('Reply-to email address for system generated email.'), get_config('system','reply_address','noreply@' . App::get_hostname()),'' ], '$reply_address' => ['reply_address', t('Reply-to email address for system generated email.'), get_config('system', 'reply_address', 'noreply@' . App::get_hostname()), ''],
'$from_email' => [ 'from_email', t('Sender (From) email address for system generated email.'), get_config('system','from_email','Administrator@' . App::get_hostname()),'' ], '$from_email' => ['from_email', t('Sender (From) email address for system generated email.'), get_config('system', 'from_email', 'Administrator@' . App::get_hostname()), ''],
'$from_email_name' => [ 'from_email_name', t('Display name of email sender for system generated email.'), get_config('system','from_email_name', System::get_site_name()),'' ], '$from_email_name' => ['from_email_name', t('Display name of email sender for system generated email.'), get_config('system', 'from_email_name', System::get_site_name()), ''],
'$directory_server' => (($dir_choices) ? [ 'directory_server', t("Directory Server URL"), get_config('system','directory_server'), t("Default directory server"), $dir_choices ] : null), '$directory_server' => (($dir_choices) ? ['directory_server', t("Directory Server URL"), get_config('system', 'directory_server'), t("Default directory server"), $dir_choices] : null),
'$proxyuser' => [ 'proxyuser', t("Proxy user"), get_config('system','proxyuser'), "" ], '$proxyuser' => ['proxyuser', t("Proxy user"), get_config('system', 'proxyuser'), ""],
'$proxy' => [ 'proxy', t("Proxy URL"), get_config('system','proxy'), "" ], '$proxy' => ['proxy', t("Proxy URL"), get_config('system', 'proxy'), ""],
'$timeout' => [ 'timeout', t("Network fetch timeout"), (x(get_config('system','curl_timeout'))?get_config('system','curl_timeout'):60), t("Value is in seconds. Set to 0 for unlimited (not recommended).") ], '$timeout' => ['timeout', t("Network fetch timeout"), (x(get_config('system', 'curl_timeout')) ? get_config('system', 'curl_timeout') : 60), t("Value is in seconds. Set to 0 for unlimited (not recommended).")],
'$post_timeout' => [ 'post_timeout', t("Network post timeout"), (x(get_config('system','curl_post_timeout'))?get_config('system','curl_post_timeout'):90), t("Value is in seconds. Set to 0 for unlimited (not recommended).") ], '$post_timeout' => ['post_timeout', t("Network post timeout"), (x(get_config('system', 'curl_post_timeout')) ? get_config('system', 'curl_post_timeout') : 90), t("Value is in seconds. Set to 0 for unlimited (not recommended).")],
'$delivery_interval' => [ 'delivery_interval', t("Delivery interval"), (x(get_config('system','delivery_interval'))?get_config('system','delivery_interval'):2), t("Delay background delivery processes by this many seconds to reduce system load. Recommend: 4-5 for shared hosts, 2-3 for virtual private servers. 0-1 for large dedicated servers.") ], '$delivery_interval' => ['delivery_interval', t("Delivery interval"), (x(get_config('system', 'delivery_interval')) ? get_config('system', 'delivery_interval') : 2), t("Delay background delivery processes by this many seconds to reduce system load. Recommend: 4-5 for shared hosts, 2-3 for virtual private servers. 0-1 for large dedicated servers.")],
'$delivery_batch_count' => [ 'delivery_batch_count', t('Deliveries per process'),(x(get_config('system','delivery_batch_count'))?get_config('system','delivery_batch_count'):3), t("Number of deliveries to attempt in a single operating system process. Adjust if necessary to tune system performance. Recommend: 1-5.") ], '$delivery_batch_count' => ['delivery_batch_count', t('Deliveries per process'), (x(get_config('system', 'delivery_batch_count')) ? get_config('system', 'delivery_batch_count') : 3), t("Number of deliveries to attempt in a single operating system process. Adjust if necessary to tune system performance. Recommend: 1-5.")],
'$force_queue' => [ 'force_queue', t("Queue Threshold"), get_config('system','force_queue_threshold',3000), t("Always defer immediate delivery if queue contains more than this number of entries.") ], '$force_queue' => ['force_queue', t("Queue Threshold"), get_config('system', 'force_queue_threshold', 3000), t("Always defer immediate delivery if queue contains more than this number of entries.")],
'$poll_interval' => [ 'poll_interval', t("Poll interval"), (x(get_config('system','poll_interval'))?get_config('system','poll_interval'):2), t("Delay background polling processes by this many seconds to reduce system load. If 0, use delivery interval.") ], '$poll_interval' => ['poll_interval', t("Poll interval"), (x(get_config('system', 'poll_interval')) ? get_config('system', 'poll_interval') : 2), t("Delay background polling processes by this many seconds to reduce system load. If 0, use delivery interval.")],
'$imagick_path' => [ 'imagick_path', t("Path to ImageMagick convert program"), get_config('system','imagick_convert_path'), t("If set, use this program to generate photo thumbnails for huge images ( > 4000 pixels in either dimension), otherwise memory exhaustion may occur. Example: /usr/bin/convert") ], '$imagick_path' => ['imagick_path', t("Path to ImageMagick convert program"), get_config('system', 'imagick_convert_path'), t("If set, use this program to generate photo thumbnails for huge images ( > 4000 pixels in either dimension), otherwise memory exhaustion may occur. Example: /usr/bin/convert")],
'$maxloadavg' => [ 'maxloadavg', t("Maximum Load Average"), ((intval(get_config('system','maxloadavg')) > 0)?get_config('system','maxloadavg'):50), t("Maximum system load before delivery and poll processes are deferred - default 50.") ], '$maxloadavg' => ['maxloadavg', t("Maximum Load Average"), ((intval(get_config('system', 'maxloadavg')) > 0) ? get_config('system', 'maxloadavg') : 50), t("Maximum system load before delivery and poll processes are deferred - default 50.")],
'$default_expire_days' => [ 'default_expire_days', t('Expiration period in days for imported streams and cached images'), intval(get_config('system','default_expire_days',60)), t('0 for no expiration of imported content') ], '$default_expire_days' => ['default_expire_days', t('Expiration period in days for imported streams and cached images'), intval(get_config('system', 'default_expire_days', 60)), t('0 for no expiration of imported content')],
'$active_expire_days' => [ 'active_expire_days', t('Do not expire any posts which have comments less than this many days ago'), intval(get_config('system','active_expire_days',7)), '' ], '$active_expire_days' => ['active_expire_days', t('Do not expire any posts which have comments less than this many days ago'), intval(get_config('system', 'active_expire_days', 7)), ''],
'$sellpage' => [ 'site_sellpage', t('Public servers: Optional landing (marketing) webpage for new registrants'), get_config('system','sellpage',''), sprintf( t('Create this page first. Default is %s/register'),z_root()) ], '$sellpage' => ['site_sellpage', t('Public servers: Optional landing (marketing) webpage for new registrants'), get_config('system', 'sellpage', ''), sprintf(t('Create this page first. Default is %s/register'), z_root())],
'$first_page' => [ 'first_page', t('Page to display after creating a new channel'), get_config('system','workflow_channel_next','profiles'), t('Default: profiles') ], '$first_page' => ['first_page', t('Page to display after creating a new channel'), get_config('system', 'workflow_channel_next', 'profiles'), t('Default: profiles')],
'$location' => [ 'site_location', t('Site location'), get_config('system','site_location',''), t('Region or country - shared with other sites') ], '$location' => ['site_location', t('Site location'), get_config('system', 'site_location', ''), t('Region or country - shared with other sites')],
'$form_security_token' => get_form_security_token("admin_site"), '$form_security_token' => get_form_security_token("admin_site"),
]); ]);
} }

View file

@ -8,27 +8,29 @@ use Michelf\MarkdownExtra;
/** /**
* @brief Admin area theme settings. * @brief Admin area theme settings.
*/ */
class Themes { class Themes
{
/** /**
* @brief * @brief
* *
*/ */
function post() { public function post()
{
$theme = argv(2); $theme = argv(2);
if (is_file("view/theme/$theme/php/config.php")){ if (is_file("view/theme/$theme/php/config.php")) {
require_once("view/theme/$theme/php/config.php"); require_once("view/theme/$theme/php/config.php");
/// @FIXME add parent theme if derived /// @FIXME add parent theme if derived
if (function_exists('theme_admin_post')){ if (function_exists('theme_admin_post')) {
theme_admin_post($a); theme_admin_post($a);
} }
} }
info(t('Theme settings updated.')); info(t('Theme settings updated.'));
if(is_ajax()) if (is_ajax())
return; return;
goaway(z_root() . '/admin/themes/' . $theme ); goaway(z_root() . '/admin/themes/' . $theme);
} }
@ -37,29 +39,30 @@ class Themes {
* *
* @return string with parsed HTML * @return string with parsed HTML
*/ */
function get(){ public function get()
{
$allowed_themes_str = get_config('system', 'allowed_themes'); $allowed_themes_str = get_config('system', 'allowed_themes');
$allowed_themes_raw = explode(',', $allowed_themes_str); $allowed_themes_raw = explode(',', $allowed_themes_str);
$allowed_themes = []; $allowed_themes = [];
if(count($allowed_themes_raw)) if (count($allowed_themes_raw))
foreach($allowed_themes_raw as $x) foreach ($allowed_themes_raw as $x)
if(strlen(trim($x))) if (strlen(trim($x)))
$allowed_themes[] = trim($x); $allowed_themes[] = trim($x);
$themes = []; $themes = [];
$files = glob('view/theme/*'); $files = glob('view/theme/*');
if($files) { if ($files) {
foreach($files as $file) { foreach ($files as $file) {
$f = basename($file); $f = basename($file);
$is_experimental = intval(file_exists($file . '/.experimental')); $is_experimental = intval(file_exists($file . '/.experimental'));
$is_supported = 1-(intval(file_exists($file . '/.unsupported'))); // Is not used yet $is_supported = 1 - (intval(file_exists($file . '/.unsupported'))); // Is not used yet
$is_allowed = intval(in_array($f,$allowed_themes)); $is_allowed = intval(in_array($f, $allowed_themes));
$themes[] = array('name' => $f, 'experimental' => $is_experimental, 'supported' => $is_supported, 'allowed' => $is_allowed); $themes[] = array('name' => $f, 'experimental' => $is_experimental, 'supported' => $is_supported, 'allowed' => $is_allowed);
} }
} }
if(! count($themes)) { if (!count($themes)) {
notice( t('No themes found.')); notice(t('No themes found.'));
return ''; return '';
} }
@ -67,55 +70,57 @@ class Themes {
* Single theme * Single theme
*/ */
if (App::$argc == 3){ if (App::$argc == 3) {
$theme = App::$argv[2]; $theme = App::$argv[2];
if(! is_dir("view/theme/$theme")){ if (!is_dir("view/theme/$theme")) {
notice( t("Item not found.") ); notice(t("Item not found."));
return ''; return '';
} }
if (x($_GET,"a") && $_GET['a']=="t"){ if (x($_GET, "a") && $_GET['a'] == "t") {
check_form_security_token_redirectOnErr('/admin/themes', 'admin_themes', 't'); check_form_security_token_redirectOnErr('/admin/themes', 'admin_themes', 't');
// Toggle theme status // Toggle theme status
$this->toggle_theme($themes, $theme, $result); $this->toggle_theme($themes, $theme, $result);
$s = $this->rebuild_theme_table($themes); $s = $this->rebuild_theme_table($themes);
if($result) if ($result)
info( sprintf('Theme %s enabled.', $theme)); info(sprintf('Theme %s enabled.', $theme));
else else
info( sprintf('Theme %s disabled.', $theme)); info(sprintf('Theme %s disabled.', $theme));
set_config('system', 'allowed_themes', $s); set_config('system', 'allowed_themes', $s);
goaway(z_root() . '/admin/themes' ); goaway(z_root() . '/admin/themes');
} }
// display theme details // display theme details
if ($this->theme_status($themes,$theme)) { if ($this->theme_status($themes, $theme)) {
$status="on"; $action= t("Disable"); $status = "on";
$action = t("Disable");
} else { } else {
$status="off"; $action= t("Enable"); $status = "off";
$action = t("Enable");
} }
$readme=Null; $readme = Null;
if (is_file("view/theme/$theme/README.md")){ if (is_file("view/theme/$theme/README.md")) {
$readme = file_get_contents("view/theme/$theme/README.md"); $readme = file_get_contents("view/theme/$theme/README.md");
$readme = MarkdownExtra::defaultTransform($readme); $readme = MarkdownExtra::defaultTransform($readme);
} else if (is_file("view/theme/$theme/README")){ } else if (is_file("view/theme/$theme/README")) {
$readme = '<pre>'. file_get_contents("view/theme/$theme/README") .'</pre>'; $readme = '<pre>' . file_get_contents("view/theme/$theme/README") . '</pre>';
} }
$admin_form = ''; $admin_form = '';
if (is_file("view/theme/$theme/php/config.php")){ if (is_file("view/theme/$theme/php/config.php")) {
require_once("view/theme/$theme/php/config.php"); require_once("view/theme/$theme/php/config.php");
if(function_exists("theme_admin")){ if (function_exists("theme_admin")) {
$admin_form = theme_admin($a); $admin_form = theme_admin($a);
} }
} }
$screenshot = array( get_theme_screenshot($theme), t('Screenshot')); $screenshot = array(get_theme_screenshot($theme), t('Screenshot'));
if(! stristr($screenshot[0],$theme)) if (!stristr($screenshot[0], $theme))
$screenshot = null; $screenshot = null;
$t = get_markup_template('admin_plugins_details.tpl'); $t = get_markup_template('admin_plugins_details.tpl');
@ -146,9 +151,9 @@ class Themes {
*/ */
$xthemes = []; $xthemes = [];
if($themes) { if ($themes) {
foreach($themes as $th) { foreach ($themes as $th) {
$xthemes[] = array($th['name'],(($th['allowed']) ? "on" : "off"), get_theme_info($th['name'])); $xthemes[] = array($th['name'], (($th['allowed']) ? "on" : "off"), get_theme_info($th['name']));
} }
} }
@ -174,14 +179,14 @@ class Themes {
* @param[in] string $th * @param[in] string $th
* @param[out] int &$result * @param[out] int &$result
*/ */
function toggle_theme(&$themes, $th, &$result) { public function toggle_theme(&$themes, $th, &$result)
for($x = 0; $x < count($themes); $x ++) { {
if($themes[$x]['name'] === $th) { for ($x = 0; $x < count($themes); $x++) {
if($themes[$x]['allowed']) { if ($themes[$x]['name'] === $th) {
if ($themes[$x]['allowed']) {
$themes[$x]['allowed'] = 0; $themes[$x]['allowed'] = 0;
$result = 0; $result = 0;
} } else {
else {
$themes[$x]['allowed'] = 1; $themes[$x]['allowed'] = 1;
$result = 1; $result = 1;
} }
@ -194,13 +199,13 @@ class Themes {
* @param string $th * @param string $th
* @return int * @return int
*/ */
function theme_status($themes, $th) { public function theme_status($themes, $th)
for($x = 0; $x < count($themes); $x ++) { {
if($themes[$x]['name'] === $th) { for ($x = 0; $x < count($themes); $x++) {
if($themes[$x]['allowed']) { if ($themes[$x]['name'] === $th) {
if ($themes[$x]['allowed']) {
return 1; return 1;
} } else {
else {
return 0; return 0;
} }
} }
@ -212,12 +217,13 @@ class Themes {
* @param array $themes * @param array $themes
* @return string * @return string
*/ */
function rebuild_theme_table($themes) { public function rebuild_theme_table($themes)
{
$o = ''; $o = '';
if(count($themes)) { if (count($themes)) {
foreach($themes as $th) { foreach ($themes as $th) {
if($th['allowed']) { if ($th['allowed']) {
if(strlen($o)) if (strlen($o))
$o .= ','; $o .= ',';
$o .= $th['name']; $o .= $th['name'];
} }

Some files were not shown because too many files have changed in this diff Show more