diff --git a/boot.php b/boot.php
index 25738192d..d82efe68a 100755
--- a/boot.php
+++ b/boot.php
@@ -52,13 +52,11 @@ define ( 'ZOT_REVISION', 1 );
define ( 'DB_UPDATE_VERSION', 1140 );
/**
- * Constant with a HTML line break.
+ * @brief Constant with a HTML line break.
*
* Contains a HTML line break (br) element and a real carriage return with line
* feed for the source.
* This can be used in HTML and JavaScript where needed a line break.
- *
- * @var string
*/
define ( 'EOL', '
' . "\r\n" );
define ( 'ATOM_TIME', 'Y-m-d\TH:i:s\Z' );
@@ -707,8 +705,6 @@ class App {
*
* Mostly unimplemented yet. Only options 'template_engine' and
* beyond are used.
- *
- * @var array
*/
private $theme = array(
'sourcename' => '',
@@ -721,15 +717,11 @@ class App {
);
/**
- * array of registered template engines ('name'=>'class name')
- *
- * @var array
+ * @brief An array of registered template engines ('name'=>'class name')
*/
public $template_engines = array();
/**
- * array of instanced template engines ('name'=>'instance')
- *
- * @var array
+ * @brief An array of instanced template engines ('name'=>'instance')
*/
public $template_engine_instance = array();
@@ -806,9 +798,7 @@ class App {
if(substr($this->cmd, 0, 1) === '~')
$this->cmd = 'channel/' . substr($this->cmd, 1);
-
- /**
- *
+ /*
* Break the URL path into C style argc/argv style arguments for our
* modules. Given "http://example.com/module/arg1/arg2", $this->argc
* will be 3 (integer) and $this->argv will contain:
@@ -816,25 +806,22 @@ class App {
* [1] => 'arg1'
* [2] => 'arg2'
*
- *
* There will always be one argument. If provided a naked domain
* URL, $this->argv[0] is set to "home".
- *
*/
- $this->argv = explode('/',$this->cmd);
+ $this->argv = explode('/', $this->cmd);
$this->argc = count($this->argv);
- if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
+ if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
$this->module = str_replace(".", "_", $this->argv[0]);
$this->module = str_replace("-", "_", $this->module);
- }
- else {
+ } else {
$this->argc = 1;
$this->argv = array('home');
$this->module = 'home';
}
- /**
+ /*
* See if there is any page number information, and initialise
* pagination
*/
@@ -846,7 +833,7 @@ class App {
$this->pager['start'] = 0;
$this->pager['total'] = 0;
- /**
+ /*
* Detect mobile devices
*/
@@ -858,7 +845,7 @@ class App {
BaseObject::set_app($this);
- /**
+ /*
* register template engines
*/
$dc = get_declared_classes();
@@ -2029,7 +2016,7 @@ function curPageURL() {
* @return mixed
*/
function get_custom_nav(&$a, $navname) {
- if(! $navname)
+ if (! $navname)
return $a->page['nav'];
// load custom nav menu by name here
}
@@ -2045,7 +2032,7 @@ function get_custom_nav(&$a, $navname) {
function load_pdl(&$a) {
require_once('include/comanche.php');
- if(! count($a->layout)) {
+ if (! count($a->layout)) {
$n = 'mod_' . $a->module . '.pdl' ;
$u = comanche_get_channel_id();
if($u)
@@ -2071,7 +2058,6 @@ function exec_pdl(&$a) {
}
-
/**
* @brief build the page.
*
@@ -2081,7 +2067,6 @@ function exec_pdl(&$a) {
*/
function construct_page(&$a) {
-
exec_pdl($a);
$comanche = ((count($a->layout)) ? true : false);
@@ -2090,28 +2075,27 @@ function construct_page(&$a) {
$installing = false;
- if($a->module == 'setup') {
+ if ($a->module == 'setup') {
$installing = true;
} else {
nav($a);
}
- if($comanche) {
-
- if($a->layout['nav']) {
+ if ($comanche) {
+ if ($a->layout['nav']) {
$a->page['nav'] = get_custom_nav($a, $a->layout['nav']);
}
}
- if(($p = theme_include(current_theme() . '.js')) != '')
+ if (($p = theme_include(current_theme() . '.js')) != '')
head_add_js($p);
- if(($p = theme_include('mod_' . $a->module . '.php')) != '')
+ if (($p = theme_include('mod_' . $a->module . '.php')) != '')
require_once($p);
require_once('include/js_strings.php');
- if(x($a->page, 'template_style'))
+ if (x($a->page, 'template_style'))
head_add_css($a->page['template_style'] . '.css');
else
head_add_css(((x($a->page, 'template')) ? $a->page['template'] : 'default' ) . '.css');
@@ -2148,7 +2132,6 @@ function construct_page(&$a) {
call_hooks('construct_page', $arr);
$a->layout = $arr['layout'];
-
foreach($a->layout as $k => $v) {
if((strpos($k, 'region_') === 0) && strlen($v)) {
if(strpos($v, '$region_') !== false) {
@@ -2250,11 +2233,11 @@ function get_directory_realm() {
*/
function get_directory_primary() {
- $dirmode = intval(get_config('system','directory_mode'));
+ $dirmode = intval(get_config('system','directory_mode'));
- if($dirmode == DIRECTORY_MODE_STANDALONE || $dirmode == DIRECTORY_MODE_PRIMARY) {
+ if($dirmode == DIRECTORY_MODE_STANDALONE || $dirmode == DIRECTORY_MODE_PRIMARY) {
return z_root();
- }
+ }
if($x = get_config('system', 'directory_primary'))
return $x;
@@ -2263,13 +2246,11 @@ function get_directory_primary() {
}
-
/**
- * @brief return relative date of last completed poller execution
+ * @brief return relative date of last completed poller execution.
*/
-
function get_poller_runtime() {
- $t = get_config('system','lastpoll');
+ $t = get_config('system', 'lastpoll');
return relative_date($t);
}
@@ -2303,7 +2284,12 @@ function z_check_cert() {
}
-
+/**
+ * @brief Send email to admin if server has an invalid certificate.
+ *
+ * If a RedMatrix hub is available over https it must have a publicly valid
+ * certificate.
+ */
function cert_bad_email() {
$a = get_app();
@@ -2320,13 +2306,12 @@ function cert_bad_email() {
'From: Administrator' . '@' . $a->get_hostname() . "\n"
. 'Content-type: text/plain; charset=UTF-8' . "\n"
. 'Content-transfer-encoding: 8bit' );
-
}
-// send warnings every 3-5 days if cron is not running.
-
-
+/**
+ * @brief Send warnings every 3-5 days if cron is not running.
+ */
function check_cron_broken() {
$t = get_config('system','lastpollcheck');
diff --git a/include/ITemplateEngine.php b/include/ITemplateEngine.php
index 53c1845f4..7bd559a63 100755
--- a/include/ITemplateEngine.php
+++ b/include/ITemplateEngine.php
@@ -1,11 +1,10 @@
- false, 'message' => '');
- // The only validation we perform by default is pure Javascript to
+ // The only validation we perform by default is pure Javascript to
// check minimum length and that both entered passwords match.
- // Use hooked functions to perform complexity requirement checks.
+ // Use hooked functions to perform complexity requirement checks.
$arr = array('password' => $password, 'result' => $result);
call_hooks('check_account_password', $arr);
return $arr['result'];
-
}
function check_account_invite($invite_code) {
@@ -75,7 +78,6 @@ function check_account_invite($invite_code) {
call_hooks('check_account_invite', $arr);
return $arr['result'];
-
}
function check_account_admin($arr) {
@@ -109,7 +111,7 @@ function create_account($arr) {
$flags = ((x($arr,'account_flags')) ? intval($arr['account_flags']) : ACCOUNT_OK);
$roles = ((x($arr,'account_roles')) ? intval($arr['account_roles']) : 0 );
$expires = ((x($arr,'expires')) ? intval($arr['expires']) : NULL_DATE);
-
+
$default_service_class = get_config('system','default_service_class');
if($default_service_class === false)
@@ -132,16 +134,16 @@ function create_account($arr) {
// allow the admin_email account to be admin, but only if it's the first account.
$c = account_total();
- if(($c === 0) && (check_account_admin($arr)))
+ if (($c === 0) && (check_account_admin($arr)))
$roles |= ACCOUNT_ROLE_ADMIN;
- // Ensure that there is a host keypair.
+ // Ensure that there is a host keypair.
- if((! get_config('system','pubkey')) && (! get_config('system','prvkey'))) {
- $hostkey = new_keypair(4096);
- set_config('system','pubkey',$hostkey['pubkey']);
- set_config('system','prvkey',$hostkey['prvkey']);
- }
+ if ((! get_config('system', 'pubkey')) && (! get_config('system', 'prvkey'))) {
+ $hostkey = new_keypair(4096);
+ set_config('system', 'pubkey', $hostkey['pubkey']);
+ set_config('system', 'prvkey', $hostkey['prvkey']);
+ }
$invite_result = check_account_invite($invite_code);
if($invite_result['error']) {
@@ -180,7 +182,6 @@ function create_account($arr) {
dbesc($roles),
dbesc($expires),
dbesc($default_service_class)
-
);
if(! $r) {
logger('create_account: DB INSERT failed.');
@@ -195,7 +196,7 @@ function create_account($arr) {
if($r && count($r)) {
$result['account'] = $r[0];
}
- else {
+ else {
logger('create_account: could not retrieve newly created account');
}
@@ -215,8 +216,8 @@ function create_account($arr) {
$result['success'] = true;
$result['email'] = $email;
$result['password'] = $password;
- return $result;
+ return $result;
}
@@ -255,7 +256,6 @@ function verify_email_address($arr) {
logger('send_reg_approval_email: failed to ' . $admin['email'] . 'account_id: ' . $arr['account']['account_id']);
return $res;
-
}
@@ -292,7 +292,6 @@ function send_reg_approval_email($arr) {
$details = (($ip) ? $ip . ' [' . gethostbyaddr($ip) . ']' : '[unknown or stealth IP]');
-
$delivered = 0;
foreach($admins as $admin) {
@@ -346,11 +345,14 @@ function send_verification_email($email,$password) {
return($res ? true : false);
}
-
+/**
+ * @brief Allows a user registration.
+ *
+ * @param string $hash
+ * @return array|boolean
+ */
function user_allow($hash) {
- $a = get_app();
-
$ret = array('success' => false);
$register = q("SELECT * FROM `register` WHERE `hash` = '%s' LIMIT 1",
@@ -363,7 +365,7 @@ function user_allow($hash) {
$account = q("SELECT * FROM account WHERE account_id = %d LIMIT 1",
intval($register[0]['uid'])
);
-
+
if(! $account)
return $ret;
@@ -381,7 +383,7 @@ function user_allow($hash) {
intval(ACCOUNT_PENDING),
intval($register[0]['uid'])
);
-
+
push_lang($register[0]['language']);
$email_tpl = get_intltext_template("register_open_eml.tpl");
@@ -402,18 +404,23 @@ function user_allow($hash) {
pop_lang();
- if($res) {
+ if ($res) {
info( t('Account approved.') . EOL );
return true;
- }
-
+ }
}
-// This does not have to go through user_remove() and save the nickname
-// permanently against re-registration, as the person was not yet
-// allowed to have friends on this system
-
+/**
+ * @brief Denies a user registration.
+ *
+ * This does not have to go through user_remove() and save the nickname
+ * permanently against re-registration, as the person was not yet
+ * allowed to have friends on this system
+ *
+ * @param string $hash
+ * @return boolean
+ */
function user_deny($hash) {
$register = q("SELECT * FROM register WHERE hash = '%s' LIMIT 1",
@@ -426,7 +433,7 @@ function user_deny($hash) {
$account = q("SELECT account_id, account_email FROM account WHERE account_id = %d LIMIT 1",
intval($register[0]['uid'])
);
-
+
if(! $account)
return false;
@@ -438,15 +445,14 @@ function user_deny($hash) {
dbesc($register[0]['id'])
);
notice( sprintf(t('Registration revoked for %s'), $account[0]['account_email']) . EOL);
+
return true;
-
+
}
function user_approve($hash) {
- $a = get_app();
-
$ret = array('success' => false);
$register = q("SELECT * FROM `register` WHERE `hash` = '%s' and password = 'verify' LIMIT 1",
@@ -459,7 +465,7 @@ function user_approve($hash) {
$account = q("SELECT * FROM account WHERE account_id = %d LIMIT 1",
intval($register[0]['uid'])
);
-
+
if(! $account)
return $ret;
@@ -482,21 +488,16 @@ function user_approve($hash) {
intval(ACCOUNT_UNVERIFIED),
intval($register[0]['uid'])
);
-
+
info( t('Account verified. Please login.') . EOL );
return true;
-
}
-
-
-
-
/**
- * @function downgrade_accounts()
- * Checks for accounts that have past their expiration date.
+ * @brief Checks for accounts that have past their expiration date.
+ *
* If the account has a service class which is not the site default,
* the service class is reset to the site default and expiration reset to never.
* If the account has no service class it is expired and subsequently disabled.
@@ -506,8 +507,6 @@ function user_approve($hash) {
* not the job of this function, but this can be implemented by plugin if desired.
* Default behaviour is to stop allowing additional resources to be consumed.
*/
-
-
function downgrade_accounts() {
$r = q("select * from account where not ( account_flags & %d )>0
@@ -604,7 +603,7 @@ function service_class_allows($uid, $property, $usage = false) {
*
* @param int $aid The account_id to check
* @param string $property The service class property to check for
- * @param int|boolean $usage, (optional) The value to check against
+ * @param int|boolean $usage (optional) The value to check against
* @return boolean
*/
function account_service_class_allows($aid, $property, $usage = false) {
diff --git a/include/attach.php b/include/attach.php
index f9206851e..415859b39 100644
--- a/include/attach.php
+++ b/include/attach.php
@@ -1,10 +1,10 @@
false);
- if(! perm_is_allowed($channel_id,$observer, 'read_storage')) {
+ if(! perm_is_allowed($channel_id, $observer, 'read_storage')) {
$ret['message'] = t('Permission denied.');
return $ret;
}
@@ -219,8 +218,9 @@ function attach_list_files($channel_id, $observer, $hash = '', $filename = '', $
*
* This could exhaust memory so most useful only when immediately sending the data.
*
- * @param $hash
- * @param $rev
+ * @param string $hash
+ * @param int $rev Revision
+ * @return array
*/
function attach_by_hash($hash, $rev = 0) {
@@ -234,7 +234,6 @@ function attach_by_hash($hash, $rev = 0) {
elseif($rev)
$sql_extra = " and revision = " . intval($rev) . " ";
-
$r = q("SELECT uid FROM attach WHERE hash = '%s' $sql_extra LIMIT 1",
dbesc($hash)
);
@@ -270,9 +269,9 @@ function attach_by_hash($hash, $rev = 0) {
/**
* @brief Find an attachment by hash and revision.
- *
+ *
* Returns the entire attach structure excluding data.
- *
+ *
* @see attach_by_hash()
* @param $hash
* @param $rev revision default 0
@@ -561,7 +560,7 @@ function z_readdir($channel_id, $observer_hash, $pathname, $parent_hash = '') {
}
else
$paths = array($pathname);
-
+
$r = q("select id, aid, uid, hash, creator, filename, filetype, filesize, revision, folder, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid from attach where id = %d and folder = '%s' and filename = '%s' and (flags & %d )>0 " . permissions_sql($channel_id),
intval($channel_id),
dbesc($parent_hash),
@@ -579,24 +578,22 @@ function z_readdir($channel_id, $observer_hash, $pathname, $parent_hash = '') {
}
/**
- * @function attach_mkdir($channel,$observer_hash,$arr);
- *
* @brief Create directory.
*
* @param array $channel channel array of owner
* @param string $observer_hash hash of current observer
* @param array $arr parameter array to fulfil request
- * Required:
- * $arr['filename']
- * $arr['folder'] // hash of parent directory, empty string for root directory
- * Optional:
- * $arr['hash'] // precumputed hash for this node
- * $arr['allow_cid']
- * $arr['allow_gid']
- * $arr['deny_cid']
- * $arr['deny_gid']
+ * - Required:
+ * * \e string \b filename
+ * * \e string \b folder hash of parent directory, empty string for root directory
+ * - Optional:
+ * * \e string \b hash precumputed hash for this node
+ * * \e tring \b allow_cid
+ * * \e string \b allow_gid
+ * * \e string \b deny_cid
+ * * \e string \b deny_gid
+ * @return array
*/
-
function attach_mkdir($channel, $observer_hash, $arr = null) {
$ret = array('success' => false);
@@ -720,13 +717,13 @@ function attach_mkdir($channel, $observer_hash, $arr = null) {
/**
* @brief Changes permissions of a file.
*
- * @param $channel_id
- * @param $resource
- * @param $allow_cid
- * @param $allow_gid
- * @param $deny_cid
- * @param $deny_gid
- * @param $recurse
+ * @param int $channel_id
+ * @param array $resource
+ * @param string $allow_cid
+ * @param string $allow_gid
+ * @param string $deny_cid
+ * @param string $deny_gid
+ * @param boolean $recurse (optional) default false
*/
function attach_change_permissions($channel_id, $resource, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $recurse = false) {
@@ -836,7 +833,6 @@ function attach_delete($channel_id, $resource) {
);
file_activity($channel_id, $object, $object['allow_cid'], $object['allow_gid'], $object['deny_cid'], $object['deny_gid'], 'update', $no_activity=false);
-
}
/**
@@ -844,8 +840,8 @@ function attach_delete($channel_id, $resource) {
*
* @warning This function cannot be used with mod/dav as it always returns a
* path valid under mod/cloud.
- *
- * @param array assoziative array with:
+ *
+ * @param array $arr assoziative array with:
* * \e int \b uid the channel's uid
* * \e string \b folder
* * \e string \b filename
@@ -973,20 +969,21 @@ function pipe_streams($in, $out) {
$size = 0;
while (!feof($in))
$size += fwrite($out, fread($in, 8192));
+
return $size;
}
/**
- * @brief Activity for files
+ * @brief Activity for files.
*
- * @param $channel_id
- * @param $object
- * @param $allow_cid
- * @param $allow_gid
- * @param $deny_cid
- * @param $deny_gid
- * @param $verb
- * @param $no_activity
+ * @param int $channel_id
+ * @param array $object
+ * @param string $allow_cid
+ * @param string $allow_gid
+ * @param string $deny_cid
+ * @param string $deny_gid
+ * @param string $verb
+ * @param boolean $no_activity
*/
function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $verb, $no_activity) {
@@ -1028,7 +1025,6 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid,
//filter out receivers which do not have permission to view filestorage
$arr_allow_cid = check_list_permissions($channel_id, $arr_allow_cid, 'view_storage');
-
}
$mid = item_message_id();
@@ -1109,7 +1105,6 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid,
$update = false;
//notice( t('File activity updated') . EOL);
-
}
if($no_activity) {
@@ -1152,15 +1147,14 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid,
//(($verb === 'post') ? notice( t('File activity posted') . EOL) : notice( t('File activity dropped') . EOL));
return;
-
}
/**
* @brief Create file activity object
*
- * @param $channel_id
- * @param $hash
- * @param $cloudpath
+ * @param int $channel_id
+ * @param string $hash
+ * @param string $cloudpath
*/
function get_file_activity_object($channel_id, $hash, $cloudpath) {
@@ -1199,8 +1193,8 @@ function get_file_activity_object($channel_id, $hash, $cloudpath) {
'deny_cid' => $x[0]['deny_cid'],
'deny_gid' => $x[0]['deny_gid']
);
- return $object;
+ return $object;
}
/**
diff --git a/include/comanche.php b/include/comanche.php
index 71ffe99b8..62bfd0ddc 100644
--- a/include/comanche.php
+++ b/include/comanche.php
@@ -101,7 +101,7 @@ function comanche_parser(&$a, $s, $pass = 0) {
}
-function comanche_menu($name,$class = '') {
+function comanche_menu($name, $class = '') {
$channel_id = comanche_get_channel_id();
if($channel_id) {
$m = menu_fetch($name,$channel_id, get_observer_hash());
@@ -111,20 +111,23 @@ function comanche_menu($name,$class = '') {
function comanche_replace_region($match) {
$a = get_app();
- if(array_key_exists($match[1], $a->page)) {
+ if (array_key_exists($match[1], $a->page)) {
return $a->page[$match[1]];
}
}
/**
- * @function comanche_get_channel_id()
- * Returns the channel_id of the profile owner of the page, or the local_channel if there is no profile owner.
- * Otherwise returns 0
- */
-
+ * @brief Returns the channel_id of the profile owner of the page.
+ *
+ * Returns the channel_id of the profile owner of the page, or the local_channel
+ * if there is no profile owner. Otherwise returns 0.
+ *
+ * @return channel_id
+ */
function comanche_get_channel_id() {
$channel_id = ((is_array(get_app()->profile)) ? get_app()->profile['profile_uid'] : 0);
- if((! $channel_id) && (local_channel()))
+
+ if ((! $channel_id) && (local_channel()))
$channel_id = local_channel();
return $channel_id;
@@ -173,23 +176,26 @@ function comanche_webpage(&$a,$s) {
}
-// Widgets will have to get any operational arguments from the session,
-// the global app environment, or config storage until we implement argument passing
-
-
+/**
+ * Widgets will have to get any operational arguments from the session, the
+ * global app environment, or config storage until we implement argument passing
+ *
+ * @param string $name
+ * @param string $text
+ */
function comanche_widget($name, $text) {
$vars = array();
$matches = array();
$cnt = preg_match_all("/\[var=(.*?)\](.*?)\[\/var\]/ism", $text, $matches, PREG_SET_ORDER);
- if($cnt) {
- foreach($matches as $mtch) {
+ if ($cnt) {
+ foreach ($matches as $mtch) {
$vars[$mtch[1]] = $mtch[2];
}
}
$func = 'widget_' . trim($name);
- if(function_exists($func))
+ if (function_exists($func))
return $func($vars);
}
diff --git a/include/config.php b/include/config.php
index b459e2c7d..c94d25eb8 100644
--- a/include/config.php
+++ b/include/config.php
@@ -3,8 +3,7 @@
* @file include/config.php
* @brief Arbitrary configuration storage.
*
- * Note:
- * Please do not store booleans - convert to 0/1 integer values
+ * @note Please do not store booleans - convert to 0/1 integer values.
* The get_?config() functions return boolean false for keys that are unset,
* and this could lead to subtle bugs.
*
@@ -18,19 +17,20 @@
* - pconfig is used for channel specific configurations and takes a
* channel_id as identifier. It stores for example which features are
* enabled per channel. The storage is of size MEDIUMTEXT.
- * @code $var = get_pconfig(local_channel(), 'category', 'key');@endcode
+ * @code{.php} $var = get_pconfig(local_channel(), 'category', 'key');@endcode
* - xconfig is the same as pconfig, except that it uses xchan as
* an identifier. This is for example for people who do not have a local account.
* The storage is of size MEDIUMTEXT.
- * @code $observer = $a->get_observer_hash();
+ * @code{.php}
+ * $observer = $a->get_observer_hash();
* if ($observer) {
* $var = get_xconfig($observer, 'category', 'key');
* }@endcode
*
* - get_config() and set_config() can also be done through the command line tool
- * @ref util/config
+ * @ref util/config.md "util/config"
* - get_pconfig() and set_pconfig() can also be done through the command line tool
- * @ref util/pconfig and takes a channel_id as first argument.
+ * @ref util/pconfig.md "util/pconfig" and takes a channel_id as first argument.
*
*/
@@ -123,7 +123,7 @@ function get_config_from_storage($family, $key) {
*
* Stores a config value ($value) in the category ($family) under the key ($key).
*
- * Please do not store booleans - convert to 0/1 integer values!
+ * @note Please do not store booleans - convert to 0/1 integer values!
*
* @param string $family
* The category of the configuration value
@@ -272,14 +272,16 @@ function get_pconfig($uid, $family, $key, $instore = false) {
* Stores a config value ($value) in the category ($family) under the key ($key)
* for the channel_id $uid.
*
- * Please do not store booleans - convert to 0/1 integer values!
+ * @note Please do not store booleans - convert to 0/1 integer values!
*
* @param string $uid
* The channel_id
* @param string $family
* The category of the configuration value
* @param string $key
- * The configuration key to query
+ * The configuration key to set
+ * @param string $value
+ * The value to store
* @return mixed Stored $value or false
*/
function set_pconfig($uid, $family, $key, $value) {
@@ -315,6 +317,7 @@ function set_pconfig($uid, $family, $key, $value) {
);
if($ret)
return $value;
+
return $ret;
}
@@ -339,6 +342,7 @@ function set_pconfig($uid, $family, $key, $value) {
if($ret)
return $value;
+
return $ret;
}
@@ -360,13 +364,14 @@ function del_pconfig($uid, $family, $key) {
global $a;
$ret = false;
- if(x($a->config[$uid][$family], $key))
+ if (x($a->config[$uid][$family], $key))
unset($a->config[$uid][$family][$key]);
$ret = q("DELETE FROM pconfig WHERE uid = %d AND cat = '%s' AND k = '%s'",
intval($uid),
dbesc($family),
dbesc($key)
);
+
return $ret;
}
@@ -448,7 +453,7 @@ function get_xconfig($xchan, $family, $key) {
* Stores a config value ($value) in the category ($family) under the key ($key)
* for the observer's $xchan hash.
*
- * Please do not store booleans - convert to 0/1 integer values!
+ * @note Please do not store booleans - convert to 0/1 integer values!
*
* @param string $xchan
* The observer's hash
@@ -456,6 +461,8 @@ function get_xconfig($xchan, $family, $key) {
* The category of the configuration value
* @param string $key
* The configuration key to set
+ * @param string $value
+ * The value to store
* @return mixed Stored $value or false
*/
function set_xconfig($xchan, $family, $key, $value) {
diff --git a/include/conversation.php b/include/conversation.php
index 4018ced28..042d01b3e 100644
--- a/include/conversation.php
+++ b/include/conversation.php
@@ -1044,7 +1044,6 @@ function builtin_activity_puller($item, &$conv_responses) {
return;
}
}
-
}
@@ -1053,7 +1052,7 @@ function builtin_activity_puller($item, &$conv_responses) {
*
* @param int $cnt number of people who like/dislike the item
* @param array $arr array of pre-linked names of likers/dislikers
- * @param string $typ eone of 'like, 'dislike'
+ * @param string $type one of 'like, 'dislike'
* @param int $id item id
* @return string formatted text
*/
@@ -1146,7 +1145,6 @@ function status_editor($a, $x, $popup = false) {
'$expireswhen' => t('Expires YYYY-MM-DD HH:MM')
));
-
$tpl = get_markup_template('jot.tpl');
$jotplugins = '';
@@ -1461,8 +1459,8 @@ function network_tabs() {
if ($no_active=='active' && x($_GET,'order')) {
switch($_GET['order']){
- case 'post': $postord_active = 'active'; $no_active=''; break;
- case 'comment' : $all_active = 'active'; $no_active=''; break;
+ case 'post': $postord_active = 'active'; $no_active=''; break;
+ case 'comment' : $all_active = 'active'; $no_active=''; break;
}
}
diff --git a/include/datetime.php b/include/datetime.php
index 5cab5889d..b0167edb2 100644
--- a/include/datetime.php
+++ b/include/datetime.php
@@ -1,54 +1,71 @@
- 1) {
+ if (count($ex) > 1) {
$continent = t($ex[0]);
- if(count($ex) > 2)
- $city = substr($value,strpos($value,'/')+1);
+ if (count($ex) > 2)
+ $city = substr($value, strpos($value, '/')+1);
else
$city = $ex[1];
- }
- else {
+ } else {
$city = $ex[0];
$continent = t('Miscellaneous');
}
$city = str_replace('_', ' ', t($city));
- if(!x($continents,$ex[0])) $continents[$ex[0]] = array();
+ if (!x($continents, $ex[0])) $continents[$ex[0]] = array();
$continents[$continent][$value] = $city;
}
+
return $continents;
}
-// General purpose date parse/convert function.
-// $from = source timezone
-// $to = dest timezone
-// $s = some parseable date/time string
-// $fmt = output format
-
-
+/**
+ * @brief General purpose date parse/convert function.
+ *
+ * @param string $from source timezone
+ * @param string $to dest timezone
+ * @param string $s some parseable date/time string
+ * @param string $fmt output format recognised from php's DateTime class
+ * http://www.php.net/manual/en/datetime.format.php
+ * @return string
+ */
function datetime_convert($from = 'UTC', $to = 'UTC', $s = 'now', $fmt = "Y-m-d H:i:s") {
// Defaults to UTC if nothing is set, but throws an exception if set to empty string.
@@ -68,44 +85,46 @@ function datetime_convert($from = 'UTC', $to = 'UTC', $s = 'now', $fmt = "Y-m-d
if(substr($s,0,10) == '0000-00-00') {
$d = new DateTime($s . ' + 32 days', new DateTimeZone('UTC'));
- return str_replace('1','0',$d->format($fmt));
+ return str_replace('1', '0', $d->format($fmt));
}
try {
$from_obj = new DateTimeZone($from);
- }
- catch(Exception $e) {
+ } catch(Exception $e) {
$from_obj = new DateTimeZone('UTC');
}
try {
$d = new DateTime($s, $from_obj);
- }
- catch(Exception $e) {
+ } catch(Exception $e) {
logger('datetime_convert: exception: ' . $e->getMessage());
$d = new DateTime('now', $from_obj);
}
try {
$to_obj = new DateTimeZone($to);
- }
- catch(Exception $e) {
+ } catch(Exception $e) {
$to_obj = new DateTimeZone('UTC');
}
$d->setTimeZone($to_obj);
+
return($d->format($fmt));
}
-// wrapper for date selector, tailored for use in birthday fields
-
+/**
+ * @brief Wrapper for date selector, tailored for use in birthday fields.
+ *
+ * @param string $dob Date of Birth
+ * @return string
+ */
function dob($dob) {
- list($year,$month,$day) = sscanf($dob,'%4d-%2d-%2d');
- $f = get_config('system','birthday_input_format');
- if(! $f)
+ list($year, $month, $day) = sscanf($dob, '%4d-%2d-%2d');
+ $f = get_config('system', 'birthday_input_format');
+ if (! $f)
$f = 'ymd';
- if($dob === '0000-00-00')
+ if ($dob === '0000-00-00')
$value = '';
else
$value = (($year) ? datetime_convert('UTC','UTC',$dob,'Y-m-d') : datetime_convert('UTC','UTC',$dob,'m-d'));
@@ -120,7 +139,6 @@ function dob($dob) {
return $o;
}
-
/**
* returns a date selector
* @param $format
@@ -135,7 +153,7 @@ function dob($dob) {
* id and name of datetimepicker (defaults to "datetimepicker")
*/
function datesel($format, $min, $max, $default, $id = 'datepicker') {
- return datetimesel($format,$min,$max,$default,$id,true,false, '','');
+ return datetimesel($format, $min, $max, $default, $id,true, false, '', '');
}
/**
@@ -154,7 +172,8 @@ function timesel($format, $h, $m, $id='timepicker') {
}
/**
- * returns a datetime selector
+ * @brief Returns a datetime selector.
+ *
* @param $format
* format string, e.g. 'ymd' or 'mdy'. Not currently supported
* @param $min
@@ -163,23 +182,25 @@ function timesel($format, $h, $m, $id='timepicker') {
* unix timestap of maximum date
* @param $default
* unix timestamp of default date
- * @param $id
+ * @param string $id
* id and name of datetimepicker (defaults to "datetimepicker")
- * @param $pickdate
+ * @param boolean $pickdate
* true to show date picker (default)
- * @param $picktime
+ * @param boolean $picktime
* true to show time picker (default)
* @param $minfrom
* set minimum date from picker with id $minfrom (none by default)
* @param $maxfrom
* set maximum date from picker with id $maxfrom (none by default)
+ * @param boolean $required default false
+ * @return string Parsed HTML output.
+ *
+ * @todo Once browser support is better this could probably be replaced with
+ * native HTML5 date picker.
*/
-function datetimesel($format, $min, $max, $default, $id = 'datetimepicker', $pickdate = true, $picktime = true, $minfrom = '', $maxfrom = '',$required = false) {
+function datetimesel($format, $min, $max, $default, $id = 'datetimepicker', $pickdate = true, $picktime = true, $minfrom = '', $maxfrom = '', $required = false) {
-
- // Once browser support is better this could probably be replaced with native HTML5 date picker
$o = '';
-
$dateformat = '';
if($pickdate) $dateformat .= 'Y-m-d';
@@ -188,7 +209,7 @@ function datetimesel($format, $min, $max, $default, $id = 'datetimepicker', $pic
$minjs = $min ? ",minDate: new Date({$min->getTimestamp()}*1000), yearStart: " . $min->format('Y') : '';
$maxjs = $max ? ",maxDate: new Date({$max->getTimestamp()}*1000), yearEnd: " . $max->format('Y') : '';
-
+
$input_text = $default ? 'value="' . date($dateformat, $default->getTimestamp()) . '"' : '';
$defaultdatejs = $default ? ",defaultDate: new Date({$default->getTimestamp()}*1000)" : '';
@@ -214,31 +235,39 @@ function datetimesel($format, $min, $max, $default, $id = 'datetimepicker', $pic
$o .= (($required) ? '*' : '');
$o .= '';
$o .= "";
+
return $o;
}
-// implements "3 seconds ago" etc.
-// based on $posted_date, (UTC).
-// Results relative to current timezone
-// Limited to range of timestamps
+/**
+ * @brief Returns a relative date string.
+ *
+ * Implements "3 seconds ago" etc.
+ * Based on $posted_date, (UTC).
+ * Results relative to current timezone.
+ * Limited to range of timestamps.
+ *
+ * @param string $posted_date
+ * @param string $format (optional) parsed with sprintf()
+ * %1$d %2$s ago, e.g. 22 hours ago, 1 minute ago
+ * @return string with relative date
+ */
+function relative_date($posted_date, $format = null) {
-
-function relative_date($posted_date,$format = null) {
-
- $localtime = datetime_convert('UTC',date_default_timezone_get(),$posted_date);
+ $localtime = datetime_convert('UTC', date_default_timezone_get(), $posted_date);
$abs = strtotime($localtime);
-
- if (is_null($posted_date) || $posted_date === NULL_DATE || $abs === False) {
- return t('never');
+
+ if (is_null($posted_date) || $posted_date === NULL_DATE || $abs === false) {
+ return t('never');
}
$etime = time() - $abs;
-
+
if ($etime < 1) {
return t('less than a second ago');
}
-
+
$a = array( 12 * 30 * 24 * 60 * 60 => array( t('year'), t('years')),
30 * 24 * 60 * 60 => array( t('month'), t('months')),
7 * 24 * 60 * 60 => array( t('week'), t('weeks')),
@@ -247,231 +276,256 @@ function relative_date($posted_date,$format = null) {
60 => array( t('minute'), t('minutes')),
1 => array( t('second'), t('seconds'))
);
-
+
foreach ($a as $secs => $str) {
$d = $etime / $secs;
if ($d >= 1) {
$r = round($d);
- // translators - e.g. 22 hours ago, 1 minute ago
- if(! $format)
- $format = t('%1$d %2$s ago');
- return sprintf( $format,$r, (($r == 1) ? $str[0] : $str[1]));
- }
- }
+ if (! $format)
+ $format = t('%1$d %2$s ago', 'e.g. 22 hours ago, 1 minute ago');
+
+ return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
+ }
+ }
}
-
-
-// Returns age in years, given a date of birth,
-// the timezone of the person whose date of birth is provided,
-// and the timezone of the person viewing the result.
-// Why? Bear with me. Let's say I live in Mittagong, Australia, and my
-// birthday is on New Year's. You live in San Bruno, California.
-// When exactly are you going to see my age increase?
-// A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start
-// celebrating and become a year older. If you wish me happy birthday
-// on January 1 (San Bruno time), you'll be a day late.
-
-function age($dob,$owner_tz = '',$viewer_tz = '') {
- if(! intval($dob))
+/**
+ * @brief Returns timezone correct age in years.
+ *
+ * Returns the age in years, given a date of birth, the timezone of the person
+ * whose date of birth is provided, and the timezone of the person viewing the
+ * result.
+ *
+ * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
+ * is on New Year's. You live in San Bruno, California.
+ * When exactly are you going to see my age increase?
+ *
+ * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
+ * and become a year older. If you wish me happy birthday on January 1
+ * (San Bruno time), you'll be a day late.
+ *
+ * @param string $dob Date of Birth
+ * @param string $owner_tz (optional) timezone of the person of interest
+ * @param string $viewer_tz (optional) timezone of the person viewing
+ * @return number
+ */
+function age($dob, $owner_tz = '', $viewer_tz = '') {
+ if (! intval($dob))
return 0;
- if(! $owner_tz)
+ if (! $owner_tz)
$owner_tz = date_default_timezone_get();
- if(! $viewer_tz)
+ if (! $viewer_tz)
$viewer_tz = date_default_timezone_get();
- $birthdate = datetime_convert('UTC',$owner_tz,$dob . ' 00:00:00+00:00','Y-m-d');
- list($year,$month,$day) = explode("-",$birthdate);
- $year_diff = datetime_convert('UTC',$viewer_tz,'now','Y') - $year;
- $curr_month = datetime_convert('UTC',$viewer_tz,'now','m');
- $curr_day = datetime_convert('UTC',$viewer_tz,'now','d');
+ $birthdate = datetime_convert('UTC', $owner_tz, $dob . ' 00:00:00+00:00','Y-m-d');
+ list($year,$month,$day) = explode("-", $birthdate);
+ $year_diff = datetime_convert('UTC', $viewer_tz, 'now', 'Y') - $year;
+ $curr_month = datetime_convert('UTC', $viewer_tz, 'now', 'm');
+ $curr_day = datetime_convert('UTC', $viewer_tz, 'now', 'd');
- if(($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day)))
+ if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day)))
$year_diff--;
+
return $year_diff;
}
+/**
+ * @brief Get days of a month in a given year.
+ *
+ * Returns number of days in the month of the given year.
+ * $m = 1 is 'January' to match human usage.
+ *
+ * @param int $y year
+ * @param int $m month (1=January, 12=December)
+ * @return int number of days in the given month
+ */
+function get_dim($y, $m) {
+ $dim = array( 0,
+ 31, 28, 31, 30, 31, 30,
+ 31, 31, 30, 31, 30, 31
+ );
+ if ($m != 2)
+ return $dim[$m];
-// Get days in month
-// get_dim($year, $month);
-// returns number of days.
-// $month[1] = 'January';
-// to match human usage.
+ if (((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0))
+ return 29;
-
-function get_dim($y,$m) {
-
- $dim = array( 0,
- 31, 28, 31, 30, 31, 30,
- 31, 31, 30, 31, 30, 31);
-
- if($m != 2)
- return $dim[$m];
- if(((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0))
- return 29;
- return $dim[2];
+ return $dim[2];
}
+/**
+ * @brief Returns the first day in month for a given month, year.
+ *
+ * Months start at 1.
+ *
+ * @param int $y Year
+ * @param int $m Month (1=January, 12=December)
+ * @return day 0 = Sunday through 6 = Saturday
+ */
+function get_first_dim($y, $m) {
+ $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
-// Returns the first day in month for a given month, year
-// get_first_dim($year,$month)
-// returns 0 = Sunday through 6 = Saturday
-// Months start at 1.
-
-
-function get_first_dim($y,$m) {
- $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
- return datetime_convert('UTC','UTC',$d,'w');
+ return datetime_convert('UTC', 'UTC', $d, 'w');
}
-// output a calendar for the given month, year.
-// if $links are provided (array), e.g. $links[12] => 'http://mylink' ,
-// date 12 will be linked appropriately. Today's date is also noted by
-// altering td class.
-// Months count from 1.
-
-
-// TODO: provide (prev,next) links, define class variations for different size calendars
-
-function cal($y = 0,$m = 0, $links = false, $class='') {
-
+/**
+ * @brief Output a calendar for the given month, year.
+ *
+ * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
+ * date 12 will be linked appropriately. Today's date is also noted by
+ * altering td class.
+ * Months count from 1.
+ *
+ * @param number $y Year
+ * @param number $m Month
+ * @param string $links (default false)
+ * @param string $class
+ * @return string
+ *
+ * @todo provide (prev,next) links, define class variations for different size calendars
+ */
+function cal($y = 0, $m = 0, $links = false, $class='') {
// month table - start at 1 to match human usage.
$mtab = array(' ',
- 'January','February','March',
- 'April','May','June',
- 'July','August','September',
- 'October','November','December'
- );
+ 'January','February','March',
+ 'April','May','June',
+ 'July','August','September',
+ 'October','November','December'
+ );
$thisyear = datetime_convert('UTC',date_default_timezone_get(),'now','Y');
$thismonth = datetime_convert('UTC',date_default_timezone_get(),'now','m');
- if(! $y)
+ if (! $y)
$y = $thisyear;
- if(! $m)
+ if (! $m)
$m = intval($thismonth);
- $dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
- $f = get_first_dim($y,$m);
- $l = get_dim($y,$m);
- $d = 1;
- $dow = 0;
- $started = false;
+ $dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
+ $f = get_first_dim($y, $m);
+ $l = get_dim($y, $m);
+ $d = 1;
+ $dow = 0;
+ $started = false;
- if(($y == $thisyear) && ($m == $thismonth))
- $tddate = intval(datetime_convert('UTC',date_default_timezone_get(),'now','j'));
+ if (($y == $thisyear) && ($m == $thismonth))
+ $tddate = intval(datetime_convert('UTC',date_default_timezone_get(),'now','j'));
$str_month = day_translate($mtab[$m]);
- $o = '
' . mb_substr(day_translate($dn[$a]),0,3,'UTF-8') . ' | '; - $o .= '||
---|---|---|
' . mb_substr(day_translate($dn[$a]),0,3,'UTF-8') . ' | '; - while($d <= $l) { - if(($dow == $f) && (! $started)) - $started = true; - $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : ''); - $o .= ""; - $day = str_replace(' ',' ',sprintf('%2.2d', $d)); - if($started) { - if(is_array($links) && isset($links[$d])) - $o .= "$day"; - else - $o .= $day; - $d ++; - } - else - $o .= ' '; - $o .= ' | '; - $dow ++; - if(($dow == 7) && ($d <= $l)) { - $dow = 0; - $o .= '
---|---|
'; - $o .= ' |
' . bbcode($ev['summary']) . '
' . "\r\n"; $o .= '' . bbcode($ev['description']) . '
' . "\r\n"; $o .= '' . t('Starts:') . ' '
. (($ev['adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(),
$ev['start'] , $bd_format ))
@@ -38,15 +45,15 @@ function format_event_html($ev) {
if(strlen($ev['location']))
$o .= ' ' . t('Location:') . ' '
- . bbcode($ev['location'])
+ . bbcode($ev['location'])
. '";
- debug_print_backtrace();
- die();
+// case PREG_BAD_UTF8_OFFSET_ERROR: echo('PREG_BAD_UTF8_OFFSET_ERROR'); break;
+ default:
+ //die("Unknown preg error.");
+ return;
}
-
-
- private function _push_stack(){
- $this->stack[] = array($this->r, $this->nodes);
- }
- private function _pop_stack(){
- list($this->r, $this->nodes) = array_pop($this->stack);
-
- }
-
- private function _get_var($name, $retNoKey=false){
- $keys = array_map('trim',explode(".",$name));
- if ($retNoKey && !array_key_exists($keys[0], $this->r)) return KEY_NOT_EXISTS;
- $val = $this->r;
- foreach($keys as $k) {
- $val = (isset($val[$k]) ? $val[$k] : null);
- }
- return template_escape($val);
- }
-
- /**
- * IF node
- *
- * {{ if <$var> }}...[{{ else }} ...] {{ endif }}
- * {{ if <$var>==
";
+ debug_print_backtrace();
+ die();
+ }
+
+ private function _push_stack() {
+ $this->stack[] = array($this->r, $this->nodes);
+ }
+
+ private function _pop_stack(){
+ list($this->r, $this->nodes) = array_pop($this->stack);
+ }
+
+ private function _get_var($name, $retNoKey=false) {
+ $keys = array_map('trim',explode(".",$name));
+ if ($retNoKey && !array_key_exists($keys[0], $this->r))
+ return KEY_NOT_EXISTS;
+
+ $val = $this->r;
+ foreach($keys as $k) {
+ $val = (isset($val[$k]) ? $val[$k] : null);
}
- /**
- * INC node
- *
- * {{ inc
var_dump($var, $var, ...);
+
+ return $ret;
+ }
+
+ /**
+ * INC node
+ * \code
+ * {{ inc var_dump($var, $var, ...);
+ */
+ private function _replcb_debug($args) {
+ $vars = array_map('trim', explode(" ",$args[2]));
+ $vars[] = $args[1];
+
+ $ret = "";
+ foreach ($vars as $var){
+ $ret .= htmlspecialchars(var_export( $this->_get_var($var), true ));
+ $ret .= "\n";
+ }
+ $ret .= "
";
+
+ return $ret;
+ }
+
+ private function _replcb_node($m) {
+ $node = $this->nodes[$m[1]];
+ if (method_exists($this, "_replcb_".$node[1])){
+ $s = call_user_func(array($this, "_replcb_".$node[1]), $node);
+ } else {
+ $s = "";
+ }
+ $s = preg_replace_callback('/\|\|([0-9]+)\|\|/', array($this, "_replcb_node"), $s);
+
+ return $s;
+ }
+
+ private function _replcb($m) {
+ //var_dump(array_map('htmlspecialchars', $m));
+ $this->done = false;
+ $this->nodes[] = (array) $m;
+
+ return "||". (count($this->nodes)-1) ."||";
+ }
+
+ private function _build_nodes($s) {
+ $this->done = false;
+ while (!$this->done) {
+ $this->done=true;
+ $s = preg_replace_callback('|{{ *([a-z]*) *([^}]*)}}([^{]*({{ *else *}}[^{]*)?){{ *end\1 *}}|', array($this, "_replcb"), $s);
+ if ($s==Null) $this->_preg_error();
+ }
+ //({{ *else *}}[^{]*)?
+ krsort($this->nodes);
+
+ return $s;
+ }
+
+ private function var_replace($s) {
+ $m = array();
+ /** regexp:
+ * \$ literal $
+ * (\[)? optional open square bracket
+ * ([a-zA-Z0-9-_]+\.?)+ var name, followed by optional
+ * dot, repeated at least 1 time
+ * (?(1)\]) if there was opened square bracket
+ * (subgrup 1), match close bracket
*/
- private function _replcb_debug($args){
- $vars = array_map('trim', explode(" ",$args[2]));
- $vars[] = $args[1];
-
- $ret = "";
- foreach ($vars as $var){
- $ret .= htmlspecialchars(var_export( $this->_get_var($var), true ));
- $ret .= "\n";
- }
- $ret .= "
";
- return $ret;
- }
-
- private function _replcb_node($m) {
- $node = $this->nodes[$m[1]];
- if (method_exists($this, "_replcb_".$node[1])){
- $s = call_user_func(array($this, "_replcb_".$node[1]), $node);
- } else {
- $s = "";
- }
- $s = preg_replace_callback('/\|\|([0-9]+)\|\|/', array($this, "_replcb_node"), $s);
- return $s;
- }
-
- private function _replcb($m){
- //var_dump(array_map('htmlspecialchars', $m));
- $this->done = false;
- $this->nodes[] = (array) $m;
- return "||". (count($this->nodes)-1) ."||";
- }
-
- private function _build_nodes($s){
- $this->done = false;
- while (!$this->done){
- $this->done=true;
- $s = preg_replace_callback('|{{ *([a-z]*) *([^}]*)}}([^{]*({{ *else *}}[^{]*)?){{ *end\1 *}}|', array($this, "_replcb"), $s);
- if ($s==Null) $this->_preg_error();
- }
- //({{ *else *}}[^{]*)?
- krsort($this->nodes);
- return $s;
- }
-
-
- private function var_replace($s){
- $m = array();
- /** regexp:
- * \$ literal $
- * (\[)? optional open square bracket
- * ([a-zA-Z0-9-_]+\.?)+ var name, followed by optional
- * dot, repeated at least 1 time
- * (?(1)\]) if there was opened square bracket
- * (subgrup 1), match close bracket
- */
- if (preg_match_all('/\$(\[)?([a-zA-Z0-9-_]+\.?)+(?(1)\])/', $s,$m)){
- foreach($m[0] as $var){
-
- $exp = str_replace(array("[", "]"), array("", ""), $var);
- $exptks = explode("|", $exp);
-
- $varn = $exptks[0];
- unset($exptks[0]);
- $val = $this->_get_var($varn, true);
- if ($val != KEY_NOT_EXISTS) {
- /* run filters */
- /*
- * Filter are in form of:
- * filtername:arg:arg:arg
- *
- * "filtername" is function name
- * "arg"s are optional, var value is appended to the end
- * if one "arg"==='x' , is replaced with var value
- *
- * examples:
- * $item.body|htmlspecialchars // escape html chars
- * $item.body|htmlspecialchars|strtoupper // escape html and uppercase result
- * $item.created|date:%Y %M %j // format date (created is a timestamp)
- * $item.body|str_replace:cat:dog // replace all "cat" with "dog"
- * $item.body|str_replace:cat:dog:x:1 // replace one "cat" with "dog"
-
- */
- foreach ($exptks as $filterstr) {
- $filter = explode(":", $filterstr);
- $filtername = $filter[0];
- unset($filter[0]);
- $valkey = array_search("x", $filter);
- if ($valkey === false) {
- $filter[] = $val;
- } else {
- $filter[$valkey] = $val;
- }
- if (function_exists($filtername)) {
- $val = call_user_func_array($filtername, $filter);
- }
- }
- $s = str_replace($var, $val, $s);
+ if (preg_match_all('/\$(\[)?([a-zA-Z0-9-_]+\.?)+(?(1)\])/', $s,$m)) {
+ foreach ($m[0] as $var) {
+ $exp = str_replace(array("[", "]"), array("", ""), $var);
+ $exptks = explode("|", $exp);
+ $varn = $exptks[0];
+ unset($exptks[0]);
+ $val = $this->_get_var($varn, true);
+ if ($val != KEY_NOT_EXISTS) {
+ /* run filters */
+ /*
+ * Filter are in form of:
+ * filtername:arg:arg:arg
+ *
+ * "filtername" is function name
+ * "arg"s are optional, var value is appended to the end
+ * if one "arg"==='x' , is replaced with var value
+ *
+ * examples:
+ * $item.body|htmlspecialchars // escape html chars
+ * $item.body|htmlspecialchars|strtoupper // escape html and uppercase result
+ * $item.created|date:%Y %M %j // format date (created is a timestamp)
+ * $item.body|str_replace:cat:dog // replace all "cat" with "dog"
+ * $item.body|str_replace:cat:dog:x:1 // replace one "cat" with "dog"
+ */
+ foreach ($exptks as $filterstr) {
+ $filter = explode(":", $filterstr);
+ $filtername = $filter[0];
+ unset($filter[0]);
+ $valkey = array_search("x", $filter);
+ if ($valkey === false) {
+ $filter[] = $val;
+ } else {
+ $filter[$valkey] = $val;
+ }
+ if (function_exists($filtername)) {
+ $val = call_user_func_array($filtername, $filter);
+ }
}
+ $s = str_replace($var, $val, $s);
}
}
-
- return $s;
- }
-
- private function replace($s,$r) {
- $this->replace_macros($s, $r);
- }
-
- // TemplateEngine interface
- public function replace_macros($s, $r) {
- $this->r = $r;
-
- $s = $this->_build_nodes($s);
-
- $s = preg_replace_callback('/\|\|([0-9]+)\|\|/', array($this, "_replcb_node"), $s);
- if ($s==Null) $this->_preg_error();
-
- // remove comments block
- $s = preg_replace('/{#[^#]*#}/', "" , $s);
-
- $t2 = dba_timer();
-
- // replace strings recursively (limit to 10 loops)
- $os = ""; $count=0;
- while(($os !== $s) && $count<10){
- $os=$s; $count++;
- $s = $this->var_replace($s);
- }
- return $s;
}
- public function get_markup_template($file, $root='') {
- $template_file = theme_include($file, $root);
- if ($template_file) {
- $content = file_get_contents($template_file);
- }
- return $content;
- }
+ return $s;
}
-
+ private function replace($s, $r) {
+ $this->replace_macros($s, $r);
+ }
+ // TemplateEngine interface
+ public function replace_macros($s, $r) {
+ $this->r = $r;
+
+ $s = $this->_build_nodes($s);
+
+ $s = preg_replace_callback('/\|\|([0-9]+)\|\|/', array($this, "_replcb_node"), $s);
+ if ($s == Null)
+ $this->_preg_error();
+
+ // remove comments block
+ $s = preg_replace('/{#[^#]*#}/', "" , $s);
+
+ //$t2 = dba_timer();
+
+ // replace strings recursively (limit to 10 loops)
+ $os = "";
+ $count=0;
+ while (($os !== $s) && $count<10) {
+ $os=$s;
+ $count++;
+ $s = $this->var_replace($s);
+ }
+
+ return $s;
+ }
+
+ public function get_markup_template($file, $root='') {
+ $template_file = theme_include($file, $root);
+ if ($template_file) {
+ $content = file_get_contents($template_file);
+ }
+
+ return $content;
+ }
+}
function template_escape($s) {
-
return str_replace(array('$','{{'),array('!_Doll^Ars1Az_!','!_DoubLe^BraceS4Rw_!'),$s);
-
-
}
function template_unescape($s) {
-
return str_replace(array('!_Doll^Ars1Az_!','!_DoubLe^BraceS4Rw_!'),array('$','{{'),$s);
-
-
-
}
diff --git a/include/text.php b/include/text.php
index 75125c606..664d5f83d 100644
--- a/include/text.php
+++ b/include/text.php
@@ -1,18 +1,26 @@
- replace)
* @return string substituted string
*/
-function replace_macros($s,$r) {
+function replace_macros($s, $r) {
$a = get_app();
$arr = array('template' => $s, 'params' => $r);
@@ -24,40 +32,38 @@ function replace_macros($s,$r) {
return $output;
}
-
-// random string, there are 86 characters max in text mode, 128 for hex
-// output is urlsafe
-
-define('RANDOM_STRING_HEX', 0x00 );
-define('RANDOM_STRING_TEXT', 0x01 );
-
-
-function random_string($size = 64,$type = RANDOM_STRING_HEX) {
+/**
+ * @brief Generates a random string.
+ *
+ * @param number $size
+ * @param int $type
+ * @return string
+ */
+function random_string($size = 64, $type = RANDOM_STRING_HEX) {
// generate a bit of entropy and run it through the whirlpool
$s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
$s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n","",base64url_encode($s,true)) : $s);
- return(substr($s,0,$size));
+
+ return(substr($s, 0, $size));
}
/**
- * This is our primary input filter.
+ * @brief This is our primary input filter.
*
* The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
* that had an XSS attack vector due to stripping the high-bit on an 8-bit character
* after cleansing, and angle chars with the high bit set could get through as markup.
- *
+ *
* This is now disabled because it was interfering with some legitimate unicode sequences
* and hopefully there aren't a lot of those browsers left.
*
* Use this on any text input where angle chars are not valid or permitted
* They will be replaced with safer brackets. This may be filtered further
- * if these are not allowed either.
+ * if these are not allowed either.
*
* @param string $string Input string
* @return string Filtered string
*/
-
-
function notags($string) {
return(str_replace(array("<",">"), array('[',']'), $string));
@@ -105,7 +111,6 @@ function z_input_filter($channel_id,$s,$type = 'text/bbcode') {
return purify_html($s);
return escape_tags($s);
-
}
@@ -114,39 +119,38 @@ function purify_html($s) {
require_once('library/HTMLPurifier.auto.php');
require_once('include/html2bbcode.php');
-// FIXME this function has html output, not bbcode - so safely purify these
-// $s = html2bb_video($s);
-// $s = oembed_html2bbcode($s);
+/**
+ * @FIXME this function has html output, not bbcode - so safely purify these
+ * $s = html2bb_video($s);
+ * $s = oembed_html2bbcode($s);
+ */
$config = HTMLPurifier_Config::createDefault();
$config->set('Cache.DefinitionImpl', null);
$config->set('Attr.EnableID', true);
$purifier = new HTMLPurifier($config);
+
return $purifier->purify($s);
}
-
-
-// generate a string that's random, but usually pronounceable.
-// used to generate initial passwords
-
-
/**
- * generate a string that's random, but usually pronounceable.
- * used to generate initial passwords
+ * @brief generate a string that's random, but usually pronounceable.
+ *
+ * Used to generate initial passwords.
+ *
* @param int $len
* @return string
*/
function autoname($len) {
- if($len <= 0)
+ if ($len <= 0)
return '';
$vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
- if(mt_rand(0,5) == 4)
+ if (mt_rand(0, 5) == 4)
$vowels[] = 'y';
$cons = array(
@@ -178,8 +182,8 @@ function autoname($len) {
$noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
- $start = mt_rand(0,2);
- if($start == 0)
+ $start = mt_rand(0, 2);
+ if ($start == 0)
$table = $vowels;
else
$table = $cons;
@@ -190,33 +194,30 @@ function autoname($len) {
$r = mt_rand(0,count($table) - 1);
$word .= $table[$r];
- if($table == $vowels)
- $table = array_merge($cons,$midcons);
+ if ($table == $vowels)
+ $table = array_merge($cons, $midcons);
else
$table = $vowels;
-
}
$word = substr($word,0,$len);
- foreach($noend as $noe) {
- if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
+ foreach ($noend as $noe) {
+ if ((strlen($word) > 2) && (substr($word,-2) == $noe)) {
$word = substr($word,0,-1);
break;
}
}
- if(substr($word,-1) == 'q')
- $word = substr($word,0,-1);
+ if (substr($word, -1) == 'q')
+ $word = substr($word, 0, -1);
+
return $word;
}
-// escape text ($str) for XML transport
-// returns escaped text.
-
-
/**
- * escape text ($str) for XML transport
+ * @brief escape text ($str) for XML transport
+ *
* @param string $str
* @return string Escaped text.
*/
@@ -228,7 +229,6 @@ function xmlify($str) {
$char = mb_substr($str,$x,1);
switch( $char ) {
-
case "\r" :
break;
case "&" :
@@ -252,9 +252,10 @@ function xmlify($str) {
default :
$buffer .= $char;
break;
- }
+ }
}
$buffer = trim($buffer);
+
return($buffer);
}
@@ -268,10 +269,12 @@ function unxmlify($s) {
return $ret;
}
-// convenience wrapper, reverse the operation "bin2hex"
-
-// This is a built-in function in php >= 5.4
-
+/**
+ * Convenience wrapper, reverse the operation "bin2hex"
+ * This is a built-in function in php >= 5.4
+ *
+ * @FIXME We already have php >= 5.4 requirements, so can we remove this?
+ */
if(! function_exists('hex2bin')) {
function hex2bin($s) {
if(! (is_string($s) && strlen($s)))
@@ -381,14 +384,16 @@ function alt_pager(&$a, $i, $more = '', $less = '') {
}
-// Turn user/group ACLs stored as angle bracketed text into arrays
-
-
+/**
+ * @brief Turn user/group ACLs stored as angle bracketed text into arrays.
+ *
+ * turn string array of angle-bracketed elements into string array
+ * e.g. "<123xyz><246qyo>
';
}
- }
- else {
+ } else {
$params['string'] = preg_replace_callback('/<(3+)/','preg_heart',$params['string']);
$s = str_replace($params['texts'],$params['icons'],$params['string']);
}
@@ -1083,6 +1087,12 @@ function smilies($s, $sample = false) {
return $s;
}
+/**
+ * @brief
+ *
+ * @param array $m
+ * @return string
+ */
function smile_shield($m) {
return '';
}
@@ -1091,16 +1101,22 @@ function smile_unshield($m) {
return base64url_decode($m[1]);
}
-// expand <3333 to the correct number of hearts
-
+/**
+ * @brief Expand <3333 to the correct number of hearts.
+ *
+ * @param array $x
+ */
function preg_heart($x) {
$a = get_app();
- if(strlen($x[1]) == 1)
+ if (strlen($x[1]) == 1)
return $x[0];
+
$t = '';
for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
$t .= '';
+
$r = str_replace($x[0],$t,$x[0]);
+
return $r;
}
@@ -1118,27 +1134,33 @@ function day_translate($s) {
return $ret;
}
-
-
+/**
+ * @brief normalises a string.
+ *
+ * @param string $url
+ * @return string
+ */
function normalise_link($url) {
- $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
- return(rtrim($ret,'/'));
+ $ret = str_replace(array('https:', '//www.'), array('http:', '//'), $url);
+
+ return(rtrim($ret, '/'));
}
/**
+ * @brief Compare two URLs to see if they are the same.
*
- * Compare two URLs to see if they are the same, but ignore
- * slight but hopefully insignificant differences such as if one
- * is https and the other isn't, or if one is www.something and
- * the other isn't - and also ignore case differences.
+ * But ignore slight but hopefully insignificant differences such as if one
+ * is https and the other isn't, or if one is www.something and the other
+ * isn't - and also ignore case differences.
*
- * Return true if the URLs match, otherwise false.
+ * @see normalis_link()
*
+ * @param string $a
+ * @param string $b
+ * @return true if the URLs match, otherwise false
*/
-
-
-function link_compare($a,$b) {
- if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
+function link_compare($a, $b) {
+ if (strcasecmp(normalise_link($a), normalise_link($b)) === 0)
return true;
return false;
@@ -1167,8 +1189,10 @@ function theme_attachments(&$item) {
$icon = '';
$icontype = substr($r['type'],0,strpos($r['type'],'/'));
- // FIXME This should probably be a giant "if" statement in the template so that we don't have icon names
- // embedded in php code
+ /**
+ * @FIXME This should probably be a giant "if" statement in the
+ * template so that we don't have icon names embedded in php code.
+ */
switch($icontype) {
case 'video':
@@ -1394,11 +1418,14 @@ function prepare_body(&$item,$attach = false) {
return $prep_arr['html'];
}
-
-// Given a text string, convert from bbcode to html and add smilie icons.
-
-
-function prepare_text($text,$content_type = 'text/bbcode') {
+/**
+ * @brief Given a text string, convert from bbcode to html and add smilie icons.
+ *
+ * @param string $text
+ * @param sting $content_type
+ * @return string
+ */
+function prepare_text($text, $content_type = 'text/bbcode') {
switch($content_type) {
case 'text/plain':
@@ -1451,19 +1478,21 @@ function prepare_text($text,$content_type = 'text/bbcode') {
/**
* zidify_callback() and zidify_links() work together to turn any HTML a tags with class="zrl" into zid links
- * These will typically be generated by a bbcode '[zrl]' tag. This is done inside prepare_text() rather than bbcode()
+ * These will typically be generated by a bbcode '[zrl]' tag. This is done inside prepare_text() rather than bbcode()
* because the latter is used for general purpose conversions and the former is used only when preparing text for
* immediate display.
- *
+ *
* Issues: Currently the order of HTML parameters in the text is somewhat rigid and inflexible.
- * We assume it looks like and will not work if zrl and href appear in a different order.
+ * We assume it looks like \ and will not work if zrl and href appear in a different order.
+ *
+ * @param array $match
+ * @return string
*/
-
-
function zidify_callback($match) {
$is_zid = ((feature_enabled(local_channel(),'sendzid')) || (strpos($match[1],'zrl')) ? true : false);
$replace = '' . "\n" ;
}
}
@@ -2094,15 +2126,16 @@ function extra_query_args() {
}
/**
- * This function removes the tag $tag from the text $body and replaces it with
- * the appropiate link.
- *
- * @param unknown_type $body the text to replace the tag in
- * @param unknown_type $access_tag - used to return tag ACL exclusions e.g. @!foo
- * @param unknown_type $str_tags string to add the tag to
- * @param unknown_type $profile_uid
- * @param unknown_type $tag the tag to replace
+ * @brief This function removes the tag $tag from the text $body and replaces it
+ * with the appropiate link.
*
+ * @param App $a
+ * @param[in,out] string &$body the text to replace the tag in
+ * @param[in,out] string &$access_tag used to return tag ACL exclusions e.g. @!foo
+ * @param[in,out] string &$str_tags string to add the tag to
+ * @param int $profile_uid
+ * @param string $tag the tag to replace
+ * @param boolean $diaspora default false
* @return boolean true if replaced, false if not replaced
*/
function handle_tag($a, &$body, &$access_tag, &$str_tags, $profile_uid, $tag, $diaspora = false) {
diff --git a/include/zot.php b/include/zot.php
index 99a787cd9..28a2e8957 100644
--- a/include/zot.php
+++ b/include/zot.php
@@ -1,110 +1,113 @@
-0 order by hubloc_url ",
dbesc($hash),
intval(HUBLOC_FLAGS_DELETED)
);
+
return $ret;
}
/**
+ * @brief Builds a zot notification packet.
*
- * @function zot_build_packet($channel,$type = 'notify',$recipients = null, $remote_key = null, $secret = null)
- * builds a zot notification packet that you can either
- * store in the queue with a message array or call zot_zot to immediately
- * zot it to the other side
- *
- * @param array $channel => sender channel structure
- * @param string $type => packet type: one of 'ping', 'pickup', 'purge', 'refresh', 'force_refresh', 'notify', 'auth_check'
- * @param array $recipients => envelope information, array ( 'guid' => string, 'guid_sig' => string ); empty for public posts
- * @param string $remote_key => optional public site key of target hub used to encrypt entire packet
- * NOTE: remote_key and encrypted packets are required for 'auth_check' packets, optional for all others
- * @param string $secret => random string, required for packets which require verification/callback
- * e.g. 'pickup', 'purge', 'notify', 'auth_check'. Packet types 'ping', 'force_refresh', and 'refresh' do not require verification
+ * Builds a zot notification packet that you can either store in the queue with
+ * a message array or call zot_zot to immediately zot it to the other side.
*
+ * @param array $channel
+ * sender channel structure
+ * @param string $type
+ * packet type: one of 'ping', 'pickup', 'purge', 'refresh', 'force_refresh', 'notify', 'auth_check'
+ * @param array $recipients
+ * envelope information, array ( 'guid' => string, 'guid_sig' => string ); empty for public posts
+ * @param string $remote_key
+ * optional public site key of target hub used to encrypt entire packet
+ * NOTE: remote_key and encrypted packets are required for 'auth_check' packets, optional for all others
+ * @param string $secret
+ * random string, required for packets which require verification/callback
+ * e.g. 'pickup', 'purge', 'notify', 'auth_check'. Packet types 'ping', 'force_refresh', and 'refresh' do not require verification
+ * @param string $extra
* @returns string json encoded zot packet
*/
-
-function zot_build_packet($channel,$type = 'notify',$recipients = null, $remote_key = null, $secret = null, $extra = null) {
+function zot_build_packet($channel, $type = 'notify', $recipients = null, $remote_key = null, $secret = null, $extra = null) {
$data = array(
'type' => $type,
@@ -118,84 +121,76 @@ function zot_build_packet($channel,$type = 'notify',$recipients = null, $remote_
'version' => ZOT_REVISION
);
- if($recipients) {
- for($x = 0; $x < count($recipients); $x ++)
+ if ($recipients) {
+ for ($x = 0; $x < count($recipients); $x ++)
unset($recipients[$x]['hash']);
$data['recipients'] = $recipients;
}
- if($secret) {
+ if ($secret) {
$data['secret'] = $secret;
$data['secret_sig'] = base64url_encode(rsa_sign($secret,$channel['channel_prvkey']));
}
- if($extra) {
- foreach($extra as $k => $v)
+ if ($extra) {
+ foreach ($extra as $k => $v)
$data[$k] = $v;
}
-
logger('zot_build_packet: ' . print_r($data,true), LOGGER_DATA);
// Hush-hush ultra top-secret mode
- if($remote_key) {
+ if ($remote_key) {
$data = crypto_encapsulate(json_encode($data),$remote_key);
}
return json_encode($data);
}
-
/**
- * @function: zot_zot
- * @param: string $url
- * @param: array $data
+ * @brief
*
- * @returns: array => see z_post_url for returned data format
+ * @see z_post_url()
+ *
+ * @param string $url
+ * @param array $data
+ * @return array see z_post_url() for returned data format
*/
-
-
-
-function zot_zot($url,$data) {
- return z_post_url($url,array('data' => $data));
+function zot_zot($url, $data) {
+ return z_post_url($url, array('data' => $data));
}
/**
- * @function: zot_finger
+ * @brief Look up information about channel.
*
- * Look up information about channel
- * @param: string $webbie
- * does not have to be host qualified e.g. 'foo' is treated as 'foo@thishub'
- * @param: array $channel
+ * @param string $webbie
+ * does not have to be host qualified e.g. 'foo' is treated as 'foo\@thishub'
+ * @param array $channel
* (optional), if supplied permissions will be enumerated specifically for $channel
- * @param: boolean $autofallback
+ * @param boolean $autofallback
* fallback/failover to http if https connection cannot be established. Default is true.
*
- * @returns: array => see z_post_url and mod/zfinger.php
+ * @return array see z_post_url() and \ref mod/zfinger.php
*/
+function zot_finger($webbie, $channel = null, $autofallback = true) {
-
-function zot_finger($webbie,$channel = null,$autofallback = true) {
-
-
- if(strpos($webbie,'@') === false) {
+ if (strpos($webbie,'@') === false) {
$address = $webbie;
$host = get_app()->get_hostname();
- }
- else {
+ } else {
$address = substr($webbie,0,strpos($webbie,'@'));
$host = substr($webbie,strpos($webbie,'@')+1);
}
$xchan_addr = $address . '@' . $host;
- if((! $address) || (! $xchan_addr)) {
+ if ((! $address) || (! $xchan_addr)) {
logger('zot_finger: no address :' . $webbie);
return array('success' => false);
- }
+ }
logger('using xchan_addr: ' . $xchan_addr, LOGGER_DATA);
-
+
// potential issue here; the xchan_addr points to the primary hub.
// The webbie we were called with may not, so it might not be found
// unless we query for hubloc_addr instead of xchan_addr
@@ -207,26 +202,24 @@ function zot_finger($webbie,$channel = null,$autofallback = true) {
intval(HUBLOC_FLAGS_PRIMARY)
);
- if($r) {
+ if ($r) {
$url = $r[0]['hubloc_url'];
- if($r[0]['hubloc_network'] && $r[0]['hubloc_network'] !== 'zot') {
+ if ($r[0]['hubloc_network'] && $r[0]['hubloc_network'] !== 'zot') {
logger('zot_finger: alternate network: ' . $webbie);
logger('url: '.$url.', net: '.var_export($r[0]['hubloc_network'],true), LOGGER_DATA);
return array('success' => false);
- }
- }
- else {
+ }
+ } else {
$url = 'https://' . $host;
}
-
$rhs = '/.well-known/zot-info';
$https = ((strpos($url,'https://') === 0) ? true : false);
logger('zot_finger: ' . $address . ' at ' . $url, LOGGER_DEBUG);
- if($channel) {
+ if ($channel) {
$postvars = array(
'address' => $address,
'target' => $channel['channel_guid'],
@@ -236,88 +229,85 @@ function zot_finger($webbie,$channel = null,$autofallback = true) {
$result = z_post_url($url . $rhs,$postvars);
-
- if((! $result['success']) && ($autofallback)) {
- if($https) {
+ if ((! $result['success']) && ($autofallback)) {
+ if ($https) {
logger('zot_finger: https failed. falling back to http');
$result = z_post_url('http://' . $host . $rhs,$postvars);
}
}
- }
- else {
+ } else {
$rhs .= '?f=&address=' . urlencode($address);
$result = z_fetch_url($url . $rhs);
- if((! $result['success']) && ($autofallback)) {
- if($https) {
+ if ((! $result['success']) && ($autofallback)) {
+ if ($https) {
logger('zot_finger: https failed. falling back to http');
$result = z_fetch_url('http://' . $host . $rhs);
}
}
}
-
- if(! $result['success'])
+
+ if (! $result['success'])
logger('zot_finger: no results');
- return $result;
-
+ return $result;
}
/**
- * @function: zot_refresh($them, $channel = null, $force = false)
+ * @brief Refreshes after permission changed or friending, etc.
+ *
+ * zot_refresh is typically invoked when somebody has changed permissions of a channel and they are notified
+ * to fetch new permissions via a finger/discovery operation. This may result in a new connection
+ * (abook entry) being added to a local channel and it may result in auto-permissions being granted.
+ *
+ * Friending in zot is accomplished by sending a refresh packet to a specific channel which indicates a
+ * permission change has been made by the sender which affects the target channel. The hub controlling
+ * the target channel does targetted discovery (a zot-finger request requesting permissions for the local
+ * channel). These are decoded here, and if necessary and abook structure (addressbook) is created to store
+ * the permissions assigned to this channel.
+ *
+ * Initially these abook structures are created with a 'pending' flag, so that no reverse permissions are
+ * implied until this is approved by the owner channel. A channel can also auto-populate permissions in
+ * return and send back a refresh packet of its own. This is used by forum and group communication channels
+ * so that friending and membership in the channel's "club" is automatic.
*
- * zot_refresh is typically invoked when somebody has changed permissions of a channel and they are notified
- * to fetch new permissions via a finger/discovery operation. This may result in a new connection
- * (abook entry) being added to a local channel and it may result in auto-permissions being granted.
- *
- * Friending in zot is accomplished by sending a refresh packet to a specific channel which indicates a
- * permission change has been made by the sender which affects the target channel. The hub controlling
- * the target channel does targetted discovery (a zot-finger request requesting permissions for the local
- * channel). These are decoded here, and if necessary and abook structure (addressbook) is created to store
- * the permissions assigned to this channel.
- *
- * Initially these abook structures are created with a 'pending' flag, so that no reverse permissions are
- * implied until this is approved by the owner channel. A channel can also auto-populate permissions in
- * return and send back a refresh packet of its own. This is used by forum and group communication channels
- * so that friending and membership in the channel's "club" is automatic.
- *
* @param array $them => xchan structure of sender
* @param array $channel => local channel structure of target recipient, required for "friending" operations
+ * @param array $force default false
*
- * @returns boolean true if successful, else false
+ * @returns boolean true if successful, else false
*/
+function zot_refresh($them, $channel = null, $force = false) {
-function zot_refresh($them,$channel = null, $force = false) {
-
- if(array_key_exists('xchan_network',$them) && ($them['xchan_network'] !== 'zot')) {
+ if (array_key_exists('xchan_network', $them) && ($them['xchan_network'] !== 'zot')) {
logger('zot_refresh: not got zot. ' . $them['xchan_name']);
return true;
}
logger('zot_refresh: them: ' . print_r($them,true), LOGGER_DATA);
- if($channel)
+ if ($channel)
logger('zot_refresh: channel: ' . print_r($channel,true), LOGGER_DATA);
$url = null;
- if($them['hubloc_url'])
+ if ($them['hubloc_url']) {
$url = $them['hubloc_url'];
- else {
+ } else {
$r = q("select hubloc_url, hubloc_flags from hubloc where hubloc_hash = '%s'",
dbesc($them['xchan_hash'])
);
- if($r) {
- foreach($r as $rr) {
- if($rr['hubloc_flags'] & HUBLOC_FLAGS_PRIMARY) {
+ if ($r) {
+ foreach ($r as $rr) {
+ if ($rr['hubloc_flags'] & HUBLOC_FLAGS_PRIMARY) {
$url = $rr['hubloc_url'];
break;
}
}
- if(! $url)
+ if (! $url)
$url = $r[0]['hubloc_url'];
}
}
- if(! $url) {
+ if (! $url) {
logger('zot_refresh: no url');
return false;
}
@@ -330,12 +320,13 @@ function zot_refresh($them,$channel = null, $force = false) {
$postvars['key'] = $channel['channel_pubkey'];
}
- if(array_key_exists('xchan_addr',$them) && $them['xchan_addr'])
+ if (array_key_exists('xchan_addr',$them) && $them['xchan_addr'])
$postvars['address'] = $them['xchan_addr'];
- if(array_key_exists('xchan_hash',$them) && $them['xchan_hash'])
+ if (array_key_exists('xchan_hash',$them) && $them['xchan_hash'])
$postvars['guid_hash'] = $them['xchan_hash'];
- if(array_key_exists('xchan_guid',$them) && $them['xchan_guid']
+ if (array_key_exists('xchan_guid',$them) && $them['xchan_guid']
&& array_key_exists('xchan_guid_sig',$them) && $them['xchan_guid_sig']) {
+
$postvars['guid'] = $them['xchan_guid'];
$postvars['guid_sig'] = $them['xchan_guid_sig'];
}
@@ -343,19 +334,19 @@ function zot_refresh($them,$channel = null, $force = false) {
$rhs = '/.well-known/zot-info';
$result = z_post_url($url . $rhs,$postvars);
-
+
logger('zot_refresh: zot-info: ' . print_r($result,true), LOGGER_DATA);
- if($result['success']) {
+ if ($result['success']) {
$j = json_decode($result['body'],true);
- if(! (($j) && ($j['success']))) {
+ if (! (($j) && ($j['success']))) {
logger('zot_refresh: result not decodable');
return false;
}
- $x = import_xchan($j,(($force) ? UPDATE_FLAGS_FORCED : UPDATE_FLAGS_UPDATED));
+ $x = import_xchan($j, (($force) ? UPDATE_FLAGS_FORCED : UPDATE_FLAGS_UPDATED));
if(! $x['success'])
return false;
@@ -415,7 +406,7 @@ function zot_refresh($them,$channel = null, $force = false) {
$next_birthday = $r[0]['abook_dob'];
$current_abook_connected = (($r[0]['abook_flags'] & ABOOK_FLAG_UNCONNECTED) ? 0 : 1);
-
+
$y = q("update abook set abook_their_perms = %d, abook_dob = '%s'
where abook_xchan = '%s' and abook_channel = %d
and not (abook_flags & %d) > 0 ",
@@ -430,8 +421,8 @@ function zot_refresh($them,$channel = null, $force = false) {
// if they are in your address book but you aren't in theirs, and/or this does not
// match your current connected state setting, toggle it.
- // FIXME: uncoverted to postgres
- // FIXME: when this was enabled, all contacts became unconnected. Currently disabled intentionally
+ /** @FIXME uncoverted to postgres */
+ /** @FIXME when this was enabled, all contacts became unconnected. Currently disabled intentionally */
// $y1 = q("update abook set abook_flags = (abook_flags ^ %d)
// where abook_xchan = '%s' and abook_channel = %d
// and not (abook_flags & %d) limit 1",
@@ -505,7 +496,7 @@ function zot_refresh($them,$channel = null, $force = false) {
'type' => NOTIFY_INTRO,
'from_xchan' => $x['hash'],
'to_xchan' => $channel['channel_hash'],
- 'link' => z_root() . '/connedit/' . $new_connection[0]['abook_id'],
+ 'link' => z_root() . '/connedit/' . $new_connection[0]['abook_id'],
));
}
@@ -514,7 +505,6 @@ function zot_refresh($them,$channel = null, $force = false) {
|| (! ($new_connection[0]['abook_flags'] & ABOOK_FLAG_PENDING)) )
proc_run('php','include/onepoll.php',$new_connection[0]['abook_id']);
}
-
}
}
}
@@ -524,25 +514,22 @@ function zot_refresh($them,$channel = null, $force = false) {
}
/**
- * @function: zot_gethub
+ * @brief Look up if channel is known and previously verified.
*
- * A guid and a url, both signed by the sender, distinguish a known sender at a known location
- * This function looks these up to see if the channel is known and therefore previously verified.
- * If not, we will need to verify it.
+ * A guid and a url, both signed by the sender, distinguish a known sender at a
+ * known location.
+ * This function looks these up to see if the channel is known and therefore
+ * previously verified. If not, we will need to verify it.
*
- * @param array $arr
- * $arr must contain:
- * string $arr['guid'] => guid of conversant
- * string $arr['guid_sig'] => guid signed with conversant's private key
- * string $arr['url'] => URL of the origination hub of this communication
- * string $arr['url_sig'] => URL signed with conversant's private key
- *
+ * @param array $arr an assoziative array which must contain:
+ * * \e string \b guid => guid of conversant
+ * * \e string \b guid_sig => guid signed with conversant's private key
+ * * \e string \b url => URL of the origination hub of this communication
+ * * \e string \b url_sig => URL signed with conversant's private key
*
- * @returns: array => hubloc record
+ * @returns array|null null if site is blacklisted or not found, otherwise an
+ * array with an hubloc record
*/
-
-
-
function zot_gethub($arr) {
if($arr['guid'] && $arr['guid_sig'] && $arr['url'] && $arr['url_sig']) {
@@ -581,26 +568,23 @@ function zot_gethub($arr) {
}
/**
- * @function zot_register_hub($arr)
+ * @brief Registers an unknown hup.
*
- * A communication has been received which has an unknown (to us) sender.
- * Perform discovery based on our calculated hash of the sender at the origination address.
- * This will fetch the discovery packet of the sender, which contains the public key we
- * need to verify our guid and url signatures.
+ * A communication has been received which has an unknown (to us) sender.
+ * Perform discovery based on our calculated hash of the sender at the
+ * origination address. This will fetch the discovery packet of the sender,
+ * which contains the public key we need to verify our guid and url signatures.
*
- * @param array $arr
- * $arr must contain:
- * string $arr['guid'] => guid of conversant
- * string $arr['guid_sig'] => guid signed with conversant's private key
- * string $arr['url'] => URL of the origination hub of this communication
- * string $arr['url_sig'] => URL signed with conversant's private key
- *
+ * @param array $arr an assoziative array which must contain:
+ * * \e string \b guid => guid of conversant
+ * * \e string \b guid_sig => guid signed with conversant's private key
+ * * \e string \b url => URL of the origination hub of this communication
+ * * \e string \b url_sig => URL signed with conversant's private key
*
- * @returns array => 'success' (boolean true or false)
- * 'message' (optional error string only if success is false)
+ * @returns array an assoziative array with:
+ * * \b success boolean true or false
+ * * \b message (optional) error string only if success is false
*/
-
-
function zot_register_hub($arr) {
$result = array('success' => false);
@@ -640,15 +624,14 @@ function zot_register_hub($arr) {
}
}
}
+
return $result;
}
-
/**
- * @function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED)
- * Takes an associative array of a fetched discovery packet and updates
+ * @brief Takes an associative array of a fetched discovery packet and updates
* all internal data structures which need to be updated as a result.
- *
+ *
* @param array $arr => json_decoded discovery packet
* @param int $ud_flags
* Determines whether to create a directory update record if any changes occur, default is UPDATE_FLAGS_UPDATED
@@ -659,13 +642,12 @@ function zot_register_hub($arr) {
* If set [typically by update_directory_entry()] indicates a specific update table row and more particularly
* contains a particular address (ud_addr) which needs to be updated in that table.
*
- * @returns array => 'success' (boolean true or false)
- * 'message' (optional error string only if success is false)
+ * @return associative array
+ * * \e boolean \b success boolean true or false
+ * * \e string \b message (optional) error string only if success is false
*/
-
function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) {
-
call_hooks('import_xchan', $arr);
$ret = array('success' => false);
@@ -700,11 +682,11 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) {
$r = q("select * from xchan where xchan_hash = '%s' limit 1",
dbesc($xchan_hash)
- );
+ );
if(! array_key_exists('connect_url', $arr))
- $arr['connect_url'] = '';
-
+ $arr['connect_url'] = '';
+
if(strpos($arr['address'],'/') !== false)
$arr['address'] = substr($arr['address'],0,strpos($arr['address'],'/'));
@@ -713,14 +695,13 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) {
$import_photos = true;
// if we import an entry from a site that's not ours and either or both of us is off the grid - hide the entry.
- // TODO: check if we're the same directory realm, which would mean we are allowed to see it
+ /** @TODO: check if we're the same directory realm, which would mean we are allowed to see it */
$dirmode = get_config('system','directory_mode');
if((($arr['site']['directory_mode'] === 'standalone') || ($dirmode & DIRECTORY_MODE_STANDALONE)) && ($arr['site']['url'] != z_root()))
$arr['searchable'] = false;
-
$hidden = (1 - intval($arr['searchable']));
// Be careful - XCHAN_FLAGS_HIDDEN should evaluate to 1
@@ -770,11 +751,9 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) {
$what .= 'xchan ';
$changed = true;
}
- }
- else {
+ } else {
$import_photos = true;
-
if((($arr['site']['directory_mode'] === 'standalone') || ($dirmode & DIRECTORY_MODE_STANDALONE))
&& ($arr['site']['url'] != z_root()))
$arr['searchable'] = false;
@@ -789,7 +768,7 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) {
$new_flags |= XCHAN_FLAGS_SELFCENSORED;
if(array_key_exists('deleted',$arr) && $arr['deleted'])
$new_flags |= XCHAN_FLAGS_DELETED;
-
+
$x = q("insert into xchan ( xchan_hash, xchan_guid, xchan_guid_sig, xchan_pubkey, xchan_photo_mimetype,
xchan_photo_l, xchan_addr, xchan_url, xchan_connurl, xchan_follow, xchan_connpage, xchan_name, xchan_network, xchan_photo_date, xchan_name_date, xchan_flags)
values ( '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d) ",
@@ -813,11 +792,9 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) {
$what .= 'new_xchan';
$changed = true;
+ }
- }
-
-
- if($import_photos) {
+ if ($import_photos) {
require_once('include/photo/photo_driver.php');
@@ -826,9 +803,9 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) {
$local = q("select channel_account_id, channel_id from channel where channel_hash = '%s' limit 1",
dbesc($xchan_hash)
);
- if($local) {
- $ph = z_fetch_url($arr['photo'],true);
- if($ph['success']) {
+ if ($local) {
+ $ph = z_fetch_url($arr['photo'], true);
+ if ($ph['success']) {
import_channel_photo($ph['body'], $arr['photo_mimetype'], $local[0]['channel_account_id'],$local[0]['channel_id']);
// reset the names in case they got messed up when we had a bug in this function
$photos = array(
@@ -839,12 +816,11 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) {
false
);
}
+ } else {
+ $photos = import_profile_photo($arr['photo'], $xchan_hash);
}
- else {
- $photos = import_profile_photo($arr['photo'],$xchan_hash);
- }
- if($photos) {
- if($photos[4]) {
+ if ($photos) {
+ if ($photos[4]) {
// importing the photo failed somehow. Leave the photo_date alone so we can try again at a later date.
// This often happens when somebody joins the matrix with a bad cert.
$r = q("update xchan set xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s'
@@ -855,8 +831,7 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) {
dbesc($photos[3]),
dbesc($xchan_hash)
);
- }
- else {
+ } else {
$r = q("update xchan set xchan_photo_date = '%s', xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s'
where xchan_hash = '%s'",
dbescdate(datetime_convert('UTC','UTC',$arr['photo_updated'])),
@@ -875,8 +850,7 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) {
// what we are missing for true hub independence is for any changes in the primary hub to
// get reflected not only in the hublocs, but also to update the URLs and addr in the appropriate xchan
-
- $s = sync_locations($arr,$arr);
+ $s = sync_locations($arr, $arr);
if($s) {
if($s['change_message'])
@@ -915,8 +889,7 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) {
$what .= 'profile ';
$changed = true;
}
- }
- else {
+ } else {
logger('import_xchan: profile not available - hiding');
// they may have made it private
$r = q("delete from xprof where xprof_hash = '%s'",
@@ -935,7 +908,6 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) {
$changed = true;
}
}
-
if(($changed) || ($ud_flags == UPDATE_FLAGS_FORCED)) {
$guid = random_string() . '@' . get_app()->get_hostname();
@@ -956,60 +928,52 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) {
$ret['hash'] = $xchan_hash;
}
-
-
logger('import_xchan: result: ' . print_r($ret,true), LOGGER_DATA);
return $ret;
}
/**
- * @function zot_process_response($hub,$arr,$outq) {
- * Called immediately after sending a zot message which is using queue processing
- * Updates the queue item according to the response result and logs any information
- * returned to aid communications troubleshooting.
+ * @brief Called immediately after sending a zot message which is using queue processing.
+ *
+ * Updates the queue item according to the response result and logs any information
+ * returned to aid communications troubleshooting.
*
* @param string $hub - url of site we just contacted
* @param array $arr - output of z_post_url()
* @param array $outq - The queue structure attached to this request
- *
- * @returns nothing
*/
+function zot_process_response($hub, $arr, $outq) {
-
-function zot_process_response($hub,$arr,$outq) {
-
- if(! $arr['success']) {
+ if (! $arr['success']) {
logger('zot_process_response: failed: ' . $hub);
return;
}
- $x = json_decode($arr['body'],true);
+ $x = json_decode($arr['body'], true);
- if(! $x) {
+ if (! $x) {
logger('zot_process_response: No json from ' . $hub);
logger('zot_process_response: headers: ' . print_r($arr['header'],true), LOGGER_DATA);
}
// update the timestamp for this site
- $r = q("update site set site_update = '%s' where site_url = '%s'",
+ q("update site set site_update = '%s' where site_url = '%s'",
dbesc(datetime_convert()),
dbesc(dirname($hub))
);
-
// synchronous message types are handled immediately
// async messages remain in the queue until processed.
- if(intval($outq['outq_async'])) {
- $r = q("update outq set outq_delivered = 1, outq_updated = '%s' where outq_hash = '%s' and outq_channel = %d",
+ if (intval($outq['outq_async'])) {
+ q("update outq set outq_delivered = 1, outq_updated = '%s' where outq_hash = '%s' and outq_channel = %d",
dbesc(datetime_convert()),
dbesc($outq['outq_hash']),
intval($outq['outq_channel'])
);
- }
- else {
- $r = q("delete from outq where outq_hash = '%s' and outq_channel = %d",
+ } else {
+ q("delete from outq where outq_hash = '%s' and outq_channel = %d",
dbesc($outq['outq_hash']),
intval($outq['outq_channel'])
);
@@ -1019,19 +983,20 @@ function zot_process_response($hub,$arr,$outq) {
}
/**
- * @function zot_fetch($arr)
+ * @brief
+ *
+ * We received a notification packet (in mod/post.php) that a message is waiting for us, and we've verified the sender.
+ * Now send back a pickup message, using our message tracking ID ($arr['secret']), which we will sign with our site private key.
+ * The entire pickup message is encrypted with the remote site's public key.
+ * If everything checks out on the remote end, we will receive back a packet containing one or more messages,
+ * which will be processed and delivered before this function ultimately returns.
+ *
+ * @see zot_import()
*
- * We received a notification packet (in mod/post.php) that a message is waiting for us, and we've verified the sender.
- * Now send back a pickup message, using our message tracking ID ($arr['secret']), which we will sign with our site private key.
- * The entire pickup message is encrypted with the remote site's public key.
- * If everything checks out on the remote end, we will receive back a packet containing one or more messages,
- * which will be processed and delivered before this function ultimately returns.
- *
* @param array $arr
* decrypted and json decoded notify packet from remote site
+ * @return array from zot_import()
*/
-
-
function zot_fetch($arr) {
logger('zot_fetch: ' . print_r($arr,true), LOGGER_DATA);
@@ -1054,31 +1019,36 @@ function zot_fetch($arr) {
);
$datatosend = json_encode(crypto_encapsulate(json_encode($data),$ret_hub['hubloc_sitekey']));
-
+
$fetch = zot_zot($url,$datatosend);
$result = zot_import($fetch, $arr['sender']['url']);
+
return $result;
}
/**
- * @function zot_import
+ * @brief Process incoming array of messages.
*
* Process an incoming array of messages which were obtained via pickup, and
* import, update, delete as directed.
- *
- * @param array $arr => 'pickup' structure returned from remote site
- * @param string $sender_url => the url specified by the sender in the initial communication
- * we will verify the sender and url in each returned message structure and also verify
- * that all the messages returned match the site url that we are currently processing.
- *
- * The message types handled here are 'activity' (e.g. posts), 'mail' , 'profile', 'location',
- * and 'channel_sync'
- *
- * @returns array => array ( [0] => string $channel_hash, [1] => string $delivery_status, [2] => string $address )
- * suitable for logging remotely, enumerating the processing results of each message/recipient combination.
- *
+ *
+ * The message types handled here are 'activity' (e.g. posts), 'mail' ,
+ * 'profile', 'location' and 'channel_sync'.
+ *
+ * @param array $arr
+ * 'pickup' structure returned from remote site
+ * @param string $sender_url
+ * the url specified by the sender in the initial communication.
+ * We will verify the sender and url in each returned message structure and
+ * also verify that all the messages returned match the site url that we are
+ * currently processing.
+ *
+ * @returns array
+ * suitable for logging remotely, enumerating the processing results of each message/recipient combination
+ * * [0] => \e string $channel_hash
+ * * [1] => \e string $delivery_status
+ * * [2] => \e string $address
*/
-
function zot_import($arr, $sender_url) {
$data = json_decode($arr['body'],true);
@@ -1168,7 +1138,7 @@ function zot_import($arr, $sender_url) {
}
}
- logger('public post');
+ logger('public post');
// Public post. look for any site members who are or may be accepting posts from this sender
// and who are allowed to see them based on the sender's permissions
@@ -1190,7 +1160,6 @@ function zot_import($arr, $sender_url) {
$i['message']['flags'] = array();
if(! in_array('private',$i['message']['flags']))
$i['message']['flags'][] = 'private';
-
}
}
@@ -1215,8 +1184,8 @@ function zot_import($arr, $sender_url) {
logger('zot_import: no deliveries on this site');
continue;
}
-
- if($i['message']) {
+
+ if($i['message']) {
if($i['message']['type'] === 'activity') {
$arr = get_item_elements($i['message']);
@@ -1230,7 +1199,6 @@ function zot_import($arr, $sender_url) {
$relay = ((array_key_exists('flags',$i['message']) && in_array('relay',$i['message']['flags'])) ? true : false);
$result = process_delivery($i['notify']['sender'],$arr,$deliveries,$relay,false,$message_request);
-
}
elseif($i['message']['type'] === 'mail') {
$arr = get_mail_elements($i['message']);
@@ -1238,9 +1206,7 @@ function zot_import($arr, $sender_url) {
logger('Mail received: ' . print_r($arr,true), LOGGER_DATA);
logger('Mail recipients: ' . print_r($deliveries,true), LOGGER_DATA);
-
$result = process_mail_delivery($i['notify']['sender'],$arr,$deliveries);
-
}
elseif($i['message']['type'] === 'profile') {
$arr = get_profile_elements($i['message']);
@@ -1249,9 +1215,7 @@ function zot_import($arr, $sender_url) {
logger('Profile recipients: ' . print_r($deliveries,true), LOGGER_DATA);
$result = process_profile_delivery($i['notify']['sender'],$arr,$deliveries);
-
}
-
elseif($i['message']['type'] === 'channel_sync') {
// $arr = get_channelsync_elements($i['message']);
@@ -1270,31 +1234,34 @@ function zot_import($arr, $sender_url) {
$result = process_location_delivery($i['notify']['sender'],$arr,$deliveries);
}
-
}
if($result){
- $return = array_merge($return,$result);
+ $return = array_merge($return, $result);
}
}
}
return $return;
-
}
// A public message with no listed recipients can be delivered to anybody who
-// has PERMS_NETWORK for that type of post, PERMS_AUTHED (in-network senders are
+// has PERMS_NETWORK for that type of post, PERMS_AUTHED (in-network senders are
// by definition authenticated) or PERMS_SITE and is one the same
// site, or PERMS_SPECIFIC and the sender is a contact who is granted
// permissions via their connection permissions in the address book.
// Here we take a given message and construct a list of hashes of everybody
-// on the site that we should try and deliver to.
+// on the site that we should try and deliver to.
// Some of these will be rejected, but this gives us a place to start.
+/**
+ * @brief
+ *
+ * @param array $msg
+ * @return NULL|array
+ */
function public_recips($msg) {
-
require_once('include/identity.php');
$check_mentions = false;
@@ -1363,7 +1330,6 @@ function public_recips($msg) {
or ( " . $col . " & " . intval(PERMS_PUBLIC) . ") > 0
or ( " . $col . " & " . intval(PERMS_AUTHED) . ") > 0 ) ";
-
$r = q("select channel_hash as hash from channel $sql or channel_hash = '%s'
and ( channel_pageflags & " . intval(PAGE_REMOVED) . " ) = 0 ",
dbesc($msg['notify']['sender']['hash'])
@@ -1514,7 +1480,6 @@ function allowed_public_recips($msg) {
return $results;
}
-
return array();
}
@@ -1544,7 +1509,6 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque
continue;
}
-
$channel = $r[0];
// allow public postings to the sys channel regardless of permissions, but not
@@ -1763,7 +1727,6 @@ function remove_community_tag($sender,$arr,$uid) {
return;
logger('remove_community_tag: invoked');
-
if(! get_pconfig($uid,'system','blocktags')) {
logger('remove_community tag: permission denied.');
@@ -1806,8 +1769,8 @@ function remove_community_tag($sender,$arr,$uid) {
logger('remove_community_tag: no parent message');
return;
}
-
- $x = q("delete from term where uid = %d and oid = %d and otype = %d and type = %d and term = '%s' and url = '%s'",
+
+ q("delete from term where uid = %d and oid = %d and otype = %d and type = %d and term = '%s' and url = '%s'",
intval($uid),
intval($r[0]['id']),
intval(TERM_OBJ_POST),
@@ -1815,8 +1778,6 @@ function remove_community_tag($sender,$arr,$uid) {
dbesc($i['object']['title']),
dbesc(get_rel_link($i['object']['link'],'alternate'))
);
-
- return;
}
function update_imported_item($sender,$item,$uid) {
@@ -1826,12 +1787,20 @@ function update_imported_item($sender,$item,$uid) {
logger('update_imported_item: failed: ' . $x['message']);
else
logger('update_imported_item');
-
}
-function delete_imported_item($sender,$item,$uid,$relay) {
+/**
+ * @brief Deletes an imported item.
+ *
+ * @param array $sender
+ * @param array $item
+ * @param int $uid
+ * @param unknown $relay
+ * @return boolean|int post_id
+ */
+function delete_imported_item($sender, $item, $uid, $relay) {
- logger('delete_imported_item invoked',LOGGER_DEBUG);
+ logger('delete_imported_item invoked', LOGGER_DEBUG);
$ownership_valid = false;
$item_found = false;
@@ -1841,13 +1810,13 @@ function delete_imported_item($sender,$item,$uid,$relay) {
dbesc($item['mid']),
intval($uid)
);
- if($r) {
- if($r[0]['author_xchan'] === $sender['hash'] || $r[0]['owner_xchan'] === $sender['hash'] || $r[0]['source_xchan'] === $sender['hash'])
+ if ($r) {
+ if ($r[0]['author_xchan'] === $sender['hash'] || $r[0]['owner_xchan'] === $sender['hash'] || $r[0]['source_xchan'] === $sender['hash'])
$ownership_valid = true;
+
$post_id = $r[0]['id'];
$item_found = true;
- }
- else {
+ } else {
// perhaps the item is still in transit and the delete notification got here before the actual item did. Store it with the deleted flag set.
// item_store() won't try to deliver any notifications or start delivery chains if this flag is set.
@@ -1855,22 +1824,24 @@ function delete_imported_item($sender,$item,$uid,$relay) {
// But this will ensure that if the (undeleted) original post comes in at a later date, we'll reject it because it will have an older timestamp.
logger('delete received for non-existent item - storing item data.');
- if($arr['author_xchan'] === $sender['hash'] || $arr['owner_xchan'] === $sender['hash'] || $arr['source_xchan'] === $sender['hash']) {
+
+ /** @BUG $arr is undefined here, so this is dead code */
+ if ($arr['author_xchan'] === $sender['hash'] || $arr['owner_xchan'] === $sender['hash'] || $arr['source_xchan'] === $sender['hash']) {
$ownership_valid = true;
$item_result = item_store($arr);
$post_id = $item_result['item_id'];
}
}
- if($ownership_valid == false) {
+ if ($ownership_valid === false) {
logger('delete_imported_item: failed: ownership issue');
return false;
}
- if($item_found) {
- if($r[0]['item_restrict'] & ITEM_DELETED) {
+ if ($item_found) {
+ if ($r[0]['item_restrict'] & ITEM_DELETED) {
logger('delete_imported_item: item was already deleted');
- if(! $relay)
+ if (! $relay)
return false;
// This is a bit hackish, but may have to suffice until the notification/delivery loop is optimised
@@ -1879,9 +1850,9 @@ function delete_imported_item($sender,$item,$uid,$relay) {
// code path downstream can relay it again (causing a loop). Since it's already gone it's not coming
// back, and we aren't going to (or shouldn't at any rate) delete it again in the future - so losing
// this information from the metadata should have no other discernible impact.
-
- if(($r[0]['id'] != $r[0]['parent']) && ($r[0]['item_flags'] & ITEM_ORIGIN)) {
- $x = q("update item set item_flags = %d where id = %d and uid = %d",
+
+ if (($r[0]['id'] != $r[0]['parent']) && ($r[0]['item_flags'] & ITEM_ORIGIN)) {
+ q("update item set item_flags = %d where id = %d and uid = %d",
intval($r[0]['item_flags'] ^ ITEM_ORIGIN),
intval($r[0]['id']),
intval($r[0]['uid'])
@@ -1889,14 +1860,13 @@ function delete_imported_item($sender,$item,$uid,$relay) {
}
}
-
require_once('include/items.php');
// Use phased deletion to set the deleted flag, call both tag_deliver and the notifier to notify downstream channels
// and then clean up after ourselves with a cron job after several days to do the delete_item_lowlevel() (DROPITEM_PHASE2).
- drop_item($post_id,false, DROPITEM_PHASE1);
- tag_deliver($uid,$post_id);
+ drop_item($post_id, false, DROPITEM_PHASE1);
+ tag_deliver($uid, $post_id);
}
return $post_id;
@@ -1904,17 +1874,13 @@ function delete_imported_item($sender,$item,$uid,$relay) {
function process_mail_delivery($sender,$arr,$deliveries) {
-
$result = array();
-
if($sender['hash'] != $arr['from_xchan']) {
logger('process_mail_delivery: sender is not mail author');
return;
}
-
-
foreach($deliveries as $d) {
$r = q("select * from channel where channel_hash = '%s' limit 1",
dbesc($d['hash'])
@@ -1946,7 +1912,7 @@ function process_mail_delivery($sender,$arr,$deliveries) {
$result[] = array($d['hash'],'mail recalled',$channel['channel_name'],$arr['mid']);
logger('mail_recalled');
}
- else {
+ else {
$result[] = array($d['hash'],'duplicate mail received',$channel['channel_name'],$arr['mid']);
logger('duplicate mail received');
}
@@ -1974,7 +1940,6 @@ function process_rating_delivery($sender,$arr) {
dbesc($sender['hash'])
);
-
if((! $z) || (! rsa_verify($arr['target'] . '.' . $arr['rating'] . '.' . $arr['rating_text'], base64url_decode($arr['signature']),$z[0]['xchan_pubkey']))) {
logger('failed to verify rating');
return;
@@ -2012,7 +1977,6 @@ function process_rating_delivery($sender,$arr) {
);
logger('rating created');
}
- return;
}
@@ -2080,7 +2044,6 @@ function sync_locations($sender,$arr,$absolute = false) {
continue;
}
-
for($x = 0; $x < count($xisting); $x ++) {
if(($xisting[$x]['hubloc_url'] === $location['url'])
&& ($xisting[$x]['hubloc_sitekey'] === $location['sitekey'])) {
@@ -2250,7 +2213,7 @@ function sync_locations($sender,$arr,$absolute = false) {
);
if($r)
hubloc_change_primary($r[0]);
- }
+ }
}
// get rid of any hubs we have for this channel which weren't reported.
@@ -2275,17 +2238,23 @@ function sync_locations($sender,$arr,$absolute = false) {
$ret['changed'] = $changed;
return $ret;
-
}
-
+/**
+ * @brief Returns an array with all known distinct hubs for this channel.
+ *
+ * @see zot_get_hublocs()
+ * @param array $channel an assoziative array which must contain
+ * * \e string \b channel_hash the hash of the channel
+ * @return array an array with assoziated arrays
+ */
function zot_encode_locations($channel) {
$ret = array();
$x = zot_get_hublocs($channel['channel_hash']);
- if($x && count($x)) {
- foreach($x as $hub) {
- if(! ($hub['hubloc_flags'] & HUBLOC_FLAGS_UNVERIFIED)) {
+ if ($x && count($x)) {
+ foreach ($x as $hub) {
+ if (! ($hub['hubloc_flags'] & HUBLOC_FLAGS_UNVERIFIED)) {
$ret[] = array(
'host' => $hub['hubloc_host'],
'address' => $hub['hubloc_addr'],
@@ -2299,24 +2268,25 @@ function zot_encode_locations($channel) {
}
}
}
+
return $ret;
}
-
-
-
-/*
- * @function import_directory_profile
+/**
+ * @brief Imports a directory profile.
*
- * @returns boolean $updated if something changed
- *
+ * @param string $hash
+ * @param array $profile
+ * @param string $addr
+ * @param number $ud_flags
+ * @param number $suppress_update default 0
+ * @return boolean $updated if something changed
*/
-
-function import_directory_profile($hash,$profile,$addr,$ud_flags = UPDATE_FLAGS_UPDATED, $suppress_update = 0) {
+function import_directory_profile($hash, $profile, $addr, $ud_flags = UPDATE_FLAGS_UPDATED, $suppress_update = 0) {
logger('import_directory_profile', LOGGER_DEBUG);
- if(! $hash)
+ if (! $hash)
return false;
$arr = array();
@@ -2337,11 +2307,11 @@ function import_directory_profile($hash,$profile,$addr,$ud_flags = UPDATE_FLAGS_
$arr['xprof_hometown'] = (($profile['hometown']) ? htmlspecialchars($profile['hometown'], ENT_COMPAT,'UTF-8',false) : '');
$clean = array();
- if(array_key_exists('keywords',$profile) and is_array($profile['keywords'])) {
+ if (array_key_exists('keywords', $profile) and is_array($profile['keywords'])) {
import_directory_keywords($hash,$profile['keywords']);
- foreach($profile['keywords'] as $kw) {
- $kw = trim(htmlspecialchars($kw,ENT_COMPAT,'UTF-8',false));
- $kw = trim($kw,',');
+ foreach ($profile['keywords'] as $kw) {
+ $kw = trim(htmlspecialchars($kw,ENT_COMPAT, 'UTF-8', false));
+ $kw = trim($kw, ',');
$clean[] = $kw;
}
}
@@ -2352,48 +2322,47 @@ function import_directory_profile($hash,$profile,$addr,$ud_flags = UPDATE_FLAGS_
// These are not translated, so the German "erwachsenen" keyword will not censor the directory profile. Only the English form - "adult".
- if(in_arrayi('nsfw',$clean) || in_arrayi('adult',$clean)) {
+ if (in_arrayi('nsfw', $clean) || in_arrayi('adult', $clean)) {
q("update xchan set xchan_flags = (xchan_flags | %d) where xchan_hash = '%s'",
intval(XCHAN_FLAGS_SELFCENSORED),
dbesc($hash)
);
}
-
$r = q("select * from xprof where xprof_hash = '%s' limit 1",
dbesc($hash)
);
-
- if($arr['xprof_age'] > 150)
+
+ if ($arr['xprof_age'] > 150)
$arr['xprof_age'] = 150;
- if($arr['xprof_age'] < 0)
+ if ($arr['xprof_age'] < 0)
$arr['xprof_age'] = 0;
-
- if($r) {
+
+ if ($r) {
$update = false;
- foreach($r[0] as $k => $v) {
- if((array_key_exists($k,$arr)) && ($arr[$k] != $v)) {
+ foreach ($r[0] as $k => $v) {
+ if ((array_key_exists($k,$arr)) && ($arr[$k] != $v)) {
logger('import_directory_profile: update ' . $k . ' => ' . $arr[$k]);
$update = true;
break;
}
}
- if($update) {
- $x = q("update xprof set
+ if ($update) {
+ q("update xprof set
xprof_desc = '%s',
xprof_dob = '%s',
- xprof_age = %d,
+ xprof_age = %d,
xprof_gender = '%s',
xprof_marital = '%s',
xprof_sexual = '%s',
xprof_locale = '%s',
xprof_region = '%s',
xprof_postcode = '%s',
- xprof_country = '%s',
- xprof_about = '%s',
- xprof_homepage = '%s',
- xprof_hometown = '%s',
- xprof_keywords = '%s'
+ xprof_country = '%s',
+ xprof_about = '%s',
+ xprof_homepage = '%s',
+ xprof_hometown = '%s',
+ xprof_keywords = '%s'
where xprof_hash = '%s'",
dbesc($arr['xprof_desc']),
dbesc($arr['xprof_dob']),
@@ -2412,11 +2381,10 @@ function import_directory_profile($hash,$profile,$addr,$ud_flags = UPDATE_FLAGS_
dbesc($arr['xprof_hash'])
);
}
- }
- else {
+ } else {
$update = true;
logger('import_directory_profile: new profile ');
- $x = q("insert into xprof (xprof_hash, xprof_desc, xprof_dob, xprof_age, xprof_gender, xprof_marital, xprof_sexual, xprof_locale, xprof_region, xprof_postcode, xprof_country, xprof_about, xprof_homepage, xprof_hometown, xprof_keywords) values ('%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
+ q("insert into xprof (xprof_hash, xprof_desc, xprof_dob, xprof_age, xprof_gender, xprof_marital, xprof_sexual, xprof_locale, xprof_region, xprof_postcode, xprof_country, xprof_about, xprof_homepage, xprof_hometown, xprof_keywords) values ('%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
dbesc($arr['xprof_hash']),
dbesc($arr['xprof_desc']),
dbesc($arr['xprof_dob']),
@@ -2438,8 +2406,9 @@ function import_directory_profile($hash,$profile,$addr,$ud_flags = UPDATE_FLAGS_
$d = array('xprof' => $arr, 'profile' => $profile, 'update' => $update);
call_hooks('import_directory_profile', $d);
- if(($d['update']) && (! $suppress_update))
+ if (($d['update']) && (! $suppress_update))
update_modtime($arr['xprof_hash'],random_string() . '@' . get_app()->get_hostname(), $addr, $ud_flags);
+
return $d['update'];
}
@@ -2528,7 +2497,6 @@ function import_site($arr,$pubkey) {
$site_directory = 0;
if($arr['directory_mode'] == 'normal')
$site_directory = DIRECTORY_MODE_NORMAL;
-
if($arr['directory_mode'] == 'primary')
$site_directory = DIRECTORY_MODE_PRIMARY;
if($arr['directory_mode'] == 'secondary')
@@ -2536,9 +2504,6 @@ function import_site($arr,$pubkey) {
if($arr['directory_mode'] == 'standalone')
$site_directory = DIRECTORY_MODE_STANDALONE;
-
-
-
$register_policy = 0;
if($arr['register_policy'] == 'closed')
$register_policy = REGISTER_CLOSED;
@@ -2569,16 +2534,16 @@ function import_site($arr,$pubkey) {
if(! $x['success'])
$access_policy = ACCESS_PRIVATE;
}
-
+
$directory_url = htmlspecialchars($arr['directory_url'],ENT_COMPAT,'UTF-8',false);
$url = htmlspecialchars(strtolower($arr['url']),ENT_COMPAT,'UTF-8',false);
$sellpage = htmlspecialchars($arr['sellpage'],ENT_COMPAT,'UTF-8',false);
$site_location = htmlspecialchars($arr['location'],ENT_COMPAT,'UTF-8',false);
$site_realm = htmlspecialchars($arr['realm'],ENT_COMPAT,'UTF-8',false);
- // You can have one and only one primary directory per realm.
+ // You can have one and only one primary directory per realm.
// Downgrade any others claiming to be primary. As they have
- // flubbed up this badly already, don't let them be directory servers at all.
+ // flubbed up this badly already, don't let them be directory servers at all.
if(($site_directory === DIRECTORY_MODE_PRIMARY)
&& ($site_realm === get_directory_realm())
@@ -2586,7 +2551,6 @@ function import_site($arr,$pubkey) {
$site_directory = DIRECTORY_MODE_NORMAL;
}
-
if($exists) {
if(($siterecord['site_flags'] != $site_directory)
|| ($siterecord['site_access'] != $access_policy)
@@ -2644,11 +2608,9 @@ function import_site($arr,$pubkey) {
}
return $update;
-
}
-
/**
* Send a zot packet to all hubs where this channel is duplicated, refreshing
* such things as personal settings, channel permissions, address book updates, etc.
@@ -2714,7 +2676,7 @@ function build_sync_packet($uid = 0, $packet = null, $groups_changed = false) {
$info['config'] = $settings;
}
}
-
+
if($channel) {
$info['channel'] = array();
foreach($channel as $k => $v) {
@@ -2775,23 +2737,20 @@ function build_sync_packet($uid = 0, $packet = null, $groups_changed = false) {
if($interval)
@time_sleep_until(microtime(true) + (float) $interval);
}
-
-
}
function process_channel_sync_delivery($sender,$arr,$deliveries) {
-// FIXME - this will sync red structures (channel, pconfig and abook). Eventually we need to make this application agnostic.
-
+ /** @FIXME this will sync red structures (channel, pconfig and abook). Eventually we need to make this application agnostic. */
$result = array();
-
- foreach($deliveries as $d) {
+
+ foreach ($deliveries as $d) {
$r = q("select * from channel where channel_hash = '%s' limit 1",
dbesc($d['hash'])
);
- if(! $r) {
+ if (! $r) {
$result[] = array($d['hash'],'not found');
continue;
}
@@ -2801,7 +2760,6 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) {
$max_friends = service_class_fetch($channel['channel_id'],'total_channels');
$max_feeds = account_service_class_fetch($channel['channel_account_id'],'total_feeds');
-
if($channel['channel_hash'] != $sender['hash']) {
logger('process_channel_sync_delivery: possible forgery. Sender ' . $sender['hash'] . ' is not ' . $channel['channel_hash']);
$result[] = array($d['hash'],'channel mismatch',$channel['channel_name'],'');
@@ -2832,8 +2790,6 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) {
}
}
-
-
if(array_key_exists('abook',$arr) && is_array($arr['abook']) && count($arr['abook'])) {
$total_friends = 0;
$total_feeds = 0;
@@ -2922,7 +2878,7 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) {
}
if($max_feeds !== false && ($clean['abook_flags'] & ABOOK_FLAG_FEED) && $total_feeds > $max_feeds) {
logger('process_channel_sync_delivery: total_feeds service class limit exceeded');
- continue;
+ continue;
}
q("insert into abook ( abook_xchan, abook_channel ) values ('%s', %d ) ",
dbesc($clean['abook_xchan']),
@@ -2931,7 +2887,7 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) {
$total_friends ++;
if($clean['abook_flags'] & ABOOK_FLAG_FEED)
$total_feeds ++;
- }
+ }
if(count($clean)) {
foreach($clean as $k => $v) {
@@ -2975,7 +2931,7 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) {
if(intval($cl['deleted']) && (! intval($y['deleted']))) {
q("delete from group_member where gid = %d",
intval($y['id'])
- );
+ );
}
}
}
@@ -3095,7 +3051,7 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) {
if(! $x) {
q("insert into profile ( profile_guid, aid, uid ) values ('%s', %d, %d)",
dbesc($profile['profile_guid']),
- intval($channel['channel_account_id']),
+ intval($channel['channel_account_id']),
intval($channel['channel_id'])
);
$x = q("select * from profile where profile_guid = '%s' and uid = %d limit 1",
@@ -3109,9 +3065,12 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) {
foreach($profile as $k => $v) {
if(in_array($k,$disallowed))
continue;
+
$clean[$k] = $v;
- // TODO - check if these are allowed, otherwise we'll error
- // We also need to import local photos if a custom photo is selected
+ /**
+ * @TODO check if these are allowed, otherwise we'll error
+ * We also need to import local photos if a custom photo is selected
+ */
}
if(count($clean)) {
foreach($clean as $k => $v) {
@@ -3121,49 +3080,58 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) {
}
}
}
-
+
$result[] = array($d['hash'],'channel sync updated',$channel['channel_name'],'');
-
-
}
+
return $result;
}
// We probably should make rpost discoverable.
-
+
function get_rpost_path($observer) {
if(! $observer)
return '';
- $parsed = parse_url($observer['xchan_url']);
- return $parsed['scheme'] . '://' . $parsed['host'] . (($parsed['port']) ? ':' . $parsed['port'] : '') . '/rpost?f=';
+ $parsed = parse_url($observer['xchan_url']);
+
+ return $parsed['scheme'] . '://' . $parsed['host'] . (($parsed['port']) ? ':' . $parsed['port'] : '') . '/rpost?f=';
}
+
+/**
+ * @brief
+ *
+ * @param array $x
+ * @return boolean|string return false or a hash
+ */
function import_author_zot($x) {
- $hash = make_xchan_hash($x['guid'],$x['guid_sig']);
+ $hash = make_xchan_hash($x['guid'], $x['guid_sig']);
$r = q("select hubloc_url from hubloc where hubloc_guid = '%s' and hubloc_guid_sig = '%s' and (hubloc_flags & %d)>0 limit 1",
dbesc($x['guid']),
dbesc($x['guid_sig']),
intval(HUBLOC_FLAGS_PRIMARY)
);
- if($r) {
+ if ($r) {
logger('import_author_zot: in cache', LOGGER_DEBUG);
return $hash;
}
logger('import_author_zot: entry not in cache - probing: ' . print_r($x,true), LOGGER_DEBUG);
-
- $them = array('hubloc_url' => $x['url'],'xchan_guid' => $x['guid'], 'xchan_guid_sig' => $x['guid_sig']);
- if(zot_refresh($them))
+
+ $them = array('hubloc_url' => $x['url'], 'xchan_guid' => $x['guid'], 'xchan_guid_sig' => $x['guid_sig']);
+ if (zot_refresh($them))
return $hash;
+
return false;
}
/**
- * @function zot_process_message_request($data)
- * If a site receives a comment to a post but finds they have no parent to attach it with, they
+ * @brief Process a message request.
+ *
+ * If a site receives a comment to a post but finds they have no parent to attach it with, they
* may send a 'request' packet containing the message_id of the missing parent. This is the handler
* for that packet. We will create a message_list array of the entire conversation starting with
* the missing parent and invoke delivery to the sender of the packet.
@@ -3173,20 +3141,21 @@ function import_author_zot($x) {
* processed/delivered in order.
*
* Called from mod/post.php
- */
-
-
+ *
+ * @param array $data
+ * @return array
+ */
function zot_process_message_request($data) {
$ret = array('success' => false);
- if(! $data['message_id']) {
+ if (! $data['message_id']) {
$ret['message'] = 'no message_id';
logger('no message_id');
return $ret;
}
$sender = $data['sender'];
- $sender_hash = make_xchan_hash($sender['guid'],$sender['guid_sig']);
+ $sender_hash = make_xchan_hash($sender['guid'], $sender['guid_sig']);
/*
* Find the local channel in charge of this post (the first and only recipient of the request packet)
@@ -3197,7 +3166,7 @@ function zot_process_message_request($data) {
$c = q("select * from channel left join xchan on channel_hash = xchan_hash where channel_hash = '%s' limit 1",
dbesc($recip_hash)
);
- if(! $c) {
+ if (! $c) {
logger('recipient channel not found.');
$ret['message'] .= 'recipient not found.' . EOL;
return $ret;
@@ -3209,7 +3178,7 @@ function zot_process_message_request($data) {
$messages = zot_feed($c[0]['channel_id'],$sender_hash,array('message_id' => $data['message_id']));
- if($messages) {
+ if ($messages) {
$env_recips = null;
$r = q("select hubloc_guid, hubloc_url, hubloc_sitekey, hubloc_network, hubloc_flags, hubloc_callback, hubloc_host
@@ -3219,20 +3188,18 @@ function zot_process_message_request($data) {
intval(HUBLOC_FLAGS_DELETED),
intval(HUBLOC_OFFLINE)
);
- if(! $r) {
+ if (! $r) {
logger('no hubs');
return $ret;
}
$hubs = $r;
- $hublist = array();
- $keys = array();
- $private = ((array_key_exists('flags',$messages[0]) && in_array('private',$messages[0]['flags'])) ? true : false);
+ $private = ((array_key_exists('flags', $messages[0]) && in_array('private',$messages[0]['flags'])) ? true : false);
if($private)
- $env_recips = array('guid' => $sender['guid'],'guid_sig' => $sender['guid_sig'],'hash' => $sender_hash);
+ $env_recips = array('guid' => $sender['guid'], 'guid_sig' => $sender['guid_sig'], 'hash' => $sender_hash);
$data_packet = json_encode(array('message_list' => $messages));
-
+
foreach($hubs as $hub) {
$hash = random_string();
@@ -3260,10 +3227,10 @@ function zot_process_message_request($data) {
* invoke delivery to send out the notify packet
*/
- proc_run('php','include/deliver.php',$hash);
+ proc_run('php', 'include/deliver.php', $hash);
}
-
}
$ret['success'] = true;
+
return $ret;
}
diff --git a/mod/admin.php b/mod/admin.php
index 7182bb9e5..fd2ba510b 100644
--- a/mod/admin.php
+++ b/mod/admin.php
@@ -73,7 +73,7 @@ function admin_post(&$a){
}
/**
- * @param App $$a
+ * @param App &$a
* @return string
*/
function admin_content(&$a) {
@@ -84,7 +84,7 @@ function admin_content(&$a) {
return login(false);
}
- /**
+ /*
* Side bar links
*/
@@ -125,7 +125,7 @@ function admin_content(&$a) {
));
- /**
+ /*
* Page content
*/
$o = '';
@@ -183,7 +183,7 @@ function admin_content(&$a) {
/**
* @brief Returns content for Admin Summary Page.
*
- * @param App $$a
+ * @param App &$a
* @return string HTML from parsed admin_summary.tpl
*/
function admin_page_summary(&$a) {
@@ -252,8 +252,9 @@ function admin_page_summary(&$a) {
/**
- * Admin Site Page
- * @param App $a
+ * @brief POST handler for Admin Site Page.
+ *
+ * @param App &$a
*/
function admin_page_site_post(&$a){
if (!x($_POST, 'page_site')){
@@ -277,15 +278,15 @@ function admin_page_site_post(&$a){
$register_text = ((x($_POST,'register_text')) ? notags(trim($_POST['register_text'])) : '');
- $allowed_sites = ((x($_POST,'allowed_sites')) ? notags(trim($_POST['allowed_sites'])) : '');
- $allowed_email = ((x($_POST,'allowed_email')) ? notags(trim($_POST['allowed_email'])) : '');
- $not_allowed_email = ((x($_POST,'not_allowed_email')) ? notags(trim($_POST['not_allowed_email'])) : '');
- $block_public = ((x($_POST,'block_public')) ? True : False);
- $force_publish = ((x($_POST,'publish_all')) ? True : False);
- $disable_discover_tab = ((x($_POST,'disable_discover_tab')) ? True : False);
- $no_login_on_homepage = ((x($_POST,'no_login_on_homepage')) ? True : False);
- $global_directory = ((x($_POST,'directory_submit_url')) ? notags(trim($_POST['directory_submit_url'])) : '');
- $no_community_page = !((x($_POST,'no_community_page')) ? True : False);
+ $allowed_sites = ((x($_POST,'allowed_sites')) ? notags(trim($_POST['allowed_sites'])) : '');
+ $allowed_email = ((x($_POST,'allowed_email')) ? notags(trim($_POST['allowed_email'])) : '');
+ $not_allowed_email = ((x($_POST,'not_allowed_email')) ? notags(trim($_POST['not_allowed_email'])) : '');
+ $block_public = ((x($_POST,'block_public')) ? True : False);
+ $force_publish = ((x($_POST,'publish_all')) ? True : False);
+ $disable_discover_tab = ((x($_POST,'disable_discover_tab')) ? True : False);
+ $no_login_on_homepage = ((x($_POST,'no_login_on_homepage')) ? True : False);
+ $global_directory = ((x($_POST,'directory_submit_url')) ? notags(trim($_POST['directory_submit_url'])) : '');
+ $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);
$verifyssl = ((x($_POST,'verifyssl')) ? True : False);
@@ -307,7 +308,7 @@ function admin_page_site_post(&$a){
set_config('system', 'sitename', $sitename);
set_config('system', 'no_login_on_homepage', $no_login_on_homepage);
set_config('system', 'verify_email', $verify_email);
- set_config('system','default_expire_days', $default_expire_days);
+ set_config('system', 'default_expire_days', $default_expire_days);
if ($banner == '') {
del_config('system', 'banner');
@@ -360,6 +361,8 @@ function admin_page_site_post(&$a){
}
/**
+ * @brief Admin page site.
+ *
* @param App $a
* @return string
*/
@@ -480,8 +483,8 @@ function admin_page_site(&$a) {
'$default_expire_days' => array('default_expire_days', t('Expiration period in days for imported (matrix/network) content'), intval(get_config('system','default_expire_days')), t('0 for no expiration of imported content')),
'$form_security_token' => get_form_security_token("admin_site"),
));
-
}
+
function admin_page_hubloc_post(&$a){
check_form_security_token_redirectOnErr('/admin/hubloc', 'admin_hubloc');
require_once('include/zot.php');
@@ -617,7 +620,6 @@ function admin_page_queue($a) {
);
}
-
$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");
@@ -626,7 +628,6 @@ function admin_page_queue($a) {
$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(
'$banner' => t('Queue Statistics'),
'$numentries' => t('Total Entries'),
@@ -763,13 +764,11 @@ function admin_page_users(&$a){
}
-// WEe'll still need to link email addresses to admin/users/channels or some such, but this bit doesn't exist yet.
+// We'll still need to link email addresses to admin/users/channels or some such, but this bit doesn't exist yet.
// That's where we need to be doing last post/channel flags/etc, not here.
-
$serviceclass = (($_REQUEST['class']) ? " and account_service_class = '" . dbesc($_REQUEST['class']) . "' " : '');
-
$order = " order by account_email asc ";
if($_REQUEST['order'] === 'expires')
$order = " order by account_expires desc ";
@@ -803,7 +802,6 @@ function admin_page_users(&$a){
// }
// $users = array_map("_setup_users", $users);
-
$t = get_markup_template('admin_users.tpl');
$o = replace_macros($t, array(
// strings //
@@ -841,9 +839,9 @@ function admin_page_users(&$a){
/**
- * Channels admin page
+ * @brief Channels admin page.
*
- * @param App $a
+ * @param App &$a
*/
function admin_page_channels_post(&$a) {
$channels = ( x($_POST, 'channel') ? $_POST['channel'] : Array() );
@@ -872,7 +870,9 @@ function admin_page_channels_post(&$a) {
}
/**
- * @param App $a
+ * @brief
+ *
+ * @param App &$a
* @return string
*/
function admin_page_channels(&$a){
@@ -975,7 +975,7 @@ function admin_page_channels(&$a){
*/
function admin_page_plugins(&$a){
- /**
+ /*
* Single plugin
*/
if ($a->argc == 3){
@@ -1055,7 +1055,7 @@ function admin_page_plugins(&$a){
}
- /**
+ /*
* List plugins
*/
$plugins = array();
@@ -1087,7 +1087,7 @@ function admin_page_plugins(&$a){
* @param string $th
* @param int $result
*/
-function toggle_theme(&$themes,$th,&$result) {
+function toggle_theme(&$themes, $th, &$result) {
for($x = 0; $x < count($themes); $x ++) {
if($themes[$x]['name'] === $th) {
if($themes[$x]['allowed']) {
@@ -1142,9 +1142,9 @@ function rebuild_theme_table($themes) {
/**
- * Themes admin page
+ * @brief Themes admin page.
*
- * @param App $a
+ * @param App &$a
* @return string
*/
function admin_page_themes(&$a){
@@ -1174,7 +1174,7 @@ function admin_page_themes(&$a){
return '';
}
- /**
+ /*
* Single theme
*/
@@ -1253,8 +1253,7 @@ function admin_page_themes(&$a){
));
}
-
- /**
+ /*
* List themes
*/
@@ -1281,9 +1280,9 @@ function admin_page_themes(&$a){
/**
- * Logs admin page
+ * @brief POST handler for logs admin page.
*
- * @param App $a
+ * @param App &$a
*/
function admin_page_logs_post(&$a) {
if (x($_POST, 'page_logs')) {
@@ -1303,6 +1302,8 @@ function admin_page_logs_post(&$a) {
}
/**
+ * @brief Logs admin page.
+ *
* @param App $a
* @return string
*/
@@ -1435,5 +1436,4 @@ function admin_page_profs(&$a) {
'$submit' => t('Save')
));
}
-
}
\ No newline at end of file
diff --git a/mod/id.php b/mod/id.php
index 05a2f3dc5..bd4c1fa89 100644
--- a/mod/id.php
+++ b/mod/id.php
@@ -1,45 +1,51 @@
t('First Name'),
- 'namePerson/last' => t('Last Name'),
- 'namePerson/friendly' => t('Nickname'),
- 'namePerson' => t('Full Name'),
- 'contact/internet/email' => t('Email'),
- 'contact/email' => t('Email'),
- 'media/image/aspect11' => t('Profile Photo'),
- 'media/image' => t('Profile Photo'),
- 'media/image/default' => t('Profile Photo'),
- 'media/image/16x16' => t('Profile Photo 16px'),
- 'media/image/32x32' => t('Profile Photo 32px'),
- 'media/image/48x48' => t('Profile Photo 48px'),
- 'media/image/64x64' => t('Profile Photo 64px'),
- 'media/image/80x80' => t('Profile Photo 80px'),
- 'media/image/128x128' => t('Profile Photo 128px'),
- 'timezone' => t('Timezone'),
- 'contact/web/default' => t('Homepage URL'),
- 'language/pref' => t('Language'),
- 'birthDate/birthYear' => t('Birth Year'),
- 'birthDate/birthMonth' => t('Birth Month'),
- 'birthDate/birthday' => t('Birth Day'),
- 'birthDate' => t('Birthdate'),
- 'gender' => t('Gender'),
- );
-
+$attrMap = array(
+ 'namePerson/first' => t('First Name'),
+ 'namePerson/last' => t('Last Name'),
+ 'namePerson/friendly' => t('Nickname'),
+ 'namePerson' => t('Full Name'),
+ 'contact/internet/email' => t('Email'),
+ 'contact/email' => t('Email'),
+ 'media/image/aspect11' => t('Profile Photo'),
+ 'media/image' => t('Profile Photo'),
+ 'media/image/default' => t('Profile Photo'),
+ 'media/image/16x16' => t('Profile Photo 16px'),
+ 'media/image/32x32' => t('Profile Photo 32px'),
+ 'media/image/48x48' => t('Profile Photo 48px'),
+ 'media/image/64x64' => t('Profile Photo 64px'),
+ 'media/image/80x80' => t('Profile Photo 80px'),
+ 'media/image/128x128' => t('Profile Photo 128px'),
+ 'timezone' => t('Timezone'),
+ 'contact/web/default' => t('Homepage URL'),
+ 'language/pref' => t('Language'),
+ 'birthDate/birthYear' => t('Birth Year'),
+ 'birthDate/birthMonth' => t('Birth Month'),
+ 'birthDate/birthday' => t('Birth Day'),
+ 'birthDate' => t('Birthdate'),
+ 'gender' => t('Gender'),
+);
+/**
+ * @brief Entrypoint for the OpenID implementation.
+ *
+ * @param App &$a
+ */
function id_init(&$a) {
- logger('id: ' . print_r($_REQUEST,true));
+ logger('id: ' . print_r($_REQUEST, true));
-
- if(argc() > 1)
+ if(argc() > 1) {
$which = argv(1);
- else {
+ } else {
$a->error = 404;
return;
}
@@ -48,41 +54,45 @@ function id_init(&$a) {
$channel = $a->get_channel();
profile_load($a,$which,$profile);
-
-
$op = new MysqlProvider;
$op->server();
-
}
-
-function getUserData($handle=null) {
- if(! local_channel()) {
+/**
+ * @brief Returns user data needed for OpenID.
+ *
+ * If no $handle is provided we will use local_channel() by default.
+ *
+ * @param string $handle (default null)
+ * @return boolean|array
+ */
+function getUserData($handle = null) {
+ if (! local_channel()) {
notice( t('Permission denied.') . EOL);
get_app()->page['content'] = login();
+
return false;
}
// logger('handle: ' . $handle);
- if($handle) {
+ if ($handle) {
$r = q("select * from channel left join xchan on channel_hash = xchan_hash where channel_address = '%s' limit 1",
dbesc($handle)
);
- }
- else {
+ } else {
$r = q("select * from channel left join xchan on channel_hash = xchan_hash where channel_id = %d",
intval(local_channel())
);
}
- if(! r)
+ if (! r)
return false;
$x = q("select * from account where account_id = %d limit 1",
intval($r[0]['channel_account_id'])
);
- if($x)
+ if ($x)
$r[0]['email'] = $x[0]['account_email'];
$p = q("select * from profile where is_default = 1 and uid = %d limit 1",
@@ -90,11 +100,11 @@ function getUserData($handle=null) {
);
$gender = '';
- if($p[0]['gender'] == t('Male'))
+ if ($p[0]['gender'] == t('Male'))
$gender = 'M';
- if($p[0]['gender'] == t('Female'))
+ if ($p[0]['gender'] == t('Female'))
$gender = 'F';
-
+
$r[0]['firstName'] = ((strpos($r[0]['channel_name'],' ')) ? substr($r[0]['channel_name'],0,strpos($r[0]['channel_name'],' ')) : $r[0]['channel_name']);
$r[0]['lastName'] = ((strpos($r[0]['channel_name'],' ')) ? substr($r[0]['channel_name'],strpos($r[0]['channel_name'],' ')+1) : '');
$r[0]['namePerson'] = $r[0]['channel_name'];
@@ -113,7 +123,7 @@ function getUserData($handle=null) {
$r[0]['birthday'] = ((intval(substr($p[0]['dob'],8,2))) ? intval(substr($p[0]['dob'],8,2)) : '');
$r[0]['birthdate'] = (($r[0]['birthyear'] && $r[0]['birthmonth'] && $r[0]['birthday']) ? $p[0]['dob'] : '');
$r[0]['gender'] = $gender;
-
+
return $r[0];
/*
@@ -144,20 +154,20 @@ function getUserData($handle=null) {
}
-
-
-class MysqlProvider extends LightOpenIDProvider
-{
-
+/**
+ * @brief MySQL provider for OpenID implementation.
+ *
+ */
+class MysqlProvider extends LightOpenIDProvider {
// See http://openid.net/specs/openid-attribute-properties-list-1_0-01.html
// This list contains a few variations of these attributes to maintain
// compatibility with legacy clients
- private $attrFieldMap = array(
- 'namePerson/first' => 'firstName',
- 'namePerson/last' => 'lastName',
- 'namePerson/friendly' => 'channel_address',
+ private $attrFieldMap = array(
+ 'namePerson/first' => 'firstName',
+ 'namePerson/last' => 'lastName',
+ 'namePerson/friendly' => 'channel_address',
'namePerson' => 'namePerson',
'contact/internet/email' => 'email',
'contact/email' => 'email',
@@ -178,11 +188,9 @@ class MysqlProvider extends LightOpenIDProvider
'birthDate/birthday' => 'birthday',
'birthDate' => 'birthdate',
'gender' => 'gender',
- );
-
-
- function setup($identity, $realm, $assoc_handle, $attributes)
- {
+ );
+
+ function setup($identity, $realm, $assoc_handle, $attributes) {
global $attrMap;
// logger('identity: ' . $identity);
@@ -190,10 +198,10 @@ class MysqlProvider extends LightOpenIDProvider
// logger('assoc_handle: ' . $assoc_handle);
// logger('attributes: ' . print_r($attributes,true));
- $data = getUserData($assoc_handle);
+ $data = getUserData($assoc_handle);
-// FIXME this needs to be a template with localised strings
+/** @FIXME this needs to be a template with localised strings */
$o .= '';
get_app()->page['content'] .= $o;
+ }
- }
-
- function checkid($realm, &$attributes)
- {
+ function checkid($realm, &$attributes) {
logger('checkid: ' . $realm);
-
logger('checkid attrs: ' . print_r($attributes,true));
+ if(isset($_POST['cancel'])) {
+ $this->cancel();
+ }
- if(isset($_POST['cancel'])) {
- $this->cancel();
- }
-
- $data = getUserData();
- if(! $data) {
- return false;
- }
+ $data = getUserData();
+ if(! $data) {
+ return false;
+ }
- $q = get_pconfig(local_channel(),'openid',$realm);
+ $q = get_pconfig(local_channel(), 'openid', $realm);
$attrs = array();
if($q) {
@@ -265,57 +269,42 @@ class MysqlProvider extends LightOpenIDProvider
$attributes[$attr] = $data[$this->attrFieldMap[$attr]];
}
}
-
- if(isset($_POST['always'])) {
- set_pconfig(local_channel(),'openid',$realm,array_keys($attributes));
- }
-
- return z_root() . '/id/' . $data['channel_address'];
- }
-
- function assoc_handle()
- {
- logger('assoc_handle');
- $channel = get_app()->get_channel();
- return z_root() . '/channel/' . $channel['channel_address'];
- }
-
- function setAssoc($handle, $data)
- {
+ if(isset($_POST['always'])) {
+ set_pconfig(local_channel(),'openid',$realm,array_keys($attributes));
+ }
+
+ return z_root() . '/id/' . $data['channel_address'];
+ }
+
+ function assoc_handle() {
+ logger('assoc_handle');
+ $channel = get_app()->get_channel();
+
+ return z_root() . '/channel/' . $channel['channel_address'];
+ }
+
+ function setAssoc($handle, $data) {
logger('setAssoc');
$channel = channelx_by_nick(basename($handle));
if($channel)
set_pconfig($channel['channel_id'],'openid','associate',$data);
- }
-
- function getAssoc($handle)
- {
+ }
+
+ function getAssoc($handle) {
logger('getAssoc: ' . $handle);
$channel = channelx_by_nick(basename($handle));
if($channel)
- return get_pconfig($channel['channel_id'],'openid','associate');
+ return get_pconfig($channel['channel_id'], 'openid', 'associate');
+
return false;
- }
-
- function delAssoc($handle)
- {
+ }
+
+ function delAssoc($handle) {
logger('delAssoc');
$channel = channelx_by_nick(basename($handle));
if($channel)
- return del_pconfig($channel['channel_id'],'openid','associate');
- }
-
+ return del_pconfig($channel['channel_id'], 'openid', 'associate');
+ }
}
-
-
-
-
-
-
-
-
-
-
-
diff --git a/mod/match.php b/mod/match.php
index 5a01ba645..fd739ba2c 100644
--- a/mod/match.php
+++ b/mod/match.php
@@ -1,14 +1,20 @@
get_baseurl() . '/' . $a->cmd;
@@ -18,22 +24,22 @@ function match_content(&$a) {
$r = q("SELECT `keywords` FROM `profile` WHERE `is_default` = 1 AND `uid` = %d LIMIT 1",
intval(local_channel())
);
- if(! count($r))
- return;
- if(! $r[0]['keywords']) {
- notice( t('No keywords to match. Please add keywords to your default profile.') . EOL);
+ if (! count($r))
return;
+ if (! $r[0]['keywords']) {
+ notice( t('No keywords to match. Please add keywords to your default profile.') . EOL);
+ return;
}
$params = array();
$tags = trim($r[0]['keywords']);
-
- if($tags) {
+
+ if ($tags) {
$params['s'] = $tags;
- if($a->pager['page'] != 1)
+ if ($a->pager['page'] != 1)
$params['p'] = $a->pager['page'];
-
+
// if(strlen(get_config('system','directory_submit_url')))
// $x = post_url('http://dir.friendica.com/msearch', $params);
// else
@@ -41,18 +47,14 @@ function match_content(&$a) {
$j = json_decode($x);
- if($j->total) {
+ if ($j->total) {
$a->set_pager_total($j->total);
$a->set_pager_itemspage($j->items_page);
}
- if(count($j->results)) {
-
-
-
+ if (count($j->results)) {
$tpl = get_markup_template('match.tpl');
- foreach($j->results as $jj) {
-
+ foreach ($j->results as $jj) {
$connlnk = $a->get_baseurl() . '/follow/?url=' . $jj->url;
$o .= replace_macros($tpl,array(
'$url' => zid($jj->url),
@@ -64,14 +66,13 @@ function match_content(&$a) {
'$tags' => $jj->tags
));
}
- }
- else {
+ } else {
info( t('No matches') . EOL);
- }
-
+ }
}
$o .= cleardiv();
$o .= paginate($a);
+
return $o;
}
diff --git a/mod/post.php b/mod/post.php
index 31b688221..37002b249 100644
--- a/mod/post.php
+++ b/mod/post.php
@@ -1,20 +1,21 @@
- the urlencoded webbie (channel@host.domain) of the channel requesting access
- ** dest => the desired destination URL (urlencoded)
- ** sec => a random string which is also stored on $mysite for use during the verification phase.
- ** version => the zot revision
- ** delegate => optional urlencoded webbie of a local channel to invoke delegation rights for
+ * Five GET parameters are supplied:
+ * * auth => the urlencoded webbie (channel@host.domain) of the channel requesting access
+ * * dest => the desired destination URL (urlencoded)
+ * * sec => a random string which is also stored on $mysite for use during the verification phase.
+ * * version => the zot revision
+ * * delegate => optional urlencoded webbie of a local channel to invoke delegation rights for
*
* When this packet is received, an "auth-check" zot message is sent to $mysite.
* (e.g. if $_GET['auth'] is foobar@podunk.edu, a zot packet is sent to the podunk.edu zot endpoint, which is typically /post)
* If no information has been recorded about the requesting identity a zot information packet will be retrieved before
* continuing.
- *
+ *
* The sender of this packet is an arbitrary/random site channel. The recipients will be a single recipient corresponding
* to the guid and guid_sig we have associated with the requesting auth identity
*
- *
- * {
- * "type":"auth_check",
- * "sender":{
- * "guid":"kgVFf_...",
- * "guid_sig":"PT9-TApz...",
- * "url":"http:\/\/podunk.edu",
- * "url_sig":"T8Bp7j..."
- * },
- * "recipients":{
- * {
- * "guid":"ZHSqb...",
- * "guid_sig":"JsAAXi..."
- * }
- * }
- * "callback":"\/post",
- * "version":1,
- * "secret":"1eaa661",
- * "secret_sig":"eKV968b1..."
- * }
- *
+ * \code{.json}
+ * {
+ * "type":"auth_check",
+ * "sender":{
+ * "guid":"kgVFf_...",
+ * "guid_sig":"PT9-TApz...",
+ * "url":"http:\/\/podunk.edu",
+ * "url_sig":"T8Bp7j..."
+ * },
+ * "recipients":{
+ * {
+ * "guid":"ZHSqb...",
+ * "guid_sig":"JsAAXi..."
+ * }
+ * }
+ * "callback":"\/post",
+ * "version":1,
+ * "secret":"1eaa661",
+ * "secret_sig":"eKV968b1..."
+ * }
+ * \endcode
*
* auth_check messages MUST use encapsulated encryption. This message is sent to the origination site, which checks the 'secret' to see
* if it is the same as the 'sec' which it passed originally. It also checks the secret_sig which is the secret signed by the
* destination channel's private key and base64url encoded. If everything checks out, a json packet is returned:
*
- * {
- * "success":1,
- * "confirm":"q0Ysovd1u..."
- * "service_class":(optional)
- * "level":(optional)
- * }
+ * \code{.json}
+ * {
+ * "success":1,
+ * "confirm":"q0Ysovd1u...",
+ * "service_class":(optional)
+ * "level":(optional)
+ * }
+ * \endcode
*
* 'confirm' in this case is the base64url encoded RSA signature of the concatenation of 'secret' with the
* base64url encoded whirlpool hash of the requestor's guid and guid_sig; signed with the source channel private key.
* This prevents a man-in-the-middle from inserting a rogue success packet. Upon receipt and successful
* verification of this packet, the destination site will redirect to the original destination URL and indicate a successful remote login.
* Service_class can be used by cooperating sites to provide different access rights based on account rights and subscription plans. It is
- * a string whose contents are not defined by protocol. Example: "basic" or "gold".
- *
- *
+ * a string whose contents are not defined by protocol. Example: "basic" or "gold".
*
+ * @param[in,out] App &$a
*/
-
- if(array_key_exists('auth',$_REQUEST)) {
+function post_init(&$a) {
+
+ if (array_key_exists('auth', $_REQUEST)) {
$ret = array('success' => false, 'message' => '');
@@ -95,7 +97,7 @@ function post_init(&$a) {
$version = $_REQUEST['version'];
$delegate = $_REQUEST['delegate'];
- $test = ((x($_REQUEST,'test')) ? intval($_REQUEST['test']) : 0);
+ $test = ((x($_REQUEST, 'test')) ? intval($_REQUEST['test']) : 0);
// They are authenticating ultimately to the site and not to a particular channel.
// Any channel will do, providing it's currently active. We just need to have an
@@ -105,10 +107,10 @@ function post_init(&$a) {
intval(PAGE_REMOVED)
);
- if(! $c) {
+ if (! $c) {
// nobody here
logger('mod_zot: auth: unable to find a response channel');
- if($test) {
+ if ($test) {
$ret['message'] .= 'no local channels found.' . EOL;
json_return_and_die($ret);
}
@@ -121,12 +123,12 @@ function post_init(&$a) {
dbesc($address)
);
- if(! $x) {
+ if (! $x) {
// finger them if they can't be found.
- $ret = zot_finger($address,null);
- if($ret['success']) {
- $j = json_decode($ret['body'],true);
- if($j)
+ $ret = zot_finger($address, null);
+ if ($ret['success']) {
+ $j = json_decode($ret['body'], true);
+ if ($j)
import_xchan($j);
$x = q("select * from hubloc left join xchan on xchan_hash = hubloc_hash where hubloc_addr = '%s' order by hubloc_id desc limit 1",
dbesc($address)
@@ -166,61 +168,60 @@ function post_init(&$a) {
$j = array();
- if(! $already_authed) {
+ if (! $already_authed) {
// Auth packets MUST use ultra top-secret hush-hush mode - e.g. the entire packet is encrypted using the site private key
// The actual channel sending the packet ($c[0]) is not important, but this provides a generic zot packet with a sender
// which can be verified
$p = zot_build_packet($c[0],$type = 'auth_check', array(array('guid' => $x[0]['hubloc_guid'],'guid_sig' => $x[0]['hubloc_guid_sig'])), $x[0]['hubloc_sitekey'], $sec);
- if($test) {
+ if ($test) {
$ret['message'] .= 'auth check packet created using sitekey ' . $x[0]['hubloc_sitekey'] . EOL;
$ret['message'] .= 'packet contents: ' . $p . EOL;
}
$result = zot_zot($x[0]['hubloc_callback'],$p);
-
- if(! $result['success']) {
+ if (! $result['success']) {
logger('mod_zot: auth_check callback failed.');
- if($test) {
+ if ($test) {
$ret['message'] .= 'auth check request to your site returned .' . print_r($result, true) . EOL;
json_return_and_die($ret);
}
goaway($desturl);
}
- $j = json_decode($result['body'],true);
- if(! $j) {
+ $j = json_decode($result['body'], true);
+ if (! $j) {
logger('mod_zot: auth_check json data malformed.');
if($test) {
$ret['message'] .= 'json malformed: ' . $result['body'] . EOL;
json_return_and_die($ret);
}
- }
+ }
}
- if($test) {
+ if ($test) {
$ret['message'] .= 'auth check request returned .' . print_r($j, true) . EOL;
- }
+ }
- if($already_authed || $j['success']) {
- if($j['success']) {
+ if ($already_authed || $j['success']) {
+ if ($j['success']) {
// legit response, but we do need to check that this wasn't answered by a man-in-middle
- if(! rsa_verify($sec . $x[0]['xchan_hash'],base64url_decode($j['confirm']),$x[0]['xchan_pubkey'])) {
+ if (! rsa_verify($sec . $x[0]['xchan_hash'],base64url_decode($j['confirm']),$x[0]['xchan_pubkey'])) {
logger('mod_zot: auth: final confirmation failed.');
- if($test) {
+ if ($test) {
$ret['message'] .= 'final confirmation failed. ' . $sec . print_r($j,true) . print_r($x[0],true);
json_return_and_die($ret);
}
-
+
goaway($desturl);
}
- if(array_key_exists('service_class',$j))
+ if (array_key_exists('service_class',$j))
$remote_service_class = $j['service_class'];
- if(array_key_exists('level',$j))
+ if (array_key_exists('level',$j))
$remote_level = $j['level'];
- if(array_key_exists('DNT',$j))
+ if (array_key_exists('DNT',$j))
$DNT = $j['DNT'];
}
// everything is good... maybe
@@ -229,35 +230,33 @@ function post_init(&$a) {
// tell them to logout if they're logged in locally as anything but the target remote account
// in which case just shut up because they don't need to be doing this at all.
- if($a->channel['channel_hash'] != $x[0]['xchan_hash']) {
+ if ($a->channel['channel_hash'] != $x[0]['xchan_hash']) {
logger('mod_zot: auth: already authenticated locally as somebody else.');
notice( t('Remote authentication blocked. You are logged into this site locally. Please logout and retry.') . EOL);
- if($test) {
+ if ($test) {
$ret['message'] .= 'already logged in locally with a conflicting identity.' . EOL;
json_return_and_die($ret);
}
-
}
goaway($desturl);
}
-
// log them in
- if($test) {
+ if ($test) {
$ret['success'] = true;
$ret['message'] .= 'Authentication Success!' . EOL;
json_return_and_die($ret);
}
$delegation_success = false;
- if($delegate) {
+ if ($delegate) {
$r = q("select * from channel left join xchan on channel_hash = xchan_hash where xchan_addr = '%s' limit 1",
dbesc($delegate)
);
- if($r && intval($r[0]['channel_id'])) {
+ if ($r && intval($r[0]['channel_id'])) {
$allowed = perm_is_allowed($r[0]['channel_id'],$x[0]['xchan_hash'],'delegate');
- if($allowed) {
+ if ($allowed) {
$_SESSION['delegate_channel'] = $r[0]['channel_id'];
$_SESSION['delegate'] = $x[0]['xchan_hash'];
$_SESSION['account_id'] = intval($r[0]['channel_account_id']);
@@ -267,12 +266,9 @@ function post_init(&$a) {
}
}
}
-
-
-
$_SESSION['authenticated'] = 1;
- if(! $delegation_success) {
+ if (! $delegation_success) {
$_SESSION['visitor_id'] = $x[0]['xchan_hash'];
$_SESSION['my_url'] = $x[0]['xchan_url'];
$_SESSION['my_address'] = $address;
@@ -289,18 +285,15 @@ function post_init(&$a) {
$a->set_groups(init_groups_visitor($_SESSION['visitor_id']));
info(sprintf( t('Welcome %s. Remote authentication successful.'),$x[0]['xchan_name']));
logger('mod_zot: auth success from ' . $x[0]['xchan_addr']);
- q("update hubloc set hubloc_status = (hubloc_status | %d ) where hubloc_id = %d ",
- intval(HUBLOC_WORKS),
- intval($x[0]['hubloc_id'])
- );
-
-
+ q("update hubloc set hubloc_status = (hubloc_status | %d ) where hubloc_id = %d ",
+ intval(HUBLOC_WORKS),
+ intval($x[0]['hubloc_id'])
+ );
} else {
- if($test) {
+ if ($test) {
$ret['message'] .= 'auth failure. ' . print_r($_REQUEST,true) . print_r($j,true) . EOL;
json_return_and_die($ret);
}
-
logger('mod_zot: magic-auth failure - not authenticated: ' . $x[0]['xchan_addr']);
q("update hubloc set hubloc_status = (hubloc_status | %d ) where hubloc_id = %d ",
intval(HUBLOC_RECEIVE_ERROR),
@@ -308,11 +301,14 @@ function post_init(&$a) {
);
}
- // FIXME - we really want to save the return_url in the session before we visit rmagic.
- // This does however prevent a recursion if you visit rmagic directly, as it would otherwise send you back here again.
- // But z_root() probably isn't where you really want to go.
+ /**
+ * @FIXME we really want to save the return_url in the session before we
+ * visit rmagic. This does however prevent a recursion if you visit
+ * rmagic directly, as it would otherwise send you back here again.
+ * But z_root() probably isn't where you really want to go.
+ */
- if($test) {
+ if ($test) {
$ret['message'] .= 'auth failure fallthrough ' . print_r($_REQUEST,true) . print_r($j,true) . EOL;
json_return_and_die($ret);
}
@@ -322,41 +318,40 @@ function post_init(&$a) {
goaway($desturl);
}
- return;
}
/**
- * @function post_post(&$a)
- * zot communications and messaging
+ * @brief zot communications and messaging.
*
- * Sender HTTP posts to this endpoint ($site/post typically) with 'data' parameter set to json zot message packet.
- * This packet is optionally encrypted, which we will discover if the json has an 'iv' element.
- * $contents => array( 'alg' => 'aes256cbc', 'iv' => initialisation vector, 'key' => decryption key, 'data' => encrypted data);
- * $contents->iv and $contents->key are random strings encrypted with this site's RSA public key and then base64url encoded.
- * Currently only 'aes256cbc' is used, but this is extensible should that algorithm prove inadequate.
+ * Sender HTTP posts to this endpoint ($site/post typically) with 'data' parameter set to json zot message packet.
+ * This packet is optionally encrypted, which we will discover if the json has an 'iv' element.
+ * $contents => array( 'alg' => 'aes256cbc', 'iv' => initialisation vector, 'key' => decryption key, 'data' => encrypted data);
+ * $contents->iv and $contents->key are random strings encrypted with this site's RSA public key and then base64url encoded.
+ * Currently only 'aes256cbc' is used, but this is extensible should that algorithm prove inadequate.
*
- * Once decrypted, one will find the normal json_encoded zot message packet.
+ * Once decrypted, one will find the normal json_encoded zot message packet.
*
* Defined packet types are: notify, purge, refresh, force_refresh, auth_check, ping, and pickup
*
* Standard packet: (used by notify, purge, refresh, force_refresh, and auth_check)
- *
+ * \code{.json}
* {
- * "type": "notify",
- * "sender":{
- * "guid":"kgVFf_1...",
- * "guid_sig":"PT9-TApzp...",
- * "url":"http:\/\/podunk.edu",
- * "url_sig":"T8Bp7j5...",
- * },
- * "recipients": { optional recipient array },
- * "callback":"\/post",
- * "version":1,
- * "secret":"1eaa...",
- * "secret_sig": "df89025470fac8..."
+ * "type": "notify",
+ * "sender":{
+ * "guid":"kgVFf_1...",
+ * "guid_sig":"PT9-TApzp...",
+ * "url":"http:\/\/podunk.edu",
+ * "url_sig":"T8Bp7j5...",
+ * },
+ * "recipients": { optional recipient array },
+ * "callback":"\/post",
+ * "version":1,
+ * "secret":"1eaa...",
+ * "secret_sig": "df89025470fac8..."
* }
- *
+ * \endcode
+ *
* Signature fields are all signed with the sender channel private key and base64url encoded.
* Recipients are arrays of guid and guid_sig, which were previously signed with the recipients private
* key and base64url encoded and later obtained via channel discovery. Absence of recipients indicates
@@ -364,108 +359,116 @@ function post_init(&$a) {
*
* "pickup" packet:
* The pickup packet is sent in response to a notify packet from another site
- *
+ * \code{.json}
* {
- * "type":"pickup",
- * "url":"http:\/\/example.com",
- * "callback":"http:\/\/example.com\/post",
- * "callback_sig":"teE1_fLI...",
- * "secret":"1eaa...",
- * "secret_sig":"O7nB4_..."
+ * "type":"pickup",
+ * "url":"http:\/\/example.com",
+ * "callback":"http:\/\/example.com\/post",
+ * "callback_sig":"teE1_fLI...",
+ * "secret":"1eaa...",
+ * "secret_sig":"O7nB4_..."
* }
+ * \endcode
*
- * In the pickup packet, the sig fields correspond to the respective data element signed with this site's system
- * private key and then base64url encoded.
+ * In the pickup packet, the sig fields correspond to the respective data
+ * element signed with this site's system private key and then base64url encoded.
* The "secret" is the same as the original secret from the notify packet.
*
- * If verification is successful, a json structure is returned
- * containing a success indicator and an array of type 'pickup'.
- * Each pickup element contains the original notify request and a message field whose contents are
- * dependent on the message type
+ * If verification is successful, a json structure is returned containing a
+ * success indicator and an array of type 'pickup'.
+ * Each pickup element contains the original notify request and a message field
+ * whose contents are dependent on the message type.
*
- * This JSON array is AES encapsulated using the site public key of the site that sent the initial zot pickup packet.
+ * This JSON array is AES encapsulated using the site public key of the site
+ * that sent the initial zot pickup packet.
* Using the above example, this would be example.com.
- *
- *
+ *
+ * \code{.json}
* {
- * "success":1,
- * "pickup":{
- * "notify":{
- * "type":"notify",
- * "sender":{
- * "guid":"kgVFf_...",
- * "guid_sig":"PT9-TApz...",
- * "url":"http:\/\/z.podunk.edu",
- * "url_sig":"T8Bp7j5D..."
- * },
- * "callback":"\/post",
- * "version":1,
- * "secret":"1eaa661..."
- * },
- * "message":{
- * "type":"activity",
- * "message_id":"10b049ce384cbb2da9467319bc98169ab36290b8bbb403aa0c0accd9cb072e76@podunk.edu",
- * "message_top":"10b049ce384cbb2da9467319bc98169ab36290b8bbb403aa0c0accd9cb072e76@podunk.edu",
- * "message_parent":"10b049ce384cbb2da9467319bc98169ab36290b8bbb403aa0c0accd9cb072e76@podunk.edu",
- * "created":"2012-11-20 04:04:16",
- * "edited":"2012-11-20 04:04:16",
- * "title":"",
- * "body":"Hi Nickordo",
- * "app":"",
- * "verb":"post",
- * "object_type":"",
- * "target_type":"",
- * "permalink":"",
- * "location":"",
- * "longlat":"",
- * "owner":{
- * "name":"Indigo",
- * "address":"indigo@podunk.edu",
- * "url":"http:\/\/podunk.edu",
- * "photo":{
- * "mimetype":"image\/jpeg",
- * "src":"http:\/\/podunk.edu\/photo\/profile\/m\/5"
+ * "success":1,
+ * "pickup":{
+ * "notify":{
+ * "type":"notify",
+ * "sender":{
+ * "guid":"kgVFf_...",
+ * "guid_sig":"PT9-TApz...",
+ * "url":"http:\/\/z.podunk.edu",
+ * "url_sig":"T8Bp7j5D..."
* },
- * "guid":"kgVFf_...",
- * "guid_sig":"PT9-TAp...",
+ * "callback":"\/post",
+ * "version":1,
+ * "secret":"1eaa661..."
* },
- * "author":{
- * "name":"Indigo",
- * "address":"indigo@podunk.edu",
- * "url":"http:\/\/podunk.edu",
- * "photo":{
- * "mimetype":"image\/jpeg",
- * "src":"http:\/\/podunk.edu\/photo\/profile\/m\/5"
+ * "message":{
+ * "type":"activity",
+ * "message_id":"10b049ce384cbb2da9467319bc98169ab36290b8bbb403aa0c0accd9cb072e76@podunk.edu",
+ * "message_top":"10b049ce384cbb2da9467319bc98169ab36290b8bbb403aa0c0accd9cb072e76@podunk.edu",
+ * "message_parent":"10b049ce384cbb2da9467319bc98169ab36290b8bbb403aa0c0accd9cb072e76@podunk.edu",
+ * "created":"2012-11-20 04:04:16",
+ * "edited":"2012-11-20 04:04:16",
+ * "title":"",
+ * "body":"Hi Nickordo",
+ * "app":"",
+ * "verb":"post",
+ * "object_type":"",
+ * "target_type":"",
+ * "permalink":"",
+ * "location":"",
+ * "longlat":"",
+ * "owner":{
+ * "name":"Indigo",
+ * "address":"indigo@podunk.edu",
+ * "url":"http:\/\/podunk.edu",
+ * "photo":{
+ * "mimetype":"image\/jpeg",
+ * "src":"http:\/\/podunk.edu\/photo\/profile\/m\/5"
+ * },
+ * "guid":"kgVFf_...",
+ * "guid_sig":"PT9-TAp...",
* },
- * "guid":"kgVFf_...",
- * "guid_sig":"PT9-TAp..."
+ * "author":{
+ * "name":"Indigo",
+ * "address":"indigo@podunk.edu",
+ * "url":"http:\/\/podunk.edu",
+ * "photo":{
+ * "mimetype":"image\/jpeg",
+ * "src":"http:\/\/podunk.edu\/photo\/profile\/m\/5"
+ * },
+ * "guid":"kgVFf_...",
+ * "guid_sig":"PT9-TAp..."
+ * }
* }
* }
* }
- *}
+ * \endcode
*
- * Currently defined message types are 'activity', 'mail', 'profile', 'location' and 'channel_sync',
- * which each have different content schemas.
+ * Currently defined message types are 'activity', 'mail', 'profile', 'location'
+ * and 'channel_sync', which each have different content schemas.
*
* Ping packet:
- * A ping packet does not require any parameters except the type. It may or may not be encrypted.
- *
+ * A ping packet does not require any parameters except the type. It may or may
+ * not be encrypted.
+ *
+ * \code{.json}
* {
- * "type": "ping"
+ * "type": "ping"
* }
- *
+ * \endcode
+ *
* On receipt of a ping packet a ping response will be returned:
*
+ * \code{.json}
* {
* "success" : 1,
* "site" {
- * "url":"http:\/\/podunk.edu",
- * "url_sig":"T8Bp7j5...",
- * "sitekey": "-----BEGIN PUBLIC KEY-----
- * MIICIjANBgkqhkiG9w0BAQE..."
- * }
+ * "url": "http:\/\/podunk.edu",
+ * "url_sig": "T8Bp7j5...",
+ * "sitekey": "-----BEGIN PUBLIC KEY-----
+ * MIICIjANBgkqhkiG9w0BAQE..."
+ * }
* }
- *
+ * \endcode
+ *
* The ping packet can be used to verify that a site has not been re-installed, and to
* initiate corrective action if it has. The url_sig is signed with the site private key
* and base64url encoded - and this should verify with the enclosed sitekey. Failure to
@@ -479,21 +482,19 @@ function post_init(&$a) {
* If you have no records which match this url_sig and key - no corrective action should
* be taken as this packet may have been returned by an imposter.
*
+ * @param[in,out] App &$a
*/
-
-
function post_post(&$a) {
-
$encrypted_packet = false;
$ret = array('success' => false);
$data = json_decode($_REQUEST['data'],true);
-
- /**
- * Many message packets will arrive encrypted. The existence of an 'iv' element
- * tells us we need to unencapsulate the AES-256-CBC content using the site private key
+ /*
+ * Many message packets will arrive encrypted. The existence of an 'iv'
+ * element tells us we need to unencapsulate the AES-256-CBC content using
+ * the site private key.
*/
if($data && array_key_exists('iv',$data)) {
@@ -539,12 +540,11 @@ function post_post(&$a) {
if($msgtype === 'pickup') {
- /**
+ /*
* The 'pickup' message arrives with a tracking ID which is associated with a particular outq_hash
* First verify that that the returned signatures verify, then check that we have an outbound queue item
* with the correct hash.
* If everything verifies, find any/all outbound messages in the queue for this hubloc and send them back
- *
*/
if((! $data['secret']) || (! $data['secret_sig'])) {
@@ -597,7 +597,7 @@ function post_post(&$a) {
json_return_and_die($ret);
}
- /**
+ /*
* If we made it to here, the signatures verify, but we still don't know if the tracking ID is valid.
* It wouldn't be an error if the tracking ID isn't found, because we may have sent this particular
* queue item with another pickup (after the tracking ID for the other pickup was verified).
@@ -613,7 +613,7 @@ function post_post(&$a) {
json_return_and_die($ret);
}
- /**
+ /*
* Everything is good if we made it here, so find all messages that are going to this location
* and send them all.
*/
@@ -651,33 +651,31 @@ function post_post(&$a) {
$encrypted = crypto_encapsulate(json_encode($ret),$sitekey);
json_return_and_die($encrypted);
- /** pickup: end */
+ /* pickup: end */
}
-
-
- /**
+ /*
* All other message types require us to verify the sender. This is a generic check, so we
* will do it once here and bail if anything goes wrong.
*/
- if(array_key_exists('sender',$data)) {
+ if (array_key_exists('sender',$data)) {
$sender = $data['sender'];
- }
+ }
- /** Check if the sender is already verified here */
+ /* Check if the sender is already verified here */
$hub = zot_gethub($sender);
- if(! $hub) {
+ if (! $hub) {
- /** Have never seen this guid or this guid coming from this location. Check it and register it. */
+ /* Have never seen this guid or this guid coming from this location. Check it and register it. */
// (!!) this will validate the sender
$result = zot_register_hub($sender);
- if((! $result['success']) || (! ($hub = zot_gethub($sender)))) {
+ if ((! $result['success']) || (! ($hub = zot_gethub($sender)))) {
$ret['message'] = 'Hub not available.';
logger('mod_zot: no hub');
json_return_and_die($ret);
@@ -695,12 +693,12 @@ function post_post(&$a) {
// a dead hub came back to life - reset any tombstones we might have
- if($hub['hubloc_status'] & HUBLOC_OFFLINE) {
+ if ($hub['hubloc_status'] & HUBLOC_OFFLINE) {
q("update hubloc set hubloc_status = (hubloc_status & ~%d) where hubloc_id = %d",
intval(HUBLOC_OFFLINE),
intval($hub['hubloc_id'])
);
- if($r[0]['hubloc_flags'] & HUBLOC_FLAGS_ORPHANCHECK) {
+ if ($r[0]['hubloc_flags'] & HUBLOC_FLAGS_ORPHANCHECK) {
q("update hubloc set hubloc_flags = (hubloc_flags & ~%d) where hubloc_id = %d",
intval(HUBLOC_FLAGS_ORPHANCHECK),
intval($hub['hubloc_id'])
@@ -711,15 +709,13 @@ function post_post(&$a) {
intval(XCHAN_FLAGS_ORPHAN),
dbesc($hub['hubloc_hash'])
);
- }
+ }
-
- /**
+ /*
* This hub has now been proven to be valid.
* Any hub with the same URL and a different sitekey cannot be valid.
* Get rid of them (mark them deleted). There's a good chance they were re-installs.
- *
*/
q("update hubloc set hubloc_flags = ( hubloc_flags | %d ) where hubloc_url = '%s' and hubloc_sitekey != '%s' ",
@@ -728,15 +724,15 @@ function post_post(&$a) {
dbesc($hub['hubloc_sitekey'])
);
- // TODO: check which hub is primary and take action if mismatched
+ /** @TODO check which hub is primary and take action if mismatched */
- if(array_key_exists('recipients',$data))
+ if (array_key_exists('recipients', $data))
$recipients = $data['recipients'];
- if($msgtype === 'auth_check') {
+ if ($msgtype === 'auth_check') {
- /**
+ /*
* Requestor visits /magic/?dest=somewhere on their own site with a browser
* magic redirects them to $destsite/post [with auth args....]
* $destsite sends an auth_check packet to originator site
@@ -751,12 +747,12 @@ function post_post(&$a) {
*/
logger('mod_zot: auth_check', LOGGER_DEBUG);
- if(! $encrypted_packet) {
+ if (! $encrypted_packet) {
logger('mod_zot: auth_check packet was not encrypted.');
$ret['message'] .= 'no packet encryption' . EOL;
json_return_and_die($ret);
}
-
+
$arr = $data['sender'];
$sender_hash = make_xchan_hash($arr['guid'],$arr['guid_sig']);
@@ -774,7 +770,7 @@ function post_post(&$a) {
// First verify their signature. We will have obtained a zot-info packet from them as part of the sender
// verification.
- if((! $y) || (! rsa_verify($data['secret'],base64url_decode($data['secret_sig']),$y[0]['xchan_pubkey']))) {
+ if ((! $y) || (! rsa_verify($data['secret'], base64url_decode($data['secret_sig']),$y[0]['xchan_pubkey']))) {
logger('mod_zot: auth_check: sender not found or secret_sig invalid.');
$ret['message'] .= 'sender not found or sig invalid ' . print_r($y,true) . EOL;
json_return_and_die($ret);
@@ -784,14 +780,14 @@ function post_post(&$a) {
$ret['message'] .= 'recipients ' . print_r($recipients,true) . EOL;
- if($data['recipients']) {
+ if ($data['recipients']) {
$arr = $data['recipients'][0];
- $recip_hash = make_xchan_hash($arr['guid'],$arr['guid_sig']);
+ $recip_hash = make_xchan_hash($arr['guid'], $arr['guid_sig']);
$c = q("select channel_id, channel_account_id, channel_prvkey from channel where channel_hash = '%s' limit 1",
dbesc($recip_hash)
);
- if(! $c) {
+ if (! $c) {
logger('mod_zot: auth_check: recipient channel not found.');
$ret['message'] .= 'recipient not found.' . EOL;
json_return_and_die($ret);
@@ -807,7 +803,7 @@ function post_post(&$a) {
dbesc($data['secret']),
dbesc($data['sender']['url'])
);
- if(! $z) {
+ if (! $z) {
logger('mod_zot: auth_check: verification key not found.');
$ret['message'] .= 'verification key not found' . EOL;
json_return_and_die($ret);
@@ -823,70 +819,66 @@ function post_post(&$a) {
logger('mod_zot: auth_check: success', LOGGER_DEBUG);
$ret['success'] = true;
$ret['confirm'] = $confirm;
- if($u && $u[0]['account_service_class'])
+ if ($u && $u[0]['account_service_class'])
$ret['service_class'] = $u[0]['account_service_class'];
// Set "do not track" flag if this site or this channel's profile is restricted
// in some way
- if(intval(get_config('system','block_public')))
+ if (intval(get_config('system','block_public')))
$ret['DNT'] = true;
- if(! perm_is_allowed($c[0]['channel_id'],'','view_profile'))
+ if (! perm_is_allowed($c[0]['channel_id'],'','view_profile'))
$ret['DNT'] = true;
- if(get_pconfig($c[0]['channel_id'],'system','do_not_track'))
+ if (get_pconfig($c[0]['channel_id'],'system','do_not_track'))
$ret['DNT'] = true;
- if(get_pconfig($c[0]['channel_id'],'system','hide_online_status'))
+ if (get_pconfig($c[0]['channel_id'],'system','hide_online_status'))
$ret['DNT'] = true;
json_return_and_die($ret);
-
}
json_return_and_die($ret);
}
- if($msgtype === 'request') {
+ if ($msgtype === 'request') {
// request a particular post/conversation by message_id
$x = zot_process_message_request($data);
json_return_and_die($x);
}
-
- if($msgtype === 'purge') {
- if($recipients) {
+ if ($msgtype === 'purge') {
+ if ($recipients) {
// basically this means "unfriend"
- foreach($recipients as $recip) {
+ foreach ($recipients as $recip) {
$r = q("select channel.*,xchan.* from channel
left join xchan on channel_hash = xchan_hash
where channel_guid = '%s' and channel_guid_sig = '%s' limit 1",
dbesc($recip['guid']),
dbesc($recip['guid_sig'])
);
- if($r) {
+ if ($r) {
$r = q("select abook_id from abook where uid = %d and abook_xchan = '%s' limit 1",
intval($r[0]['channel_id']),
dbesc(make_xchan_hash($sender['guid'],$sender['guid_sig']))
);
- if($r) {
+ if ($r) {
contact_remove($r[0]['channel_id'],$r[0]['abook_id']);
}
}
}
- }
- else {
+ } else {
// Unfriend everybody - basically this means the channel has committed suicide
$arr = $data['sender'];
$sender_hash = make_xchan_hash($arr['guid'],$arr['guid_sig']);
-
+
require_once('include/Contact.php');
remove_all_xchan_resources($sender_hash);
$ret['success'] = true;
json_return_and_die($ret);
-
}
}
- if(($msgtype === 'refresh') || ($msgtype === 'force_refresh')) {
+ if (($msgtype === 'refresh') || ($msgtype === 'force_refresh')) {
// remote channel info (such as permissions or photo or something)
// has been updated. Grab a fresh copy and sync it.
@@ -894,11 +886,11 @@ function post_post(&$a) {
// force_refresh unconditionally creates a directory update record,
// even if no changes were detected upon processing.
- if($recipients) {
+ if ($recipients) {
// This would be a permissions update, typically for one connection
- foreach($recipients as $recip) {
+ foreach ($recipients as $recip) {
$r = q("select channel.*,xchan.* from channel
left join xchan on channel_hash = xchan_hash
where channel_guid = '%s' and channel_guid_sig = '%s' limit 1",
@@ -910,44 +902,37 @@ function post_post(&$a) {
'xchan_guid' => $sender['guid'],
'xchan_guid_sig' => $sender['guid_sig'],
'hubloc_url' => $sender['url']
- ),$r[0], (($msgtype === 'force_refresh') ? true : false));
+ ), $r[0], (($msgtype === 'force_refresh') ? true : false));
}
- }
- else {
+ } else {
// system wide refresh
-
+
$x = zot_refresh(array(
'xchan_guid' => $sender['guid'],
'xchan_guid_sig' => $sender['guid_sig'],
'hubloc_url' => $sender['url']
- ),null,(($msgtype === 'force_refresh') ? true : false));
+ ), null, (($msgtype === 'force_refresh') ? true : false));
}
$ret['success'] = true;
json_return_and_die($ret);
}
- if($msgtype === 'notify') {
+ if ($msgtype === 'notify') {
$async = get_config('system','queued_fetch');
- if($async) {
+ if ($async) {
// add to receive queue
// qreceive_add($data);
- }
- else {
+ } else {
$x = zot_fetch($data);
$ret['delivery_report'] = $x;
}
$ret['success'] = true;
json_return_and_die($ret);
-
}
-
// catchall
json_return_and_die($ret);
-
-
}
-
diff --git a/mod/randprof.php b/mod/randprof.php
index bddb3251a..9817685c8 100644
--- a/mod/randprof.php
+++ b/mod/randprof.php
@@ -6,6 +6,7 @@ function randprof_init(&$a) {
$x = random_profile();
if($x)
goaway(chanlink_url($x));
- // FIXME this doesn't work at the moment as a fallback
+
+ /** FIXME this doesn't work at the moment as a fallback */
goaway($a->get_baseurl() . '/profile');
}
diff --git a/mod/regdir.php b/mod/regdir.php
index 5331c1dd4..025be220b 100644
--- a/mod/regdir.php
+++ b/mod/regdir.php
@@ -1,18 +1,17 @@
false);
@@ -31,8 +30,7 @@ function regdir_init(&$a) {
if($realm === DIRECTORY_REALM) {
$valid = 1;
- }
- else {
+ } else {
$token = get_config('system','realm_token');
if($token && $access_token != $token) {
$result['message'] = 'This realm requires an access token';
@@ -40,19 +38,19 @@ function regdir_init(&$a) {
}
$valid = 1;
}
-
+
$dirmode = intval(get_config('system','directory_mode'));
- if($dirmode == DIRECTORY_MODE_NORMAL) {
+ if ($dirmode == DIRECTORY_MODE_NORMAL) {
$ret['message'] = t('This site is not a directory server');
json_return_and_die($ret);
}
$m = null;
- if($url) {
+ if ($url) {
$m = parse_url($url);
- if((! $m) || (! @dns_get_record($m['host'], DNS_A + DNS_CNAME + DNS_PTR)) || (! filter_var($m['host'], FILTER_VALIDATE_IP) )) {
+ if ((! $m) || (! @dns_get_record($m['host'], DNS_A + DNS_CNAME + DNS_PTR)) || (! filter_var($m['host'], FILTER_VALIDATE_IP) )) {
$result['message'] = 'unparseable url';
json_return_and_die($result);
}
@@ -75,31 +73,28 @@ function regdir_init(&$a) {
);
json_return_and_die($result);
- }
- else {
+ } else {
// We can put this in the sql without the condition after 31 april 2015 assuming
// most directory servers will have updated by then
// This just makes sure it happens if I forget
$sql_extra = ((datetime_convert() > datetime_convert('UTC','UTC','2015-04-31')) ? ' and site_valid = 1 ' : '' );
- if($dirmode == DIRECTORY_MODE_STANDALONE) {
+ if ($dirmode == DIRECTORY_MODE_STANDALONE) {
$r = array(array('site_url' => z_root()));
- }
- else {
+ } else {
$r = q("select site_url from site where site_flags in ( 1, 2 ) and site_realm = '%s' $sql_extra ",
dbesc(get_directory_realm())
);
}
- if($r) {
+ if ($r) {
$result['success'] = true;
$result['directories'] = array();
- foreach($r as $rr)
+ foreach ($r as $rr)
$result['directories'][] = $rr['site_url'];
+
json_return_and_die($result);
}
}
json_return_and_die($result);
-
-
-}
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/mod/share.php b/mod/share.php
index 923971694..d5a389bdf 100644
--- a/mod/share.php
+++ b/mod/share.php
@@ -13,7 +13,6 @@ function share_init(&$a) {
if(! (local_channel() || remote_channel()))
killme();
-
$r = q("SELECT * from item left join xchan on author_xchan = xchan_hash WHERE id = %d LIMIT 1",
intval($post_id)
);
@@ -30,13 +29,12 @@ function share_init(&$a) {
if(! $r)
killme();
- // FIXME - we only share bbcode
+ /** @FIXME we only share bbcode */
if($r[0]['mimetype'] !== 'text/bbcode')
killme();
- // FIXME - eventually we want to post remotely via rpost
- // on your home site.
+ /** @FIXME eventually we want to post remotely via rpost on your home site */
// When that works remove this next bit:
if(! local_channel())
@@ -64,20 +62,20 @@ function share_init(&$a) {
echo $o;
killme();
}
-
+
$observer = $a->get_observer();
$parsed = $observer['xchan_url'];
if($parsed) {
$post_url = $parsed['scheme'] . ':' . $parsed['host'] . (($parsed['port']) ? ':' . $parsed['port'] : '')
. '/rpost';
- // FIXME - we were probably called from JS
- // so we don't know the return page.
- // in fact we won't be able to load the remote page.
- // we might need an iframe
+
+ /**
+ * @FIXME we were probably called from JS so we don't know the return page.
+ * In fact we won't be able to load the remote page.
+ * we might need an iframe
+ */
$x = z_post_url($post_url, array('f' => '', 'body' => $o ));
killme();
}
-
-
}
diff --git a/mod/thing.php b/mod/thing.php
index 4ec10f5a6..c6b70fbb4 100644
--- a/mod/thing.php
+++ b/mod/thing.php
@@ -1,4 +1,8 @@
-get_account();
$channel = $a->get_channel();
@@ -26,19 +27,18 @@ function thing_init(&$a) {
$hash = random_string();
-
$verbs = obj_verbs();
- /**
+ /**
* verbs: [0] = first person singular, e.g. "I want", [1] = 3rd person singular, e.g. "Bill wants"
* We use the first person form when creating an activity, but the third person for use in activities
- * FIXME: There is no accounting for verb gender for languages where this is significant. We may eventually
+ * @FIXME There is no accounting for verb gender for languages where this is significant. We may eventually
* require obj_verbs() to provide full conjugations and specify which form to use in the $_REQUEST params to this module.
*/
$translated_verb = $verbs[$verb][1];
- /**
+ /*
* The site administrator can do things that normals cannot.
* This is restricted because it will likely cause
* an activitystreams protocol violation and the activity might
@@ -50,14 +50,14 @@ function thing_init(&$a) {
if(! $translated_verb) {
if(is_site_admin())
$translated_verb = $verb;
- }
-
- /**
+ }
+
+ /*
* Things, objects: We do not provide definite (a, an) or indefinite (the) articles or singular/plural designators
* That needs to be specified in your thing. e.g. Mike has "a carrot", Greg wants "balls", Bob likes "the Boston Red Sox".
*/
- /**
+ /*
* Future work on this module might produce more complex activities with targets, e.g. Phillip likes Karen's moustache
* and to describe other non-thing objects like channels, such as Karl wants Susan - where Susan represents a channel profile.
*/
@@ -65,8 +65,6 @@ function thing_init(&$a) {
if((! $name) || (! $translated_verb))
return;
-
-
if($term_hash) {
$t = q("select * from obj left join term on obj_obj = term_hash where term_hash != '' and obj_type = %d and term_hash = '%s' limit 1",
intval(TERM_OBJ_THING),
@@ -115,7 +113,6 @@ function thing_init(&$a) {
$local_photo_type = $arr[3];
}
-
$r = q("select * from term where uid = %d and otype = %d and type = %d and term = '%s' limit 1",
intval(local_channel()),
intval(TERM_OBJ_THING),
@@ -159,14 +156,12 @@ function thing_init(&$a) {
info( t('Thing added'));
-
if($activity) {
$arr = array();
$links = array(array('rel' => 'alternate','type' => 'text/html', 'href' => $term['url']));
if($local_photo)
$links[] = array('rel' => 'photo', 'type' => $local_photo_type, 'href' => $local_photo);
-
$objtype = ACTIVITY_OBJ_THING;
$obj = json_encode(array(
@@ -182,9 +177,8 @@ function thing_init(&$a) {
$arr['owner_xchan'] = $channel['channel_hash'];
$arr['author_xchan'] = $channel['channel_hash'];
-
$arr['item_flags'] = ITEM_ORIGIN|ITEM_WALL|ITEM_THREAD_TOP;
-
+
$ulink = '[zrl=' . $channel['xchan_url'] . ']' . $channel['channel_name'] . '[/zrl]';
$plink = '[zrl=' . $term['url'] . ']' . $term['term'] . '[/zrl]';
@@ -212,14 +206,14 @@ function thing_init(&$a) {
else
$arr['allow_cid'] = '<' . get_observer_hash() . '>';
}
-
+
$ret = post_activity_item($arr);
}
}
function thing_content(&$a) {
-
+
if(argc() == 2) {
$r = q("select * from obj left join term on obj_obj = term_hash where term_hash != '' and obj_type = %d and term_hash = '%s' limit 1",
@@ -249,12 +243,10 @@ function thing_content(&$a) {
}
$thing_hash = '';
-
if(argc() == 3 && argv(1) === 'edit') {
$thing_hash = argv(2);
-
$r = q("select * from obj left join term on obj_obj = term_hash where term_hash != '' and obj_type = %d and term_hash = '%s' limit 1",
intval(TERM_OBJ_THING),
dbesc($thing_hash)
@@ -265,7 +257,6 @@ function thing_content(&$a) {
return '';
}
-
$o .= replace_macros(get_markup_template('thing_edit.tpl'),array(
'$thing_hdr' => t('Edit Thing'),
'$multiprof' => feature_enabled(local_channel(),'multi_profiles'),
@@ -300,7 +291,6 @@ function thing_content(&$a) {
return '';
}
-
$x = q("delete from obj where obj_obj = '%s' and obj_type = %d and obj_channel = %d",
dbesc($thing_hash),
intval(TERM_OBJ_THING),
@@ -310,6 +300,7 @@ function thing_content(&$a) {
dbesc($thing_hash),
intval(local_channel())
);
+
return $o;
}
@@ -328,6 +319,4 @@ function thing_content(&$a) {
));
return $o;
-
-
}
diff --git a/util/Doxyfile b/util/Doxyfile
index 44fef3838..f700c2abe 100644
--- a/util/Doxyfile
+++ b/util/Doxyfile
@@ -1,4 +1,4 @@
-INPUT = index.php boot.php mod/ include/ setup/ util/ view/
+INPUT = README.md index.php boot.php mod/ include/ util/ view/ version.inc
RECURSIVE = YES
PROJECT_NAME = "The RedMatrix"
PROJECT_LOGO = images/rm-64.png
@@ -12,9 +12,12 @@ GENERATE_LATEX = NO
EXTRACT_ALL = YES
EXTRACT_PRIVATE = YES
GENERATE_TODOLIST = YES
-USE_MDFILE_AS_MAINPAGE = README
+USE_MDFILE_AS_MAINPAGE = README.md
REFERENCED_BY_RELATION = YES
GENERATE_TREEVIEW = YES
HTML_FOOTER = util/Doxygen.footer
ALIASES += "license=@par License:\n"
ALIASES += "fixme=\xrefitem fixme \"Fixme\" \"Fixme List\""
+ALIASES += "FIXME=\fixme"
+ALIASES += "TODO=\todo"
+ALIASES += "BUG=\bug"