aboutsummaryrefslogtreecommitdiffstats
path: root/include
diff options
context:
space:
mode:
authorfriendica <info@friendica.com>2015-04-23 19:49:41 -0700
committerfriendica <info@friendica.com>2015-04-23 19:49:41 -0700
commit6679734135fb04f4a7beccb81663bf1e9574f062 (patch)
tree887488543d98b5dd297d917718bdd99844e83ba5 /include
parent08b757a22cd2804bfec8ecf682b6987b8c06ca49 (diff)
parentc696860cc53bc25558d83de5eda65d9b583da382 (diff)
downloadvolse-hubzilla-6679734135fb04f4a7beccb81663bf1e9574f062.tar.gz
volse-hubzilla-6679734135fb04f4a7beccb81663bf1e9574f062.tar.bz2
volse-hubzilla-6679734135fb04f4a7beccb81663bf1e9574f062.zip
Merge branch 'master' into tres
Conflicts: include/Contact.php include/ItemObject.php include/api.php include/attach.php include/diaspora.php include/dir_fns.php include/enotify.php include/event.php include/expire.php include/items.php include/notifier.php include/notify.php include/photos.php include/taxonomy.php include/text.php include/widgets.php include/zot.php mod/admin.php mod/channel.php mod/dirsearch.php mod/display.php mod/editwebpage.php mod/events.php mod/home.php mod/item.php mod/manage.php mod/mood.php mod/network.php mod/page.php mod/photos.php mod/ping.php mod/post.php mod/thing.php mod/viewsrc.php view/css/mod_events.css
Diffstat (limited to 'include')
-rwxr-xr-xinclude/ITemplateEngine.php21
-rw-r--r--include/Import/refimport.php2
-rw-r--r--include/ItemObject.php45
-rw-r--r--include/RedDAV/RedBrowser.php11
-rw-r--r--include/RedDAV/RedDirectory.php1
-rw-r--r--include/RedDAV/RedFile.php3
-rw-r--r--include/account.php257
-rw-r--r--include/api.php357
-rw-r--r--include/attach.php258
-rw-r--r--include/auth.php3
-rw-r--r--include/bb2diaspora.php81
-rw-r--r--include/bbcode.php423
-rw-r--r--include/bookmarks.php2
-rw-r--r--include/chat.php47
-rw-r--r--include/comanche.php167
-rw-r--r--include/config.php29
-rw-r--r--include/conversation.php570
-rw-r--r--include/crypto.php15
-rw-r--r--include/datetime.php452
-rwxr-xr-xinclude/dba/dba_driver.php23
-rw-r--r--include/deliver.php28
-rwxr-xr-xinclude/diaspora.php344
-rw-r--r--include/dir_fns.php289
-rw-r--r--include/directory.php34
-rw-r--r--include/enotify.php191
-rw-r--r--include/event.php124
-rw-r--r--include/expire.php84
-rw-r--r--include/features.php7
-rw-r--r--include/follow.php10
-rw-r--r--include/group.php4
-rw-r--r--include/hubloc.php20
-rw-r--r--include/identity.php440
-rwxr-xr-xinclude/items.php1180
-rw-r--r--include/js_strings.php2
-rw-r--r--include/language.php104
-rw-r--r--include/menu.php66
-rw-r--r--include/nav.php4
-rw-r--r--include/network.php117
-rw-r--r--include/notifier.php54
-rw-r--r--include/notify.php2
-rwxr-xr-xinclude/oembed.php18
-rw-r--r--include/onepoll.php2
-rw-r--r--include/permissions.php130
-rw-r--r--include/photo/photo_driver.php11
-rw-r--r--include/photos.php244
-rwxr-xr-xinclude/plugin.php131
-rw-r--r--include/poller.php19
-rw-r--r--include/queue.php21
-rw-r--r--include/ratenotif.php22
-rw-r--r--include/security.php42
-rw-r--r--include/session.php118
-rw-r--r--include/sharedwithme.php32
-rw-r--r--include/socgraph.php53
-rw-r--r--include/taxonomy.php135
-rwxr-xr-xinclude/template_processor.php540
-rw-r--r--include/text.php522
-rw-r--r--include/widgets.php51
-rw-r--r--include/zot.php1388
58 files changed, 5463 insertions, 3887 deletions
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 @@
-<?php
-require_once 'boot.php';
-
-
-/**
- * Interface for template engines
- */
-interface ITemplateEngine {
- public function replace_macros($s,$v);
- public function get_markup_template($file, $root='');
-}
+<?php
+require_once 'boot.php';
+
+/**
+ * @brief Interface for template engines.
+ */
+interface ITemplateEngine {
+ public function replace_macros($s, $v);
+ public function get_markup_template($file, $root='');
+}
diff --git a/include/Import/refimport.php b/include/Import/refimport.php
index a7c0ef4c8..9b9b04bc7 100644
--- a/include/Import/refimport.php
+++ b/include/Import/refimport.php
@@ -177,7 +177,7 @@ function reflect_photo_callback($matches) {
'resource_id' => str_replace('-','',$hash),
'filename' => $hash . '.jpg',
'type' => 'image/jpeg',
- 'not_visible' => true
+ 'visible' => false
)
);
diff --git a/include/ItemObject.php b/include/ItemObject.php
index 0b7b22303..1cb7bf25c 100644
--- a/include/ItemObject.php
+++ b/include/ItemObject.php
@@ -134,6 +134,39 @@ class Item extends BaseObject {
$profile_name = $item['author']['xchan_name'];
$location = format_location($item);
+ $isevent = false;
+ $attend = null;
+ $canvote = false;
+
+ // process action responses - e.g. like/dislike/attend/agree/whatever
+ $response_verbs = array('like');
+ if(feature_enabled($conv->get_profile_owner(),'dislike'))
+ $response_verbs[] = 'dislike';
+ if($item['obj_type'] === ACTIVITY_OBJ_EVENT) {
+ $response_verbs[] = 'attendyes';
+ $response_verbs[] = 'attendno';
+ $response_verbs[] = 'attendmaybe';
+ if($this->is_commentable()) {
+ $isevent = true;
+ $attend = array( t('I will attend'), t('I will not attend'), t('I might attend'));
+ }
+ }
+
+ $consensus = (($item['item_flags'] & ITEM_CONSENSUS) ? true : false);
+ if($consensus) {
+ $response_verbs[] = 'agree';
+ $response_verbs[] = 'disagree';
+ $response_verbs[] = 'abstain';
+ if($this->is_commentable()) {
+ $conlabels = array( t('I agree'), t('I disagree'), t('I abstain'));
+ $canvote = true;
+ }
+ }
+
+ if(! feature_enabled($conv->get_profile_owner(),'dislike'))
+ unset($conv_responses['dislike']);
+
+ $responses = get_responses($conv_responses,$response_verbs,$this,$item);
$like_count = ((x($conv_responses['like'],$item['mid'])) ? $conv_responses['like'][$item['mid']] : '');
$like_list = ((x($conv_responses['like'],$item['mid'])) ? $conv_responses['like'][$item['mid'] . '-l'] : '');
@@ -253,6 +286,11 @@ class Item extends BaseObject {
'body' => $body,
'text' => strip_tags($body),
'id' => $this->get_id(),
+ 'isevent' => $isevent,
+ 'attend' => $attend,
+ 'consensus' => $consensus,
+ 'conlabels' => $conlabels,
+ 'canvote' => $canvote,
'linktitle' => sprintf( t('View %s\'s profile - %s'), $profile_name, $item['author']['xchan_addr']),
'olinktitle' => sprintf( t('View %s\'s profile - %s'), $this->get_owner_name(), $item['owner']['xchan_addr']),
'llink' => $item['llink'],
@@ -271,7 +309,7 @@ class Item extends BaseObject {
'title_tosource' => get_pconfig($conv->get_profile_owner(),'system','title_tosource'),
'ago' => relative_date($item['created']),
'app' => $item['app'],
- 'str_app' => sprintf( t(' from %s'), $item['app']),
+ 'str_app' => sprintf( t('from %s'), $item['app']),
'isotime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'c'),
'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
'editedtime' => (($item['edited'] != $item['created']) ? sprintf( t('last edited: %s'), datetime_convert('UTC', date_default_timezone_get(), $item['edited'], 'r')) : ''),
@@ -307,6 +345,7 @@ class Item extends BaseObject {
'comment_count_txt' => $comment_count_txt,
'list_unseen_txt' => $list_unseen_txt,
'markseen' => t('Mark all seen'),
+ 'responses' => $responses,
'like_count' => $like_count,
'like_list' => $like_list,
'like_list_part' => $like_list_part,
@@ -569,7 +608,7 @@ class Item extends BaseObject {
if((! visible_activity($child->data)) || array_key_exists('author_blocked',$child->data)) {
continue;
}
- if($child->data['item_unseen'])
+ if(intval($child->data['item_unseen']))
$total ++;
}
}
@@ -633,7 +672,7 @@ class Item extends BaseObject {
'$edquote' => t('Quote'),
'$edcode' => t('Code'),
'$edimg' => t('Image'),
- '$edurl' => t('Link'),
+ '$edurl' => t('Insert Link'),
'$edvideo' => t('Video'),
'$preview' => t('Preview'), // ((feature_enabled($conv->get_profile_owner(),'preview')) ? t('Preview') : ''),
'$indent' => $indent,
diff --git a/include/RedDAV/RedBrowser.php b/include/RedDAV/RedBrowser.php
index e651562ec..a0330d7cc 100644
--- a/include/RedDAV/RedBrowser.php
+++ b/include/RedDAV/RedBrowser.php
@@ -95,6 +95,7 @@ class RedBrowser extends DAV\Browser\Plugin {
'{DAV:}getlastmodified',
), 1);
+
$parent = $this->server->tree->getNodeForPath($path);
$parentpath = array();
@@ -167,6 +168,7 @@ class RedBrowser extends DAV\Browser\Plugin {
$fullPath = DAV\URLUtil::encodePath('/' . trim($this->server->getBaseUri() . ($path ? $path . '/' : '') . $name, '/'));
+
$displayName = isset($file[200]['{DAV:}displayname']) ? $file[200]['{DAV:}displayname'] : $name;
$displayName = $this->escapeHTML($displayName);
@@ -269,18 +271,19 @@ class RedBrowser extends DAV\Browser\Plugin {
'$nick' => $this->auth->getCurrentUser()
));
- get_app()->page['content'] = $html;
- load_pdl(get_app());
+ $a = get_app();
+ $a->page['content'] = $html;
+ load_pdl($a);
$theme_info_file = "view/theme/" . current_theme() . "/php/theme.php";
if (file_exists($theme_info_file)){
require_once($theme_info_file);
if (function_exists(str_replace('-', '_', current_theme()) . '_init')) {
$func = str_replace('-', '_', current_theme()) . '_init';
- $func(get_app());
+ $func($a);
}
}
- construct_page(get_app());
+ construct_page($a);
}
/**
diff --git a/include/RedDAV/RedDirectory.php b/include/RedDAV/RedDirectory.php
index 68186d21b..922be378d 100644
--- a/include/RedDAV/RedDirectory.php
+++ b/include/RedDAV/RedDirectory.php
@@ -49,6 +49,7 @@ class RedDirectory extends DAV\Node implements DAV\ICollection, DAV\IQuota {
* @param RedBasicAuth &$auth_plugin
*/
public function __construct($ext_path, &$auth_plugin) {
+// $ext_path = urldecode($ext_path);
//logger('directory ' . $ext_path, LOGGER_DATA);
$this->ext_path = $ext_path;
// remove "/cloud" from the beginning of the path
diff --git a/include/RedDAV/RedFile.php b/include/RedDAV/RedFile.php
index 9ce6490a7..b7aa5473a 100644
--- a/include/RedDAV/RedFile.php
+++ b/include/RedDAV/RedFile.php
@@ -80,7 +80,8 @@ class RedFile extends DAV\Node implements DAV\IFile {
$newName = str_replace('/', '%2F', $newName);
$r = q("UPDATE attach SET filename = '%s' WHERE hash = '%s' AND id = %d",
- dbesc($this->data['filename']),
+ dbesc($newName),
+ dbesc($this->data['hash']),
intval($this->data['id'])
);
}
diff --git a/include/account.php b/include/account.php
index 19c13d5bd..5926e05c1 100644
--- a/include/account.php
+++ b/include/account.php
@@ -1,4 +1,8 @@
-<?php /** @file */
+<?php
+/**
+ * @file include/account.php
+ * @brief Somme account related functions.
+ */
require_once('include/config.php');
require_once('include/network.php');
@@ -43,15 +47,14 @@ function check_account_email($email) {
function check_account_password($password) {
$result = array('error' => 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
@@ -523,9 +522,7 @@ function downgrade_accounts() {
$basic = get_config('system','default_service_class');
-
foreach($r as $rr) {
-
if(($basic) && ($rr['account_service_class']) && ($rr['account_service_class'] != $basic)) {
$x = q("UPDATE account set account_service_class = '%s', account_expires = '%s'
where account_id = %d",
@@ -550,74 +547,98 @@ function downgrade_accounts() {
}
+/**
+ * @brief Check service_class restrictions.
+ *
+ * If there are no service_classes defined, everything is allowed.
+ * If $usage is supplied, we check against a maximum count and return true if
+ * the current usage is less than the subscriber plan allows. Otherwise we
+ * return boolean true or false if the property is allowed (or not) in this
+ * subscriber plan. An unset property for this service plan means the property
+ * is allowed, so it is only necessary to provide negative properties for each
+ * plan, or what the subscriber is not allowed to do.
+ *
+ * Like account_service_class_allows() but queries directly by account rather
+ * than channel. Service classes are set for accounts, so we look up the
+ * account for the channel and fetch the service class restrictions of the
+ * account.
+ *
+ * @see account_service_class_allows() if you have a channel_id already
+ * @see service_class_fetch()
+ *
+ * @param int $uid The channel_id to check
+ * @param string $property The service class property to check for
+ * @param string|boolean $usage (optional) The value to check against
+ * @return boolean
+ */
+function service_class_allows($uid, $property, $usage = false) {
+ $limit = service_class_fetch($uid, $property);
-// check service_class restrictions. If there are no service_classes defined, everything is allowed.
-// if $usage is supplied, we check against a maximum count and return true if the current usage is
-// less than the subscriber plan allows. Otherwise we return boolean true or false if the property
-// is allowed (or not) in this subscriber plan. An unset property for this service plan means
-// the property is allowed, so it is only necessary to provide negative properties for each plan,
-// or what the subscriber is not allowed to do.
-
-
-function service_class_allows($uid,$property,$usage = false) {
- $a = get_app();
- if($uid == local_channel()) {
- $service_class = $a->account['account_service_class'];
- }
- else {
- $r = q("select account_service_class as service_class
- from channel c, account a
- where c.channel_account_id=a.account_id and c.channel_id= %d limit 1",
- intval($uid)
- );
- if($r !== false and count($r)) {
- $service_class = $r[0]['service_class'];
- }
- }
- if(! x($service_class))
- return true; // everything is allowed
-
- $arr = get_config('service_class',$service_class);
- if(! is_array($arr) || (! count($arr)))
- return true;
+ if($limit === false)
+ return true; // No service class set => everything is allowed
- if($usage === false)
- return ((x($arr[$property])) ? (bool) $arr[$property] : true);
- else {
- if(! array_key_exists($property,$arr))
- return true;
- return (((intval($usage)) < intval($arr[$property])) ? true : false);
+ if($usage === false) {
+ // We use negative values for not allowed properties in a subscriber plan
+ return ((x($limit)) ? (bool) $limit : true);
+ } else {
+ return (((intval($usage)) < intval($limit)) ? true : false);
}
}
-// like service_class_allows but queries by account rather than channel
-function account_service_class_allows($aid,$property,$usage = false) {
- $a = get_app();
- $r = q("select account_service_class as service_class from account where account_id = %d limit 1",
- intval($aid)
- );
- if($r !== false and count($r)) {
- $service_class = $r[0]['service_class'];
- }
+/**
+ * @brief Check service class restrictions by account.
+ *
+ * If there are no service_classes defined, everything is allowed.
+ * If $usage is supplied, we check against a maximum count and return true if
+ * the current usage is less than the subscriber plan allows. Otherwise we
+ * return boolean true or false if the property is allowed (or not) in this
+ * subscriber plan. An unset property for this service plan means the property
+ * is allowed, so it is only necessary to provide negative properties for each
+ * plan, or what the subscriber is not allowed to do.
+ *
+ * Like service_class_allows() but queries directly by account rather than channel.
+ *
+ * @see service_class_allows() if you have a channel_id instead of an account_id
+ * @see account_service_class_fetch()
+ *
+ * @param int $aid The account_id to check
+ * @param string $property The service class property to check for
+ * @param int|boolean $usage (optional) The value to check against
+ * @return boolean
+ */
+function account_service_class_allows($aid, $property, $usage = false) {
- if(! x($service_class))
- return true; // everything is allowed
+ $limit = account_service_class_fetch($aid, $property);
- $arr = get_config('service_class',$service_class);
- if(! is_array($arr) || (! count($arr)))
- return true;
+ if($limit === false)
+ return true; // No service class is set => everything is allowed
- if($usage === false)
- return ((x($arr[$property])) ? (bool) $arr[$property] : true);
- else {
- if(! array_key_exists($property,$arr))
- return true;
- return (((intval($usage)) < intval($arr[$property])) ? true : false);
+ if($usage === false) {
+ // We use negative values for not allowed properties in a subscriber plan
+ return ((x($limit)) ? (bool) $limit : true);
+ } else {
+ return (((intval($usage)) < intval($limit)) ? true : false);
}
}
-
-function service_class_fetch($uid,$property) {
+/**
+ * @brief Queries a service class value for a channel and property.
+ *
+ * Service classes are set for accounts, so look up the account for this channel
+ * and fetch the service classe of the account.
+ *
+ * If no service class is available it returns false and everything should be
+ * allowed.
+ *
+ * @see account_service_class_fetch()
+ *
+ * @param int $uid The channel_id to query
+ * @param string $property The service property name to check for
+ * @return boolean|int
+ *
+ * @todo Should we merge this with account_service_class_fetch()?
+ */
+function service_class_fetch($uid, $property) {
$a = get_app();
if($uid == local_channel()) {
$service_class = $a->account['account_service_class'];
@@ -635,17 +656,27 @@ function service_class_fetch($uid,$property) {
if(! x($service_class))
return false; // everything is allowed
- $arr = get_config('service_class',$service_class);
+ $arr = get_config('service_class', $service_class);
if(! is_array($arr) || (! count($arr)))
return false;
- return((array_key_exists($property,$arr)) ? $arr[$property] : false);
+ return((array_key_exists($property, $arr)) ? $arr[$property] : false);
}
-// like service_class_fetch but queries by account rather than channel
-
-function account_service_class_fetch($aid,$property) {
+/**
+ * @brief Queries a service class value for an account and property.
+ *
+ * Like service_class_fetch() but queries by account rather than channel.
+ *
+ * @see service_class_fetch() if you have channel_id.
+ * @see account_service_class_allows()
+ *
+ * @param int $aid The account_id to query
+ * @param string $property The service property name to check for
+ * @return boolean|int
+ */
+function account_service_class_fetch($aid, $property) {
$r = q("select account_service_class as service_class from account where account_id = %d limit 1",
intval($aid)
@@ -657,17 +688,17 @@ function account_service_class_fetch($aid,$property) {
if(! x($service_class))
return false; // everything is allowed
- $arr = get_config('service_class',$service_class);
+ $arr = get_config('service_class', $service_class);
if(! is_array($arr) || (! count($arr)))
return false;
- return((array_key_exists($property,$arr)) ? $arr[$property] : false);
+ return((array_key_exists($property, $arr)) ? $arr[$property] : false);
}
function upgrade_link($bbcode = false) {
- $l = get_config('service_class','upgrade_link');
+ $l = get_config('service_class', 'upgrade_link');
if(! $l)
return '';
if($bbcode)
@@ -685,4 +716,4 @@ function upgrade_message($bbcode = false) {
function upgrade_bool_message($bbcode = false) {
$x = upgrade_link($bbcode);
return t('This action is not available under your subscription plan.') . (($x) ? ' ' . $x : '') ;
-}
+} \ No newline at end of file
diff --git a/include/api.php b/include/api.php
index 565f634ef..bc1fa53b9 100644
--- a/include/api.php
+++ b/include/api.php
@@ -267,40 +267,46 @@ require_once('include/items.php');
* Returns user info array.
*/
- function api_get_user(&$a, $contact_id = Null){
+ function api_get_user(&$a, $contact_id = null, $contact_xchan = null){
global $called_api;
$user = null;
$extra_query = "";
- if(!is_null($contact_id)){
- $user=$contact_id;
- $extra_query = " AND abook_id = %d ";
- }
-
- if(is_null($user) && x($_GET, 'user_id')) {
- $user = intval($_GET['user_id']);
- $extra_query = " AND abook_id = %d ";
- }
- if(is_null($user) && x($_GET, 'screen_name')) {
- $user = dbesc($_GET['screen_name']);
- $extra_query = " AND xchan_addr like '%s@%%' ";
- if (api_user()!==false)
- $extra_query .= " AND abook_channel = ".intval(api_user());
+ if(! is_null($contact_xchan)) {
+ $user = local_channel();
+ $extra_query = " and abook_xchan = '" . dbesc($contact_xchan) . "' ";
}
+ else {
+ if(!is_null($contact_id)){
+ $user=$contact_id;
+ $extra_query = " AND abook_id = %d ";
+ }
- if (is_null($user) && argc() > (count($called_api)-1)){
- $argid = count($called_api);
- list($user, $null) = explode(".",argv($argid));
- if(is_numeric($user)){
- $user = intval($user);
+ if(is_null($user) && x($_GET, 'user_id')) {
+ $user = intval($_GET['user_id']);
$extra_query = " AND abook_id = %d ";
- } else {
- $user = dbesc($user);
+ }
+ if(is_null($user) && x($_GET, 'screen_name')) {
+ $user = dbesc($_GET['screen_name']);
$extra_query = " AND xchan_addr like '%s@%%' ";
- if (api_user() !== false)
+ if (api_user()!==false)
$extra_query .= " AND abook_channel = ".intval(api_user());
}
+
+ if (is_null($user) && argc() > (count($called_api)-1) && (strstr($a->cmd,'/users'))){
+ $argid = count($called_api);
+ list($xx, $null) = explode(".",argv($argid));
+ if(is_numeric($xx)){
+ $user = intval($xx);
+ $extra_query = " AND abook_id = %d ";
+ } else {
+ $user = dbesc($xx);
+ $extra_query = " AND xchan_addr like '%s@%%' ";
+ if (api_user() !== false)
+ $extra_query .= " AND abook_channel = ".intval(api_user());
+ }
+ }
}
if (! $user) {
@@ -316,11 +322,13 @@ require_once('include/items.php');
logger('api_user: ' . $extra_query . ', user: ' . $user);
// user info
+
$uinfo = q("SELECT * from abook left join xchan on abook_xchan = xchan_hash
WHERE 1
$extra_query",
$user
);
+
if (count($uinfo)==0) {
return False;
}
@@ -392,7 +400,7 @@ require_once('include/items.php');
'utc_offset' => "+00:00",
'time_zone' => 'UTC', //$uinfo[0]['timezone'],
'geo_enabled' => false,
- 'statuses_count' => intval($countitms), #XXX: fix me
+ 'statuses_count' => intval($countitms), //#XXX: fix me
'lang' => get_app()->language,
'description' => (($profile) ? $profile[0]['pdesc'] : ''),
'followers_count' => intval($countfollowers),
@@ -408,11 +416,16 @@ require_once('include/items.php');
'profile_background_tile' => false,
'profile_use_background_image' => false,
'notifications' => false,
- 'following' => '', #XXX: fix me
- 'verified' => true, #XXX: fix me
- 'status' => array()
+ 'following' => '', // #XXX: fix me
+ 'verified' => true // #XXX: fix me
);
-
+
+ $x = api_get_status($uinfo[0]['xchan_hash']);
+ if($x)
+ $ret['status'] = $x;
+
+// logger('api_get_user: ' . print_r($ret,true));
+
return $ret;
}
@@ -444,12 +457,12 @@ require_once('include/items.php');
'description' => '',
'profile_image_url' => $item['author']['xchan_photo_m'],
'url' => $item['author']['xchan_url'],
- 'protected' => false, #
+ 'protected' => false,
'followers_count' => 0,
'friends_count' => 0,
'created_at' => '',
'favourites_count' => 0,
- 'utc_offset' => 0, #XXX: fix me
+ 'utc_offset' => 0, // #XXX: fix me
'time_zone' => '', //$uinfo[0]['timezone'],
'statuses_count' => 0,
'following' => 1,
@@ -458,7 +471,7 @@ require_once('include/items.php');
'uid' => 0,
'contact_url' => 0,
'geo_enabled' => false,
- 'lang' => 'en', #XXX: fix me
+ 'lang' => 'en', // #XXX: fix me
'contributors_enabled' => false,
'follow_request_sent' => false,
'profile_background_color' => 'cfe8f6',
@@ -469,9 +482,8 @@ require_once('include/items.php');
'profile_background_image_url' => '',
'profile_background_tile' => false,
'profile_use_background_image' => false,
- 'verified' => true, #XXX: fix me
- 'followers' => '', #XXX: fix me
- 'status' => array()
+ 'verified' => true, // #XXX: fix me
+ 'followers' => '' // #XXX: fix me
);
return $ret;
@@ -620,10 +632,14 @@ require_once('include/items.php');
function api_red_xchan(&$a,$type) {
+ logger('api_xchan');
+
if(api_user() === false)
return false;
+ logger('api_xchan');
require_once('include/hubloc.php');
- if($_SERVER['request_method'] === 'POST') {
+
+ if($_SERVER['REQUEST_METHOD'] === 'POST') {
$r = xchan_store($_REQUEST);
}
$r = xchan_fetch($_REQUEST);
@@ -661,8 +677,9 @@ require_once('include/items.php');
$a->argv[1] = $user_info['screen_name'];
$_REQUEST['silent']='1'; //tell wall_upload function to return img info instead of echo
- require_once('mod/wall_upload.php');
- $posted = wall_upload_post($a);
+ $_FILES['userfile'] = $_FILES['media'];
+ require_once('mod/wall_attach.php');
+ $posted = wall_attach_post($a);
//now that we have the img url in bbcode we can add it to the status and insert the wall item.
$_REQUEST['body']=$txt."\n\n".$posted;
@@ -725,6 +742,16 @@ require_once('include/items.php');
else
$_REQUEST['parent_mid'] = $parent;
+ if($_REQUEST['namespace'] && $parent) {
+ $x = q("select iid from item_id where service = '%s' and sid = '%s' limit 1",
+ dbesc($_REQUEST['namespace']),
+ dbesc($parent)
+ );
+ if($x) {
+ $_REQUEST['parent'] = $x[0]['iid'];
+ }
+ }
+
if(requestdata('lat') && requestdata('long'))
$_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
@@ -739,8 +766,8 @@ require_once('include/items.php');
$_FILES['userfile'] = $_FILES['media'];
// upload the image if we have one
$_REQUEST['silent']='1'; //tell wall_upload function to return img info instead of echo
- require_once('mod/wall_upload.php');
- $media = wall_upload_post($a);
+ require_once('mod/wall_attach.php');
+ $media = wall_attach_post($a);
if(strlen($media)>0)
$_REQUEST['body'] .= "\n\n".$media;
}
@@ -791,13 +818,65 @@ require_once('include/items.php');
api_register_func('api/red/item/new','red_item_new', true);
+ function api_get_status($xchan_hash) {
+ require_once('include/security.php');
+ $lastwall = q("SELECT * from item where
+ item_private = 0 and item_restrict = 0
+ and author_xchan = '%s'
+ and allow_cid = '' and allow_gid = '' and deny_cid = '' and deny_gid = ''
+ and verb = '%s'
+ order by created desc limit 1",
+ dbesc($xchan_hash),
+ dbesc(ACTIVITY_POST)
+ );
+ if($lastwall){
+ $lastwall = $lastwall[0];
+
+ $in_reply_to_status_id = '';
+ $in_reply_to_user_id = '';
+ $in_reply_to_screen_name = '';
+ if($lastwall['author_xchan'] != $lastwall['owner_xchan']) {
+ $w = q("select * from abook left join xchan on abook_xchan = xchan_hash where
+ xchan_hash = '%s' limit 1",
+ dbesc($lastwall['owner_xchan'])
+ );
+ if($w) {
+ $in_reply_to_user_id = $w[0]['abook_id'];
+ $in_reply_to_screen_name = substr($w[0]['xchan_addr'],0,strpos($w[0]['xchan_addr'],'@'));
+ }
+ }
+
+ if ($lastwall['parent']!=$lastwall['id']) {
+ $in_reply_to_status_id=$lastwall['thr_parent'];
+ if(! $in_reply_to_user_id) {
+ $in_reply_to_user_id = $user_info['id'];
+ $in_reply_to_screen_name = $user_info['screen_name'];
+ }
+ }
+ unobscure($lastwall);
+ $status_info = array(
+ 'text' => html2plain(prepare_text($lastwall['body'],$lastwall['mimetype']), 0),
+ 'truncated' => false,
+ 'created_at' => api_date($lastwall['created']),
+ 'in_reply_to_status_id' => $in_reply_to_status_id,
+ 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
+ 'id' => ($lastwall['id']),
+ 'in_reply_to_user_id' => $in_reply_to_user_id,
+ 'in_reply_to_screen_name' => $in_reply_to_screen_name,
+ 'geo' => '',
+ 'favorited' => false,
+ 'coordinates' => $lastwall['coord'],
+ 'place' => $lastwall['location'],
+ 'contributors' => ''
+ );
-
-
-
+ }
+
+ return $status_info;
+ }
function api_status_show(&$a, $type){
$user_info = api_get_user($a);
@@ -806,12 +885,11 @@ require_once('include/items.php');
require_once('include/security.php');
- $lastwall = q("SELECT * from item where 1
- and item_private = 0 and item_restrict = 0
+ $lastwall = q("SELECT * from item where
+ item_private = 0 and item_restrict = 0
and author_xchan = '%s'
and allow_cid = '' and allow_gid = '' and deny_cid = '' and deny_gid = ''
and verb = '%s'
- and uid in ( " . stream_perms_api_uids() . " )
order by created desc limit 1",
dbesc($user_info['guid']),
dbesc(ACTIVITY_POST)
@@ -885,7 +963,6 @@ require_once('include/items.php');
and author_xchan = '%s'
and allow_cid = '' and allow_gid = '' and deny_cid = '' and deny_gid = ''
and verb = '%s'
- and uid in ( " . stream_perms_api_uids() . " )
order by created desc limit 1",
dbesc($user_info['guid']),
dbesc(ACTIVITY_POST)
@@ -1031,8 +1108,8 @@ require_once('include/items.php');
if (api_user()===false) return false;
$user_info = api_get_user($a);
- // get last newtork messages
+ $sys = get_sys_channel();
// params
$count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
@@ -1054,7 +1131,7 @@ require_once('include/items.php');
and allow_cid = '' and allow_gid = ''
and deny_cid = '' and deny_gid = ''
and item_private = 0
- and uid in ( " . stream_perms_api_uids() . " )
+ and uid = " . $sys['channel_id'] . "
$sql_extra
AND id > %d group by mid
order by received desc LIMIT %d OFFSET %d ",
@@ -1401,58 +1478,155 @@ require_once('include/items.php');
api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
+
+ /**
+ * Star/unstar an item
+ * param: id : id of the item
+ *
+ * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
+ */
+ function api_favorites_create_destroy(&$a, $type){
+
+ logger('favorites_create_destroy');
+
+ if (api_user()===false)
+ return false;
+
+ $action = str_replace(".".$type,"",argv(2));
+ if (argc() > 3) {
+ $itemid = intval(argv(3));
+ } else {
+ $itemid = intval($_REQUEST['id']);
+ }
+
+ $item = q("SELECT * FROM item WHERE id = %d AND uid = %d",
+ intval($itemid),
+ intval(api_user())
+ );
+
+ if (! $item)
+ return false;
+
+ switch($action){
+ case "create":
+
+ $flags = $item[0]['item_flags'] | ITEM_STARRED;
+
+ break;
+ case "destroy":
+
+ $flags = $item[0]['item_flags'] | (~ ITEM_STARRED);
+ break;
+ default:
+ return false;
+ }
+
+ $r = q("UPDATE item SET item_flags = %d where id = %d and uid = %d",
+ intval($flags),
+ intval($itemid),
+ intval(api_user())
+ );
+ if(! $r)
+ return false;
+
+ $item = q("SELECT * FROM item WHERE id = %d AND uid = %d",
+ intval($itemid),
+ intval(api_user())
+ );
+
+ xchan_query($item,true);
+
+
+ $user_info = api_get_user($a);
+ $rets = api_format_items($item,$user_info);
+ $ret = $rets[0];
+
+ $data = array('$status' => $ret);
+ switch($type){
+ case "atom":
+ case "rss":
+ $data = api_rss_extra($a, $data, $user_info);
+ }
+
+ return api_apply_template("status", $type, $data);
+ }
+
+ api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
+ api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
+
+
+
function api_favorites(&$a, $type){
- if (api_user()===false) return false;
+ if (api_user()===false)
+ return false;
$user_info = api_get_user($a);
- // in friendica starred item are private
- // return favorites only for self
- logger('api_favorites: self:' . $user_info['self']);
- if ($user_info['self']==0) {
- $ret = array();
- } else {
+ // params
+ $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
+ $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
+ if($page < 0)
+ $page = 0;
+ $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
+ $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
+ $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
+ $start = $page*$count;
- // params
- $count = (x($_GET,'count')?$_GET['count']:20);
- $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
- if ($page<0) $page=0;
-
- $start = $page*$count;
-
- $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
- `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
- `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn_id`, `contact`.`self`,
- `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
- FROM `item`, `contact`
- WHERE `item`.`uid` = %d
- AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
- AND `item`.`starred` = 1
- AND `contact`.`id` = `item`.`contact-id`
- AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
- $sql_extra
- ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
- intval($user_info['uid']),
- intval($start), intval($count)
- );
+ //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
- $ret = api_format_items($r,$user_info);
+ $sql_extra = '';
+ if ($max_id > 0)
+ $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
+ if ($exclude_replies > 0)
+ $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
+ if (api_user() != $user_info['uid']) {
+ $observer = get_app()->get_observer();
+ require_once('include/permissions.php');
+ if(! perm_is_allowed($user_info['uid'],(($observer) ? $observer['xchan_hash'] : ''),'view_stream'))
+ return '';
+ $sql_extra .= " and item_private = 0 ";
}
+ $r = q("SELECT * from item WHERE uid = %d and item_restrict = 0
+ and ( item_flags & %d ) > 0 $sql_extra
+ AND id > %d
+ ORDER BY received DESC LIMIT %d ,%d ",
+ intval($user_info['uid']),
+ intval(ITEM_STARRED),
+ intval($since_id),
+ intval($start),
+ intval($count)
+ );
+
+ xchan_query($r,true);
+
+ $ret = api_format_items($r,$user_info);
+
$data = array('$statuses' => $ret);
switch($type){
case "atom":
case "rss":
$data = api_rss_extra($a, $data, $user_info);
+ break;
+ case "as":
+ $as = api_format_as($a, $ret, $user_info);
+ $as['title'] = $a->config['sitename']." Home Timeline";
+ $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
+ return($as);
+ break;
}
return api_apply_template("timeline", $type, $data);
+
}
api_register_func('api/favorites','api_favorites', true);
+
+
+
function api_format_as($a, $ret, $user_info) {
$as = array();
@@ -1518,7 +1692,7 @@ require_once('include/items.php');
return($as);
}
- function api_format_messages($item, $recipient, $sender) {
+ function api_format_message($item, $recipient, $sender) {
// standard meta information
$ret = array(
'id' => $item['id'],
@@ -1530,7 +1704,7 @@ require_once('include/items.php');
'recipient_screen_name' => $recipient['screen_name'],
'recipient' => $recipient,
);
- unobscure($item);
+ unobscure_mail($item);
//don't send title to regular StatusNET requests to avoid confusing these apps
if (x($_GET, 'getText')) {
$ret['title'] = $item['title'] ;
@@ -1568,6 +1742,8 @@ require_once('include/items.php');
localize_item($item);
$status_user = (($item['author_xchan']==$user_info['guid'])?$user_info: api_item_get_user($a,$item));
+ if(array_key_exists('status',$status_user))
+ unset($status_user['status']);
if($item['parent'] != $item['id']) {
$r = q("select id from item where parent= %d and id < %d order by id desc limit 1",
@@ -1893,7 +2069,7 @@ require_once('include/items.php');
if ($id>-1) {
$r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
- $ret = api_format_messages($r[0], $recipient, $sender);
+ $ret = api_format_message($r[0], $recipient, $sender);
} else {
$ret = array("error"=>$id);
@@ -1947,18 +2123,16 @@ require_once('include/items.php');
$ret = Array();
if($r) {
foreach($r as $item) {
- if ($box == "inbox" || $item['from-url'] != $profile_url){
- $recipient = $user_info;
- // fixme to lookup recipient
- $sender = api_get_user($a);
- }
- elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
- // fixme to lookup recipient
- $recipient = api_get_user($a);
+ if ($item['from_xchan'] == $channel['channel_hash']) {
$sender = $user_info;
+ $recipient = api_get_user($a, null, $item['to_xchan']);
+ }
+ else {
+ $sender = api_get_user($a, null, $item['from_xchan']);
+ $recipient = $user_info;
}
- $ret[]=api_format_messages($item, $recipient, $sender);
+ $ret[]=api_format_message($item, $recipient, $sender);
}
}
@@ -2024,9 +2198,6 @@ logger('Req: ' . var_export($req,true));
/*
Not implemented by now:
-favorites
-favorites/create
-favorites/destroy
statuses/retweets_of_me
friendships/create
friendships/destroy
diff --git a/include/attach.php b/include/attach.php
index cd8fe4f06..122f374b0 100644
--- a/include/attach.php
+++ b/include/attach.php
@@ -1,10 +1,10 @@
<?php
-
-/** @file
+/**
+ * @file include/attach.php
*
* @brief File/attach API with the potential for revision control.
*
- * TODO: a filesystem storage abstraction which maintains security (and 'data' contains a system filename
+ * @TODO: a filesystem storage abstraction which maintains security (and 'data' contains a system filename
* which is inaccessible from the web). This could get around PHP storage limits and store videos and larger
* items, using fread or OS methods or native code to read/write or chunk it through.
* Also an 'append' option to the storage function might be a useful addition.
@@ -15,10 +15,10 @@ require_once('include/security.php');
/**
* @brief Guess the mimetype from file ending.
- *
+ *
* This function takes a file name and guess the mimetype from the
* filename extension.
- *
+ *
* @param $filename a string filename
* @return string The mimetype according to a file ending.
*/
@@ -65,10 +65,10 @@ function z_mime_content_type($filename) {
'mov' => 'video/quicktime',
'ogg' => 'application/ogg',
'opus' => 'audio/ogg',
- 'webm' => 'audio/webm',
'webm' => 'video/webm',
- 'mp4' => 'audio/mp4',
+// 'webm' => 'audio/webm',
'mp4' => 'video/mp4',
+// 'mp4' => 'audio/mp4',
// adobe
'pdf' => 'application/pdf',
@@ -117,23 +117,22 @@ function z_mime_content_type($filename) {
/**
* @brief Count files/attachments.
- *
- *
- * @param $channel_id
- * @param $observer
- * @param $hash (optional)
- * @param $filename (optional)
- * @param $filetype (optional)
- * @return array
- * $ret['success'] boolean
- * $ret['results'] amount of found results, or false
- * $ret['message'] string with error messages if any
+ *
+ * @param int $channel_id
+ * @param string $observer
+ * @param string $hash (optional)
+ * @param string $filename (optional)
+ * @param string $filetype (optional)
+ * @return assoziative array with:
+ * * \e boolean \b success
+ * * \e int|boolean \b results amount of found results, or false
+ * * \e string \b message with error messages if any
*/
function attach_count_files($channel_id, $observer, $hash = '', $filename = '', $filetype = '') {
$ret = array('success' => 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,12 +269,16 @@ 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 $ref
+ * @param $rev revision default 0
+ * @return array Everything except data.
+ * * \e boolean \b success boolean true or false
+ * * \e string \b message (optional) only when success is false
+ * * \e array \b data array of attach DB entry without data component
*/
function attach_by_hash_nodata($hash, $rev = 0) {
@@ -318,6 +321,7 @@ function attach_by_hash_nodata($hash, $rev = 0) {
$ret['success'] = true;
$ret['data'] = $r[0];
+
return $ret;
}
@@ -361,6 +365,7 @@ function attach_store($channel, $observer_hash, $options = '', $arr = null) {
$existing_size = 0;
if($options === 'replace') {
+ /** @BUG $replace is undefined here */
$x = q("select id, hash, filesize from attach where id = %d and uid = %d limit 1",
intval($replace),
intval($channel_id)
@@ -373,7 +378,7 @@ function attach_store($channel, $observer_hash, $options = '', $arr = null) {
$existing_size = intval($x[0]['filesize']);
$hash = $x[0]['hash'];
}
-
+
if($options === 'revise' || $options === 'update') {
$sql_options = " order by revision desc ";
if($options === 'update' && $arr && array_key_exists('revision',$arr))
@@ -513,22 +518,24 @@ function attach_store($channel, $observer_hash, $options = '', $arr = null) {
}
/**
- * Read a virtual directory and return contents, checking permissions of all parent components.
- * @function z_readdir
+ * @brief Read a virtual directory and return contents.
+ *
+ * Also checking permissions of all parent components.
+ *
* @param integer $channel_id
* @param string $observer_hash hash of current observer
* @param string $pathname
* @param string $parent_hash (optional)
*
- * @returns array $ret
- * $ret['success'] = boolean true or false
- * $ret['message'] = error message if success is false
- * $ret['data'] = array of attach DB entries without data component
+ * @return array $ret
+ * * \e boolean \b success boolean true or false
+ * * \e string \b message error message if success is false
+ * * \e array \b data array of attach DB entries without data component
*/
function z_readdir($channel_id, $observer_hash, $pathname, $parent_hash = '') {
$ret = array('success' => false);
- if(! perm_is_allowed($r[0]['uid'], get_observer_hash(), 'view_storage')) {
+ if(! perm_is_allowed($channel_id, get_observer_hash(), 'view_storage')) {
$ret['message'] = t('Permission denied.');
return $ret;
}
@@ -553,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),
@@ -571,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);
@@ -698,7 +703,7 @@ function attach_mkdir($channel, $observer_hash, $arr = null) {
);
}
else {
- logger('attach_mkdir: ' . mkdir . ' ' . $path . 'failed.');
+ logger('attach_mkdir: ' . mkdir . ' ' . $path . ' failed.');
$ret['message'] = t('mkdir failed.');
}
}
@@ -712,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) {
@@ -807,8 +812,8 @@ function attach_delete($channel_id, $resource) {
if($y) {
$f = 'store/' . $channel_address . '/' . $y[0]['data'];
- if(is_dir($f))
- @rmdir($f);
+ if(is_dir($y[0]['data']))
+ @rmdir($y[0]['data']);
elseif(file_exists($f))
unlink($f);
}
@@ -827,18 +832,19 @@ function attach_delete($channel_id, $resource) {
intval($channel_id)
);
- file_activity($channel_id, $object, $allow_cid='', $allow_gid='', $deny_cid='', $deny_gid='', 'update', $no_activity=false);
-
+ file_activity($channel_id, $object, $object['allow_cid'], $object['allow_gid'], $object['deny_cid'], $object['deny_gid'], 'update', $notify=0);
}
/**
* @brief Returns path to file in cloud/.
- * This function cannot be used with mod/dav as it always returns a path valid under mod/cloud
- *
- * @param array
- * $arr[uid] int the channels uid
- * $arr[folder] string
- * $arr[filename]] string
+ *
+ * @warning This function cannot be used with mod/dav as it always returns a
+ * path valid under mod/cloud.
+ *
+ * @param array $arr assoziative array with:
+ * * \e int \b uid the channel's uid
+ * * \e string \b folder
+ * * \e string \b filename
* @return string
* path to the file in cloud/
*/
@@ -895,6 +901,7 @@ function get_cloudpath($arr) {
* @return string with the full folder path
*/
function get_parent_cloudpath($channel_id, $channel_name, $attachHash) {
+ $parentFullPath = '';
// build directory tree
$parentHash = $attachHash;
do {
@@ -933,9 +940,9 @@ function find_folder_hash_by_attach_hash($channel_id, $attachHash) {
/**
* @brief Returns the filename of an attachment in a given channel.
*
- * @param mixed $channel_id
+ * @param int $channel_id
* The id of the channel
- * @param mixed $attachHash
+ * @param string $attachHash
* The hash of the attachment
* @return string
* The filename of the attachment
@@ -949,6 +956,7 @@ function find_filename_by_hash($channel_id, $attachHash) {
if ($r) {
$filename = $r[0]['filename'];
}
+
return $filename;
}
@@ -961,10 +969,23 @@ function pipe_streams($in, $out) {
$size = 0;
while (!feof($in))
$size += fwrite($out, fread($in, 8192));
+
return $size;
}
-function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $verb, $no_activity) {
+/**
+ * @brief Activity for files.
+ *
+ * @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, $notify) {
require_once('include/items.php');
@@ -974,6 +995,15 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid,
if(!$object)
return;
+ //turn strings into arrays
+ $arr_allow_cid = expand_acl($allow_cid);
+ $arr_allow_gid = expand_acl($allow_gid);
+ $arr_deny_cid = expand_acl($deny_cid);
+ $arr_deny_gid = expand_acl($deny_gid);
+
+ //filter out receivers which do not have permission to view filestorage
+ $arr_allow_cid = check_list_permissions($channel_id, $arr_allow_cid, 'view_storage');
+
$is_dir = (($object['flags'] & ATTACH_FLAG_DIR) ? true : false);
//do not send activity for folders for now
@@ -985,13 +1015,16 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid,
$folder_hash = $object['folder'];
- $r_perms = recursive_activity_recipients($allow_cid, $allow_gid, $deny_cid, $deny_gid, $folder_hash);
+ $r_perms = recursive_activity_recipients($arr_allow_cid, $arr_allow_gid, $arr_deny_cid, $arr_deny_gid, $folder_hash);
- $allow_cid = perms2str($r_perms['allow_cid']);
- $allow_gid = perms2str($r_perms['allow_gid']);
- $deny_cid = perms2str($r_perms['deny_cid']);
- $deny_gid = perms2str($r_perms['deny_gid']);
+ //split up returned perms
+ $arr_allow_cid = $r_perms['allow_cid'];
+ $arr_allow_gid = $r_perms['allow_gid'];
+ $arr_deny_cid = $r_perms['deny_cid'];
+ $arr_deny_gid = $r_perms['deny_gid'];
+ //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();
@@ -1004,13 +1037,12 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid,
$objtype = ACTIVITY_OBJ_FILE;
-
- $private = (($allow_cid || $allow_gid || $deny_cid || $deny_gid) ? 1 : 0);
+ $private = (($arr_allow_cid[0] || $arr_allow_gid[0] || $arr_deny_cid[0] || $arr_deny_gid[0]) ? 1 : 0);
$jsonobject = json_encode($object);
//check if item for this object exists
- $y = q("SELECT * FROM item WHERE verb = '%s' AND obj_type = '%s' AND resource_id = '%s' AND uid = %d LIMIT 1",
+ $y = q("SELECT mid FROM item WHERE verb = '%s' AND obj_type = '%s' AND resource_id = '%s' AND uid = %d LIMIT 1",
dbesc(ACTIVITY_POST),
dbesc($objtype),
dbesc($object['hash']),
@@ -1034,6 +1066,12 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid,
if($update && $verb == 'post' ) {
//send update activity and create a new one
+ //updates should be sent to everybody with recursive perms and all eventual former allowed members ($object['allow_cid'] etc.).
+ $u_arr_allow_cid = array_unique(array_merge($arr_allow_cid, expand_acl($object['allow_cid'])));
+ $u_arr_allow_gid = array_unique(array_merge($arr_allow_gid, expand_acl($object['allow_gid'])));
+ $u_arr_deny_cid = array_unique(array_merge($arr_deny_cid, expand_acl($object['deny_cid'])));
+ $u_arr_deny_gid = array_unique(array_merge($arr_deny_gid, expand_acl($object['deny_gid'])));
+
$u_mid = item_message_id();
$arr['aid'] = get_account_id();
@@ -1068,10 +1106,9 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid,
$update = false;
//notice( t('File activity updated') . EOL);
-
}
- if($no_activity) {
+ if(! $notify) {
return;
}
@@ -1087,10 +1124,10 @@ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid,
$arr['author_xchan'] = $poster['xchan_hash'];
$arr['owner_xchan'] = $poster['xchan_hash'];
$arr['title'] = '';
- $arr['allow_cid'] = $allow_cid;
- $arr['allow_gid'] = $allow_gid;
- $arr['deny_cid'] = $deny_cid;
- $arr['deny_gid'] = $deny_gid;
+ $arr['allow_cid'] = perms2str($arr_allow_cid);
+ $arr['allow_gid'] = perms2str($arr_allow_gid);
+ $arr['deny_cid'] = perms2str($arr_deny_cid);
+ $arr['deny_gid'] = perms2str($arr_deny_gid);
$arr['item_hidden'] = 1;
$arr['item_private'] = $private;
$arr['verb'] = (($update) ? ACTIVITY_UPDATE : ACTIVITY_POST);
@@ -1112,12 +1149,18 @@ 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 int $channel_id
+ * @param string $hash
+ * @param string $cloudpath
+ */
function get_file_activity_object($channel_id, $hash, $cloudpath) {
- $x = q("SELECT creator, filename, filetype, filesize, revision, folder, flags, created, edited FROM attach WHERE uid = %d AND hash = '%s' LIMIT 1",
+ $x = q("SELECT creator, filename, filetype, filesize, revision, folder, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid FROM attach WHERE uid = %d AND hash = '%s' LIMIT 1",
intval($channel_id),
dbesc($hash)
);
@@ -1146,20 +1189,36 @@ function get_file_activity_object($channel_id, $hash, $cloudpath) {
'folder' => $x[0]['folder'],
'flags' => $x[0]['flags'],
'created' => $x[0]['created'],
- 'edited' => $x[0]['edited']
+ 'edited' => $x[0]['edited'],
+ 'allow_cid' => $x[0]['allow_cid'],
+ 'allow_gid' => $x[0]['allow_gid'],
+ 'deny_cid' => $x[0]['deny_cid'],
+ 'deny_gid' => $x[0]['deny_gid']
);
- return $object;
+ return $object;
}
-function recursive_activity_recipients($allow_cid, $allow_gid, $deny_cid, $deny_gid, $folder_hash) {
+/**
+ * @brief Returns array of channels which have recursive permission for a file
+ *
+ * @param $arr_allow_cid
+ * @param $arr_allow_gid
+ * @param $arr_deny_cid
+ * @param $arr_deny_gid
+ * @param $folder_hash
+ */
+function recursive_activity_recipients($arr_allow_cid, $arr_allow_gid, $arr_deny_cid, $arr_deny_gid, $folder_hash) {
+ $ret = array();
+ $parent_arr = array();
$poster = get_app()->get_observer();
- $arr_allow_cid = expand_acl($allow_cid);
- $arr_allow_gid = expand_acl($allow_gid);
- $arr_deny_cid = expand_acl($deny_cid);
- $arr_deny_gid = expand_acl($deny_gid);
+ //turn allow_gid into allow_cid's
+ foreach($arr_allow_gid as $gid) {
+ $in_group = in_group($gid);
+ $arr_allow_cid = array_unique(array_merge($arr_allow_cid, $in_group));
+ }
$count = 0;
while($folder_hash) {
@@ -1173,8 +1232,10 @@ function recursive_activity_recipients($allow_cid, $allow_gid, $deny_cid, $deny_
$parent_arr['allow_cid'][] = expand_acl($x[0]['allow_cid']);
$parent_arr['allow_gid'][] = expand_acl($x[0]['allow_gid']);
- //TODO: should find a much better solution for the allow_cid <-> allow_gid problem.
- //Do not use allow_gid for now. Instead lookup the members of the group directly and add them to allow_cid.
+ /**
+ * @TODO should find a much better solution for the allow_cid <-> allow_gid problem.
+ * Do not use allow_gid for now. Instead lookup the members of the group directly and add them to allow_cid.
+ * */
if($parent_arr['allow_gid']) {
foreach($parent_arr['allow_gid'][$count] as $gid) {
$in_group = in_group($gid);
@@ -1186,11 +1247,9 @@ function recursive_activity_recipients($allow_cid, $allow_gid, $deny_cid, $deny_
$parent_arr['deny_gid'][] = expand_acl($x[0]['deny_gid']);
$count++;
-
}
$folder_hash = $x[0]['folder'];
-
}
//if none of the parent folders is private just return file perms
@@ -1258,11 +1317,18 @@ function recursive_activity_recipients($allow_cid, $allow_gid, $deny_cid, $deny_
}
return $ret;
-
}
+
+/**
+ * @brief Returns members of a group
+ *
+ * @param $group_id
+ */
function in_group($group_id) {
- //TODO: make these two queries one with a join.
+ $group_members = array();
+
+ /** @TODO make these two queries one with a join. */
$x = q("SELECT id FROM groups WHERE hash = '%s'",
dbesc($group_id)
);
diff --git a/include/auth.php b/include/auth.php
index 6c9c33861..643894e32 100644
--- a/include/auth.php
+++ b/include/auth.php
@@ -29,7 +29,8 @@ function nuke_session() {
unset($_SESSION['mobile_theme']);
unset($_SESSION['show_mobile']);
unset($_SESSION['page_flags']);
- unset($_SESSION['submanage']);
+ unset($_SESSION['delegate']);
+ unset($_SESSION['delegate_channel']);
unset($_SESSION['my_url']);
unset($_SESSION['my_address']);
unset($_SESSION['addr']);
diff --git a/include/bb2diaspora.php b/include/bb2diaspora.php
index 5b675128f..74ef368cf 100644
--- a/include/bb2diaspora.php
+++ b/include/bb2diaspora.php
@@ -1,4 +1,8 @@
-<?php /** @file */
+<?php
+/**
+ * @file include/bb2diaspora.php
+ * @brief Some functions for BB conversions for Diaspora protocol.
+ */
require_once("include/oembed.php");
require_once("include/event.php");
@@ -107,14 +111,19 @@ function diaspora_mention_callback($matches) {
}
-
-// we don't want to support a bbcode specific markdown interpreter
-// and the markdown library we have is pretty good, but provides HTML output.
-// So we'll use that to convert to HTML, then convert the HTML back to bbcode,
-// and then clean up a few Diaspora specific constructs.
-
-function diaspora2bb($s,$use_zrl = false) {
-
+/**
+ * @brief
+ *
+ * We don't want to support a bbcode specific markdown interpreter
+ * and the markdown library we have is pretty good, but provides HTML output.
+ * So we'll use that to convert to HTML, then convert the HTML back to bbcode,
+ * and then clean up a few Diaspora specific constructs.
+ *
+ * @param string $s
+ * @param boolean $use_zrl default false
+ * @return string
+ */
+function diaspora2bb($s, $use_zrl = false) {
$s = str_replace("&#xD;","\r",$s);
$s = str_replace("&#xD;\n&gt;","",$s);
@@ -150,7 +159,6 @@ function diaspora2bb($s,$use_zrl = false) {
}
else {
$s = preg_replace("/([^\]\=]|^)(https?\:\/\/)([a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2$3]$2$3[/url]',$s);
-
}
//$s = preg_replace("/([^\]\=]|^)(https?\:\/\/)(vimeo|youtu|www\.youtube|soundcloud)([a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2$3$4]$2$3$4[/url]',$s);
@@ -217,18 +225,33 @@ function diaspora_ol($s) {
//////////////////////
// Non-Markdownify versions of "diaspora_ol" and "diaspora_ul"
//////////////////////
+/**
+ * @brief
+ *
+ * Replace "[\\*]" followed by any number (including zero) of
+ * spaces by "* " to match Diaspora's list format.
+ *
+ * @param string $s
+ * @return string
+ */
function diaspora_ul($s) {
- // Replace "[\\*]" followed by any number (including zero) of
- // spaces by "* " to match Diaspora's list format
return preg_replace("/\[\\\\\*\]( *)/", "* ", $s[1]);
}
+/**
+ * @brief
+ *
+ * A hack: Diaspora will create a properly-numbered ordered list even
+ * if you use '1.' for each element of the list, like:
+ * \code
+ * 1. First element
+ * 1. Second element
+ * 1. Third element
+ * \endcode
+ * @param string $s
+ * @return string
+ */
function diaspora_ol($s) {
- // A hack: Diaspora will create a properly-numbered ordered list even
- // if you use '1.' for each element of the list, like:
- // 1. First element
- // 1. Second element
- // 1. Third element
return preg_replace("/\[\\\\\*\]( *)/", "1. ", $s[1]);
}
@@ -240,8 +263,8 @@ function bb2dmention_callback($match) {
if($r)
return '@{' . $match[3] . ' ; ' . $r[0]['xchan_addr'] . '}';
- return '@' . $match[3];
+ return '@' . $match[3];
}
@@ -272,14 +295,15 @@ function bb2diaspora_itemwallwall(&$item) {
}
// $item['author'] might cause a surprise further down the line if it wasn't expected to be here.
-
- if(! $author_exists)
- $unset($item['author']);
+ if(! $author_exists)
+ unset($item['author']);
}
-function bb2diaspora_itembody($item,$force_update = false) {
+function bb2diaspora_itembody($item, $force_update = false) {
+
+ $matches = array();
if(($item['diaspora_meta']) && (! $force_update)) {
$diaspora_meta = json_decode($item['diaspora_meta'],true);
@@ -295,8 +319,6 @@ function bb2diaspora_itembody($item,$force_update = false) {
logger('bb2diaspora_itembody: cached ');
$newitem = $item;
$newitem['body'] = $meta['body'];
-// this won't work - the post is now in markdown
-// bb2diaspora_itemwallwall($newitem);
return $newitem['body'];
}
}
@@ -317,7 +339,8 @@ function bb2diaspora_itembody($item,$force_update = false) {
bb2diaspora_itemwallwall($newitem);
- $body = preg_replace('/\#\^http/i', 'http', $newitem['body']);
+ $title = $newitem['title'];
+ $body = preg_replace('/\#\^http/i', 'http', $newitem['body']);
// protect tags and mentions from hijacking
@@ -345,8 +368,8 @@ function bb2diaspora_itembody($item,$force_update = false) {
$body = "## " . $title . "\n\n" . $body;
if($item['attach']) {
- $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
- if(cnt) {
+ $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item['attach'], $matches, PREG_SET_ORDER);
+ if($cnt) {
$body .= "\n" . t('Attachments:') . "\n";
foreach($matches as $mtch) {
$body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
@@ -357,7 +380,6 @@ function bb2diaspora_itembody($item,$force_update = false) {
// logger('bb2diaspora_itembody : ' . $body, LOGGER_DATA);
return html_entity_decode($body);
-
}
function bb2diaspora($Text,$preserve_nl = false, $fordiaspora = true) {
@@ -366,7 +388,7 @@ function bb2diaspora($Text,$preserve_nl = false, $fordiaspora = true) {
// The bbcode parser now handles youtube-links (and the other stuff) correctly.
// Additionally the html code is now fixed so that lists are now working.
- /**
+ /*
* Transform #tags, strip off the [url] and replace spaces with underscore
*/
$Text = preg_replace_callback('/#\[([zu])rl\=(\w+.*?)\](\w+.*?)\[\/[(zu)]rl\]/i', create_function('$match',
@@ -452,5 +474,6 @@ function format_event_diaspora($ev) {
. "\n";
$o .= "\n";
+
return $o;
}
diff --git a/include/bbcode.php b/include/bbcode.php
index 8f2b5bd38..47a1fd223 100644
--- a/include/bbcode.php
+++ b/include/bbcode.php
@@ -1,28 +1,33 @@
-<?php /** @file */
+<?php
+/**
+ * @file include/bbcode.php
+ * @brief BBCode related functions for parsing, etc.
+ */
-require_once("include/oembed.php");
+require_once('include/oembed.php');
require_once('include/event.php');
require_once('include/zot.php');
require_once('include/hubloc.php');
function tryoembed($match) {
- $url = ((count($match)==2)?$match[1]:$match[2]);
+ $url = ((count($match) == 2) ? $match[1] : $match[2]);
$o = oembed_fetch_url($url);
- if ($o->type=="error") return $match[0];
+ if ($o->type == 'error')
+ return $match[0];
$html = oembed_format_object($o);
return $html;
}
function tryzrlaudio($match) {
-
$link = $match[1];
$zrl = is_matrix_url($link);
if($zrl)
$link = zid($link);
- return '<audio src="' . str_replace(' ','%20',$link) . '" controls="controls" ><a href="' . str_replace(' ','%20',$link) . '">' . $link . '</a></audio>';
+
+ return '<audio src="' . str_replace(' ','%20',$link) . '" controls="controls"><a href="' . str_replace(' ','%20',$link) . '">' . $link . '</a></audio>';
}
function tryzrlvideo($match) {
@@ -30,8 +35,8 @@ function tryzrlvideo($match) {
$zrl = is_matrix_url($link);
if($zrl)
$link = zid($link);
- return '<video controls="controls" src="' . str_replace(' ','%20',$link) . '" style="width:100%; max-width:' . get_app()->videowidth . 'px"><a href="' . str_replace(' ','%20',$link) . '">' . $link . '</a></video>';
+ return '<video controls="controls" src="' . str_replace(' ','%20',$link) . '" style="width:100%; max-width:' . get_app()->videowidth . 'px"><a href="' . str_replace(' ','%20',$link) . '">' . $link . '</a></video>';
}
// [noparse][i]italic[/i][/noparse] turns into
@@ -39,11 +44,12 @@ function tryzrlvideo($match) {
// to hide them from parser.
function bb_spacefy($st) {
- $whole_match = $st[0];
- $captured = $st[1];
- $spacefied = preg_replace("/\[(.*?)\]/", "[ $1 ]", $captured);
- $new_str = str_replace($captured, $spacefied, $whole_match);
- return $new_str;
+ $whole_match = $st[0];
+ $captured = $st[1];
+ $spacefied = preg_replace("/\[(.*?)\]/", "[ $1 ]", $captured);
+ $new_str = str_replace($captured, $spacefied, $whole_match);
+
+ return $new_str;
}
// The previously spacefied [noparse][ i ]italic[ /i ][/noparse],
@@ -51,10 +57,11 @@ function bb_spacefy($st) {
// returning [i]italic[/i]
function bb_unspacefy_and_trim($st) {
- $whole_match = $st[0];
- $captured = $st[1];
- $unspacefied = preg_replace("/\[ (.*?)\ ]/", "[$1]", $captured);
- return $unspacefied;
+ //$whole_match = $st[0];
+ $captured = $st[1];
+ $unspacefied = preg_replace("/\[ (.*?)\ ]/", "[$1]", $captured);
+
+ return $unspacefied;
}
@@ -103,8 +110,8 @@ function bb_extract_images($body) {
function bb_replace_images($body, $images) {
$newbody = $body;
-
$cnt = 0;
+
if(! $images)
return $newbody;
@@ -119,10 +126,15 @@ function bb_replace_images($body, $images) {
return $newbody;
}
-
-
+/**
+ * @brief Parses crypt BBCode.
+ *
+ * @param array $match
+ * @return string HTML code
+ */
function bb_parse_crypt($match) {
+ $matches = array();
$attributes = $match[1];
$algorithm = "";
@@ -137,7 +149,6 @@ function bb_parse_crypt($match) {
$hint = "";
-
preg_match("/hint='(.*?)'/ism", $attributes, $matches);
if ($matches[1] != "")
$hint = $matches[1];
@@ -147,36 +158,42 @@ function bb_parse_crypt($match) {
$x = random_string();
- $Text = '<br/><div id="' . $x . '"><img src="' . z_root() . '/images/lock_icon.gif" onclick="red_decrypt(\'' . $algorithm . '\',\'' . $hint . '\',\'' . $match[2] . '\',\'#' . $x . '\');" alt="' . t('Encrypted content') . '" title="' . t('Encrypted content') . '" /></div><br />';
+ $Text = '<br /><div id="' . $x . '"><img src="' . z_root() . '/images/lock_icon.gif" onclick="red_decrypt(\'' . $algorithm . '\',\'' . $hint . '\',\'' . $match[2] . '\',\'#' . $x . '\');" alt="' . t('Encrypted content') . '" title="' . t('Encrypted content') . '" /></div><br />';
return $Text;
-
}
function bb_parse_app($match) {
require_once('include/apps.php');
$app = app_decode($match[1]);
- if($app)
+ if ($app)
return app_render($app);
-
}
function bb_parse_element($match) {
$j = json_decode(base64url_decode($match[1]),true);
- if($j) {
+ if ($j) {
$o = EOL . '<a href="#" onclick="importElement(\'' . $match[1] . '\'); return false;" >' . t('Install design element: ') . $j['pagetitle'] . '</a>' . EOL;
}
+
return $o;
}
+/**
+ * @brief Returns an QR-code image from a value given in $match[1].
+ *
+ * @param array $match
+ * @return string HTML img with QR-code of $match[1]
+ */
function bb_qr($match) {
return '<img class="zrl" src="' . z_root() . '/photo/qr?f=&qr=' . urlencode($match[1]) . '" alt="' . t('QR code') . '" title="' . htmlspecialchars($match[1],ENT_QUOTES,'UTF-8') . '" />';
-}
+}
function bb_ShareAttributes($match) {
+ $matches = array();
$attributes = $match[1];
$author = "";
@@ -204,13 +221,14 @@ function bb_ShareAttributes($match) {
if ($matches[1] != "")
$posted = $matches[1];
+ // message_id is never used, do we still need it?
$message_id = "";
preg_match("/message_id='(.*?)'/ism", $attributes, $matches);
if ($matches[1] != "")
$message_id = $matches[1];
- // FIXME - this should really be a wall-item-ago so it will get updated on the client
+ /** @FIXME - this should really be a wall-item-ago so it will get updated on the client */
$reldate = (($posted) ? relative_date($posted) : '');
$headline = '<div class="shared_container"> <div class="shared_header">';
@@ -230,24 +248,30 @@ function bb_ShareAttributes($match) {
$text = $headline . '<div class="reshared-content">' . trim($match[2]) . '</div></div>';
- return($text);
+ return $text;
}
function bb_location($match) {
// not yet implemented
}
-function bbiframe($match) {
+/**
+ * @brief Returns an iframe from $match[1].
+ *
+ * @param array $match
+ * @return string HTML iframe with content of $match[1]
+ */
+function bb_iframe($match) {
$a = get_app();
-
- $sandbox = ((strpos($match[1],get_app()->get_hostname())) ? ' sandbox="allow-scripts" ' : '');
+ $sandbox = ((strpos($match[1], $a->get_hostname())) ? ' sandbox="allow-scripts" ' : '');
return '<iframe ' . $sandbox . ' src="' . $match[1] . '" width="' . $a->videowidth . '" height="' . $a->videoheight . '"><a href="' . $match[1] . '">' . $match[1] . '</a></iframe>';
}
function bb_ShareAttributesSimple($match) {
+ $matches = array();
$attributes = $match[1];
$author = "";
@@ -268,16 +292,16 @@ function bb_ShareAttributesSimple($match) {
if ($matches[1] != "")
$profile = $matches[1];
- $text = "<br />".html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8').' <a href="'.$profile.'">'.$author."</a>: div class=\"reshared-content\">" .$match[2]."</div>";
+ $text = '<br />' . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . ' <a href="' . $profile . '">' . $author . '</a>: div class="reshared-content">' . $match[2] . '</div>';
return($text);
}
function rpost_callback($match) {
if ($match[2]) {
- return str_replace($match[0],get_rpost_path(get_app()->get_observer()) . '&title=' . urlencode($match[2]) . '&body=' . urlencode($match[3]),$match[0]);
+ return str_replace($match[0], get_rpost_path(get_app()->get_observer()) . '&title=' . urlencode($match[2]) . '&body=' . urlencode($match[3]), $match[0]);
} else {
- return str_replace($match[0],get_rpost_path(get_app()->get_observer()) . '&body=' . urlencode($match[3]),$match[0]);
+ return str_replace($match[0], get_rpost_path(get_app()->get_observer()) . '&body=' . urlencode($match[3]), $match[0]);
}
}
@@ -291,46 +315,59 @@ function bb_map_location($match) {
return str_replace($match[0],'<div class="map" >' . generate_named_map($match[1]) . '</div>', $match[0]);
}
+function bb_opentag($match) {
+ $rnd = mt_rand();
+ return "<br /><div onclick=\"openClose('opendiv-" . $rnd . "');return false;\" class=\"fakelink\">" . $match[1] . "</div><div id=\"opendiv-" . $rnd . "\" style=\"display: none;\">" . $match[2] . "</div>";
+}
+/**
+ * @brief Sanitize style properties from BBCode to HTML.
+ *
+ * @param array $input
+ * @return string A HTML span tag with the styles.
+ */
function bb_sanitize_style($input) {
- //whitelist property limits (0 = no limitation)
- $w = array( // color properties
- "color" => 0,
- "background-color" => 0,
+ // whitelist array: property => limits (0 = no limitation)
+ $w = array(
+ // color properties
+ "color" => 0,
+ "background-color" => 0,
// box properties
- "padding" => array("px"=>100, "%"=>0, "em"=>2, "ex"=>2, "mm"=>0, "cm"=>0, "in"=>0, "pt"=>0, "pc"=>0),
- "margin" => array("px"=>100, "%"=>0, "em"=>2, "ex"=>2, "mm"=>0, "cm"=>0, "in"=>0, "pt"=>0, "pc"=>0),
- "border" => array("px"=>100, "%"=>0, "em"=>2, "ex"=>2, "mm"=>0, "cm"=>0, "in"=>0, "pt"=>0, "pc"=>0),
- "float" => 0,
- "clear" => 0,
+ "padding" => array("px"=>100, "%"=>0, "em"=>2, "ex"=>2, "mm"=>0, "cm"=>0, "in"=>0, "pt"=>0, "pc"=>0),
+ "margin" => array("px"=>100, "%"=>0, "em"=>2, "ex"=>2, "mm"=>0, "cm"=>0, "in"=>0, "pt"=>0, "pc"=>0),
+ "border" => array("px"=>100, "%"=>0, "em"=>2, "ex"=>2, "mm"=>0, "cm"=>0, "in"=>0, "pt"=>0, "pc"=>0),
+ "float" => 0,
+ "clear" => 0,
// text properties
- "text-decoration" => 0,
-
+ "text-decoration" => 0,
);
+ $css = array();
$css_string = $input[1];
- $a = explode(';',$css_string);
+ $a = explode(';', $css_string);
+
foreach($a as $parts){
list($k, $v) = explode(':', $parts);
- $css[ trim($k) ] = trim($v);
+ $css[ trim($k) ] = trim($v);
}
// sanitize properties
$b = array_merge(array_diff_key($css, $w), array_diff_key($w, $css));
$css = array_diff_key($css, $b);
+ $css_string_san = '';
- foreach($css as $key => $value) {
- if($w[$key] != null) {
- foreach($w[$key] as $limit_key => $limit_value) {
+ foreach ($css as $key => $value) {
+ if ($w[$key] != null) {
+ foreach ($w[$key] as $limit_key => $limit_value) {
//sanitize values
- if(strpos($value, $limit_key)) {
+ if (strpos($value, $limit_key)) {
$value = preg_replace_callback(
"/(\S.*?)$limit_key/ism",
function($match) use($limit_value, $limit_key) {
- if($match[1] > $limit_value) {
+ if ($match[1] > $limit_value) {
return $limit_value . $limit_key;
} else {
- return $match[1] . $limit_key;
+ return $match[1] . $limit_key;
}
},
$value
@@ -340,19 +377,20 @@ function bb_sanitize_style($input) {
}
$css_string_san .= $key . ":" . $value ."; ";
}
- return "<span style=\"" . $css_string_san . "\">" . $input[2] . "</span>";
+
+ return '<span style="' . $css_string_san . '">' . $input[2] . '</span>';
}
// BBcode 2 HTML was written by WAY2WEB.net
// extended to work with Mistpark/Friendica/Red - Mike Macgirvin
-function bbcode($Text,$preserve_nl = false, $tryoembed = true) {
+function bbcode($Text, $preserve_nl = false, $tryoembed = true) {
$a = get_app();
- // Move all spaces out of the tags
+ // Move all spaces out of the tags
// ....Uhm why?
- // This is basically doing a trim() on the stuff in between tags, but it messes up
+ // This is basically doing a trim() on the stuff in between tags, but it messes up
// carefully crafted bbcode and especially other pre-formatted code.
// Commenting out until we come up with a use case where it's needed. Then let's try and
// special case rather than a heavy-handed approach like this.
@@ -393,7 +431,7 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) {
$Text = preg_replace("/\[observer\=0\](.*?)\[\/observer\]/ism", '$1', $Text);
$Text = preg_replace("/\[rpost(=.*?)?\](.*?)\[\/rpost\]/ism", '', $Text);
}
- }
+ }
$channel = $a->get_channel();
if (strpos($Text,'[/channel]') !== false) {
@@ -404,7 +442,7 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) {
$Text = preg_replace("/\[channel\=1\].*?\[\/channel\]/ism", '', $Text);
$Text = preg_replace("/\[channel\=0\](.*?)\[\/channel\]/ism", '$1', $Text);
}
- }
+ }
$x = bb_extract_images($Text);
@@ -413,14 +451,14 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) {
$Text = str_replace(array('[baseurl]','[sitename]'),array(z_root(),get_config('system','sitename')),$Text);
-
+
// Replace any html brackets with HTML Entities to prevent executing HTML or script
// Don't use strip_tags here because it breaks [url] search by replacing & with amp
$Text = str_replace("<", "&lt;", $Text);
$Text = str_replace(">", "&gt;", $Text);
-
+
// Convert new line chars to html <br /> tags
// nlbr seems to be hopelessly messed up
@@ -428,14 +466,14 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) {
// We'll emulate it.
- $Text = str_replace("\r\n","\n", $Text);
- $Text = str_replace(array("\r","\n"), array('<br />','<br />'), $Text);
+ $Text = str_replace("\r\n", "\n", $Text);
+ $Text = str_replace(array("\r", "\n"), array('<br />', '<br />'), $Text);
- if($preserve_nl)
- $Text = str_replace(array("\n","\r"), array('',''),$Text);
+ if ($preserve_nl)
+ $Text = str_replace(array("\n", "\r"), array('', ''), $Text);
- $Text = str_replace(array("\t"," "),array("&nbsp;&nbsp;&nbsp;&nbsp;","&nbsp;&nbsp;"),$Text);
+ $Text = str_replace(array("\t", " "), array("&nbsp;&nbsp;&nbsp;&nbsp;", "&nbsp;&nbsp;"), $Text);
// Set up the parameters for a URL search string
$URLSearchString = "^\[\]";
@@ -452,56 +490,53 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) {
$Text = str_replace('[observer.url]',$observer['xchan_url'], $Text);
$Text = str_replace('[observer.name]',$s1 . $observer['xchan_name'] . $s2, $Text);
$Text = str_replace('[observer.address]',$s1 . $observer['xchan_addr'] . $s2, $Text);
- $Text = str_replace('[observer.webname]',$s1 . substr($observer['xchan_addr'],0,strpos($observer['xchan_addr'],'@')) . $s2, $Text);
- $Text = str_replace('[observer.photo]',$s1 . '[zmg]'.$observer['xchan_photo_l'].'[/zmg]' . $s2, $Text);
+ $Text = str_replace('[observer.webname]', substr($observer['xchan_addr'],0,strpos($observer['xchan_addr'],'@')), $Text);
+ $Text = str_replace('[observer.photo]',$s1 . '[zmg]'.$observer['xchan_photo_l'].'[/zmg]' . $s2, $Text);
} else {
$Text = str_replace('[observer.baseurl]', '', $Text);
$Text = str_replace('[observer.url]','', $Text);
$Text = str_replace('[observer.name]','', $Text);
$Text = str_replace('[observer.address]','', $Text);
$Text = str_replace('[observer.webname]','',$Text);
- $Text = str_replace('[observer.photo]','', $Text);
+ $Text = str_replace('[observer.photo]','', $Text);
}
-
-
// Perform URL Search
- $urlchars = '[a-zA-Z0-9\:\/\-\?\&\;\.\=\@\_\~\#\%\$\!\+\,]';
+ $urlchars = '[a-zA-Z0-9\:\/\-\?\&\;\.\=\@\_\~\#\%\$\!\+\,\@]';
if (strpos($Text,'http') !== false) {
- $Text = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/$urlchars+)/ism", '$1<a href="$2" >$2</a>', $Text);
+ $Text = preg_replace("/([^\]\='".'"'."\/]|^|\#\^)(https?\:\/\/$urlchars+)/ism", '$1<a href="$2" >$2</a>', $Text);
}
if (strpos($Text,'[/qr]') !== false) {
- $Text = preg_replace_callback("/\[qr\](.*?)\[\/qr\]/ism","bb_qr",$Text);
+ $Text = preg_replace_callback("/\[qr\](.*?)\[\/qr\]/ism", 'bb_qr', $Text);
}
-
if (strpos($Text,'[/share]') !== false) {
- $Text = preg_replace_callback("/\[share(.*?)\](.*?)\[\/share\]/ism","bb_ShareAttributes",$Text);
+ $Text = preg_replace_callback("/\[share(.*?)\](.*?)\[\/share\]/ism", 'bb_ShareAttributes', $Text);
}
if($tryoembed) {
if (strpos($Text,'[/url]') !== false) {
- $Text = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism",'tryoembed',$Text);
+ $Text = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism", 'tryoembed', $Text);
}
- }
+ }
if (strpos($Text,'[/url]') !== false) {
- $Text = preg_replace("/\#\^\[url\]([$URLSearchString]*)\[\/url\]/ism", '<span class="bookmark-identifier">#^</span><a class="bookmark" href="$1" >$1</a>', $Text);
+ $Text = preg_replace("/\#\^\[url\]([$URLSearchString]*)\[\/url\]/ism", '<span class="bookmark-identifier">#^</span><a class="bookmark" href="$1" >$1</a>', $Text);
$Text = preg_replace("/\#\^\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '<span class="bookmark-identifier">#^</span><a class="bookmark" href="$1" >$2</a>', $Text);
$Text = preg_replace("/\[url\]([$URLSearchString]*)\[\/url\]/ism", '<a href="$1" >$1</a>', $Text);
$Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '<a href="$1" >$2</a>', $Text);
- }
+ }
if (strpos($Text,'[/zrl]') !== false) {
- $Text = preg_replace("/\#\^\[zrl\]([$URLSearchString]*)\[\/zrl\]/ism", '<span class="bookmark-identifier">#^</span><a class="zrl bookmark" href="$1" >$1</a>', $Text);
- $Text = preg_replace("/\#\^\[zrl\=([$URLSearchString]*)\](.*?)\[\/zrl\]/ism", '<span class="bookmark-identifier">#^</span><a class="zrl bookmark" href="$1" >$2</a>', $Text);
+ $Text = preg_replace("/\#\^\[zrl\]([$URLSearchString]*)\[\/zrl\]/ism", '<span class="bookmark-identifier">#^</span><a class="zrl bookmark" href="$1" >$1</a>', $Text);
+ $Text = preg_replace("/\#\^\[zrl\=([$URLSearchString]*)\](.*?)\[\/zrl\]/ism", '<span class="bookmark-identifier">#^</span><a class="zrl bookmark" href="$1" >$2</a>', $Text);
$Text = preg_replace("/\[zrl\]([$URLSearchString]*)\[\/zrl\]/ism", '<a class="zrl" href="$1" >$1</a>', $Text);
$Text = preg_replace("/\[zrl\=([$URLSearchString]*)\](.*?)\[\/zrl\]/ism", '<a class="zrl" href="$1" >$2</a>', $Text);
- }
+ }
// Perform MAIL Search
- if (strpos($Text,'[/mail]') !== false) {
+ if (strpos($Text,'[/mail]') !== false) {
$Text = preg_replace("/\[mail\]([$MAILSearchString]*)\[\/mail\]/", '<a href="mailto:$1">$1</a>', $Text);
$Text = preg_replace("/\[mail\=([$MAILSearchString]*)\](.*?)\[\/mail\]/", '<a href="mailto:$1">$2</a>', $Text);
}
@@ -509,54 +544,52 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) {
// leave open the posibility of [map=something]
// this is replaced in prepare_body() which has knowledge of the item location
- if (strpos($Text,'[/map]') !== false) {
- $Text = preg_replace_callback("/\[map\](.*?)\[\/map\]/ism",'bb_map_location',$Text);
+ if (strpos($Text,'[/map]') !== false) {
+ $Text = preg_replace_callback("/\[map\](.*?)\[\/map\]/ism", 'bb_map_location', $Text);
}
-
- if (strpos($Text,'[map=') !== false) {
- $Text = preg_replace_callback("/\[map=(.*?)\]/ism",'bb_map_coords',$Text);
+ if (strpos($Text,'[map=') !== false) {
+ $Text = preg_replace_callback("/\[map=(.*?)\]/ism", 'bb_map_coords', $Text);
}
-
- if (strpos($Text,'[map]') !== false) {
+ if (strpos($Text,'[map]') !== false) {
$Text = preg_replace("/\[map\]/", '<div class="map"></div>', $Text);
}
// Check for bold text
- if (strpos($Text,'[b]') !== false) {
- $Text = preg_replace("(\[b\](.*?)\[\/b\])ism",'<strong>$1</strong>',$Text);
+ if (strpos($Text,'[b]') !== false) {
+ $Text = preg_replace("(\[b\](.*?)\[\/b\])ism", '<strong>$1</strong>', $Text);
}
// Check for Italics text
- if (strpos($Text,'[i]') !== false) {
- $Text = preg_replace("(\[i\](.*?)\[\/i\])ism",'<em>$1</em>',$Text);
+ if (strpos($Text,'[i]') !== false) {
+ $Text = preg_replace("(\[i\](.*?)\[\/i\])ism", '<em>$1</em>', $Text);
}
// Check for Underline text
- if (strpos($Text,'[u]') !== false) {
- $Text = preg_replace("(\[u\](.*?)\[\/u\])ism",'<u>$1</u>',$Text);
+ if (strpos($Text,'[u]') !== false) {
+ $Text = preg_replace("(\[u\](.*?)\[\/u\])ism", '<u>$1</u>', $Text);
}
// Check for strike-through text
if (strpos($Text,'[s]') !== false) {
- $Text = preg_replace("(\[s\](.*?)\[\/s\])ism",'<strike>$1</strike>',$Text);
+ $Text = preg_replace("(\[s\](.*?)\[\/s\])ism", '<strike>$1</strike>', $Text);
}
// Check for over-line text
- if (strpos($Text,'[o]') !== false) {
- $Text = preg_replace("(\[o\](.*?)\[\/o\])ism",'<span class="overline">$1</span>',$Text);
+ if (strpos($Text,'[o]') !== false) {
+ $Text = preg_replace("(\[o\](.*?)\[\/o\])ism", '<span class="overline">$1</span>', $Text);
}
- if (strpos($Text,'[sup]') !== false) {
- $Text = preg_replace("(\[sup\](.*?)\[\/sup\])ism",'<sup>$1</sup>',$Text);
+ if (strpos($Text,'[sup]') !== false) {
+ $Text = preg_replace("(\[sup\](.*?)\[\/sup\])ism", '<sup>$1</sup>', $Text);
}
- if (strpos($Text,'[sub]') !== false) {
- $Text = preg_replace("(\[sub\](.*?)\[\/sub\])ism",'<sub>$1</sub>',$Text);
+ if (strpos($Text,'[sub]') !== false) {
+ $Text = preg_replace("(\[sub\](.*?)\[\/sub\])ism", '<sub>$1</sub>', $Text);
}
-
+
// Check for colored text
- if (strpos($Text,'[/color]') !== false) {
- $Text = preg_replace("(\[color=(.*?)\](.*?)\[\/color\])ism","<span style=\"color: $1;\">$2</span>",$Text);
+ if (strpos($Text,'[/color]') !== false) {
+ $Text = preg_replace("(\[color=(.*?)\](.*?)\[\/color\])ism", "<span style=\"color: $1;\">$2</span>", $Text);
}
// Check for sized text
- // [size=50] --> font-size: 50px (with the unit).
- if (strpos($Text,'[/size]') !== false) {
- $Text = preg_replace("(\[size=(\d*?)\](.*?)\[\/size\])ism","<span style=\"font-size: $1px;\">$2</span>",$Text);
- $Text = preg_replace("(\[size=(.*?)\](.*?)\[\/size\])ism","<span style=\"font-size: $1;\">$2</span>",$Text);
+ // [size=50] --> font-size: 50px (with the unit).
+ if (strpos($Text,'[/size]') !== false) {
+ $Text = preg_replace("(\[size=(\d*?)\](.*?)\[\/size\])ism", "<span style=\"font-size: $1px;\">$2</span>", $Text);
+ $Text = preg_replace("(\[size=(.*?)\](.*?)\[\/size\])ism", "<span style=\"font-size: $1;\">$2</span>", $Text);
}
// Check for h1
if (strpos($Text,'[h1]') !== false) {
@@ -582,13 +615,17 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) {
if (strpos($Text,'[h6]') !== false) {
$Text = preg_replace("(\[h6\](.*?)\[\/h6\])ism",'<h6>$1</h6>',$Text);
}
- // Check for table of content
+ // Check for table of content without params
if (strpos($Text,'[toc]') !== false) {
$Text = preg_replace("/\[toc\]/ism",'<ul id="toc"></ul>',$Text);
}
+ // Check for table of content with params
+ if (strpos($Text,'[toc') !== false) {
+ $Text = preg_replace("/\[toc([^\]]+?)\]/ism",'<ul$1></ul>',$Text);
+ }
// Check for centered text
- if (strpos($Text,'[/center]') !== false) {
- $Text = preg_replace("(\[center\](.*?)\[\/center\])ism","<div style=\"text-align:center;\">$1</div>",$Text);
+ if (strpos($Text,'[/center]') !== false) {
+ $Text = preg_replace("(\[center\](.*?)\[\/center\])ism", "<div style=\"text-align:center;\">$1</div>", $Text);
}
// Check for list text
$Text = str_replace("[*]", "<li>", $Text);
@@ -597,51 +634,54 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) {
$endlessloop = 0;
while ((((strpos($Text, "[/list]") !== false) && (strpos($Text, "[list") !== false)) ||
- ((strpos($Text, "[/ol]") !== false) && (strpos($Text, "[ol]") !== false)) ||
- ((strpos($Text, "[/ul]") !== false) && (strpos($Text, "[ul]") !== false)) ||
- ((strpos($Text, "[/li]") !== false) && (strpos($Text, "[li]") !== false))) && (++$endlessloop < 20)) {
- $Text = preg_replace("/\[list\](.*?)\[\/list\]/ism", '<ul class="listbullet" style="list-style-type: circle;">$1</ul>' ,$Text);
- $Text = preg_replace("/\[list=\](.*?)\[\/list\]/ism", '<ul class="listnone" style="list-style-type: none;">$1</ul>' ,$Text);
- $Text = preg_replace("/\[list=1\](.*?)\[\/list\]/ism", '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>' ,$Text);
- $Text = preg_replace("/\[list=((?-i)i)\](.*?)\[\/list\]/ism",'<ul class="listlowerroman" style="list-style-type: lower-roman;">$2</ul>' ,$Text);
- $Text = preg_replace("/\[list=((?-i)I)\](.*?)\[\/list\]/ism", '<ul class="listupperroman" style="list-style-type: upper-roman;">$2</ul>' ,$Text);
- $Text = preg_replace("/\[list=((?-i)a)\](.*?)\[\/list\]/ism", '<ul class="listloweralpha" style="list-style-type: lower-alpha;">$2</ul>' ,$Text);
- $Text = preg_replace("/\[list=((?-i)A)\](.*?)\[\/list\]/ism", '<ul class="listupperalpha" style="list-style-type: upper-alpha;">$2</ul>' ,$Text);
- $Text = preg_replace("/\[ul\](.*?)\[\/ul\]/ism", '<ul class="listbullet" style="list-style-type: circle;">$1</ul>' ,$Text);
- $Text = preg_replace("/\[ol\](.*?)\[\/ol\]/ism", '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>' ,$Text);
- $Text = preg_replace("/\[li\](.*?)\[\/li\]/ism", '<li>$1</li>' ,$Text);
- }
- if (strpos($Text,'[th]') !== false) {
- $Text = preg_replace("/\[th\](.*?)\[\/th\]/sm", '<th>$1</th>' ,$Text);
+ ((strpos($Text, "[/ol]") !== false) && (strpos($Text, "[ol]") !== false)) ||
+ ((strpos($Text, "[/ul]") !== false) && (strpos($Text, "[ul]") !== false)) ||
+ ((strpos($Text, "[/li]") !== false) && (strpos($Text, "[li]") !== false))) && (++$endlessloop < 20)) {
+ $Text = preg_replace("/\[list\](.*?)\[\/list\]/ism", '<ul class="listbullet" style="list-style-type: circle;">$1</ul>', $Text);
+ $Text = preg_replace("/\[list=\](.*?)\[\/list\]/ism", '<ul class="listnone" style="list-style-type: none;">$1</ul>', $Text);
+ $Text = preg_replace("/\[list=1\](.*?)\[\/list\]/ism", '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>', $Text);
+ $Text = preg_replace("/\[list=((?-i)i)\](.*?)\[\/list\]/ism",'<ul class="listlowerroman" style="list-style-type: lower-roman;">$2</ul>', $Text);
+ $Text = preg_replace("/\[list=((?-i)I)\](.*?)\[\/list\]/ism", '<ul class="listupperroman" style="list-style-type: upper-roman;">$2</ul>', $Text);
+ $Text = preg_replace("/\[list=((?-i)a)\](.*?)\[\/list\]/ism", '<ul class="listloweralpha" style="list-style-type: lower-alpha;">$2</ul>', $Text);
+ $Text = preg_replace("/\[list=((?-i)A)\](.*?)\[\/list\]/ism", '<ul class="listupperalpha" style="list-style-type: upper-alpha;">$2</ul>', $Text);
+ $Text = preg_replace("/\[ul\](.*?)\[\/ul\]/ism", '<ul class="listbullet" style="list-style-type: circle;">$1</ul>', $Text);
+ $Text = preg_replace("/\[ol\](.*?)\[\/ol\]/ism", '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>', $Text);
+ $Text = preg_replace("/\[li\](.*?)\[\/li\]/ism", '<li>$1</li>', $Text);
+ }
+ if (strpos($Text,'[th]') !== false) {
+ $Text = preg_replace("/\[th\](.*?)\[\/th\]/sm", '<th>$1</th>', $Text);
}
if (strpos($Text,'[td]') !== false) {
- $Text = preg_replace("/\[td\](.*?)\[\/td\]/sm", '<td>$1</td>' ,$Text);
+ $Text = preg_replace("/\[td\](.*?)\[\/td\]/sm", '<td>$1</td>', $Text);
}
- if (strpos($Text,'[tr]') !== false) {
- $Text = preg_replace("/\[tr\](.*?)\[\/tr\]/sm", '<tr>$1</tr>' ,$Text);
+ if (strpos($Text,'[tr]') !== false) {
+ $Text = preg_replace("/\[tr\](.*?)\[\/tr\]/sm", '<tr>$1</tr>', $Text);
}
- if (strpos($Text,'[/table]') !== false) {
- $Text = preg_replace("/\[table\](.*?)\[\/table\]/sm", '<table>$1</table>' ,$Text);
- $Text = preg_replace("/\[table border=1\](.*?)\[\/table\]/sm", '<table border="1" >$1</table>' ,$Text);
- $Text = preg_replace("/\[table border=0\](.*?)\[\/table\]/sm", '<table border="0" >$1</table>' ,$Text);
+ if (strpos($Text,'[/table]') !== false) {
+ $Text = preg_replace("/\[table\](.*?)\[\/table\]/sm", '<table>$1</table>', $Text);
+ $Text = preg_replace("/\[table border=1\](.*?)\[\/table\]/sm", '<table border="1" >$1</table>', $Text);
+ $Text = preg_replace("/\[table border=0\](.*?)\[\/table\]/sm", '<table border="0" >$1</table>', $Text);
}
- $Text = str_replace('[hr]','<hr />', $Text);
+ $Text = str_replace('</tr><br /><tr>', "</tr>\n<tr>", $Text);
+ $Text = str_replace('[hr]', '<hr />', $Text);
// This is actually executed in prepare_body()
- $Text = str_replace('[nosmile]','',$Text);
+ $Text = str_replace('[nosmile]', '', $Text);
// Check for font change text
- if (strpos($Text,'[/font]') !== false) {
- $Text = preg_replace("/\[font=(.*?)\](.*?)\[\/font\]/sm","<span style=\"font-family: $1;\">$2</span>",$Text);
+ if (strpos($Text,'[/font]') !== false) {
+ $Text = preg_replace("/\[font=(.*?)\](.*?)\[\/font\]/sm", "<span style=\"font-family: $1;\">$2</span>", $Text);
}
- // Declare the format for [code] layout
+ // Declare the format for [code] layout
$CodeLayout = '<code>$1</code>';
+
// Check for [code] text
- if (strpos($Text,'[code]') !== false) {
- $Text = preg_replace("/\[code\](.*?)\[\/code\]/ism","$CodeLayout", $Text);
+ if (strpos($Text,'[code]') !== false) {
+ $Text = preg_replace("/\[code\](.*?)\[\/code\]/ism", "$CodeLayout", $Text);
}
+
// Declare the format for [spoiler] layout
$SpoilerLayout = '<blockquote class="spoiler">$1</blockquote>';
@@ -649,7 +689,7 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) {
// handle nested quotes
$endlessloop = 0;
while ((strpos($Text, "[/spoiler]") !== false) and (strpos($Text, "[spoiler]") !== false) and (++$endlessloop < 20))
- $Text = preg_replace("/\[spoiler\](.*?)\[\/spoiler\]/ism","$SpoilerLayout", $Text);
+ $Text = preg_replace("/\[spoiler\](.*?)\[\/spoiler\]/ism", "$SpoilerLayout", $Text);
// Check for [spoiler=Author] text
@@ -662,6 +702,13 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) {
"<br /><strong class=".'"spoiler"'.">" . $t_wrote . "</strong><blockquote class=".'"spoiler"'.">$2</blockquote>",
$Text);
+
+ $endlessloop = 0;
+ while ((strpos($Text, "[/open]")!== false) and (strpos($Text, "[open=") !== false) and (++$endlessloop < 20)) {
+ $Text = preg_replace_callback("/\[open=(.*?)\](.*?)\[\/open\]/ism", 'bb_opentag', $Text);
+ }
+
+
// Declare the format for [quote] layout
$QuoteLayout = '<blockquote>$1</blockquote>';
@@ -669,7 +716,7 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) {
// handle nested quotes
$endlessloop = 0;
while ((strpos($Text, "[/quote]") !== false) and (strpos($Text, "[quote]") !== false) and (++$endlessloop < 20))
- $Text = preg_replace("/\[quote\](.*?)\[\/quote\]/ism","$QuoteLayout", $Text);
+ $Text = preg_replace("/\[quote\](.*?)\[\/quote\]/ism", "$QuoteLayout", $Text);
// Check for [quote=Author] text
@@ -733,9 +780,9 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) {
}
// crypt
- if (strpos($Text,'[/crypt]') !== false) {
+ if (strpos($Text,'[/crypt]') !== false) {
$x = random_string();
- $Text = preg_replace("/\[crypt\](.*?)\[\/crypt\]/ism",'<br/><div id="' . $x . '"><img src="' .$a->get_baseurl() . '/images/lock_icon.gif" onclick="red_decrypt(\'rot13\',\'\',\'$1\',\'#' . $x . '\');" alt="' . t('Encrypted content') . '" title="' . t('Encrypted content') . '" /><br /></div>', $Text);
+ $Text = preg_replace("/\[crypt\](.*?)\[\/crypt\]/ism",'<br /><div id="' . $x . '"><img src="' .$a->get_baseurl() . '/images/lock_icon.gif" onclick="red_decrypt(\'rot13\',\'\',\'$1\',\'#' . $x . '\');" alt="' . t('Encrypted content') . '" title="' . t('Encrypted content') . '" /><br /></div>', $Text);
$Text = preg_replace_callback("/\[crypt (.*?)\](.*?)\[\/crypt\]/ism", 'bb_parse_crypt', $Text);
}
@@ -747,24 +794,35 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) {
$Text = preg_replace_callback("/\[element\](.*?)\[\/element\]/ism",'bb_parse_element', $Text);
}
-
// html5 video and audio
- if (strpos($Text,'[/video]') !== false) {
- $Text = preg_replace_callback("/\[video\](.*?\.(ogg|ogv|oga|ogm|webm|mp4))\[\/video\]/ism", 'tryzrlvideo', $Text);
+ if (strpos($Text,'[/video]') !== false) {
+ $Text = preg_replace_callback("/\[video\](.*?\.(ogg|ogv|oga|ogm|webm|mp4|mpeg|mpg))\[\/video\]/ism", 'tryzrlvideo', $Text);
}
- if (strpos($Text,'[/audio]') !== false) {
+ if (strpos($Text,'[/audio]') !== false) {
$Text = preg_replace_callback("/\[audio\](.*?\.(ogg|ogv|oga|ogm|webm|mp4|mp3|opus))\[\/audio\]/ism", 'tryzrlaudio', $Text);
}
+ if (strpos($Text,'[/zvideo]') !== false) {
+ $Text = preg_replace_callback("/\[zvideo\](.*?\.(ogg|ogv|oga|ogm|webm|mp4|mpeg|mpg))\[\/zvideo\]/ism", 'tryzrlvideo', $Text);
+ }
+ if (strpos($Text,'[/zaudio]') !== false) {
+ $Text = preg_replace_callback("/\[zaudio\](.*?\.(ogg|ogv|oga|ogm|webm|mp4|mp3|opus))\[\/zaudio\]/ism", 'tryzrlaudio', $Text);
+ }
// Try to Oembed
if ($tryoembed) {
-
- if (strpos($Text,'[/video]') !== false) {
+ if (strpos($Text,'[/video]') !== false) {
$Text = preg_replace_callback("/\[video\](.*?)\[\/video\]/ism", 'tryoembed', $Text);
}
if (strpos($Text,'[/audio]') !== false) {
$Text = preg_replace_callback("/\[audio\](.*?)\[\/audio\]/ism", 'tryoembed', $Text);
}
+
+ if (strpos($Text,'[/zvideo]') !== false) {
+ $Text = preg_replace_callback("/\[zvideo\](.*?)\[\/zvideo\]/ism", 'tryoembed', $Text);
+ }
+ if (strpos($Text,'[/zaudio]') !== false) {
+ $Text = preg_replace_callback("/\[zaudio\](.*?)\[\/zaudio\]/ism", 'tryoembed', $Text);
+ }
}
// if video couldn't be embedded, link to it instead.
@@ -775,43 +833,47 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) {
$Text = preg_replace("/\[audio\](.*?)\[\/audio\]/", '<a href="$1">$1</a>', $Text);
}
-
-
+ if (strpos($Text,'[/zvideo]') !== false) {
+ $Text = preg_replace("/\[zvideo\](.*?)\[\/zvideo\]/", '<a class="zid" href="$1">$1</a>', $Text);
+ }
+ if (strpos($Text,'[/zaudio]') !== false) {
+ $Text = preg_replace("/\[zaudio\](.*?)\[\/zaudio\]/", '<a class="zid" href="$1">$1</a>', $Text);
+ }
if ($tryoembed){
if (strpos($Text,'[/iframe]') !== false) {
- $Text = preg_replace_callback("/\[iframe\](.*?)\[\/iframe\]/ism", 'bbiframe', $Text);
+ $Text = preg_replace_callback("/\[iframe\](.*?)\[\/iframe\]/ism", 'bb_iframe', $Text);
}
- }
- else {
+ } else {
if (strpos($Text,'[/iframe]') !== false) {
$Text = preg_replace("/\[iframe\](.*?)\[\/iframe\]/ism", '<a href="$1">$1</a>', $Text);
}
}
+
// Youtube extensions
if (strpos($Text,'[youtube]') !== false) {
if ($tryoembed) {
- $Text = preg_replace_callback("/\[youtube\](https?:\/\/www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", 'tryoembed', $Text);
- $Text = preg_replace_callback("/\[youtube\](www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", 'tryoembed', $Text);
- $Text = preg_replace_callback("/\[youtube\](https?:\/\/youtu.be\/.*?)\[\/youtube\]/ism",'tryoembed',$Text);
+ $Text = preg_replace_callback("/\[youtube\](https?:\/\/www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", 'tryoembed', $Text);
+ $Text = preg_replace_callback("/\[youtube\](www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", 'tryoembed', $Text);
+ $Text = preg_replace_callback("/\[youtube\](https?:\/\/youtu.be\/.*?)\[\/youtube\]/ism", 'tryoembed', $Text);
}
- $Text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/watch\?v\=(.*?)\[\/youtube\]/ism",'[youtube]$1[/youtube]',$Text);
- $Text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/embed\/(.*?)\[\/youtube\]/ism",'[youtube]$1[/youtube]',$Text);
- $Text = preg_replace("/\[youtube\]https?:\/\/youtu.be\/(.*?)\[\/youtube\]/ism",'[youtube]$1[/youtube]',$Text);
+ $Text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/watch\?v\=(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $Text);
+ $Text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/embed\/(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $Text);
+ $Text = preg_replace("/\[youtube\]https?:\/\/youtu.be\/(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $Text);
if ($tryoembed)
- $Text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", '<iframe width="' . $a->videowidth . '" height="' . $a->videoheight . '" src="http://www.youtube.com/embed/$1" frameborder="0" ></iframe>', $Text);
- else
+ $Text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", '<iframe width="' . $a->videowidth . '" height="' . $a->videoheight . '" src="http://www.youtube.com/embed/$1" frameborder="0"></iframe>', $Text);
+ else
$Text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", "http://www.youtube.com/watch?v=$1", $Text);
}
if (strpos($Text,'[vimeo]') !== false) {
if ($tryoembed) {
- $Text = preg_replace_callback("/\[vimeo\](https?:\/\/player.vimeo.com\/video\/[0-9]+).*?\[\/vimeo\]/ism",'tryoembed',$Text);
- $Text = preg_replace_callback("/\[vimeo\](https?:\/\/vimeo.com\/[0-9]+).*?\[\/vimeo\]/ism",'tryoembed',$Text);
+ $Text = preg_replace_callback("/\[vimeo\](https?:\/\/player.vimeo.com\/video\/[0-9]+).*?\[\/vimeo\]/ism", 'tryoembed', $Text);
+ $Text = preg_replace_callback("/\[vimeo\](https?:\/\/vimeo.com\/[0-9]+).*?\[\/vimeo\]/ism", 'tryoembed', $Text);
}
- $Text = preg_replace("/\[vimeo\]https?:\/\/player.vimeo.com\/video\/([0-9]+)(.*?)\[\/vimeo\]/ism",'[vimeo]$1[/vimeo]',$Text);
- $Text = preg_replace("/\[vimeo\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/vimeo\]/ism",'[vimeo]$1[/vimeo]',$Text);
+ $Text = preg_replace("/\[vimeo\]https?:\/\/player.vimeo.com\/video\/([0-9]+)(.*?)\[\/vimeo\]/ism", '[vimeo]$1[/vimeo]', $Text);
+ $Text = preg_replace("/\[vimeo\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/vimeo\]/ism", '[vimeo]$1[/vimeo]', $Text);
if ($tryoembed)
$Text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism", '<iframe width="' . $a->videowidth . '" height="' . $a->videoheight . '" src="http://player.vimeo.com/video/$1" frameborder="0" ></iframe>', $Text);
@@ -830,7 +892,7 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) {
// Summary (e.g. title) is required, earlier revisions only required description (in addition to
// start which is always required). Allow desc with a missing summary for compatibility.
- if((x($ev,'desc') || x($ev,'summary')) && x($ev,'start')) {
+ if ((x($ev,'desc') || x($ev,'summary')) && x($ev,'start')) {
$sub = format_event_html($ev);
$Text = preg_replace("/\[event\-summary\](.*?)\[\/event\-summary\]/ism",'',$Text);
@@ -844,26 +906,25 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true) {
// Unhide all [noparse] contained bbtags unspacefying them
// and triming the [noparse] tag.
if (strpos($Text,'[noparse]') !== false) {
- $Text = preg_replace_callback("/\[noparse\](.*?)\[\/noparse\]/ism", 'bb_unspacefy_and_trim',$Text);
+ $Text = preg_replace_callback("/\[noparse\](.*?)\[\/noparse\]/ism", 'bb_unspacefy_and_trim', $Text);
}
if (strpos($Text,'[nobb]') !== false) {
- $Text = preg_replace_callback("/\[nobb\](.*?)\[\/nobb\]/ism", 'bb_unspacefy_and_trim',$Text);
+ $Text = preg_replace_callback("/\[nobb\](.*?)\[\/nobb\]/ism", 'bb_unspacefy_and_trim', $Text);
}
if (strpos($Text,'[pre]') !== false) {
- $Text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", 'bb_unspacefy_and_trim',$Text);
+ $Text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", 'bb_unspacefy_and_trim', $Text);
}
- $Text = preg_replace('/\[\&amp\;([#a-z0-9]+)\;\]/','&$1;',$Text);
+ $Text = preg_replace('/\[\&amp\;([#a-z0-9]+)\;\]/', '&$1;', $Text);
// fix any escaped ampersands that may have been converted into links
- $Text = preg_replace("/\<(.*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism",'<$1$2=$3&$4>',$Text);
+ $Text = preg_replace("/\<(.*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism", '<$1$2=$3&$4>', $Text);
- $Text = preg_replace("/\<(.*?)(src|href)=\"[^hfm#](.*?)\>/ism",'<$1$2="">',$Text);
+ $Text = preg_replace("/\<(.*?)(src|href)=\"[^zhfm#](.*?)\>/ism", '<$1$2="">', $Text);
- $Text = bb_replace_images($Text,$saved_images);
+ $Text = bb_replace_images($Text, $saved_images);
- call_hooks('bbcode',$Text);
+ call_hooks('bbcode', $Text);
return $Text;
}
-
diff --git a/include/bookmarks.php b/include/bookmarks.php
index e70158476..c6e8e86f2 100644
--- a/include/bookmarks.php
+++ b/include/bookmarks.php
@@ -9,7 +9,7 @@ function bookmark_add($channel,$sender,$taxonomy,$private,$opts = null) {
$ischat = false;
if(is_array($opts)) {
- $menu_id = ((x($opts,'menu_id')) ? intval($opt['menu_id']) : 0);
+ $menu_id = ((x($opts,'menu_id')) ? intval($opts['menu_id']) : 0);
$menu_name = ((x($opts,'menu_name')) ? escape_tags($opts['menu_name']) : '');
$ischat = ((x($opts,'ischat')) ? intval($opts['ischat']) : 0);
}
diff --git a/include/chat.php b/include/chat.php
index b19d495bb..05bb02bb9 100644
--- a/include/chat.php
+++ b/include/chat.php
@@ -1,7 +1,20 @@
-<?php /** @file */
+<?php
+/**
+ * @file include/chat.php
+ * @brief Chat related functions.
+ */
-function chatroom_create($channel,$arr) {
+/**
+ * @brief Creates a chatroom.
+ *
+ * @param array $channel
+ * @param array $arr
+ * @return An associative array containing:
+ * - success: A boolean
+ * - message: (optional) A string
+ */
+function chatroom_create($channel, $arr) {
$ret = array('success' => false);
@@ -24,14 +37,14 @@ function chatroom_create($channel,$arr) {
intval($channel['channel_account_id'])
);
if($r)
- $limit = service_class_fetch($channel_id,'chatrooms');
+ $limit = service_class_fetch($channel['channel_id'], 'chatrooms');
- if(($r) && ($limit !== false) && ($r[0]['total'] >= $limit)) {
- $ret['message'] = upgrade_message();
- return $ret;
- }
+ if(($r) && ($limit !== false) && ($r[0]['total'] >= $limit)) {
+ $ret['message'] = upgrade_message();
+ return $ret;
+ }
- if(! array_key_exists('expire',$arr))
+ if(! array_key_exists('expire', $arr))
$arr['expire'] = 120; // minutes, e.g. 2 hours
$created = datetime_convert();
@@ -60,6 +73,7 @@ function chatroom_create($channel,$arr) {
function chatroom_destroy($channel,$arr) {
$ret = array('success' => false);
+
if(intval($arr['cr_id']))
$sql_extra = " and cr_id = " . intval($arr['cr_id']) . " ";
elseif(trim($arr['cr_name']))
@@ -72,7 +86,7 @@ function chatroom_destroy($channel,$arr) {
$r = q("select * from chatroom where cr_uid = %d $sql_extra limit 1",
intval($channel['channel_id'])
);
- if(! $r) {
+ if(! $r) {
$ret['message'] = t('Invalid room specifier.');
return $ret;
}
@@ -88,12 +102,13 @@ function chatroom_destroy($channel,$arr) {
intval($r[0]['cr_id'])
);
}
+
$ret['success'] = true;
return $ret;
}
-function chatroom_enter($observer_xchan,$room_id,$status,$client) {
+function chatroom_enter($observer_xchan, $room_id, $status, $client) {
if(! $room_id || ! $observer_xchan)
return;
@@ -117,7 +132,7 @@ function chatroom_enter($observer_xchan,$room_id,$status,$client) {
return false;
}
- $limit = service_class_fetch($r[0]['cr_uid'],'chatters_inroom');
+ $limit = service_class_fetch($r[0]['cr_uid'], 'chatters_inroom');
if($limit !== false) {
$y = q("select count(*) as total from chatpresence where cp_room = %d",
intval($room_id)
@@ -157,12 +172,12 @@ function chatroom_enter($observer_xchan,$room_id,$status,$client) {
dbesc($status),
dbesc($client)
);
-
+
return $r;
}
-function chatroom_leave($observer_xchan,$room_id,$client) {
+function chatroom_leave($observer_xchan, $room_id, $client) {
if(! $room_id || ! $observer_xchan)
return;
@@ -208,7 +223,7 @@ function chatroom_list_count($uid) {
* It is the caller's responsibility to enter the room.
*/
-function chat_message($uid,$room_id,$xchan,$text) {
+function chat_message($uid, $room_id, $xchan, $text) {
$ret = array('success' => false);
@@ -230,14 +245,14 @@ function chat_message($uid,$room_id,$xchan,$text) {
'chat_text' => $text
);
- call_hooks('chat_message',$arr);
+ call_hooks('chat_message', $arr);
$x = q("insert into chat ( chat_room, chat_xchan, created, chat_text )
values( %d, '%s', '%s', '%s' )",
intval($room_id),
dbesc($xchan),
dbesc(datetime_convert()),
- dbesc($arr['chat_text'])
+ dbesc($arr['chat_text'])
);
$ret['success'] = true;
diff --git a/include/comanche.php b/include/comanche.php
index b181d415a..e0d3af985 100644
--- a/include/comanche.php
+++ b/include/comanche.php
@@ -15,23 +15,22 @@ require_once('include/widgets.php');
// page layout from the given description
-function pdl_selector($uid,$current="") {
-
+function pdl_selector($uid, $current="") {
$o = '';
$sql_extra = item_permissions_sql($uid);
- $r = q("select item_id.*, mid from item_id left join item on iid = item.id where item_id.uid = %d and item_id.uid = item.uid and service = 'PDL' order by sid asc",
- intval($owner)
+ $r = q("select item_id.*, mid from item_id left join item on iid = item.id where item_id.uid = %d and item_id.uid = item.uid and service = 'PDL' $sql_extra order by sid asc",
+ intval($uid)
);
$arr = array('channel_id' => $uid, 'current' => $current, 'entries' => $r);
call_hooks('pdl_selector',$arr);
$entries = $arr['entries'];
- $current = $arr['current'];
-
- $o .= "<select name=\"pdl_select\" id=\"pdl_select\" size=\"1\" >";
+ $current = $arr['current'];
+
+ $o .= '<select name="pdl_select" id="pdl_select" size="1">';
$entries[] = array('title' => t('Default'), 'mid' => '');
foreach($entries as $selection) {
$selected = (($selection == $current) ? ' selected="selected" ' : '');
@@ -40,109 +39,131 @@ function pdl_selector($uid,$current="") {
$o .= '</select>';
return $o;
-}
+}
-function comanche_parser(&$a,$s) {
+function comanche_parser(&$a, $s, $pass = 0) {
+ $matches = array();
$cnt = preg_match_all("/\[comment\](.*?)\[\/comment\]/ism", $s, $matches, PREG_SET_ORDER);
if($cnt) {
foreach($matches as $mtch) {
- $s = str_replace($mtch[0],'',$s);
+ $s = str_replace($mtch[0], '', $s);
}
}
- $cnt = preg_match("/\[layout\](.*?)\[\/layout\]/ism", $s, $matches);
- if($cnt)
- $a->page['template'] = trim($matches[1]);
+ if($pass == 0) {
+ $cnt = preg_match("/\[layout\](.*?)\[\/layout\]/ism", $s, $matches);
+ if($cnt)
+ $a->page['template'] = trim($matches[1]);
- $cnt = preg_match("/\[template=(.*?)\](.*?)\[\/template\]/ism", $s, $matches);
- if($cnt) {
- $a->page['template'] = trim($matches[2]);
- $a->page['template_style'] = trim($matches[2]) . '_' . $matches[1];
- }
+ $cnt = preg_match("/\[template=(.*?)\](.*?)\[\/template\]/ism", $s, $matches);
+ if($cnt) {
+ $a->page['template'] = trim($matches[2]);
+ $a->page['template_style'] = trim($matches[2]) . '_' . $matches[1];
+ }
- $cnt = preg_match("/\[template\](.*?)\[\/template\]/ism", $s, $matches);
- if($cnt) {
- $a->page['template'] = trim($matches[1]);
- }
+ $cnt = preg_match("/\[template\](.*?)\[\/template\]/ism", $s, $matches);
+ if($cnt) {
+ $a->page['template'] = trim($matches[1]);
+ }
- $cnt = preg_match("/\[theme=(.*?)\](.*?)\[\/theme\]/ism", $s, $matches);
- if($cnt) {
- $a->layout['schema'] = trim($matches[1]);
- $a->layout['theme'] = trim($matches[2]);
- }
+ $cnt = preg_match("/\[theme=(.*?)\](.*?)\[\/theme\]/ism", $s, $matches);
+ if($cnt) {
+ $a->layout['schema'] = trim($matches[1]);
+ $a->layout['theme'] = trim($matches[2]);
+ }
- $cnt = preg_match("/\[theme\](.*?)\[\/theme\]/ism", $s, $matches);
- if($cnt)
- $a->layout['theme'] = trim($matches[1]);
+ $cnt = preg_match("/\[theme\](.*?)\[\/theme\]/ism", $s, $matches);
+ if($cnt)
+ $a->layout['theme'] = trim($matches[1]);
- $cnt = preg_match_all("/\[region=(.*?)\](.*?)\[\/region\]/ism", $s, $matches, PREG_SET_ORDER);
- if($cnt) {
- foreach($matches as $mtch) {
- $a->layout['region_' . $mtch[1]] = comanche_region($a,$mtch[2]);
+ $cnt = preg_match_all("/\[webpage\](.*?)\[\/webpage\]/ism", $s, $matches, PREG_SET_ORDER);
+ if($cnt) {
+ // only the last webpage definition is used if there is more than one
+ foreach($matches as $mtch) {
+ $a->layout['webpage'] = comanche_webpage($a,$mtch[1]);
+ }
}
- }
- $cnt = preg_match_all("/\[webpage\](.*?)\[\/webpage\]/ism", $s, $matches, PREG_SET_ORDER);
- if($cnt) {
- // only the last webpage definition is used if there is more than one
- foreach($matches as $mtch) {
- $a->layout['webpage'] = comanche_webpage($a,$mtch[1]);
+ }
+ else {
+ $cnt = preg_match_all("/\[region=(.*?)\](.*?)\[\/region\]/ism", $s, $matches, PREG_SET_ORDER);
+ if($cnt) {
+ foreach($matches as $mtch) {
+ $a->layout['region_' . $mtch[1]] = comanche_region($a,$mtch[2]);
+ }
}
+
}
}
-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());
- return menu_render($m,$class);
+ $m = menu_fetch($name,$channel_id, get_observer_hash());
+ return menu_render($m, $class);
}
}
function comanche_replace_region($match) {
$a = get_app();
- if(array_key_exists($match[1],$a->page)) {
+ if (array_key_exists($match[1], $a->page)) {
return $a->page[$match[1]];
}
}
/**
- * @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;
}
-function comanche_block($name) {
+function comanche_block($s) {
+ $var = array();
+ $matches = array();
+ $name = $s;
+ $cnt = preg_match_all("/\[var=(.*?)\](.*?)\[\/var\]/ism", $s, $matches, PREG_SET_ORDER);
+ if($cnt) {
+ foreach($matches as $mtch) {
+ $var[$mtch[1]] = $mtch[2];
+ $name = str_replace($mtch[0], '', $name);
+ }
+ }
+
+ $o = '';
$channel_id = comanche_get_channel_id();
-
+
if($channel_id) {
- $o = '';
$r = q("select * from item inner join item_id on iid = item.id and item_id.uid = item.uid and item.uid = %d and service = 'BUILDBLOCK' and sid = '%s' limit 1",
intval($channel_id),
dbesc($name)
);
if($r) {
- $o = '<div class="widget bblock">';
+ $o .= (($var['wrap'] == 'none') ? '' : '<div class="bblock">');
if($r[0]['title'])
$o .= '<h3>' . $r[0]['title'] . '</h3>';
- $o .= prepare_text($r[0]['body'],$r[0]['mimetype']);
- $o .= '</div>';
+ $o .= prepare_text($r[0]['body'], $r[0]['mimetype']);
+ $o .= (($var['wrap'] == 'none') ? '' : '</div>');
}
}
+
return $o;
}
@@ -154,8 +175,9 @@ function comanche_block($name) {
// of what template and webpage options we might desire.
function comanche_webpage(&$a,$s) {
-
$ret = array();
+ $matches = array();
+
$cnt = preg_match_all("/\[authored\](.*?)\[\/authored\]/ism", $s, $matches, PREG_SET_ORDER);
if($cnt) {
foreach($matches as $mtch) {
@@ -166,32 +188,37 @@ 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
-
-
-function comanche_widget($name,$text) {
- $a = get_app();
+/**
+ * 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);
}
-function comanche_region(&$a,$s) {
+function comanche_region(&$a, $s) {
+ $matches = array();
$cnt = preg_match_all("/\[menu\](.*?)\[\/menu\]/ism", $s, $matches, PREG_SET_ORDER);
if($cnt) {
foreach($matches as $mtch) {
- $s = str_replace($mtch[0],comanche_menu(trim($mtch[1])),$s);
+ $s = str_replace($mtch[0], comanche_menu(trim($mtch[1])), $s);
}
}
@@ -244,7 +271,3 @@ function register_page_template($arr) {
get_app()->page_layouts[$arr['template']] = array($arr['variant']);
return;
}
-
-
-
-
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 @@
* - <b>pconfig</b> is used for channel specific configurations and takes a
* <i>channel_id</i> 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
* - <b>xconfig</b> is the same as pconfig, except that it uses <i>xchan</i> 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 f76d3a27c..0250ad8b9 100644
--- a/include/conversation.php
+++ b/include/conversation.php
@@ -205,22 +205,22 @@ function localize_item(&$item){
$item['body'] .= "\n\n\n" . $Bphoto;
}
- if (stristr($item['verb'],ACTIVITY_POKE)) {
+ if (stristr($item['verb'], ACTIVITY_POKE)) {
- // FIXME for obscured private posts, until then leave untranslated
+ /** @FIXME for obscured private posts, until then leave untranslated */
return;
$verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
if(! $verb)
return;
+
if ($item['obj_type']=="" || $item['obj_type']!== ACTIVITY_OBJ_PERSON) return;
$Aname = $item['author']['xchan_name'];
$Alink = $item['author']['xchan_url'];
-
$obj= json_decode_plus($item['object']);
-
+
$Blink = $Bphoto = '';
if($obj['link']) {
@@ -246,7 +246,6 @@ function localize_item(&$item){
$item['body'] = $item['localize'] = sprintf($txt, $A, $B);
$item['body'] .= "\n\n\n" . $Bphoto;
-
}
if (stristr($item['verb'],ACTIVITY_MOOD)) {
$verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
@@ -366,54 +365,72 @@ function localize_item(&$item){
&& strlen($item['body']) && (! strpos($item['body'],'data'))) {
$item['body'] = json_encode(crypto_encapsulate($item['body'],get_config('system','pubkey')));
}
-
}
/**
- * Count the total of comments on this item and its desendants
+ * @brief Count the total of comments on this item and its desendants.
+ *
+ * @param array $item an assoziative item-array which provides:
+ * * \e array \b children
+ * @return number
*/
function count_descendants($item) {
$total = count($item['children']);
- if($total > 0) {
- foreach($item['children'] as $child) {
- if(! visible_activity($child))
- $total --;
- $total += count_descendants($child);
- }
- }
+ if ($total > 0) {
+ foreach ($item['children'] as $child) {
+ if (! visible_activity($child))
+ $total --;
+
+ $total += count_descendants($child);
+ }
+ }
return $total;
}
+/**
+ * @brief Check if the activity of the item is visible.
+ *
+ * likes (etc.) can apply to other things besides posts. Check if they are post
+ * children, in which case we handle them specially.
+ *
+ * @param array $item
+ * @return boolean
+ */
function visible_activity($item) {
+ $hidden_activities = array(ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_AGREE, ACTIVITY_DISAGREE, ACTIVITY_ABSTAIN, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE);
- // likes (etc.) can apply to other things besides posts. Check if they are post children,
- // in which case we handle them specially
-
- $hidden_activities = array(ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_AGREE, ACTIVITY_DISAGREE, ACTIVITY_ABSTAIN);
- foreach($hidden_activities as $act) {
- if((activity_match($item['verb'],$act)) && ($item['mid'] != $item['parent_mid'])) {
+ foreach ($hidden_activities as $act) {
+ if ((activity_match($item['verb'], $act)) && ($item['mid'] != $item['parent_mid'])) {
return false;
}
}
+
return true;
}
/**
- * "Render" a conversation or list of items for HTML display.
+ * @brief "Render" a conversation or list of items for HTML display.
+ *
* There are two major forms of display:
- * - Sequential or unthreaded ("New Item View" or search results)
- * - conversation view
+ * - Sequential or unthreaded ("New Item View" or search results)
+ * - conversation view
+ *
* The $mode parameter decides between the various renderings and also
* figures out how to determine page owner and other contextual items
* that are based on unique features of the calling module.
*
+ * @param App &$a
+ * @param array $items
+ * @param string $mode
+ * @param boolean $update
+ * @param string $page_mode default traditional
+ * @param string $prepared_item
+ * @return string
*/
-
-
function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $prepared_item = '') {
$content_html = '';
@@ -423,39 +440,38 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $
$ssl_state = ((local_channel()) ? true : false);
- if(local_channel())
+ if (local_channel())
load_pconfig(local_channel(),'');
$arr_blocked = null;
- if(local_channel())
+ if (local_channel())
$str_blocked = get_pconfig(local_channel(),'system','blocked');
- if(! local_channel() && ($mode == 'network')) {
+ if (! local_channel() && ($mode == 'network')) {
$sys = get_sys_channel();
$id = $sys['channel_id'];
$str_blocked = get_pconfig($id,'system','blocked');
}
-
- if($str_blocked) {
- $arr_blocked = explode(',',$str_blocked);
- for($x = 0; $x < count($arr_blocked); $x ++)
+
+ if ($str_blocked) {
+ $arr_blocked = explode(',',$str_blocked);
+ for ($x = 0; $x < count($arr_blocked); $x ++)
$arr_blocked[$x] = trim($arr_blocked[$x]);
}
-
- $profile_owner = 0;
- $page_writeable = false;
+ $profile_owner = 0;
+ $page_writeable = false;
$live_update_div = '';
$preview = (($page_mode === 'preview') ? true : false);
$previewing = (($preview) ? ' preview ' : '');
- if($mode === 'network') {
+ if ($mode === 'network') {
$profile_owner = local_channel();
$page_writeable = true;
- if(!$update) {
+ if (!$update) {
// The special div is needed for liveUpdate to kick in for this page.
// We only launch liveUpdate if you aren't filtering in some incompatible
// way and also you aren't writing a comment (discovered in javascript).
@@ -481,13 +497,13 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $
}
}
- elseif($mode === 'channel') {
+ elseif ($mode === 'channel') {
$profile_owner = $a->profile['profile_uid'];
$page_writeable = ($profile_owner == local_channel());
- if(!$update) {
+ if (!$update) {
$tab = notags(trim($_GET['tab']));
- if($tab === 'posts') {
+ if ($tab === 'posts') {
// This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
// because browser prefetching might change it on us. We have to deliver it with the page.
@@ -498,23 +514,23 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $
}
}
- elseif($mode === 'display') {
+ elseif ($mode === 'display') {
$profile_owner = local_channel();
$page_writeable = false;
$live_update_div = '<div id="live-display"></div>' . "\r\n";
}
- elseif($mode === 'page') {
+ elseif ($mode === 'page') {
$profile_owner = $a->profile['uid'];
$page_writeable = ($profile_owner == local_channel());
$live_update_div = '<div id="live-page"></div>' . "\r\n";
}
- elseif($mode === 'search') {
+ elseif ($mode === 'search') {
$live_update_div = '<div id="live-search"></div>' . "\r\n";
}
- elseif($mode === 'photos') {
+ elseif ($mode === 'photos') {
$profile_onwer = $a->profile['profile_uid'];
$page_writeable = ($profile_owner == local_channel());
$live_update_div = '<div id="live-photos"></div>' . "\r\n";
@@ -524,12 +540,12 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $
$page_dropping = ((local_channel() && local_channel() == $profile_owner) ? true : false);
- if(! feature_enabled($profile_owner,'multi_delete'))
+ if (! feature_enabled($profile_owner,'multi_delete'))
$page_dropping = false;
$channel = $a->get_channel();
- $observer = $a->get_observer();
+ $observer = $a->get_observer();
if($update)
$return_url = $_SESSION['return_url'];
@@ -543,7 +559,12 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $
$items = $cb['items'];
- $conv_responses = array(array('like'),array('dislike'),array('agree'),array('disagree'),array('abstain'));
+ $conv_responses = array(
+ 'like' => array('title' => t('Likes','title')),'dislike' => array('title' => t('Dislikes','title')),
+ 'agree' => array('title' => t('Agree','title')),'disagree' => array('title' => t('Disagree','title')), 'abstain' => array('title' => t('Abstain','title')),
+ 'attendyes' => array('title' => t('Attending','title')), 'attendno' => array('title' => t('Not attending','title')), 'attendmaybe' => array('title' => t('Might attend','title'))
+ );
+
// array with html for each thread (parent+comments)
$threads = array();
@@ -623,7 +644,6 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $
else
$dropping = false;
-
$drop = array(
'pagedropping' => $page_dropping,
'dropping' => $dropping,
@@ -633,7 +653,7 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $
$star = false;
$isstarred = "unstarred icon-star-empty";
-
+
$lock = (($item['item_private'] || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
? t('Private Message')
: false
@@ -645,17 +665,14 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $
$verified = (intval($item['item_verified']) ? t('Message signature validated') : '');
$forged = ((($item['sig']) && (! intval($item['item_verified']))) ? t('Message signature incorrect') : '');
-
$unverified = '';
-
$tags=array();
$terms = get_terms_oftype($item['term'],array(TERM_HASHTAG,TERM_MENTION,TERM_UNKNOWN));
if(count($terms))
foreach($terms as $tag)
$tags[] = format_term_for_display($tag);
-
$body = prepare_body($item,true);
$tmp_item = array(
@@ -687,7 +704,7 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $
'text' => strip_tags($body),
'ago' => relative_date($item['created']),
'app' => $item['app'],
- 'str_app' => sprintf( t(' from %s'), $item['app']),
+ 'str_app' => sprintf( t('from %s'), $item['app']),
'isotime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'c'),
'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
'editedtime' => (($item['edited'] != $item['created']) ? sprintf( t('last edited: %s'), datetime_convert('UTC', date_default_timezone_get(), $item['edited'], 'r')) : ''),
@@ -717,12 +734,9 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $
// $threads[$threadsid]['id'] = $item['item_id'];
$threads[] = $arr['output'];
-
}
-
}
- else
- {
+ else {
// Normal View
// logger('conv: items: ' . print_r($items,true));
@@ -737,7 +751,6 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $
if($mode === 'display' && $items)
$conv->set_profile_owner($items[0]['uid']);
-
// get all the topmost parents
// this shouldn't be needed, as we should have only them in our array
// But for now, this array respects the old style, just in case
@@ -770,14 +783,7 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $
}
}
- like_puller($a, $item, $conv_responses, 'like');
-
- if(feature_enabled($profile_owner, 'dislike'))
- like_puller($a, $item, $conv_responses, 'dislike');
-
- like_puller($a, $item, $conv_responses, 'agree');
- like_puller($a, $item, $conv_responses, 'disagree');
- like_puller($a, $item, $conv_responses, 'abstain');
+ builtin_activity_puller($item, $conv_responses);
if(! visible_activity($item)) {
continue;
@@ -824,20 +830,19 @@ function conversation(&$a, $items, $mode, $update, $page_mode = 'traditional', $
// logger('nouveau: ' . print_r($threads,true));
- $o .= replace_macros($page_template, array(
- '$baseurl' => $a->get_baseurl($ssl_state),
+ $o .= replace_macros($page_template, array(
+ '$baseurl' => $a->get_baseurl($ssl_state),
'$photo_item' => $content_html,
- '$live_update' => $live_update_div,
- '$remove' => t('remove'),
- '$mode' => $mode,
- '$user' => $a->user,
- '$threads' => $threads,
+ '$live_update' => $live_update_div,
+ '$remove' => t('remove'),
+ '$mode' => $mode,
+ '$user' => $a->user,
+ '$threads' => $threads,
'$wait' => t('Loading...'),
- '$dropping' => ($page_dropping?t('Delete Selected Items'):False),
- ));
+ '$dropping' => ($page_dropping?t('Delete Selected Items'):False),
+ ));
return $o;
-
}
@@ -885,7 +890,6 @@ function item_photo_menu($item){
$vsrc_link = "";
$follow_url = "";
-
$local_channel = local_channel();
if($local_channel) {
@@ -903,7 +907,7 @@ function item_photo_menu($item){
}
}
- $profile_link = chanlink_hash($item['author_xchan']);
+ $profile_link = chanlink_hash($item['author_xchan']);
if($item['uid'] > 0)
$pm_url = $a->get_baseurl($ssl_state) . '/mail/new/?f=&hash=' . $item['author_xchan'];
@@ -920,7 +924,6 @@ function item_photo_menu($item){
$posts_link = $a->get_baseurl($ssl_state) . '/network/?cid=' . $contact['abook_id'];
$clean_url = normalise_link($item['author-link']);
-
}
$menu = Array(
@@ -936,7 +939,6 @@ function item_photo_menu($item){
t("Poke") => $poke_link
);
-
$args = array('item' => $item, 'menu' => $menu);
call_hooks('item_photo_menu', $args);
@@ -951,94 +953,111 @@ function item_photo_menu($item){
}
elseif ($v!="") $o .= "<li><a href=\"$v\">$k</a></li>\n";
}
+
return $o;
}
/**
- * @brief Returns a like/dislike entry.
- * It gives back a HTML link to the channel that liked/disliked.
+ * @brief Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
+ *
+ * Increments the count of each matching activity and adds a link to the author as needed.
*
- * @param array $a (not used)
* @param array $item
- * @param array &$arr
- * @param string $mode like/dislike
- * @return void
+ * @param array &$conv_responses (already created with builtin activity structure)
*/
-function like_puller($a, $item, &$arr, $mode) {
+function builtin_activity_puller($item, &$conv_responses) {
- $url = '';
+ // if this item is a post or comment there's nothing for us to do here, just return.
- switch($mode) {
- case 'like':
- case 'unlike':
- $verb = ACTIVITY_LIKE;
- break;
- case 'dislike':
- case 'undislike':
- $verb = ACTIVITY_DISLIKE;
- break;
- case 'agree':
- case 'unagree':
- $verb = ACTIVITY_AGREE;
- break;
- case 'disagree':
- case 'undisagree':
- $verb = ACTIVITY_DISAGREE;
- break;
- case 'abstain':
- case 'unabstain':
- $verb = ACTIVITY_ABSTAIN;
- break;
- default:
- return;
- break;
- }
+ if(activity_match($item['verb'],ACTIVITY_POST))
+ return;
+
+ foreach($conv_responses as $mode => $v) {
- if((activity_match($item['verb'], $verb)) && ($item['id'] != $item['parent'])) {
+ $url = '';
- if($item['author']['xchan_url'])
- $url = chanlink_url($item['author']['xchan_url']);
+ switch($mode) {
+ case 'like':
+ $verb = ACTIVITY_LIKE;
+ break;
+ case 'dislike':
+ $verb = ACTIVITY_DISLIKE;
+ break;
+ case 'agree':
+ $verb = ACTIVITY_AGREE;
+ break;
+ case 'disagree':
+ $verb = ACTIVITY_DISAGREE;
+ break;
+ case 'abstain':
+ $verb = ACTIVITY_ABSTAIN;
+ break;
+ case 'attendyes':
+ $verb = ACTIVITY_ATTEND;
+ break;
+ case 'attendno':
+ $verb = ACTIVITY_ATTENDNO;
+ break;
+ case 'attendmaybe':
+ $verb = ACTIVITY_ATTENDMAYBE;
+ break;
+ default:
+ return;
+ break;
+ }
- if(! $item['thr_parent'])
- $item['thr_parent'] = $item['parent_mid'];
+ if((activity_match($item['verb'], $verb)) && ($item['id'] != $item['parent'])) {
+ $name = (($item['author']['xchan_name']) ? $item['author']['xchan_name'] : t('Unknown'));
+ $url = (($item['author']['xchan_url'])
+ ? '<a href="' . chanlink_url($item['author']['xchan_url']) . '">' . $name . '</a>'
+ : '<a href="#" class="disabled">' . $name . '</a>'
+ );
- if(! ((isset($arr[$mode][$item['thr_parent'] . '-l'])) && (is_array($arr[$mode][$item['thr_parent'] . '-l']))))
- $arr[$mode][$item['thr_parent'] . '-l'] = array();
+ if(! $item['thr_parent'])
+ $item['thr_parent'] = $item['parent_mid'];
- if(! isset($arr[$mode][$item['thr_parent']]))
- $arr[$mode][$item['thr_parent']] = 1;
- else
- $arr[$mode][$item['thr_parent']] ++;
+ if(! ((isset($conv_responses[$mode][$item['thr_parent'] . '-l']))
+ && (is_array($conv_responses[$mode][$item['thr_parent'] . '-l']))))
+ $conv_responses[$mode][$item['thr_parent'] . '-l'] = array();
- $name = (($item['author']['xchan_name']) ? $item['author']['xchan_name'] : t('Unknown'));
+ // only list each unique author once
+ if(in_array($url,$conv_responses[$mode][$item['thr_parent'] . '-l']))
+ continue;
- if($url)
- $arr[$mode][$item['thr_parent'] . '-l'][] = '<a href="'. $url . '">' . $name . '</a>';
- else
- $arr[$mode][$item['thr_parent'] . '-l'][] = '<a href="#" class="disabled">' . $name . '</a>';
+ if(! isset($conv_responses[$mode][$item['thr_parent']]))
+ $conv_responses[$mode][$item['thr_parent']] = 1;
+ else
+ $conv_responses[$mode][$item['thr_parent']] ++;
+
+ $conv_responses[$mode][$item['thr_parent'] . '-l'][] = $url;
+
+ // there can only be one activity verb per item so if we found anything, we can stop looking
+ return;
+ }
}
- return;
}
-// Format the like/dislike text for a profile item
-// $cnt = number of people who like/dislike the item
-// $arr = array of pre-linked names of likers/dislikers
-// $type = one of 'like, 'dislike'
-// $id = item id
-// returns formatted text
-
-function format_like($cnt,$arr,$type,$id) {
+/**
+ * @brief Format the like/dislike text for a profile item.
+ *
+ * @param int $cnt number of people who like/dislike the item
+ * @param array $arr array of pre-linked names of likers/dislikers
+ * @param string $type one of 'like, 'dislike'
+ * @param int $id item id
+ * @return string formatted text
+ */
+function format_like($cnt, $arr, $type, $id) {
$o = '';
- if($cnt == 1)
+ if ($cnt == 1) {
$o .= (($type === 'like') ? sprintf( t('%s likes this.'), $arr[0]) : sprintf( t('%s doesn\'t like this.'), $arr[0])) . EOL ;
- else {
+ } else {
$spanatts = 'class="fakelink" onclick="openClose(\'' . $type . 'list-' . $id . '\');"';
$o .= (($type === 'like') ?
sprintf( tt('<span %1$s>%2$d people</span> like this.','<span %1$s>%2$d people</span> like this.',$cnt), $spanatts, $cnt)
:
sprintf( tt('<span %1$s>%2$d people</span> don\'t like this.','<span %1$s>%2$d people</span> don\'t like this.',$cnt), $spanatts, $cnt) );
- $o .= EOL ;
+ $o .= EOL;
$total = count($arr);
if($total >= MAX_LIKERS)
$arr = array_slice($arr, 0, MAX_LIKERS - 1);
@@ -1050,11 +1069,12 @@ function format_like($cnt,$arr,$type,$id) {
$str = (($type === 'like') ? sprintf( t('%s like this.'), $str) : sprintf( t('%s don\'t like this.'), $str));
$o .= "\t" . '<div id="' . $type . 'list-' . $id . '" style="display: none;" >' . $str . '</div>';
}
+
return $o;
}
-function status_editor($a,$x,$popup=false) {
+function status_editor($a, $x, $popup = false) {
$o = '';
@@ -1065,26 +1085,28 @@ function status_editor($a,$x,$popup=false) {
// if(feature_enabled(local_channel(),'richtext'))
// $plaintext = false;
+ $voting = feature_enabled(local_channel(), 'consensus_tools');
+
$mimeselect = '';
- if(array_key_exists('mimetype',$x) && $x['mimetype']) {
+ if(array_key_exists('mimetype', $x) && $x['mimetype']) {
if($x['mimetype'] != 'text/bbcode')
$plaintext = true;
- if($x['mimetype'] === 'choose') {
+ if($x['mimetype'] === 'choose') {
$mimeselect = mimetype_select($x['profile_uid']);
}
else
- $mimeselect = '<input type="hidden" name="mimetype" value="' . $x['mimetype'] . '" />';
+ $mimeselect = '<input type="hidden" name="mimetype" value="' . $x['mimetype'] . '" />';
}
$layoutselect = '';
- if(array_key_exists('layout',$x) && $x['layout']) {
+ if(array_key_exists('layout', $x) && $x['layout']) {
if($x['layout'] === 'choose') {
$layoutselect = layout_select($x['profile_uid']);
}
else
- $layoutselect = '<input type="hidden" name="layout_mid" value="' . $x['layout'] . '" />';
+ $layoutselect = '<input type="hidden" name="layout_mid" value="' . $x['layout'] . '" />';
}
-
+
if(array_key_exists('channel_select',$x) && $x['channel_select']) {
require_once('include/identity.php');
@@ -1097,7 +1119,7 @@ function status_editor($a,$x,$popup=false) {
$webpage = ((x($x,'webpage')) ? $x['webpage'] : '');
$tpl = get_markup_template('jot-header.tpl');
-
+
$a->page['htmlhead'] .= replace_macros($tpl, array(
'$newpost' => 'true',
'$baseurl' => $a->get_baseurl(true),
@@ -1106,44 +1128,50 @@ function status_editor($a,$x,$popup=false) {
'$nickname' => $x['nickname'],
'$ispublic' => t('Visible to <strong>everybody</strong>'),
'$linkurl' => t('Please enter a link URL:'),
- '$vidurl' => t("Please enter a video link/URL:"),
- '$audurl' => t("Please enter an audio link/URL:"),
+ '$vidurl' => t('Please enter a video link/URL:'),
+ '$audurl' => t('Please enter an audio link/URL:'),
'$term' => t('Tag term:'),
'$fileas' => t('Save to Folder:'),
'$whereareu' => t('Where are you right now?'),
'$expireswhen' => t('Expires YYYY-MM-DD HH:MM')
));
-
- $tpl = get_markup_template("jot.tpl");
+ $tpl = get_markup_template('jot.tpl');
$jotplugins = '';
$jotnets = '';
$preview = t('Preview');
// $preview = ((feature_enabled($x['profile_uid'],'preview')) ? t('Preview') : '');
- if(x($x,'nopreview'))
+ if(x($x, 'nopreview'))
$preview = '';
- $defexpire = ((($z = get_pconfig($x['profile_uid'],'system','default_post_expire')) && (! $webpage)) ? $z : '');
-
+ $defexpire = ((($z = get_pconfig($x['profile_uid'], 'system', 'default_post_expire')) && (! $webpage)) ? $z : '');
+ if($defexpire)
+ $defexpire = datetime_convert('UTC',date_default_timezone_get(),$defexpire,'Y-m-d H:i');
- $cipher = get_pconfig($x['profile_uid'],'system','default_cipher');
+ $cipher = get_pconfig($x['profile_uid'], 'system', 'default_cipher');
if(! $cipher)
$cipher = 'aes256';
call_hooks('jot_tool', $jotplugins);
call_hooks('jot_networks', $jotnets);
- $o .= replace_macros($tpl,array(
- '$return_path' => ((x($x,'return_path')) ? $x['return_path'] : $a->query_string),
+ $o .= replace_macros($tpl, array(
+ '$return_path' => ((x($x, 'return_path')) ? $x['return_path'] : $a->query_string),
'$action' => $a->get_baseurl(true) . '/item',
'$share' => (x($x,'button') ? $x['button'] : t('Share')),
'$webpage' => $webpage,
- '$placeholdpagetitle' => ((x($x,'ptlabel')) ? $x['ptlabel'] : t('Page link title')),
- '$pagetitle' => (x($x,'pagetitle') ? $x['pagetitle'] : ''),
+ '$placeholdpagetitle' => ((x($x,'ptlabel')) ? $x['ptlabel'] : t('Page link name')),
+ '$pagetitle' => (x($x,'pagetitle') ? $x['pagetitle'] : ''),
'$id_select' => $id_select,
'$id_seltext' => t('Post as'),
+ '$writefiles' => (perm_is_allowed($x['profile_uid'], get_observer_hash(), 'post_photos') || perm_is_allowed($x['profile_uid'], get_observer_hash(), 'write_storage')),
+ '$bold' => t('Bold'),
+ '$italic' => t('Italic'),
+ '$underline' => t('Underline'),
+ '$quote' => t('Quote'),
+ '$code' => t('Code'),
'$upload' => t('Upload photo'),
'$shortupload' => t('upload photo'),
'$attach' => t('Attach file'),
@@ -1156,11 +1184,14 @@ function status_editor($a,$x,$popup=false) {
'$shortaudio' => t('audio link'),
'$setloc' => t('Set your location'),
'$shortsetloc' => t('set location'),
- '$noloc' => ((get_pconfig($x['profile_uid'],'system','use_browser_location')) ? t('Clear browser location') : ''),
+ '$voting' => t('Toggle voting'),
+ '$feature_voting' => $voting,
+ '$consensus' => 0,
+ '$noloc' => ((get_pconfig($x['profile_uid'], 'system', 'use_browser_location')) ? t('Clear browser location') : ''),
'$shortnoloc' => t('clear location'),
- '$title' => ((x($x,'title')) ? htmlspecialchars($x['title'], ENT_COMPAT,'UTF-8') : ''),
+ '$title' => ((x($x, 'title')) ? htmlspecialchars($x['title'], ENT_COMPAT,'UTF-8') : ''),
'$placeholdertitle' => t('Title (optional)'),
- '$catsenabled' => ((feature_enabled($x['profile_uid'],'categories') && (! $webpage)) ? 'categories' : ''),
+ '$catsenabled' => ((feature_enabled($x['profile_uid'], 'categories') && (! $webpage)) ? 'categories' : ''),
'$category' => "",
'$placeholdercategory' => t('Categories (optional, comma-separated list)'),
'$wait' => t('Please wait'),
@@ -1168,6 +1199,7 @@ function status_editor($a,$x,$popup=false) {
'$shortpermset' => t('permissions'),
'$ptyp' => (($notes_cid) ? 'note' : 'wall'),
'$content' => ((x($x,'body')) ? htmlspecialchars($x['body'], ENT_COMPAT,'UTF-8') : ''),
+ '$attachment' => ((x($x, 'attachment')) ? $x['attachment'] : ''),
'$post_id' => '',
'$baseurl' => $a->get_baseurl(true),
'$defloc' => $x['default_location'],
@@ -1179,26 +1211,25 @@ function status_editor($a,$x,$popup=false) {
'$acl' => $x['acl'],
'$mimeselect' => $mimeselect,
'$layoutselect' => $layoutselect,
- '$showacl' => ((array_key_exists('showacl',$x)) ? $x['showacl'] : true),
+ '$showacl' => ((array_key_exists('showacl', $x)) ? $x['showacl'] : true),
'$bang' => $x['bang'],
'$profile_uid' => $x['profile_uid'],
'$preview' => $preview,
- '$source' => ((x($x,'source')) ? $x['source'] : ''),
+ '$source' => ((x($x, 'source')) ? $x['source'] : ''),
'$jotplugins' => $jotplugins,
'$defexpire' => $defexpire,
- '$feature_expire' => ((feature_enabled($x['profile_uid'],'content_expire') && (! $webpage)) ? true : false),
+ '$feature_expire' => ((feature_enabled($x['profile_uid'], 'content_expire') && (! $webpage)) ? true : false),
'$expires' => t('Set expiration date'),
- '$feature_encrypt' => ((feature_enabled($x['profile_uid'],'content_encrypt') && (! $webpage)) ? true : false),
+ '$feature_encrypt' => ((feature_enabled($x['profile_uid'], 'content_encrypt') && (! $webpage)) ? true : false),
'$encrypt' => t('Encrypt text'),
'$cipher' => $cipher,
'$expiryModalOK' => t('OK'),
- '$expiryModalCANCEL' => t('Cancel')
+ '$expiryModalCANCEL' => t('Cancel'),
+ '$expanded' => ((x($x, 'expanded')) ? $x['expanded'] : false),
));
-
- if ($popup==true){
- $o = '<div id="jot-popup" style="display: none;">'.$o.'</div>';
-
+ if ($popup === true) {
+ $o = '<div id="jot-popup" style="display:none">' . $o . '</div>';
}
return $o;
@@ -1247,13 +1278,12 @@ function add_children_to_list($children, &$arr) {
}
}
-function conv_sort($arr,$order) {
+function conv_sort($arr, $order) {
if((!(is_array($arr) && count($arr))))
return array();
$parents = array();
- $children = array();
foreach($arr as $x)
if($x['id'] == $x['parent'])
@@ -1308,6 +1338,7 @@ function find_thread_parent_index($arr,$x) {
foreach($arr as $k => $v)
if($v['id'] == $x['parent'])
return $k;
+
return false;
}
@@ -1336,11 +1367,11 @@ function render_location_default($item) {
else
$location = '<span class="smalltext">' . $coord . '</span>';
}
+
return $location;
}
-
function prepare_page($item) {
$a = get_app();
$naked = ((get_pconfig($item['uid'],'system','nakedpage')) ? 1 : 0);
@@ -1357,14 +1388,15 @@ function prepare_page($item) {
// prepare_body calls unobscure() as a side effect. Do it here so that
// the template will get passed an unobscured title.
- $body = prepare_body($item,true);
- $tpl = get_pconfig($item['uid'],'system','pagetemplate');
- if (! $tpl)
- $tpl = 'page_display.tpl';
- return replace_macros(get_markup_template($tpl),array(
+ $body = prepare_body($item, true);
+ $tpl = get_pconfig($item['uid'], 'system', 'pagetemplate');
+ if (! $tpl)
+ $tpl = 'page_display.tpl';
+
+ return replace_macros(get_markup_template($tpl), array(
'$author' => (($naked) ? '' : $item['author']['xchan_name']),
'$auth_url' => (($naked) ? '' : zid($item['author']['xchan_url'])),
- '$date' => (($naked) ? '' : datetime_convert('UTC',date_default_timezone_get(),$item['created'],'Y-m-d H:i')),
+ '$date' => (($naked) ? '' : datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'Y-m-d H:i')),
'$title' => smilies(bbcode($item['title'])),
'$body' => $body,
'$preview' => $preview,
@@ -1388,15 +1420,15 @@ function network_tabs() {
if(x($_GET,'new')) {
$new_active = 'active';
}
-
+
if(x($_GET,'search')) {
$search_active = 'active';
}
-
+
if(x($_GET,'star')) {
$starred_active = 'active';
}
-
+
if(x($_GET,'conv')) {
$conv_active = 'active';
}
@@ -1409,8 +1441,6 @@ function network_tabs() {
$public_active = 'active';
}
-
-
if (($new_active == '')
&& ($starred_active == '')
&& ($conv_active == '')
@@ -1422,11 +1452,11 @@ 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;
}
}
-
+
if ($no_active=='active') $all_active='active';
$cmd = $a->cmd;
@@ -1437,22 +1467,22 @@ function network_tabs() {
if(! get_config('system','disable_discover_tab')) {
$tabs[] = array(
'label' => t('Discover'),
- 'url'=>z_root() . '/' . $cmd . '?f=&fh=1' ,
- 'sel'=> $public_active,
- 'title'=> t('Imported public streams'),
+ 'url' => z_root() . '/' . $cmd . '?f=&fh=1' ,
+ 'sel' => $public_active,
+ 'title' => t('Imported public streams'),
);
}
$tabs[] = array(
'label' => t('Commented Order'),
- 'url'=>z_root() . '/' . $cmd . '?f=&order=comment' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : '') . ((x($_GET,'gid')) ? '&gid=' . $_GET['gid'] : ''),
+ 'url'=>z_root() . '/' . $cmd . '?f=&order=comment' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : '') . ((x($_GET,'gid')) ? '&gid=' . $_GET['gid'] : ''),
'sel'=>$all_active,
'title'=> t('Sort by Comment Date'),
);
-
+
$tabs[] = array(
'label' => t('Posted Order'),
- 'url'=>z_root() . '/' . $cmd . '?f=&order=post' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : '') . ((x($_GET,'gid')) ? '&gid=' . $_GET['gid'] : ''),
+ 'url'=>z_root() . '/' . $cmd . '?f=&order=post' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : '') . ((x($_GET,'gid')) ? '&gid=' . $_GET['gid'] : ''),
'sel'=>$postord_active,
'title' => t('Sort by Post Date'),
);
@@ -1466,7 +1496,7 @@ function network_tabs() {
);
}
- if(feature_enabled(local_channel(),'new_tab')) {
+ if(feature_enabled(local_channel(),'new_tab')) {
$tabs[] = array(
'label' => t('New'),
'url' => z_root() . '/' . $cmd . '?f=' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : '') . '&new=1' . ((x($_GET,'gid')) ? '&gid=' . $_GET['gid'] : ''),
@@ -1492,39 +1522,43 @@ function network_tabs() {
'sel'=> $spam_active,
'title' => t('Posts flagged as SPAM'),
);
- }
+ }
$arr = array('tabs' => $tabs);
call_hooks('network_tabs', $arr);
$tpl = get_markup_template('common_tabs.tpl');
- return replace_macros($tpl,array('$tabs' => $arr['tabs']));
-
+ return replace_macros($tpl, array('$tabs' => $arr['tabs']));
}
-
-
-function profile_tabs($a, $is_owner=False, $nickname=Null){
+/**
+ * @brief
+ *
+ * @param App $a
+ * @param boolean $is_owner default false
+ * @param string $nickname default null
+ * @return void|string
+ */
+function profile_tabs($a, $is_owner = false, $nickname = null){
// Don't provide any profile tabs if we're running as the sys channel
-
- if($a->is_sys)
+ if ($a->is_sys)
return;
-
+
$channel = $a->get_channel();
if (is_null($nickname))
$nickname = $channel['channel_address'];
$uid = (($a->profile['profile_uid']) ? $a->profile['profile_uid'] : local_channel());
-
- if (get_pconfig($uid,'system','noprofiletabs'))
+
+ if (get_pconfig($uid, 'system', 'noprofiletabs'))
return;
-
- if(x($_GET,'tab'))
+
+ if (x($_GET, 'tab'))
$tab = notags(trim($_GET['tab']));
-
+
$url = $a->get_baseurl() . '/channel/' . $nickname;
$pr = $a->get_baseurl() . '/profile/' . $nickname;
@@ -1540,42 +1574,42 @@ function profile_tabs($a, $is_owner=False, $nickname=Null){
$p = get_all_perms($uid,get_observer_hash());
- if($p['view_profile']) {
+ if ($p['view_profile']) {
$tabs[] = array(
'label' => t('About'),
- 'url' => $pr,
- 'sel' => ((argv(0) == 'profile') ? 'active' : ''),
+ 'url' => $pr,
+ 'sel' => ((argv(0) == 'profile') ? 'active' : ''),
'title' => t('Profile Details'),
'id' => 'profile-tab',
);
}
- if($p['view_photos']) {
+ if ($p['view_photos']) {
$tabs[] = array(
'label' => t('Photos'),
- 'url' => $a->get_baseurl() . '/photos/' . $nickname,
- 'sel' => ((argv(0) == 'photos') ? 'active' : ''),
+ 'url' => $a->get_baseurl() . '/photos/' . $nickname,
+ 'sel' => ((argv(0) == 'photos') ? 'active' : ''),
'title' => t('Photo Albums'),
'id' => 'photo-tab',
);
}
- if($p['view_storage']) {
+ if ($p['view_storage']) {
$tabs[] = array(
'label' => t('Files'),
- 'url' => $a->get_baseurl() . '/cloud/' . $nickname . ((get_observer_hash()) ? '' : '?f=&davguest=1'),
- 'sel' => ((argv(0) == 'cloud' || argv(0) == 'sharedwithme') ? 'active' : ''),
+ 'url' => $a->get_baseurl() . '/cloud/' . $nickname . ((get_observer_hash()) ? '' : '?f=&davguest=1'),
+ 'sel' => ((argv(0) == 'cloud' || argv(0) == 'sharedwithme') ? 'active' : ''),
'title' => t('Files and Storage'),
'id' => 'files-tab',
);
}
- if($p['chat']) {
+ if ($p['chat']) {
require_once('include/chat.php');
$has_chats = chatroom_list_count($uid);
if ($has_chats) {
$tabs[] = array(
'label' => t('Chatrooms'),
- 'url' => $a->get_baseurl() . '/chat/' . $nickname,
- 'sel' => ((argv(0) == 'chat') ? 'active' : '' ),
+ 'url' => $a->get_baseurl() . '/chat/' . $nickname,
+ 'sel' => ((argv(0) == 'chat') ? 'active' : '' ),
'title' => t('Chatrooms'),
'id' => 'chat-tab',
);
@@ -1584,33 +1618,29 @@ function profile_tabs($a, $is_owner=False, $nickname=Null){
require_once('include/menu.php');
$has_bookmarks = menu_list_count(local_channel(),'',MENU_BOOKMARK) + menu_list_count(local_channel(),'',MENU_SYSTEM|MENU_BOOKMARK);
- if($is_owner && $has_bookmarks) {
+ if ($is_owner && $has_bookmarks) {
$tabs[] = array(
'label' => t('Bookmarks'),
- 'url' => $a->get_baseurl() . '/bookmarks',
- 'sel' => ((argv(0) == 'bookmarks') ? 'active' : ''),
+ 'url' => $a->get_baseurl() . '/bookmarks',
+ 'sel' => ((argv(0) == 'bookmarks') ? 'active' : ''),
'title' => t('Saved Bookmarks'),
'id' => 'bookmarks-tab',
);
}
-
- if($is_owner && feature_enabled($uid,'webpages')) {
+ if ($p['write_pages'] && feature_enabled($uid,'webpages')) {
$tabs[] = array(
'label' => t('Webpages'),
- 'url' => $a->get_baseurl() . '/webpages/' . $nickname,
- 'sel' => ((argv(0) == 'webpages') ? 'active' : ''),
+ 'url' => $a->get_baseurl() . '/webpages/' . $nickname,
+ 'sel' => ((argv(0) == 'webpages') ? 'active' : ''),
'title' => t('Manage Webpages'),
'id' => 'webpages-tab',
);
- }
-
- else {
- // FIXME
- // we probably need a listing of events that were created by
- // this channel and are visible to the observer
-
-
+ } else {
+ /**
+ * @FIXME we probably need a listing of events that were created by
+ * this channel and are visible to the observer
+ */
}
$arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
@@ -1620,3 +1650,67 @@ function profile_tabs($a, $is_owner=False, $nickname=Null){
return replace_macros($tpl,array('$tabs' => $arr['tabs']));
}
+
+
+function get_responses($conv_responses,$response_verbs,$ob,$item) {
+
+ $ret = array();
+ foreach($response_verbs as $v) {
+ $ret[$v] = array();
+ $ret[$v]['count'] = ((x($conv_responses[$v],$item['mid'])) ? $conv_responses[$v][$item['mid']] : '');
+ $ret[$v]['list'] = ((x($conv_responses[$v],$item['mid'])) ? $conv_responses[$v][$item['mid'] . '-l'] : '');
+ if(count($ret[$v]['list']) > MAX_LIKERS) {
+ $ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS);
+ array_push($ret[$v]['list_part'], '<a href="#" data-toggle="modal" data-target="#' . $v . 'Modal-'
+ . (($ob) ? $ob->get_id() : $item['id']) . '"><b>' . t('View all') . '</b></a>');
+ } else {
+ $ret[$v]['list_part'] = '';
+ }
+ $ret[$v]['button'] = get_response_button_text($v,$ret[$v]['count']);
+ $ret[$v]['title'] = $conv_responses[$v]['title'];
+ }
+
+ $count = 0;
+ foreach ($ret as $key) {
+ if ($key['count'] == true)
+ $count++;
+ }
+
+ $ret['count'] = $count;
+
+//logger('ret: ' . print_r($ret,true));
+
+ return $ret;
+}
+
+function get_response_button_text($v,$count) {
+ switch($v) {
+ case 'like':
+ return tt('Like','Likes',$count,'noun');
+ break;
+ case 'dislike':
+ return tt('Dislike','Dislikes',$count,'noun');
+ break;
+ case 'attendyes':
+ return tt('Attending','Attending',$count,'noun');
+ break;
+ case 'attendno':
+ return tt('Not Attending','Not Attending',$count,'noun');
+ break;
+ case 'attendmaybe':
+ return tt('Undecided','Undecided',$count,'noun');
+ break;
+ case 'agree':
+ return tt('Agree','Agrees',$count,'noun');
+ break;
+ case 'disagree':
+ return tt('Disagree','Disagrees',$count,'noun');
+ break;
+ case 'abstain':
+ return tt('Abstain','Abstains',$count,'noun');
+ break;
+ default:
+ return '';
+ break;
+ }
+}
diff --git a/include/crypto.php b/include/crypto.php
index ab083cfaa..a4ce2cf98 100644
--- a/include/crypto.php
+++ b/include/crypto.php
@@ -300,7 +300,6 @@ function salmon_key($pubkey) {
// used in Friendica 'RINO'. This function is messy and should be retired.
-if(! function_exists('aes_decrypt')) {
function aes_decrypt($val,$ky)
{
$key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
@@ -310,10 +309,10 @@ function aes_decrypt($val,$ky)
$enc = MCRYPT_RIJNDAEL_128;
$dec = @mcrypt_decrypt($enc, $key, $val, $mode, @mcrypt_create_iv( @mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM ) );
return rtrim($dec,(( ord(substr($dec,strlen($dec)-1,1))>=0 and ord(substr($dec, strlen($dec)-1,1))<=16)? chr(ord( substr($dec,strlen($dec)-1,1))):null));
-}}
+}
+
-if(! function_exists('aes_encrypt')) {
function aes_encrypt($val,$ky)
{
$key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
@@ -323,6 +322,14 @@ function aes_encrypt($val,$ky)
$enc=MCRYPT_RIJNDAEL_128;
$val=str_pad($val, (16*(floor(strlen($val) / 16)+(strlen($val) % 16==0?2:1))), chr(16-(strlen($val) % 16)));
return mcrypt_encrypt($enc, $key, $val, $mode, mcrypt_create_iv( mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM));
-}}
+}
+function z_obscure($s) {
+ return json_encode(crypto_encapsulate($s,get_config('system','pubkey')));
+}
+function z_unobscure($s) {
+ if(strpos($s,"{\"") !== 0)
+ return $s;
+ return crypto_unencapsulate(json_decode($s,true),get_config('system','prvkey'));
+}
diff --git a/include/datetime.php b/include/datetime.php
index a387d84c4..b0167edb2 100644
--- a/include/datetime.php
+++ b/include/datetime.php
@@ -1,54 +1,71 @@
-<?php /** @file */
-
-// two-level sort for timezones.
+<?php
+/**
+ * @file include/datetime.php
+ * @brief Some functions for date and time related tasks.
+ */
+/**
+ * @brief Two-level sort for timezones.
+ *
+ * @param string $a
+ * @param string $b
+ * @return number
+ */
function timezone_cmp($a, $b) {
if(strstr($a,'/') && strstr($b,'/')) {
if ( t($a) == t($b)) return 0;
return ( t($a) < t($b)) ? -1 : 1;
}
- if(strstr($a,'/')) return -1;
- if(strstr($b,'/')) return 1;
+ if (strstr($a,'/')) return -1;
+ if (strstr($b,'/')) return 1;
if ( t($a) == t($b)) return 0;
+
return ( t($a) < t($b)) ? -1 : 1;
}
-// Return timezones grouped (primarily) by continent
+/**
+ * @brief Return timezones grouped (primarily) by continent.
+ *
+ * @return array
+ */
function get_timezones( ){
$timezone_identifiers = DateTimeZone::listIdentifiers();
usort($timezone_identifiers, 'timezone_cmp');
$continent = '';
$continents = array();
- foreach($timezone_identifiers as $value) {
+ foreach ($timezone_identifiers as $value) {
$ex = explode("/", $value);
- if(count($ex) > 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,21 +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) {
- // Once browser support is better this could probably be replaced with native HTML5 date picker
- $o = '';
+function datetimesel($format, $min, $max, $default, $id = 'datetimepicker', $pickdate = true, $picktime = true, $minfrom = '', $maxfrom = '', $required = false) {
+ $o = '';
$dateformat = '';
if($pickdate) $dateformat .= 'Y-m-d';
@@ -186,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)" : '';
@@ -212,31 +235,39 @@ function datetimesel($format, $min, $max, $default, $id = 'datetimepicker', $pic
$o .= (($required) ? '<span class="required" title="' . t('Required') . '" >*</span>' : '');
$o .= '</div>';
$o .= "<script type='text/javascript'>\$(function () {var picker = \$('#$id').datetimepicker({step:5,format:'$dateformat' $minjs $maxjs $pickers $defaultdatejs}); $extra_js})</script>";
+
return $o;
}
-// implements "3 seconds ago" etc.
-// based on $posted_date, (UTC).
-// Results relative to current timezone
-// Limited to range of timestamps
-
-
-function relative_date($posted_date,$format = null) {
+/**
+ * @brief Returns a relative date string.
+ *
+ * Implements "3 seconds ago" etc.
+ * Based on $posted_date, (UTC).
+ * Results relative to current timezone.
+ * Limited to range of timestamps.
+ *
+ * @param string $posted_date
+ * @param string $format (optional) parsed with sprintf()
+ * <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
+ * @return string with relative date
+ */
+function relative_date($posted_date, $format = null) {
- $localtime = datetime_convert('UTC',date_default_timezone_get(),$posted_date);
+ $localtime = datetime_convert('UTC', date_default_timezone_get(), $posted_date);
$abs = strtotime($localtime);
-
- if (is_null($posted_date) || $posted_date === NULL_DATE || $abs === False) {
- return t('never');
+
+ if (is_null($posted_date) || $posted_date === NULL_DATE || $abs === false) {
+ return t('never');
}
$etime = time() - $abs;
-
+
if ($etime < 1) {
return t('less than a second ago');
}
-
+
$a = array( 12 * 30 * 24 * 60 * 60 => array( t('year'), t('years')),
30 * 24 * 60 * 60 => array( t('month'), t('months')),
7 * 24 * 60 * 60 => array( t('week'), t('weeks')),
@@ -245,231 +276,256 @@ function relative_date($posted_date,$format = null) {
60 => array( t('minute'), t('minutes')),
1 => array( t('second'), t('seconds'))
);
-
+
foreach ($a as $secs => $str) {
$d = $etime / $secs;
if ($d >= 1) {
$r = round($d);
- // translators - e.g. 22 hours ago, 1 minute ago
- if(! $format)
- $format = t('%1$d %2$s ago');
- return sprintf( $format,$r, (($r == 1) ? $str[0] : $str[1]));
- }
- }
-}
-
+ if (! $format)
+ $format = t('%1$d %2$s ago', 'e.g. 22 hours ago, 1 minute ago');
+ return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
+ }
+ }
+}
-// Returns age in years, given a date of birth,
-// the timezone of the person whose date of birth is provided,
-// and the timezone of the person viewing the result.
-// Why? Bear with me. Let's say I live in Mittagong, Australia, and my
-// birthday is on New Year's. You live in San Bruno, California.
-// When exactly are you going to see my age increase?
-// A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start
-// celebrating and become a year older. If you wish me happy birthday
-// on January 1 (San Bruno time), you'll be a day late.
-
-function age($dob,$owner_tz = '',$viewer_tz = '') {
- if(! intval($dob))
+/**
+ * @brief Returns timezone correct age in years.
+ *
+ * Returns the age in years, given a date of birth, the timezone of the person
+ * whose date of birth is provided, and the timezone of the person viewing the
+ * result.
+ *
+ * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
+ * is on New Year's. You live in San Bruno, California.
+ * When exactly are you going to see my age increase?
+ *
+ * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
+ * and become a year older. If you wish me happy birthday on January 1
+ * (San Bruno time), you'll be a day late.
+ *
+ * @param string $dob Date of Birth
+ * @param string $owner_tz (optional) timezone of the person of interest
+ * @param string $viewer_tz (optional) timezone of the person viewing
+ * @return number
+ */
+function age($dob, $owner_tz = '', $viewer_tz = '') {
+ if (! intval($dob))
return 0;
- if(! $owner_tz)
+ if (! $owner_tz)
$owner_tz = date_default_timezone_get();
- if(! $viewer_tz)
+ if (! $viewer_tz)
$viewer_tz = date_default_timezone_get();
- $birthdate = datetime_convert('UTC',$owner_tz,$dob . ' 00:00:00+00:00','Y-m-d');
- list($year,$month,$day) = explode("-",$birthdate);
- $year_diff = datetime_convert('UTC',$viewer_tz,'now','Y') - $year;
- $curr_month = datetime_convert('UTC',$viewer_tz,'now','m');
- $curr_day = datetime_convert('UTC',$viewer_tz,'now','d');
+ $birthdate = datetime_convert('UTC', $owner_tz, $dob . ' 00:00:00+00:00','Y-m-d');
+ list($year,$month,$day) = explode("-", $birthdate);
+ $year_diff = datetime_convert('UTC', $viewer_tz, 'now', 'Y') - $year;
+ $curr_month = datetime_convert('UTC', $viewer_tz, 'now', 'm');
+ $curr_day = datetime_convert('UTC', $viewer_tz, 'now', 'd');
- if(($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day)))
+ if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day)))
$year_diff--;
+
return $year_diff;
}
+/**
+ * @brief Get days of a month in a given year.
+ *
+ * Returns number of days in the month of the given year.
+ * $m = 1 is 'January' to match human usage.
+ *
+ * @param int $y year
+ * @param int $m month (1=January, 12=December)
+ * @return int number of days in the given month
+ */
+function get_dim($y, $m) {
+ $dim = array( 0,
+ 31, 28, 31, 30, 31, 30,
+ 31, 31, 30, 31, 30, 31
+ );
+ if ($m != 2)
+ return $dim[$m];
-// Get days in month
-// get_dim($year, $month);
-// returns number of days.
-// $month[1] = 'January';
-// to match human usage.
-
-
-function get_dim($y,$m) {
+ if (((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0))
+ return 29;
- $dim = array( 0,
- 31, 28, 31, 30, 31, 30,
- 31, 31, 30, 31, 30, 31);
-
- if($m != 2)
- return $dim[$m];
- if(((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0))
- return 29;
- return $dim[2];
+ return $dim[2];
}
+/**
+ * @brief Returns the first day in month for a given month, year.
+ *
+ * Months start at 1.
+ *
+ * @param int $y Year
+ * @param int $m Month (1=January, 12=December)
+ * @return day 0 = Sunday through 6 = Saturday
+ */
+function get_first_dim($y, $m) {
+ $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
-// Returns the first day in month for a given month, year
-// get_first_dim($year,$month)
-// returns 0 = Sunday through 6 = Saturday
-// Months start at 1.
-
-
-function get_first_dim($y,$m) {
- $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
- return datetime_convert('UTC','UTC',$d,'w');
+ return datetime_convert('UTC', 'UTC', $d, 'w');
}
-// output a calendar for the given month, year.
-// if $links are provided (array), e.g. $links[12] => 'http://mylink' ,
-// date 12 will be linked appropriately. Today's date is also noted by
-// altering td class.
-// Months count from 1.
-
-
-// TODO: provide (prev,next) links, define class variations for different size calendars
-
-function cal($y = 0,$m = 0, $links = false, $class='') {
-
+/**
+ * @brief Output a calendar for the given month, year.
+ *
+ * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
+ * date 12 will be linked appropriately. Today's date is also noted by
+ * altering td class.
+ * Months count from 1.
+ *
+ * @param number $y Year
+ * @param number $m Month
+ * @param string $links (default false)
+ * @param string $class
+ * @return string
+ *
+ * @todo provide (prev,next) links, define class variations for different size calendars
+ */
+function cal($y = 0, $m = 0, $links = false, $class='') {
// month table - start at 1 to match human usage.
$mtab = array(' ',
- 'January','February','March',
- 'April','May','June',
- 'July','August','September',
- 'October','November','December'
- );
+ 'January','February','March',
+ 'April','May','June',
+ 'July','August','September',
+ 'October','November','December'
+ );
$thisyear = datetime_convert('UTC',date_default_timezone_get(),'now','Y');
$thismonth = datetime_convert('UTC',date_default_timezone_get(),'now','m');
- if(! $y)
+ if (! $y)
$y = $thisyear;
- if(! $m)
+ if (! $m)
$m = intval($thismonth);
- $dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
- $f = get_first_dim($y,$m);
- $l = get_dim($y,$m);
- $d = 1;
- $dow = 0;
- $started = false;
+ $dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
+ $f = get_first_dim($y, $m);
+ $l = get_dim($y, $m);
+ $d = 1;
+ $dow = 0;
+ $started = false;
- if(($y == $thisyear) && ($m == $thismonth))
- $tddate = intval(datetime_convert('UTC',date_default_timezone_get(),'now','j'));
+ if (($y == $thisyear) && ($m == $thismonth))
+ $tddate = intval(datetime_convert('UTC',date_default_timezone_get(),'now','j'));
$str_month = day_translate($mtab[$m]);
- $o = '<table class="calendar' . $class . '">';
- $o .= "<caption>$str_month $y</caption><tr>";
- for($a = 0; $a < 7; $a ++)
- $o .= '<th>' . mb_substr(day_translate($dn[$a]),0,3,'UTF-8') . '</th>';
- $o .= '</tr><tr>';
-
- while($d <= $l) {
- if(($dow == $f) && (! $started))
- $started = true;
- $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
- $o .= "<td $today>";
- $day = str_replace(' ','&nbsp;',sprintf('%2.2d', $d));
- if($started) {
- if(is_array($links) && isset($links[$d]))
- $o .= "<a href=\"{$links[$d]}\">$day</a>";
- else
- $o .= $day;
- $d ++;
- }
- else
- $o .= '&nbsp;';
- $o .= '</td>';
- $dow ++;
- if(($dow == 7) && ($d <= $l)) {
- $dow = 0;
- $o .= '</tr><tr>';
- }
- }
- if($dow)
- for($a = $dow; $a < 7; $a ++)
- $o .= '<td>&nbsp;</td>';
- $o .= '</tr></table>'."\r\n";
-
- return $o;
-}
+ $o = '<table class="calendar' . $class . '">';
+ $o .= "<caption>$str_month $y</caption><tr>";
+ for ($a = 0; $a < 7; $a ++)
+ $o .= '<th>' . mb_substr(day_translate($dn[$a]),0,3,'UTF-8') . '</th>';
+
+ $o .= '</tr><tr>';
+
+ while ($d <= $l) {
+ if (($dow == $f) && (! $started))
+ $started = true;
+
+ $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
+ $o .= "<td $today>";
+ $day = str_replace(' ','&nbsp;',sprintf('%2.2d', $d));
+ if ($started) {
+ if (is_array($links) && isset($links[$d]))
+ $o .= "<a href=\"{$links[$d]}\">$day</a>";
+ else
+ $o .= $day;
+
+ $d ++;
+ } else {
+ $o .= '&nbsp;';
+ }
+
+ $o .= '</td>';
+ $dow ++;
+ if (($dow == 7) && ($d <= $l)) {
+ $dow = 0;
+ $o .= '</tr><tr>';
+ }
+ }
+ if ($dow)
+ for ($a = $dow; $a < 7; $a ++)
+ $o .= '<td>&nbsp;</td>';
+
+ $o .= '</tr></table>'."\r\n";
+ return $o;
+}
/**
- * Return the next birthday, converted from the owner's timezone to UTC.
+ * @brief Return the next birthday, converted from the owner's timezone to UTC.
+ *
* This makes it globally portable.
* If the provided birthday lacks a month and or day, return an empty string.
* A missing year is acceptable.
+ *
+ * @param string $dob Date of Birth
+ * @param string $tz Timezone
+ * @param string $format
+ * @return string
*/
+function z_birthday($dob, $tz, $format="Y-m-d H:i:s") {
-
-function z_birthday($dob,$tz,$format="Y-m-d H:i:s") {
-
- if(! strlen($tz))
+ if (! strlen($tz))
$tz = 'UTC';
$birthday = '';
$tmp_dob = substr($dob,5);
$tmp_d = substr($dob,8);
- if(intval($tmp_dob) && intval($tmp_d)) {
+ if (intval($tmp_dob) && intval($tmp_d)) {
$y = datetime_convert($tz,$tz,'now','Y');
$bd = $y . '-' . $tmp_dob . ' 00:00';
$t_dob = strtotime($bd);
$now = strtotime(datetime_convert($tz,$tz,'now'));
- if($t_dob < $now)
+ if ($t_dob < $now)
$bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
+
$birthday = datetime_convert($tz,'UTC',$bd,$format);
}
return $birthday;
-
}
/**
+ * @brief Create a birthday event for any connections with a birthday in the next 1-2 weeks.
*
- * Create a birthday event for any connections with a birthday in the next 1-2 weeks.
* Update the year so that we don't create another event until next year.
- *
*/
-
-
function update_birthdays() {
require_once('include/event.php');
require_once('include/permissions.php');
- $r = q("SELECT * FROM abook left join xchan on abook_xchan = xchan_hash
+ $r = q("SELECT * FROM abook left join xchan on abook_xchan = xchan_hash
WHERE abook_dob > %s + interval %s and abook_dob < %s + interval %s",
db_utcnow(), db_quoteinterval('7 day'),
db_utcnow(), db_quoteinterval('14 day')
- );
- if($r) {
- foreach($r as $rr) {
-
- if(! perm_is_allowed($rr['abook_channel'],$rr['xchan_hash'],'send_stream'))
+ );
+ if ($r) {
+ foreach ($r as $rr) {
+ if (! perm_is_allowed($rr['abook_channel'], $rr['xchan_hash'], 'send_stream'))
continue;
$ev = array();
$ev['uid'] = $rr['abook_channel'];
$ev['account'] = $rr['abook_account'];
$ev['event_xchan'] = $rr['xchan_hash'];
- $ev['start'] = datetime_convert('UTC','UTC', $rr['abook_dob']);
- $ev['finish'] = datetime_convert('UTC','UTC', $rr['abook_dob'] . ' + 1 day ');
+ $ev['start'] = datetime_convert('UTC', 'UTC', $rr['abook_dob']);
+ $ev['finish'] = datetime_convert('UTC', 'UTC', $rr['abook_dob'] . ' + 1 day ');
$ev['adjust'] = 1;
- $ev['summary'] = sprintf( t('%1$s\'s birthday'), $rr['xchan_name']);
- $ev['description'] = sprintf( t('Happy Birthday %1$s'),
+ $ev['summary'] = sprintf( t('%1$s\'s birthday'), $rr['xchan_name']);
+ $ev['description'] = sprintf( t('Happy Birthday %1$s'),
'[zrl=' . $rr['xchan_url'] . ']' . $rr['xchan_name'] . '[/zrl]') ;
$ev['type'] = 'birthday';
-
+
$z = event_store_event($ev);
- if($z) {
- $item_id = event_store_item($ev,$z);
+ if ($z) {
+ $item_id = event_store_item($ev, $z);
q("update abook set abook_dob = '%s' where abook_id = %d",
- dbesc(intval($rr['abook_dob']) + 1 . substr($rr['abook_dob'],4)),
+ dbesc(intval($rr['abook_dob']) + 1 . substr($rr['abook_dob'], 4)),
intval($rr['abook_id'])
);
}
diff --git a/include/dba/dba_driver.php b/include/dba/dba_driver.php
index 4a0f5e37b..708d8e709 100755
--- a/include/dba/dba_driver.php
+++ b/include/dba/dba_driver.php
@@ -24,7 +24,6 @@
function dba_factory($server, $port,$user,$pass,$db,$dbtype,$install = false) {
$dba = null;
-
$dbtype = intval($dbtype);
if($dbtype == DBTYPE_POSTGRES) {
@@ -59,7 +58,7 @@ abstract class dba_driver {
const INSTALL_SCRIPT='install/schema_mysql.sql';
const NULL_DATE = '0000-00-00 00:00:00';
const UTC_NOW = 'UTC_TIMESTAMP()';
-
+
protected $debug = 0;
protected $db;
public $connected = false;
@@ -121,11 +120,11 @@ abstract class dba_driver {
function get_null_date() {
return static::NULL_DATE;
}
-
+
function get_install_script() {
return static::INSTALL_SCRIPT;
}
-
+
function utcnow() {
return static::UTC_NOW;
}
@@ -145,6 +144,7 @@ abstract class dba_driver {
return false;
}
}
+
return true;
}
@@ -166,19 +166,19 @@ abstract class dba_driver {
function quote_interval($txt) {
return $txt;
}
-
+
function optimize_table($table) {
q('OPTIMIZE TABLE '.$table);
}
-
+
function concat($fld, $sep) {
return 'GROUP_CONCAT(DISTINCT '.$fld.' SEPARATOR \''.$sep.'\')';
}
-
+
function escapebin($str) {
return $this->escape($str);
}
-
+
function unescapebin($str) {
return $str;
}
@@ -193,6 +193,7 @@ function printable($s) {
$s = str_replace("\x00",'.',$s);
if(x($_SERVER,'SERVER_NAME'))
$s = escape_tags($s);
+
return $s;
}
@@ -252,7 +253,7 @@ function db_quoteinterval($txt) {
function dbesc_identifier($str) {
global $db;
- return $db->escape_identifier($txt);
+ return $db->escape_identifier($str);
}
function db_utcnow() {
@@ -349,6 +350,7 @@ function dbesc_array_cb(&$item, $key) {
$item = '0001-01-01 00:00:00';
else if($item == '0001-01-01 00:00:00' && ACTIVE_DBTYPE == DBTYPE_MYSQL)
$item = '0000-00-00 00:00:00';
+
$item = dbesc($item);
}
}
@@ -382,8 +384,7 @@ function db_getfunc($f) {
$f = strtolower($f);
if(isset($lookup[$f]) && isset($lookup[$f][ACTIVE_DBTYPE]))
return $lookup[$f][ACTIVE_DBTYPE];
-
+
logger('Unable to abstract DB function "'. $f . '" for dbtype ' . ACTIVE_DBTYPE, LOGGER_DEBUG);
return $f;
}
-
diff --git a/include/deliver.php b/include/deliver.php
index 47d8562df..0fb7a4aeb 100644
--- a/include/deliver.php
+++ b/include/deliver.php
@@ -20,6 +20,32 @@ function deliver_run($argv, $argc) {
dbesc($argv[$x])
);
if($r) {
+
+ /**
+ * Check to see if we have any recent communications with this hub (in the last month).
+ * If not, reduce the outq_priority.
+ */
+
+ $h = parse_url($r[0]['outq_posturl']);
+ if($h) {
+ $base = $h['scheme'] . '://' . $h['host'] . (($h['port']) ? ':' . $h['port'] : '');
+ if($base !== z_root()) {
+ $y = q("select site_update from site where site_url = '%s' ",
+ dbesc($base)
+ );
+ if($y && $y[0]['site_update'] < datetime_convert('UTC','UTC','now - 1 month')) {
+ q("update outq set outq_priority = %d where outq_hash = '%s'",
+ intval($r[0]['outq_priority'] + 10),
+ dbesc($r[0]['outq_hash'])
+ );
+ logger('immediate delivery deferred for site ' . $base);
+ continue;
+ }
+ }
+ }
+
+ // "post" queue driver - used for diaspora and friendica-over-diaspora communications.
+
if($r[0]['outq_driver'] === 'post') {
$result = z_post_url($r[0]['outq_posturl'],$r[0]['outq_msg']);
if($result['success'] && $result['return_code'] < 300) {
@@ -74,9 +100,11 @@ function deliver_run($argv, $argc) {
logger('deliver: dest: ' . $r[0]['outq_posturl'], LOGGER_DEBUG);
$result = zot_zot($r[0]['outq_posturl'],$r[0]['outq_notify']);
if($result['success']) {
+ logger('deliver: remote zot delivery succeeded to ' . $r[0]['outq_posturl']);
zot_process_response($r[0]['outq_posturl'],$result, $r[0]);
}
else {
+ logger('deliver: remote zot delivery failed to ' . $r[0]['outq_posturl']);
$y = q("update outq set outq_updated = '%s' where outq_hash = '%s'",
dbesc(datetime_convert()),
dbesc($argv[$x])
diff --git a/include/diaspora.php b/include/diaspora.php
index c02110ae2..26f0dc70f 100755
--- a/include/diaspora.php
+++ b/include/diaspora.php
@@ -698,6 +698,57 @@ function diaspora_request($importer,$xml) {
return;
}
+
+//FIXME
+/*
+ if(feature_enabled($channel['channel_id'],'premium_channel')) {
+ $myaddr = $importer['channel_address'] . '@' . get_app()->get_hostname();
+ $cnv = random_string();
+ $mid = random_string();
+
+ $msg = t('You have started sharing with a Redmatrix premium channel.');
+ $msg .= t('Redmatrix premium channels are not available for sharing with Diaspora members. This sharing request has been blocked.') . "\r";
+ $msg .= t('Please do not reply to this message, as this channel is not sharing with you and any reply will not be seen by the recipient.') . "\r";
+
+ $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
+ $signed_text = $mid . ';' . $cnv . ';' . $msg . ';'
+ . $created . ';' . $myaddr . ';' . $cnv;
+
+ $sig = base64_encode(rsa_sign($signed_text,$importer['channel_prvkey'],'sha256'));
+
+ $conv = array(
+ 'guid' => xmlify($cnv),
+ 'subject' => xmlify(t('Sharing request failed.')),
+ 'created_at' => xmlify($created),
+ 'diaspora_handle' => xmlify($myaddr),
+ 'participant_handles' => xmlify($myaddr . ';' . $sender_handle)
+ );
+
+ $msg = array(
+ 'guid' => xmlify($mid),
+ 'parent_guid' => xmlify($cnv),
+ 'parent_author_signature' => xmlify($sig),
+ 'author_signature' => xmlify($sig),
+ 'text' => xmlify($msg),
+ 'created_at' => xmlify($created),
+ 'diaspora_handle' => xmlify($myaddr),
+ 'conversation_guid' => xmlify($cnv)
+ );
+
+ $conv['messages'] = array($msg);
+ $tpl = get_markup_template('diaspora_conversation.tpl');
+ $xmsg = replace_macros($tpl, array('$conv' => $conv));
+
+ $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$importer,$ret,$importer['channel_prvkey'],$ret['xchan_pubkey'],false)));
+
+ diaspora_transmit($importer,$ret,$slap,false);
+ return;
+ }
+
+*/
+// End FIXME
+
+
$role = get_pconfig($channel['channel_id'],'system','permissions_role');
if($role) {
$x = get_role_perms($role);
@@ -709,13 +760,19 @@ function diaspora_request($importer,$xml) {
$their_perms = PERMS_R_STREAM|PERMS_R_PROFILE|PERMS_R_PHOTOS|PERMS_R_ABOOK|PERMS_W_STREAM|PERMS_W_COMMENT|PERMS_W_MAIL|PERMS_W_CHAT|PERMS_R_STORAGE|PERMS_R_PAGES;
+
+ $closeness = get_pconfig($importer['channel_id'],'system','new_abook_closeness');
+ if($closeness === false)
+ $closeness = 80;
+
+
$r = q("insert into abook ( abook_account, abook_channel, abook_xchan, abook_my_perms, abook_their_perms, abook_closeness, abook_rating, abook_created, abook_updated, abook_connected, abook_dob, abook_flags) values ( %d, %d, '%s', %d, %d, %d, %d, '%s', '%s', '%s', '%s', %d )",
intval($importer['channel_account_id']),
intval($importer['channel_id']),
dbesc($ret['xchan_hash']),
intval($default_perms),
intval($their_perms),
- intval(99),
+ intval($closeness),
intval(0),
dbesc(datetime_convert()),
dbesc(datetime_convert()),
@@ -799,11 +856,6 @@ function diaspora_post($importer,$xml,$msg) {
}
- if((! $importer['system']) && (! perm_is_allowed($importer['channel_id'],$contact['xchan_hash'],'send_stream'))) {
- logger('diaspora_post: Ignoring this author.');
- return 202;
- }
-
$search_guid = ((strlen($guid) == 64) ? $guid . '%' : $guid);
$r = q("SELECT id FROM item WHERE uid = %d AND mid like '%s' LIMIT 1",
@@ -827,6 +879,12 @@ function diaspora_post($importer,$xml,$msg) {
$body = scale_external_images($body);
}
+ $maxlen = get_max_import_size();
+
+ if($maxlen && mb_strlen($body) > $maxlen) {
+ $body = mb_substr($body,0,$maxlen,'UTF-8');
+ logger('message length exceeds max_import_size: truncated');
+ }
//WTF? FIXME
// Add OEmbed and other information to the body
@@ -835,34 +893,21 @@ function diaspora_post($importer,$xml,$msg) {
$datarray = array();
- $tags = get_tags($body);
-
-
- if(count($tags)) {
-
- $datarray['term'] = array();
-
- foreach($tags as $tag) {
- if(strpos($tag,'#') === 0) {
- if((strpos($tag,'[url=')) || (strpos($tag,'[zrl')))
- continue;
-
- // don't link tags that are already embedded in links
-
- if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
- continue;
- if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
- continue;
+ // Look for tags and linkify them
+ $results = linkify_tags(get_app(), $body, $importer['channel_id'], true);
- $basetag = str_replace('_',' ',substr($tag,1));
- $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
+ $datarray['term'] = array();
+ if($results) {
+ foreach($results as $result) {
+ $success = $result['success'];
+ if($success['replaced']) {
$datarray['term'][] = array(
'uid' => $importer['channel_id'],
- 'type' => TERM_HASHTAG,
+ 'type' => $success['termtype'],
'otype' => TERM_OBJ_POST,
- 'term' => $basetag,
- 'url' => z_root() . '/search?tag=' . rawurlencode($basetag)
+ 'term' => $success['term'],
+ 'url' => $success['url']
);
}
}
@@ -897,6 +942,8 @@ function diaspora_post($importer,$xml,$msg) {
}
+
+
$plink = service_plink($contact,$guid);
@@ -920,6 +967,13 @@ function diaspora_post($importer,$xml,$msg) {
$datarray['item_unseen'] = 1;
$datarray['item_thread_top'] = 1;
+ $tgroup = tgroup_check($importer['channel_id'],$datarray);
+
+ if((! $importer['system']) && (! perm_is_allowed($importer['channel_id'],$contact['xchan_hash'],'send_stream')) && (! $tgroup)) {
+ logger('diaspora_post: Ignoring this author.');
+ return 202;
+ }
+
$result = item_store($datarray);
return;
@@ -986,11 +1040,6 @@ function diaspora_reshare($importer,$xml,$msg) {
if(! $contact)
return;
- if((! $importer['system']) && (! perm_is_allowed($importer['channel_id'],$contact['xchan_hash'],'send_stream'))) {
- logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
- return 202;
- }
-
$search_guid = ((strlen($guid) == 64) ? $guid . '%' : $guid);
$r = q("SELECT id FROM item WHERE uid = %d AND mid like '%s' LIMIT 1",
intval($importer['channel_id']),
@@ -1040,10 +1089,12 @@ function diaspora_reshare($importer,$xml,$msg) {
//return;
}
- //if(! $body) {
- // logger('diaspora_reshare: empty body: source= ' . $x);
- // return;
- //}
+ $maxlen = get_max_import_size();
+
+ if($maxlen && mb_strlen($body) > $maxlen) {
+ $body = mb_substr($body,0,$maxlen,'UTF-8');
+ logger('message length exceeds max_import_size: truncated');
+ }
$person = find_diaspora_person_by_handle($orig_author);
@@ -1053,56 +1104,33 @@ function diaspora_reshare($importer,$xml,$msg) {
$orig_author_photo = $person['xchan_photo_m'];
}
- $newbody = "[share author='" . urlencode($orig_author_name)
- . "' profile='" . $orig_author_link
- . "' avatar='" . $orig_author_photo
- . "' link='" . $orig_url
- . "' posted='" . datetime_convert('UTC','UTC',unxmlify($source_xml->post->status_message->created_at))
- . "' message_id='" . unxmlify($source_xml->post->status_message->guid)
- . "']" . $body . "[/share]";
-
$created = unxmlify($xml->created_at);
$private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
$datarray = array();
- $str_tags = '';
-
- $tags = get_tags($newbody);
+ // Look for tags and linkify them
+ $results = linkify_tags(get_app(), $body, $importer['channel_id'], true);
+ $datarray['term'] = array();
- if(count($tags)) {
-
- $datarray['term'] = array();
-
- foreach($tags as $tag) {
- if(strpos($tag,'#') === 0) {
- if((strpos($tag,'[url=')) || (strpos($tag,'[zrl')))
- continue;
-
- // don't link tags that are already embedded in links
-
- if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$newbody))
- continue;
- if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$newbody))
- continue;
-
- $basetag = str_replace('_',' ',substr($tag,1));
- $newbody = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$newbody);
-
+ if($results) {
+ foreach($results as $result) {
+ $success = $result['success'];
+ if($success['replaced']) {
$datarray['term'][] = array(
'uid' => $importer['channel_id'],
- 'type' => TERM_HASHTAG,
+ 'type' => $success['termtype'],
'otype' => TERM_OBJ_POST,
- 'term' => $basetag,
- 'url' => z_root() . '/search?tag=' . rawurlencode($basetag)
+ 'term' => $success['term'],
+ 'url' => $success['url']
);
}
}
}
- $cnt = preg_match_all('/@\[url=(.*?)\](.*?)\[\/url\]/ism',$newbody,$matches,PREG_SET_ORDER);
+ $cnt = preg_match_all('/@\[url=(.*?)\](.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
if($cnt) {
foreach($matches as $mtch) {
$datarray['term'][] = array(
@@ -1115,6 +1143,34 @@ function diaspora_reshare($importer,$xml,$msg) {
}
}
+ $cnt = preg_match_all('/@\[zrl=(.*?)\](.*?)\[\/zrl\]/ism',$body,$matches,PREG_SET_ORDER);
+ if($cnt) {
+ foreach($matches as $mtch) {
+ // don't include plustags in the term
+ $term = ((substr($mtch[2],-1,1) === '+') ? substr($mtch[2],0,-1) : $mtch[2]);
+ $datarray['term'][] = array(
+ 'uid' => $importer['channel_id'],
+ 'type' => TERM_MENTION,
+ 'otype' => TERM_OBJ_POST,
+ 'term' => $term,
+ 'url' => $mtch[1]
+ );
+ }
+ }
+
+
+
+
+
+ $newbody = "[share author='" . urlencode($orig_author_name)
+ . "' profile='" . $orig_author_link
+ . "' avatar='" . $orig_author_photo
+ . "' link='" . $orig_url
+ . "' posted='" . datetime_convert('UTC','UTC',unxmlify($source_xml->post->status_message->created_at))
+ . "' message_id='" . unxmlify($source_xml->post->status_message->guid)
+ . "']" . $body . "[/share]";
+
+
$plink = service_plink($contact,$guid);
$datarray['uid'] = $importer['channel_id'];
@@ -1129,6 +1185,15 @@ function diaspora_reshare($importer,$xml,$msg) {
$datarray['app'] = 'Diaspora';
+
+ $tgroup = tgroup_check($importer['channel_id'],$datarray);
+
+ if((! $importer['system']) && (! perm_is_allowed($importer['channel_id'],$contact['xchan_hash'],'send_stream')) && (! $tgroup)) {
+ logger('diaspora_post: Ignoring this author.');
+ return 202;
+ }
+
+
$result = item_store($datarray);
return;
@@ -1257,31 +1322,21 @@ function diaspora_comment($importer,$xml,$msg) {
return;
}
- if((! $importer['system']) && (! perm_is_allowed($importer['channel_id'],$contact['xchan_hash'],'post_comments'))) {
- logger('diaspora_comment: Ignoring this author.');
- return 202;
- }
- // Friendica is currently truncating guids at 64 chars
+
+ $pubcomment = get_pconfig($importer['channel_id'],'system','diaspora_public_comments');
- $search_guid = $guid;
- if(strlen($guid) == 64)
- $search_guid = $guid . '%';
+ // by default comments on public posts are allowed from anybody on Diaspora. That is their policy.
+ // Once this setting is set to something we'll track your preference and it will over-ride the default.
- $r = q("SELECT * FROM item WHERE uid = %d AND mid like '%s' LIMIT 1",
- intval($importer['channel_id']),
- dbesc($search_guid)
- );
- if($r) {
- logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
- return;
- }
+ if($pubcomment === false)
+ $pubcomment = 1;
+ // Friendica is currently truncating guids at 64 chars
$search_guid = $parent_guid;
if(strlen($parent_guid) == 64)
$search_guid = $parent_guid . '%';
-
$r = q("SELECT * FROM item WHERE uid = %d AND mid LIKE '%s' LIMIT 1",
intval($importer['channel_id']),
dbesc($search_guid)
@@ -1290,8 +1345,27 @@ function diaspora_comment($importer,$xml,$msg) {
logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
return;
}
+
$parent_item = $r[0];
+ if(intval($parent_item['item_private']))
+ $pubcomment = 0;
+
+ $search_guid = $guid;
+ if(strlen($guid) == 64)
+ $search_guid = $guid . '%';
+
+
+ $r = q("SELECT * FROM item WHERE uid = %d AND mid like '%s' LIMIT 1",
+ intval($importer['channel_id']),
+ dbesc($search_guid)
+ );
+ if($r) {
+ logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
+ return;
+ }
+
+
/* How Diaspora performs comment signature checking:
@@ -1326,6 +1400,12 @@ function diaspora_comment($importer,$xml,$msg) {
// our post, so he/she must be a contact of ours and his/her public key
// should be in $msg['key']
+ if($importer['system']) {
+ // don't relay to the sys channel
+ logger('diaspora_comment: relay to sys channel blocked.');
+ return;
+ }
+
$author_signature = base64_decode($author_signature);
if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
@@ -1354,35 +1434,32 @@ function diaspora_comment($importer,$xml,$msg) {
$body = diaspora2bb($text);
- $datarray = array();
-
- $tags = get_tags($body);
- if(count($tags)) {
+ $maxlen = get_max_import_size();
- $datarray['term'] = array();
+ if($maxlen && mb_strlen($body) > $maxlen) {
+ $body = mb_substr($body,0,$maxlen,'UTF-8');
+ logger('message length exceeds max_import_size: truncated');
+ }
- foreach($tags as $tag) {
- if(strpos($tag,'#') === 0) {
- if((strpos($tag,'[url=')) || (strpos($tag,'[zrl')))
- continue;
- // don't link tags that are already embedded in links
+ $datarray = array();
- if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
- continue;
- if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
- continue;
+ // Look for tags and linkify them
+ $results = linkify_tags(get_app(), $body, $importer['channel_id'], true);
- $basetag = str_replace('_',' ',substr($tag,1));
- $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
+ $datarray['term'] = array();
+ if($results) {
+ foreach($results as $result) {
+ $success = $result['success'];
+ if($success['replaced']) {
$datarray['term'][] = array(
'uid' => $importer['channel_id'],
- 'type' => TERM_HASHTAG,
+ 'type' => $success['termtype'],
'otype' => TERM_OBJ_POST,
- 'term' => $basetag,
- 'url' => z_root() . '/search?tag=' . rawurlencode($basetag)
+ 'term' => $success['term'],
+ 'url' => $success['url']
);
}
}
@@ -1401,6 +1478,21 @@ function diaspora_comment($importer,$xml,$msg) {
}
}
+ $cnt = preg_match_all('/@\[zrl=(.*?)\](.*?)\[\/zrl\]/ism',$body,$matches,PREG_SET_ORDER);
+ if($cnt) {
+ foreach($matches as $mtch) {
+ // don't include plustags in the term
+ $term = ((substr($mtch[2],-1,1) === '+') ? substr($mtch[2],0,-1) : $mtch[2]);
+ $datarray['term'][] = array(
+ 'uid' => $importer['channel_id'],
+ 'type' => TERM_MENTION,
+ 'otype' => TERM_OBJ_POST,
+ 'term' => $term,
+ 'url' => $mtch[1]
+ );
+ }
+ }
+
$datarray['uid'] = $importer['channel_id'];
$datarray['verb'] = ACTIVITY_POST;
$datarray['mid'] = $guid;
@@ -1432,6 +1524,22 @@ function diaspora_comment($importer,$xml,$msg) {
$datarray['diaspora_meta'] = json_encode(crypto_encapsulate(json_encode($x),$key));
}
+
+
+ // So basically if something arrives at the sys channel it's by definition public and we allow it.
+ // If $pubcomment and the parent was public, we allow it.
+ // In all other cases, honour the permissions for this Diaspora connection
+
+ $tgroup = tgroup_check($importer['channel_id'],$datarray);
+
+ if((! $importer['system']) && (! $pubcomment) && (! perm_is_allowed($importer['channel_id'],$contact['xchan_hash'],'post_comments')) && (! $tgroup)) {
+ logger('diaspora_comment: Ignoring this author.');
+ return 202;
+ }
+
+
+
+
$result = item_store($datarray);
if($result && $result['success'])
@@ -1540,6 +1648,15 @@ function diaspora_conversation($importer,$xml,$msg) {
$body = diaspora2bb($msg_text);
+
+ $maxlen = get_max_import_size();
+
+ if($maxlen && mb_strlen($body) > $maxlen) {
+ $body = mb_substr($body,0,$maxlen,'UTF-8');
+ logger('message length exceeds max_import_size: truncated');
+ }
+
+
$author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
$author_signature = base64_decode($msg_author_signature);
@@ -1677,6 +1794,17 @@ function diaspora_message($importer,$xml,$msg) {
$subject = $conversation['subject'];
$body = diaspora2bb($msg_text);
+
+
+ $maxlen = get_max_import_size();
+
+ if($maxlen && mb_strlen($body) > $maxlen) {
+ $body = mb_substr($body,0,$maxlen,'UTF-8');
+ logger('message length exceeds max_import_size: truncated');
+ }
+
+
+
$message_id = $msg_diaspora_handle . ':' . $msg_guid;
$author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
diff --git a/include/dir_fns.php b/include/dir_fns.php
index b5ba296cf..eaa2db84b 100644
--- a/include/dir_fns.php
+++ b/include/dir_fns.php
@@ -1,14 +1,23 @@
-<?php /** @file */
+<?php
+/**
+ * @file include/dir_fns.php
+ */
require_once('include/permissions.php');
+/**
+ * @brief
+ *
+ * @param int $dirmode
+ * @return array
+ */
function find_upstream_directory($dirmode) {
global $DIRECTORY_FALLBACK_SERVERS;
$preferred = get_config('system','directory_server');
- if(! $preferred) {
+ if (! $preferred) {
- /**
+ /*
* No directory has yet been set. For most sites, pick one at random
* from our list of directory servers. However, if we're a directory
* server ourself, point at the local instance
@@ -18,41 +27,40 @@ function find_upstream_directory($dirmode) {
*/
$dirmode = intval(get_config('system','directory_mode'));
- if($dirmode == DIRECTORY_MODE_NORMAL) {
+ if ($dirmode == DIRECTORY_MODE_NORMAL) {
$toss = mt_rand(0,count($DIRECTORY_FALLBACK_SERVERS));
$preferred = $DIRECTORY_FALLBACK_SERVERS[$toss];
set_config('system','directory_server',$preferred);
- }
- else{
+ } else{
set_config('system','directory_server',z_root());
}
}
+
return array('url' => $preferred);
}
+/**
+ * Directories may come and go over time. We will need to check that our
+ * directory server is still valid occasionally, and reset to something that
+ * is if our directory has gone offline for any reason
+ */
function check_upstream_directory() {
- /**
- * Directories may come and go over time. We will need to check that our
- * directory server is still valid occasionally, and reset to something that
- * is if our directory has gone offline for any reason
- */
-
- $directory = get_config('system','directory_server');
+ $directory = get_config('system', 'directory_server');
// it's possible there is no directory server configured and the local hub is being used.
// If so, default to preserving the absence of a specific server setting.
- $isadir = true;
+ $isadir = true;
- if($directory) {
+ if ($directory) {
$h = parse_url($directory);
- if($h) {
- $x = zot_finger('sys@' . $h['host']);
- if($x['success']) {
- $j = json_decode($x['body'],true);
- if(array_key_exists('site',$j) && array_key_exists('directory_mode',$j['site'])) {
- if($j['site']['directory_mode'] === 'normal') {
+ if ($h) {
+ $x = zot_finger('[system]@' . $h['host']);
+ if ($x['success']) {
+ $j = json_decode($x['body'], true);
+ if (array_key_exists('site', $j) && array_key_exists('directory_mode', $j['site'])) {
+ if ($j['site']['directory_mode'] === 'normal') {
$isadir = false;
}
}
@@ -60,16 +68,61 @@ function check_upstream_directory() {
}
}
- if(! $isadir)
- set_config('system','directory_server','');
- return;
+ if (! $isadir)
+ set_config('system', 'directory_server', '');
}
-
+
+function get_globaldir_setting($observer) {
+
+ if($observer)
+ $globaldir = get_xconfig($observer,'directory','globaldir');
+ else
+ $globaldir = ((array_key_exists('globaldir',$_SESSION)) ? intval($_SESSION['globaldir']) : false);
+
+ if($globaldir === false)
+ $globaldir = get_config('directory','globaldir');
+
+ return $globaldir;
+}
+
+function get_safemode_setting($observer) {
+
+ if ($observer)
+ $safe_mode = get_xconfig($observer,'directory','safe_mode');
+ else
+ $safe_mode = ((array_key_exists('safemode',$_SESSION)) ? intval($_SESSION['safemode']) : false);
+
+ if($safe_mode === false)
+ $safe_mode = get_config('directory','safe_mode');
+
+ if($safe_mode === false)
+ $safe_mode = 1;
+
+ return $safe_mode;
+}
+
+/**
+ * @brief Called by the directory_sort widget.
+ */
function dir_sort_links() {
+
+ $safe_mode = 1;
+
+ $observer = get_observer_hash();
+
+ $safe_mode = get_safemode_setting($observer);
+ $globaldir = get_globaldir_setting($observer);
+
// Build urls without order and pubforums so it's easy to tack on the changed value
// Probably there's an easier way to do this
- $current_order = (($_REQUEST['order']) ? $_REQUEST['order'] : 'normal');
+
+ $directory_sort_order = get_config('system','directory_sort_order');
+ if(! $directory_sort_order)
+ $directory_sort_order = 'date';
+
+
+ $current_order = (($_REQUEST['order']) ? $_REQUEST['order'] : $directory_sort_order);
$url = 'directory?f=';
$tmp = array_merge($_GET,$_POST);
@@ -80,6 +133,8 @@ function dir_sort_links() {
$tmp = array_merge($_GET,$_POST);
unset($tmp['pubforums']);
+ unset($tmp['global']);
+ unset($tmp['safe']);
unset($tmp['q']);
unset($tmp['f']);
$forumsurl = $url . http_build_query($tmp);
@@ -90,49 +145,43 @@ function dir_sort_links() {
'$reverse' => t('Reverse Alphabetic'),
'$date' => t('Newest to Oldest'),
'$reversedate' => t('Oldest to Newest'),
- '$pubforums' => t('Public Forums Only'),
- '$pubforumsonly' => x($_REQUEST,'pubforums') ? $_REQUEST['pubforums'] : '',
'$sort' => t('Sort'),
'$selected_sort' => $current_order,
'$sorturl' => $sorturl,
'$forumsurl' => $forumsurl,
+ '$safemode' => array('safemode', t('Safe Mode'),$safe_mode,'','',' onchange=\'window.location.href="' . $forumsurl . '&safe="+(this.checked ? 1 : 0)\''),
- ));
- return $o;
-}
-
-function dir_safe_mode() {
- $observer = get_observer_hash();
- if (! $observer)
- return;
- if ($observer)
- $safe_mode = get_xconfig($observer,'directory','safe_mode');
- if($safe_mode === '0')
- $toggle = t('Enable Safe Search');
- else
- $toggle = t('Disable Safe Search');
- $o = replace_macros(get_markup_template('safesearch.tpl'), array(
- '$safemode' => t('Safe Mode'),
- '$toggle' => $toggle,
+ '$pubforums' => array('pubforums', t('Public Forums Only'),(x($_REQUEST,'pubforums') ? $_REQUEST['pubforums'] : ''),'','',' onchange=\'window.location.href="' . $forumsurl . '&pubforums="+(this.checked ? 1 : 0)\''),
+ '$globaldir' => array('globaldir', t('This Website Only'), 1-intval($globaldir),'','',' onchange=\'window.location.href="' . $forumsurl . '&global="+(this.checked ? 0 : 1)\''),
));
return $o;
}
+/**
+ * @brief Checks the directory mode of this hub.
+ *
+ * Checks the directory mode of this hub to see if it is some form of directory server. If it is,
+ * get the directory realm of this hub. Fetch a list of all other directory servers in this realm and request
+ * a directory sync packet. This will contain both directory updates and new ratings. Store these all in the DB.
+ * In the case of updates, we will query each of them asynchronously from a poller task. Ratings are stored
+ * directly if the rater's signature matches.
+ *
+ * @param int $dirmode;
+ */
function sync_directories($dirmode) {
- if($dirmode == DIRECTORY_MODE_STANDALONE || $dirmode == DIRECTORY_MODE_NORMAL)
+ if ($dirmode == DIRECTORY_MODE_STANDALONE || $dirmode == DIRECTORY_MODE_NORMAL)
return;
$realm = get_directory_realm();
- if($realm == DIRECTORY_REALM) {
+ if ($realm == DIRECTORY_REALM) {
$r = q("select * from site where (site_flags & %d) > 0 and site_url != '%s' and ( site_realm = '%s' or site_realm = '') ",
intval(DIRECTORY_MODE_PRIMARY|DIRECTORY_MODE_SECONDARY),
dbesc(z_root()),
dbesc($realm)
);
- }
- else {
+ } else {
$r = q("select * from site where (site_flags & %d) > 0 and site_url != '%s' and site_realm like '%s' ",
intval(DIRECTORY_MODE_PRIMARY|DIRECTORY_MODE_SECONDARY),
dbesc(z_root()),
@@ -141,49 +190,56 @@ function sync_directories($dirmode) {
}
// If there are no directory servers, setup the fallback master
- // FIXME - what to do if we're in a different realm?
+ /** @FIXME What to do if we're in a different realm? */
- if((! $r) && (z_root() != DIRECTORY_FALLBACK_MASTER)) {
- $r = array(
+ if ((! $r) && (z_root() != DIRECTORY_FALLBACK_MASTER)) {
+ $r = array();
+ $r[] = array(
'site_url' => DIRECTORY_FALLBACK_MASTER,
'site_flags' => DIRECTORY_MODE_PRIMARY,
'site_update' => NULL_DATE,
'site_directory' => DIRECTORY_FALLBACK_MASTER . '/dirsearch',
- 'site_realm' => DIRECTORY_REALM
+ 'site_realm' => DIRECTORY_REALM,
+ 'site_valid' => 1
);
- $x = q("insert into site ( site_url, site_flags, site_update, site_directory, site_realm )
+ $x = q("insert into site ( site_url, site_flags, site_update, site_directory, site_realm, site_valid )
values ( '%s', %d', '%s', '%s', '%s' ) ",
dbesc($r[0]['site_url']),
intval($r[0]['site_flags']),
dbesc($r[0]['site_update']),
dbesc($r[0]['site_directory']),
- dbesc($r[0]['site_realm'])
+ dbesc($r[0]['site_realm']),
+ intval($r[0]['site_valid'])
);
$r = q("select * from site where (site_flags & %d) > 0 and site_url != '%s'",
intval(DIRECTORY_MODE_PRIMARY|DIRECTORY_MODE_SECONDARY),
dbesc(z_root())
);
-
- }
- if(! $r)
+ }
+ if (! $r)
return;
- foreach($r as $rr) {
- if(! $rr['site_directory'])
+ foreach ($r as $rr) {
+ if (! $rr['site_directory'])
continue;
logger('sync directories: ' . $rr['site_directory']);
- // for brand new directory servers, only load the last couple of days. Everything before that will be repeats.
+ // for brand new directory servers, only load the last couple of days.
+ // It will take about a month for a new directory to obtain the full current repertoire of channels.
+ /** @FIXME Go back and pick up earlier ratings if this is a new directory server. These do not get refreshed. */
+
+ $token = get_config('system','realm_token');
$syncdate = (($rr['site_sync'] === NULL_DATE) ? datetime_convert('UTC','UTC','now - 2 days') : $rr['site_sync']);
- $x = z_fetch_url($rr['site_directory'] . '?f=&sync=' . urlencode($syncdate));
+ $x = z_fetch_url($rr['site_directory'] . '?f=&sync=' . urlencode($syncdate) . (($token) ? '&t=' . $token : ''));
- if(! $x['success'])
+ if (! $x['success'])
continue;
+
$j = json_decode($x['body'],true);
- if((! $j['transactions']) || (! is_array($j['transactions'])))
+ if (!($j['transactions']) || ($j['ratings']))
continue;
q("update site set site_sync = '%s' where site_url = '%s'",
@@ -193,17 +249,18 @@ function sync_directories($dirmode) {
logger('sync_directories: ' . $rr['site_url'] . ': ' . print_r($j,true), LOGGER_DATA);
- if(count($j['transactions'])) {
- foreach($j['transactions'] as $t) {
+ if (is_array($j['transactions']) && count($j['transactions'])) {
+ foreach ($j['transactions'] as $t) {
$r = q("select * from updates where ud_guid = '%s' limit 1",
dbesc($t['transaction_id'])
);
if($r)
continue;
+
$ud_flags = 0;
- if(is_array($t['flags']) && in_array('deleted',$t['flags']))
+ if (is_array($t['flags']) && in_array('deleted',$t['flags']))
$ud_flags |= UPDATE_FLAGS_DELETED;
- if(is_array($t['flags']) && in_array('forced',$t['flags']))
+ if (is_array($t['flags']) && in_array('forced',$t['flags']))
$ud_flags |= UPDATE_FLAGS_FORCED;
$z = q("insert into updates ( ud_hash, ud_guid, ud_date, ud_flags, ud_addr )
@@ -216,38 +273,41 @@ function sync_directories($dirmode) {
);
}
}
- if(count($j['ratings'])) {
- foreach($j['ratings'] as $rr) {
+ if (is_array($j['ratings']) && count($j['ratings'])) {
+ foreach ($j['ratings'] as $rr) {
$x = q("select * from xlink where xlink_xchan = '%s' and xlink_link = '%s' and xlink_static = 1",
dbesc($rr['channel']),
dbesc($rr['target'])
);
- if($x && $x[0]['xlink_updated'] >= $rr['edited'])
+ if ($x && $x[0]['xlink_updated'] >= $rr['edited'])
continue;
+
+ // Ratings are signed by the rater. We need to verify before we can accept it.
+ /** @TODO Queue or defer if the xchan is not yet present on our site */
+
$y = q("select xchan_pubkey from xchan where xchan_hash = '%s' limit 1",
dbesc($rr['channel'])
);
- if(! $y) {
+ if (! $y) {
logger('key unavailable on this site for ' . $rr['channel']);
continue;
}
- if(! rsa_verify($rr['target'] . '.' . $rr['rating'] . '.' . $rr['rating_text'], base64url_decode($rr['signature']),$y[0]['xchan_pubkey'])) {
- logger('failed to verify rating');
+ if (! rsa_verify($rr['target'] . '.' . $rr['rating'] . '.' . $rr['rating_text'], base64url_decode($rr['signature']),$y[0]['xchan_pubkey'])) {
+ logger('failed to verify rating');
continue;
}
- if($x) {
+ if ($x) {
$z = q("update xlink set xlink_rating = %d, xlink_rating_text = '%s', xlink_sig = '%s', xlink_updated = '%s' where xlink_id = %d",
intval($rr['rating']),
dbesc($rr['rating_text']),
dbesc($rr['signature']),
dbesc(datetime_convert()),
intval($x[0]['xlink_id'])
- );
- logger('rating updated');
- }
- else {
- $z = q("insert into xlink ( xlink_xchan, xlink_link, xlink_rating, xlink_rating_text, xlink_sig, xlink_updated, xlink_static ) values( '%s', '%s', %d, '%s', '%s', 1 ) ",
+ );
+ logger('rating updated');
+ } else {
+ $z = q("insert into xlink ( xlink_xchan, xlink_link, xlink_rating, xlink_rating_text, xlink_sig, xlink_updated, xlink_static ) values( '%s', '%s', %d, '%s', '%s', '%s', 1 ) ",
dbesc($rr['channel']),
dbesc($rr['target']),
intval($rr['rating']),
@@ -263,37 +323,52 @@ function sync_directories($dirmode) {
}
+/**
+ * @brief
+ *
+ * Given an update record, probe the channel, grab a zot-info packet and refresh/sync the data.
+ *
+ * Ignore updating records marked as deleted.
+ *
+ * If successful, sets ud_last in the DB to the current datetime for this
+ * reddress/webbie.
+ *
+ * @param array $ud Entry from update table
+ */
function update_directory_entry($ud) {
logger('update_directory_entry: ' . print_r($ud,true), LOGGER_DATA);
- if($ud['ud_addr'] && (! ($ud['ud_flags'] & UPDATE_FLAGS_DELETED))) {
+ if ($ud['ud_addr'] && (! ($ud['ud_flags'] & UPDATE_FLAGS_DELETED))) {
$success = false;
- $x = zot_finger($ud['ud_addr'],'');
- if($x['success']) {
- $j = json_decode($x['body'],true);
- if($j)
+ $x = zot_finger($ud['ud_addr'], '');
+ if ($x['success']) {
+ $j = json_decode($x['body'], true);
+ if ($j)
$success = true;
- $y = import_xchan($j,0,$ud);
+
+ $y = import_xchan($j, 0, $ud);
}
- if(! $success) {
- $r = q("update updates set ud_last = '%s' where ud_addr = '%s'",
+ if (! $success) {
+ q("update updates set ud_last = '%s' where ud_addr = '%s'",
dbesc(datetime_convert()),
dbesc($ud['ud_addr'])
);
}
}
-
}
/**
- * @function local_dir_update($uid,$force)
- * push local channel updates to a local directory server
+ * @brief Push local channel updates to a local directory server.
+ *
+ * This is called from include/directory.php if a profile is to be pushed to the
+ * directory and the local hub in this case is any kind of directory server.
*
+ * @param int $uid
+ * @param boolean $force
*/
-
-function local_dir_update($uid,$force) {
+function local_dir_update($uid, $force) {
logger('local_dir_update: uid: ' . $uid, LOGGER_DEBUG);
@@ -304,12 +379,12 @@ function local_dir_update($uid,$force) {
$profile = array();
$profile['encoding'] = 'zot';
- if($p) {
+ if ($p) {
$hash = $p[0]['channel_hash'];
$profile['description'] = $p[0]['pdesc'];
$profile['birthday'] = $p[0]['dob'];
- if($age = age($p[0]['dob'],$p[0]['channel_timezone'],''))
+ if ($age = age($p[0]['dob'],$p[0]['channel_timezone'],''))
$profile['age'] = $age;
$profile['gender'] = $p[0]['gender'];
@@ -323,14 +398,15 @@ function local_dir_update($uid,$force) {
$profile['homepage'] = $p[0]['homepage'];
$profile['hometown'] = $p[0]['hometown'];
- if($p[0]['keywords']) {
+ if ($p[0]['keywords']) {
$tags = array();
- $k = explode(' ',$p[0]['keywords']);
- if($k)
- foreach($k as $kk)
- if(trim($kk))
+ $k = explode(' ', $p[0]['keywords']);
+ if ($k)
+ foreach ($k as $kk)
+ if (trim($kk))
$tags[] = trim($kk);
- if($tags)
+
+ if ($tags)
$profile['keywords'] = $tags;
}
@@ -351,10 +427,9 @@ function local_dir_update($uid,$force) {
$address = $p[0]['channel_address'] . '@' . get_app()->get_hostname();
- if(perm_is_allowed($uid,'','view_profile')) {
- import_directory_profile($hash,$profile,$address,0);
- }
- else {
+ if (perm_is_allowed($uid, '', 'view_profile')) {
+ import_directory_profile($hash, $profile, $address, 0);
+ } else {
// they may have made it private
$r = q("delete from xprof where xprof_hash = '%s'",
dbesc($hash)
@@ -366,7 +441,5 @@ function local_dir_update($uid,$force) {
}
$ud_hash = random_string() . '@' . get_app()->get_hostname();
- update_modtime($hash,$ud_hash,$p[0]['channel_address'] . '@' . get_app()->get_hostname(),(($force) ? UPDATE_FLAGS_FORCED : UPDATE_FLAGS_UPDATED));
-
+ update_modtime($hash, $ud_hash, $p[0]['channel_address'] . '@' . get_app()->get_hostname(),(($force) ? UPDATE_FLAGS_FORCED : UPDATE_FLAGS_UPDATED));
}
-
diff --git a/include/directory.php b/include/directory.php
index a7324a99a..9ab1d805b 100644
--- a/include/directory.php
+++ b/include/directory.php
@@ -1,14 +1,23 @@
-<?php /** @file */
+<?php
+/**
+ * @file include/directory.php
+ * @brief executes directory_run()
+ */
require_once('boot.php');
require_once('include/zot.php');
require_once('include/cli_startup.php');
require_once('include/dir_fns.php');
-
+/**
+ * @brief
+ *
+ * @param array $argv
+ * @param array $argc
+ */
function directory_run($argv, $argc){
- cli_startup();
+ cli_startup();
if($argc < 2)
return;
@@ -37,8 +46,9 @@ function directory_run($argv, $argc){
$channel = $x[0];
+ if($dirmode != DIRECTORY_MODE_NORMAL) {
- if(($dirmode == DIRECTORY_MODE_PRIMARY) || ($dirmode == DIRECTORY_MODE_STANDALONE)) {
+ // this is an in-memory update and we don't need to send a network packet.
local_dir_update($argv[1],$force);
@@ -54,6 +64,8 @@ function directory_run($argv, $argc){
return;
}
+ // otherwise send the changes upstream
+
$directory = find_upstream_directory($dirmode);
$url = $directory['url'] . '/post';
@@ -66,8 +78,9 @@ function directory_run($argv, $argc){
if(! $z['success']) {
- // FIXME - we aren't updating channel_dirdate if we have to queue
- // the directory packet. That means we'll try again on the next poll run.
+ /** @FIXME we aren't updating channel_dirdate if we have to queue
+ * the directory packet. That means we'll try again on the next poll run.
+ */
$hash = random_string();
q("insert into outq ( outq_hash, outq_account, outq_channel, outq_driver, outq_posturl, outq_async, outq_created, outq_updated, outq_notify, outq_msg )
@@ -83,8 +96,7 @@ function directory_run($argv, $argc){
dbesc($packet),
dbesc('')
);
- }
- else {
+ } else {
q("update channel set channel_dirdate = '%s' where channel_id = %d",
dbesc(datetime_convert()),
intval($channel['channel_id'])
@@ -97,7 +109,7 @@ function directory_run($argv, $argc){
}
-if (array_search(__file__,get_included_files())===0){
- directory_run($argv,$argc);
- killme();
+if (array_search(__file__, get_included_files()) === 0) {
+ directory_run($argv, $argc);
+ killme();
}
diff --git a/include/enotify.php b/include/enotify.php
index 77b84d373..06e9aad37 100644
--- a/include/enotify.php
+++ b/include/enotify.php
@@ -1,33 +1,50 @@
-<?php /** @file */
-
+<?php
+/**
+ * @file include/enotify.php
+ *
+ * @brief File with functions and a class for email notifications.
+ */
+
+/**
+ * @brief
+ *
+ * @param array $params an assoziative array with:
+ * * \e string \b from_xchan sender xchan hash
+ * * \e string \b to_xchan recipient xchan hash
+ * * \e array \b item an assoziative array
+ * * \e int \b type one of the NOTIFY_* constants from boot.php
+ * * \e string \b link
+ * * \e string \b parent_mid
+ * * \e string \b otype
+ * * \e string \b verb
+ * * \e string \b activity
+ */
function notification($params) {
logger('notification: entry', LOGGER_DEBUG);
// throw a small amount of entropy into the system to breakup duplicates arriving at the same precise instant.
- usleep(mt_rand(0,10000));
-
+ usleep(mt_rand(0, 10000));
$a = get_app();
- if($params['from_xchan']) {
+ if ($params['from_xchan']) {
$x = q("select * from xchan where xchan_hash = '%s' limit 1",
dbesc($params['from_xchan'])
);
}
- if($params['to_xchan']) {
+ if ($params['to_xchan']) {
$y = q("select channel.*, account.* from channel left join account on channel_account_id = account_id
where channel_hash = '%s' and not (channel_pageflags & %d)>0 limit 1",
dbesc($params['to_xchan']),
intval(PAGE_REMOVED)
);
}
- if($x & $y) {
+ if ($x & $y) {
$sender = $x[0];
$recip = $y[0];
- }
- else {
+ } else {
logger('notification: no sender or recipient.');
logger('sender: ' . $params['from_xchan']);
logger('recip: ' . $params['to_xchan']);
@@ -55,10 +72,10 @@ function notification($params) {
$additional_mail_header = "";
- if(array_key_exists('item',$params)) {
+ if (array_key_exists('item', $params)) {
require_once('include/conversation.php');
// if it's a normal item...
- if(array_key_exists('verb',$params['item'])) {
+ if (array_key_exists('verb', $params['item'])) {
// localize_item() alters the original item so make a copy first
$i = $params['item'];
logger('calling localize');
@@ -71,8 +88,7 @@ function notification($params) {
$title = $params['item']['title'];
$body = $params['item']['body'];
}
- }
- else {
+ } else {
$title = $body = '';
}
@@ -80,7 +96,7 @@ function notification($params) {
// e.g. "your post", "David's photo", etc.
$possess_desc = t('%s <!item_type!>');
- if($params['type'] == NOTIFY_MAIL) {
+ if ($params['type'] == NOTIFY_MAIL) {
logger('notification: mail');
$subject = sprintf( t('[Red:Notify] New mail received at %s'),$sitename);
@@ -92,28 +108,27 @@ function notification($params) {
$itemlink = $siteurl . '/mail/' . $params['item']['id'];
}
- if($params['type'] == NOTIFY_COMMENT) {
+ if ($params['type'] == NOTIFY_COMMENT) {
// logger("notification: params = " . print_r($params, true), LOGGER_DEBUG);
$itemlink = $params['link'];
-
// ignore like/unlike activity on posts - they probably require a sepearate notification preference
- if(array_key_exists('item',$params) && (! visible_activity($params['item'])))
+ if (array_key_exists('item',$params) && (! visible_activity($params['item'])))
return;
$parent_mid = $params['parent_mid'];
// Check to see if there was already a notify for this post.
// If so don't create a second notification
-
+
$p = null;
$p = q("select id from notify where link = '%s' and uid = %d limit 1",
dbesc($params['link']),
intval($recip['channel_id'])
);
- if($p) {
+ if ($p) {
logger('notification: comment already notified');
pop_lang();
return;
@@ -182,26 +197,26 @@ function notification($params) {
$subject = sprintf( t('[Red:Notify] %s posted to your profile wall') , $sender['xchan_name']);
$preamble = sprintf( t('%1$s, %2$s posted to your profile wall at %3$s') , $recip['channel_name'], $sender['xchan_name'], $sitename);
-
+
$epreamble = sprintf( t('%1$s, %2$s posted to [zrl=%3$s]your wall[/zrl]') ,
$recip['channel_name'],
'[zrl=' . $sender['xchan_url'] . ']' . $sender['xchan_name'] . '[/zrl]',
$params['link']);
-
+
$sitelink = t('Please visit %s to view and/or reply to the conversation.');
$tsitelink = sprintf( $sitelink, $siteurl );
$hsitelink = sprintf( $sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
$itemlink = $params['link'];
}
- if($params['type'] == NOTIFY_TAGSELF) {
+ if ($params['type'] == NOTIFY_TAGSELF) {
$p = null;
$p = q("select id from notify where link = '%s' and uid = %d limit 1",
dbesc($params['link']),
intval($recip['channel_id'])
);
- if($p) {
+ if ($p) {
logger('enotify: tag: already notified about this post');
pop_lang();
return;
@@ -220,8 +235,7 @@ function notification($params) {
$itemlink = $params['link'];
}
- if($params['type'] == NOTIFY_POKE) {
-
+ if ($params['type'] == NOTIFY_POKE) {
$subject = sprintf( t('[Red:Notify] %1$s poked you') , $sender['xchan_name']);
$preamble = sprintf( t('%1$s, %2$s poked you at %3$s') , $recip['channel_name'], $sender['xchan_name'], $sitename);
$epreamble = sprintf( t('%1$s, %2$s [zrl=%2$s]poked you[/zrl].') ,
@@ -239,7 +253,7 @@ function notification($params) {
$itemlink = $params['link'];
}
- if($params['type'] == NOTIFY_TAGSHARE) {
+ if ($params['type'] == NOTIFY_TAGSHARE) {
$subject = sprintf( t('[Red:Notify] %s tagged your post') , $sender['xchan_name']);
$preamble = sprintf( t('%1$s, %2$s tagged your post at %3$s') , $recip['channel_name'],$sender['xchan_name'], $sitename);
$epreamble = sprintf( t('%1$s, %2$s tagged [zrl=%3$s]your post[/zrl]') ,
@@ -253,7 +267,7 @@ function notification($params) {
$itemlink = $params['link'];
}
- if($params['type'] == NOTIFY_INTRO) {
+ if ($params['type'] == NOTIFY_INTRO) {
$subject = sprintf( t('[Red:Notify] Introduction received'));
$preamble = sprintf( t('%1$s, you\'ve received an new connection request from \'%2$s\' at %3$s'), $recip['channel_name'], $sender['xchan_name'], $sitename);
$epreamble = sprintf( t('%1$s, you\'ve received [zrl=%2$s]a new connection request[/zrl] from %3$s.'),
@@ -268,7 +282,7 @@ function notification($params) {
$itemlink = $params['link'];
}
- if($params['type'] == NOTIFY_SUGGEST) {
+ if ($params['type'] == NOTIFY_SUGGEST) {
$subject = sprintf( t('[Red:Notify] Friend suggestion received'));
$preamble = sprintf( t('%1$s, you\'ve received a friend suggestion from \'%2$s\' at %3$s'), $recip['channel_name'], $sender['xchan_name'], $sitename);
$epreamble = sprintf( t('%1$s, you\'ve received [zrl=%2$s]a friend suggestion[/zrl] for %3$s from %4$s.'),
@@ -276,7 +290,7 @@ function notification($params) {
$itemlink,
'[zrl=' . $params['item']['url'] . ']' . $params['item']['name'] . '[/zrl]',
'[zrl=' . $sender['xchan_url'] . ']' . $sender['xchan_name'] . '[/zrl]');
-
+
$body = t('Name:') . ' ' . $params['item']['name'] . "\n";
$body .= t('Photo:') . ' ' . $params['item']['photo'] . "\n";
$body .= sprintf( t('You may visit their profile at %s'),$params['item']['url']);
@@ -287,27 +301,27 @@ function notification($params) {
$itemlink = $params['link'];
}
- if($params['type'] == NOTIFY_CONFIRM) {
-
+ if ($params['type'] == NOTIFY_CONFIRM) {
+ // ?
}
- if($params['type'] == NOTIFY_SYSTEM) {
-
+ if ($params['type'] == NOTIFY_SYSTEM) {
+ // ?
}
$h = array(
- 'params' => $params,
+ 'params' => $params,
'subject' => $subject,
- 'preamble' => $preamble,
- 'epreamble' => $epreamble,
- 'body' => $body,
+ 'preamble' => $preamble,
+ 'epreamble' => $epreamble,
+ 'body' => $body,
'sitelink' => $sitelink,
'tsitelink' => $tsitelink,
'hsitelink' => $hsitelink,
'itemlink' => $itemlink
);
-
- call_hooks('enotify',$h);
+
+ call_hooks('enotify', $h);
$subject = $h['subject'];
$preamble = $h['preamble'];
@@ -319,16 +333,16 @@ function notification($params) {
$itemlink = $h['itemlink'];
- require_once('include/html2bbcode.php');
+ require_once('include/html2bbcode.php');
do {
$dups = false;
$hash = random_string();
- $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
+ $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
dbesc($hash));
- if(count($r))
+ if (count($r))
$dups = true;
- } while($dups == true);
+ } while ($dups === true);
$datarray = array();
@@ -348,10 +362,10 @@ function notification($params) {
$datarray['abort'] = false;
$datarray['item'] = $params['item'];
-
+
call_hooks('enotify_store', $datarray);
- if($datarray['abort']) {
+ if ($datarray['abort']) {
pop_lang();
return;
}
@@ -365,8 +379,8 @@ function notification($params) {
// So easiest solution to hide them from Notices is to mark them as seen right away.
// Another option would be to not add them to the DB, and change how emails are handled (probably would be better that way)
$always_show_in_notices = get_pconfig($recip['channel_id'],'system','always_show_in_notices');
- if(!$always_show_in_notices) {
- if(($params['type'] == NOTIFY_WALL) || ($params['type'] == NOTIFY_MAIL) || ($params['type'] == NOTIFY_INTRO)) {
+ if (!$always_show_in_notices) {
+ if (($params['type'] == NOTIFY_WALL) || ($params['type'] == NOTIFY_MAIL) || ($params['type'] == NOTIFY_INTRO)) {
$seen = 1;
}
}
@@ -392,9 +406,9 @@ function notification($params) {
dbesc($hash),
intval($recip['channel_id'])
);
- if($r)
+ if ($r) {
$notify_id = $r[0]['id'];
- else {
+ } else {
logger('notification not found.');
pop_lang();
return;
@@ -405,7 +419,7 @@ function notification($params) {
// wretched hack, but we don't want to duplicate all the preamble variations and we also don't want to screw up a translation
- if(($a->language === 'en' || (! $a->language)) && strpos($msg,', '))
+ if (($a->language === 'en' || (! $a->language)) && strpos($msg,', '))
$msg = substr($msg,strpos($msg,', ')+1);
$r = q("update notify set msg = '%s' where id = %d and uid = %d",
@@ -413,12 +427,11 @@ function notification($params) {
intval($notify_id),
intval($datarray['uid'])
);
-
// send email notification if notification preferences permit
require_once('bbcode.php');
- if((intval($recip['channel_notifyflags']) & intval($params['type'])) || $params['type'] == NOTIFY_SYSTEM) {
+ if ((intval($recip['channel_notifyflags']) & intval($params['type'])) || $params['type'] == NOTIFY_SYSTEM) {
logger('notification: sending notification email');
@@ -429,8 +442,6 @@ function notification($params) {
return;
}
-
-
$textversion = strip_tags(html_entity_decode(bbcode(stripslashes(str_replace(array("\\r", "\\n"), array( "", "\n"), $body))),ENT_QUOTES,'UTF-8'));
$htmlversion = bbcode(stripslashes(str_replace(array("\\r","\\n"), array("","<br />\n"),$body)));
@@ -450,7 +461,6 @@ function notification($params) {
unset($_SESSION['zid_override']);
unset($_SESSION['zrl_override']);
-
$datarray = array();
$datarray['banner'] = $banner;
$datarray['product'] = $product;
@@ -485,13 +495,13 @@ function notification($params) {
$private_activity = false;
- if(! $datarray['email_secure']) {
- switch($params['type']) {
+ if (! $datarray['email_secure']) {
+ switch ($params['type']) {
case NOTIFY_WALL:
case NOTIFY_TAGSELF:
case NOTIFY_POKE:
case NOTIFY_COMMENT:
- if(! $private)
+ if (! $private)
break;
$private_activity = true;
case NOTIFY_MAIL:
@@ -503,11 +513,12 @@ function notification($params) {
}
}
- if($private_activity
- && intval(get_pconfig($datarray['uid'],'system','ignore_private_notifications'))) {
+ if ($private_activity
+ && intval(get_pconfig($datarray['uid'], 'system', 'ignore_private_notifications'))) {
+
pop_lang();
return;
- }
+ }
// load the template for private message notifications
$tpl = get_markup_template('email_notify_html.tpl');
@@ -525,13 +536,13 @@ function notification($params) {
'$hitemlink' => $datarray['hitemlink'],
'$thanks' => $datarray['thanks'],
'$site_admin' => $datarray['site_admin'],
- '$title' => $datarray['title'],
- '$htmlversion' => $datarray['htmlversion'],
+ '$title' => $datarray['title'],
+ '$htmlversion' => $datarray['htmlversion'],
));
-
+
// load the template for private message notifications
$tpl = get_markup_template('email_notify_text.tpl');
- $email_text_body = replace_macros($tpl,array(
+ $email_text_body = replace_macros($tpl, array(
'$banner' => $datarray['banner'],
'$product' => $datarray['product'],
'$preamble' => $datarray['preamble'],
@@ -545,8 +556,8 @@ function notification($params) {
'$titemlink' => $datarray['titemlink'],
'$thanks' => $datarray['thanks'],
'$site_admin' => $datarray['site_admin'],
- '$title' => $datarray['title'],
- '$textversion' => $datarray['textversion'],
+ '$title' => $datarray['title'],
+ '$textversion' => $datarray['textversion'],
));
// logger('text: ' . $email_text_body);
@@ -570,41 +581,48 @@ function notification($params) {
}
+/**
+ * @brief A class for sending email notifications.
+ *
+ * @fixme Class names start mostly with capital letter to distinguish them easier.
+ */
class enotify {
/**
- * Send a multipart/alternative message with Text and HTML versions
+ * @brief Send a multipart/alternative message with Text and HTML versions.
*
- * @param fromName name of the sender
- * @param fromEmail email fo the sender
- * @param replyTo replyTo address to direct responses
- * @param toEmail destination email address
- * @param messageSubject subject of the message
- * @param htmlVersion html version of the message
- * @param textVersion text only version of the message
- * @param additionalMailHeader additions to the smtp mail header
+ * @param array $params an assoziative array with:
+ * * \e string \b fromName name of the sender
+ * * \e string \b fromEmail email of the sender
+ * * \e string \b replyTo replyTo address to direct responses
+ * * \e string \b toEmail destination email address
+ * * \e string \b messageSubject subject of the message
+ * * \e string \b htmlVersion html version of the message
+ * * \e string \b textVersion text only version of the message
+ * * \e string \b additionalMailHeader additions to the smtp mail header
*/
static public function send($params) {
$fromName = email_header_encode(html_entity_decode($params['fromName'],ENT_QUOTES,'UTF-8'),'UTF-8');
$messageSubject = email_header_encode(html_entity_decode($params['messageSubject'],ENT_QUOTES,'UTF-8'),'UTF-8');
-
+
// generate a mime boundary
- $mimeBoundary =rand(0,9)."-"
- .rand(10000000000,9999999999)."-"
- .rand(10000000000,9999999999)."=:"
- .rand(10000,99999);
+ $mimeBoundary = rand(0, 9) . "-"
+ .rand(10000000000, 9999999999) . "-"
+ .rand(10000000000, 9999999999) . "=:"
+ .rand(10000, 99999);
// generate a multipart/alternative message header
$messageHeader =
$params['additionalMailHeader'] .
- "From: $fromName <{$params['fromEmail']}>\n" .
+ "From: $fromName <{$params['fromEmail']}>\n" .
"Reply-To: $fromName <{$params['replyTo']}>\n" .
"MIME-Version: 1.0\n" .
"Content-Type: multipart/alternative; boundary=\"{$mimeBoundary}\"";
// assemble the final multipart message body with the text and html types included
- $textBody = chunk_split(base64_encode($params['textVersion']));
- $htmlBody = chunk_split(base64_encode($params['htmlVersion']));
+ $textBody = chunk_split(base64_encode($params['textVersion']));
+ $htmlBody = chunk_split(base64_encode($params['htmlVersion']));
+
$multipartMessageBody =
"--" . $mimeBoundary . "\n" . // plain text section
"Content-Type: text/plain; charset=UTF-8\n" .
@@ -618,12 +636,11 @@ class enotify {
// send the message
$res = mail(
- $params['toEmail'], // send to address
+ $params['toEmail'], // send to address
$messageSubject, // subject
- $multipartMessageBody, // message body
+ $multipartMessageBody, // message body
$messageHeader // message headers
);
logger("notification: enotify::send returns " . $res, LOGGER_DEBUG);
}
}
-
diff --git a/include/event.php b/include/event.php
index 9da7a42a9..498297157 100644
--- a/include/event.php
+++ b/include/event.php
@@ -1,6 +1,14 @@
-<?php /** @file */
-
-
+<?php
+/**
+ * @file include/event.php
+ */
+
+/**
+ * @brief Returns an event as HTML
+ *
+ * @param array $ev
+ * @return string
+ */
function format_event_html($ev) {
require_once('include/bbcode.php');
@@ -12,13 +20,12 @@ function format_event_html($ev) {
$o = '<div class="vevent">' . "\r\n";
-
$o .= '<p class="summary event-summary">' . bbcode($ev['summary']) . '</p>' . "\r\n";
$o .= '<p class="description event-description">' . bbcode($ev['description']) . '</p>' . "\r\n";
$o .= '<p class="event-start">' . t('Starts:') . ' <abbr class="dtstart" title="'
- . datetime_convert('UTC','UTC',$ev['start'], (($ev['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' ))
+ . datetime_convert('UTC', 'UTC', $ev['start'], (($ev['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' ))
. '" >'
. (($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 .= '<p class="event-location"> ' . t('Location:') . ' <span class="location">'
- . bbcode($ev['location'])
+ . bbcode($ev['location'])
. '</span></p>' . "\r\n";
$o .= '</div>' . "\r\n";
+
return $o;
}
-
function ical_wrapper($ev) {
if(! ((is_array($ev)) && count($ev)))
@@ -56,7 +63,7 @@ function ical_wrapper($ev) {
$o .= "\nVERSION:2.0";
$o .= "\nMETHOD:PUBLISH";
$o .= "\nPRODID:-//" . get_config('system','sitename') . "//" . RED_PLATFORM . "//" . strtoupper(get_app()->language). "\n";
- if(array_key_exists('start',$ev))
+ if(array_key_exists('start', $ev))
$o .= format_event_ical($ev);
else {
foreach($ev as $e) {
@@ -84,13 +91,15 @@ function format_event_ical($ev) {
if($ev['description'])
$o .= "\nDESCRIPTION:" . format_ical_text($ev['description']);
$o .= "\nEND:VEVENT\n";
+
return $o;
}
-function format_ical_text($s) {
+function format_ical_text($s) {
require_once('include/bbcode.php');
require_once('include/html2plain.php');
+
return(wordwrap(html2plain(bbcode($s)),72,"\n ",true));
}
@@ -117,16 +126,16 @@ function format_event_bbcode($ev) {
if($ev['adjust'])
$o .= '[event-adjust]' . $ev['adjust'] . '[/event-adjust]';
-
return $o;
-
}
+
function bbtovcal($s) {
$o = '';
$ev = bbtoevent($s);
if($ev['description'])
$o = format_event_html($ev);
+
return $o;
}
@@ -154,27 +163,41 @@ function bbtoevent($s) {
if(preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is",$s,$match))
$ev['adjust'] = $match[1];
$ev['nofinish'] = (((x($ev, 'start') && $ev['start']) && (!x($ev, 'finish') || !$ev['finish'])) ? 1 : 0);
- return $ev;
+ return $ev;
}
-
+/**
+ * @brief Sorts the given array of events by date.
+ *
+ * @see ev_compare()
+ * @param array $arr
+ * @return sorted array
+ */
function sort_by_date($arr) {
- if(is_array($arr))
- usort($arr,'ev_compare');
+ if (is_array($arr))
+ usort($arr, 'ev_compare');
+
return $arr;
}
-
-function ev_compare($a,$b) {
+/**
+ * @brief Compare function for events.
+ *
+ * @see sort_by_date()
+ * @param array $a
+ * @param array $b
+ * @return number return values like strcmp()
+ */
+function ev_compare($a, $b) {
$date_a = (($a['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$a['start']) : $a['start']);
$date_b = (($b['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$b['start']) : $b['start']);
- if($date_a === $date_b)
- return strcasecmp($a['description'],$b['description']);
-
- return strcmp($date_a,$date_b);
+ if ($date_a === $date_b)
+ return strcasecmp($a['description'], $b['description']);
+
+ return strcmp($date_a, $date_b);
}
@@ -182,11 +205,9 @@ function event_store_event($arr) {
$arr['created'] = (($arr['created']) ? $arr['created'] : datetime_convert());
$arr['edited'] = (($arr['edited']) ? $arr['edited'] : datetime_convert());
- $arr['type'] = (($arr['type']) ? $arr['type'] : 'event' );
+ $arr['type'] = (($arr['type']) ? $arr['type'] : 'event' );
$arr['event_xchan'] = (($arr['event_xchan']) ? $arr['event_xchan'] : '');
-
-
// Existing event being modified
if($arr['id'] || $arr['event_hash']) {
@@ -206,7 +227,6 @@ function event_store_event($arr) {
);
}
-
if(! $r)
return false;
@@ -216,7 +236,7 @@ function event_store_event($arr) {
}
$hash = $r[0]['event_hash'];
-
+
// The event changed. Update it.
$r = q("UPDATE `event` SET
@@ -251,14 +271,12 @@ function event_store_event($arr) {
intval($r[0]['id']),
intval($arr['uid'])
);
- }
- else {
+ } else {
- // New event. Store it.
+ // New event. Store it.
$hash = random_string();
-
$r = q("INSERT INTO event ( uid,aid,event_xchan,event_hash,created,edited,start,finish,summary,description,location,type,
adjust,nofinish,allow_cid,allow_gid,deny_cid,deny_gid)
VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' ) ",
@@ -280,7 +298,6 @@ function event_store_event($arr) {
dbesc($arr['allow_gid']),
dbesc($arr['deny_cid']),
dbesc($arr['deny_gid'])
-
);
}
@@ -292,7 +309,6 @@ function event_store_event($arr) {
return $r[0];
return false;
-
}
function event_addtocal($item_id, $uid) {
@@ -339,22 +355,21 @@ function event_addtocal($item_id, $uid) {
intval($item['id']),
intval($channel['channel_id'])
);
+
return true;
}
}
+
return false;
}
-
-function event_store_item($arr,$event) {
+function event_store_item($arr, $event) {
require_once('include/datetime.php');
require_once('include/items.php');
require_once('include/bbcode.php');
- $a = get_app();
-
$item = null;
if($arr['mid'] && $arr['uid']) {
@@ -370,28 +385,28 @@ function event_store_item($arr,$event) {
$item_arr = array();
$prefix = '';
- $birthday = false;
+// $birthday = false;
if($event['type'] === 'birthday') {
$prefix = t('This event has been added to your calendar.');
- $birthday = true;
+// $birthday = true;
// The event is created on your own site by the system, but appears to belong
// to the birthday person. It also isn't propagated - so we need to prevent
// folks from trying to comment on it. If you're looking at this and trying to
// fix it, you'll need to completely change the way birthday events are created
- // and send them out from the source. This has its own issues.
+ // and send them out from the source. This has its own issues.
$item_arr['comment_policy'] = 'none';
}
$r = q("SELECT * FROM item left join xchan on author_xchan = xchan_hash WHERE resource_id = '%s' AND resource_type = 'event' and uid = %d LIMIT 1",
- dbesc($event['event_hash']),
+ dbesc($event['event_hash']),
intval($arr['uid'])
);
if($r) {
- $obj = json_encode(array(
+ $object = json_encode(array(
'type' => ACTIVITY_OBJ_EVENT,
'id' => z_root() . '/event/' . $r[0]['resource_id'],
'title' => $arr['summary'],
@@ -409,7 +424,7 @@ function event_store_item($arr,$event) {
$private = (($arr['allow_cid'] || $arr['allow_gid'] || $arr['deny_cid'] || $arr['deny_gid']) ? 1 : 0);
- q("UPDATE item SET title = '%s', body = '%s', object = '%s', allow_cid = '%s', allow_gid = '%s', deny_cid = '%s', deny_gid = '%s', edited = '%s', item_flags = %d, item_private = %d WHERE id = %d AND uid = %d",
+ q("UPDATE item SET title = '%s', body = '%s', object = '%s', allow_cid = '%s', allow_gid = '%s', deny_cid = '%s', deny_gid = '%s', edited = '%s', item_flags = %d, item_private = %d, obj_type = '%s' WHERE id = %d AND uid = %d",
dbesc($arr['summary']),
dbesc($prefix . format_event_bbcode($arr)),
dbesc($object),
@@ -420,12 +435,12 @@ function event_store_item($arr,$event) {
dbesc($arr['edited']),
intval($r[0]['item_flags']),
intval($private),
+ dbesc(ACTIVITY_OBJ_EVENT),
intval($r[0]['id']),
intval($arr['uid'])
);
-
- $s = q("delete from term where oid = %d and otype = %d",
+ q("delete from term where oid = %d and otype = %d",
intval($r[0]['id']),
intval(TERM_OBJ_POST)
);
@@ -442,19 +457,18 @@ function event_store_item($arr,$event) {
dbesc($t['url'])
);
}
- }
+ }
$item_id = $r[0]['id'];
call_hooks('event_updated', $event['id']);
+
return $item_id;
- }
- else {
+ } else {
$z = q("select * from channel where channel_id = %d limit 1",
intval($arr['uid'])
);
-
$private = (($arr['allow_cid'] || $arr['allow_gid'] || $arr['deny_cid'] || $arr['deny_gid']) ? 1 : 0);
$item_wall = 0;
@@ -471,7 +485,6 @@ function event_store_item($arr,$event) {
$item_wall = 1;
$item_origin = 1;
}
-
}
if(! $arr['mid'])
@@ -482,8 +495,6 @@ function event_store_item($arr,$event) {
$item_arr['author_xchan'] = $arr['event_xchan'];
$item_arr['mid'] = $arr['mid'];
$item_arr['parent_mid'] = $arr['mid'];
-
-
$item_arr['owner_xchan'] = (($wall) ? $z[0]['channel_hash'] : $arr['event_xchan']);
$item_arr['author_xchan'] = $arr['event_xchan'];
$item_arr['title'] = $arr['summary'];
@@ -497,9 +508,8 @@ function event_store_item($arr,$event) {
$item_arr['item_origin'] = $item_origin;
$item_arr['item_thread_top'] = $item_thread_top;;
-
- if(array_key_exists('term',$arr))
- $item_arr['term'] = $arr['term'];
+ if(array_key_exists('term', $arr))
+ $item_arr['term'] = $arr['term'];
$item_arr['resource_type'] = 'event';
$item_arr['resource_id'] = $event['event_hash'];
@@ -514,15 +524,13 @@ function event_store_item($arr,$event) {
else
$item_arr['plink'] = z_root() . '/display/' . $item_arr['mid'];
-
$x = q("select * from xchan where xchan_hash = '%s' limit 1",
dbesc($arr['event_xchan'])
);
if($x) {
-
$item_arr['object'] = json_encode(array(
'type' => ACTIVITY_OBJ_EVENT,
- 'id' => z_root() . '/event/' . $hash,
+ 'id' => z_root() . '/event/' . $event['event_hash'],
'title' => $arr['summary'],
'content' => format_event_bbcode($arr),
'author' => array(
@@ -541,7 +549,7 @@ function event_store_item($arr,$event) {
$item_id = $res['item_id'];
- call_hooks("event_created", $event['id']);
+ call_hooks('event_created', $event['id']);
return $item_id;
}
diff --git a/include/expire.php b/include/expire.php
index b0bf55e4f..8ba9f746b 100644
--- a/include/expire.php
+++ b/include/expire.php
@@ -1,4 +1,7 @@
-<?php /** @file */
+<?php
+/**
+ * @file include/expire.php
+ */
require_once('boot.php');
require_once('include/cli_startup.php');
@@ -7,58 +10,91 @@ function expire_run($argv, $argc){
cli_startup();
+ // perform final cleanup on previously delete items
+
$r = q("select id from item where item_deleted = 1 and not (item_restrict & %d)>0 and changed < %s - INTERVAL %s",
intval(ITEM_PENDING_REMOVE),
db_utcnow(), db_quoteinterval('10 DAY')
);
- if($r) {
- foreach($r as $rr) {
- drop_item($rr['id'],false,DROPITEM_PHASE2);
+ if ($r) {
+ foreach ($r as $rr) {
+ drop_item($rr['id'], false, DROPITEM_PHASE2);
}
}
// physically remove anything that has been deleted for more than two months
+ /** @FIXME - this is a wretchedly inefficient query */
- $r = q("delete from item where ( item_restrict & %d )>0 and changed < %s - INTERVAL %s",
+ $r = q("delete from item where ( item_restrict & %d ) > 0 and changed < %s - INTERVAL %s",
intval(ITEM_PENDING_REMOVE),
db_utcnow(), db_quoteinterval('36 DAY')
);
- // make this optional as it could have a performance impact on large sites
+ /** @FIXME make this optional as it could have a performance impact on large sites */
- if(intval(get_config('system','optimize_items')))
+ if (intval(get_config('system', 'optimize_items')))
q("optimize table item");
logger('expire: start', LOGGER_DEBUG);
-
- $r = q("SELECT channel_id, channel_address, channel_expire_days from channel where channel_expire_days != 0");
- if($r && count($r)) {
- foreach($r as $rr) {
- logger('Expire: ' . $rr['channel_address'] . ' interval: ' . $rr['channel_expire_days'], LOGGER_DEBUG);
- item_expire($rr['channel_id'],$rr['channel_expire_days']);
+ $site_expire = get_config('system', 'default_expire_days');
+
+ logger('site_expire: ' . $site_expire);
+
+ $r = q("SELECT channel_id, channel_address, channel_pageflags, channel_expire_days from channel where true");
+
+ if ($r) {
+ foreach ($r as $rr) {
+
+ // expire the sys channel separately
+ if ($rr['channel_pageflags'] & PAGE_SYSTEM)
+ continue;
+
+ // service class default (if non-zero) over-rides the site default
+
+ $service_class_expire = service_class_fetch($rr['channel_id'], 'expire_days');
+ if (intval($service_class_expire))
+ $channel_expire = $service_class_expire;
+ else
+ $channel_expire = $site_expire;
+
+ if (intval($channel_expire) && (intval($channel_expire) < intval($rr['channel_expire_days'])) ||
+ intval($rr['channel_expire_days'] == 0)) {
+ $expire_days = $channel_expire;
+ } else {
+ $expire_days = $rr['channel_expire_days'];
+ }
+
+ // if the site or service class expiration is non-zero and less than person expiration, use that
+ logger('Expire: ' . $rr['channel_address'] . ' interval: ' . $expire_days, LOGGER_DEBUG);
+ item_expire($rr['channel_id'], $expire_days);
}
}
-
$x = get_sys_channel();
- if($x) {
+ if ($x) {
// this should probably just fetch the channel_expire_days from the sys channel,
// but there's no convenient way to set it.
- $expire_days = get_config('externals','expire_days');
- if($expire_days === false)
+ $expire_days = get_config('system', 'sys_expire_days');
+ if ($expire_days === false)
$expire_days = 30;
- if($expire_days)
- item_expire($x['channel_id'],$expire_days);
- }
+ if (intval($site_expire) && (intval($site_expire) < intval($expire_days))) {
+ $expire_days = $site_expire;
+ }
- return;
+ logger('Expire: sys interval: ' . $expire_days, LOGGER_DEBUG);
+
+ if ($expire_days)
+ item_expire($x['channel_id'], $expire_days);
+
+ logger('Expire: sys: done', LOGGER_DEBUG);
+ }
}
-if (array_search(__file__,get_included_files())===0){
- expire_run($argv,$argc);
- killme();
+if (array_search(__file__, get_included_files()) === 0){
+ expire_run($argv, $argc);
+ killme();
}
diff --git a/include/features.php b/include/features.php
index 6b4bc34c6..4121880a4 100644
--- a/include/features.php
+++ b/include/features.php
@@ -44,10 +44,8 @@ function get_features() {
array('webpages', t('Web Pages'), t('Provide managed web pages on your channel'),false),
array('private_notes', t('Private Notes'), t('Enables a tool to store notes and reminders'),false),
array('nav_channel_select', t('Navigation Channel Select'), t('Change channels directly from within the navigation dropdown menu'),false),
+ array('photo_location', t('Photo Location'), t('If location data is available on uploaded photos, link this to a map.'),false),
-
- //FIXME - needs a description, but how the hell do we explain this to normals?
- array('sendzid', t('Extended Identity Sharing'), t('Share your identity with all websites on the internet. When disabled, identity is only shared with sites in the matrix.'),false),
array('expert', t('Expert Mode'), t('Enable Expert Mode to provide advanced configuration options'),false),
array('premium_channel', t('Premium Channel'), t('Allows you to set restrictions and terms on those that connect with your channel'),false),
),
@@ -60,7 +58,8 @@ function get_features() {
array('large_photos', t('Large Photos'), t('Include large (640px) photo thumbnails in posts. If not enabled, use small (320px) photo thumbnails'),false),
array('channel_sources', t('Channel Sources'), t('Automatically import channel content from other channels or feeds'),false),
array('content_encrypt', t('Even More Encryption'), t('Allow optional encryption of content end-to-end with a shared secret key'),false),
- array('adult_photo_flagging', t('Flag Adult Photos'), t('Provide photo edit option to hide adult photos from default album view'),false),
+ array('consensus_tools', t('Enable voting tools'), t('Provide a class of post which others can vote on'),false),
+
),
// Network Tools
diff --git a/include/follow.php b/include/follow.php
index 2d6791420..fd4e1597a 100644
--- a/include/follow.php
+++ b/include/follow.php
@@ -227,10 +227,16 @@ function new_contact($uid,$url,$channel,$interactive = false, $confirm = false)
);
}
else {
- $r = q("insert into abook ( abook_account, abook_channel, abook_xchan, abook_flags, abook_their_perms, abook_my_perms, abook_created, abook_updated )
- values( %d, %d, '%s', %d, %d, %d, '%s', '%s' ) ",
+
+ $closeness = get_pconfig($uid,'system','new_abook_closeness');
+ if($closeness === false)
+ $closeness = 80;
+
+ $r = q("insert into abook ( abook_account, abook_channel, abook_closeness, abook_xchan, abook_flags, abook_their_perms, abook_my_perms, abook_created, abook_updated )
+ values( %d, %d, %d, '%s', %d, %d, %d, '%s', '%s' ) ",
intval($aid),
intval($uid),
+ intval($closeness),
dbesc($xchan_hash),
intval(($is_http) ? ABOOK_FLAG_FEED : 0),
intval(($is_http) ? $their_perms|PERMS_R_STREAM|PERMS_A_REPUBLISH : $their_perms),
diff --git a/include/group.php b/include/group.php
index 1e718aeaa..2e064473c 100644
--- a/include/group.php
+++ b/include/group.php
@@ -253,7 +253,7 @@ function group_side($every="connections",$each="group",$edit = false, $group_id
'text' => t('All Channels'),
'id' => 0,
'selected' => (($group_id == 0) ? 'group-selected' : ''),
- 'href' => $every,
+ 'href' => $every . (($every === 'network') ? '?f=&gid=0' : ''),
);
@@ -296,7 +296,7 @@ function group_side($every="connections",$each="group",$edit = false, $group_id
$o = replace_macros($tpl, array(
'$title' => t('Collections'),
'$edittext' => t('Edit collection'),
- '$createtext' => t('Create a new collection'),
+ '$createtext' => t('Add new collection'),
'$ungrouped' => (($every === 'contacts') ? t('Channels not in any collection') : ''),
'$groups' => $groups,
'$add' => t('add'),
diff --git a/include/hubloc.php b/include/hubloc.php
index 2367744ec..515223f53 100644
--- a/include/hubloc.php
+++ b/include/hubloc.php
@@ -169,10 +169,22 @@ function hubloc_change_primary($hubloc) {
return true;
}
-
+
+// We use the post url to distinguish between http and https hublocs.
+// The https might be alive, and the http dead.
+
+function hubloc_mark_as_down($posturl) {
+ $r = q("update hubloc set hubloc_status = ( hubloc_status | %d ) where hubloc_callback = '%s'",
+ intval(HUBLOC_OFFLINE),
+ dbesc($posturl)
+ );
+}
+
function xchan_store($arr) {
+ logger('xchan_store: ' . print_r($arr,true));
+
if(! $arr['hash'])
$arr['hash'] = $arr['guid'];
if(! $arr['hash'])
@@ -191,7 +203,7 @@ function xchan_store($arr) {
if(! $arr['url'])
$arr['url'] = z_root();
if(! $arr['photo'])
- $arr['photo'] = get_default_profile_photo();
+ $arr['photo'] = z_root() . '/' . get_default_profile_photo();
$r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_guid_sig, xchan_pubkey, xchan_addr, xchan_url, xchan_connurl, xchan_follow, xchan_connpage, xchan_name, xchan_network, xchan_instance_url, xchan_hidden, xchan_orphan, xchan_censored, xchan_selfcensored, xchan_system, xchan_pubforum, xchan_deleted, xchan_name_date ) values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s','%s','%s','%s',%d, %d, %d, %d, %d, %d, %d, '%s') ",
dbesc($arr['hash']),
@@ -251,12 +263,12 @@ function xchan_fetch($arr) {
if(! $key)
return false;
- $r = q("select * from xchan where $key = '$v'");
+ $r = q("select * from xchan where $key = '$v' limit 1");
if(! $r)
return false;
$ret = array();
- foreach($r as $k => $v) {
+ foreach($r[0] as $k => $v) {
if($k === 'xchan_addr')
$ret['address'] = $v;
else
diff --git a/include/identity.php b/include/identity.php
index 4a39070bd..16127f7d0 100644
--- a/include/identity.php
+++ b/include/identity.php
@@ -1,27 +1,29 @@
-<?php /** @file */
+<?php
+/**
+ * @file include/identity.php
+ */
require_once('include/zot.php');
require_once('include/crypto.php');
/**
- * @function identity_check_service_class($account_id)
- * Called when creating a new channel. Checks the account's service class and number
- * of current channels to determine whether creating a new channel is within the current
- * service class constraints.
+ * @brief Called when creating a new channel.
+ *
+ * Checks the account's service class and number of current channels to determine
+ * whether creating a new channel is within the current service class constraints.
*
* @param int $account_id
* Account_id used for this request
*
- * @returns array
- * 'success' => boolean true if creating a new channel is allowed for this account
- * 'message' => if success is false, optional error text
+ * @returns assoziative array with:
+ * * \e boolean \b success boolean true if creating a new channel is allowed for this account
+ * * \e string \b message (optional) if success is false, optional error text
+ * * \e int \b total_identities
*/
-
-
function identity_check_service_class($account_id) {
- $ret = array('success' => false, $message => '');
-
+ $ret = array('success' => false, 'message' => '');
+
$r = q("select count(channel_id) as total from channel where channel_account_id = %d and not ( channel_pageflags & %d )>0 ",
intval($account_id),
intval(PAGE_REMOVED)
@@ -30,68 +32,67 @@ function identity_check_service_class($account_id) {
$ret['total_identities'] = 0;
$ret['message'] = t('Unable to obtain identity information from database');
return $ret;
- }
+ }
$ret['total_identities'] = intval($r[0]['total']);
- if(! account_service_class_allows($account_id,'total_identities',$r[0]['total'])) {
- $result['message'] .= upgrade_message();
- return $result;
+ if (! account_service_class_allows($account_id, 'total_identities', $r[0]['total'])) {
+ $ret['message'] .= upgrade_message();
+ return $ret;
}
$ret['success'] = true;
+
return $ret;
}
/**
- * @function validate_channelname($name)
- * Determine if the channel name is allowed when creating a new channel.
+ * @brief Determine if the channel name is allowed when creating a new channel.
+ *
* This action is pluggable.
+ * We're currently only checking for an empty name or one that exceeds our
+ * storage limit (255 chars). 255 chars is probably going to create a mess on
+ * some pages.
+ * Plugins can set additional policies such as full name requirements, character
+ * sets, multi-byte length, etc.
*
* @param string $name
*
* @returns nil return if name is valid, or string describing the error state.
- *
- * We're currently only checking for an empty name or one that exceeds our storage limit (255 chars).
- * 255 chars is probably going to create a mess on some pages.
- * Plugins can set additional policies such as full name requirements, character sets, multi-byte
- * length, etc.
- *
*/
-
function validate_channelname($name) {
- if(! $name)
+ if (! $name)
return t('Empty name');
- if(strlen($name) > 255)
+
+ if (strlen($name) > 255)
return t('Name too long');
+
$arr = array('name' => $name);
- call_hooks('validate_channelname',$arr);
- if(x($arr,'message'))
+ call_hooks('validate_channelname', $arr);
+
+ if (x($arr, 'message'))
return $arr['message'];
- return;
}
/**
- * @function create_sys_channel()
- * Create a system channel - which has no account attached
+ * @brief Create a system channel - which has no account attached.
*
*/
-
function create_sys_channel() {
- if(get_sys_channel())
+ if (get_sys_channel())
return;
- // Ensure that there is a host keypair.
+ // Ensure that there is a host keypair.
- if((! get_config('system','pubkey')) && (! get_config('system','prvkey'))) {
+ if ((! get_config('system', 'pubkey')) && (! get_config('system', 'prvkey'))) {
require_once('include/crypto.php');
- $hostkey = new_keypair(4096);
- set_config('system','pubkey',$hostkey['pubkey']);
- set_config('system','prvkey',$hostkey['prvkey']);
- }
+ $hostkey = new_keypair(4096);
+ set_config('system', 'pubkey', $hostkey['pubkey']);
+ set_config('system', 'prvkey', $hostkey['prvkey']);
+ }
create_identity(array(
'account_id' => 'xxx', // This will create an identity with an (integer) account_id of 0, but account_id is required
@@ -103,63 +104,79 @@ function create_sys_channel() {
));
}
+
+/**
+ * @brief Returns the sys channel.
+ *
+ * @return array|boolean
+ */
function get_sys_channel() {
$r = q("select * from channel left join xchan on channel_hash = xchan_hash where (channel_pageflags & %d)>0 limit 1",
intval(PAGE_SYSTEM)
);
- if($r)
+
+ if ($r)
return $r[0];
+
return false;
}
+
+/**
+ * @brief Checks if $channel_id is sys channel.
+ *
+ * @param int $channel_id
+ * @return boolean
+ */
function is_sys_channel($channel_id) {
$r = q("select channel_pageflags from channel where channel_id = %d limit 1",
intval($channel_id)
);
- if(($r) && ($r[0]['channel_pageflags'] & PAGE_SYSTEM))
+
+ if (($r) && ($r[0]['channel_pageflags'] & PAGE_SYSTEM))
return true;
+
return false;
}
/**
- * @channel_total()
- * Return the total number of channels on this site. No filtering is performed except to check PAGE_REMOVED
+ * @brief Return the total number of channels on this site.
*
- * @returns int
- * on error returns boolean false
+ * No filtering is performed except to check PAGE_REMOVED.
*
+ * @returns int|booleean
+ * on error returns boolean false
*/
-
function channel_total() {
$r = q("select channel_id from channel where not ( channel_pageflags & %d )>0",
intval(PAGE_REMOVED)
);
- if(is_array($r))
+ if (is_array($r))
return count($r);
+
return false;
}
/**
- * @function create_identity($arr)
- * Create a new channel
- * Also creates the related xchan, hubloc, profile, and "self" abook records, and an
- * empty "Friends" group/collection for the new channel
+ * @brief Create a new channel.
*
- * @param array $arr
- * 'name' => full name of channel
- * 'nickname' => "email/url-compliant" nickname
- * 'account_id' => account_id to attach with this channel
- * [other identity fields as desired]
+ * Also creates the related xchan, hubloc, profile, and "self" abook records,
+ * and an empty "Friends" group/collection for the new channel.
+ *
+ * @param array $arr assoziative array with:
+ * * \e string \b name full name of channel
+ * * \e string \b nickname "email/url-compliant" nickname
+ * * \e int \b account_id to attach with this channel
+ * * [other identity fields as desired]
*
* @returns array
* 'success' => boolean true or false
* 'message' => optional error text if success is false
* 'channel' => if successful the created channel array
*/
-
function create_identity($arr) {
$a = get_app();
@@ -176,7 +193,6 @@ function create_identity($arr) {
// save this for auto_friending
$total_identities = $ret['total_identities'];
-
$nick = mb_strtolower(trim($arr['nickname']));
if(! $nick) {
$ret['message'] = t('Nickname is required.');
@@ -205,7 +221,6 @@ function create_identity($arr) {
$guid = zot_new_uid($nick);
$key = new_keypair(4096);
-
$sig = base64url_encode(rsa_sign($guid,$key['prvkey']));
$hash = make_xchan_hash($guid,$sig);
@@ -221,9 +236,6 @@ function create_identity($arr) {
if(array_key_exists('primary', $arr))
$primary = intval($arr['primary']);
-
- $perms_sql = '';
-
$role_permissions = null;
$global_perms = get_perms();
@@ -249,9 +261,7 @@ function create_identity($arr) {
}
}
-
- $expire = get_config('system', 'default_expire_days');
- $expire = (($expire===false)? '0': $expire);
+ $expire = 0;
$r = q("insert into channel ( channel_account_id, channel_primary,
channel_name, channel_address, channel_guid, channel_guid_sig,
@@ -271,7 +281,6 @@ function create_identity($arr) {
intval($expire),
dbesc($a->timezone)
);
-
$r = q("select * from channel where channel_account_id = %d
and channel_guid = '%s' limit 1",
@@ -283,7 +292,7 @@ function create_identity($arr) {
$ret['message'] = t('Unable to retrieve created identity');
return $ret;
}
-
+
$ret['channel'] = $r[0];
if(intval($arr['account_id']))
@@ -309,7 +318,6 @@ function create_identity($arr) {
if(! $r)
logger('create_identity: Unable to store hub location');
-
$newuid = $ret['channel']['channel_id'];
$r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_guid_sig, xchan_pubkey, xchan_photo_l, xchan_photo_m, xchan_photo_s, xchan_addr, xchan_url, xchan_follow, xchan_connurl, xchan_name, xchan_network, xchan_photo_date, xchan_name_date, xchan_system ) values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
@@ -331,9 +339,8 @@ function create_identity($arr) {
intval($system)
);
- // Not checking return value.
+ // Not checking return value.
// It's ok for this to fail if it's an imported channel, and therefore the hash is a duplicate
-
$r = q("INSERT INTO profile ( aid, uid, profile_guid, profile_name, is_default, publish, name, photo, thumb)
VALUES ( %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s') ",
@@ -420,37 +427,31 @@ function create_identity($arr) {
}
call_hooks('register_account', $newuid);
-
+
proc_run('php','include/directory.php', $ret['channel']['channel_id']);
}
$ret['success'] = true;
return $ret;
-
}
-
/**
- * @function set_default_login_identity($account_id, $channel_id, $force = true)
- * Set default channel to be used on login
+ * @brief Set default channel to be used on login.
*
* @param int $account_id
* login account
* @param int $channel_id
* channel id to set as default for this account
- * @param boolean force
+ * @param boolean $force
* if true, set this default unconditionally
* if $force is false only do this if there is no existing default
- *
- * @returns nil
*/
-
-function set_default_login_identity($account_id,$channel_id,$force = true) {
+function set_default_login_identity($account_id, $channel_id, $force = true) {
$r = q("select account_default_channel from account where account_id = %d limit 1",
intval($account_id)
);
- if($r) {
- if((intval($r[0]['account_default_channel']) == 0) || ($force)) {
+ if ($r) {
+ if ((intval($r[0]['account_default_channel']) == 0) || ($force)) {
$r = q("update account set account_default_channel = %d where account_id = %d",
intval($channel_id),
intval($account_id)
@@ -460,8 +461,7 @@ function set_default_login_identity($account_id,$channel_id,$force = true) {
}
/**
- * @function identity_basic_export($channel_id,$items = false)
- * Create an array representing the important channel information
+ * @brief Create an array representing the important channel information
* which would be necessary to create a nomadic identity clone. This includes
* most channel resources and connection information with the exception of content.
*
@@ -472,9 +472,7 @@ function set_default_login_identity($account_id,$channel_id,$force = true) {
*
* @returns array
* See function for details
- *
*/
-
function identity_basic_export($channel_id, $items = false) {
/*
@@ -538,7 +536,6 @@ function identity_basic_export($channel_id, $items = false) {
if($r)
$ret['config'] = $r;
-
$r = q("select type, data from photo where scale = 4 and profile = 1 and uid = %d limit 1",
intval($channel_id)
);
@@ -565,11 +562,9 @@ function identity_basic_export($channel_id, $items = false) {
if($r)
$ret['obj'] = $r;
-
if(! $items)
return $ret;
-
$r = q("select likes.*, item.mid from likes left join item on likes.iid = item.id where likes.channel_id = %d",
intval($channel_id)
);
@@ -577,17 +572,16 @@ function identity_basic_export($channel_id, $items = false) {
if($r)
$ret['likes'] = $r;
-
$r = q("select item_id.*, item.mid from item_id left join item on item_id.iid = item.id where item_id.uid = %d",
intval($channel_id)
);
-
+
if($r)
- $ret['item_id'] = $r;
+ $ret['item_id'] = $r;
- $key = get_config('system','prvkey');
+ //$key = get_config('system','prvkey');
- // warning: this may run into memory limits on smaller systems
+ /** @warning this may run into memory limits on smaller systems */
$r = q("select * from item where item_wall = 1 and item_deleted = 0 and uid = %d",
intval($channel_id)
@@ -598,25 +592,17 @@ function identity_basic_export($channel_id, $items = false) {
$r = fetch_post_tags($r,true);
foreach($r as $rr)
$ret['item'][] = encode_item($rr,true);
-
}
- return $ret;
+ return $ret;
}
-
/**
+ * @brief Loads a profile into the App structure.
*
- * @function : profile_load(&$a, $nickname, $profile)
- * Generate
- * @param App $a
- * @param string $nickname
- * @param string $profile
- *
- * Summary: Loads a profile into the App structure.
- * The function requires a writeable copy of the main App structure, and the nickname
- * of a valid channel.
+ * The function requires a writeable copy of the main App structure, and the
+ * nickname of a valid channel.
*
* Permissions of the current observer are checked. If a restricted profile is available
* to the current observer, that will be loaded instead of the channel default profile.
@@ -625,9 +611,10 @@ function identity_basic_export($channel_id, $items = false) {
*
* The channel default theme is also selected for use, unless over-riden elsewhere.
*
+ * @param[in,out] App &$a
+ * @param string $nickname
+ * @param string $profile
*/
-
-
function profile_load(&$a, $nickname, $profile = '') {
logger('profile_load: ' . $nickname . (($profile) ? ' profile: ' . $profile : ''));
@@ -635,7 +622,7 @@ function profile_load(&$a, $nickname, $profile = '') {
$user = q("select channel_id from channel where channel_address = '%s' limit 1",
dbesc($nickname)
);
-
+
if(! $user) {
logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
notice( t('Requested channel is not available.') . EOL );
@@ -683,7 +670,6 @@ function profile_load(&$a, $nickname, $profile = '') {
);
}
-
if(! $p) {
logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
notice( t('Requested profile is not available.') . EOL );
@@ -722,16 +708,18 @@ function profile_load(&$a, $nickname, $profile = '') {
$p[0]['extra_fields'] = $extra_fields;
- $z = q("select xchan_photo_date from xchan where xchan_hash = '%s' limit 1",
+ $z = q("select xchan_photo_date, xchan_addr from xchan where xchan_hash = '%s' limit 1",
dbesc($p[0]['channel_hash'])
);
- if($z)
+ if($z) {
$p[0]['picdate'] = $z[0]['xchan_photo_date'];
+ $p[0]['reddress'] = str_replace('@','&#xff20;',$z[0]['xchan_addr']);
+ }
-
// fetch user tags if this isn't the default profile
if(! $p[0]['is_default']) {
+ /** @BUG $profile_uid is undefinded for this query, so should not work. */
$x = q("select `keywords` from `profile` where uid = %d and `is_default` = 1 limit 1",
intval($profile_uid)
);
@@ -743,7 +731,6 @@ function profile_load(&$a, $nickname, $profile = '') {
$keywords = str_replace(array('#',',',' ',',,'),array('',' ',',',','),$p[0]['keywords']);
if(strlen($keywords) && $can_view_profile)
$a->page['htmlhead'] .= '<meta name="keywords" content="' . htmlentities($keywords,ENT_COMPAT,'UTF-8') . '" />' . "\r\n" ;
-
}
$a->profile = $p[0];
@@ -755,7 +742,6 @@ function profile_load(&$a, $nickname, $profile = '') {
if($can_view_profile) {
$online = get_online_status($nickname);
$a->profile['online_status'] = $online['result'];
-
}
if(local_channel()) {
@@ -763,7 +749,7 @@ function profile_load(&$a, $nickname, $profile = '') {
$_SESSION['mobile_theme'] = $a->profile['channel_mobile_theme'];
}
- /**
+ /*
* load/reload current theme info
*/
@@ -775,36 +761,34 @@ function profile_load(&$a, $nickname, $profile = '') {
// if (file_exists($theme_info_file)){
// require_once($theme_info_file);
// }
-
- return;
}
-function profile_create_sidebar(&$a,$connect = true) {
+/**
+ * @brief
+ *
+ * @param App &$a
+ * @param boolean $connect
+ */
+function profile_create_sidebar(&$a, $connect = true) {
- $block = (((get_config('system','block_public')) && (! local_channel()) && (! remote_channel())) ? true : false);
+ $block = (((get_config('system', 'block_public')) && (! local_channel()) && (! remote_channel())) ? true : false);
- $a->set_widget('profile',profile_sidebar($a->profile, $block, $connect));
- return;
+ $a->set_widget('profile', profile_sidebar($a->profile, $block, $connect));
}
-
/**
+ * @brief Formats a profile for display in the sidebar.
*
- * Function: profile_sidebar
- *
- * Formats a profile for display in the sidebar.
* It is very difficult to templatise the HTML completely
* because of all the conditional logic.
*
- * @parameter: array $profile
+ * @param array $profile
+ * @param int $block
+ * @param boolean $show_connect
*
- * Returns HTML string stuitable for sidebar inclusion
+ * @return HTML string suitable for sidebar inclusion
* Exceptions: Returns empty string if passed $profile is wrong type or not populated
- *
*/
-
-
-
function profile_sidebar($profile, $block = 0, $show_connect = true) {
$a = get_app();
@@ -813,13 +797,12 @@ function profile_sidebar($profile, $block = 0, $show_connect = true) {
$o = '';
$location = false;
- $address = false;
$pdesc = true;
+ $reddress = true;
if((! is_array($profile)) && (! count($profile)))
return $o;
-
head_set_icon($profile['thumb']);
$is_owner = (($profile['uid'] == local_channel()) ? true : false);
@@ -847,13 +830,11 @@ function profile_sidebar($profile, $block = 0, $show_connect = true) {
// show edit profile to yourself
if($is_owner) {
-
$profile['menu'] = array(
'chg_photo' => t('Change profile photo'),
'entries' => array(),
);
-
$multi_profiles = feature_enabled(local_channel(), 'multi_profiles');
if($multi_profiles) {
$profile['edit'] = array($a->get_baseurl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles'));
@@ -861,10 +842,9 @@ function profile_sidebar($profile, $block = 0, $show_connect = true) {
}
else
$profile['edit'] = array($a->get_baseurl() . '/profiles/' . $profile['id'], t('Edit Profile'),'',t('Edit Profile'));
-
+
$r = q("SELECT * FROM `profile` WHERE `uid` = %d",
local_channel());
-
if($r) {
foreach($r as $rr) {
@@ -891,27 +871,27 @@ function profile_sidebar($profile, $block = 0, $show_connect = true) {
|| (x($profile,'country_name') == 1))
$location = t('Location:');
- $profile['homepage'] = linkify($profile['homepage']);
+ $profile['homepage'] = linkify($profile['homepage'],true);
$gender = ((x($profile,'gender') == 1) ? t('Gender:') : False);
$marital = ((x($profile,'marital') == 1) ? t('Status:') : False);
$homepage = ((x($profile,'homepage') == 1) ? t('Homepage:') : False);
$profile['online'] = (($profile['online_status'] === 'online') ? t('Online Now') : False);
-logger('online: ' . $profile['online']);
+ logger('online: ' . $profile['online']);
if(! perm_is_allowed($profile['uid'],((is_array($observer)) ? $observer['xchan_hash'] : ''),'view_profile')) {
$block = true;
}
if(($profile['hidewall'] && (! local_channel()) && (! remote_channel())) || $block ) {
- $location = $pdesc = $gender = $marital = $homepage = $online = False;
+ $location = $reddress = $pdesc = $gender = $marital = $homepage = False;
}
$firstname = ((strpos($profile['channel_name'],' '))
? trim(substr($profile['channel_name'],0,strpos($profile['channel_name'],' '))) : $profile['channel_name']);
$lastname = (($firstname === $profile['channel_name']) ? '' : trim(substr($profile['channel_name'],strlen($firstname))));
- $diaspora = array(
+ $diaspora = array(
'podloc' => z_root(),
'searchable' => (($block) ? 'false' : 'true'),
'nickname' => $profile['channel_address'],
@@ -955,6 +935,7 @@ logger('online: ' . $profile['online']);
'$homepage' => $homepage,
'$chanmenu' => $channel_menu,
'$diaspora' => $diaspora,
+ '$reddress' => $reddress,
'$rating' => $z,
'$contact_block' => $contact_block,
));
@@ -967,9 +948,9 @@ logger('online: ' . $profile['online']);
}
-// FIXME or remove
-
-
+/**
+ * @FIXME or remove
+ */
function get_birthdays() {
$a = get_app();
@@ -1027,7 +1008,6 @@ logger('online: ' . $profile['online']);
$rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . t('[today]') : '');
$rr['startime'] = Null;
$rr['today'] = $today;
-
}
}
}
@@ -1041,14 +1021,13 @@ logger('online: ' . $profile['online']);
'$events' => $r,
'$lbr' => '{', // raw brackets mess up if/endif macro processing
'$rbr' => '}'
-
));
}
-// FIXME
-
-
+/**
+ * @FIXME
+ */
function get_events() {
require_once('include/bbcode.php');
@@ -1082,7 +1061,6 @@ logger('online: ' . $profile['online']);
}
$classtoday = (($istoday) ? 'event-today' : '');
-
foreach($r as &$rr) {
if($rr['adjust'])
$md = datetime_convert('UTC',$a->timezone,$rr['start'],'Y/m');
@@ -1129,19 +1107,19 @@ function advanced_profile(&$a) {
if($a->profile['name']) {
$tpl = get_markup_template('profile_advanced.tpl');
-
+
$profile = array();
-
+
$profile['fullname'] = array( t('Full Name:'), $a->profile['name'] ) ;
-
+
if($a->profile['gender']) $profile['gender'] = array( t('Gender:'), $a->profile['gender'] );
-
+
$ob_hash = get_observer_hash();
if($ob_hash && perm_is_allowed($a->profile['profile_uid'],$ob_hash,'post_like')) {
$profile['canlike'] = true;
$profile['likethis'] = t('Like this channel');
$profile['profile_guid'] = $a->profile['profile_guid'];
- }
+ }
$likers = q("select liker, xchan.* from likes left join xchan on liker = xchan_hash where channel_id = %d and target_type = '%s' and verb = '%s'",
intval($a->profile['profile_uid']),
@@ -1172,19 +1150,19 @@ function advanced_profile(&$a) {
: day_translate(datetime_convert('UTC','UTC','2001-' . substr($a->profile['dob'],5) . ' 00:00 +00:00',$short_bd_format)));
}
$profile['birthday'] = array( t('Birthday:'), $val);
-
}
- if($age = age($a->profile['dob'],$a->profile['timezone'],'')) $profile['age'] = array( t('Age:'), $age );
-
-
- if($a->profile['marital']) $profile['marital'] = array( t('Status:'), $a->profile['marital']);
+ if($age = age($a->profile['dob'],$a->profile['timezone'],''))
+ $profile['age'] = array( t('Age:'), $age );
+ if($a->profile['marital'])
+ $profile['marital'] = array( t('Status:'), $a->profile['marital']);
- if($a->profile['with']) $profile['marital']['with'] = bbcode($a->profile['with']);
+ if($a->profile['with'])
+ $profile['marital']['with'] = bbcode($a->profile['with']);
if(strlen($a->profile['howlong']) && $a->profile['howlong'] !== NULL_DATE) {
- $profile['howlong'] = relative_date($a->profile['howlong'], t('for %1$d %2$s'));
+ $profile['howlong'] = relative_date($a->profile['howlong'], t('for %1$d %2$s'));
}
if($a->profile['sexual']) $profile['sexual'] = array( t('Sexual Preference:'), $a->profile['sexual'] );
@@ -1240,54 +1218,55 @@ function advanced_profile(&$a) {
// logger('mod_profile: things: ' . print_r($things,true), LOGGER_DATA);
- return replace_macros($tpl, array(
- '$title' => t('Profile'),
+ return replace_macros($tpl, array(
+ '$title' => t('Profile'),
'$canlike' => (($profile['canlike'])? true : false),
'$likethis' => t('Like this thing'),
- '$profile' => $profile,
+ '$profile' => $profile,
'$things' => $things
- ));
- }
+ ));
+ }
return '';
}
-
-
function get_my_url() {
- if(x($_SESSION,'zrl_override'))
+ if(x($_SESSION, 'zrl_override'))
return $_SESSION['zrl_override'];
- if(x($_SESSION,'my_url'))
+ if(x($_SESSION, 'my_url'))
return $_SESSION['my_url'];
+
return false;
}
function get_my_address() {
- if(x($_SESSION,'zid_override'))
+ if(x($_SESSION, 'zid_override'))
return $_SESSION['zid_override'];
- if(x($_SESSION,'my_address'))
+ if(x($_SESSION, 'my_address'))
return $_SESSION['my_address'];
+
return false;
}
/**
- * @function zid_init(&$a)
- * If somebody arrives at our site using a zid, add their xchan to our DB if we don't have it already.
- * And if they aren't already authenticated here, attempt reverse magic auth.
+ * @brief
+ *
+ * If somebody arrives at our site using a zid, add their xchan to our DB if we don't have it already.
+ * And if they aren't already authenticated here, attempt reverse magic auth.
+ *
+ * @param App &$a
*
* @hooks 'zid_init'
* string 'zid' - their zid
* string 'url' - the destination url
- *
*/
-
function zid_init(&$a) {
$tmp_str = get_my_address();
if(validate_email($tmp_str)) {
proc_run('php','include/gprobe.php',bin2hex($tmp_str));
$arr = array('zid' => $tmp_str, 'url' => $a->cmd);
- call_hooks('zid_init',$arr);
+ call_hooks('zid_init',$arr);
if(! local_channel()) {
$r = q("select * from hubloc where hubloc_addr = '%s' order by hubloc_connected desc limit 1",
dbesc($tmp_str)
@@ -1309,8 +1288,8 @@ function zid_init(&$a) {
}
/**
- * @function zid($s,$address = '')
- * Adds a zid parameter to a url
+ * @brief Adds a zid parameter to a url.
+ *
* @param string $s
* The url to accept the zid
* @param boolean $address
@@ -1322,31 +1301,33 @@ function zid_init(&$a) {
* string zid - urlencoded zid
* string result - the return string we calculated, change it if you want to return something else
*/
-
-
function zid($s,$address = '') {
- if(! strlen($s) || strpos($s,'zid='))
+ if (! strlen($s) || strpos($s,'zid='))
return $s;
+
$has_params = ((strpos($s,'?')) ? true : false);
- $num_slashes = substr_count($s,'/');
- if(! $has_params)
- $has_params = ((strpos($s,'&')) ? true : false);
+ $num_slashes = substr_count($s, '/');
+ if (! $has_params)
+ $has_params = ((strpos($s, '&')) ? true : false);
+
$achar = strpos($s,'?') ? '&' : '?';
$mine = get_my_url();
$myaddr = (($address) ? $address : get_my_address());
- // FIXME checking against our own channel url is no longer reliable. We may have a lot
- // of urls attached to out channel. Should probably match against our site, since we
- // will not need to remote authenticate on our own site anyway.
+ /** @FIXME checking against our own channel url is no longer reliable. We may have a lot
+ * of urls attached to out channel. Should probably match against our site, since we
+ * will not need to remote authenticate on our own site anyway.
+ */
- if($mine && $myaddr && (! link_compare($mine,$s)))
+ if ($mine && $myaddr && (! link_compare($mine,$s)))
$zurl = $s . (($num_slashes >= 3) ? '' : '/') . $achar . 'zid=' . urlencode($myaddr);
else
$zurl = $s;
$arr = array('url' => $s, 'zid' => urlencode($myaddr), 'result' => $zurl);
call_hooks('zid', $arr);
+
return $arr['result'];
}
@@ -1366,55 +1347,45 @@ function get_theme_uid() {
$x = get_sys_channel();
if($x)
return $x['channel_id'];
- }
+ }
+
return $uid;
}
/**
-* @function get_default_profile_photo($size = 175)
-* Retrieves the path of the default_profile_photo for this system
-* with the specified size.
+* @brief Retrieves the path of the default_profile_photo for this system
+* with the specified size.
+*
* @param int $size
-* one of (175, 80, 48)
+* one of (175, 80, 48)
* @returns string
-*
*/
-
function get_default_profile_photo($size = 175) {
- $scheme = get_config('system','default_profile_photo');
- if(! $scheme)
- $scheme = 'rainbow_man';
- return 'images/default_profile_photos/' . $scheme . '/' . $size . '.png';
-}
+ $scheme = get_config('system','default_profile_photo');
+ if(! $scheme)
+ $scheme = 'rainbow_man';
+ return 'images/default_profile_photos/' . $scheme . '/' . $size . '.png';
+}
/**
+ * @brief Test whether a given identity is NOT a member of the Red Matrix.
*
- * @function is_foreigner($s)
- * Test whether a given identity is NOT a member of the Red Matrix
* @param string $s;
* xchan_hash of the identity in question
- *
* @returns boolean true or false
- *
*/
-
function is_foreigner($s) {
- return((strpbrk($s,'.:@')) ? true : false);
+ return((strpbrk($s, '.:@')) ? true : false);
}
-
/**
+ * @brief Test whether a given identity is a member of the Red Matrix.
*
- * @function is_member($s)
- * Test whether a given identity is a member of the Red Matrix
* @param string $s;
* xchan_hash of the identity in question
- *
* @returns boolean true or false
- *
*/
-
function is_member($s) {
return((is_foreigner($s)) ? false : true);
}
@@ -1461,8 +1432,8 @@ function remote_online_status($webbie) {
if($j)
$result = (($j['result']) ? $j['result'] : false);
}
- return $result;
+ return $result;
}
@@ -1474,17 +1445,20 @@ function get_channel_by_nick($nick) {
}
-
+/**
+ * @brief
+ *
+ * @return string
+ */
function identity_selector() {
- if(local_channel()) {
+ if (local_channel()) {
$r = q("select channel.*, xchan.* from channel left join xchan on channel.channel_hash = xchan.xchan_hash where channel.channel_account_id = %d and (channel_pageflags & %d) = 0 order by channel_name ",
intval(get_account_id()),
intval(PAGE_REMOVED)
);
- if(count($r) > 1) {
- $selected_channel = null;
- $account = get_app()->get_account();
- $o = replace_macros(get_markup_template('channel_id_select.tpl'),array(
+ if (count($r) > 1) {
+ //$account = get_app()->get_account();
+ $o = replace_macros(get_markup_template('channel_id_select.tpl'), array(
'$channels' => $r,
'$selected' => local_channel()
));
@@ -1504,6 +1478,7 @@ function is_public_profile() {
$channel = get_app()->get_channel();
if($channel && $channel['channel_r_profile'] == PERMS_PUBLIC)
return true;
+
return false;
}
@@ -1519,7 +1494,6 @@ function get_profile_fields_basic($filter = 0) {
$x[$f] = 1;
return $x;
-
}
@@ -1533,6 +1507,7 @@ function get_profile_fields_advanced($filter = 0) {
if($basic)
foreach($basic as $f => $v)
$x[$f] = $v;
+
if($profile_fields_advanced)
foreach($profile_fields_advanced as $f)
$x[$f] = 1;
@@ -1541,28 +1516,26 @@ function get_profile_fields_advanced($filter = 0) {
}
/**
- * @function notifications_off($channel_id)
- * Clear notifyflags for a channel - most likely during bulk import of content or other activity that is likely
- * to generate huge amounts of undesired notifications.
+ * @brief Clear notifyflags for a channel.
+ *
+ * Most likely during bulk import of content or other activity that is likely
+ * to generate huge amounts of undesired notifications.
+ *
* @param int $channel_id
* The channel to disable notifications for
* @returns int
* Current notification flag value. Send this to notifications_on() to restore the channel settings when finished
* with the activity requiring notifications_off();
*/
-
-
-
function notifications_off($channel_id) {
$r = q("select channel_notifyflags from channel where channel_id = %d limit 1",
intval($channel_id)
);
- $x = q("update channel set channel_notifyflags = 0 where channel_id = %d",
+ q("update channel set channel_notifyflags = 0 where channel_id = %d",
intval($channel_id)
);
return intval($r[0]['channel_notifyflags']);
-
}
@@ -1583,5 +1556,6 @@ function get_channel_default_perms($uid) {
);
if($r)
return $r[0]['abook_my_perms'];
+
return 0;
}
diff --git a/include/items.php b/include/items.php
index 4608d5d55..1eb1a6446 100755
--- a/include/items.php
+++ b/include/items.php
@@ -1,4 +1,10 @@
-<?php /** @file */
+<?php
+/**
+ * @file include/items.php
+ */
+
+/** @todo deprecated in newer SabreDAV releases Sabre\HTTP\URLUtil */
+use Sabre\DAV\URLUtil;
require_once('include/bbcode.php');
require_once('include/oembed.php');
@@ -6,8 +12,14 @@ require_once('include/crypto.php');
require_once('include/photo/photo_driver.php');
require_once('include/permissions.php');
-
-function collect_recipients($item,&$private_envelope) {
+/**
+ * @brief Collects recipients.
+ *
+ * @param array $item
+ * @param[out] boolean $private_envelope
+ * @return array containing the recipients
+ */
+function collect_recipients($item, &$private_envelope) {
require_once('include/group.php');
@@ -25,9 +37,9 @@ function collect_recipients($item,&$private_envelope) {
$recipients = array_unique(array_merge($allow_people,$allow_groups));
- // if you specifically deny somebody but haven't allowed anybody, we'll allow everybody in your
+ // if you specifically deny somebody but haven't allowed anybody, we'll allow everybody in your
// address book minus the denied connections. The post is still private and can't be seen publicly
- // as that would allow the denied person to see the post by logging out.
+ // as that would allow the denied person to see the post by logging out.
if((! $item['allow_cid']) && (! $item['allow_gid'])) {
$r = q("select * from abook where abook_channel = %d and not (abook_flags & %d)>0 ",
@@ -57,17 +69,17 @@ function collect_recipients($item,&$private_envelope) {
}
else {
- // if the post is marked private but there are no recipients and public_policy/scope = self,
+ // if the post is marked private but there are no recipients and public_policy/scope = self,
// only add the author and owner as recipients. The ACL for the post may live on the hub of
// a different clone. We need to get the post to that hub.
// The post may be private by virtue of not being visible to anybody on the internet,
- // but there are no envelope recipients, so set this to false. Delivery is controlled
+ // but there are no envelope recipients, so set this to false. Delivery is controlled
// by the directives in $item['public_policy'].
$private_envelope = false;
require_once('include/identity.php');
- $sys = get_sys_channel();
+ //$sys = get_sys_channel();
if(array_key_exists('public_policy',$item) && $item['public_policy'] !== 'self') {
$r = q("select abook_xchan, xchan_network from abook left join xchan on abook_xchan = xchan_hash where abook_channel = %d and not (abook_flags & %d)>0 ",
@@ -84,7 +96,7 @@ function collect_recipients($item,&$private_envelope) {
switch($policy) {
case 'net':
case 'aut':
- case 'sit':
+ case 'sit':
case 'any':
case 'con':
if($rr['xchan_network'] != 'zot')
@@ -103,17 +115,16 @@ function collect_recipients($item,&$private_envelope) {
}
}
-
// This is a somewhat expensive operation but important.
// Don't send this item to anybody who isn't allowed to see it
$recipients = check_list_permissions($item['uid'],$recipients,'view_stream');
- // remove any upstream recipients from our list.
+ // remove any upstream recipients from our list.
// If it is ourself we'll add it back in a second.
- // This should prevent complex delivery chains from getting overly complex by not
+ // This should prevent complex delivery chains from getting overly complex by not
// sending to anybody who is on our list of those who sent it to us.
-
+
if($item['route']) {
$route = explode(',',$item['route']);
if(count($route)) {
@@ -123,13 +134,12 @@ function collect_recipients($item,&$private_envelope) {
}
// add ourself just in case we have nomadic clones that need to get a copy.
-
+
$recipients[] = $item['author_xchan'];
if($item['owner_xchan'] != $item['author_xchan'])
$recipients[] = $item['owner_xchan'];
return $recipients;
-
}
/**
@@ -139,30 +149,35 @@ function collect_recipients($item,&$private_envelope) {
* They can still be addressed individually.
* Networks may need to be added or removed from this list as circumstances change.
*
- * Update: this may need to be the default, which will force people to opt-in to sending stuff
- * privately to insecure platforms.
+ * Update: this may need to be the default, which will force people to opt-in to
+ * sending stuff privately to insecure platforms.
+ *
+ * @param int $channel_id
+ * @param array $arr
+ * @return array containing the sane xchan_hashes
*/
-
-function filter_insecure($channel_id,$arr) {
+function filter_insecure($channel_id, $arr) {
$insecure_nets = " and not xchan_network in ('diaspora', 'friendica-over-diaspora') ";
$ret = array();
- if((! intval(get_config($channel_id,'system','filter_insecure_collections'))) || (! $arr))
+ if((! intval(get_config($channel_id, 'system', 'filter_insecure_collections'))) || (! $arr))
return $arr;
$str = '';
foreach($arr as $rr) {
if(strlen($str))
$str .= ',';
+
$str .= "'" . dbesc($rr) . "'";
}
- $r = q("select xchan_hash from xchan where xchan_hash in ($str) $insecure_nets ");
+ $r = q("select xchan_hash from xchan where xchan_hash in ($str) $insecure_nets");
if($r) {
foreach($r as $rr) {
$ret[] = $rr['xchan_hash'];
}
}
+
return $ret;
}
@@ -173,30 +188,33 @@ function comments_are_now_closed($item) {
if($d > $item['comments_closed'])
return true;
}
+
return false;
}
/**
- * @function can_comment_on_post($observer_xchan,$item);
+ * @brief
*
* This function examines the comment_policy attached to an item and decides if the current observer has
* sufficient privileges to comment. This will normally be called on a remote site where perm_is_allowed()
* will not be suitable because the post owner does not have a local channel_id.
* Generally we should look at the item - in particular the author['book_flags'] and see if ABOOK_FLAG_SELF is set.
- * If it is, you should be able to use perm_is_allowed( ... 'post_comments'), and if it isn't you need to call
+ * If it is, you should be able to use perm_is_allowed( ... 'post_comments'), and if it isn't you need to call
* can_comment_on_post()
- * We also check the comments_closed date/time on the item if this is set.
+ * We also check the comments_closed date/time on the item if this is set.
+ *
+ * @param string $observer_xchan
+ * @param array $item
+ * @return boolean
*/
-
-function can_comment_on_post($observer_xchan,$item) {
+function can_comment_on_post($observer_xchan, $item) {
// logger('can_comment_on_post: comment_policy: ' . $item['comment_policy'], LOGGER_DEBUG);
if(! $observer_xchan)
return false;
-
if($item['comment_policy'] === 'none')
return false;
@@ -205,15 +223,16 @@ function can_comment_on_post($observer_xchan,$item) {
if($observer_xchan === $item['author_xchan'] || $observer_xchan === $item['owner_xchan'])
return true;
+
switch($item['comment_policy']) {
case 'self':
if($observer_xchan === $item['author_xchan'] || $observer_xchan === $item['owner_xchan'])
return true;
break;
case 'public':
- // We don't allow public comments yet, until a policy
- // for dealing with anonymous comments is in place with
- // a means to moderate comments. Until that time, return
+ // We don't allow public comments yet, until a policy
+ // for dealing with anonymous comments is in place with
+ // a means to moderate comments. Until that time, return
// false.
return false;
break;
@@ -233,36 +252,36 @@ function can_comment_on_post($observer_xchan,$item) {
return true;
if(strstr($item['comment_policy'],'site:') && strstr($item['comment_policy'],get_app()->get_hostname()))
return true;
-
+
return false;
}
/**
- * @function add_source_route($iid,$hash)
- * Adds $hash to the item source route specified by $iid
- * @param integer $iid
- * item['id'] of target item
- * @param string $hash
- * xchan_hash of the channel that sent the item
- * Modifies item pointed to by $iid
+ * @brief Adds $hash to the item source route specified by $iid.
*
- * $item['route'] contains a comma-separated list of xchans that sent the current message,
+ * $item['route'] contains a comma-separated list of xchans that sent the current message,
* somewhat analogous to the * Received: header line in email. We can use this to perform
- * loop detection and to avoid sending a particular item to any "upstream" sender (they
- * already have a copy because they sent it to us).
+ * loop detection and to avoid sending a particular item to any "upstream" sender (they
+ * already have a copy because they sent it to us).
+ *
+ * Modifies item in the database pointed to by $iid.
*
+ * @param integer $iid
+ * item['id'] of target item
+ * @param string $hash
+ * xchan_hash of the channel that sent the item
*/
-
-function add_source_route($iid,$hash) {
+function add_source_route($iid, $hash) {
// logger('add_source_route ' . $iid . ' ' . $hash, LOGGER_DEBUG);
if((! $iid) || (! $hash))
return;
+
$r = q("select route from item where id = %d limit 1",
intval($iid)
);
if($r) {
- $new_route = (($r[0]['route']) ? $r[0]['route'] . ',' : '') . $hash;
+ $new_route = (($r[0]['route']) ? $r[0]['route'] . ',' : '') . $hash;
q("update item set route = '%s' where id = %d",
(dbesc($new_route)),
intval($iid)
@@ -271,17 +290,17 @@ function add_source_route($iid,$hash) {
}
-
/**
- * @function red_zrl_callback
- * preg_match function when fixing 'naked' links in mod item.php
- * Check if we've got a hubloc for the site and use a zrl if we do, a url if we don't.
- * Remove any existing zid= param which may have been pasted by mistake - and will have
- * the author's credentials. zid's are dynamic and can't really be passed around like
- * that.
+ * @brief preg_match function when fixing 'naked' links in mod item.php.
+ *
+ * Check if we've got a hubloc for the site and use a zrl if we do, a url if we don't.
+ * Remove any existing zid= param which may have been pasted by mistake - and will have
+ * the author's credentials. zid's are dynamic and can't really be passed around like
+ * that.
+ *
+ * @param array $matches
+ * @return string
*/
-
-
function red_zrl_callback($matches) {
require_once('include/hubloc.php');
$zrl = is_matrix_url($matches[2]);
@@ -296,19 +315,24 @@ function red_zrl_callback($matches) {
$matches[1] = '';
if($zrl)
return $matches[1] . '#^[zrl=' . $matches[2] . ']' . $matches[2] . '[/zrl]';
+
return $matches[1] . '#^[url=' . $matches[2] . ']' . $matches[2] . '[/url]';
}
-
-// If we've got a url or zrl tag with a naked url somewhere in the link text,
-// escape it with quotes unless the naked url is a linked photo.
-
+/**
+ * If we've got a url or zrl tag with a naked url somewhere in the link text,
+ * escape it with quotes unless the naked url is a linked photo.
+ *
+ * @param array $matches
+ * @return string
+ */
function red_escape_zrl_callback($matches) {
// Uncertain why the url/zrl forms weren't picked up by the non-greedy regex.
- if((strpos($matches[3],'zmg') !== false) || (strpos($matches[3],'img') !== false) || (strpos($matches[3],'zrl') !== false) || (strpos($matches[3],'url') !== false))
+ if((strpos($matches[3], 'zmg') !== false) || (strpos($matches[3], 'img') !== false) || (strpos($matches[3],'zrl') !== false) || (strpos($matches[3],'url') !== false))
return $matches[0];
+
return '[' . $matches[1] . 'rl' . $matches[2] . ']' . $matches[3] . '"' . $matches[4] . '"' . $matches[5] . '[/' . $matches[6] . 'rl]';
}
@@ -318,7 +342,6 @@ function red_escape_codeblock($m) {
function red_unescape_codeblock($m) {
return '[' . $m[2] . base64_decode($m[1]) . '[/' . $m[2] . ']';
-
}
@@ -334,28 +357,23 @@ function red_zrlify_img_callback($matches) {
if($zrl)
return '[zmg' . $matches[1] . ']' . $matches[2] . '[/zmg]';
+
return $matches[0];
}
-
-
/**
- * @function post_activity_item($arr)
- *
- * post an activity
- *
- * @param array $arr
+ * @brief Post an activity.
*
* In its simplest form one needs only to set $arr['body'] to post a note to the logged in channel's wall.
- * Much more complex activities can be created. Permissions are checked. No filtering, tag expansion
+ * Much more complex activities can be created. Permissions are checked. No filtering, tag expansion
* or other processing is performed.
*
- * @returns array
- * 'success' => true or false
- * 'activity' => the resulting activity if successful
+ * @param array $arr
+ * @returns array
+ * * \e boolean \b success true or false
+ * * \e array \b activity the resulting activity if successful
*/
-
function post_activity_item($arr) {
$ret = array('success' => false);
@@ -374,8 +392,8 @@ function post_activity_item($arr) {
$channel = get_app()->get_channel();
$observer = get_app()->get_observer();
- $arr['aid'] = ((x($arr,'aid')) ? $arr['aid'] : $channel['channel_account_id']);
- $arr['uid'] = ((x($arr,'uid')) ? $arr['uid'] : $channel['channel_id']);
+ $arr['aid'] = ((x($arr,'aid')) ? $arr['aid'] : $channel['channel_account_id']);
+ $arr['uid'] = ((x($arr,'uid')) ? $arr['uid'] : $channel['channel_id']);
if(! perm_is_allowed($arr['uid'],$observer['xchan_hash'],(($is_comment) ? 'post_comments' : 'post_wall'))) {
$ret['message'] = t('Permission denied');
@@ -409,26 +427,24 @@ function post_activity_item($arr) {
$arr['body'] = json_encode(crypto_encapsulate($arr['body'],$key));
}
- $arr['mid'] = ((x($arr,'mid')) ? $arr['mid'] : item_message_id());
- $arr['parent_mid'] = ((x($arr,'parent_mid')) ? $arr['parent_mid'] : $arr['mid']);
- $arr['thr_parent'] = ((x($arr,'thr_parent')) ? $arr['thr_parent'] : $arr['mid']);
+ $arr['mid'] = ((x($arr,'mid')) ? $arr['mid'] : item_message_id());
+ $arr['parent_mid'] = ((x($arr,'parent_mid')) ? $arr['parent_mid'] : $arr['mid']);
+ $arr['thr_parent'] = ((x($arr,'thr_parent')) ? $arr['thr_parent'] : $arr['mid']);
- $arr['owner_xchan'] = ((x($arr,'owner_xchan')) ? $arr['owner_xchan'] : $channel['channel_hash']);
- $arr['author_xchan'] = ((x($arr,'author_xchan')) ? $arr['author_xchan'] : $observer['xchan_hash']);
+ $arr['owner_xchan'] = ((x($arr,'owner_xchan')) ? $arr['owner_xchan'] : $channel['channel_hash']);
+ $arr['author_xchan'] = ((x($arr,'author_xchan')) ? $arr['author_xchan'] : $observer['xchan_hash']);
- $arr['verb'] = ((x($arr,'verb')) ? $arr['verb'] : ACTIVITY_POST);
- $arr['obj_type'] = ((x($arr,'obj_type')) ? $arr['obj_type'] : ACTIVITY_OBJ_NOTE);
- if($is_comment)
+ $arr['verb'] = ((x($arr,'verb')) ? $arr['verb'] : ACTIVITY_POST);
+ $arr['obj_type'] = ((x($arr,'obj_type')) ? $arr['obj_type'] : ACTIVITY_OBJ_NOTE);
+ if(($is_comment) && ($arr['obj_type'] === ACTIVITY_OBJ_NOTE))
$arr['obj_type'] = ACTIVITY_OBJ_COMMENT;
-
$arr['allow_cid'] = ((x($arr,'allow_cid')) ? $arr['allow_cid'] : $channel['channel_allow_cid']);
$arr['allow_gid'] = ((x($arr,'allow_gid')) ? $arr['allow_gid'] : $channel['channel_allow_gid']);
$arr['deny_cid'] = ((x($arr,'deny_cid')) ? $arr['deny_cid'] : $channel['channel_deny_cid']);
$arr['deny_gid'] = ((x($arr,'deny_gid')) ? $arr['deny_gid'] : $channel['channel_deny_gid']);
- $arr['comment_policy'] = map_scope($channel['channel_w_comment']);
-
+ $arr['comment_policy'] = map_scope($channel['channel_w_comment']);
if ((! $arr['plink']) && (intval($arr['item_thread_top']))) {
$arr['plink'] = z_root() . '/channel/' . $channel['channel_address'] . '/?f=&mid=' . $arr['mid'];
@@ -446,8 +462,7 @@ function post_activity_item($arr) {
return $ret;
}
-
- $post = item_store($arr);
+ $post = item_store($arr);
if($post['success'])
$post_id = $post['item_id'];
@@ -464,15 +479,15 @@ function post_activity_item($arr) {
}
return $ret;
-
}
/**
- * @function get_public_feed($channel,$params)
- * generate an Atom feed
+ * @brief Generate an Atom feed.
+ *
+ * @param array $channel
+ * @param array $params
*/
-
-function get_public_feed($channel,$params) {
+function get_public_feed($channel, $params) {
$type = 'xml';
$begin = NULL_DATE;
@@ -493,7 +508,7 @@ function get_public_feed($channel,$params) {
$params['direction'] = ((x($params,'direction')) ? $params['direction'] : 'desc');
$params['pages'] = ((x($params,'pages')) ? intval($params['pages']) : 0);
$params['top'] = ((x($params,'top')) ? intval($params['top']) : 0);
-
+
switch($params['type']) {
case 'json':
header("Content-type: application/atom+json");
@@ -504,24 +519,26 @@ function get_public_feed($channel,$params) {
break;
}
-
- return get_feed_for($channel,get_observer_hash(),$params);
+ return get_feed_for($channel, get_observer_hash(), $params);
}
-
-
-
+/**
+ * @brief
+ *
+ * @param array $channel
+ * @param string $observer_hash
+ * @param array $params
+ * @return string
+ */
function get_feed_for($channel, $observer_hash, $params) {
if(! channel)
http_status_exit(401);
-
if($params['pages']) {
if(! perm_is_allowed($channel['channel_id'],$observer_hash,'view_pages'))
http_status_exit(403);
- }
- else {
+ } else {
if(! perm_is_allowed($channel['channel_id'],$observer_hash,'view_stream'))
http_status_exit(403);
}
@@ -537,7 +554,6 @@ function get_feed_for($channel, $observer_hash, $params) {
'top' => $params['top']
), $channel, $observer_hash, CLIENT_MODE_NORMAL, get_app()->module);
-
$feed_template = get_markup_template('atom_feed.tpl');
$atom = '';
@@ -570,7 +586,8 @@ function get_feed_for($channel, $observer_hash, $params) {
if($item['item_private'])
continue;
- $atom .= atom_entry($item,$type,null,$owner,true);
+ /** @BUG $owner is undefined in this call */
+ $atom .= atom_entry($item, $type, null, $owner, true);
}
}
@@ -581,10 +598,17 @@ function get_feed_for($channel, $observer_hash, $params) {
return $atom;
}
-
+/**
+ * @brief
+ *
+ * @param array $item an associative array with
+ * * \b string \b verb
+ * @return string item's verb if set, default ACTIVITY_POST see boot.php
+ */
function construct_verb($item) {
- if($item['verb'])
+ if ($item['verb'])
return $item['verb'];
+
return ACTIVITY_POST;
}
@@ -603,11 +627,11 @@ function construct_activity_object($item) {
if($r->title)
$o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
if($r->links) {
- // FIXME!!
+ /** @FIXME!! */
if(substr($r->link,0,1) === '<') {
$r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
$o .= $r->link;
- }
+ }
else
$o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
}
@@ -618,7 +642,7 @@ function construct_activity_object($item) {
}
return '';
-}
+}
function construct_activity_target($item) {
@@ -634,31 +658,36 @@ function construct_activity_target($item) {
if($r->title)
$o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
if($r->links) {
- // FIXME !!!
+ /** @FIXME !!! */
if(substr($r->link,0,1) === '<') {
if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
$r->link = str_replace('&','&amp;', $r->link);
$r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
$o .= $r->link;
- }
+ }
else
$o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
}
if($r->content)
$o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
+
$o .= '</as:target>' . "\r\n";
+
return $o;
}
return '';
}
-/* limit_body_size()
+/**
+ * @brief Limit lenght on imported system messages.
+ *
+ * The purpose of this function is to apply system message length limits to
+ * imported messages without including any embedded photos in the length.
*
- * The purpose of this function is to apply system message length limits to
- * imported messages without including any embedded photos in the length
+ * @param string $body
+ * @return string
*/
-
function limit_body_size($body) {
$maxlen = get_max_import_size();
@@ -670,7 +699,6 @@ function limit_body_size($body) {
$orig_body = $body;
$new_body = '';
$textlen = 0;
- $max_found = false;
$img_start = strpos($orig_body, '[img');
$img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
@@ -699,7 +727,6 @@ function limit_body_size($body) {
$new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start);
}
else {
-
if( ($textlen + $img_end) > $maxlen ) {
if($textlen < $maxlen) {
$new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
@@ -785,15 +812,15 @@ function get_item_elements($x) {
if($arr['edited'] > datetime_convert())
$arr['edited'] = datetime_convert();
- $arr['expires'] = ((x($x,'expires') && $x['expires'])
- ? datetime_convert('UTC','UTC',$x['expires'])
+ $arr['expires'] = ((x($x,'expires') && $x['expires'])
+ ? datetime_convert('UTC','UTC',$x['expires'])
: NULL_DATE);
- $arr['commented'] = ((x($x,'commented') && $x['commented'])
- ? datetime_convert('UTC','UTC',$x['commented'])
+ $arr['commented'] = ((x($x,'commented') && $x['commented'])
+ ? datetime_convert('UTC','UTC',$x['commented'])
: $arr['created']);
- $arr['comments_closed'] = ((x($x,'comments_closed') && $x['comments_closed'])
- ? datetime_convert('UTC','UTC',$x['comments_closed'])
+ $arr['comments_closed'] = ((x($x,'comments_closed') && $x['comments_closed'])
+ ? datetime_convert('UTC','UTC',$x['comments_closed'])
: NULL_DATE);
$arr['title'] = (($x['title']) ? htmlspecialchars($x['title'], ENT_COMPAT,'UTF-8',false) : '');
@@ -864,7 +891,6 @@ function get_item_elements($x) {
return array();
}
-
if($arr['sig']) {
$r = q("select xchan_pubkey from xchan where xchan_hash = '%s' limit 1",
dbesc($arr['author_xchan'])
@@ -878,8 +904,7 @@ function get_item_elements($x) {
// if it's a private post, encrypt it in the DB.
// We have to do that here because we need to cleanse the input and prevent bad stuff from getting in,
- // and we need plaintext to do that.
-
+ // and we need plaintext to do that.
if(intval($arr['item_private'])) {
@@ -906,11 +931,9 @@ function get_item_elements($x) {
$arr['item_restrict'] = $x['item_restrict'];
$arr['item_flags'] = $x['item_flags'];
$arr['attach'] = $x['attach'];
-
}
return $arr;
-
}
@@ -938,10 +961,17 @@ function import_author_xchan($x) {
return(($y) ? $y : false);
}
-
+/**
+ * @brief Imports an author from Diaspora.
+ *
+ * @param array $x an associative array with
+ * * \e string \b address
+ * @return boolean|string false on error, otherwise xchan_hash of the new entry
+ */
function import_author_diaspora($x) {
if(! $x['address'])
return false;
+
if(discover_by_webbie($x['address'])) {
$r = q("select xchan_hash from xchan where xchan_addr = '%s' limit 1",
dbesc($x['address'])
@@ -949,12 +979,20 @@ function import_author_diaspora($x) {
if($r)
return $r[0]['xchan_hash'];
}
+
return false;
}
-
+/**
+ * @brief Imports an author from a RSS feed.
+ *
+ * @param array $x an associative array with
+ * * \e string \b url
+ * * \e string \b name
+ * * \e string \b guid
+ * @return boolean|string
+ */
function import_author_rss($x) {
-
if(! $x['url'])
return false;
@@ -967,7 +1005,7 @@ function import_author_rss($x) {
}
$name = trim($x['name']);
- $r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_url, xchan_name, xchan_network )
+ $r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_url, xchan_name, xchan_network )
values ( '%s', '%s', '%s', '%s', '%s' )",
dbesc($x['guid']),
dbesc($x['guid']),
@@ -975,13 +1013,15 @@ function import_author_rss($x) {
dbesc(($name) ? $name : t('(Unknown)')),
dbesc('rss')
);
+
if($r && $x['photo']) {
$photos = import_profile_photo($x['photo']['src'],$x['url']);
if($photos) {
+ /** @bug $arr is undefined in this SQL query */
$r = q("update xchan set xchan_photo_date = '%s', xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' where xchan_url = '%s' and xchan_network = 'rss'",
- dbesc(datetime_convert('UTC','UTC',$arr['photo_updated'])),
+ dbesc(datetime_convert('UTC', 'UTC', $arr['photo_updated'])),
dbesc($photos[0]),
dbesc($photos[1]),
dbesc($photos[2]),
@@ -994,7 +1034,6 @@ function import_author_rss($x) {
}
return false;
-
}
function import_author_unknown($x) {
@@ -1012,7 +1051,7 @@ function import_author_unknown($x) {
$name = trim($x['name']);
- $r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_url, xchan_name, xchan_network )
+ $r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_url, xchan_name, xchan_network )
values ( '%s', '%s', '%s', '%s', '%s' )",
dbesc($x['url']),
dbesc($x['url']),
@@ -1025,6 +1064,7 @@ function import_author_unknown($x) {
$photos = import_profile_photo($x['photo']['src'],$x['url']);
if($photos) {
+ /** @bug $arr is undefined in this SQL query */
$r = q("update xchan set xchan_photo_date = '%s', xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' where xchan_url = '%s' and xchan_network = 'unknown'",
dbesc(datetime_convert('UTC','UTC',$arr['photo_updated'])),
dbesc($photos[0]),
@@ -1039,7 +1079,6 @@ function import_author_unknown($x) {
}
return false;
-
}
function encode_item($item,$mirror = false) {
@@ -1073,7 +1112,7 @@ function encode_item($item,$mirror = false) {
$item['body'] = crypto_unencapsulate(json_decode_plus($item['body']),$key);
}
- // If we're trying to backup an item so that it's recoverable or for export/imprt,
+ // If we're trying to backup an item so that it's recoverable or for export/imprt,
// add all the attributes we need to recover it
if($mirror) {
@@ -1146,11 +1185,16 @@ function encode_item($item,$mirror = false) {
logger('encode_item: ' . print_r($x,true), LOGGER_DATA);
return $x;
-
}
-
-function map_scope($scope,$strip = false) {
+/**
+ * @brief
+ *
+ * @param int $scope
+ * @param boolean $strip (optional) default false
+ * @return string
+ */
+function map_scope($scope, $strip = false) {
switch($scope) {
case 0:
return 'self';
@@ -1170,8 +1214,14 @@ function map_scope($scope,$strip = false) {
default:
return 'contacts';
}
-}
+}
+/**
+ * @brief Returns a descriptive text for a given $scope.
+ *
+ * @param string $scope
+ * @return string translated string describing the scope
+ */
function translate_scope($scope) {
if(! $scope || $scope === 'public')
return t('Visible to anybody on the internet.');
@@ -1191,9 +1241,15 @@ function translate_scope($scope) {
return t('Visible to specific connections.');
}
+/**
+ * @brief
+ *
+ * @param array $xchan
+ * @return array an associative array
+ */
function encode_item_xchan($xchan) {
-
$ret = array();
+
$ret['name'] = $xchan['xchan_name'];
$ret['address'] = $xchan['xchan_addr'];
$ret['url'] = (($xchan['hubloc_url']) ? $xchan['hubloc_url'] : $xchan['xchan_url']);
@@ -1201,11 +1257,12 @@ function encode_item_xchan($xchan) {
$ret['photo'] = array('mimetype' => $xchan['xchan_photo_mimetype'], 'src' => $xchan['xchan_photo_m']);
$ret['guid'] = $xchan['xchan_guid'];
$ret['guid_sig'] = $xchan['xchan_guid_sig'];
+
return $ret;
}
function encode_item_terms($terms) {
- $ret = array();
+ $ret = array();
$allowed_export_terms = array( TERM_UNKNOWN, TERM_HASHTAG, TERM_MENTION, TERM_CATEGORY, TERM_BOOKMARK );
@@ -1215,22 +1272,38 @@ function encode_item_terms($terms) {
$ret[] = array('tag' => $term['term'], 'url' => $term['url'], 'type' => termtype($term['type']));
}
}
+
return $ret;
}
+/**
+ * @brief
+ *
+ * @param int $t
+ * @return string
+ */
function termtype($t) {
$types = array('unknown','hashtag','mention','category','private_category','file','search','thing','bookmark');
+
return(($types[$t]) ? $types[$t] : 'unknown');
}
+/**
+ * @brief
+ *
+ * @param array $t
+ * @return array|string empty string or array containing associative arrays with
+ * * \e string \b term
+ * * \e string \b url
+ * * \e int \b type
+ */
function decode_tags($t) {
-
if($t) {
$ret = array();
foreach($t as $x) {
$tag = array();
- $tag['term'] = htmlspecialchars($x['tag'], ENT_COMPAT,'UTF-8',false);
- $tag['url'] = htmlspecialchars($x['url'], ENT_COMPAT,'UTF-8',false);
+ $tag['term'] = htmlspecialchars($x['tag'], ENT_COMPAT, 'UTF-8', false);
+ $tag['url'] = htmlspecialchars($x['url'], ENT_COMPAT, 'UTF-8', false);
switch($x['type']) {
case 'hashtag':
$tag['type'] = TERM_HASHTAG;
@@ -1263,14 +1336,19 @@ function decode_tags($t) {
}
$ret[] = $tag;
}
+
return $ret;
}
- return '';
+ return '';
}
-// santise a potentially complex array
-
+/**
+ * @brief Santise a potentially complex array.
+ *
+ * @param array $arr
+ * @return array|string
+ */
function activity_sanitise($arr) {
if($arr) {
if(is_array($arr)) {
@@ -1279,19 +1357,24 @@ function activity_sanitise($arr) {
if(is_array($x))
$ret[$k] = activity_sanitise($x);
else
- $ret[$k] = htmlspecialchars($x, ENT_COMPAT,'UTF-8',false);
+ $ret[$k] = htmlspecialchars($x, ENT_COMPAT, 'UTF-8', false);
}
return $ret;
}
else {
- return htmlspecialchars($arr, ENT_COMPAT,'UTF-8', false);
+ return htmlspecialchars($arr, ENT_COMPAT, 'UTF-8', false);
}
}
+
return '';
}
-// sanitise a simple linear array
-
+/**
+ * @brief Sanitise a simple linear array.
+ *
+ * @param array $arr
+ * @return array|string
+ */
function array_sanitise($arr) {
if($arr) {
$ret = array();
@@ -1300,6 +1383,7 @@ function array_sanitise($arr) {
}
return $ret;
}
+
return '';
}
@@ -1322,7 +1406,7 @@ function encode_item_flags($item) {
$ret[] = 'consensus';
if($item['item_private'])
$ret[] = 'private';
-
+
return $ret;
}
@@ -1415,7 +1499,6 @@ function get_mail_elements($x) {
return array();
return $arr;
-
}
@@ -1441,23 +1524,25 @@ function get_profile_elements($x) {
$arr['postcode'] = (($x['postcode']) ? htmlspecialchars($x['postcode'], ENT_COMPAT,'UTF-8',false) : '');
$arr['country'] = (($x['country']) ? htmlspecialchars($x['country'], ENT_COMPAT,'UTF-8',false) : '');
- $arr['keywords'] = (($x['keywords'] && is_array($x['keywords'])) ? array_sanitise($x['keywords']) : array());
+ $arr['keywords'] = (($x['keywords'] && is_array($x['keywords'])) ? array_sanitise($x['keywords']) : array());
return $arr;
-
}
+/**
+ * @param object $feed
+ * @param array $item
+ * @param[out] array $author
+ * @return multitype:multitype: string NULL number Ambigous <NULL, string, number> Ambigous <mixed, string> Ambigous <multitype:multitype:string Ambigous <NULL, string> , multitype:multitype:string unknown > multitype:NULL unknown
+ */
+function get_atom_elements($feed, $item, &$author) {
-
-function get_atom_elements($feed,$item,&$author) {
-
-
- $best_photo = array();
+ //$best_photo = array();
$res = array();
$found_author = $item->get_author();
- if($found_author) {
+ if($found_author) {
$author['author_name'] = unxmlify($found_author->get_name());
$author['author_link'] = unxmlify($found_author->get_link());
$author['author_is_feed'] = false;
@@ -1527,7 +1612,7 @@ function get_atom_elements($feed,$item,&$author) {
if($rawmedia && $rawmedia[0]['attribs']['']['url']) {
$author['author_photo'] = strip_tags(unxmlify($rawmedia[0]['attribs']['']['url']));
}
- }
+ }
// No photo/profile-link on the item - look at the feed level
@@ -1569,9 +1654,9 @@ function get_atom_elements($feed,$item,&$author) {
$apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
if($apps && $apps[0]['attribs']['']['source']) {
$res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
- }
+ }
- /**
+ /*
* If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
*/
@@ -1585,24 +1670,22 @@ function get_atom_elements($feed,$item,&$author) {
// make sure nobody is trying to sneak some html tags by us
$res['body'] = notags(base64url_decode($res['body']));
- // We could probably turn these old Friendica bbcode bookmarks into bookmark tags but we'd have to
+ // We could probably turn these old Friendica bbcode bookmarks into bookmark tags but we'd have to
// create a term table item for them. For now just make sure they stay as links.
$res['body'] = preg_replace('/\[bookmark(.*?)\](.*?)\[\/bookmark\]/','[url$1]$2[/url]',$res['body']);
-
}
-
$res['body'] = limit_body_size($res['body']);
- // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
- // the content type. Our own network only emits text normally, though it might have been converted to
+ // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
+ // the content type. Our own network only emits text normally, though it might have been converted to
// html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
// have to assume it is all html and needs to be purified.
- // It doesn't matter all that much security wise - because before this content is used anywhere, we are
- // going to escape any tags we find regardless, but this lets us import a limited subset of html from
- // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
+ // It doesn't matter all that much security wise - because before this content is used anywhere, we are
+ // going to escape any tags we find regardless, but this lets us import a limited subset of html from
+ // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
// html.
if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {
@@ -1616,8 +1699,6 @@ function get_atom_elements($feed,$item,&$author) {
$res['body'] = purify_html($res['body']);
$res['body'] = @html2bbcode($res['body']);
-
-
}
elseif(! $have_real_body) {
@@ -1648,7 +1729,6 @@ function get_atom_elements($feed,$item,&$author) {
);
}
-
$private = $item->get_item_tags(NAMESPACE_DFRN,'private');
if($private && intval($private[0]['data']) > 0)
$res['item_private'] = ((intval($private[0]['data'])) ? 1 : 0);
@@ -1659,18 +1739,16 @@ function get_atom_elements($feed,$item,&$author) {
if($rawlocation)
$res['location'] = unxmlify($rawlocation[0]['data']);
-
$rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
if($rawcreated)
$res['created'] = unxmlify($rawcreated[0]['data']);
-
$rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
if($rawedited)
$res['edited'] = unxmlify($rawedited[0]['data']);
if((x($res,'edited')) && (! (x($res,'created'))))
- $res['created'] = $res['edited'];
+ $res['created'] = $res['edited'];
if(! $res['created'])
$res['created'] = $item->get_date('c');
@@ -1731,7 +1809,7 @@ function get_atom_elements($feed,$item,&$author) {
}
// translate OStatus unfollow to activity streams if it happened to get selected
-
+
if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
$res['verb'] = ACTIVITY_UNFOLLOW;
@@ -1761,7 +1839,7 @@ function get_atom_elements($feed,$item,&$author) {
'url' => $termurl,
'term' => $termterm,
);
- }
+ }
}
}
@@ -1771,7 +1849,6 @@ function get_atom_elements($feed,$item,&$author) {
$attach = $item->get_enclosures();
if($attach) {
$res['attach'] = array();
- $att_arr = array();
foreach($attach as $att) {
$len = intval($att->get_length());
$link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
@@ -1786,6 +1863,7 @@ function get_atom_elements($feed,$item,&$author) {
$title = ' ';
if(! $type)
$type = 'application/octet-stream';
+
$res['attach'][] = array('href' => $link, 'length' => $len, 'type' => $type, 'title' => $title );
}
}
@@ -1799,7 +1877,7 @@ function get_atom_elements($feed,$item,&$author) {
if($child[NAMESPACE_ACTIVITY]['obj_type'][0]['data']) {
$res['obj_type'] = $child[NAMESPACE_ACTIVITY]['obj_type'][0]['data'];
$obj['type'] = $child[NAMESPACE_ACTIVITY]['obj_type'][0]['data'];
- }
+ }
if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
$obj['id'] = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'];
if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
@@ -1813,10 +1891,8 @@ function get_atom_elements($feed,$item,&$author) {
// preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
$obj['orig'] = xmlify($body);
if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
-
$body = purify_html($body);
$body = html2bbcode($body);
-
}
$obj['content'] = $body;
@@ -1834,7 +1910,7 @@ function get_atom_elements($feed,$item,&$author) {
if($child[NAMESPACE_ACTIVITY]['obj_type'][0]['data']) {
$res['tgt_type'] = $child[NAMESPACE_ACTIVITY]['obj_type'][0]['data'];
$obj['type'] = $child[NAMESPACE_ACTIVITY]['obj_type'][0]['data'];
- }
+ }
if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
$obj['id'] = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'];
if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
@@ -1845,13 +1921,12 @@ function get_atom_elements($feed,$item,&$author) {
$body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
if(! $body)
$body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
+
// preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
$obj['orig'] = xmlify($body);
if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
-
$body = purify_html($body);
$body = html2bbcode($body);
-
}
$obj['content'] = $body;
@@ -1892,17 +1967,26 @@ function encode_rel_links($links) {
$o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
$o .= ' />' . "\n" ;
}
+
return xmlify($o);
}
-function item_store($arr,$allow_exec = false) {
+/**
+ * @brief
+ *
+ * @param array $arr
+ * @param boolean $allow_exec (optional) default false
+ * @return array
+ * * \e boolean \b success
+ * * \e int \b item_id
+ */
+function item_store($arr, $allow_exec = false) {
$d = array('item' => $arr, 'allow_exec' => $allow_exec);
call_hooks('item_store', $d );
$arr = $d['item'];
$allow_exec = $d['allow_exec'];
-
$ret = array('success' => false, 'item_id' => 0);
if(! $arr['uid']) {
@@ -1911,9 +1995,9 @@ function item_store($arr,$allow_exec = false) {
return $ret;
}
- $uplinked_comment = false;
+ //$uplinked_comment = false;
- // If a page layout is provided, ensure it exists and belongs to us.
+ // If a page layout is provided, ensure it exists and belongs to us.
if(array_key_exists('layout_mid',$arr) && $arr['layout_mid']) {
$l = q("select item_type from item where mid = '%s' and uid = %d limit 1",
@@ -1951,8 +2035,6 @@ function item_store($arr,$allow_exec = false) {
$arr['item_private'] = ((x($arr,'item_private')) ? intval($arr['item_private']) : 0 );
$arr['item_flags'] = ((x($arr,'item_flags')) ? intval($arr['item_flags']) : 0 );
-
-
// only detect language if we have text content, and if the post is private but not yet
// obscured, make it so.
@@ -1962,7 +2044,6 @@ function item_store($arr,$allow_exec = false) {
// apply the input filter here - if it is obscured it has been filtered already
$arr['body'] = z_input_filter($arr['uid'],$arr['body'],$arr['mimetype']);
-
if(local_channel() && (! $arr['sig'])) {
$channel = get_app()->get_channel();
if($channel['channel_hash'] === $arr['author_xchan']) {
@@ -1972,7 +2053,7 @@ function item_store($arr,$allow_exec = false) {
}
$allowed_languages = get_pconfig($arr['uid'],'system','allowed_languages');
-
+
if((is_array($allowed_languages)) && ($arr['lang']) && (! array_key_exists($arr['lang'],$allowed_languages))) {
$translate = array('item' => $arr, 'from' => $arr['lang'], 'to' => $allowed_languages, 'translated' => false);
call_hooks('item_translate', $translate);
@@ -1991,7 +2072,6 @@ function item_store($arr,$allow_exec = false) {
if($arr['body'])
$arr['body'] = json_encode(crypto_encapsulate($arr['body'],$key));
}
-
}
if((x($arr,'object')) && is_array($arr['object'])) {
@@ -2058,8 +2138,6 @@ function item_store($arr,$allow_exec = false) {
if(! $arr['plink'])
$arr['plink'] = $arr['llink'];
-
-
if($arr['parent_mid'] === $arr['mid']) {
$parent_id = 0;
$parent_deleted = 0;
@@ -2071,7 +2149,7 @@ function item_store($arr,$allow_exec = false) {
$comments_closed = $arr['comments_closed'];
$arr['item_thread_top'] = 1;
}
- else {
+ else {
// find the parent and snarf the item id and ACL's
// and anything else we need to inherit
@@ -2083,6 +2161,16 @@ function item_store($arr,$allow_exec = false) {
if($r) {
+ // in case item_store was killed before the parent's parent attribute got set,
+ // set it now. This happens with some regularity on Dreamhost. This will keep
+ // us from getting notifications for threads that exist but which we can't see.
+
+ if(($r[0]['mid'] === $r[0]['parent_mid']) && (! intval($r[0]['parent']))) {
+ q("update item set parent = id where id = %d",
+ intval($r[0]['id'])
+ );
+ }
+
if(comments_are_now_closed($r[0])) {
logger('item_store: comments closed');
$ret['message'] = 'Comments closed.';
@@ -2098,7 +2186,7 @@ function item_store($arr,$allow_exec = false) {
if($r[0]['mid'] != $r[0]['parent_mid']) {
$arr['parent_mid'] = $r[0]['parent_mid'];
- $z = q("SELECT * FROM `item` WHERE `mid` = '%s' AND `parent_mid` = '%s' AND `uid` = %d
+ $z = q("SELECT * FROM `item` WHERE `mid` = '%s' AND `parent_mid` = '%s' AND `uid` = %d
ORDER BY `id` ASC LIMIT 1",
dbesc($r[0]['parent_mid']),
dbesc($r[0]['parent_mid']),
@@ -2126,7 +2214,7 @@ function item_store($arr,$allow_exec = false) {
if($r[0]['owner_xchan'] !== $arr['owner_xchan']) {
$arr['owner_xchan'] = $r[0]['owner_xchan'];
- $uplinked_comment = true;
+// $uplinked_comment = true;
}
// if the parent is private, force privacy for the entire conversation
@@ -2136,7 +2224,7 @@ function item_store($arr,$allow_exec = false) {
// Edge case. We host a public forum that was originally posted to privately.
// The original author commented, but as this is a comment, the permissions
- // weren't fixed up so it will still show the comment as private unless we fix it here.
+ // weren't fixed up so it will still show the comment as private unless we fix it here.
if(intval($r[0]['item_uplink']) && (! $r[0]['item_private']))
$arr['item_private'] = 0;
@@ -2150,8 +2238,7 @@ function item_store($arr,$allow_exec = false) {
if($parent_deleted)
$arr['item_deleted'] = 1;
-
-
+
$r = q("SELECT `id` FROM `item` WHERE `mid` = '%s' AND `uid` = %d LIMIT 1",
dbesc($arr['mid']),
intval($arr['uid'])
@@ -2184,7 +2271,7 @@ function item_store($arr,$allow_exec = false) {
if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid) || strlen($public_policy))
$private = 1;
else
- $private = $arr['item_private'];
+ $private = $arr['item_private'];
$arr['parent'] = $parent_id;
$arr['allow_cid'] = $allow_cid;
@@ -2199,10 +2286,10 @@ function item_store($arr,$allow_exec = false) {
dbesc_array($arr);
- $r = dbq("INSERT INTO `item` (`"
- . implode("`, `", array_keys($arr))
- . "`) VALUES ('"
- . implode("', '", array_values($arr))
+ $r = dbq("INSERT INTO `item` (`"
+ . implode("`, `", array_keys($arr))
+ . "`) VALUES ('"
+ . implode("', '", array_values($arr))
. "')" );
// find the item we just created
@@ -2256,7 +2343,7 @@ function item_store($arr,$allow_exec = false) {
}
$arr['term'] = $terms;
- }
+ }
call_hooks('post_remote_end',$arr);
@@ -2275,9 +2362,16 @@ function item_store($arr,$allow_exec = false) {
);
- send_status_notifications($current_post,$arr);
+ // If _creating_ a deleted item, don't propagate it further or send out notifications.
+ // We need to store the item details just in case the delete came in before the original post,
+ // so that we have an item in the DB that's marked deleted and won't store a fresh post
+ // that isn't aware that we were already told to delete it.
+
+ if(! ($arr['item_restrict'] & ITEM_DELETED)) {
+ send_status_notifications($current_post,$arr);
+ tag_deliver($arr['uid'],$current_post);
+ }
- tag_deliver($arr['uid'],$current_post);
$ret['success'] = true;
$ret['item_id'] = $current_post;
@@ -2316,7 +2410,7 @@ function item_store_update($arr,$allow_exec = false) {
logger('item_store_update: original post not found: ' . $orig_post_id);
$ret['message'] = 'no original';
return $ret;
- }
+ }
// override the unseen flag with the original
@@ -2325,9 +2419,9 @@ function item_store_update($arr,$allow_exec = false) {
$arr['item_flags'] = intval($arr['item_flags']) | $orig[0]['item_flags'];
$arr['item_restrict'] = intval($arr['item_restrict']) | $orig[0]['item_restrict'];
-
if(array_key_exists('edit',$arr))
- unset($arr['edit']);
+ unset($arr['edit']);
+
$arr['mimetype'] = ((x($arr,'mimetype')) ? notags(trim($arr['mimetype'])) : 'text/bbcode');
if(($arr['mimetype'] == 'application/x-php') && (! $allow_exec)) {
@@ -2351,7 +2445,7 @@ function item_store_update($arr,$allow_exec = false) {
}
$allowed_languages = get_pconfig($arr['uid'],'system','allowed_languages');
-
+
if((is_array($allowed_languages)) && ($arr['lang']) && (! array_key_exists($arr['lang'],$allowed_languages))) {
$translate = array('item' => $arr, 'from' => $arr['lang'], 'to' => $allowed_languages, 'translated' => false);
call_hooks('item_translate', $translate);
@@ -2370,10 +2464,8 @@ function item_store_update($arr,$allow_exec = false) {
if($arr['body'])
$arr['body'] = json_encode(crypto_encapsulate($arr['body'],$key));
}
-
}
-
if((x($arr,'object')) && is_array($arr['object'])) {
activity_sanitise($arr['object']);
$arr['object'] = json_encode($arr['object']);
@@ -2389,7 +2481,6 @@ function item_store_update($arr,$allow_exec = false) {
$arr['attach'] = json_encode($arr['attach']);
}
-
unset($arr['id']);
unset($arr['uid']);
unset($arr['aid']);
@@ -2436,15 +2527,13 @@ function item_store_update($arr,$allow_exec = false) {
$arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : $orig[0]['app']);
// $arr['item_restrict'] = ((x($arr,'item_restrict')) ? intval($arr['item_restrict']) : $orig[0]['item_restrict'] );
// $arr['item_flags'] = ((x($arr,'item_flags')) ? intval($arr['item_flags']) : $orig[0]['item_flags'] );
-
+
$arr['sig'] = ((x($arr,'sig')) ? $arr['sig'] : '');
$arr['layout_mid'] = ((array_key_exists('layout_mid',$arr)) ? dbesc($arr['layout_mid']) : $orig[0]['layout_mid'] );
$arr['public_policy'] = ((x($arr,'public_policy')) ? notags(trim($arr['public_policy'])) : $orig[0]['public_policy'] );
$arr['comment_policy'] = ((x($arr,'comment_policy')) ? notags(trim($arr['comment_policy'])) : $orig[0]['comment_policy'] );
-
-
call_hooks('post_remote_update',$arr);
if(x($arr,'cancel')) {
@@ -2466,11 +2555,11 @@ function item_store_update($arr,$allow_exec = false) {
logger('item_store_update: ' . print_r($arr,true), LOGGER_DATA);
$str = '';
- foreach($arr as $k => $v) {
- if($str)
- $str .= ",";
- $str .= " `" . $k . "` = '" . $v . "' ";
- }
+ foreach($arr as $k => $v) {
+ if($str)
+ $str .= ",";
+ $str .= " `" . $k . "` = '" . $v . "' ";
+ }
$r = dbq("update `item` set " . $str . " where id = " . $orig_post_id );
@@ -2501,7 +2590,7 @@ function item_store_update($arr,$allow_exec = false) {
}
$arr['term'] = $terms;
- }
+ }
call_hooks('post_remote_update_end',$arr);
@@ -2516,7 +2605,7 @@ function item_store_update($arr,$allow_exec = false) {
function store_diaspora_comment_sig($datarray, $channel, $parent_item, $post_id, $walltowall = false) {
- // We won't be able to sign Diaspora comments for authenticated visitors
+ // We won't be able to sign Diaspora comments for authenticated visitors
// - we don't have their private key
// since Diaspora doesn't handle edits we can only do this for the original text and not update it.
@@ -2527,9 +2616,9 @@ function store_diaspora_comment_sig($datarray, $channel, $parent_item, $post_id,
if($walltowall) {
logger('wall to wall comment',LOGGER_DEBUG);
// post will come across with the owner's identity. Throw a preamble onto the post to indicate the true author.
- $signed_body = "\n\n"
+ $signed_body = "\n\n"
. '![' . $datarray['author']['xchan_name'] . '](' . $datarray['author']['xchan_photo_m'] . ')'
- . '[' . $datarray['author']['xchan_name'] . '](' . $datarray['author']['xchan_url'] . ')' . "\n\n"
+ . '[' . $datarray['author']['xchan_name'] . '](' . $datarray['author']['xchan_url'] . ')' . "\n\n"
. $signed_body;
}
@@ -2539,8 +2628,9 @@ function store_diaspora_comment_sig($datarray, $channel, $parent_item, $post_id,
$signed_text = $datarray['mid'] . ';' . $parent_item['mid'] . ';' . $signed_body . ';' . $diaspora_handle;
+ /** @FIXME $uprvkey is undefined, do we still need this if-statement? */
if( $uprvkey !== false )
- $authorsig = base64_encode(rsa_sign($signed_text,$channel['channel_prvkey'],'sha256'));
+ $authorsig = base64_encode(rsa_sign($signed_text, $channel['channel_prvkey'], 'sha256'));
else
$authorsig = '';
@@ -2551,7 +2641,7 @@ function store_diaspora_comment_sig($datarray, $channel, $parent_item, $post_id,
$r = q("update item set diaspora_meta = '%s' where id = %d",
dbesc(json_encode($y)),
- intval($post_id)
+ intval($post_id)
);
if(! $r)
@@ -2601,7 +2691,6 @@ function send_status_notifications($post_id,$item) {
$link = get_app()->get_baseurl() . '/display/' . $item['mid'];
-
$y = q("select id from notify where link = '%s' and uid = %d limit 1",
dbesc($link),
intval($item['uid'])
@@ -2612,50 +2701,50 @@ function send_status_notifications($post_id,$item) {
if(! $notify)
return;
+
require_once('include/enotify.php');
notification(array(
'type' => NOTIFY_COMMENT,
'from_xchan' => $item['author_xchan'],
'to_xchan' => $r[0]['channel_hash'],
'item' => $item,
- 'link' => $link,
+ 'link' => $link,
'verb' => ACTIVITY_POST,
'otype' => 'item',
'parent' => $parent,
'parent_mid' => $item['parent_mid']
));
- return;
}
-
-
-
-
function get_item_contact($item,$contacts) {
if(! count($contacts) || (! is_array($item)))
return false;
+
foreach($contacts as $contact) {
if($contact['id'] == $item['contact-id']) {
return $contact;
break; // NOTREACHED
}
}
+
return false;
}
-
-function tag_deliver($uid,$item_id) {
-
- // Called when we deliver things that might be tagged in ways that require delivery processing.
- // Handles community tagging of posts and also look for mention tags
- // and sets up a second delivery chain if appropriate
-
- $a = get_app();
+/**
+ * @brief Called when we deliver things that might be tagged in ways that require delivery processing.
+ *
+ * Handles community tagging of posts and also look for mention tags and sets up
+ * a second delivery chain if appropriate.
+ *
+ * @param int $uid
+ * @param int $item_id
+ */
+function tag_deliver($uid, $item_id) {
$mention = false;
- /**
+ /*
* Fetch stuff we need - a channel and an item
*/
@@ -2664,7 +2753,7 @@ function tag_deliver($uid,$item_id) {
);
if(! $u)
return;
-
+
$i = q("select * from item where id = %d and uid = %d limit 1",
intval($item_id),
intval($uid)
@@ -2684,22 +2773,23 @@ function tag_deliver($uid,$item_id) {
return;
}
-
- /**
+ /*
* Seems like a good place to plug in a poke notification.
*/
if (stristr($item['verb'],ACTIVITY_POKE)) {
$poke_notify = true;
- if(($item['obj_type'] == "") || ($item['obj_type'] !== ACTIVITY_OBJ_PERSON) || (! $item['object']))
- $poke_notify = false;
+ if(($item['obj_type'] == "") || ($item['obj_type'] !== ACTIVITY_OBJ_PERSON) || (! $item['object']))
+ $poke_notify = false;
$obj = json_decode_plus($item['object']);
if($obj) {
if($obj['id'] !== $u[0]['channel_hash'])
$poke_notify = false;
}
+ if($item['item_restrict'] & ITEM_DELETED)
+ $poke_notify = false;
$verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
if($poke_notify) {
@@ -2717,7 +2807,7 @@ function tag_deliver($uid,$item_id) {
}
}
- /**
+ /*
* Do community tagging
*/
@@ -2726,7 +2816,7 @@ function tag_deliver($uid,$item_id) {
// We received a community tag activity for a post.
// See if we are the owner of the parent item and have given permission to tag our posts.
// If so tag the parent post.
-
+
logger('tag_deliver: community tag activity received');
if(($item['owner_xchan'] === $u[0]['channel_hash']) && (! get_pconfig($u[0]['channel_id'],'system','blocktags'))) {
@@ -2751,7 +2841,7 @@ function tag_deliver($uid,$item_id) {
dbesc(datetime_convert()),
dbesc($j_tgt['id']),
intval($u[0]['channel_id'])
- );
+ );
proc_run('php','include/notifier.php','edit_post',$p[0]['id']);
}
}
@@ -2761,7 +2851,7 @@ function tag_deliver($uid,$item_id) {
logger('tag_deliver: tag permission denied for ' . $u[0]['channel_address']);
}
- /**
+ /*
* A "union" is a message which our channel has sourced from another channel.
* This sets up a second delivery chain just like forum tags do.
* Find out if this is a source-able post.
@@ -2787,11 +2877,10 @@ function tag_deliver($uid,$item_id) {
}
- /**
+ /*
* Now we've got those out of the way. Let's see if this is a post that's tagged for re-delivery
*/
-
$terms = get_terms_oftype($item['term'],TERM_MENTION);
if($terms)
@@ -2801,23 +2890,23 @@ function tag_deliver($uid,$item_id) {
if($terms) {
foreach($terms as $term) {
- if(link_compare($term['url'],$link)) {
+ if(link_compare($term['url'],$link)) {
$mention = true;
break;
}
}
- }
+ }
if($mention) {
logger('tag_deliver: mention found for ' . $u[0]['channel_name']);
$r = q("update item set item_mentionsme = 1 where id = %d",
intval($item_id)
- );
+ );
// At this point we've determined that the person receiving this post was mentioned in it or it is a union.
// Now let's check if this mention was inside a reshare so we don't spam a forum
- // If it's private we may have to unobscure it momentarily so that we can parse it.
+ // If it's private we may have to unobscure it momentarily so that we can parse it.
$body = '';
@@ -2827,18 +2916,19 @@ function tag_deliver($uid,$item_id) {
$body = crypto_unencapsulate(json_decode_plus($item['body']),$key);
}
else
- $body = $item['body'];
+ $body = $item['body'];
$body = preg_replace('/\[share(.*?)\[\/share\]/','',$body);
$tagged = false;
$plustagged = false;
+ $matches = array();
$pattern = '/@\!?\[zrl\=' . preg_quote($term['url'],'/') . '\]' . preg_quote($term['term'],'/') . '\[\/zrl\]/';
- if(preg_match($pattern,$body,$matches))
+ if(preg_match($pattern,$body,$matches))
$tagged = true;
- $pattern = '/@\!?\[zrl\=(.*?)\](.*?)\+\[\/zrl\]/';
+ $pattern = '/@\!?\[zrl\=([^\]]*?)\]((?:.(?!\[zrl\=))*?)\+\[\/zrl\]/';
if(preg_match_all($pattern,$body,$matches,PREG_SET_ORDER)) {
$max_forums = get_config('system','max_tagged_forums');
@@ -2865,7 +2955,7 @@ function tag_deliver($uid,$item_id) {
$arr = array('channel_id' => $uid, 'item' => $item, 'body' => $body);
call_hooks('tagged',$arr);
- /**
+ /*
* Kill two birds with one stone. As long as we're here, send a mention notification.
*/
@@ -2893,7 +2983,6 @@ function tag_deliver($uid,$item_id) {
logger('tag_delivery denied for uid ' . $uid . ' and xchan ' . $item['author_xchan']);
return;
}
-
}
if((! $mention) && (! $union)) {
@@ -2912,25 +3001,18 @@ function tag_deliver($uid,$item_id) {
logger('tag_deliver: creating second delivery chain.');
start_delivery_chain($u[0],$item,$item_id,null);
-
}
/**
- * @function tgroup_check($uid,$item)
+ * @brief This function is called pre-deliver to see if a post matches the criteria to be tag delivered.
*
- * This function is called pre-deliver to see if a post matches the criteria to be tag delivered.
* We don't actually do anything except check that it matches the criteria.
* This is so that the channel with tag_delivery enabled can receive the post even if they turn off
* permissions for the sender to send their stream. tag_deliver() can't be called until the post is actually stored.
- * By then it would be too late to reject it.
+ * By then it would be too late to reject it.
*/
-
-
-
function tgroup_check($uid,$item) {
- $a = get_app();
-
$mention = false;
// check that the message originated elsewhere and is a top-level post
@@ -2943,6 +3025,7 @@ function tgroup_check($uid,$item) {
);
if($r)
return true;
+
return false;
}
if(! perm_is_allowed($uid,$item['author_xchan'],'tag_deliver'))
@@ -2964,13 +3047,12 @@ function tgroup_check($uid,$item) {
if($terms) {
foreach($terms as $term) {
- if(link_compare($term['url'],$link)) {
+ if(link_compare($term['url'],$link)) {
$mention = true;
break;
}
}
- }
-
+ }
if($mention) {
logger('tgroup_check: mention found for ' . $u[0]['channel_name']);
@@ -2992,12 +3074,12 @@ function tgroup_check($uid,$item) {
$body = preg_replace('/\[share(.*?)\[\/share\]/','',$body);
-
// $pattern = '/@\!?\[zrl\=' . preg_quote($term['url'],'/') . '\]' . preg_quote($term['term'] . '+','/') . '\[\/zrl\]/';
- $pattern = '/@\!?\[zrl\=(.*?)\](.*?)\+\[\/zrl\]/';
+ $pattern = '/@\!?\[zrl\=([^\]]*?)\]((?:.(?!\[zrl\=))*?)\+\[\/zrl\]/';
$found = false;
+ $matches = array();
if(preg_match_all($pattern,$body,$matches,PREG_SET_ORDER)) {
$max_forums = get_config('system','max_tagged_forums');
@@ -3022,23 +3104,25 @@ function tgroup_check($uid,$item) {
}
return true;
-
}
/**
* Sourced and tag-delivered posts are re-targetted for delivery to the connections of the channel
- * receiving the post. This starts the second delivery chain, by resetting permissions and ensuring
- * that ITEM_UPLINK is set on the parent post, and storing the current owner_xchan as the source_xchan.
+ * receiving the post. This starts the second delivery chain, by resetting permissions and ensuring
+ * that ITEM_UPLINK is set on the parent post, and storing the current owner_xchan as the source_xchan.
* We'll become the new owner. If called without $parent, this *is* the parent post.
+ *
+ * @param array $channel
+ * @param array $item
+ * @param int $item_id
+ * @param boolean $parent
*/
-
-function start_delivery_chain($channel,$item,$item_id,$parent) {
-
+function start_delivery_chain($channel, $item, $item_id, $parent) {
// Change this copy of the post to a forum head message and deliver to all the tgroup members
// also reset all the privacy bits to the forum default permissions
- $private = (($channel['channel_allow_cid'] || $channel['channel_allow_gid']
+ $private = (($channel['channel_allow_cid'] || $channel['channel_allow_gid']
|| $channel['channel_deny_cid'] || $channel['channel_deny_gid']) ? 1 : 0);
$new_public_policy = map_scope($channel['channel_r_stream'],true);
@@ -3046,6 +3130,7 @@ function start_delivery_chain($channel,$item,$item_id,$parent) {
if((! $private) && $new_public_policy)
$private = 1;
+
$item_wall = 1;
$item_origin = 1;
$item_uplink = 0;
@@ -3068,7 +3153,7 @@ function start_delivery_chain($channel,$item,$item_id,$parent) {
$r = q("update item set source_xchan = owner_xchan where id = %d",
intval($item_id)
);
- }
+ }
$title = $item['title'];
$body = $item['body'];
@@ -3118,34 +3203,25 @@ function start_delivery_chain($channel,$item,$item_id,$parent) {
if($r)
proc_run('php','include/notifier.php','tgroup',$item_id);
else
- logger('start_delivery_chain: failed to update item');
-
- return;
+ logger('start_delivery_chain: failed to update item');
}
-
-
/**
- * @function check_item_source($uid,$item)
- * @param $uid
- * @param $item
+ * @brief
*
- * @description
- * Checks to see if this item owner is referenced as a source for this channel and if the post
+ * Checks to see if this item owner is referenced as a source for this channel and if the post
* matches the rules for inclusion in this channel. Returns true if we should create a second delivery
* chain and false if none of the rules apply, or if the item is private.
+ *
+ * @param int $uid
+ * @param array $item
*/
-
-
-function check_item_source($uid,$item) {
-
-
+function check_item_source($uid, $item) {
$r = q("select * from source where src_channel_id = %d and ( src_xchan = '%s' or src_xchan = '*' ) limit 1",
intval($uid),
dbesc(($item['source_xchan']) ? $item['source_xchan'] : $item['owner_xchan'])
);
-
if(! $r)
return false;
@@ -3154,18 +3230,15 @@ function check_item_source($uid,$item) {
dbesc($item['owner_xchan'])
);
-
if(! $x)
return false;
-
if(! ($x[0]['abook_their_perms'] & PERMS_A_REPUBLISH))
return false;
if($item['item_private'] && (! ($x[0]['abook_flags'] & ABOOK_FLAG_FEED)))
return false;
-
if($r[0]['src_channel_xchan'] === $item['owner_xchan'])
return false;
@@ -3176,6 +3249,7 @@ function check_item_source($uid,$item) {
$text = prepare_text($item['body'],$item['mimetype']);
$text = html2plain($text);
+ /** @BUG $items is undefined, should this be $item? */
$tags = ((count($items['term'])) ? $items['term'] : false);
$words = explode("\n",$r[0]['src_patt']);
@@ -3190,12 +3264,11 @@ function check_item_source($uid,$item) {
return true;
}
}
+
return false;
}
-
-
function mail_store($arr) {
if(! $arr['channel_id']) {
@@ -3203,7 +3276,7 @@ function mail_store($arr) {
return 0;
}
- if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
+ if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
$arr['body'] = escape_tags($arr['body']);
if(array_key_exists('attach',$arr) && is_array($arr['attach']))
@@ -3220,7 +3293,6 @@ function mail_store($arr) {
$arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
$arr['mail_flags'] = ((x($arr,'mail_flags')) ? intval($arr['mail_flags']) : 0 );
-
if(! $arr['parent_mid']) {
logger('mail_store: missing parent');
@@ -3247,10 +3319,10 @@ function mail_store($arr) {
logger('mail_store: ' . print_r($arr,true), LOGGER_DATA);
- $r = dbq("INSERT INTO mail (`"
- . implode("`, `", array_keys($arr))
- . "`) VALUES ('"
- . implode("', '", array_values($arr))
+ $r = dbq("INSERT INTO mail (`"
+ . implode("`, `", array_keys($arr))
+ . "`) VALUES ('"
+ . implode("', '", array_values($arr))
. "')" );
// find the item we just created
@@ -3286,9 +3358,9 @@ function mail_store($arr) {
'type' => NOTIFY_MAIL,
'item' => $arr,
'verb' => ACTIVITY_POST,
- 'otype' => 'mail'
+ 'otype' => 'mail'
);
-
+
notification($notif_params);
}
@@ -3296,35 +3368,35 @@ function mail_store($arr) {
return $current_post;
}
-
/**
+ * @brief Process atom feed and update anything/everything we might need to update.
*
- * consume_feed - process atom feed and update anything/everything we might need to update
- *
- * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
- *
- * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
- * It is this person's stuff that is going to be updated.
- * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
- * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
- * have a contact record.
- * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
+ * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
* might not) try and subscribe to it.
* $datedir sorts in reverse order
- * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
- * imported prior to its children being seen in the stream unless we are certain
- * of how the feed is arranged/ordered.
- * With $pass = 1, we only pull parent items out of the stream.
- * With $pass = 2, we only pull children (comments/likes).
+ *
+ * @param array $xml
+ * The (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
+ * @param $importer
+ * The contact_record (joined to user_record) of the local user who owns this
+ * relationship. It is this person's stuff that is going to be updated.
+ * @param $contact
+ * The person who is sending us stuff. If not set, we MAY be processing a "follow" activity
+ * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
+ * have a contact record.
+ * @param int $pass by default ($pass = 0) we cannot guarantee that a parent item has been
+ * imported prior to its children being seen in the stream unless we are certain
+ * of how the feed is arranged/ordered.
+ * * With $pass = 1, we only pull parent items out of the stream.
+ * * With $pass = 2, we only pull children (comments/likes).
*
* So running this twice, first with pass 1 and then with pass 2 will do the right
* thing regardless of feed ordering. This won't be adequate in a fully-threaded
* model where comments can have sub-threads. That would require some massive sorting
* to get all the feed items into a mostly linear ordering, and might still require
- * recursion.
+ * recursion.
*/
-
-function consume_feed($xml,$importer,&$contact,$pass = 0) {
+function consume_feed($xml, $importer, &$contact, $pass = 0) {
require_once('library/simplepie/simplepie.inc');
@@ -3361,7 +3433,6 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) {
$when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
}
-
if($deleted && is_array($contact)) {
$r = q("SELECT * from item where mid = '%s' and author_xchan = '%s' and uid = %d limit 1",
dbesc(base64url_encode($mid)),
@@ -3376,7 +3447,7 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) {
logger('consume_feed: deleting item ' . $item['id'] . ' mid=' . base64url_decode($item['mid']), LOGGER_DEBUG);
drop_item($item['id'],false);
}
- }
+ }
}
}
}
@@ -3407,7 +3478,6 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) {
if($pass == 1)
continue;
-
// Have we seen it? If not, import it.
$item_id = base64url_encode($item->get_id());
@@ -3418,24 +3488,21 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) {
$author['author_name'] = $contact['xchan_name'];
if((! x($author,'author_link')) || ($author['author_is_feed']))
$author['author_link'] = $contact['xchan_url'];
- if((! x($author,'author_photo'))|| ($author['author_is_feed']))
+ if((! x($author,'author_photo'))|| ($author['author_is_feed']))
$author['author_photo'] = $contact['xchan_photo_m'];
$datarray['author_xchan'] = '';
if($author['author_link'] != $contact['xchan_url']) {
$x = import_author_unknown(array('name' => $author['author_name'],'url' => $author['author_link'],'photo' => array('src' => $author['author_photo'])));
- if($x)
+ if($x)
$datarray['author_xchan'] = $x;
-
}
if(! $datarray['author_xchan'])
$datarray['author_xchan'] = $contact['xchan_hash'];
-
$datarray['owner_xchan'] = $contact['xchan_hash'];
-
$r = q("SELECT edited FROM item WHERE mid = '%s' AND uid = %d LIMIT 1",
dbesc($item_id),
intval($importer['channel_id'])
@@ -3444,8 +3511,8 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) {
// Update content if 'updated' changes
if($r) {
- if((x($datarray,'edited') !== false)
- && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
+ if((x($datarray,'edited') !== false)
+ && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
// do not accept (ignore) an earlier edit than one we currently have.
if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
@@ -3459,15 +3526,12 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) {
$datarray['parent_mid'] = $parent_mid;
$datarray['uid'] = $importer['channel_id'];
-
-
logger('consume_feed: ' . print_r($datarray,true),LOGGER_DATA);
$xx = item_store($datarray);
$r = $xx['item_id'];
continue;
}
-
else {
// Head post of a conversation. Have we seen it? If not, import it.
@@ -3481,7 +3545,7 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) {
$author['author_name'] = $contact['xchan_name'];
if((! x($author,'author_link')) || ($author['author_is_feed']))
$author['author_link'] = $contact['xchan_url'];
- if((! x($author,'author_photo'))|| ($author['author_is_feed']))
+ if((! x($author,'author_photo'))|| ($author['author_is_feed']))
$author['author_photo'] = $contact['xchan_photo_m'];
}
@@ -3494,17 +3558,14 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) {
if($author['author_link'] != $contact['xchan_url']) {
$x = import_author_unknown(array('name' => $author['author_name'],'url' => $author['author_link'],'photo' => array('src' => $author['author_photo'])));
- if($x)
+ if($x)
$datarray['author_xchan'] = $x;
-
}
if(! $datarray['author_xchan'])
$datarray['author_xchan'] = $contact['xchan_hash'];
-
$datarray['owner_xchan'] = $contact['xchan_hash'];
-
$r = q("SELECT edited FROM item WHERE mid = '%s' AND uid = %d LIMIT 1",
dbesc($item_id),
intval($importer['channel_id'])
@@ -3513,8 +3574,8 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) {
// Update content if 'updated' changes
if($r) {
- if((x($datarray,'edited') !== false)
- && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
+ if((x($datarray,'edited') !== false)
+ && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
// do not accept (ignore) an earlier edit than one we currently have.
if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
@@ -3526,7 +3587,6 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) {
continue;
}
-
$datarray['parent_mid'] = $item_id;
$datarray['uid'] = $importer['channel_id'];
@@ -3537,26 +3597,20 @@ function consume_feed($xml,$importer,&$contact,$pass = 0) {
$author['owner_avatar'] = $contact['thumb'];
}
- logger('consume_feed: author ' . print_r($author,true),LOGGER_DEBUG);
-
+ logger('consume_feed: author ' . print_r($author,true),LOGGER_DEBUG);
logger('consume_feed: ' . print_r($datarray,true),LOGGER_DATA);
$xx = item_store($datarray);
$r = $xx['item_id'];
continue;
-
}
}
}
-
-
}
function update_feed_item($uid,$datarray) {
-
logger('update_feed_item: not implemented! ' . $uid . ' ' . print_r($datarray,true), LOGGER_DATA);
-
}
@@ -3566,6 +3620,7 @@ function handle_feed($uid,$abook_id,$url) {
$channel = channelx_by_n($uid);
if(! $channel)
return;
+
$x = q("select * from abook left join xchan on abook_xchan = xchan_hash where abook_id = %d and abook_channel = %d limit 1",
dbesc($abook_id),
intval($uid)
@@ -3587,13 +3642,13 @@ function atom_author($tag,$name,$uri,$h,$w,$type,$photo) {
$o = '';
if(! $tag)
return $o;
+
$name = xmlify($name);
$uri = xmlify($uri);
$h = intval($h);
$w = intval($w);
$photo = xmlify($photo);
-
$o .= "<$tag>\r\n";
$o .= "<name>$name</name>\r\n";
$o .= "<uri>$uri</uri>\r\n";
@@ -3603,13 +3658,12 @@ function atom_author($tag,$name,$uri,$h,$w,$type,$photo) {
call_hooks('atom_author', $o);
$o .= "</$tag>\r\n";
+
return $o;
}
function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
- $a = get_app();
-
if(! $item['parent'])
return;
@@ -3622,7 +3676,6 @@ function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
else
$body = $item['body'];
-
$o = "\r\n\r\n<entry>\r\n";
if(is_array($author))
@@ -3656,11 +3709,9 @@ function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
if(($item['item_private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
$o .= '<zot:private>' . (($item['item_private']) ? $item['item_private'] : 1) . '</zot:private>' . "\r\n";
-
if($item['app'])
$o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
-
$verb = construct_verb($item);
$o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
$actobj = construct_activity_object($item);
@@ -3684,11 +3735,11 @@ function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
// $mentioned = get_mentions($item,$tags);
// if($mentioned)
// $o .= $mentioned;
-
+
call_hooks('atom_entry', $o);
$o .= '</entry>' . "\r\n";
-
+
return $o;
}
@@ -3711,7 +3762,6 @@ function fix_private_photos($s, $uid, $item = null, $cid = 0) {
logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
-
if(stristr($image , $site . '/photo/')) {
// Only embed locally hosted photos
$replace = false;
@@ -3731,7 +3781,7 @@ function fix_private_photos($s, $uid, $item = null, $cid = 0) {
// Check to see if we should replace this photo link with an embedded image
// 1. No need to do so if the photo is public
// 2. If there's a contact-id provided, see if they're in the access list
- // for the photo. If so, embed it.
+ // for the photo. If so, embed it.
// 3. Otherwise, if we have an item, see if the item permissions match the photo
// permissions, regardless of order but first check to see if they're an exact
// match to save some processing overhead.
@@ -3740,7 +3790,7 @@ function fix_private_photos($s, $uid, $item = null, $cid = 0) {
if($cid) {
$recips = enumerate_permissions($r[0]);
if(in_array($cid, $recips)) {
- $replace = true;
+ $replace = true;
}
}
elseif($item) {
@@ -3773,7 +3823,7 @@ function fix_private_photos($s, $uid, $item = null, $cid = 0) {
}
}
}
- }
+ }
$new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/zmg]';
$orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/zmg]'));
@@ -3794,11 +3844,12 @@ function fix_private_photos($s, $uid, $item = null, $cid = 0) {
function has_permissions($obj) {
if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
return true;
+
return false;
}
function compare_permissions($obj1,$obj2) {
- // first part is easy. Check that these are exactly the same.
+ // first part is easy. Check that these are exactly the same.
if(($obj1['allow_cid'] == $obj2['allow_cid'])
&& ($obj1['allow_gid'] == $obj2['allow_gid'])
&& ($obj1['deny_cid'] == $obj2['deny_cid'])
@@ -3816,10 +3867,15 @@ function compare_permissions($obj1,$obj2) {
return false;
}
-// returns an array of contact-ids that are allowed to see this object
-
+/**
+ * @brief Returns an array of contact-ids that are allowed to see this object.
+ *
+ * @param object $obj
+ * @return array
+ */
function enumerate_permissions($obj) {
require_once('include/group.php');
+
$allow_people = expand_acl($obj['allow_cid']);
$allow_groups = expand_groups(expand_acl($obj['allow_gid']));
$deny_people = expand_acl($obj['deny_cid']);
@@ -3827,6 +3883,7 @@ function enumerate_permissions($obj) {
$recipients = array_unique(array_merge($allow_people,$allow_groups));
$deny = array_unique(array_merge($deny_people,$deny_groups));
$recipients = array_diff($recipients,$deny);
+
return $recipients;
}
@@ -3843,6 +3900,7 @@ function item_getfeedtags($item) {
$ret[] = array('@',$term['url'],$term['term']);
}
}
+
return $ret;
}
@@ -3863,11 +3921,11 @@ function item_getfeedattach($item) {
}
}
}
+
return $ret;
}
-
function item_expire($uid,$days) {
if((! $uid) || ($days < 1))
@@ -3882,13 +3940,17 @@ function item_expire($uid,$days) {
$sql_extra = ((intval($expire_network_only)) ? " AND item_wall = 0 " : "");
- $r = q("SELECT * FROM `item`
- WHERE `uid` = %d
- AND `created` < %s - INTERVAL %s
- AND `id` = `parent`
+ $expire_limit = get_config('system','expire_limit');
+ if(! intval($expire_limit))
+ $expire_limit = 5000;
+
+ $r = q("SELECT * FROM `item`
+ WHERE `uid` = %d
+ AND `created` < %s - INTERVAL %s
+ AND `id` = `parent`
$sql_extra
AND item_retained = 0
- AND (item_restrict = 0 ) ",
+ AND (item_restrict = 0 ) LIMIT $expire_limit ",
intval($uid),
db_utcnow(), db_quoteinterval(intval($days).' DAY')
);
@@ -3923,7 +3985,6 @@ function item_expire($uid,$days) {
}
// proc_run('php',"include/notifier.php","expire","$uid");
-
}
function retain_item($id) {
@@ -3955,7 +4016,7 @@ function drop_items($items) {
// Delete item with given item $id. $interactive means we're running interactively, and must check
// permissions to carry out this act. If it is non-interactive, we are deleting something at the
-// system's request and do not check permission. This is very important to know.
+// system's request and do not check permission. This is very important to know.
// Some deletion requests (those coming from remote sites) must be staged.
// $stage = 0 => unstaged
@@ -3964,7 +4025,6 @@ function drop_items($items) {
function drop_item($id,$interactive = true,$stage = DROPITEM_NORMAL,$force = false) {
-
$a = get_app();
// locate item to be deleted
@@ -3994,6 +4054,11 @@ function drop_item($id,$interactive = true,$stage = DROPITEM_NORMAL,$force = fal
if(local_channel() && local_channel() == $item['uid'])
$ok_to_delete = true;
+ // sys owned item, requires site admin to delete
+ $sys = get_sys_channel();
+ if(is_site_admin() && $sys['channel_id'] == $item['uid'])
+ $ok_to_delete = true;
+
// author deletion
$observer = $a->get_observer();
if($observer && $observer['xchan_hash'] && ($observer['xchan_hash'] === $item['author_xchan']))
@@ -4001,7 +4066,7 @@ function drop_item($id,$interactive = true,$stage = DROPITEM_NORMAL,$force = fal
if($ok_to_delete) {
- // set the deleted flag immediately on this item just in case the
+ // set the deleted flag immediately on this item just in case the
// hook calls a remote process which loops. We'll delete it properly in a second.
if(($linked_item) && (! $force)) {
@@ -4035,18 +4100,17 @@ function drop_item($id,$interactive = true,$stage = DROPITEM_NORMAL,$force = fal
return 1;
// send the notification upstream/downstream as the case may be
- // only send notifications to others if this is the owner's wall item.
+ // only send notifications to others if this is the owner's wall item.
- // This isn't optimal. We somehow need to pass to this function whether or not
- // to call the notifier, or we need to call the notifier from the calling function.
+ // This isn't optimal. We somehow need to pass to this function whether or not
+ // to call the notifier, or we need to call the notifier from the calling function.
// We'll rely on the undocumented behaviour that DROPITEM_PHASE1 is (hopefully) only
- // set if we know we're going to send delete notifications out to others.
+ // set if we know we're going to send delete notifications out to others.
if((intval($item['item_wall']) && ($stage != DROPITEM_PHASE2)) || ($stage == DROPITEM_PHASE1))
proc_run('php','include/notifier.php','drop',$notify_id);
goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
-
}
else {
if(! $interactive)
@@ -4054,14 +4118,20 @@ function drop_item($id,$interactive = true,$stage = DROPITEM_NORMAL,$force = fal
notice( t('Permission denied.') . EOL);
goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
}
-
}
-// This function does not check for permission and does not send notifications and does not check recursion.
-// It merely destroys all resources associated with an item.
-// Please do not use without a suitable wrapper.
-
-function delete_item_lowlevel($item,$stage = DROPITEM_NORMAL,$force = false) {
+/**
+ * @warning This function does not check for permission and does not send
+ * notifications and does not check recursion.
+ * It merely destroys all resources associated with an item.
+ * Please do not use without a suitable wrapper.
+ *
+ * @param array $item
+ * @param int $stage
+ * @param boolean $force
+ * @return boolean
+ */
+function delete_item_lowlevel($item, $stage = DROPITEM_NORMAL, $force = false) {
$linked_item = (($item['resource_id']) ? true : false);
@@ -4116,15 +4186,13 @@ function delete_item_lowlevel($item,$stage = DROPITEM_NORMAL,$force = false) {
break;
}
-
- // immediately remove any undesired profile likes.
+ // immediately remove any undesired profile likes.
q("delete from likes where iid = %d and channel_id = %d",
intval($item['id']),
intval($item['uid'])
);
-
// network deletion request. Keep the message structure so that we can deliver delete notifications.
// Come back after several days (or perhaps a month) to do the lowlevel delete (DROPITEM_PHASE2).
@@ -4146,7 +4214,7 @@ function delete_item_lowlevel($item,$stage = DROPITEM_NORMAL,$force = false) {
intval(TERM_OBJ_POST)
);
- // FIXME remove notifications for this item
+ /** @FIXME remove notifications for this item */
return true;
}
@@ -4167,26 +4235,31 @@ function first_post_date($uid,$wall = false) {
// logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
return substr(datetime_convert('',date_default_timezone_get(),$r[0]['created']),0,10);
}
+
return false;
}
/**
- * modified posted_dates() {below} to arrange the list in years, which we'll eventually
- * use to make a menu of years with collapsible sub-menus for the months instead of the
+ * modified posted_dates() {below} to arrange the list in years, which we'll eventually
+ * use to make a menu of years with collapsible sub-menus for the months instead of the
* current flat list of all representative dates.
+ *
+ * @param int $uid
+ * @param unknown $wall
+ * @param unknown $mindate
+ * @return array
*/
-
-function list_post_dates($uid,$wall,$mindate) {
+function list_post_dates($uid, $wall, $mindate) {
$dnow = datetime_convert('',date_default_timezone_get(),'now','Y-m-d');
if($mindate)
- $dthen = datetime_convert('',date_default_timezone_get(),$mindate);
+ $dthen = datetime_convert('',date_default_timezone_get(), $mindate);
else
- $dthen = first_post_date($uid,$wall);
+ $dthen = first_post_date($uid, $wall);
if(! $dthen)
return array();
- // If it's near the end of a long month, backup to the 28th so that in
+ // If it's near the end of a long month, backup to the 28th so that in
// consecutive loops we'll always get a whole month difference.
if(intval(substr($dnow,8)) > 28)
@@ -4209,6 +4282,7 @@ function list_post_dates($uid,$wall,$mindate) {
$ret[$dyear][] = array($str,$end_month,$start_month);
$dnow = datetime_convert('','',$dnow . ' -1 month', 'Y-m-d');
}
+
return $ret;
}
@@ -4220,7 +4294,7 @@ function posted_dates($uid,$wall) {
if(! $dthen)
return array();
- // If it's near the end of a long month, backup to the 28th so that in
+ // If it's near the end of a long month, backup to the 28th so that in
// consecutive loops we'll always get a whole month difference.
if(intval(substr($dnow,8)) > 28)
@@ -4247,7 +4321,7 @@ function posted_dates($uid,$wall) {
function fetch_post_tags($items,$link = false) {
$tag_finder = array();
- if($items) {
+ if($items) {
foreach($items as $item) {
if(is_array($item)) {
if(array_key_exists('item_id',$item)) {
@@ -4271,7 +4345,6 @@ function fetch_post_tags($items,$link = false) {
);
}
-
for($x = 0; $x < count($items); $x ++) {
if($tags) {
foreach($tags as $t) {
@@ -4302,7 +4375,6 @@ function fetch_post_tags($items,$link = false) {
function zot_feed($uid,$observer_xchan,$arr) {
-
$result = array();
$mindate = null;
$message_id = null;
@@ -4315,9 +4387,9 @@ function zot_feed($uid,$observer_xchan,$arr) {
$message_id = $arr['message_id'];
}
-
if(! $mindate)
$mindate = NULL_DATE;
+
$mindate = dbesc($mindate);
logger('zot_feed: requested for uid ' . $uid . ' from observer ' . $observer_xchan, LOGGER_DEBUG);
@@ -4334,12 +4406,11 @@ function zot_feed($uid,$observer_xchan,$arr) {
$sql_extra = item_permissions_sql($uid);
}
+ $limit = " LIMIT 100 ";
+
if($mindate != NULL_DATE) {
$sql_extra .= " and ( created > '$mindate' or edited > '$mindate' ) ";
- $limit = "";
}
- else
- $limit = " limit 0, 50 ";
if($message_id) {
$sql_extra .= " and mid = '" . dbesc($message_id) . "' ";
@@ -4348,21 +4419,27 @@ function zot_feed($uid,$observer_xchan,$arr) {
$items = array();
+ /** @FIXME fix this part for PostgreSQL */
+
+ if(ACTIVE_DBTYPE == DBTYPE_POSTGRES) {
+ return array();
+ }
+
if(is_sys_channel($uid)) {
require_once('include/security.php');
- $r = q("SELECT distinct parent, created from item
+ $r = q("SELECT parent, created from item
WHERE uid != %d
- and uid in (" . stream_perms_api_uids(PERMS_PUBLIC) . ") AND item_restrict = 0
+ and uid in (" . stream_perms_api_uids(PERMS_PUBLIC,10,1) . ") AND item_restrict = 0
AND item_wall = 1
- and item_private = 0 $sql_extra ORDER BY created ASC $limit",
+ and item_private = 0 $sql_extra GROUP BY parent ORDER BY created ASC $limit",
intval($uid)
);
}
else {
- $r = q("SELECT distinct parent, created from item
+ $r = q("SELECT parent, created from item
WHERE uid = %d AND item_restrict = 0
AND item_wall = 1
- $sql_extra ORDER BY created ASC $limit",
+ $sql_extra GROUP BY parent ORDER BY created ASC $limit",
intval($uid)
);
}
@@ -4370,8 +4447,8 @@ function zot_feed($uid,$observer_xchan,$arr) {
if($r) {
$parents_str = ids_to_querystr($r,'parent');
$sys_query = ((is_sys_channel($uid)) ? $sql_extra : '');
-
- $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item`
+
+ $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item`
WHERE `item`.`item_restrict` = 0
AND `item`.`parent` IN ( %s ) $sys_query ",
dbesc($parents_str)
@@ -4383,12 +4460,10 @@ function zot_feed($uid,$observer_xchan,$arr) {
$items = fetch_post_tags($items);
require_once('include/conversation.php');
$items = conv_sort($items,'ascending');
-
}
else
$items = array();
-
logger('zot_feed: number items: ' . count($items),LOGGER_DEBUG);
foreach($items as $item)
@@ -4409,13 +4484,13 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C
$sql_nets = '';
$sql_options = '';
$sql_extra2 = '';
- $sql_extra3 = '';
+ $sql_extra3 = '';
$def_acl = '';
$item_uids = ' true ';
-
+
if ($arr['uid']) $uid= $arr['uid'];
-
+
if($channel) {
$uid = $channel['channel_id'];
$uidhash = $channel['channel_hash'];
@@ -4431,61 +4506,60 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C
$sql_extra = " AND item.parent IN ( SELECT parent FROM item WHERE item_thread_top = 1 $sql_options ) ";
if($arr['since_id'])
- $sql_extra .= " and item.id > " . $since_id . " ";
-
- if($arr['gid'] && $uid) {
- $r = q("SELECT * FROM `groups` WHERE id = %d AND uid = %d LIMIT 1",
- intval($arr['group']),
- intval($uid)
- );
- if(! $r) {
+ $sql_extra .= " and item.id > " . $since_id . " ";
+
+ if($arr['gid'] && $uid) {
+ $r = q("SELECT * FROM `groups` WHERE id = %d AND uid = %d LIMIT 1",
+ intval($arr['group']),
+ intval($uid)
+ );
+ if(! $r) {
$result['message'] = t('Collection not found.');
return $result;
- }
+ }
$contact_str = '';
- $contacts = group_get_members($group);
- if($contacts) {
+ /** @FIXME $group is undefined */
+ $contacts = group_get_members($group);
+ if ($contacts) {
foreach($contacts as $c) {
if($contact_str)
$contact_str .= ',';
- $contact_str .= "'" . $c['xchan'] . "'";
+
+ $contact_str .= "'" . $c['xchan'] . "'";
}
- }
- else {
- $contact_str = ' 0 ';
+ } else {
+ $contact_str = ' 0 ';
$result['message'] = t('Collection is empty.');
return $result;
- }
+ }
- $sql_extra = " AND item.parent IN ( SELECT DISTINCT parent FROM item WHERE true $sql_options AND (( author_xchan IN ( $contact_str ) OR owner_xchan in ( $contact_str)) or allow_gid like '" . protect_sprintf('%<' . dbesc($r[0]['hash']) . '>%') . "' ) and id = parent and item_restrict = 0 ) ";
+ $sql_extra = " AND item.parent IN ( SELECT DISTINCT parent FROM item WHERE true $sql_options AND (( author_xchan IN ( $contact_str ) OR owner_xchan in ( $contact_str)) or allow_gid like '" . protect_sprintf('%<' . dbesc($r[0]['hash']) . '>%') . "' ) and id = parent and item_restrict = 0 ) ";
$x = group_rec_byhash($uid,$r[0]['hash']);
$result['headline'] = sprintf( t('Collection: %s'),$x['name']);
+ }
+ elseif($arr['cid'] && $uid) {
- }
- elseif($arr['cid'] && $uid) {
-
- $r = q("SELECT abook.*, xchan.* from abook left join xchan on abook_xchan = xchan_hash where abook_id = %d and abook_channel = %d and not ( abook_flags & " . intval(ABOOK_FLAG_BLOCKED) . ")>0 limit 1",
+ $r = q("SELECT abook.*, xchan.* from abook left join xchan on abook_xchan = xchan_hash where abook_id = %d and abook_channel = %d and not ( abook_flags & " . intval(ABOOK_FLAG_BLOCKED) . ")>0 limit 1",
intval($arr['cid']),
intval(local_channel())
- );
- if($r) {
- $sql_extra = " AND item.parent IN ( SELECT DISTINCT parent FROM item WHERE true $sql_options AND uid = " . intval($arr['uid']) . " AND ( author_xchan = '" . dbesc($r[0]['abook_xchan']) . "' or owner_xchan = '" . dbesc($r[0]['abook_xchan']) . "' ) and item_restrict = 0 ) ";
+ );
+ if ($r) {
+ $sql_extra = " AND item.parent IN ( SELECT DISTINCT parent FROM item WHERE true $sql_options AND uid = " . intval($arr['uid']) . " AND ( author_xchan = '" . dbesc($r[0]['abook_xchan']) . "' or owner_xchan = '" . dbesc($r[0]['abook_xchan']) . "' ) and item_restrict = 0 ) ";
$result['headline'] = sprintf( t('Connection: %s'),$r[0]['xchan_name']);
- }
- else {
+ } else {
$result['message'] = t('Connection not found.');
return $result;
- }
- }
+ }
+ }
- if($arr['datequery']) {
- $sql_extra3 .= protect_sprintf(sprintf(" AND item.created <= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$arr['datequery']))));
- }
- if($arr['datequery2']) {
- $sql_extra3 .= protect_sprintf(sprintf(" AND item.created >= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$arr['datequery2']))));
- }
+ if ($arr['datequery']) {
+ $sql_extra3 .= protect_sprintf(sprintf(" AND item.created <= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$arr['datequery']))));
+ }
+ if ($arr['datequery2']) {
+ $sql_extra3 .= protect_sprintf(sprintf(" AND item.created >= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$arr['datequery2']))));
+ }
if(! array_key_exists('nouveau',$arr)) {
$sql_extra2 = " AND item.parent = item.id ";
@@ -4493,6 +4567,7 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C
}
if($arr['search']) {
+
if(strpos($arr['search'],'#') === 0)
$sql_extra .= term_query('item',substr($arr['search'],1),TERM_HASHTAG);
else
@@ -4511,24 +4586,20 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C
);
}
+ if (($client_mode & CLIENT_MODE_UPDATE) && (! ($client_mode & CLIENT_MODE_LOAD))) {
+ // only setup pagination on initial page view
+ $pager_sql = '';
+ } else {
+ $itemspage = (($channel) ? get_pconfig($uid,'system','itemspage') : 20);
+ $a->set_pager_itemspage(((intval($itemspage)) ? $itemspage : 20));
+ $pager_sql = sprintf(" LIMIT %d OFFSET %d ", intval(get_app()->pager['itemspage']), intval(get_app()->pager['start']));
+ }
- if(($client_mode & CLIENT_MODE_UPDATE) && (! ($client_mode & CLIENT_MODE_LOAD))) {
-
- // only setup pagination on initial page view
- $pager_sql = '';
-
- }
- else {
- $itemspage = (($channel) ? get_pconfig($uid,'system','itemspage') : 20);
- $a->set_pager_itemspage(((intval($itemspage)) ? $itemspage : 20));
- $pager_sql = sprintf(" LIMIT %d OFFSET %d ", intval(get_app()->pager['itemspage']), intval(get_app()->pager['start']));
- }
-
- if(isset($arr['start']) && isset($arr['records']))
- $pager_sql = sprintf(" LIMIT %d OFFSET %d ", intval($arr['records']), intval($arr['start']));
+ if (isset($arr['start']) && isset($arr['records']))
+ $pager_sql = sprintf(" LIMIT %d OFFSET %d ", intval($arr['records']), intval($arr['start']));
- if(array_key_exists('cmin',$arr) || array_key_exists('cmax',$arr)) {
- if(($arr['cmin'] != 0) || ($arr['cmax'] != 99)) {
+ if (array_key_exists('cmin',$arr) || array_key_exists('cmax',$arr)) {
+ if (($arr['cmin'] != 0) || ($arr['cmax'] != 99)) {
// Not everybody who shows up in the network stream will be in your address book.
// By default those that aren't are assumed to have closeness = 99; but this isn't
@@ -4537,21 +4608,22 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C
$sql_nets .= " AND ";
- if($arr['cmax'] == 99)
+ if ($arr['cmax'] == 99)
$sql_nets .= " ( ";
$sql_nets .= "( abook.abook_closeness >= " . intval($arr['cmin']) . " ";
$sql_nets .= " AND abook.abook_closeness <= " . intval($arr['cmax']) . " ) ";
- if($cmax == 99)
+ /** @fixme dead code, $cmax is undefined */
+ if ($cmax == 99)
$sql_nets .= " OR abook.abook_closeness IS NULL ) ";
- }
+ }
}
$simple_update = (($client_mode & CLIENT_MODE_UPDATE) ? " and item.item_unseen = 1 " : '');
if($client_mode & CLIENT_MODE_LOAD)
$simple_update = '';
- $start = dba_timer();
+ //$start = dba_timer();
require_once('include/security.php');
$sql_extra .= item_permissions_sql($channel['channel_id']);
@@ -4561,33 +4633,31 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C
else
$item_restrict = " AND item_type = 0 ";
+ if ($arr['nouveau'] && ($client_mode & CLIENT_MODE_LOAD) && $channel) {
+ // "New Item View" - show all items unthreaded in reverse created date order
- if($arr['nouveau'] && ($client_mode & CLIENT_MODE_LOAD) && $channel) {
- // "New Item View" - show all items unthreaded in reverse created date order
-
- $items = q("SELECT item.*, item.id AS item_id FROM item
- WHERE $item_uids $item_restrict
- $simple_update
- $sql_extra $sql_nets
- ORDER BY item.received DESC $pager_sql "
- );
+ $items = q("SELECT item.*, item.id AS item_id FROM item
+ WHERE $item_uids $item_restrict
+ $simple_update
+ $sql_extra $sql_nets
+ ORDER BY item.received DESC $pager_sql"
+ );
- require_once('include/items.php');
+ require_once('include/items.php');
- xchan_query($items);
+ xchan_query($items);
- $items = fetch_post_tags($items,true);
- }
- else {
+ $items = fetch_post_tags($items,true);
+ } else {
- // Normal conversation view
+ // Normal conversation view
- if($arr['order'] === 'post')
+ if($arr['order'] === 'post')
$ordering = "created";
- else
+ else
$ordering = "commented";
- if(($client_mode & CLIENT_MODE_LOAD) || ($client_mode == CLIENT_MODE_NORMAL)) {
+ if(($client_mode & CLIENT_MODE_LOAD) || ($client_mode == CLIENT_MODE_NORMAL)) {
// Fetch a page full of parent items for this page
@@ -4600,7 +4670,7 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C
ORDER BY item.$ordering DESC $pager_sql ",
intval(ABOOK_FLAG_BLOCKED)
);
-
+
}
else {
// update
@@ -4613,48 +4683,46 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C
);
}
- $first = dba_timer();
+ //$first = dba_timer();
- // Then fetch all the children of the parents that are on this page
+ // Then fetch all the children of the parents that are on this page
- if($r) {
+ if($r) {
- $parents_str = ids_to_querystr($r,'item_id');
+ $parents_str = ids_to_querystr($r,'item_id');
if($arr['top'])
$sql_extra = ' and id = parent ' . $sql_extra;
- $items = q("SELECT item.*, item.id AS item_id FROM item
- WHERE $item_uids $item_restrict
- AND item.parent IN ( %s )
- $sql_extra ",
- dbesc($parents_str)
- );
+ $items = q("SELECT item.*, item.id AS item_id FROM item
+ WHERE $item_uids $item_restrict
+ AND item.parent IN ( %s )
+ $sql_extra ",
+ dbesc($parents_str)
+ );
- $second = dba_timer();
+ //$second = dba_timer();
- xchan_query($items);
+ xchan_query($items);
- $third = dba_timer();
+ //$third = dba_timer();
- $items = fetch_post_tags($items,true);
+ $items = fetch_post_tags($items,true);
- $fourth = dba_timer();
+ //$fourth = dba_timer();
require_once('include/conversation.php');
- $items = conv_sort($items,$ordering);
-
- //logger('items: ' . print_r($items,true));
+ $items = conv_sort($items,$ordering);
- }
- else {
- $items = array();
- }
+ //logger('items: ' . print_r($items,true));
+ } else {
+ $items = array();
+ }
- if($parents_str && $arr['mark_seen'])
- $update_unseen = ' AND parent IN ( ' . dbesc($parents_str) . ' )';
- // FIXME finish mark unseen sql
- }
+ if($parents_str && $arr['mark_seen'])
+ $update_unseen = ' AND parent IN ( ' . dbesc($parents_str) . ' )';
+ /** @FIXME finish mark unseen sql */
+ }
return $items;
}
@@ -4675,11 +4743,11 @@ function update_remote_id($channel,$post_id,$webpage,$pagetitle,$namespace,$remo
$pagetitle = $remote_id;
}
- if($page_type) {
+ if($page_type) {
- // store page info as an alternate message_id so we can access it via
+ // store page info as an alternate message_id so we can access it via
// https://sitename/page/$channelname/$pagetitle
- // if no pagetitle was given or it couldn't be transliterated into a url, use the first
+ // if no pagetitle was given or it couldn't be transliterated into a url, use the first
// sixteen bytes of the mid - which makes the link portable and not quite as daunting
// as the entire mid. If it were the post_id the link would be less portable.
@@ -4703,17 +4771,17 @@ function update_remote_id($channel,$post_id,$webpage,$pagetitle,$namespace,$remo
);
}
}
-
}
-
/**
- * change access control for item with message_id $mid and channel_id $uid
+ * @brief Change access control for item with message_id $mid and channel_id $uid.
+ *
+ * @param string $xchan_hash
+ * @param string $mid
+ * @param int $uid
*/
-
-
-function item_add_cid($xchan_hash,$mid,$uid) {
+function item_add_cid($xchan_hash, $mid, $uid) {
$r = q("select id from item where mid = '%s' and uid = %d and allow_cid like '%s'",
dbesc($mid),
intval($uid),
@@ -4744,7 +4812,7 @@ function item_remove_cid($xchan_hash,$mid,$uid) {
}
// Set item permissions based on results obtained from linkify_tags()
-function set_linkified_perms($linkified, &$str_contact_allow, &$str_group_allow, $profile_uid, $parent_item = false) {
+function set_linkified_perms($linkified, &$str_contact_allow, &$str_group_allow, $profile_uid, $parent_item = false, &$private) {
$first_access_tag = true;
foreach($linkified as $x) {
@@ -4754,9 +4822,9 @@ function set_linkified_perms($linkified, &$str_contact_allow, &$str_group_allow,
if ($first_access_tag && (! get_pconfig($profile_uid,'system','no_private_mention_acl_override'))) {
// This is a tough call, hence configurable. The issue is that one can type in a @!privacy mention
- // and also have a default ACL (perhaps from viewing a collection) and could be suprised that the
+ // and also have a default ACL (perhaps from viewing a collection) and could be suprised that the
// privacy mention wasn't the only recipient. So the default is to wipe out the existing ACL if a
- // private mention is found. This can be over-ridden if you wish private mentions to be in
+ // private mention is found. This can be over-ridden if you wish private mentions to be in
// addition to the current ACL settings.
$str_contact_allow = '';
@@ -4765,12 +4833,30 @@ function set_linkified_perms($linkified, &$str_contact_allow, &$str_group_allow,
}
if(strpos($access_tag,'cid:') === 0) {
$str_contact_allow .= '<' . substr($access_tag,4) . '>';
- $access_tag = '';
+ $access_tag = '';
+ $private = 1;
}
elseif(strpos($access_tag,'gid:') === 0) {
$str_group_allow .= '<' . substr($access_tag,4) . '>';
- $access_tag = '';
+ $access_tag = '';
+ $private = 1;
}
}
}
}
+
+/**
+ * We can't trust ITEM_ORIGIN to tell us if this is a local comment
+ * which needs to be relayed, because it was misconfigured at one point for several
+ * months and set for some remote items (in alternate delivery chains). This could
+ * cause looping, so use this hackish but accurate method.
+ *
+ * @param array $item
+ * @return boolean
+ */
+function comment_local_origin($item) {
+ if(stripos($item['mid'], get_app()->get_hostname()) && ($item['parent'] != $item['id']))
+ return true;
+
+ return false;
+}
diff --git a/include/js_strings.php b/include/js_strings.php
index 56ffa9536..cae8da5de 100644
--- a/include/js_strings.php
+++ b/include/js_strings.php
@@ -20,6 +20,8 @@ function js_strings() {
'$rating_val' => t('Rating'),
'$rating_text' => t('Describe (optional)'),
'$submit' => t('Submit'),
+ '$linkurl' => t('Please enter a link URL'),
+ '$leavethispage' => t('Unsaved changes. Are you sure you wish to leave this page?'),
'$t01' => ((t('timeago.prefixAgo') != 'timeago.prefixAgo') ? t('timeago.prefixAgo') : ''),
'$t02' => ((t('timeago.prefixFromNow') != 'timeago.prefixFromNow') ? t('timeago.prefixFromNow') : ''),
diff --git a/include/language.php b/include/language.php
index f5ee3471e..1e8528dc1 100644
--- a/include/language.php
+++ b/include/language.php
@@ -1,8 +1,8 @@
<?php
/**
- * @file
+ * @file include/language.php
*
- * @brief translation support
+ * @brief Translation support.
*
* This file contains functions to work with translations and other
* language related tasks.
@@ -24,8 +24,9 @@
*/
function get_browser_language() {
$langs = array();
+ $lang_parse = array();
- if (x($_SERVER,'HTTP_ACCEPT_LANGUAGE')) {
+ if (x($_SERVER, 'HTTP_ACCEPT_LANGUAGE')) {
// break up string into pieces (languages and q factors)
preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i',
$_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);
@@ -33,7 +34,7 @@ function get_browser_language() {
if (count($lang_parse[1])) {
// create a list like "en" => 0.8
$langs = array_combine($lang_parse[1], $lang_parse[4]);
-
+
// set default to 1 for any without q factor
foreach ($langs as $lang => $val) {
if ($val === '') $langs[$lang] = 1;
@@ -109,9 +110,12 @@ function pop_lang() {
$a->language = $a->langsave;
}
-
-// load string translation table for alternate language
-
+/**
+ * @brief Load string translation table for alternate language.
+ *
+ * @param string $lang language code in 2-letter ISO 639-1 (en, de, fr) format
+ * @param boolean $install (optional) default false
+ */
function load_translation_table($lang, $install = false) {
global $a;
@@ -138,52 +142,67 @@ function load_translation_table($lang, $install = false) {
if(file_exists("view/local-$lang/strings.php")) {
include("view/local-$lang/strings.php");
}
-
}
/**
- * @brief translate string if translation exists.
+ * @brief Translate string if translation exists.
*
- * @param $s string that should get translated
- * @param $ctx optional context to appear in po file
+ * @param string $s string that should get translated
+ * @param string $ctx (optional) context to appear in po file
* @return translated string if exists, otherwise return $s
*
*/
-function t($s,$ctx = '') {
+function t($s, $ctx = '') {
global $a;
- $cs = $ctx?"__ctx:".$ctx."__ ".$s:$s;
- if(x($a->strings,$cs)) {
+ $cs = $ctx ? '__ctx:' . $ctx . '__ ' . $s : $s;
+ if (x($a->strings, $cs)) {
$t = $a->strings[$cs];
+
return is_array($t) ? $t[0] : $t;
}
+
return $s;
}
-
+/**
+ * @brief
+ *
+ * @param string $singular
+ * @param string $plural
+ * @param int $count
+ * @param string $ctx
+ * @return string
+ */
function tt($singular, $plural, $count, $ctx = ''){
$a = get_app();
- $cs = $ctx?"__ctx:".$ctx."__ ".$singular:$singular;
- if(x($a->strings,$cs)) {
+ $cs = $ctx ? "__ctx:" . $ctx . "__ " . $singular : $singular;
+ if (x($a->strings,$cs)) {
$t = $a->strings[$cs];
$f = 'string_plural_select_' . str_replace('-', '_', $a->language);
- if(! function_exists($f))
+ if (! function_exists($f))
$f = 'string_plural_select_default';
+
$k = $f($count);
+
return is_array($t) ? $t[$k] : $t;
}
-
- if ($count != 1){
+
+ if ($count != 1) {
return $plural;
} else {
return $singular;
}
}
-// provide a fallback which will not collide with
-// a function defined in any language file
-
+/**
+ * @brief Provide a fallback which will not collide with a function defined in
+ * any language file.
+ *
+ * @param int $n
+ * @return boolean
+ */
function string_plural_select_default($n) {
return ($n != 1);
}
@@ -199,26 +218,26 @@ function string_plural_select_default($n) {
* returned through config['system']['language_detect_min_confidence'].
*
* @see http://pear.php.net/package/Text_LanguageDetect
- * @param s A string to examine
+ * @param string $s A string to examine
* @return Language code in 2-letter ISO 639-1 (en, de, fr) format
*/
function detect_language($s) {
require_once('Text/LanguageDetect.php');
$min_length = get_config('system', 'language_detect_min_length');
- if($min_length === false)
+ if ($min_length === false)
$min_length = LANGUAGE_DETECT_MIN_LENGTH;
$min_confidence = get_config('system', 'language_detect_min_confidence');
- if($min_confidence === false)
+ if ($min_confidence === false)
$min_confidence = LANGUAGE_DETECT_MIN_CONFIDENCE;
// embedded apps have long base64 strings which will trip up the detector.
$naked_body = preg_replace('/\[app\](.*?)\[\/app\]/','',$s);
// strip off bbcode
$naked_body = preg_replace('/\[(.+?)\]/', '', $naked_body);
- if(mb_strlen($naked_body) < intval($min_length)) {
- logger('detect language: string length less than ' . intval($min_length), LOGGER_DATA);
+ if (mb_strlen($naked_body) < intval($min_length)) {
+ logger('string length less than ' . intval($min_length), LOGGER_DATA);
return '';
}
@@ -232,11 +251,11 @@ function detect_language($s) {
logger('detect language exception: ' . $e->getMessage(), LOGGER_DATA);
}
- if((! $lng) || (! (x($lng,'language')))) {
+ if ((! $lng) || (! (x($lng,'language')))) {
return '';
}
- if($lng['confidence'] < (float) $min_confidence) {
+ if ($lng['confidence'] < (float) $min_confidence) {
logger('detect language: confidence less than ' . (float) $min_confidence, LOGGER_DATA);
return '';
}
@@ -250,38 +269,37 @@ function detect_language($s) {
* By default we use the localized language name. You can switch the result
* to any language with the optional 2nd parameter $l.
*
- * $s and $l should be in 2-letter ISO 639-1 format
+ * $s and $l should be in 2-letter ISO 639-1 format.
*
* If nothing could be looked up it returns $s.
*
- * @param $s Language code to look up
- * @param $l (optional) In which language to return the name
+ * @param string $s Language code to look up
+ * @param string $l (optional) In which language to return the name
* @return string with the language name, or $s if unrecognized
+ *
+ * @todo include CommerceGuys\Intl through composer like SabreDAV.
*/
require_once(__DIR__ . '/../library/intl/vendor/autoload.php');
use CommerceGuys\Intl\Language\LanguageRepository;
function get_language_name($s, $l = null) {
// get() expects the second part to be in upper case
- if(strpos($s,'-') !== false) $s = substr($s,0,2) . strtoupper(substr($s,2));
- if($l !== null && strpos($l,'-') !== false) $l = substr($l,0,2) . strtoupper(substr($l,2));
+ if (strpos($s, '-') !== false) $s = substr($s, 0, 2) . strtoupper(substr($s, 2));
+ if ($l !== null && strpos($l, '-') !== false) $l = substr($l, 0, 2) . strtoupper(substr($l, 2));
$languageRepository = new LanguageRepository;
// Sometimes intl doesn't like the second part at all ...
try {
$language = $languageRepository->get($s, $l);
- }
- catch(CommerceGuys\Intl\Exception\UnknownLanguageException $e) {
- $s = substr($s,0,2);
- if($l !== null) $l = substr($s,0,2);
+ } catch(CommerceGuys\Intl\Exception\UnknownLanguageException $e) {
+ $s = substr($s, 0, 2);
+ if($l !== null) $l = substr($s, 0, 2);
try {
$language = $languageRepository->get($s, $l);
- }
- catch(CommerceGuys\Intl\Exception\UnknownLanguageException $e) {
+ } catch (CommerceGuys\Intl\Exception\UnknownLanguageException $e) {
return $s; // Give up
}
- }
+ }
return $language->getName();
}
-
diff --git a/include/menu.php b/include/menu.php
index 81e986132..b4f4555a5 100644
--- a/include/menu.php
+++ b/include/menu.php
@@ -25,6 +25,7 @@ function menu_fetch($name,$uid,$observer_xchan) {
}
function menu_render($menu, $class='', $edit = false) {
+
if(! $menu)
return '';
@@ -40,6 +41,7 @@ function menu_render($menu, $class='', $edit = false) {
'$menu' => $menu['menu'],
'$class' => $class,
'$edit' => (($edit) ? t("Edit") : ''),
+ '$id' => $menu['menu']['menu_id'],
'$items' => $menu['items']
));
}
@@ -60,14 +62,13 @@ function menu_fetch_id($menu_id,$channel_id) {
function menu_create($arr) {
-
$menu_name = trim(escape_tags($arr['menu_name']));
$menu_desc = trim(escape_tags($arr['menu_desc']));
$menu_flags = intval($arr['menu_flags']);
-
- if(! $menu_desc)
- $menu_desc = $menu_name;
+ //allow menu_desc (title) to be empty
+ //if(! $menu_desc)
+ // $menu_desc = $menu_name;
if(! $menu_name)
return false;
@@ -144,8 +145,9 @@ function menu_edit($arr) {
$menu_desc = trim(escape_tags($arr['menu_desc']));
$menu_flags = intval($arr['menu_flags']);
- if(! $menu_desc)
- $menu_desc = $menu_name;
+ //allow menu_desc (title) to be empty
+ //if(! $menu_desc)
+ // $menu_desc = $menu_name;
if(! $menu_name)
return false;
@@ -227,31 +229,10 @@ function menu_add_item($menu_id, $uid, $arr) {
$channel = get_app()->get_channel();
}
- if (($channel)
- && (! $arr['contact_allow'])
- && (! $arr['group_allow'])
- && (! $arr['contact_deny'])
- && (! $arr['group_deny'])) {
- $str_group_allow = $channel['channel_allow_gid'];
- $str_contact_allow = $channel['channel_allow_cid'];
- $str_group_deny = $channel['channel_deny_gid'];
- $str_contact_deny = $channel['channel_deny_cid'];
- }
- else {
-
- // use the posted permissions
-
- $str_group_allow = perms2str($arr['group_allow']);
- $str_contact_allow = perms2str($arr['contact_allow']);
- $str_group_deny = perms2str($arr['group_deny']);
- $str_contact_deny = perms2str($arr['contact_deny']);
- }
-
-// unused
-// $allow_cid = perms2str($arr['allow_cid']);
-// $allow_gid = perms2str($arr['allow_gid']);
-// $deny_cid = perms2str($arr['deny_cid']);
-// $deny_gid = perms2str($arr['deny_gid']);
+ $str_group_allow = perms2str($arr['group_allow']);
+ $str_contact_allow = perms2str($arr['contact_allow']);
+ $str_group_deny = perms2str($arr['group_deny']);
+ $str_contact_deny = perms2str($arr['contact_deny']);
$r = q("insert into menu_item ( mitem_link, mitem_desc, mitem_flags, allow_cid, allow_gid, deny_cid, deny_gid, mitem_channel_id, mitem_menu_id, mitem_order ) values ( '%s', '%s', %d, '%s', '%s', '%s', '%s', %d, %d, %d ) ",
dbesc($mitem_link),
@@ -283,25 +264,10 @@ function menu_edit_item($menu_id, $uid, $arr) {
$channel = get_app()->get_channel();
}
- if ((! $arr['contact_allow'])
- && (! $arr['group_allow'])
- && (! $arr['contact_deny'])
- && (! $arr['group_deny'])) {
- $str_group_allow = $channel['channel_allow_gid'];
- $str_contact_allow = $channel['channel_allow_cid'];
- $str_group_deny = $channel['channel_deny_gid'];
- $str_contact_deny = $channel['channel_deny_cid'];
- }
- else {
-
- // use the posted permissions
-
- $str_group_allow = perms2str($arr['group_allow']);
- $str_contact_allow = perms2str($arr['contact_allow']);
- $str_group_deny = perms2str($arr['group_deny']);
- $str_contact_deny = perms2str($arr['contact_deny']);
- }
-
+ $str_group_allow = perms2str($arr['group_allow']);
+ $str_contact_allow = perms2str($arr['contact_allow']);
+ $str_group_deny = perms2str($arr['group_deny']);
+ $str_contact_deny = perms2str($arr['contact_deny']);
$r = q("update menu_item set mitem_link = '%s', mitem_desc = '%s', mitem_flags = %d, allow_cid = '%s', allow_gid = '%s', deny_cid = '%s', deny_gid = '%s', mitem_order = %d where mitem_channel_id = %d and mitem_menu_id = %d and mitem_id = %d",
dbesc($mitem_link),
diff --git a/include/nav.php b/include/nav.php
index 5e8317cfa..1134d1b48 100644
--- a/include/nav.php
+++ b/include/nav.php
@@ -176,10 +176,8 @@ EOT;
if(local_channel()) {
- $network_options = get_pconfig(local_channel(),'system','network_page_default');
- $nav['network'] = array('network' . (($network_options) ? '?f=&' . $network_options : ''),
- t('Matrix'), "", t('Your matrix'),'network_nav_btn');
+ $nav['network'] = array('network', t('Matrix'), "", t('Your matrix'),'network_nav_btn');
$nav['network']['mark'] = array('', t('Mark all matrix notifications seen'), '','');
$nav['home'] = array('channel/' . $channel['channel_address'], t('Channel Home'), "", t('Channel home'),'home_nav_btn');
diff --git a/include/network.php b/include/network.php
index 84c1c17f8..0ee7f044f 100644
--- a/include/network.php
+++ b/include/network.php
@@ -1,38 +1,43 @@
-<?php /** @file */
-
-
+<?php
+/**
+ * @file include/network.php
+ */
+/**
+ * @brief Returns path to CA file.
+ *
+ * @return string
+ */
function get_capath() {
return appdirpath() . '/library/cacert.pem';
}
/**
- * @function z_fetch_url
+ * @brief fetches an URL.
+ *
* @param string $url
* URL to fetch
- * @param boolean $binary = false
+ * @param boolean $binary default false
* TRUE if asked to return binary results (file download)
- * @param int $redirects = 0
+ * @param int $redirects default 0
* internal use, recursion counter
- * @param array $opts (optional parameters)
- * 'accept_content' => supply Accept: header with 'accept_content' as the value
- * 'timeout' => int seconds, default system config value or 60 seconds
- * 'http_auth' => username:password
- * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
- *
- * @returns array
- * 'return_code' => HTTP return code or 0 if timeout or failure
- * 'success' => boolean true (if HTTP 2xx result) or false
- * 'header' => HTTP headers
- * 'body' => fetched content
+ * @param array $opts (optional parameters) assoziative array with:
+ * * \b accept_content => supply Accept: header with 'accept_content' as the value
+ * * \b timeout => int seconds, default system config value or 60 seconds
+ * * \b http_auth => username:password
+ * * \b novalidate => do not validate SSL certs, default is to validate using our CA list
+ * * \b nobody => only return the header
+ *
+ * @return array an assoziative array with:
+ * * \e int \b return_code => HTTP return code or 0 if timeout or failure
+ * * \e boolean \b success => boolean true (if HTTP 2xx result) or false
+ * * \e string \b header => HTTP headers
+ * * \e string \b body => fetched content
*/
-
function z_fetch_url($url, $binary = false, $redirects = 0, $opts = array()) {
$ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => "");
- $a = get_app();
-
$ch = @curl_init($url);
if(($redirects > 8) || (! $ch))
return false;
@@ -51,6 +56,9 @@ function z_fetch_url($url, $binary = false, $redirects = 0, $opts = array()) {
if(x($opts,'headers'))
@curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
+ if(x($opts,'nobody'))
+ @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
+
if(x($opts,'timeout') && intval($opts['timeout'])) {
@curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
}
@@ -67,7 +75,6 @@ function z_fetch_url($url, $binary = false, $redirects = 0, $opts = array()) {
@curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,
((x($opts,'novalidate') && intval($opts['novalidate'])) ? false : true));
-
$prx = get_config('system','proxy');
if(strlen($prx)) {
@curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
@@ -109,7 +116,7 @@ function z_fetch_url($url, $binary = false, $redirects = 0, $opts = array()) {
$url_parsed = @parse_url($newurl);
if (isset($url_parsed)) {
@curl_close($ch);
- return z_fetch_url($newurl,$binary,$redirects++,$opts);
+ return z_fetch_url($newurl,$binary,++$redirects,$opts);
}
}
@@ -128,14 +135,15 @@ function z_fetch_url($url, $binary = false, $redirects = 0, $opts = array()) {
if(x($opts,'debug')) {
$ret['debug'] = $curl_info;
}
-
+
@curl_close($ch);
return($ret);
}
/**
- * @function z_post_url
+ * @brief
+ *
* @param string $url
* URL to post
* @param mixed $params
@@ -150,17 +158,15 @@ function z_fetch_url($url, $binary = false, $redirects = 0, $opts = array()) {
* 'timeout' => int seconds, default system config value or 60 seconds
* 'http_auth' => username:password
* 'novalidate' => do not validate SSL certs, default is to validate using our CA list
- *
- * @returns array
- * 'return_code' => HTTP return code or 0 if timeout or failure
- * 'success' => boolean true (if HTTP 2xx result) or false
- * 'header' => HTTP headers
- * 'body' => fetched content
+ * @return array an assoziative array with:
+ * * \e int \b return_code => HTTP return code or 0 if timeout or failure
+ * * \e boolean \b success => boolean true (if HTTP 2xx result) or false
+ * * \e string \b header => HTTP headers
+ * * \e string \b body => content
+ * * \e string \b debug => from curl_info()
*/
-
-
function z_post_url($url,$params, $redirects = 0, $opts = array()) {
-
+
$ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => "");
$ch = curl_init($url);
@@ -182,6 +188,9 @@ function z_post_url($url,$params, $redirects = 0, $opts = array()) {
if(x($opts,'headers'))
@curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
+ if(x($opts,'nobody'))
+ @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
+
if(x($opts,'timeout') && intval($opts['timeout'])) {
@curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
}
@@ -239,7 +248,7 @@ function z_post_url($url,$params, $redirects = 0, $opts = array()) {
if($http_code == 303) {
return z_fetch_url($newurl,false,$redirects++,$opts);
} else {
- return z_post_url($newurl,$params,$redirects++,$opts);
+ return z_post_url($newurl,$params,++$redirects,$opts);
}
}
}
@@ -253,24 +262,35 @@ function z_post_url($url,$params, $redirects = 0, $opts = array()) {
logger('z_post_url: debug: ' . print_r($curl_info,true), LOGGER_DATA);
}
- $ret['body'] = substr($s,strlen($header));
+ $ret['body'] = substr($s, strlen($header));
$ret['header'] = $header;
if(x($opts,'debug')) {
$ret['debug'] = $curl_info;
}
-
curl_close($ch);
return($ret);
}
+/**
+ * @brief Like z_post_url() but with an application/json HTTP header.
+ *
+ * Add a "Content-Type: application/json" HTTP-header to $opts and call z_post_url().
+ *
+ * @see z_post_url()
+ *
+ * @param string $url
+ * @param array $params
+ * @param number $redirects default 0
+ * @param array $opts (optional) curl options
+ * @return z_post_url()
+ */
+function z_post_url_json($url, $params, $redirects = 0, $opts = array()) {
-function z_post_url_json($url,$params,$redirects = 0, $opts = array()) {
+ $opts = array_merge($opts, array('headers' => array('Content-Type: application/json')));
- $opts = array_merge($opts,array('headers' => array('Content-Type: application/json')));
return z_post_url($url,json_encode($params),$redirects,$opts);
-
}
@@ -301,22 +321,19 @@ function xml_status($st, $message = '') {
}
/**
- * @function http_status_exit
- *
- * Send HTTP status header and exit
+ * @brief Send HTTP status header and exit.
+ *
* @param int $val
* integer HTTP status result value
* @param string $msg
* optional message
* @returns (does not return, process is terminated)
*/
+function http_status_exit($val, $msg = '') {
-function http_status_exit($val,$msg = '') {
-
- $err = '';
- if($val >= 400)
+ if ($val >= 400)
$msg = (($msg) ? $msg : 'Error');
- if($val >= 200 && $val < 300)
+ if ($val >= 200 && $val < 300)
$msg = (($msg) ? $msg : 'OK');
logger('http_status_exit ' . $val . ' ' . $msg);
@@ -511,6 +528,7 @@ function allowed_email($email) {
function avatar_img($email) {
+ $avatar = array();
$a = get_app();
$avatar['size'] = 175;
@@ -520,10 +538,11 @@ function avatar_img($email) {
call_hooks('avatar_lookup', $avatar);
- if(! $avatar['success'])
+ if (! $avatar['success'])
$avatar['url'] = $a->get_baseurl() . '/' . get_default_profile_photo();
logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
+
return $avatar['url'];
}
@@ -1530,7 +1549,7 @@ function service_plink($contact, $guid) {
$m = parse_url($contact['xchan_url']);
if($m) {
- $url = $scheme . '://' . $m['host'] . (($m['port']) ? ':' . $m['port'] : '');
+ $url = $m['scheme'] . '://' . $m['host'] . (($m['port']) ? ':' . $m['port'] : '');
}
else
$url = 'https://' . substr($contact['xchan_addr'],strpos($contact['xchan_addr'],'@')+1);
diff --git a/include/notifier.php b/include/notifier.php
index 174df7120..4ea1ffe35 100644
--- a/include/notifier.php
+++ b/include/notifier.php
@@ -100,10 +100,14 @@ function notifier_run($argv, $argc){
// Get the recipient
$r = q("select abook.*, hubloc.* from abook
left join hubloc on hubloc_hash = abook_xchan
- where abook_id = %d and not ( abook_flags & %d )>0 limit 1",
+ where abook_id = %d and not ( abook_flags & %d ) > 0
+ and not (hubloc_flags & %d) > 0 and not (hubloc_status & %d) > 0 limit 1",
intval($item_id),
- intval(ABOOK_FLAG_SELF)
+ intval(ABOOK_FLAG_SELF),
+ intval(HUBLOC_FLAGS_DELETED),
+ intval(HUBLOC_OFFLINE)
);
+
if($r) {
// Get the sender
$s = q("select * from channel left join xchan on channel_hash = xchan_hash where channel_id = %d limit 1",
@@ -116,8 +120,11 @@ function notifier_run($argv, $argc){
}
else {
// send a refresh message to each hub they have registered here
- $h = q("select * from hubloc where hubloc_hash = '%s'",
- dbesc($r[0]['hubloc_hash'])
+ $h = q("select * from hubloc where hubloc_hash = '%s'
+ and not (hubloc_flags & %d) > 0 and not (hubloc_status & %d) > 0",
+ dbesc($r[0]['hubloc_hash']),
+ intval(HUBLOC_FLAGS_DELETED),
+ intval(HUBLOC_OFFLINE)
);
if($h) {
foreach($h as $hh) {
@@ -128,17 +135,31 @@ function notifier_run($argv, $argc){
));
if($data) {
$result = zot_zot($hh['hubloc_callback'],$data);
-// zot_queue_item is not yet written
-// if(! $result['success'])
-// zot_queue_item();
+ // if immediate delivery failed, stick it in the queue to try again later.
+
+ if(! $result['success']) {
+ $hash = random_string();
+ q("insert into outq ( outq_hash, outq_account, outq_channel, outq_driver, outq_posturl, outq_async, outq_created, outq_updated, outq_notify, outq_msg )
+ values ( '%s', %d, %d, '%s', '%s', %d, '%s', '%s', '%s', '%s' )",
+ dbesc($hash),
+ intval($s[0]['channel_account_id']),
+ intval($s[0]['channel_id']),
+ dbesc('zot'),
+ dbesc($hh['hubloc_callback']),
+ intval(1),
+ dbesc(datetime_convert()),
+ dbesc(datetime_convert()),
+ dbesc($data),
+ dbesc('')
+ );
+ }
}
}
}
}
}
}
-
return;
}
@@ -313,9 +334,12 @@ function notifier_run($argv, $argc){
$r = fetch_post_tags($r);
$target_item = $r[0];
+ $deleted_item = false;
if(intval($target_item['item_deleted']))
logger('notifier: target item ITEM_DELETED', LOGGER_DEBUG);
+ $deleted_item = true;
+ }
if(intval($target_item['item_type']) != ITEM_TYPE_POST) {
logger('notifier: target item not forwardable: type ' . $target_item['item_type'], LOGGER_DEBUG);
@@ -364,7 +388,16 @@ function notifier_run($argv, $argc){
$encoded_item = encode_item($target_item);
- $relay_to_owner = (((! $top_level_post) && (intval($target_item['item_origin']))) ? true : false);
+ // Send comments to the owner to re-deliver to everybody in the conversation
+ // We only do this if the item in question originated on this site. This prevents looping.
+ // To clarify, a site accepting a new comment is responsible for sending it to the owner for relay.
+ // Relaying should never be initiated on a post that arrived from elsewhere.
+
+ // We should normally be able to rely on ITEM_ORIGIN, but start_delivery_chain() incorrectly set this
+ // flag on comments for an extended period. So we'll also call comment_local_origin() which looks at
+ // the hostname in the message_id and provides a second (fallback) opinion.
+
+ $relay_to_owner = (((! $top_level_post) && (intval($target_item['item_origin'])) && comment_local_origin($target_item)) ? true : false);
$uplink = false;
@@ -476,6 +509,9 @@ function notifier_run($argv, $argc){
logger('notifier: hub choice: ' . intval($relay_to_owner) . ' ' . intval($private) . ' ' . $cmd, LOGGER_DEBUG);
+ // FIXME: I think we need to remove the private bit or this clause will never execute. Needs more coffee to think it through.
+ // We may in fact have to send it to clones in case the one we pick recently died.
+
if($relay_to_owner && (! $private) && ($cmd !== 'relay')) {
// If sending a followup to the post owner, only send it to one channel clone - to avoid race conditions.
diff --git a/include/notify.php b/include/notify.php
index 987ca8c0f..2b032b56b 100644
--- a/include/notify.php
+++ b/include/notify.php
@@ -29,7 +29,7 @@ function format_notification($item) {
'url' => $item['author']['xchan_url'],
'photo' => $item['author']['xchan_photo_s'],
'when' => relative_date($item['created']),
- 'class' => (($item['item_unseen']) ? 'notify-unseen' : 'notify-seen'),
+ 'class' => (intval($item['item_unseen']) ? 'notify-unseen' : 'notify-seen'),
'message' => strip_tags(bbcode($itemem_text))
);
diff --git a/include/oembed.php b/include/oembed.php
index 38c433e99..0628afaa9 100755
--- a/include/oembed.php
+++ b/include/oembed.php
@@ -8,13 +8,25 @@ function oembed_replacecb($matches){
}
+// if the url is embeddable with oembed, return the bbcode link.
+
+function oembed_process($url) {
+ $j = oembed_fetch_url($url);
+ logger('oembed_process: ' . print_r($j,true));
+ if($j && $j->type !== 'error')
+ return '[embed]' . $url . '[/embed]';
+ return false;
+}
+
+
+
function oembed_fetch_url($embedurl){
$a = get_app();
$txt = Cache::get($a->videowidth . $embedurl);
- if(strstr($txt,'youtu')) {
+ if(strstr($txt,'youtu') && strstr(z_root(),'https:')) {
$txt = str_replace('http:','https:',$txt);
}
@@ -105,7 +117,7 @@ function oembed_format_object($j){
$th=120; $tw = $th*$tr;
$tpl=get_markup_template('oembed_video.tpl');
- if(strstr($embedurl,'youtu')) {
+ if(strstr($embedurl,'youtu') && strstr(z_root(),'https:')) {
$embedurl = str_replace('http:','https:',$embedurl);
$j->thumbnail_url = str_replace('http:','https:', $j->thumbnail_url);
$jhtml = str_replace('http:','https:', $jhtml);
@@ -142,7 +154,7 @@ function oembed_format_object($j){
// add link to source if not present in "rich" type
if ( $j->type!='rich' || !strpos($j->html,$embedurl) ){
$embedlink = (isset($j->title))?$j->title:$embedurl;
- $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
+ $ret .= '<span class="bookmark-identifier">#^</span>' . "<a href='$embedurl' rel='oembed'>$embedlink</a>";
$ret .= "<br>";
if (isset($j->author_name)) $ret.=" by ".$j->author_name;
if (isset($j->provider_name)) $ret.=" on ".$j->provider_name;
diff --git a/include/onepoll.php b/include/onepoll.php
index ee90fbdb1..66b000934 100644
--- a/include/onepoll.php
+++ b/include/onepoll.php
@@ -125,7 +125,7 @@ function onepoll_run($argv, $argc){
if(($x) && ($x['success'])) {
$total = 0;
- logger('onepoll: feed update ' . $contact['xchan_name']);
+ logger('onepoll: feed update ' . $contact['xchan_name'] . ' ' . $feedurl);
$j = json_decode($x['body'],true);
if($j['success'] && $j['messages']) {
diff --git a/include/permissions.php b/include/permissions.php
index ccbde1a7c..68ff2b3d4 100644
--- a/include/permissions.php
+++ b/include/permissions.php
@@ -1,6 +1,6 @@
<?php
/**
- * @file incldue/permissions.php
+ * @file include/permissions.php
*
* This file conntains functions to check and work with permissions.
*/
@@ -422,12 +422,12 @@ function site_default_perms() {
'post_wall' => PERMS_SPECIFIC,
'post_comments' => PERMS_SPECIFIC,
'post_mail' => PERMS_SPECIFIC,
- 'post_photos' => 0,
+ 'post_photos' => PERMS_SPECIFIC,
'tag_deliver' => PERMS_SPECIFIC,
'chat' => PERMS_SPECIFIC,
- 'write_storage' => 0,
- 'write_pages' => 0,
- 'delegate' => 0,
+ 'write_storage' => PERMS_SPECIFIC,
+ 'write_pages' => PERMS_SPECIFIC,
+ 'delegate' => PERMS_SPECIFIC,
'post_like' => PERMS_NETWORK
);
@@ -445,21 +445,21 @@ function site_default_perms() {
/**
- * @function get_role_perms($role)
- * @param string $role
- *
- * Given a string for the channel role ('social','forum', etc)
+ * @brief Return an array of all permissions for this role.
+ *
+ * Given a string for the channel role ('social','forum', etc)
* return an array of all permission fields pre-filled for this role.
* This includes the channel permission scope indicators (anything beginning with 'channel_') as well as
- * perms_auto: true or false to create auto-permissions for this channel
- * perms_follow: The permissions to apply when initiating a connection request to another channel
- * perms_accept: The permissions to apply when accepting a connection request from another channel (not automatic)
- * default_collection: true or false to make the default ACL include the channel's default collection
- * directory_publish: true or false to publish this channel in the directory
+ * * perms_auto: true or false to create auto-permissions for this channel
+ * * perms_follow: The permissions to apply when initiating a connection request to another channel
+ * * perms_accept: The permissions to apply when accepting a connection request from another channel (not automatic)
+ * * default_collection: true or false to make the default ACL include the channel's default collection
+ * * directory_publish: true or false to publish this channel in the directory
* Any attributes may be extended (new roles defined) and modified (specific permissions altered) by plugins
*
+ * @param string $role
+ * @return array
*/
-
function get_role_perms($role) {
$ret = array();
@@ -487,13 +487,13 @@ function get_role_perms($role) {
$ret['channel_w_tagwall'] = PERMS_SPECIFIC;
$ret['channel_w_comment'] = PERMS_SPECIFIC;
$ret['channel_w_mail'] = PERMS_SPECIFIC;
- $ret['channel_w_photos'] = 0;
+ $ret['channel_w_photos'] = PERMS_SPECIFIC;
$ret['channel_w_chat'] = PERMS_SPECIFIC;
- $ret['channel_a_delegate'] = 0;
+ $ret['channel_a_delegate'] = PERMS_SPECIFIC;
$ret['channel_r_storage'] = PERMS_PUBLIC;
- $ret['channel_w_storage'] = 0;
+ $ret['channel_w_storage'] = PERMS_SPECIFIC;
$ret['channel_r_pages'] = PERMS_PUBLIC;
- $ret['channel_w_pages'] = 0;
+ $ret['channel_w_pages'] = PERMS_SPECIFIC;
$ret['channel_a_republish'] = PERMS_SPECIFIC;
$ret['channel_w_like'] = PERMS_NETWORK;
@@ -519,13 +519,13 @@ function get_role_perms($role) {
$ret['channel_w_tagwall'] = PERMS_SPECIFIC;
$ret['channel_w_comment'] = PERMS_SPECIFIC;
$ret['channel_w_mail'] = PERMS_SPECIFIC;
- $ret['channel_w_photos'] = 0;
+ $ret['channel_w_photos'] = PERMS_SPECIFIC;
$ret['channel_w_chat'] = PERMS_SPECIFIC;
- $ret['channel_a_delegate'] = 0;
+ $ret['channel_a_delegate'] = PERMS_SPECIFIC;
$ret['channel_r_storage'] = PERMS_PUBLIC;
- $ret['channel_w_storage'] = 0;
+ $ret['channel_w_storage'] = PERMS_SPECIFIC;
$ret['channel_r_pages'] = PERMS_PUBLIC;
- $ret['channel_w_pages'] = 0;
+ $ret['channel_w_pages'] = PERMS_SPECIFIC;
$ret['channel_a_republish'] = PERMS_SPECIFIC;
$ret['channel_w_like'] = PERMS_SPECIFIC;
@@ -551,13 +551,13 @@ function get_role_perms($role) {
$ret['channel_w_tagwall'] = PERMS_SPECIFIC;
$ret['channel_w_comment'] = PERMS_SPECIFIC;
$ret['channel_w_mail'] = PERMS_SPECIFIC;
- $ret['channel_w_photos'] = 0;
+ $ret['channel_w_photos'] = PERMS_SPECIFIC;
$ret['channel_w_chat'] = PERMS_SPECIFIC;
- $ret['channel_a_delegate'] = 0;
+ $ret['channel_a_delegate'] = PERMS_SPECIFIC;
$ret['channel_r_storage'] = PERMS_PUBLIC;
- $ret['channel_w_storage'] = 0;
+ $ret['channel_w_storage'] = PERMS_SPECIFIC;
$ret['channel_r_pages'] = PERMS_PUBLIC;
- $ret['channel_w_pages'] = 0;
+ $ret['channel_w_pages'] = PERMS_SPECIFIC;
$ret['channel_a_republish'] = PERMS_SPECIFIC;
$ret['channel_w_like'] = PERMS_SPECIFIC;
@@ -578,18 +578,18 @@ function get_role_perms($role) {
$ret['channel_r_profile'] = PERMS_PUBLIC;
$ret['channel_r_photos'] = PERMS_PUBLIC;
$ret['channel_r_abook'] = PERMS_PUBLIC;
- $ret['channel_w_stream'] = 0;
+ $ret['channel_w_stream'] = PERMS_SPECIFIC;
$ret['channel_w_wall'] = PERMS_SPECIFIC;
$ret['channel_w_tagwall'] = PERMS_SPECIFIC;
$ret['channel_w_comment'] = PERMS_SPECIFIC;
$ret['channel_w_mail'] = PERMS_SPECIFIC;
- $ret['channel_w_photos'] = 0;
+ $ret['channel_w_photos'] = PERMS_SPECIFIC;
$ret['channel_w_chat'] = PERMS_SPECIFIC;
- $ret['channel_a_delegate'] = 0;
+ $ret['channel_a_delegate'] = PERMS_SPECIFIC;
$ret['channel_r_storage'] = PERMS_PUBLIC;
- $ret['channel_w_storage'] = 0;
+ $ret['channel_w_storage'] = PERMS_SPECIFIC;
$ret['channel_r_pages'] = PERMS_PUBLIC;
- $ret['channel_w_pages'] = 0;
+ $ret['channel_w_pages'] = PERMS_SPECIFIC;
$ret['channel_a_republish'] = PERMS_SPECIFIC;
$ret['channel_w_like'] = PERMS_NETWORK;
@@ -610,18 +610,18 @@ function get_role_perms($role) {
$ret['channel_r_profile'] = PERMS_PUBLIC;
$ret['channel_r_photos'] = PERMS_PUBLIC;
$ret['channel_r_abook'] = PERMS_PUBLIC;
- $ret['channel_w_stream'] = 0;
+ $ret['channel_w_stream'] = PERMS_SPECIFIC;
$ret['channel_w_wall'] = PERMS_SPECIFIC;
$ret['channel_w_tagwall'] = PERMS_SPECIFIC;
$ret['channel_w_comment'] = PERMS_SPECIFIC;
$ret['channel_w_mail'] = PERMS_SPECIFIC;
- $ret['channel_w_photos'] = 0;
+ $ret['channel_w_photos'] = PERMS_SPECIFIC;
$ret['channel_w_chat'] = PERMS_SPECIFIC;
- $ret['channel_a_delegate'] = 0;
+ $ret['channel_a_delegate'] = PERMS_SPECIFIC;
$ret['channel_r_storage'] = PERMS_PUBLIC;
- $ret['channel_w_storage'] = 0;
+ $ret['channel_w_storage'] = PERMS_SPECIFIC;
$ret['channel_r_pages'] = PERMS_PUBLIC;
- $ret['channel_w_pages'] = 0;
+ $ret['channel_w_pages'] = PERMS_SPECIFIC;
$ret['channel_a_republish'] = PERMS_SPECIFIC;
$ret['channel_w_like'] = PERMS_SPECIFIC;
@@ -642,18 +642,18 @@ function get_role_perms($role) {
$ret['channel_r_profile'] = PERMS_SPECIFIC;
$ret['channel_r_photos'] = PERMS_SPECIFIC;
$ret['channel_r_abook'] = PERMS_SPECIFIC;
- $ret['channel_w_stream'] = 0;
+ $ret['channel_w_stream'] = PERMS_SPECIFIC;
$ret['channel_w_wall'] = PERMS_SPECIFIC;
- $ret['channel_w_tagwall'] = 0;
+ $ret['channel_w_tagwall'] = PERMS_SPECIFIC;
$ret['channel_w_comment'] = PERMS_SPECIFIC;
$ret['channel_w_mail'] = PERMS_SPECIFIC;
- $ret['channel_w_photos'] = 0;
+ $ret['channel_w_photos'] = PERMS_SPECIFIC;
$ret['channel_w_chat'] = PERMS_SPECIFIC;
- $ret['channel_a_delegate'] = 0;
+ $ret['channel_a_delegate'] = PERMS_SPECIFIC;
$ret['channel_r_storage'] = PERMS_SPECIFIC;
- $ret['channel_w_storage'] = 0;
+ $ret['channel_w_storage'] = PERMS_SPECIFIC;
$ret['channel_r_pages'] = PERMS_SPECIFIC;
- $ret['channel_w_pages'] = 0;
+ $ret['channel_w_pages'] = PERMS_SPECIFIC;
$ret['channel_a_republish'] = PERMS_SPECIFIC;
$ret['channel_w_like'] = PERMS_SPECIFIC;
@@ -679,13 +679,13 @@ function get_role_perms($role) {
$ret['channel_w_tagwall'] = PERMS_SPECIFIC;
$ret['channel_w_comment'] = PERMS_SPECIFIC;
$ret['channel_w_mail'] = PERMS_SPECIFIC;
- $ret['channel_w_photos'] = 0;
+ $ret['channel_w_photos'] = PERMS_SPECIFIC;
$ret['channel_w_chat'] = PERMS_SPECIFIC;
- $ret['channel_a_delegate'] = 0;
+ $ret['channel_a_delegate'] = PERMS_SPECIFIC;
$ret['channel_r_storage'] = PERMS_PUBLIC;
- $ret['channel_w_storage'] = 0;
+ $ret['channel_w_storage'] = PERMS_SPECIFIC;
$ret['channel_r_pages'] = PERMS_PUBLIC;
- $ret['channel_w_pages'] = 0;
+ $ret['channel_w_pages'] = PERMS_SPECIFIC;
$ret['channel_a_republish'] = PERMS_NETWORK;
$ret['channel_w_like'] = PERMS_NETWORK;
@@ -711,13 +711,13 @@ function get_role_perms($role) {
$ret['channel_w_tagwall'] = PERMS_SPECIFIC;
$ret['channel_w_comment'] = PERMS_SPECIFIC;
$ret['channel_w_mail'] = PERMS_SPECIFIC;
- $ret['channel_w_photos'] = 0;
+ $ret['channel_w_photos'] = PERMS_SPECIFIC;
$ret['channel_w_chat'] = PERMS_SPECIFIC;
- $ret['channel_a_delegate'] = 0;
+ $ret['channel_a_delegate'] = PERMS_SPECIFIC;
$ret['channel_r_storage'] = PERMS_PUBLIC;
- $ret['channel_w_storage'] = 0;
+ $ret['channel_w_storage'] = PERMS_SPECIFIC;
$ret['channel_r_pages'] = PERMS_PUBLIC;
- $ret['channel_w_pages'] = 0;
+ $ret['channel_w_pages'] = PERMS_SPECIFIC;
$ret['channel_a_republish'] = PERMS_SPECIFIC;
$ret['channel_w_like'] = PERMS_NETWORK;
@@ -736,18 +736,18 @@ function get_role_perms($role) {
$ret['channel_r_profile'] = PERMS_PUBLIC;
$ret['channel_r_photos'] = PERMS_PUBLIC;
$ret['channel_r_abook'] = PERMS_PUBLIC;
- $ret['channel_w_stream'] = 0;
- $ret['channel_w_wall'] = 0;
- $ret['channel_w_tagwall'] = 0;
- $ret['channel_w_comment'] = 0;
- $ret['channel_w_mail'] = 0;
- $ret['channel_w_photos'] = 0;
- $ret['channel_w_chat'] = 0;
- $ret['channel_a_delegate'] = 0;
+ $ret['channel_w_stream'] = PERMS_SPECIFIC;
+ $ret['channel_w_wall'] = PERMS_SPECIFIC;
+ $ret['channel_w_tagwall'] = PERMS_SPECIFIC;
+ $ret['channel_w_comment'] = PERMS_SPECIFIC;
+ $ret['channel_w_mail'] = PERMS_SPECIFIC;
+ $ret['channel_w_photos'] = PERMS_SPECIFIC;
+ $ret['channel_w_chat'] = PERMS_SPECIFIC;
+ $ret['channel_a_delegate'] = PERMS_SPECIFIC;
$ret['channel_r_storage'] = PERMS_PUBLIC;
- $ret['channel_w_storage'] = 0;
+ $ret['channel_w_storage'] = PERMS_SPECIFIC;
$ret['channel_r_pages'] = PERMS_PUBLIC;
- $ret['channel_w_pages'] = 0;
+ $ret['channel_w_pages'] = PERMS_SPECIFIC;
$ret['channel_a_republish'] = PERMS_SPECIFIC;
$ret['channel_w_like'] = PERMS_NETWORK;
@@ -775,7 +775,7 @@ function get_role_perms($role) {
$ret['channel_w_mail'] = PERMS_SPECIFIC;
$ret['channel_w_photos'] = PERMS_SPECIFIC;
$ret['channel_w_chat'] = PERMS_SPECIFIC;
- $ret['channel_a_delegate'] = 0;
+ $ret['channel_a_delegate'] = PERMS_SPECIFIC;
$ret['channel_r_storage'] = PERMS_PUBLIC;
$ret['channel_w_storage'] = PERMS_SPECIFIC;
$ret['channel_r_pages'] = PERMS_PUBLIC;
@@ -800,9 +800,8 @@ function get_role_perms($role) {
}
/**
- * @brief Returns a list or roles, grouped by type
+ * @brief Returns a list or roles, grouped by type.
*
- * @param string $current The current role
* @return string Returns an array of roles, grouped by type
*/
function get_roles() {
@@ -811,7 +810,8 @@ function get_roles() {
t('Community Forum') => array('forum' => t('Mostly Public'), 'forum_restricted' => t('Restricted'), 'forum_private' => t('Private')),
t('Feed Republish') => array('feed' => t('Mostly Public'), 'feed_restricted' => t('Restricted')),
t('Special Purpose') => array('soapbox' => t('Celebrity/Soapbox'), 'repository' => t('Group Repository')),
- t('Other') => array('custom' => t('Custom/Expert Mode')));
+ t('Other') => array('custom' => t('Custom/Expert Mode'))
+ );
return $roles;
}
diff --git a/include/photo/photo_driver.php b/include/photo/photo_driver.php
index e63125671..6f508bf72 100644
--- a/include/photo/photo_driver.php
+++ b/include/photo/photo_driver.php
@@ -241,9 +241,9 @@ abstract class photo_driver {
if((! function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg'))
return;
- $exif = @exif_read_data($filename);
+ $exif = @exif_read_data($filename,null,true);
if($exif) {
- $ort = $exif['Orientation'];
+ $ort = $exif['IFD0']['Orientation'];
switch($ort)
{
@@ -280,7 +280,14 @@ abstract class photo_driver {
$this->rotate(90);
break;
}
+
+ // logger('exif: ' . print_r($exif,true));
+ return $exif;
+
}
+
+ return false;
+
}
diff --git a/include/photos.php b/include/photos.php
index 43386d626..29e2f32e2 100644
--- a/include/photos.php
+++ b/include/photos.php
@@ -1,10 +1,21 @@
-<?php /** @file */
+<?php
+/**
+ * @file include/photos.php
+ * @brief Functions related to photo handling.
+ */
require_once('include/permissions.php');
require_once('include/items.php');
require_once('include/photo/photo_driver.php');
-
+/**
+ * @brief
+ *
+ * @param array $channel
+ * @param array $observer
+ * @param array $args
+ * @return array
+ */
function photo_upload($channel, $observer, $args) {
$ret = array('success' => false);
@@ -18,12 +29,12 @@ function photo_upload($channel, $observer, $args) {
call_hooks('photo_upload_begin', $args);
- /**
+ /*
* Determine the album to use
*/
- $album = $args['album'];
- $newalbum = $args['newalbum'];
+ $album = $args['album'];
+ $newalbum = $args['newalbum'];
logger('photo_upload: album= ' . $album . ' newalbum= ' . $newalbum , LOGGER_DEBUG);
@@ -31,39 +42,20 @@ function photo_upload($channel, $observer, $args) {
if($newalbum)
$album = $newalbum;
else
- $album = datetime_convert('UTC',date_default_timezone_get(),'now', 'Y');
+ $album = datetime_convert('UTC',date_default_timezone_get(),'now', 'Y-m');
}
- /**
- *
- * We create a wall item for every photo, but we don't want to
- * overwhelm the data stream with a hundred newly uploaded photos.
- * So we will make the first photo uploaded to this album in the last several hours
- * visible by default, the rest will become visible over time when and if
- * they acquire comments, likes, dislikes, and/or tags
- *
- */
-
- $r = q("SELECT * FROM photo WHERE album = '%s' AND uid = %d AND created > %s - INTERVAL %s ",
- dbesc($album),
- intval($channel_id),
- db_utcnow(), db_quoteinterval('3 HOUR')
- );
- if((! $r) || ($album == t('Profile Photos')))
+ if(intval($args['visible']) || $args['visible'] === 'true')
$visible = 1;
else
$visible = 0;
-
- if(intval($args['not_visible']) || $args['not_visible'] === 'true')
- $visible = 0;
$str_group_allow = perms2str(((is_array($args['group_allow'])) ? $args['group_allow'] : explode(',',$args['group_allow'])));
$str_contact_allow = perms2str(((is_array($args['contact_allow'])) ? $args['contact_allow'] : explode(',',$args['contact_allow'])));
$str_group_deny = perms2str(((is_array($args['group_deny'])) ? $args['group_deny'] : explode(',',$args['group_deny'])));
$str_contact_deny = perms2str(((is_array($args['contact_deny'])) ? $args['contact_deny'] : explode(',',$args['contact_deny'])));
-
- if($args['data']) {
+ if ($args['data']) {
// allow an import from a binary string representing the image.
// This bypasses the upload step and max size limit checking
@@ -74,23 +66,21 @@ function photo_upload($channel, $observer, $args) {
// this is going to be deleted if it exists
$src = '/tmp/deletemenow';
$type = $args['type'];
- }
- else {
+ } else {
$f = array('src' => '', 'filename' => '', 'filesize' => 0, 'type' => '');
call_hooks('photo_upload_file',$f);
- if(x($f,'src') && x($f,'filesize')) {
+ if (x($f,'src') && x($f,'filesize')) {
$src = $f['src'];
$filename = $f['filename'];
$filesize = $f['filesize'];
$type = $f['type'];
- }
- else {
- $src = $_FILES['userfile']['tmp_name'];
- $filename = basename($_FILES['userfile']['name']);
- $filesize = intval($_FILES['userfile']['size']);
- $type = $_FILES['userfile']['type'];
+ } else {
+ $src = $_FILES['userfile']['tmp_name'];
+ $filename = basename($_FILES['userfile']['name']);
+ $filesize = intval($_FILES['userfile']['size']);
+ $type = $_FILES['userfile']['type'];
}
if (! $type)
@@ -98,17 +88,16 @@ function photo_upload($channel, $observer, $args) {
logger('photo_upload: received file: ' . $filename . ' as ' . $src . ' ('. $type . ') ' . $filesize . ' bytes', LOGGER_DEBUG);
-
$maximagesize = get_config('system','maximagesize');
- if(($maximagesize) && ($filesize > $maximagesize)) {
+ if (($maximagesize) && ($filesize > $maximagesize)) {
$ret['message'] = sprintf ( t('Image exceeds website size limit of %lu bytes'), $maximagesize);
@unlink($src);
call_hooks('photo_upload_end',$ret);
return $ret;
}
- if(! $filesize) {
+ if (! $filesize) {
$ret['message'] = t('Image file is empty.');
@unlink($src);
call_hooks('photo_post_end',$ret);
@@ -120,24 +109,22 @@ function photo_upload($channel, $observer, $args) {
$imagedata = @file_get_contents($src);
}
-
$r = q("select sum(size) as total from photo where aid = %d and scale = 0 ",
intval($account_id)
);
$limit = service_class_fetch($channel_id,'photo_upload_limit');
- if(($r) && ($limit !== false) && (($r[0]['total'] + strlen($imagedata)) > $limit)) {
+ if (($r) && ($limit !== false) && (($r[0]['total'] + strlen($imagedata)) > $limit)) {
$ret['message'] = upgrade_message();
@unlink($src);
call_hooks('photo_post_end',$ret);
return $ret;
}
-
$ph = photo_factory($imagedata, $type);
- if(! $ph->is_valid()) {
+ if (! $ph->is_valid()) {
$ret['message'] = t('Unable to process image');
logger('photo_upload: unable to process image');
@unlink($src);
@@ -145,13 +132,14 @@ function photo_upload($channel, $observer, $args) {
return $ret;
}
- $ph->orient($src);
+ $exif = $ph->orient($src);
+
@unlink($src);
$max_length = get_config('system','max_image_length');
- if(! $max_length)
+ if (! $max_length)
$max_length = MAX_IMAGE_LENGTH;
- if($max_length > 0)
+ if ($max_length > 0)
$ph->scaleImage($max_length);
$width = $ph->getWidth();
@@ -162,7 +150,7 @@ function photo_upload($channel, $observer, $args) {
$photo_hash = (($args['resource_id']) ? $args['resource_id'] : photo_new_resource());
$visitor = '';
- if($channel['channel_hash'] !== $observer['xchan_hash'])
+ if ($channel['channel_hash'] !== $observer['xchan_hash'])
$visitor = $observer['xchan_hash'];
$errors = false;
@@ -181,11 +169,10 @@ function photo_upload($channel, $observer, $args) {
if($args['description'])
$p['description'] = $args['description'];
-
$r1 = $ph->save($p);
if(! $r1)
$errors = true;
-
+
if(($width > 640 || $height > 640) && (! $errors)) {
$ph->scaleImage(640);
$p['scale'] = 1;
@@ -204,7 +191,6 @@ function photo_upload($channel, $observer, $args) {
$errors = true;
}
-
if($errors) {
q("delete from photo where resource_id = '%s' and uid = %d",
dbesc($photo_hash),
@@ -220,17 +206,31 @@ function photo_upload($channel, $observer, $args) {
$width_x_height = $ph->getWidth() . 'x' . $ph->getHeight();
- $basename = basename($filename);
$mid = item_message_id();
// Create item container
+
$item_hidden = (($visible) ? 0 : 1 );
+
+ $lat = $lon = null;
+
+ if($exif && $exif['GPS']) {
+ if(feature_enabled($channel_id,'photo_location')) {
+ $lat = getGps($exif['GPS']['GPSLatitude'], $exif['GPS']['GPSLatitudeRef']);
+ $lon = getGps($exif['GPS']['GPSLongitude'], $exif['GPS']['GPSLongitudeRef']);
+ }
+ }
+
+
$title = '';
$mid = item_message_id();
-
+
$arr = array();
+ if($lat && $lon)
+ $arr['coord'] = $lat . ' ' . $lon;
+
$arr['aid'] = $account_id;
$arr['uid'] = $channel_id;
$arr['mid'] = $mid;
@@ -249,12 +249,13 @@ function photo_upload($channel, $observer, $args) {
$arr['item_wall'] = 1;
$arr['item_origin'] = 1;
$arr['item_thread_top'] = 1;
+
$arr['plink'] = z_root() . '/channel/' . $channel['channel_address'] . '/?f=&mid=' . $arr['mid'];
// We should also put a width_x_height on large photos. Left as an exercise for
// devs looking fo simple stuff to fix.
- $larger = feature_enabled($channel['channel_id'],'large_photos');
+ $larger = feature_enabled($channel['channel_id'], 'large_photos');
if($larger) {
$tag = '[zmg]';
if($r2)
@@ -269,11 +270,10 @@ function photo_upload($channel, $observer, $args) {
$tag = '[zmg]';
}
+ $arr['body'] = '[zrl=' . z_root() . '/photos/' . $channel['channel_address'] . '/image/' . $photo_hash . ']'
+ . $tag . z_root() . "/photo/{$photo_hash}-{$smallest}.".$ph->getExt() . '[/zmg]'
+ . '[/zrl]';
- $arr['body'] = '[zrl=' . z_root() . '/photos/' . $channel['channel_address'] . '/image/' . $photo_hash . ']'
- . $tag . z_root() . "/photo/{$photo_hash}-{$smallest}.".$ph->getExt() . '[/zmg]'
- . '[/zrl]';
-
$result = item_store($arr);
$item_id = $result['item_id'];
@@ -291,18 +291,26 @@ function photo_upload($channel, $observer, $args) {
return $ret;
}
-
-
-
-function photos_albums_list($channel,$observer) {
+/**
+ * @brief Returns a list with all photo albums observer is allowed to see.
+ *
+ * Returns an associative array with all albums where observer has permissions.
+ *
+ * @param array $channel
+ * @param array $observer
+ * @return bool|array false if no view_photos permission or an array
+ * * success (bool)
+ * * albums (array)
+ */
+function photos_albums_list($channel, $observer) {
$channel_id = $channel['channel_id'];
$observer_xchan = (($observer) ? $observer['xchan_hash'] : '');
- if(! perm_is_allowed($channel_id,$observer_xchan,'view_photos'))
+ if(! perm_is_allowed($channel_id, $observer_xchan, 'view_photos'))
return false;
- // FIXME - create a permissions SQL which works on arbitrary observers and channels, regardless of login or web status
+ /** @FIXME create a permissions SQL which works on arbitrary observers and channels, regardless of login or web status */
$sql_extra = permissions_sql($channel_id);
@@ -310,7 +318,6 @@ function photos_albums_list($channel,$observer) {
intval($channel_id),
intval(PHOTO_NORMAL),
intval(PHOTO_PROFILE)
-
);
// add various encodings to the array so we can just loop through and pick them out in a template
@@ -326,12 +333,13 @@ function photos_albums_list($channel,$observer) {
'total' => $album['total'],
'url' => z_root() . '/photos/' . $channel['channel_address'] . '/album/' . bin2hex($album['album']),
'urlencode' => urlencode($album['album']),
- 'bin2hex' => bin2hex($album['album']));
+ 'bin2hex' => bin2hex($album['album'])
+ );
$ret['albums'][] = $entry;
}
}
- return $ret;
+ return $ret;
}
function photos_album_widget($channelx,$observer,$albums = null) {
@@ -359,11 +367,19 @@ function photos_album_widget($channelx,$observer,$albums = null) {
? t('Upload New Photos') : '')
));
}
+
return $o;
}
-
-function photos_list_photos($channel,$observer,$album = '') {
+/**
+ * @brief
+ *
+ * @param array $channel
+ * @param array $observer
+ * @param string $album default empty
+ * @return boolean|array
+ */
+function photos_list_photos($channel, $observer, $album = '') {
$channel_id = $channel['channel_id'];
$observer_xchan = (($observer) ? $observer['xchan_hash'] : '');
@@ -383,7 +399,7 @@ function photos_list_photos($channel,$observer,$album = '') {
intval(PHOTO_NORMAL),
intval(PHOTO_PROFILE)
);
-
+
if($r) {
for($x = 0; $x < count($r); $x ++) {
$r[$x]['src'] = z_root() . '/photo/' . $r[$x]['resource_id'] . '-' . $r[$x]['scale'];
@@ -395,17 +411,33 @@ function photos_list_photos($channel,$observer,$album = '') {
return $ret;
}
-
-
-function photos_album_exists($channel_id,$album) {
- $r = q("SELECT id from photo where album = '%s' and uid = %d limit 1",
+/**
+ * @brief Check if given photo album exists in channel.
+ *
+ * @param int $channel_id id of the channel
+ * @param string $album name of the album
+ * @return boolean
+ */
+function photos_album_exists($channel_id, $album) {
+ $r = q("SELECT id FROM photo WHERE album = '%s' AND uid = %d limit 1",
dbesc($album),
intval($channel_id)
);
+
return (($r) ? true : false);
}
-function photos_album_rename($channel_id,$oldname,$newname) {
+/**
+ * @brief Renames a photo album in a channel.
+ *
+ * @todo Do we need to check if new album name already exists?
+ *
+ * @param int $channel_id id of the channel
+ * @param string $oldname The name of the album to rename
+ * @param string $newname The new name of the album
+ * @return bool|array
+ */
+function photos_album_rename($channel_id, $oldname, $newname) {
return q("UPDATE photo SET album = '%s' WHERE album = '%s' AND uid = %d",
dbesc($newname),
dbesc($oldname),
@@ -413,43 +445,58 @@ function photos_album_rename($channel_id,$oldname,$newname) {
);
}
-
-function photos_album_get_db_idstr($channel_id,$album,$remote_xchan = '') {
-
- if($remote_xchan) {
+/**
+ * @brief
+ *
+ * @param int $channel_id
+ * @param string $album
+ * @param string $remote_xchan
+ * @return string|boolean
+ */
+function photos_album_get_db_idstr($channel_id, $album, $remote_xchan = '') {
+
+ if ($remote_xchan) {
$r = q("SELECT distinct resource_id as from photo where xchan = '%s' and uid = %d and album = '%s' ",
dbesc($remote_xchan),
intval($channel_id),
dbesc($album)
);
- }
- else {
+ } else {
$r = q("SELECT distinct resource_id from photo where uid = %d and album = '%s' ",
intval($channel_id),
dbesc($album)
);
}
- if($r) {
+ if ($r) {
$arr = array();
- foreach($r as $rr) {
+ foreach ($r as $rr) {
$arr[] = "'" . dbesc($rr['resource_id']) . "'" ;
}
$str = implode(',',$arr);
return $str;
}
- return false;
+ return false;
}
+/**
+ * @brief Creates a new photo item.
+ *
+ * @param array $channel
+ * @param string $creator_hash
+ * @param array $photo
+ * @param boolean $visible default false
+ * @return int item_id
+ */
function photos_create_item($channel, $creator_hash, $photo, $visible = false) {
// Create item container
+
$item_hidden = (($visible) ? 0 : 1 );
- $title = '';
$mid = item_message_id();
-
+
$arr = array();
$arr['aid'] = $channel['channel_account_id'];
@@ -475,9 +522,34 @@ function photos_create_item($channel, $creator_hash, $photo, $visible = false) {
$arr['body'] = '[zrl=' . z_root() . '/photos/' . $channel['channel_address'] . '/image/' . $photo['resource_id'] . ']'
. '[zmg]' . z_root() . '/photo/' . $photo['resource_id'] . '-' . $photo['scale'] . '[/zmg]'
. '[/zrl]';
-
+
$result = item_store($arr);
$item_id = $result['item_id'];
+
return $item_id;
+}
+
+
+function getGps($exifCoord, $hemi) {
+
+ $degrees = count($exifCoord) > 0 ? gps2Num($exifCoord[0]) : 0;
+ $minutes = count($exifCoord) > 1 ? gps2Num($exifCoord[1]) : 0;
+ $seconds = count($exifCoord) > 2 ? gps2Num($exifCoord[2]) : 0;
+
+ $flip = ($hemi == 'W' or $hemi == 'S') ? -1 : 1;
+
+ return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
+}
+
+function gps2Num($coordPart) {
+
+ $parts = explode('/', $coordPart);
+
+ if (count($parts) <= 0)
+ return 0;
+
+ if (count($parts) == 1)
+ return $parts[0];
+ return floatval($parts[0]) / floatval($parts[1]);
}
diff --git a/include/plugin.php b/include/plugin.php
index 08decc8e3..4d8405b62 100755
--- a/include/plugin.php
+++ b/include/plugin.php
@@ -7,13 +7,12 @@
require_once("include/smarty.php");
+
/**
* @brief unloads an addon.
*
* @param string $plugin name of the addon
- * @return void
*/
-
function unload_plugin($plugin){
logger("Addons: unloading " . $plugin, LOGGER_DEBUG);
@@ -28,9 +27,8 @@ function unload_plugin($plugin){
* @brief uninstalls an addon.
*
* @param string $plugin name of the addon
- * @return bool
+ * @return boolean
*/
-
function uninstall_plugin($plugin) {
unload_plugin($plugin);
@@ -38,7 +36,7 @@ function uninstall_plugin($plugin) {
return false;
logger("Addons: uninstalling " . $plugin);
- $t = @filemtime('addon/' . $plugin . '/' . $plugin . '.php');
+ //$t = @filemtime('addon/' . $plugin . '/' . $plugin . '.php');
@include_once('addon/' . $plugin . '/' . $plugin . '.php');
if(function_exists($plugin . '_uninstall')) {
$func = $plugin . '_uninstall';
@@ -68,9 +66,9 @@ function install_plugin($plugin) {
$func();
}
- $plugin_admin = (function_exists($plugin . "_plugin_admin") ? 1 : 0);
+ $plugin_admin = (function_exists($plugin . '_plugin_admin') ? 1 : 0);
- $r = q("INSERT INTO `addon` (`name`, `installed`, `timestamp`, `plugin_admin`) VALUES ( '%s', 1, %d , %d ) ",
+ q("INSERT INTO `addon` (`name`, `installed`, `timestamp`, `plugin_admin`) VALUES ( '%s', 1, %d , %d ) ",
dbesc($plugin),
intval($t),
$plugin_admin
@@ -91,7 +89,7 @@ function load_plugin($plugin) {
return false;
logger("Addons: loading " . $plugin, LOGGER_DEBUG);
- $t = @filemtime('addon/' . $plugin . '/' . $plugin . '.php');
+ //$t = @filemtime('addon/' . $plugin . '/' . $plugin . '.php');
@include_once('addon/' . $plugin . '/' . $plugin . '.php');
if(function_exists($plugin . '_load')) {
$func = $plugin . '_load';
@@ -120,6 +118,7 @@ function plugin_is_installed($name) {
);
if($r)
return true;
+
return false;
}
@@ -189,12 +188,13 @@ function register_hook($hook, $file, $function, $priority = 0) {
if(count($r))
return true;
- $r = q("INSERT INTO `hook` (`hook`, `file`, `function`, `priority`) VALUES ( '%s', '%s', '%s', '%s' ) ",
+ $r = q("INSERT INTO `hook` (`hook`, `file`, `function`, `priority`) VALUES ( '%s', '%s', '%s', '%s' )",
dbesc($hook),
dbesc($file),
dbesc($function),
dbesc($priority)
);
+
return $r;
}
@@ -205,7 +205,7 @@ function register_hook($hook, $file, $function, $priority = 0) {
* @param string $hook the name of the hook
* @param string $file the name of the file that hooks into
* @param string $function the name of the function that the hook called
- * @return mixed
+ * @return array
*/
function unregister_hook($hook, $file, $function) {
$r = q("DELETE FROM hook WHERE hook = '%s' AND `file` = '%s' AND `function` = '%s'",
@@ -213,6 +213,7 @@ function unregister_hook($hook, $file, $function) {
dbesc($file),
dbesc($function)
);
+
return $r;
}
@@ -228,11 +229,13 @@ function load_hooks() {
$a = get_app();
// if(! is_array($a->hooks))
$a->hooks = array();
+
$r = q("SELECT * FROM hook WHERE true ORDER BY priority DESC");
if($r) {
foreach($r as $rr) {
if(! array_key_exists($rr['hook'],$a->hooks))
$a->hooks[$rr['hook']] = array();
+
$a->hooks[$rr['hook']][] = array($rr['file'],$rr['function']);
}
}
@@ -240,8 +243,7 @@ function load_hooks() {
}
/**
- *
- * @function insert_hook($hook,$fn)
+ * @brief Inserts a hook into a page request.
*
* Insert a short-lived hook into the running page request.
* Hooks are normally persistent so that they can be called
@@ -252,36 +254,45 @@ function load_hooks() {
* which will not persist beyond the life of this page request
* or the current process.
*
- * @param string $hook;
+ * @param string $hook
* name of hook to attach callback
- * @param string $fn;
+ * @param string $fn
* function name of callback handler
- *
*/
-function insert_hook($hook,$fn) {
+function insert_hook($hook, $fn) {
$a = get_app();
if(! is_array($a->hooks))
$a->hooks = array();
- if(! array_key_exists($hook,$a->hooks))
+
+ if(! array_key_exists($hook, $a->hooks))
$a->hooks[$hook] = array();
- $a->hooks[$hook][] = array('',$fn);
-}
+ $a->hooks[$hook][] = array('', $fn);
+}
+/**
+ * @brief Calls a hook.
+ *
+ * Use this function when you want to be able to allow a hook to manipulate
+ * the provided data.
+ *
+ * @param string $name of the hook to call
+ * @param string|array &$data to transmit to the callback handler
+ */
function call_hooks($name, &$data = null) {
$a = get_app();
- if((is_array($a->hooks)) && (array_key_exists($name,$a->hooks))) {
+ if((is_array($a->hooks)) && (array_key_exists($name, $a->hooks))) {
foreach($a->hooks[$name] as $hook) {
if($hook[0])
@include_once($hook[0]);
+
if(function_exists($hook[1])) {
$func = $hook[1];
- $func($a,$data);
- }
- else {
+ $func($a, $data);
+ } else {
// remove orphan hooks
- q("delete from hook where hook = '%s' and file = '$s' and function = '%s' limit 1",
+ q("DELETE FROM hook WHERE hook = '%s' AND file = '%s' AND function = '%s'",
dbesc($name),
dbesc($hook[0]),
dbesc($hook[1])
@@ -293,9 +304,10 @@ function call_hooks($name, &$data = null) {
/**
- * @brief parse plugin comment in search of plugin infos.
+ * @brief Parse plugin comment in search of plugin infos.
*
* like
+ * \code
* * Name: Plugin
* * Description: A plugin which plugs in
* * Version: 1.2.3
@@ -303,21 +315,23 @@ function call_hooks($name, &$data = null) {
* * Author: Jane <email>
* * Compat: Red [(version)], Friendica [(version)]
* *
- *
+ *\endcode
* @param string $plugin the name of the plugin
* @return array with the plugin information
*/
function get_plugin_info($plugin){
- $info = Array(
+ $m = array();
+ $info = array(
'name' => $plugin,
- 'description' => "",
+ 'description' => '',
'author' => array(),
- 'version' => "",
- 'compat' => ""
+ 'version' => '',
+ 'compat' => ''
);
- if (!is_file("addon/$plugin/$plugin.php")) return $info;
-
+ if (!is_file("addon/$plugin/$plugin.php"))
+ return $info;
+
$f = file_get_contents("addon/$plugin/$plugin.php");
$r = preg_match("|/\*.*\*/|msU", $f, $m);
@@ -328,7 +342,7 @@ function get_plugin_info($plugin){
if ($l != ""){
list($k, $v) = array_map("trim", explode(":", $l, 2));
$k = strtolower($k);
- if ($k == "author"){
+ if ($k == 'author'){
$r = preg_match("|([^<]+)<([^>]+)>|", $v, $m);
if ($r) {
$info['author'][] = array('name' => $m[1], 'link' => $m[2]);
@@ -343,14 +357,16 @@ function get_plugin_info($plugin){
}
}
}
+
return $info;
}
/**
- * @brief parse theme comment in search of theme infos.
+ * @brief Parse theme comment in search of theme infos.
*
* like
+ * \code
* * Name: My Theme
* * Description: My Cool Theme
* * Version: 1.2.3
@@ -358,18 +374,19 @@ function get_plugin_info($plugin){
* * Maintainer: Jane <profile url>
* * Compat: Friendica [(version)], Red [(version)]
* *
- *
+ * \endcode
* @param string $theme the name of the theme
* @return array
*/
function get_theme_info($theme){
- $info=Array(
+ $m = array();
+ $info = array(
'name' => $theme,
- 'description' => "",
+ 'description' => '',
'author' => array(),
- 'version' => "",
- 'compat' => "",
- 'credits' => "",
+ 'version' => '',
+ 'compat' => '',
+ 'credits' => '',
'maintainer' => array(),
'experimental' => false,
'unsupported' => false
@@ -377,10 +394,12 @@ function get_theme_info($theme){
if(file_exists("view/theme/$theme/experimental"))
$info['experimental'] = true;
+
if(file_exists("view/theme/$theme/unsupported"))
$info['unsupported'] = true;
- if (!is_file("view/theme/$theme/php/theme.php")) return $info;
+ if (!is_file("view/theme/$theme/php/theme.php"))
+ return $info;
$f = file_get_contents("view/theme/$theme/php/theme.php");
$r = preg_match("|/\*.*\*/|msU", $f, $m);
@@ -392,7 +411,7 @@ function get_theme_info($theme){
if ($l != ""){
list($k, $v) = array_map("trim", explode(":", $l, 2));
$k = strtolower($k);
- if ($k == "author"){
+ if ($k == 'author'){
$r = preg_match("|([^<]+)<([^>]+)>|", $v, $m);
if ($r) {
$info['author'][] = array('name' => $m[1], 'link' => $m[2]);
@@ -400,7 +419,7 @@ function get_theme_info($theme){
$info['author'][] = array('name' => $v);
}
}
- elseif ($k == "maintainer"){
+ elseif ($k == 'maintainer'){
$r = preg_match("|([^<]+)<([^>]+)>|", $v, $m);
if ($r) {
$info['maintainer'][] = array('name' => $m[1], 'link' => $m[2]);
@@ -415,10 +434,18 @@ function get_theme_info($theme){
}
}
}
+
return $info;
}
-
+/**
+ * @brief Returns the theme's screenshot.
+ *
+ * The screenshot is expected as view/theme/$theme/img/screenshot.[png|jpg].
+ *
+ * @param sring $theme The name of the theme
+ * @return string
+ */
function get_theme_screenshot($theme) {
$a = get_app();
$exts = array('.png', '.jpg');
@@ -426,16 +453,15 @@ function get_theme_screenshot($theme) {
if(file_exists('view/theme/' . $theme . '/img/screenshot' . $ext))
return($a->get_baseurl() . '/view/theme/' . $theme . '/img/screenshot' . $ext);
}
+
return($a->get_baseurl() . '/images/blank.png');
}
-
/**
- * @brief add CSS to <head>
+ * @brief add CSS to \<head\>
*
* @param string $src
* @param string $media change media attribute (default to 'screen')
- * @return void
*/
function head_add_css($src, $media = 'screen') {
get_app()->css_sources[] = array($src, $media);
@@ -444,21 +470,23 @@ function head_add_css($src, $media = 'screen') {
function head_remove_css($src, $media = 'screen') {
$a = get_app();
$index = array_search(array($src, $media), $a->css_sources);
- if($index !== false)
+ if ($index !== false)
unset($a->css_sources[$index]);
}
function head_get_css() {
$str = '';
$sources = get_app()->css_sources;
- if(count($sources))
- foreach($sources as $source)
+ if (count($sources)) {
+ foreach ($sources as $source)
$str .= format_css_if_exists($source);
+ }
+
return $str;
}
function format_css_if_exists($source) {
- if(strpos($source[0],'/') !== false)
+ if (strpos($source[0], '/') !== false)
$path = $source[0];
else
$path = theme_include($source[0]);
@@ -565,6 +593,7 @@ function theme_include($file, $root = '') {
if(file_exists($p))
return $p;
}
+
return '';
}
diff --git a/include/poller.php b/include/poller.php
index 2756ca1c6..a175d59b5 100644
--- a/include/poller.php
+++ b/include/poller.php
@@ -41,6 +41,12 @@ function poller_run($argv, $argc){
// run queue delivery process in the background
proc_run('php',"include/queue.php");
+
+
+ // maintenance for mod sharedwithme - check for updated items and remove them
+
+ require_once('include/sharedwithme.php');
+ apply_updates();
// expire any expired mail
@@ -81,11 +87,13 @@ function poller_run($argv, $argc){
}
// publish any applicable items that were set to be published in the future
- // (time travel posts)
+ // (time travel posts). Restrict to items that have come of age in the last
+ // couple of days to limit the query to something reasonable.
- $r = q("select id from item where ( item_restrict & %d ) > 0 and created <= %s ",
+ $r = q("select id from item where ( item_restrict & %d ) > 0 and created <= %s and created > '%s' ",
intval(ITEM_DELAYED_PUBLISH),
- db_utcnow()
+ db_utcnow(),
+ dbesc(datetime_convert('UTC','UTC','now - 2 days'))
);
if($r) {
foreach($r as $rr) {
@@ -149,6 +157,7 @@ function poller_run($argv, $argc){
call_hooks('cron_weekly',datetime_convert());
+ z_check_cert();
require_once('include/hubloc.php');
prune_hub_reinstalls();
@@ -164,8 +173,8 @@ function poller_run($argv, $argc){
);
$dirmode = intval(get_config('system','directory_mode'));
- if($dirmode == DIRECTORY_MODE_SECONDARY) {
- logger('regdir: ' . print_r(z_fetch_url(get_directory_primary() . '/regdir?f=&url=' . z_root() . '&realm=' . get_directory_realm()),true));
+ if($dirmode === DIRECTORY_MODE_SECONDARY || $dirmode === DIRECTORY_MODE_PRIMARY) {
+ logger('regdir: ' . print_r(z_fetch_url(get_directory_primary() . '/regdir?f=&url=' . urlencode(z_root()) . '&realm=' . urlencode(get_directory_realm())),true));
}
/**
diff --git a/include/queue.php b/include/queue.php
index b6a540ef9..7d2ad3b2d 100644
--- a/include/queue.php
+++ b/include/queue.php
@@ -39,12 +39,25 @@ function queue_run($argv, $argc){
// so that we don't start off a thousand deliveries for a couple of dead hubs.
// The zot driver will deliver everything destined for a single hub once contact is made (*if* contact is made).
// Other drivers will have to do something different here and may need their own query.
+
+ // Note: this requires some tweaking as new posts to long dead hubs once a day will keep them in the
+ // "every 15 minutes" category. We probably need to prioritise them when inserted into the queue
+ // or just prior to this query based on recent and long-term delivery history. If we have good reason to believe
+ // the site is permanently down, there's no reason to attempt delivery at all, or at most not more than once
+ // or twice a day.
+
+ // FIXME: can we sort postgres on outq_priority and maintain the 'distinct' ?
+ // The order by max(outq_priority) might be a dodgy query because of the group by.
+ // The desired result is to return a sequence in the order most likely to be delivered in this run.
+ // If a hub has already been sitting in the queue for a few days, they should be delivered last;
+ // hence every failure should drop them further down the priority list.
+
if(ACTIVE_DBTYPE == DBTYPE_POSTGRES) {
$prefix = 'DISTINCT ON (outq_posturl)';
$suffix = 'ORDER BY outq_posturl';
} else {
$prefix = '';
- $suffix = 'GROUP BY outq_posturl';
+ $suffix = 'GROUP BY outq_posturl ORDER BY max(outq_priority)';
}
$r = q("SELECT $prefix * FROM outq WHERE outq_delivered = 0 and (( outq_created > %s - INTERVAL %s and outq_updated < %s - INTERVAL %s ) OR ( outq_updated < %s - INTERVAL %s )) $suffix",
db_utcnow(), db_quoteinterval('12 HOUR'),
@@ -69,7 +82,7 @@ function queue_run($argv, $argc){
}
else {
logger('queue: queue post returned ' . $result['return_code'] . ' from ' . $rr['outq_posturl'],LOGGER_DEBUG);
- $y = q("update outq set outq_updated = '%s' where outq_hash = '%s'",
+ $y = q("update outq set outq_updated = '%s', outq_priority = outq_priority + 10 where outq_hash = '%s'",
dbesc(datetime_convert()),
dbesc($rr['outq_hash'])
);
@@ -78,11 +91,13 @@ function queue_run($argv, $argc){
}
$result = zot_zot($rr['outq_posturl'],$rr['outq_notify']);
if($result['success']) {
+ logger('queue: deliver zot success to ' . $rr['outq_posturl'], LOGGER_DEBUG);
zot_process_response($rr['outq_posturl'],$result, $rr);
}
else {
$deadguys[] = $rr['outq_posturl'];
- $y = q("update outq set outq_updated = '%s' where outq_hash = '%s'",
+ logger('queue: deliver zot returned ' . $result['return_code'] . ' from ' . $rr['outq_posturl'],LOGGER_DEBUG);
+ $y = q("update outq set outq_updated = '%s', outq_priority = outq_priority + 10 where outq_hash = '%s'",
dbesc(datetime_convert()),
dbesc($rr['outq_hash'])
);
diff --git a/include/ratenotif.php b/include/ratenotif.php
index 4fa0077a6..63fd7c2ee 100644
--- a/include/ratenotif.php
+++ b/include/ratenotif.php
@@ -76,8 +76,8 @@ function ratenotif_run($argv, $argc){
if($j && $j['success'] && is_array($j['directories'])) {
foreach($j['directories'] as $h) {
-// if($h == z_root())
-// continue;
+ if($h == z_root())
+ continue;
$hash = random_string();
$n = zot_build_packet($channel,'notify',null,null,$hash);
@@ -94,21 +94,21 @@ function ratenotif_run($argv, $argc){
dbesc($n),
dbesc(json_encode($encoded_item))
);
- }
- $deliver[] = $hash;
- if(count($deliver) >= $deliveries_per_process) {
- proc_run('php','include/deliver.php',$deliver);
- $deliver = array();
- if($interval)
- @time_sleep_until(microtime(true) + (float) $interval);
- }
+ $deliver[] = $hash;
+ if(count($deliver) >= $deliveries_per_process) {
+ proc_run('php','include/deliver.php',$deliver);
+ $deliver = array();
+ if($interval)
+ @time_sleep_until(microtime(true) + (float) $interval);
+ }
+ }
// catch any stragglers
if(count($deliver)) {
- proc_run('php','include/deliver.php',$deliver);
+ proc_run('php','include/deliver.php',$deliver);
}
}
}
diff --git a/include/security.php b/include/security.php
index 216299099..c3b0e9763 100644
--- a/include/security.php
+++ b/include/security.php
@@ -22,7 +22,7 @@ function authenticate_success($user_record, $login_initial = false, $interactive
$a->account = $user_record;
$_SESSION['account_id'] = $user_record['account_id'];
$_SESSION['authenticated'] = 1;
-
+
if($login_initial || $update_lastlog) {
q("update account set account_lastlog = '%s' where account_id = %d",
dbesc(datetime_convert()),
@@ -150,11 +150,7 @@ function change_channel($change_channel) {
*/
function permissions_sql($owner_id, $remote_verified = false, $groups = null) {
- if(defined('STATUSNET_PRIVACY_COMPATIBILITY'))
- return '';
-
$local_channel = local_channel();
- $remote_channel = remote_channel();
/**
* Construct permissions
@@ -173,7 +169,7 @@ function permissions_sql($owner_id, $remote_verified = false, $groups = null) {
*/
if(($local_channel) && ($local_channel == $owner_id)) {
- $sql = '';
+ $sql = '';
}
/**
@@ -194,7 +190,7 @@ function permissions_sql($owner_id, $remote_verified = false, $groups = null) {
if(is_array($groups) && count($groups)) {
foreach($groups as $g)
$gs .= '|<' . $g . '>';
- }
+ }
$regexop = db_getfunc('REGEXP');
$sql = sprintf(
" AND ( NOT (deny_cid like '%s' OR deny_gid $regexop '%s')
@@ -223,11 +219,7 @@ function permissions_sql($owner_id, $remote_verified = false, $groups = null) {
*/
function item_permissions_sql($owner_id, $remote_verified = false, $groups = null) {
- if(defined('STATUSNET_PRIVACY_COMPATIBILITY'))
- return '';
-
$local_channel = local_channel();
- $remote_channel = remote_channel();
/**
* Construct permissions
@@ -246,7 +238,7 @@ function item_permissions_sql($owner_id, $remote_verified = false, $groups = nul
}
/**
- * Authenticated visitor. Unless pre-verified,
+ * Authenticated visitor. Unless pre-verified,
* check that the contact belongs to this $owner_id
* and load the groups the visitor belongs to.
* If pre-verified, the caller is expected to have already
@@ -330,7 +322,7 @@ function public_permissions_sql($observer_hash) {
*/
function get_form_security_token($typename = '') {
$a = get_app();
-
+
$timestamp = time();
$sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $timestamp . $typename);
@@ -340,16 +332,16 @@ function get_form_security_token($typename = '') {
function check_form_security_token($typename = '', $formname = 'form_security_token') {
if (!x($_REQUEST, $formname)) return false;
$hash = $_REQUEST[$formname];
-
+
$max_livetime = 10800; // 3 hours
-
+
$a = get_app();
-
+
$x = explode('.', $hash);
if (time() > (IntVal($x[0]) + $max_livetime)) return false;
-
+
$sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $x[0] . $typename);
-
+
return ($sec_hash == $x[1]);
}
@@ -404,20 +396,22 @@ function init_groups_visitor($contact_id) {
// will likely be too expensive.
// Returns a string list of comma separated channel_ids suitable for direct inclusion in a SQL query
-function stream_perms_api_uids($perms = NULL ) {
+function stream_perms_api_uids($perms = NULL, $limit = 0, $rand = 0 ) {
$perms = is_null($perms) ? (PERMS_SITE|PERMS_NETWORK|PERMS_PUBLIC) : $perms;
$ret = array();
+ $limit_sql = (($limit) ? " LIMIT " . intval($limit) . " " : '');
+ $random_sql = (($rand) ? " ORDER BY " . db_getfunc('RAND') . " " : '');
if(local_channel())
$ret[] = local_channel();
- $r = q("select channel_id from channel where channel_r_stream > 0 and (channel_r_stream & %d)>0 and not (channel_pageflags & %d)>0",
+ $r = q("select channel_id from channel where channel_r_stream > 0 and ( channel_r_stream & %d )>0 and ( channel_pageflags & %d ) = 0 $random_sql $limit_sql ",
intval($perms),
intval(PAGE_ADULT|PAGE_CENSORED|PAGE_SYSTEM|PAGE_REMOVED)
);
if($r) {
foreach($r as $rr)
if(! in_array($rr['channel_id'], $ret))
- $ret[] = $rr['channel_id'];
+ $ret[] = $rr['channel_id'];
}
$str = '';
@@ -425,7 +419,7 @@ function stream_perms_api_uids($perms = NULL ) {
foreach($ret as $rr) {
if($str)
$str .= ',';
- $str .= intval($rr);
+ $str .= intval($rr);
}
}
logger('stream_perms_api_uids: ' . $str, LOGGER_DEBUG);
@@ -447,7 +441,7 @@ function stream_perms_xchans($perms = NULL ) {
if($r) {
foreach($r as $rr)
if(! in_array($rr['channel_hash'], $ret))
- $ret[] = $rr['channel_hash'];
+ $ret[] = $rr['channel_hash'];
}
$str = '';
@@ -455,7 +449,7 @@ function stream_perms_xchans($perms = NULL ) {
foreach($ret as $rr) {
if($str)
$str .= ',';
- $str .= "'" . dbesc($rr) . "'";
+ $str .= "'" . dbesc($rr) . "'";
}
}
logger('stream_perms_xchans: ' . $str, LOGGER_DEBUG);
diff --git a/include/session.php b/include/session.php
index ed4dfdd16..31b3f0614 100644
--- a/include/session.php
+++ b/include/session.php
@@ -1,24 +1,29 @@
-<?php /** @file */
-
-// Session management functions. These provide database storage of PHP
-// session info.
+<?php
+/**
+ * @file include/session.php
+ *
+ * @brief This file includes session related functions.
+ *
+ * Session management functions. These provide database storage of PHP
+ * session info.
+ */
$session_exists = 0;
$session_expire = 180000;
-
-
-
function new_cookie($time) {
- $old_sid = session_id();
+ $old_sid = session_id();
// ??? This shouldn't have any effect if called after session_start()
// We probably need to set the session expiration and change the PHPSESSID cookie.
- session_set_cookie_params($time);
- session_regenerate_id(false);
+ session_set_cookie_params($time);
+ session_regenerate_id(false);
- q("UPDATE session SET sid = '%s' WHERE sid = '%s'", dbesc(session_id()), dbesc($old_sid));
+ q("UPDATE session SET sid = '%s' WHERE sid = '%s'",
+ dbesc(session_id()),
+ dbesc($old_sid)
+ );
if (x($_COOKIE, 'jsAvailable')) {
if ($time) {
@@ -31,62 +36,72 @@ function new_cookie($time) {
}
-function ref_session_open ($s,$n) {
- return true;
+function ref_session_open ($s, $n) {
+ return true;
}
function ref_session_read ($id) {
- global $session_exists;
- if(x($id))
- $r = q("SELECT `data` FROM `session` WHERE `sid`= '%s'", dbesc($id));
- if(count($r)) {
- $session_exists = true;
- return $r[0]['data'];
- }
- return '';
+ global $session_exists;
+ if(x($id))
+ $r = q("SELECT `data` FROM `session` WHERE `sid`= '%s'", dbesc($id));
+
+ if(count($r)) {
+ $session_exists = true;
+ return $r[0]['data'];
+ }
+
+ return '';
}
-function ref_session_write ($id,$data) {
- global $session_exists, $session_expire;
- if(! $id || ! $data) {
- return false;
- }
+function ref_session_write ($id, $data) {
+ global $session_exists, $session_expire;
- $expire = time() + $session_expire;
- $default_expire = time() + 300;
+ if(! $id || ! $data) {
+ return false;
+ }
- if($session_exists)
- $r = q("UPDATE `session`
- SET `data` = '%s', `expire` = '%s'
- WHERE `sid` = '%s'",
- dbesc($data), dbesc($expire), dbesc($id));
- else
- $r = q("INSERT INTO `session` (sid, expire, data) values ('%s', '%s', '%s')",
- //SET `sid` = '%s', `expire` = '%s', `data` = '%s'",
- dbesc($id), dbesc($default_expire), dbesc($data));
+ $expire = time() + $session_expire;
+ $default_expire = time() + 300;
+
+ if($session_exists) {
+ q("UPDATE `session`
+ SET `data` = '%s', `expire` = '%s' WHERE `sid` = '%s'",
+ dbesc($data),
+ dbesc($expire),
+ dbesc($id)
+ );
+ } else {
+ q("INSERT INTO `session` (sid, expire, data) values ('%s', '%s', '%s')",
+ //SET `sid` = '%s', `expire` = '%s', `data` = '%s'",
+ dbesc($id),
+ dbesc($default_expire),
+ dbesc($data)
+ );
+ }
- return true;
+ return true;
}
function ref_session_close() {
- return true;
+ return true;
}
function ref_session_destroy ($id) {
- q("DELETE FROM `session` WHERE `sid` = '%s'", dbesc($id));
- return true;
+ q("DELETE FROM `session` WHERE `sid` = '%s'", dbesc($id));
+ return true;
}
function ref_session_gc($expire) {
- q("DELETE FROM session WHERE expire < %d", dbesc(time()));
- if (! get_config('system','innodb'))
- db_optimizetable('session');
- return true;
+ q("DELETE FROM session WHERE expire < %d", dbesc(time()));
+ if (! get_config('system', 'innodb'))
+ db_optimizetable('session');
+
+ return true;
}
$gc_probability = 50;
@@ -95,5 +110,14 @@ ini_set('session.gc_probability', $gc_probability);
ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_httponly', 1);
-
-session_set_save_handler ('ref_session_open', 'ref_session_close', 'ref_session_read', 'ref_session_write', 'ref_session_destroy', 'ref_session_gc');
+/*
+ * PHP function which sets our user-level session storage functions.
+ */
+session_set_save_handler(
+ 'ref_session_open',
+ 'ref_session_close',
+ 'ref_session_read',
+ 'ref_session_write',
+ 'ref_session_destroy',
+ 'ref_session_gc'
+); \ No newline at end of file
diff --git a/include/sharedwithme.php b/include/sharedwithme.php
new file mode 100644
index 000000000..b01764ad3
--- /dev/null
+++ b/include/sharedwithme.php
@@ -0,0 +1,32 @@
+<?php
+
+function apply_updates() {
+
+ //check for updated items and remove them
+ $x = q("SELECT mid, max(object) AS object FROM item WHERE verb = '%s' AND obj_type = '%s' GROUP BY mid",
+ dbesc(ACTIVITY_UPDATE),
+ dbesc(ACTIVITY_OBJ_FILE)
+ );
+
+ if($x) {
+
+ foreach($x as $xx) {
+
+ $object = json_decode($xx['object'],true);
+
+ $d_mid = $object['d_mid'];
+ $u_mid = $xx['mid'];
+
+ $y = q("DELETE FROM item WHERE obj_type = '%s' AND (verb = '%s' AND mid = '%s') OR (verb = '%s' AND mid = '%s')",
+ dbesc(ACTIVITY_OBJ_FILE),
+ dbesc(ACTIVITY_POST),
+ dbesc($d_mid),
+ dbesc(ACTIVITY_UPDATE),
+ dbesc($u_mid)
+ );
+
+ }
+
+ }
+
+}
diff --git a/include/socgraph.php b/include/socgraph.php
index 3b135267d..d8e2e1958 100644
--- a/include/socgraph.php
+++ b/include/socgraph.php
@@ -3,7 +3,7 @@
require_once('include/dir_fns.php');
require_once('include/zot.php');
-/*
+/**
* poco_load
*
* xchan is your connection
@@ -21,13 +21,10 @@ require_once('include/zot.php');
* the given uid, cid to the global contact entry. There can be many uid/cid combinations
* pointing to the same global contact id.
*
+ * @param string $xchan
+ * @param string $url
*/
-
-
-
-
-function poco_load($xchan = '',$url = null) {
- $a = get_app();
+function poco_load($xchan = '', $url = null) {
if($xchan && ! $url) {
$r = q("select xchan_connurl from xchan where xchan_hash = '%s' limit 1",
@@ -43,7 +40,6 @@ function poco_load($xchan = '',$url = null) {
return;
}
-
$url = $url . '?f=&fields=displayName,hash,urls,photos,rating' ;
logger('poco_load: ' . $url, LOGGER_DEBUG);
@@ -148,7 +144,7 @@ function poco_load($xchan = '',$url = null) {
logger('poco_load: missing data');
continue;
}
-
+
$x = q("select xchan_hash from xchan where xchan_hash = '%s' limit 1",
dbesc($hash)
);
@@ -182,7 +178,7 @@ function poco_load($xchan = '',$url = null) {
continue;
}
}
-
+
$total ++;
@@ -192,19 +188,15 @@ function poco_load($xchan = '',$url = null) {
);
if(! $r) {
- q("insert into xlink ( xlink_xchan, xlink_link, xlink_rating, xlink_rating_text, xlink_updated, xlink_static ) values ( '%s', '%s', %d, '%s', '%s', 0 ) ",
+ q("insert into xlink ( xlink_xchan, xlink_link, xlink_updated, xlink_static ) values ( '%s', '%s', '%s', 0 ) ",
dbesc($xchan),
dbesc($hash),
- intval($rating),
- dbesc($rating_text),
dbesc(datetime_convert())
);
}
else {
- q("update xlink set xlink_updated = '%s', xlink_rating = %d, xlink_rating_text = '%s' where xlink_id = %d",
+ q("update xlink set xlink_updated = '%s' where xlink_id = %d",
dbesc(datetime_convert()),
- intval($rating),
- dbesc($rating_text),
intval($r[0]['xlink_id'])
);
}
@@ -216,7 +208,6 @@ function poco_load($xchan = '',$url = null) {
db_utcnow(), db_quoteinterval('2 DAY')
);
-
}
@@ -253,7 +244,6 @@ function common_friends($uid,$xchan,$start = 0,$limit=100000000,$shuffle = false
);
return $r;
-
}
@@ -269,8 +259,8 @@ function count_common_friends_zcid($uid,$zcid) {
if(count($r))
return $r[0]['total'];
- return 0;
+ return 0;
}
function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
@@ -292,7 +282,6 @@ function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = fal
);
return $r;
-
}
@@ -307,8 +296,8 @@ function count_all_friends($uid,$cid) {
if(count($r))
return $r[0]['total'];
- return 0;
+ return 0;
}
@@ -377,9 +366,7 @@ function suggestion_query($uid, $myxchan, $start = 0, $limit = 80) {
function update_suggestions() {
- $a = get_app();
-
- $dirmode = get_config('system','directory_mode');
+ $dirmode = get_config('system', 'directory_mode');
if($dirmode === false)
$dirmode = DIRECTORY_MODE_NORMAL;
@@ -393,8 +380,6 @@ function update_suggestions() {
if(! $url)
return;
-
-
$ret = z_fetch_url($url);
if($ret['success']) {
@@ -407,7 +392,6 @@ function update_suggestions() {
db_utcnow(), db_quoteinterval('7 DAY')
);
-
$j = json_decode($ret['body'],true);
if($j && $j['success']) {
foreach($j['entries'] as $host) {
@@ -441,7 +425,6 @@ function poco($a,$extended = false) {
$system_mode = true;
}
-
$format = (($_REQUEST['format']) ? $_REQUEST['format'] : 'json');
$justme = false;
@@ -456,7 +439,7 @@ function poco($a,$extended = false) {
}
if(argc() > 4 && intval(argv(4)) && $justme == false)
$cid = intval(argv(4));
-
+
if(! $system_mode) {
$r = q("SELECT channel_id from channel where channel_address = '%s' limit 1",
@@ -506,8 +489,8 @@ function poco($a,$extended = false) {
$startIndex = intval($_GET['startIndex']);
if(! $startIndex)
$startIndex = 0;
- $itemsPerPage = ((x($_GET,'count') && intval($_GET['count'])) ? intval($_GET['count']) : $totalResults);
+ $itemsPerPage = ((x($_GET,'count') && intval($_GET['count'])) ? intval($_GET['count']) : $totalResults);
if($system_mode) {
$r = q("SELECT abook.*, xchan.* from abook left join xchan on abook_xchan = xchan_hash where ( abook_flags & " . ABOOK_FLAG_SELF .
@@ -515,8 +498,7 @@ function poco($a,$extended = false) {
intval($itemsPerPage),
intval($startIndex)
);
- }
- else {
+ } else {
$r = q("SELECT abook.*, xchan.* from abook left join xchan on abook_xchan = xchan_hash where abook_channel = %d
$sql_extra LIMIT %d OFFSET %d",
intval($channel_id),
@@ -544,8 +526,7 @@ function poco($a,$extended = false) {
}
}
- $ret['entry'] = array();
-
+ $ret['entry'] = array();
$fields_ret = array(
'id' => false,
@@ -559,10 +540,10 @@ function poco($a,$extended = false) {
'rating' => false
);
- if((! x($_GET,'fields')) || ($_GET['fields'] === '@all'))
+ if((! x($_GET,'fields')) || ($_GET['fields'] === '@all')) {
foreach($fields_ret as $k => $v)
$fields_ret[$k] = true;
- else {
+ } else {
$fields_req = explode(',',$_GET['fields']);
foreach($fields_req as $f)
$fields_ret[trim($f)] = true;
diff --git a/include/taxonomy.php b/include/taxonomy.php
index 9be04e16c..ea41369ad 100644
--- a/include/taxonomy.php
+++ b/include/taxonomy.php
@@ -38,6 +38,7 @@ function term_query($table,$s,$type = TERM_UNKNOWN) {
function store_item_tag($uid,$iid,$otype,$type,$term,$url = '') {
if(! $term)
return false;
+
$r = q("select * from term
where uid = %d and oid = %d and otype = %d and type = %d
and term = '%s' and url = '%s' ",
@@ -50,6 +51,7 @@ function store_item_tag($uid,$iid,$otype,$type,$term,$url = '') {
);
if($r)
return false;
+
$r = q("insert into term (uid, oid, otype, type, term, url)
values( %d, %d, %d, %d, '%s', '%s') ",
intval($uid),
@@ -59,9 +61,11 @@ function store_item_tag($uid,$iid,$otype,$type,$term,$url = '') {
dbesc($term),
dbesc($url)
);
+
return $r;
}
-
+
+
function get_terms_oftype($arr,$type) {
$ret = array();
if(! (is_array($arr) && count($arr)))
@@ -74,6 +78,7 @@ function get_terms_oftype($arr,$type) {
foreach($arr as $x)
if($x['type'] == $t)
$ret[] = $x;
+
return $ret;
}
@@ -98,7 +103,12 @@ function format_term_for_display($term) {
function tagadelic($uid, $count = 0, $authors = '', $flags = 0, $restrict = 0, $type = TERM_HASHTAG) {
- $sql_options = '';
+ require_once('include/security.php');
+
+ if(! perm_is_allowed($uid,get_observer_hash(),'view_stream'))
+ return array();
+
+ $sql_options = item_permissions_sql($uid);
$count = intval($count);
if($flags) {
@@ -109,6 +119,7 @@ function tagadelic($uid, $count = 0, $authors = '', $flags = 0, $restrict = 0, $
if($authors) {
if(! is_array($authors))
$authors = array($authors);
+
stringify_array_elms($authors,true);
$sql_options .= " and author_xchan in (" . implode(',',$authors) . ") ";
}
@@ -128,8 +139,8 @@ function tagadelic($uid, $count = 0, $authors = '', $flags = 0, $restrict = 0, $
if(! $r)
return array();
-
- // Find minimum and maximum log-count.
+
+ // Find minimum and maximum log-count.
$tags = array();
$min = 1e9;
$max = -1e9;
@@ -149,22 +160,23 @@ function tagadelic($uid, $count = 0, $authors = '', $flags = 0, $restrict = 0, $
$range = max(.01, $max - $min) * 1.0001;
for($x = 0; $x < count($tags); $x ++) {
- $tags[$x][2] = 1 + floor(5 * ($tags[$x][1] - $min) / $range);
+ $tags[$x][2] = 1 + floor(9 * ($tags[$x][1] - $min) / $range);
}
return $tags;
}
+
function tags_sort($a,$b) {
- if(strtolower($a[0]) == strtolower($b[0]))
- return 0;
- return((strtolower($a[0]) < strtolower($b[0])) ? -1 : 1);
+ if(strtolower($a[0]) == strtolower($b[0]))
+ return 0;
+
+ return((strtolower($a[0]) < strtolower($b[0])) ? -1 : 1);
}
function dir_tagadelic($count = 0) {
- $sql_options = '';
$count = intval($count);
// Fetch tags
@@ -175,8 +187,8 @@ function dir_tagadelic($count = 0) {
if(! $r)
return array();
-
- // Find minimum and maximum log-count.
+
+ // Find minimum and maximum log-count.
$tags = array();
$min = 1e9;
$max = -1e9;
@@ -196,7 +208,7 @@ function dir_tagadelic($count = 0) {
$range = max(.01, $max - $min) * 1.0001;
for($x = 0; $x < count($tags); $x ++) {
- $tags[$x][2] = 1 + floor(5 * ($tags[$x][1] - $min) / $range);
+ $tags[$x][2] = 1 + floor(9 * ($tags[$x][1] - $min) / $range);
}
return $tags;
@@ -204,65 +216,71 @@ function dir_tagadelic($count = 0) {
function tagblock($link,$uid,$count = 0,$authors = '',$flags = 0,$restrict = 0,$type = TERM_HASHTAG) {
- $o = '';
- $tab = 0;
- $r = tagadelic($uid,$count,$authors,$flags,$restrict,$type);
-
- if($r) {
- $o = '<div class="tagblock widget"><h3>' . t('Tags') . '</h3><div class="tags" align="center">';
- foreach($r as $rr) {
- $o .= '<span class="tag'.$rr[2].'">#</span><a href="'.$link .'/' . '?f=&tag=' . urlencode($rr[0]).'" class="tag'.$rr[2].'">'.$rr[0].'</a> ' . "\r\n";
+ $o = '';
+
+ $r = tagadelic($uid,$count,$authors,$flags,$restrict,$type);
+
+ if($r) {
+ $o = '<div class="tagblock widget"><h3>' . t('Tags') . '</h3><div class="tags" align="center">';
+ foreach($r as $rr) {
+ $o .= '<span class="tag'.$rr[2].'">#</span><a href="'.$link .'/' . '?f=&tag=' . urlencode($rr[0]).'" class="tag'.$rr[2].'">'.$rr[0].'</a> ' . "\r\n";
+ }
+ $o .= '</div></div>';
}
- $o .= '</div></div>';
- }
+
return $o;
}
+
function wtagblock($uid,$count = 0,$authors = '',$flags = 0,$restrict = 0,$type = TERM_HASHTAG) {
- $o = '';
- $tab = 0;
- $r = tagadelic($uid,$count,$authors,$flags,$restrict,$type);
+ $o = '';
- if($r) {
- $c = q("select channel_address from channel where channel_id = %d limit 1",
- intval($uid)
- );
+ $r = tagadelic($uid,$count,$authors,$flags,$restrict,$type);
- $o = '<div class="tagblock widget"><h3>' . t('Tags') . '</h3><div class="tags" align="center">';
- foreach($r as $rr) {
- $o .= '<span class="tag' . $rr[2] . '">#</span><a href="channel/' . $c[0]['channel_address'] . '?f=&tag=' . urlencode($rr[0]).'" class="tag'.$rr[2].'">'.$rr[0].'</a> ' . "\r\n";
+ if($r) {
+ $c = q("select channel_address from channel where channel_id = %d limit 1",
+ intval($uid)
+ );
+
+ $o = '<div class="tagblock widget"><h3>' . t('Tags') . '</h3><div class="tags" align="center">';
+ foreach($r as $rr) {
+ $o .= '<span class="tag' . $rr[2] . '">#</span><a href="channel/' . $c[0]['channel_address'] . '?f=&tag=' . urlencode($rr[0]).'" class="tag'.$rr[2].'">'.$rr[0].'</a> ' . "\r\n";
+ }
+ $o .= '</div></div>';
}
- $o .= '</div></div>';
- }
+
return $o;
}
function catblock($uid,$count = 0,$authors = '',$flags = 0,$restrict = 0,$type = TERM_CATEGORY) {
- $o = '';
- $tab = 0;
-
- $r = tagadelic($uid,$count,$authors,$flags,$restrict,$type);
+ $o = '';
- if($r) {
- $c = q("select channel_address from channel where channel_id = %d limit 1",
- intval($uid)
- );
+ $r = tagadelic($uid,$count,$authors,$flags,$restrict,$type);
- $o = '<div class="tagblock widget"><h3>' . t('Categories') . '</h3><div class="tags" align="center">';
- foreach($r as $rr) {
- $o .= '<a href="channel/' . $c[0]['channel_address']. '?f=&cat=' . urlencode($rr[0]).'" class="tag'.$rr[2].'">'.$rr[0].'</a> ' . "\r\n";
+ if($r) {
+ $c = q("select channel_address from channel where channel_id = %d limit 1",
+ intval($uid)
+ );
+
+ $o = '<div class="tagblock widget"><h3>' . t('Categories') . '</h3><div class="tags" align="center">';
+ foreach($r as $rr) {
+ $o .= '<a href="channel/' . $c[0]['channel_address']. '?f=&cat=' . urlencode($rr[0]).'" class="tag'.$rr[2].'">'.$rr[0].'</a> ' . "\r\n";
+ }
+ $o .= '</div></div>';
}
- $o .= '</div></div>';
- }
+
return $o;
}
-
function dir_tagblock($link,$r) {
$o = '';
- $tab = 0;
+
+ $observer = get_observer_hash();
+ if(! get_globaldir_setting($observer))
+ return $o;
+
if(! $r)
$r = get_app()->data['directory_keywords'];
@@ -274,14 +292,12 @@ function dir_tagblock($link,$r) {
}
$o .= '</div></div>';
}
+
return $o;
}
-
-
-
/**
* verbs: [0] = first person singular, e.g. "I want", [1] = 3rd person singular, e.g. "Bill wants"
* We use the first person form when creating an activity, but the third person for use in activities
@@ -289,8 +305,6 @@ function dir_tagblock($link,$r) {
* require obj_verbs() to provide full conjugations and specify which form to use in the $_REQUEST params to this module.
*/
-
-
function obj_verbs() {
$verbs = array(
'has' => array( t('have'), t('has')),
@@ -301,26 +315,27 @@ function obj_verbs() {
$arr = array('verbs' => $verbs);
call_hooks('obj_verbs', $arr);
+
return $arr['verbs'];
}
function obj_verb_selector($current = '') {
$verbs = obj_verbs();
- $o .= '<select class="obj-verb-selector" name="verb" >';
+ $o = '<select class="obj-verb-selector" name="verb">';
foreach($verbs as $k => $v) {
$selected = (($k == $current) ? ' selected="selected" ' : '');
$o .= '<option value="' . urlencode($k) . '"' . $selected . '>' . $v[1] . '</option>';
}
$o .= '</select>';
- return $o;
+ return $o;
}
function get_things($profile_hash,$uid) {
$sql_extra = (($profile_hash) ? " and obj_page = '" . $profile_hash . "' " : '');
-
+
$r = q("select * from obj left join term on obj_obj = term_hash where term_hash != '' and uid = %d and obj_type = %d $sql_extra order by obj_verb, term",
intval($uid),
intval(TERM_OBJ_THING)
@@ -376,11 +391,11 @@ function get_things($profile_hash,$uid) {
for($x = 0; $x < count($l); $x ++)
$l[$x]['xchan_url'] = zid($l[$x]['xchan_url']);
-
+
if(! $things[$rr['obj_verb']])
$things[$rr['obj_verb']] = array();
- $things[$rr['obj_verb']][] = array('term' => $rr['term'],'url' => $rr['url'],'img' => $rr['imgurl'], 'profile' => $rr['profile_name'],'term_hash' => $rr['term_hash'], 'likes' => $l,'like_count' => count($l),'like_label' => tt('Like','Likes',count($l),'noun'));
+ $things[$rr['obj_verb']][] = array('term' => $rr['term'],'url' => $rr['url'],'img' => $rr['imgurl'], 'profile' => $rr['profile_name'],'term_hash' => $rr['term_hash'], 'likes' => $l,'like_count' => count($l),'like_label' => tt('Like','Likes',count($l),'noun'));
}
$sorted_things = array();
if($things) {
@@ -392,6 +407,6 @@ function get_things($profile_hash,$uid) {
}
}
//logger('things: ' . print_r($sorted_things,true));
- return $sorted_things;
+ return $sorted_things;
} \ No newline at end of file
diff --git a/include/template_processor.php b/include/template_processor.php
index 74acc9c67..d2bf283e3 100755
--- a/include/template_processor.php
+++ b/include/template_processor.php
@@ -1,305 +1,307 @@
<?php
- require_once 'include/ITemplateEngine.php';
-
- define ("KEY_NOT_EXISTS", '^R_key_not_Exists^');
-
- class Template implements ITemplateEngine {
- static $name ="internal";
-
- var $r;
- var $search;
- var $replace;
- var $stack = array();
- var $nodes = array();
- var $done = false;
- var $d = false;
- var $lang = null;
- var $debug=false;
-
- private function _preg_error(){
-
- switch(preg_last_error()){
- case PREG_INTERNAL_ERROR: echo('PREG_INTERNAL_ERROR'); break;
- case PREG_BACKTRACK_LIMIT_ERROR: echo('PREG_BACKTRACK_LIMIT_ERROR'); break;
- case PREG_RECURSION_LIMIT_ERROR: echo('PREG_RECURSION_LIMIT_ERROR'); break;
- case PREG_BAD_UTF8_ERROR: echo('PREG_BAD_UTF8_ERROR'); break;
+require_once 'include/ITemplateEngine.php';
+
+define ("KEY_NOT_EXISTS", '^R_key_not_Exists^');
+
+class Template implements ITemplateEngine {
+ static $name ="internal";
+
+ var $r;
+ var $search;
+ var $replace;
+ var $stack = array();
+ var $nodes = array();
+ var $done = false;
+ var $d = false;
+ var $lang = null;
+ var $debug=false;
+
+ private function _preg_error() {
+ switch(preg_last_error()) {
+ case PREG_INTERNAL_ERROR: echo('PREG_INTERNAL_ERROR'); break;
+ case PREG_BACKTRACK_LIMIT_ERROR: echo('PREG_BACKTRACK_LIMIT_ERROR'); break;
+ case PREG_RECURSION_LIMIT_ERROR: echo('PREG_RECURSION_LIMIT_ERROR'); break;
+ case PREG_BAD_UTF8_ERROR: echo('PREG_BAD_UTF8_ERROR'); break;
// This is only valid for php > 5.3, not certain how to code around it for unit tests
-// case PREG_BAD_UTF8_OFFSET_ERROR: echo('PREG_BAD_UTF8_OFFSET_ERROR'); break;
- default:
- //die("Unknown preg error.");
- return;
- }
- echo "<hr><pre>";
- debug_print_backtrace();
- die();
+// case PREG_BAD_UTF8_OFFSET_ERROR: echo('PREG_BAD_UTF8_OFFSET_ERROR'); break;
+ default:
+ //die("Unknown preg error.");
+ return;
}
-
-
- private function _push_stack(){
- $this->stack[] = array($this->r, $this->nodes);
- }
- private function _pop_stack(){
- list($this->r, $this->nodes) = array_pop($this->stack);
-
- }
-
- private function _get_var($name, $retNoKey=false){
- $keys = array_map('trim',explode(".",$name));
- if ($retNoKey && !array_key_exists($keys[0], $this->r)) return KEY_NOT_EXISTS;
- $val = $this->r;
- foreach($keys as $k) {
- $val = (isset($val[$k]) ? $val[$k] : null);
- }
- return template_escape($val);
+ echo "<hr><pre>";
+ debug_print_backtrace();
+ die();
+ }
+
+ private function _push_stack() {
+ $this->stack[] = array($this->r, $this->nodes);
+ }
+
+ private function _pop_stack(){
+ list($this->r, $this->nodes) = array_pop($this->stack);
+ }
+
+ private function _get_var($name, $retNoKey=false) {
+ $keys = array_map('trim',explode(".",$name));
+ if ($retNoKey && !array_key_exists($keys[0], $this->r))
+ return KEY_NOT_EXISTS;
+
+ $val = $this->r;
+ foreach($keys as $k) {
+ $val = (isset($val[$k]) ? $val[$k] : null);
}
-
- /**
- * IF node
- *
- * {{ if <$var> }}...[{{ else }} ...] {{ endif }}
- * {{ if <$var>==<val|$var> }}...[{{ else }} ...]{{ endif }}
- * {{ if <$var>!=<val|$var> }}...[{{ else }} ...]{{ endif }}
- */
- private function _replcb_if($args){
- if (strpos($args[2],"==")>0){
- list($a,$b) = array_map("trim",explode("==",$args[2]));
- $a = $this->_get_var($a);
- if ($b[0]=="$") $b = $this->_get_var($b);
- $val = ($a == $b);
- } else if (strpos($args[2],"!=")>0){
- list($a,$b) = array_map("trim", explode("!=",$args[2]));
- $a = $this->_get_var($a);
- if ($b[0]=="$") $b = $this->_get_var($b);
- $val = ($a != $b);
- } else {
- $val = $this->_get_var($args[2]);
- }
- $x = preg_split("|{{ *else *}}|", $args[3]);
- return ( ($val) ? $x[0] : (isset($x[1]) ? $x[1] : ""));
+
+ return template_escape($val);
+ }
+
+ /**
+ * IF node
+ * \code
+ * {{ if <$var> }}...[{{ else }} ...] {{ endif }}
+ * {{ if <$var>==<val|$var> }}...[{{ else }} ...]{{ endif }}
+ * {{ if <$var>!=<val|$var> }}...[{{ else }} ...]{{ endif }}
+ * \endcode
+ */
+ private function _replcb_if($args) {
+ if (strpos($args[2],"==")>0){
+ list($a,$b) = array_map("trim",explode("==",$args[2]));
+ $a = $this->_get_var($a);
+ if ($b[0]=="$") $b = $this->_get_var($b);
+ $val = ($a == $b);
+ } else if (strpos($args[2],"!=")>0){
+ list($a,$b) = array_map("trim", explode("!=",$args[2]));
+ $a = $this->_get_var($a);
+ if ($b[0]=="$") $b = $this->_get_var($b);
+ $val = ($a != $b);
+ } else {
+ $val = $this->_get_var($args[2]);
}
-
- /**
- * FOR node
- *
- * {{ for <$var> as $name }}...{{ endfor }}
- * {{ for <$var> as $key=>$name }}...{{ endfor }}
- */
- private function _replcb_for($args){
- $m = array_map('trim', explode(" as ", $args[2]));
- $x = explode("=>",$m[1]);
- if (count($x) == 1) {
- $varname = $x[0];
- $keyname = "";
- } else {
- list($keyname, $varname) = $x;
- }
- if ($m[0]=="" || $varname=="" || is_null($varname)) die("template error: 'for ".$m[0]." as ".$varname."'") ;
- //$vals = $this->r[$m[0]];
- $vals = $this->_get_var($m[0]);
- $ret="";
- if (!is_array($vals)) return $ret;
- foreach ($vals as $k=>$v){
- $this->_push_stack();
- $r = $this->r;
- $r[$varname] = $v;
- if ($keyname!='') $r[$keyname] = (($k === 0) ? '0' : $k);
- $ret .= $this->replace($args[3], $r);
- $this->_pop_stack();
- }
- return $ret;
+ $x = preg_split("|{{ *else *}}|", $args[3]);
+
+ return ( ($val) ? $x[0] : (isset($x[1]) ? $x[1] : ""));
+ }
+
+ /**
+ * FOR node
+ * \code
+ * {{ for <$var> as $name }}...{{ endfor }}
+ * {{ for <$var> as $key=>$name }}...{{ endfor }}
+ * \endcode
+ */
+ private function _replcb_for($args) {
+ $m = array_map('trim', explode(" as ", $args[2]));
+ $x = explode("=>",$m[1]);
+ if (count($x) == 1) {
+ $varname = $x[0];
+ $keyname = "";
+ } else {
+ list($keyname, $varname) = $x;
}
+ if ($m[0]=="" || $varname=="" || is_null($varname)) die("template error: 'for ".$m[0]." as ".$varname."'") ;
+ //$vals = $this->r[$m[0]];
+ $vals = $this->_get_var($m[0]);
+ $ret="";
+ if (!is_array($vals)) return $ret;
- /**
- * INC node
- *
- * {{ inc <templatefile> [with $var1=$var2] }}{{ endinc }}
- */
- private function _replcb_inc($args){
- if (strpos($args[2],"with")) {
- list($tplfile, $newctx) = array_map('trim', explode("with",$args[2]));
- } else {
- $tplfile = trim($args[2]);
- $newctx = null;
- }
-
- if ($tplfile[0]=="$") $tplfile = $this->_get_var($tplfile);
-
+ foreach ($vals as $k=>$v){
$this->_push_stack();
$r = $this->r;
- if (!is_null($newctx)) {
- list($a,$b) = array_map('trim', explode("=",$newctx));
- $r[$a] = $this->_get_var($b);
- }
- $this->nodes = Array();
- $tpl = get_markup_template($tplfile);
- $ret = $this->replace($tpl, $r);
+ $r[$varname] = $v;
+ if ($keyname!='') $r[$keyname] = (($k === 0) ? '0' : $k);
+ $ret .= $this->replace($args[3], $r);
$this->_pop_stack();
- return $ret;
-
}
-
- /**
- * DEBUG node
- *
- * {{ debug $var [$var [$var [...]]] }}{{ enddebug }}
- *
- * replace node with <pre>var_dump($var, $var, ...);</pre>
- */
- private function _replcb_debug($args){
- $vars = array_map('trim', explode(" ",$args[2]));
- $vars[] = $args[1];
-
- $ret = "<pre>";
- foreach ($vars as $var){
- $ret .= htmlspecialchars(var_export( $this->_get_var($var), true ));
- $ret .= "\n";
- }
- $ret .= "</pre>";
- return $ret;
+
+ return $ret;
+ }
+
+ /**
+ * INC node
+ * \code
+ * {{ inc <templatefile> [with $var1=$var2] }}{{ endinc }}
+ * \endcode
+ */
+ private function _replcb_inc($args) {
+ if (strpos($args[2],"with")) {
+ list($tplfile, $newctx) = array_map('trim', explode("with",$args[2]));
+ } else {
+ $tplfile = trim($args[2]);
+ $newctx = null;
}
- private function _replcb_node($m) {
- $node = $this->nodes[$m[1]];
- if (method_exists($this, "_replcb_".$node[1])){
- $s = call_user_func(array($this, "_replcb_".$node[1]), $node);
- } else {
- $s = "";
- }
- $s = preg_replace_callback('/\|\|([0-9]+)\|\|/', array($this, "_replcb_node"), $s);
- return $s;
+ if ($tplfile[0]=="$") $tplfile = $this->_get_var($tplfile);
+
+ $this->_push_stack();
+ $r = $this->r;
+ if (!is_null($newctx)) {
+ list($a,$b) = array_map('trim', explode("=",$newctx));
+ $r[$a] = $this->_get_var($b);
+ }
+ $this->nodes = Array();
+ $tpl = get_markup_template($tplfile);
+ $ret = $this->replace($tpl, $r);
+ $this->_pop_stack();
+
+ return $ret;
+ }
+
+ /**
+ * DEBUG node
+ * \code
+ * {{ debug $var [$var [$var [...]]] }}{{ enddebug }}
+ * \endcode
+ * replace node with <pre>var_dump($var, $var, ...);</pre>
+ */
+ private function _replcb_debug($args) {
+ $vars = array_map('trim', explode(" ",$args[2]));
+ $vars[] = $args[1];
+
+ $ret = "<pre>";
+ foreach ($vars as $var){
+ $ret .= htmlspecialchars(var_export( $this->_get_var($var), true ));
+ $ret .= "\n";
}
-
- private function _replcb($m){
- //var_dump(array_map('htmlspecialchars', $m));
- $this->done = false;
- $this->nodes[] = (array) $m;
- return "||". (count($this->nodes)-1) ."||";
+ $ret .= "</pre>";
+
+ return $ret;
+ }
+
+ private function _replcb_node($m) {
+ $node = $this->nodes[$m[1]];
+ if (method_exists($this, "_replcb_".$node[1])){
+ $s = call_user_func(array($this, "_replcb_".$node[1]), $node);
+ } else {
+ $s = "";
}
-
- private function _build_nodes($s){
- $this->done = false;
- while (!$this->done){
- $this->done=true;
- $s = preg_replace_callback('|{{ *([a-z]*) *([^}]*)}}([^{]*({{ *else *}}[^{]*)?){{ *end\1 *}}|', array($this, "_replcb"), $s);
- if ($s==Null) $this->_preg_error();
- }
- //({{ *else *}}[^{]*)?
- krsort($this->nodes);
- return $s;
+ $s = preg_replace_callback('/\|\|([0-9]+)\|\|/', array($this, "_replcb_node"), $s);
+
+ return $s;
+ }
+
+ private function _replcb($m) {
+ //var_dump(array_map('htmlspecialchars', $m));
+ $this->done = false;
+ $this->nodes[] = (array) $m;
+
+ return "||". (count($this->nodes)-1) ."||";
+ }
+
+ private function _build_nodes($s) {
+ $this->done = false;
+ while (!$this->done) {
+ $this->done=true;
+ $s = preg_replace_callback('|{{ *([a-z]*) *([^}]*)}}([^{]*({{ *else *}}[^{]*)?){{ *end\1 *}}|', array($this, "_replcb"), $s);
+ if ($s==Null) $this->_preg_error();
}
-
-
- private function var_replace($s){
- $m = array();
- /** regexp:
- * \$ literal $
- * (\[)? optional open square bracket
- * ([a-zA-Z0-9-_]+\.?)+ var name, followed by optional
- * dot, repeated at least 1 time
- * (?(1)\]) if there was opened square bracket
- * (subgrup 1), match close bracket
- */
- if (preg_match_all('/\$(\[)?([a-zA-Z0-9-_]+\.?)+(?(1)\])/', $s,$m)){
- foreach($m[0] as $var){
-
- $exp = str_replace(array("[", "]"), array("", ""), $var);
- $exptks = explode("|", $exp);
-
- $varn = $exptks[0];
- unset($exptks[0]);
- $val = $this->_get_var($varn, true);
- if ($val != KEY_NOT_EXISTS) {
- /* run filters */
- /*
- * Filter are in form of:
- * filtername:arg:arg:arg
- *
- * "filtername" is function name
- * "arg"s are optional, var value is appended to the end
- * if one "arg"==='x' , is replaced with var value
- *
- * examples:
- * $item.body|htmlspecialchars // escape html chars
- * $item.body|htmlspecialchars|strtoupper // escape html and uppercase result
- * $item.created|date:%Y %M %j // format date (created is a timestamp)
- * $item.body|str_replace:cat:dog // replace all "cat" with "dog"
- * $item.body|str_replace:cat:dog:x:1 // replace one "cat" with "dog"
-
- */
- foreach ($exptks as $filterstr) {
- $filter = explode(":", $filterstr);
- $filtername = $filter[0];
- unset($filter[0]);
- $valkey = array_search("x", $filter);
- if ($valkey === false) {
- $filter[] = $val;
- } else {
- $filter[$valkey] = $val;
- }
- if (function_exists($filtername)) {
- $val = call_user_func_array($filtername, $filter);
- }
- }
- $s = str_replace($var, $val, $s);
+ //({{ *else *}}[^{]*)?
+ krsort($this->nodes);
+
+ return $s;
+ }
+ private function var_replace($s) {
+ $m = array();
+ /** regexp:
+ * \$ literal $
+ * (\[)? optional open square bracket
+ * ([a-zA-Z0-9-_]+\.?)+ var name, followed by optional
+ * dot, repeated at least 1 time
+ * (?(1)\]) if there was opened square bracket
+ * (subgrup 1), match close bracket
+ */
+ if (preg_match_all('/\$(\[)?([a-zA-Z0-9-_]+\.?)+(?(1)\])/', $s,$m)) {
+ foreach ($m[0] as $var) {
+ $exp = str_replace(array("[", "]"), array("", ""), $var);
+ $exptks = explode("|", $exp);
+
+ $varn = $exptks[0];
+ unset($exptks[0]);
+ $val = $this->_get_var($varn, true);
+ if ($val != KEY_NOT_EXISTS) {
+ /* run filters */
+ /*
+ * Filter are in form of:
+ * filtername:arg:arg:arg
+ *
+ * "filtername" is function name
+ * "arg"s are optional, var value is appended to the end
+ * if one "arg"==='x' , is replaced with var value
+ *
+ * examples:
+ * $item.body|htmlspecialchars // escape html chars
+ * $item.body|htmlspecialchars|strtoupper // escape html and uppercase result
+ * $item.created|date:%Y %M %j // format date (created is a timestamp)
+ * $item.body|str_replace:cat:dog // replace all "cat" with "dog"
+ * $item.body|str_replace:cat:dog:x:1 // replace one "cat" with "dog"
+ */
+ foreach ($exptks as $filterstr) {
+ $filter = explode(":", $filterstr);
+ $filtername = $filter[0];
+ unset($filter[0]);
+ $valkey = array_search("x", $filter);
+ if ($valkey === false) {
+ $filter[] = $val;
+ } else {
+ $filter[$valkey] = $val;
+ }
+ if (function_exists($filtername)) {
+ $val = call_user_func_array($filtername, $filter);
+ }
}
+ $s = str_replace($var, $val, $s);
}
}
-
- return $s;
- }
-
- private function replace($s,$r) {
- $this->replace_macros($s, $r);
- }
-
- // TemplateEngine interface
- public function replace_macros($s, $r) {
- $this->r = $r;
-
- $s = $this->_build_nodes($s);
-
- $s = preg_replace_callback('/\|\|([0-9]+)\|\|/', array($this, "_replcb_node"), $s);
- if ($s==Null) $this->_preg_error();
-
- // remove comments block
- $s = preg_replace('/{#[^#]*#}/', "" , $s);
-
- $t2 = dba_timer();
-
- // replace strings recursively (limit to 10 loops)
- $os = ""; $count=0;
- while(($os !== $s) && $count<10){
- $os=$s; $count++;
- $s = $this->var_replace($s);
- }
- return $s;
}
- public function get_markup_template($file, $root='') {
- $template_file = theme_include($file, $root);
- if ($template_file) {
- $content = file_get_contents($template_file);
- }
- return $content;
- }
+ return $s;
}
-
+ private function replace($s, $r) {
+ $this->replace_macros($s, $r);
+ }
+ // TemplateEngine interface
+ public function replace_macros($s, $r) {
+ $this->r = $r;
+ $s = $this->_build_nodes($s);
-function template_escape($s) {
+ $s = preg_replace_callback('/\|\|([0-9]+)\|\|/', array($this, "_replcb_node"), $s);
+ if ($s == Null)
+ $this->_preg_error();
- return str_replace(array('$','{{'),array('!_Doll^Ars1Az_!','!_DoubLe^BraceS4Rw_!'),$s);
+ // remove comments block
+ $s = preg_replace('/{#[^#]*#}/', "" , $s);
+ //$t2 = dba_timer();
-}
+ // replace strings recursively (limit to 10 loops)
+ $os = "";
+ $count=0;
+ while (($os !== $s) && $count<10) {
+ $os=$s;
+ $count++;
+ $s = $this->var_replace($s);
+ }
-function template_unescape($s) {
+ return $s;
+ }
- return str_replace(array('!_Doll^Ars1Az_!','!_DoubLe^BraceS4Rw_!'),array('$','{{'),$s);
+ public function get_markup_template($file, $root='') {
+ $template_file = theme_include($file, $root);
+ if ($template_file) {
+ $content = file_get_contents($template_file);
+ }
+ return $content;
+ }
+}
+function template_escape($s) {
+ return str_replace(array('$','{{'),array('!_Doll^Ars1Az_!','!_DoubLe^BraceS4Rw_!'),$s);
+}
+
+function template_unescape($s) {
+ return str_replace(array('!_Doll^Ars1Az_!','!_DoubLe^BraceS4Rw_!'),array('$','{{'),$s);
}
diff --git a/include/text.php b/include/text.php
index fc2f35135..1292d49d3 100644
--- a/include/text.php
+++ b/include/text.php
@@ -1,18 +1,26 @@
-<?php /** @file */
-
+<?php
+/**
+ * @file include/text.php
+ */
require_once("include/template_processor.php");
require_once("include/smarty.php");
+// 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 );
+
/**
- * This is our template processor
+ * @brief This is our template processor.
*
* @param string|FriendicaSmarty $s the string requiring macro substitution,
- * or an instance of FriendicaSmarty
+ * or an instance of FriendicaSmarty
* @param array $r key value pairs (search => 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));
@@ -92,12 +98,20 @@ function z_input_filter($channel_id,$s,$type = 'text/bbcode') {
return escape_tags($s);
if($type == 'text/plain')
return escape_tags($s);
+
+ $a = get_app();
+ if($a->is_sys) {
+ return $s;
+ }
+
$r = q("select account_id, account_roles, channel_pageflags from account left join channel on channel_account_id = account_id where channel_id = %d limit 1",
intval($channel_id)
);
- if($r && (($r[0]['account_roles'] & ACCOUNT_ROLE_ALLOWCODE) || ($r[0]['channel_pageflags'] & PAGE_ALLOWCODE))) {
- if(local_channel() && (get_account_id() == $r[0]['account_id'])) {
- return $s;
+ if($r) {
+ if(($r[0]['account_roles'] & ACCOUNT_ROLE_ALLOWCODE) || ($r[0]['channel_pageflags'] & PAGE_ALLOWCODE)) {
+ if(local_channel() && (get_account_id() == $r[0]['account_id'])) {
+ return $s;
+ }
}
}
@@ -105,50 +119,46 @@ function z_input_filter($channel_id,$s,$type = 'text/bbcode') {
return purify_html($s);
return escape_tags($s);
-
}
-
-
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(
@@ -180,8 +190,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;
@@ -192,33 +202,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.
*/
@@ -230,7 +237,6 @@ function xmlify($str) {
$char = mb_substr($str,$x,1);
switch( $char ) {
-
case "\r" :
break;
case "&" :
@@ -254,9 +260,10 @@ function xmlify($str) {
default :
$buffer .= $char;
break;
- }
+ }
}
$buffer = trim($buffer);
+
return($buffer);
}
@@ -270,10 +277,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)))
@@ -360,8 +369,6 @@ function paginate(&$a) {
function alt_pager(&$a, $i, $more = '', $less = '') {
- $o = '';
-
if(! $more)
$more = t('older');
if(! $less)
@@ -370,10 +377,10 @@ function alt_pager(&$a, $i, $more = '', $less = '') {
$stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
$stripped = str_replace('q=','',$stripped);
$stripped = trim($stripped,'/');
- $pagenum = $a->pager['page'];
+ //$pagenum = $a->pager['page'];
$url = $a->get_baseurl() . '/' . $stripped;
- return replace_macros(get_markup_template('alt_pager.tpl'),array(
+ return replace_macros(get_markup_template('alt_pager.tpl'), array(
'$has_less' => (($a->pager['page'] > 1) ? true : false),
'$has_more' => (($i > 0 && $i >= $a->pager['itemspage']) ? true : false),
'$less' => $less,
@@ -385,14 +392,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><sxo33e>" => array(123xyz,246qyo,sxo33e);
+ *
+ * @param string $s
+ * @return array
+ */
function expand_acl($s) {
-
- // turn string array of angle-bracketed elements into string array
- // e.g. "<123xyz><246qyo><sxo33e>" => array(123xyz,246qyo,sxo33e);
-
$ret = array();
if(strlen($s)) {
@@ -403,34 +412,41 @@ function expand_acl($s) {
$ret[] = $aa;
}
}
+
return $ret;
}
-// Used to wrap ACL elements in angle brackets for storage
-
-
+/**
+ * @brief Used to wrap ACL elements in angle brackets for storage.
+ *
+ * @param[in,out] array &$item
+ */
function sanitise_acl(&$item) {
- if(strlen($item))
+ if (strlen($item))
$item = '<' . notags(trim($item)) . '>';
else
unset($item);
}
-
-// Convert an ACL array to a storable string
-
+/**
+ * @brief Convert an ACL array to a storable string.
+ *
+ * @param array $p
+ * @return array
+ */
function perms2str($p) {
$ret = '';
- if(is_array($p))
+ if (is_array($p))
$tmp = $p;
else
- $tmp = explode(',',$p);
+ $tmp = explode(',', $p);
- if(is_array($tmp)) {
- array_walk($tmp,'sanitise_acl');
- $ret = implode('',$tmp);
+ if (is_array($tmp)) {
+ array_walk($tmp, 'sanitise_acl');
+ $ret = implode('', $tmp);
}
+
return $ret;
}
@@ -600,6 +616,7 @@ function activity_match($haystack,$needle) {
function get_tags($s) {
$ret = array();
+ $match = array();
// ignore anything in a code block
@@ -625,7 +642,8 @@ function get_tags($s) {
// The lookbehind is used to prevent a match in the middle of a word
// '=' needs to be avoided because when the replacement is made (in handle_tag()) it has to be ignored there
// Feel free to allow '=' if the issue with '=' is solved in handle_tag()
- if(preg_match_all('/(?<![a-zA-Z0-9=])(@[^ \x0D\x0A,:?\[]+ [^ \x0D\x0A@,:?\[]+)/',$s,$match)) {
+ // added / ? and [ to avoid issues with hashchars in url paths
+ if(preg_match_all('/(?<![a-zA-Z0-9=\/\?])(@[^ \x0D\x0A,:?\[]+ [^ \x0D\x0A@,:?\[]+)/',$s,$match)) {
foreach($match[1] as $mtch) {
if(substr($mtch,-1,1) === '.')
$ret[] = substr($mtch,0,-1);
@@ -637,7 +655,7 @@ function get_tags($s) {
// Otherwise pull out single word tags. These can be @nickname, @first_last
// and #hash tags.
- if(preg_match_all('/(?<![a-zA-Z0-9=])([@#][^ \x0D\x0A,;:?\[]+)/',$s,$match)) {
+ if(preg_match_all('/(?<![a-zA-Z0-9=\/\?])([@#][^ \x0D\x0A,;:?\[]+)/',$s,$match)) {
foreach($match[1] as $mtch) {
if(substr($mtch,-1,1) === '.')
$mtch = substr($mtch,0,-1);
@@ -739,6 +757,7 @@ function contact_block() {
if((! is_array($a->profile)) || ($a->profile['hide_friends']))
return $o;
+
$r = q("SELECT COUNT(abook_id) AS total FROM abook left join xchan on abook_xchan = xchan_hash WHERE abook_channel = %d and not ( abook_flags & %d )>0 and xchan_orphan = 0 and xchan_deleted = 0 $sql_extra",
intval($a->profile['uid']),
intval($abook_flags)
@@ -750,15 +769,13 @@ function contact_block() {
$contacts = t('No connections');
$micropro = null;
} else {
- if(ACTIVE_DBTYPE == DBTYPE_POSTGRES) {
- $randfunc = 'RANDOM()';
- } else {
- $randfunc = 'RAND()';
- }
+
+ $randfunc = db_getfunc('RAND');
+
$r = q("SELECT abook.*, xchan.* FROM abook left join xchan on abook.abook_xchan = xchan.xchan_hash WHERE abook_channel = %d AND not ( abook_flags & %d)>0 and xchan_orphan = 0 and xchan_deleted = 0 $sql_extra ORDER BY $randfunc LIMIT %d",
- intval($a->profile['uid']),
- intval($abook_flags|ABOOK_FLAG_ARCHIVED),
- intval($shown)
+ intval($a->profile['uid']),
+ intval($abook_flags|ABOOK_FLAG_ARCHIVED),
+ intval($shown)
);
if(count($r)) {
@@ -861,51 +878,48 @@ function valid_email($x){
return false;
}
-
/**
+ * @brief Replace naked text hyperlink with HTML formatted hyperlink.
*
- * Function: linkify
- *
- * Replace naked text hyperlink with HTML formatted hyperlink
- *
+ * @param string $s
+ * @param boolean $me (optional) default false
+ * @return string
*/
-
-
-function linkify($s) {
- $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\@\~\#\'\%\$\!\+]*)/", ' <a href="$1" >$1</a>', $s);
+function linkify($s, $me = false) {
+ $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\@\~\#\'\%\$\!\+\,\@]*)/", (($me) ? ' <a href="$1" rel="me" >$1</a>' : ' <a href="$1" >$1</a>'), $s);
$s = preg_replace("/\<(.*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
+
return($s);
}
-
/**
- * @function sslify($s)
- * Replace media element using http url with https to a local redirector if using https locally
- * @param string $s
+ * @brief Replace media element using http url with https to a local redirector
+ * if using https locally.
*
* Looks for HTML tags containing src elements that are http when we're viewing an https page
* Typically this throws an insecure content violation in the browser. So we redirect them
* to a local redirector which uses https and which redirects to the selected content
*
+ * @param string $s
* @returns string
*/
function sslify($s) {
- if(strpos(z_root(),'https:') === false)
+ if (strpos(z_root(),'https:') === false)
return $s;
$matches = null;
$cnt = preg_match_all("/\<(.*?)src=\"(http\:.*?)\"(.*?)\>/",$s,$matches,PREG_SET_ORDER);
- if($cnt) {
- foreach($matches as $match) {
- $filename = basename( parse_url($match[2],PHP_URL_PATH) );
+ if ($cnt) {
+ foreach ($matches as $match) {
+ $filename = basename( parse_url($match[2], PHP_URL_PATH) );
$s = str_replace($match[2],z_root() . '/sslify/' . $filename . '?f=&url=' . urlencode($match[2]),$s);
}
}
+
return $s;
}
-
function get_poke_verbs() {
// index is present tense verb
// value is array containing past tense verb, translation of present, translation of past
@@ -1028,56 +1042,50 @@ function list_smilies() {
'<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
'<img class="smiley" src="' . $a->get_baseurl() . '/images/like.gif" alt=":like" />',
'<img class="smiley" src="' . $a->get_baseurl() . '/images/dislike.gif" alt=":dislike" />',
- '<a href="http://getzot.com"><strong>red<img class="smiley" src="' . $a->get_baseurl() . '/images/rm-16.png" alt="' . urlencode('red#matrix') . '" />matrix</strong></a>',
- '<a href="http://getzot.com"><strong>red<img class="smiley" src="' . $a->get_baseurl() . '/images/rm-16.png" alt="' . urlencode('red#') . '" />matrix</strong></a>',
- '<a href="http://getzot.com"><strong>red<img class="smiley" src="' . $a->get_baseurl() . '/images/rm-16.png" alt="r#" />matrix</strong></a>'
+ '<a href="http://getzot.com"><strong>red<img class="smiley bb_rm-logo" src="' . $a->get_baseurl() . '/images/rm-32.png" alt="' . urlencode('red#matrix') . '" />matrix</strong></a>',
+ '<a href="http://getzot.com"><strong>red<img class="smiley bb_rm-logo" src="' . $a->get_baseurl() . '/images/rm-32.png" alt="' . urlencode('red#') . '" />matrix</strong></a>',
+ '<a href="http://getzot.com"><strong>red<img class="smiley bb_rm-logo" src="' . $a->get_baseurl() . '/images/rm-32.png" alt="r#" />matrix</strong></a>'
);
$params = array('texts' => $texts, 'icons' => $icons);
call_hooks('smilie', $params);
+
return $params;
}
/**
- *
- * Function: smilies
- *
- * Description:
- * Replaces text emoticons with graphical images
- *
- * @Parameter: string $s
- *
- * Returns string
+ * @brief Replaces text emoticons with graphical images.
*
* It is expected that this function will be called using HTML text.
* We will escape text between HTML pre and code blocks, and HTML attributes
* (such as urls) from being processed.
- *
+ *
* At a higher level, the bbcode [nosmile] tag can be used to prevent this
* function from being executed by the prepare_text() routine when preparing
- * bbcode source for HTML display
+ * bbcode source for HTML display.
*
+ * @param string $s
+ * @param boolean $sample (optional) default false
+ * @return string
*/
function smilies($s, $sample = false) {
- $a = get_app();
- if(intval(get_config('system','no_smilies'))
- || (local_channel() && intval(get_pconfig(local_channel(),'system','no_smilies'))))
+ if(intval(get_config('system', 'no_smilies'))
+ || (local_channel() && intval(get_pconfig(local_channel(), 'system', 'no_smilies'))))
return $s;
- $s = preg_replace_callback('{<(pre|code)>.*?</\1>}ism','smile_shield',$s);
- $s = preg_replace_callback('/<[a-z]+ .*?>/ism','smile_shield',$s);
+ $s = preg_replace_callback('{<(pre|code)>.*?</\1>}ism', 'smile_shield', $s);
+ $s = preg_replace_callback('/<[a-z]+ .*?>/ism', 'smile_shield', $s);
$params = list_smilies();
$params['string'] = $s;
- if($sample) {
+ if ($sample) {
$s = '<div class="smiley-sample">';
- for($x = 0; $x < count($params['texts']); $x ++) {
+ for ($x = 0; $x < count($params['texts']); $x ++) {
$s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
}
- }
- else {
+ } else {
$params['string'] = preg_replace_callback('/&lt;(3+)/','preg_heart',$params['string']);
$s = str_replace($params['texts'],$params['icons'],$params['string']);
}
@@ -1087,6 +1095,12 @@ function smilies($s, $sample = false) {
return $s;
}
+/**
+ * @brief
+ *
+ * @param array $m
+ * @return string
+ */
function smile_shield($m) {
return '<!--base64:' . base64url_encode($m[0]) . '-->';
}
@@ -1095,16 +1109,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 .= '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
+
$r = str_replace($x[0],$t,$x[0]);
+
return $r;
}
@@ -1122,27 +1142,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;
@@ -1162,6 +1188,17 @@ function unobscure(&$item) {
}
}
+function unobscure_mail(&$item) {
+ if(array_key_exists('mail_flags',$item) && ($item['mail_flags'] & MAIL_OBSCURED)) {
+ $key = get_config('system','prvkey');
+ if($item['title'])
+ $item['title'] = crypto_unencapsulate(json_decode_plus($item['title']),$key);
+ if($item['body'])
+ $item['body'] = crypto_unencapsulate(json_decode_plus($item['body']),$key);
+ }
+}
+
+
function theme_attachments(&$item) {
$arr = json_decode_plus($item['attach']);
@@ -1171,8 +1208,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':
@@ -1238,15 +1277,19 @@ function format_categories(&$item,$writeable) {
return $s;
}
-// Add any hashtags which weren't mentioned in the message body, e.g. community tags
-
+/**
+ * @brief Add any hashtags which weren't mentioned in the message body, e.g. community tags
+ *
+ * @param[in] array &$item
+ * @return string HTML link of hashtag
+ */
function format_hashtags(&$item) {
-
$s = '';
- $terms = get_terms_oftype($item['term'],TERM_HASHTAG);
+
+ $terms = get_terms_oftype($item['term'], TERM_HASHTAG);
if($terms) {
foreach($terms as $t) {
- $term = htmlspecialchars($t['term'],ENT_COMPAT,'UTF-8',false) ;
+ $term = htmlspecialchars($t['term'], ENT_COMPAT, 'UTF-8', false) ;
if(! trim($term))
continue;
if(strpos($item['body'], $t['url']))
@@ -1258,6 +1301,7 @@ function format_hashtags(&$item) {
$s .= '#<a href="' . zid($t['url']) . '" >' . $term . '</a>';
}
}
+
return $s;
}
@@ -1281,6 +1325,7 @@ function format_mentions(&$item) {
$s .= '@<a href="' . zid($t['url']) . '" >' . $term . '</a>';
}
}
+
return $s;
}
@@ -1313,13 +1358,13 @@ function generate_map($coord) {
$coord = str_replace(array(',','/',' '),array(' ',' ',' '),$coord);
$arr = array('lat' => trim(substr($coord,0,strpos($coord,' '))), 'lon' => trim(substr($coord,strpos($coord,' ')+1)), 'html' => '');
call_hooks('generate_map',$arr);
- return $arr['html'];
+ return (($arr['html']) ? $arr['html'] : $coord);
}
function generate_named_map($location) {
$arr = array('location' => $location, 'html' => '');
call_hooks('generate_named_map',$arr);
- return $arr['html'];
+ return (($arr['html']) ? $arr['html'] : $location);
}
@@ -1398,11 +1443,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':
@@ -1455,19 +1503,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 <a class="zrl" href="xxxxxxxxxx"> and will not work if zrl and href appear in a different order.
+ * We assume it looks like \<a class="zrl" href="xxxxxxxxxx"\> 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 = '<a' . $match[1] . ' href="' . (($is_zid) ? zid($match[2]) : $match[2]) . '"';
$x = str_replace($match[0],$replace,$match[0]);
+
return $x;
}
@@ -1476,6 +1526,7 @@ function zidify_img_callback($match) {
$replace = '<img' . $match[1] . ' src="' . (($is_zid) ? zid($match[2]) : $match[2]) . '"';
$x = str_replace($match[0],$replace,$match[0]);
+
return $x;
}
@@ -1483,16 +1534,17 @@ function zidify_img_callback($match) {
function zidify_links($s) {
$s = preg_replace_callback('/\<a(.*?)href\=\"(.*?)\"/ism','zidify_callback',$s);
$s = preg_replace_callback('/\<img(.*?)src\=\"(.*?)\"/ism','zidify_img_callback',$s);
+
return $s;
}
-
/**
- * return atom link elements for all of our hubs
+ * @brief Return atom link elements for all of our hubs.
+ *
+ * @return string
*/
-
function feed_hublinks() {
- $hub = get_config('system','huburl');
+ $hub = get_config('system', 'huburl');
$hubxml = '';
if(strlen($hub)) {
@@ -1502,6 +1554,7 @@ function feed_hublinks() {
$h = trim($h);
if(! strlen($h))
continue;
+
$hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
}
}
@@ -1553,18 +1606,20 @@ function layout_select($channel_id, $current = '') {
intval($channel_id),
intval(ITEM_TYPE_PDL)
);
+
if($r) {
- $o = t('Select a page layout: ');
- $o .= '<select name="layout_mid" id="select-layout_mid" >';
- $empty_selected = (($current === '') ? ' selected="selected" ' : '');
- $o .= '<option value="" ' . $empty_selected . '>' . t('default') . '</option>';
+ $empty_selected = (($current === false) ? ' selected="selected" ' : '');
+ $options .= '<option value="" ' . $empty_selected . '>' . t('default') . '</option>';
foreach($r as $rr) {
$selected = (($rr['mid'] == $current) ? ' selected="selected" ' : '');
- $o .= '<option value="' . $rr['mid'] . '"' . $selected . '>' . $rr['sid'] . '</option>';
+ $options .= '<option value="' . $rr['mid'] . '"' . $selected . '>' . $rr['sid'] . '</option>';
}
- $o .= '</select>';
}
+ $o = replace_macros(get_markup_template('field_select_raw.tpl'), array(
+ '$field' => array('layout_mid', t('Page layout'), $selected, t('You can create your own with the layouts tool'), $options)
+ ));
+
return $o;
}
@@ -1578,25 +1633,33 @@ function mimetype_select($channel_id, $current = 'text/bbcode') {
'text/plain'
);
- $r = q("select account_id, account_roles, channel_pageflags from account left join channel on account_id = channel_account_id where
- channel_id = %d limit 1",
- intval($channel_id)
- );
+ $a = get_app();
+ if($a->is_sys) {
+ $x[] = 'application/x-php';
+ }
+ else {
+ $r = q("select account_id, account_roles, channel_pageflags from account left join channel on account_id = channel_account_id where
+ channel_id = %d limit 1",
+ intval($channel_id)
+ );
- if($r) {
- if(($r[0]['account_roles'] & ACCOUNT_ROLE_ALLOWCODE) || ($r[0]['channel_pageflags'] & PAGE_ALLOWCODE)) {
- if(local_channel() && get_account_id() == $r[0]['account_id'])
- $x[] = 'application/x-php';
- }
+ if($r) {
+ if(($r[0]['account_roles'] & ACCOUNT_ROLE_ALLOWCODE) || ($r[0]['channel_pageflags'] & PAGE_ALLOWCODE)) {
+ if(local_channel() && get_account_id() == $r[0]['account_id']) {
+ $x[] = 'application/x-php';
+ }
+ }
+ }
}
- $o = t('Page content type: ');
- $o .= '<select name="mimetype" id="mimetype-select">';
foreach($x as $y) {
- $select = (($y == $current) ? ' selected="selected" ' : '');
- $o .= '<option name="' . $y . '"' . $select . '>' . $y . '</option>';
+ $selected = (($y == $current) ? ' selected="selected" ' : '');
+ $options .= '<option name="' . $y . '"' . $selected . '>' . $y . '</option>';
}
- $o .= '</select>';
+
+ $o = replace_macros(get_markup_template('field_select_raw.tpl'), array(
+ '$field' => array('mimetype', t('Page content type'), $selected, '', $options)
+ ));
return $o;
}
@@ -1859,9 +1922,13 @@ function check_webbie($arr) {
function ids_to_querystr($arr,$idx = 'id') {
$t = array();
- foreach($arr as $x)
- $t[] = $x[$idx];
-
+ if($arr) {
+ foreach($arr as $x) {
+ if(! in_array($x[$idx],$t)) {
+ $t[] = $x[$idx];
+ }
+ }
+ }
return(implode(',', $t));
}
@@ -2033,7 +2100,11 @@ function json_decode_plus($s) {
return $x;
}
-
+/**
+ * @brief Creates navigation menu for webpage, layout, blocks, menu sites.
+ *
+ * @return string
+ */
function design_tools() {
$channel = get_app()->get_channel();
@@ -2048,7 +2119,7 @@ function design_tools() {
$who = $channel['channel_address'];
return replace_macros(get_markup_template('design_tools.tpl'), array(
- '$title' => t('Design'),
+ '$title' => t('Design Tools'),
'$who' => $who,
'$sys' => $sys,
'$blocks' => t('Blocks'),
@@ -2094,21 +2165,23 @@ 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) {
+function handle_tag($a, &$body, &$access_tag, &$str_tags, $profile_uid, $tag, $diaspora = false) {
$replaced = false;
$r = null;
+ $match = array();
$termtype = ((strpos($tag,'#') === 0) ? TERM_HASHTAG : TERM_UNKNOWN);
$termtype = ((strpos($tag,'@') === 0) ? TERM_MENTION : $termtype);
@@ -2172,7 +2245,7 @@ function handle_tag($a, &$body, &$access_tag, &$str_tags, $profile_uid, $tag) {
if(strpos($tag,'@') === 0) {
// The @! tag will alter permissions
- $exclusive = ((strpos($tag,'!') === 1) ? true : false);
+ $exclusive = ((strpos($tag,'!') === 1 && (! $diaspora)) ? true : false);
//is it already replaced?
if(strpos($tag,'[zrl='))
@@ -2201,10 +2274,19 @@ function handle_tag($a, &$body, &$access_tag, &$str_tags, $profile_uid, $tag) {
// Here we're looking for an address book entry as provided by the auto-completer
// of the form something+nnn where nnn is an abook_id or the first chars of xchan_hash
- if(strrpos($newname,'+')) {
+
+ // If there's a +nnn in the string make sure there isn't a space preceding it
+
+ $t1 = strpos($newname,' ');
+ $t2 = strrpos($newname,'+');
+
+ if($t1 && $t2 && $t1 < $t2)
+ $t2 = 0;
+
+ if(($t2) && (! $diaspora)) {
//get the id
- $tagcid = substr($newname,strrpos($newname,'+') + 1);
+ $tagcid = substr($newname,$t2 + 1);
if(strrpos($tagcid,' '))
$tagcid = substr($tagcid,0,strrpos($tagcid,' '));
@@ -2349,12 +2431,13 @@ function handle_tag($a, &$body, &$access_tag, &$str_tags, $profile_uid, $tag) {
return array('replaced' => $replaced, 'termtype' => $termtype, 'term' => $newname, 'url' => $url, 'contact' => $r[0]);
}
-function linkify_tags($a, &$body, $uid) {
+function linkify_tags($a, &$body, $uid, $diaspora = false) {
$str_tags = '';
$tagged = array();
- $result = array();
+ $results = array();
$tags = get_tags($body);
+
if(count($tags)) {
foreach($tags as $tag) {
$access_tag = '';
@@ -2372,18 +2455,22 @@ function linkify_tags($a, &$body, $uid) {
if($fullnametagged)
continue;
- $success = handle_tag($a, $body, $access_tag, $str_tags, ($uid) ? $uid : $profile_uid , $tag);
+ $success = handle_tag($a, $body, $access_tag, $str_tags, ($uid) ? $uid : $a->profile_uid , $tag, $diaspora);
$results[] = array('success' => $success, 'access_tag' => $access_tag);
if($success['replaced']) $tagged[] = $tag;
}
}
+
return $results;
}
/**
- * @brief returns icon name for use with e.g. font-awesome based on mime-type
+ * @brief returns icon name for use with e.g. font-awesome based on mime-type.
+ *
+ * These are the the font-awesome names of version 3.2.1. The newer font-awesome
+ * 4 has different names.
*
- * @param string $type
+ * @param string $type mime type
* @return string
*/
function getIconFromType($type) {
@@ -2436,10 +2523,10 @@ function getIconFromType($type) {
* @brief Returns a human readable formatted string for filesizes.
*
* @param int $size filesize in bytes
- * @return string
+ * @return string human readable formatted filesize
*/
function userReadableSize($size) {
- $ret = "";
+ $ret = '';
if (is_numeric($size)) {
$incr = 0;
$k = 1024;
@@ -2448,7 +2535,8 @@ function userReadableSize($size) {
$incr++;
$size = round($size / $k, 2);
}
- $ret = $size . " " . $unit[$incr];
+ $ret = $size . ' ' . $unit[$incr];
}
+
return $ret;
}
diff --git a/include/widgets.php b/include/widgets.php
index 7cc9fc708..5a61ea639 100644
--- a/include/widgets.php
+++ b/include/widgets.php
@@ -233,7 +233,6 @@ function widget_savedsearch($arr) {
$srchurl = rtrim(preg_replace('/searchsave\=[^\&].*?(\&|$)/is','',$srchurl),'&');
$hasq = ((strpos($srchurl,'?') !== false) ? true : false);
$srchurl = rtrim(preg_replace('/searchremove\=[^\&].*?(\&|$)/is','',$srchurl),'&');
- $hasq = ((strpos($srchurl,'?') !== false) ? true : false);
$srchurl = rtrim(preg_replace('/search\=[^\&].*?(\&|$)/is','',$srchurl),'&');
$srchurl = rtrim(preg_replace('/submit\=[^\&].*?(\&|$)/is','',$srchurl),'&');
@@ -241,7 +240,10 @@ function widget_savedsearch($arr) {
$hasq = ((strpos($srchurl,'?') !== false) ? true : false);
+ $hasamp = ((strpos($srchurl,'&') !== false) ? true : false);
+ if(($hasamp) && (! $hasq))
+ $srchurl = substr($srchurl,0,strpos($srchurl,'&')) . '?f=&' . substr($srchurl,strpos($srchurl,'&')+1);
$o = '';
@@ -257,8 +259,8 @@ function widget_savedsearch($arr) {
$saved[] = array(
'id' => $rr['tid'],
'term' => $rr['term'],
- 'dellink' => z_root() . '/' . $srchurl . (($hasq) ? '' : '?f=') . '&amp;searchremove=1&amp;search=' . urlencode($rr['term']),
- 'srchlink' => z_root() . '/' . $srchurl . (($hasq) ? '' : '?f=') . '&amp;search=' . urlencode($rr['term']),
+ 'dellink' => z_root() . '/' . $srchurl . (($hasq || $hasamp) ? '' : '?f=') . '&amp;searchremove=1&amp;search=' . urlencode($rr['term']),
+ 'srchlink' => z_root() . '/' . $srchurl . (($hasq || $hasamp) ? '' : '?f=') . '&amp;search=' . urlencode($rr['term']),
'displayterm' => htmlspecialchars($rr['term'], ENT_COMPAT,'UTF-8'),
'encodedterm' => urlencode($rr['term']),
'delete' => t('Remove term'),
@@ -418,18 +420,35 @@ function widget_affinity($arr) {
$cmin = ((x($_REQUEST,'cmin')) ? intval($_REQUEST['cmin']) : 0);
$cmax = ((x($_REQUEST,'cmax')) ? intval($_REQUEST['cmax']) : 99);
+
if(feature_enabled(local_channel(),'affinity')) {
+
+ $labels = array(
+ t('Me'),
+ t('Family'),
+ t('Friends'),
+ t('Acquaintances'),
+ t('All')
+ );
+ call_hooks('affinity_labels',$labels);
+ $label_str = '';
+
+ if($labels) {
+ foreach($labels as $l) {
+ if($label_str) {
+ $label_str .= ", '|'";
+ $label_str .= ", '" . $l . "'";
+ }
+ else
+ $label_str .= "'" . $l . "'";
+ }
+ }
+
$tpl = get_markup_template('main_slider.tpl');
$x = replace_macros($tpl,array(
'$val' => $cmin . ',' . $cmax,
'$refresh' => t('Refresh'),
- '$me' => t('Me'),
- '$intimate' => t('Best Friends'),
- '$friends' => t('Friends'),
- '$coworkers' => t('Co-workers'),
- '$oldfriends' => t('Former Friends'),
- '$acquaintances' => t('Acquaintances'),
- '$world' => t('Everybody')
+ '$labels' => $label_str,
));
$arr = array('html' => $x);
call_hooks('main_slider',$arr);
@@ -605,9 +624,6 @@ function widget_vcard($arr) {
* The following directory widgets are only useful on the directory page
*/
-function widget_dirsafemode($arr) {
- return dir_safe_mode();
-}
function widget_dirsort($arr) {
return dir_sort_links();
@@ -963,3 +979,12 @@ function widget_rating($arr) {
return $o;
}
+
+// used by site ratings pages to provide a return link
+function widget_pubsites() {
+ if(get_app()->poi)
+ return;
+ return '<div class="widget"><ul class="nav nav-pills"><li><a href="pubsites">' . t('Public Hubs') . '</a></li></ul></div>';
+}
+
+
diff --git a/include/zot.php b/include/zot.php
index b654a1b86..2111b33a6 100644
--- a/include/zot.php
+++ b/include/zot.php
@@ -1,109 +1,114 @@
-<?php /** @file */
-
-require_once('include/crypto.php');
-require_once('include/items.php');
-require_once('include/hubloc.php');
-
+<?php
/**
- * Red implementation of zot protocol.
+ * @file include/zot.php
+ * @brief RedMatrix implementation of zot protocol.
*
* https://github.com/friendica/red/wiki/zot
* https://github.com/friendica/red/wiki/Zot---A-High-Level-Overview
*
*/
+require_once('include/crypto.php');
+require_once('include/items.php');
+require_once('include/hubloc.php');
+
/**
+ * @brief Generates a unique string for use as a zot guid.
*
- * @function zot_new_uid($channel_nick)
+ * Generates a unique string for use as a zot guid using our DNS-based url, the
+ * channel nickname and some entropy.
+ * The entropy ensures uniqueness against re-installs where the same URL and
+ * nickname are chosen.
*
- * Generates a unique string for use as a zot guid using our DNS-based url, the channel nickname and some entropy.
- * The entropy ensures uniqueness against re-installs where the same URL and nickname are chosen.
- * NOTE: zot doesn't require this to be unique. Internally we use a whirlpool hash of this guid and the signature
- * of this guid signed with the channel private key. This can be verified and should make the probability of
- * collision of the verified result negligible within the constraints of our immediate universe.
- *
- * @param string channel_nickname = unique nickname of controlling entity
+ * @note zot doesn't require this to be unique. Internally we use a whirlpool
+ * hash of this guid and the signature of this guid signed with the channel
+ * private key. This can be verified and should make the probability of
+ * collision of the verified result negligible within the constraints of our
+ * immediate universe.
*
+ * @param string $channel_nick a unique nickname of controlling entity
* @returns string
- *
*/
-
function zot_new_uid($channel_nick) {
$rawstr = z_root() . '/' . $channel_nick . '.' . mt_rand();
- return(base64url_encode(hash('whirlpool',$rawstr,true),true));
-}
+ return(base64url_encode(hash('whirlpool', $rawstr, true), true));
+}
/**
+ * @brief Generates a portable hash identifier for a channel.
*
- * function make_xchan_hash($guid,$guid_sig)
+ * Generates a portable hash identifier for the channel identified by $guid and
+ * signed with $guid_sig.
*
- * Generates a portable hash identifier for the channel identified by $guid and signed with $guid_sig
- * This ID is portable across the network but MUST be calculated locally by verifying the signature
- * and can not be trusted as an identity.
+ * @note This ID is portable across the network but MUST be calculated locally
+ * by verifying the signature and can not be trusted as an identity.
*
+ * @param string $guid
+ * @param string $guid_sig
*/
-
-function make_xchan_hash($guid,$guid_sig) {
- return base64url_encode(hash('whirlpool',$guid . $guid_sig, true));
+function make_xchan_hash($guid, $guid_sig) {
+ return base64url_encode(hash('whirlpool', $guid . $guid_sig, true));
}
/**
- * @function zot_get_hublocs($hash)
- * Given a zot hash, return all distinct hubs.
- * This function is used in building the zot discovery packet
- * and therefore should only be used by channels which are defined
- * on this hub
- * @param string $hash - xchan_hash
- * @retuns array of hubloc (hub location structures)
- * hubloc_id int
- * hubloc_guid char(255)
- * hubloc_guid_sig text
- * hubloc_hash char(255)
- * hubloc_addr char(255)
- * hubloc_flags int
- * hubloc_status int
- * hubloc_url char(255)
- * hubloc_url_sig text
- * hubloc_host char(255)
- * hubloc_callback char(255)
- * hubloc_connect char(255)
- * hubloc_sitekey text
- * hubloc_updated datetime
- * hubloc_connected datetime
+ * @brief Given a zot hash, return all distinct hubs.
+ *
+ * This function is used in building the zot discovery packet and therefore
+ * should only be used by channels which are defined on this hub.
*
+ * @param string $hash - xchan_hash
+ * @returns array of hubloc (hub location structures)
+ * * \b hubloc_id int
+ * * \b hubloc_guid char(255)
+ * * \b hubloc_guid_sig text
+ * * \b hubloc_hash char(255)
+ * * \b hubloc_addr char(255)
+ * * \b hubloc_flags int
+ * * \b hubloc_status int
+ * * \b hubloc_url char(255)
+ * * \b hubloc_url_sig text
+ * * \b hubloc_host char(255)
+ * * \b hubloc_callback char(255)
+ * * \b hubloc_connect char(255)
+ * * \b hubloc_sitekey text
+ * * \b hubloc_updated datetime
+ * * \b hubloc_connected datetime
*/
-
function zot_get_hublocs($hash) {
- /** Only search for active hublocs - e.g. those that haven't been marked deleted */
+ /* Only search for active hublocs - e.g. those that haven't been marked deleted */
$ret = q("select * from hubloc where hubloc_hash = '%s' and hubloc_deleted != 0 order by hubloc_url ",
dbesc($hash)
);
+
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,
@@ -112,119 +117,110 @@ function zot_build_packet($channel,$type = 'notify',$recipients = null, $remote_
'guid_sig' => base64url_encode(rsa_sign($channel['channel_guid'],$channel['channel_prvkey'])),
'url' => z_root(),
'url_sig' => base64url_encode(rsa_sign(z_root(),$channel['channel_prvkey']))
- ),
+ ),
'callback' => '/post',
'version' => ZOT_REVISION
);
- 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) {
- $data['secret'] = $secret;
+ if ($secret) {
+ $data['secret'] = $secret;
$data['secret_sig'] = base64url_encode(rsa_sign($secret,$channel['channel_prvkey']));
}
- if($extra) {
- foreach($extra as $k => $v)
+ if ($extra) {
+ foreach ($extra as $k => $v)
$data[$k] = $v;
}
-
logger('zot_build_packet: ' . print_r($data,true), LOGGER_DATA);
// Hush-hush ultra top-secret mode
- if($remote_key) {
+ if ($remote_key) {
$data = crypto_encapsulate(json_encode($data),$remote_key);
}
return json_encode($data);
}
-
/**
- * @function: zot_zot
- * @param: string $url
- * @param: array $data
+ * @brief
+ *
+ * @see z_post_url()
*
- * @returns: array => see z_post_url for returned data format
+ * @param string $url
+ * @param array $data
+ * @return array see z_post_url() for returned data format
*/
-
-
-
-function zot_zot($url,$data) {
- return z_post_url($url,array('data' => $data));
+function zot_zot($url, $data) {
+ return z_post_url($url, array('data' => $data));
}
/**
- * @function: zot_finger
+ * @brief Look up information about channel.
*
- * Look up information about channel
- * @param: string $webbie
- * does not have to be host qualified e.g. 'foo' is treated as 'foo@thishub'
- * @param: array $channel
+ * @param string $webbie
+ * does not have to be host qualified e.g. 'foo' is treated as 'foo\@thishub'
+ * @param array $channel
* (optional), if supplied permissions will be enumerated specifically for $channel
- * @param: boolean $autofallback
+ * @param boolean $autofallback
* fallback/failover to http if https connection cannot be established. Default is true.
*
- * @returns: array => see z_post_url and mod/zfinger.php
+ * @return array see z_post_url() and \ref mod/zfinger.php
*/
+function zot_finger($webbie, $channel = null, $autofallback = true) {
-
-function zot_finger($webbie,$channel = null,$autofallback = true) {
-
-
- if(strpos($webbie,'@') === false) {
+ if (strpos($webbie,'@') === false) {
$address = $webbie;
$host = get_app()->get_hostname();
- }
- else {
+ } else {
$address = substr($webbie,0,strpos($webbie,'@'));
$host = substr($webbie,strpos($webbie,'@')+1);
}
$xchan_addr = $address . '@' . $host;
- if((! $address) || (! $xchan_addr)) {
+ if ((! $address) || (! $xchan_addr)) {
logger('zot_finger: no address :' . $webbie);
return array('success' => false);
- }
+ }
logger('using xchan_addr: ' . $xchan_addr, LOGGER_DATA);
-
+
// potential issue here; the xchan_addr points to the primary hub.
// The webbie we were called with may not, so it might not be found
// unless we query for hubloc_addr instead of xchan_addr
- $r = q("select xchan.*, hubloc.* from xchan
+ $r = q("select xchan.*, hubloc.* from xchan
left join hubloc on xchan_hash = hubloc_hash
where xchan_addr = '%s' and hubloc_primary = 1 limit 1",
dbesc($xchan_addr)
);
- 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'],
@@ -234,88 +230,85 @@ function zot_finger($webbie,$channel = null,$autofallback = true) {
$result = z_post_url($url . $rhs,$postvars);
-
- if((! $result['success']) && ($autofallback)) {
- if($https) {
+ if ((! $result['success']) && ($autofallback)) {
+ if ($https) {
logger('zot_finger: https failed. falling back to http');
$result = z_post_url('http://' . $host . $rhs,$postvars);
}
}
- }
- else {
+ } else {
$rhs .= '?f=&address=' . urlencode($address);
$result = z_fetch_url($url . $rhs);
- if((! $result['success']) && ($autofallback)) {
- if($https) {
+ if ((! $result['success']) && ($autofallback)) {
+ if ($https) {
logger('zot_finger: https failed. falling back to http');
$result = z_fetch_url('http://' . $host . $rhs);
}
}
}
-
- if(! $result['success'])
- logger('zot_finger: no results');
- return $result;
+ if (! $result['success'])
+ logger('zot_finger: no results');
+ return $result;
}
/**
- * @function: zot_refresh($them, $channel = null, $force = false)
+ * @brief Refreshes after permission changed or friending, etc.
+ *
+ * zot_refresh is typically invoked when somebody has changed permissions of a channel and they are notified
+ * to fetch new permissions via a finger/discovery operation. This may result in a new connection
+ * (abook entry) being added to a local channel and it may result in auto-permissions being granted.
+ *
+ * Friending in zot is accomplished by sending a refresh packet to a specific channel which indicates a
+ * permission change has been made by the sender which affects the target channel. The hub controlling
+ * the target channel does targetted discovery (a zot-finger request requesting permissions for the local
+ * channel). These are decoded here, and if necessary and abook structure (addressbook) is created to store
+ * the permissions assigned to this channel.
+ *
+ * Initially these abook structures are created with a 'pending' flag, so that no reverse permissions are
+ * implied until this is approved by the owner channel. A channel can also auto-populate permissions in
+ * return and send back a refresh packet of its own. This is used by forum and group communication channels
+ * so that friending and membership in the channel's "club" is automatic.
*
- * zot_refresh is typically invoked when somebody has changed permissions of a channel and they are notified
- * to fetch new permissions via a finger/discovery operation. This may result in a new connection
- * (abook entry) being added to a local channel and it may result in auto-permissions being granted.
- *
- * Friending in zot is accomplished by sending a refresh packet to a specific channel which indicates a
- * permission change has been made by the sender which affects the target channel. The hub controlling
- * the target channel does targetted discovery (a zot-finger request requesting permissions for the local
- * channel). These are decoded here, and if necessary and abook structure (addressbook) is created to store
- * the permissions assigned to this channel.
- *
- * Initially these abook structures are created with a 'pending' flag, so that no reverse permissions are
- * implied until this is approved by the owner channel. A channel can also auto-populate permissions in
- * return and send back a refresh packet of its own. This is used by forum and group communication channels
- * so that friending and membership in the channel's "club" is automatic.
- *
* @param array $them => xchan structure of sender
* @param array $channel => local channel structure of target recipient, required for "friending" operations
+ * @param array $force default false
*
- * @returns boolean true if successful, else false
+ * @returns boolean true if successful, else false
*/
+function zot_refresh($them, $channel = null, $force = false) {
-function zot_refresh($them,$channel = null, $force = false) {
-
- if(array_key_exists('xchan_network',$them) && ($them['xchan_network'] !== 'zot')) {
+ if (array_key_exists('xchan_network', $them) && ($them['xchan_network'] !== 'zot')) {
logger('zot_refresh: not got zot. ' . $them['xchan_name']);
return true;
}
logger('zot_refresh: them: ' . print_r($them,true), LOGGER_DATA);
- if($channel)
+ if ($channel)
logger('zot_refresh: channel: ' . print_r($channel,true), LOGGER_DATA);
$url = null;
- if($them['hubloc_url'])
+ if ($them['hubloc_url']) {
$url = $them['hubloc_url'];
- else {
+ } else {
$r = q("select hubloc_url, hubloc_flags from hubloc where hubloc_hash = '%s'",
dbesc($them['xchan_hash'])
);
- if($r) {
- foreach($r as $rr) {
- if($rr['hubloc_flags'] & HUBLOC_FLAGS_PRIMARY) {
+ if ($r) {
+ foreach ($r as $rr) {
+ if ($rr['hubloc_flags'] & HUBLOC_FLAGS_PRIMARY) {
$url = $rr['hubloc_url'];
break;
}
}
- if(! $url)
+ if (! $url)
$url = $r[0]['hubloc_url'];
}
}
- if(! $url) {
+ if (! $url) {
logger('zot_refresh: no url');
return false;
}
@@ -328,12 +321,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'];
}
@@ -341,19 +335,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;
@@ -383,7 +377,7 @@ function zot_refresh($them,$channel = null, $force = false) {
if($k === 'connected') {
$connected_set = intval($v);
continue;
- }
+ }
if(($v) && (array_key_exists($k,$global_perms))) {
$their_perms = $their_perms | intval($global_perms[$k][1]);
}
@@ -396,7 +390,7 @@ function zot_refresh($them,$channel = null, $force = false) {
intval(ABOOK_FLAG_SELF)
);
- if(array_key_exists('profile',$j) && array_key_exists('next_birthday',$j['profile'])) {
+ if(array_key_exists('profile',$j) && array_key_exists('next_birthday',$j['profile'])) {
$next_birthday = datetime_convert('UTC','UTC',$j['profile']['next_birthday']);
}
else {
@@ -405,17 +399,17 @@ function zot_refresh($them,$channel = null, $force = false) {
if($r) {
- // if the dob is the same as what we have stored (disregarding the year), keep the one
+ // if the dob is the same as what we have stored (disregarding the year), keep the one
// we have as we may have updated the year after sending a notification; and resetting
- // to the one we just received would cause us to create duplicated events.
+ // to the one we just received would cause us to create duplicated events.
if(substr($r[0]['abook_dob'],5) == substr($next_birthday,5))
$next_birthday = $r[0]['abook_dob'];
$current_abook_connected = (($r[0]['abook_flags'] & ABOOK_FLAG_UNCONNECTED) ? 0 : 1);
-
+
$y = q("update abook set abook_their_perms = %d, abook_dob = '%s'
- where abook_xchan = '%s' and abook_channel = %d
+ where abook_xchan = '%s' and abook_channel = %d
and not (abook_flags & %d) > 0 ",
intval($their_perms),
dbescdate($next_birthday),
@@ -427,11 +421,11 @@ function zot_refresh($them,$channel = null, $force = false) {
// if(($connected_set === 0 || $connected_set === 1) && ($connected_set !== $current_abook_unconnected)) {
// if they are in your address book but you aren't in theirs, and/or this does not
- // match your current connected state setting, toggle it.
- // FIXME: uncoverted to postgres
- // FIXME: when this was enabled, all contacts became unconnected. Currently disabled intentionally
+ // match your current connected state setting, toggle it.
+ /** @FIXME uncoverted to postgres */
+ /** @FIXME when this was enabled, all contacts became unconnected. Currently disabled intentionally */
// $y1 = q("update abook set abook_flags = (abook_flags ^ %d)
-// where abook_xchan = '%s' and abook_channel = %d
+// where abook_xchan = '%s' and abook_channel = %d
// and not (abook_flags & %d) limit 1",
// intval(ABOOK_FLAG_UNCONNECTED),
// dbesc($x['hash']),
@@ -445,7 +439,7 @@ function zot_refresh($them,$channel = null, $force = false) {
else {
// if we were just granted read stream permission and didn't have it before, try to pull in some posts
if((! ($r[0]['abook_their_perms'] & PERMS_R_STREAM)) && ($their_perms & PERMS_R_STREAM))
- proc_run('php','include/onepoll.php',$r[0]['abook_id']);
+ proc_run('php','include/onepoll.php',$r[0]['abook_id']);
}
}
else {
@@ -457,14 +451,20 @@ function zot_refresh($them,$channel = null, $force = false) {
}
if(! $default_perms)
$default_perms = intval(get_pconfig($channel['channel_id'],'system','autoperms'));
-
+
// Keep original perms to check if we need to notify them
$previous_perms = get_all_perms($channel['channel_id'],$x['hash']);
- $y = q("insert into abook ( abook_account, abook_channel, abook_xchan, abook_their_perms, abook_my_perms, abook_created, abook_updated, abook_dob, abook_flags ) values ( %d, %d, '%s', %d, %d, '%s', '%s', '%s', %d )",
+
+ $closeness = get_pconfig($channel['channel_id'],'system','new_abook_closeness');
+ if($closeness === false)
+ $closeness = 80;
+
+ $y = q("insert into abook ( abook_account, abook_channel, abook_closeness, abook_xchan, abook_their_perms, abook_my_perms, abook_created, abook_updated, abook_dob, abook_flags ) values ( %d, %d, %d, '%s', %d, %d, '%s', '%s', '%s', %d )",
intval($channel['channel_account_id']),
intval($channel['channel_id']),
+ intval($closeness),
dbesc($x['hash']),
intval($their_perms),
intval($default_perms),
@@ -494,47 +494,44 @@ function zot_refresh($them,$channel = null, $force = false) {
if($new_connection) {
require_once('include/enotify.php');
notification(array(
- 'type' => NOTIFY_INTRO,
- 'from_xchan' => $x['hash'],
- 'to_xchan' => $channel['channel_hash'],
- 'link' => z_root() . '/connedit/' . $new_connection[0]['abook_id'],
+ 'type' => NOTIFY_INTRO,
+ 'from_xchan' => $x['hash'],
+ 'to_xchan' => $channel['channel_hash'],
+ 'link' => z_root() . '/connedit/' . $new_connection[0]['abook_id'],
));
}
if($new_connection && ($their_perms & PERMS_R_STREAM)) {
if(($channel['channel_w_stream'] & PERMS_PENDING)
|| (! ($new_connection[0]['abook_flags'] & ABOOK_FLAG_PENDING)) )
- proc_run('php','include/onepoll.php',$new_connection[0]['abook_id']);
+ proc_run('php','include/onepoll.php',$new_connection[0]['abook_id']);
}
-
}
}
}
return true;
}
+
return false;
}
/**
- * @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 associative array which must contain:
+ * * \e string \b guid => guid of conversant
+ * * \e string \b guid_sig => guid signed with conversant's private key
+ * * \e string \b url => URL of the origination hub of this communication
+ * * \e string \b url_sig => URL signed with conversant's private key
*
- * @returns: array => 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']) {
@@ -554,8 +551,8 @@ function zot_gethub($arr) {
return null;
}
- $r = q("select * from hubloc
- where hubloc_guid = '%s' and hubloc_guid_sig = '%s'
+ $r = q("select * from hubloc
+ where hubloc_guid = '%s' and hubloc_guid_sig = '%s'
and hubloc_url = '%s' and hubloc_url_sig = '%s'
limit 1",
dbesc($arr['guid']),
@@ -569,30 +566,28 @@ function zot_gethub($arr) {
}
}
logger('zot_gethub: not found: ' . print_r($arr,true), LOGGER_DEBUG);
+
return null;
}
/**
- * @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 associative array which must contain:
+ * * \e string \b guid => guid of conversant
+ * * \e string \b guid_sig => guid signed with conversant's private key
+ * * \e string \b url => URL of the origination hub of this communication
+ * * \e string \b url_sig => URL signed with conversant's private key
*
- * @returns array => 'success' (boolean true or false)
- * 'message' (optional error string only if success is false)
+ * @returns array an associative 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);
@@ -612,8 +607,8 @@ function zot_register_hub($arr) {
if($x['success']) {
$record = json_decode($x['body'],true);
- /*
- * We now have a key - only continue registration if our signatures are valid
+ /*
+ * We now have a key - only continue registration if our signatures are valid
* AND the guid and guid sig in the returned packet match those provided in
* our current communication.
*/
@@ -629,18 +624,17 @@ function zot_register_hub($arr) {
}
else {
logger('zot_register_hub: failure to verify returned packet.');
- }
+ }
}
}
+
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
@@ -648,20 +642,19 @@ function zot_register_hub($arr) {
* this typically occurs once a month for each channel as part of a scheduled ping to notify the directory
* that the channel still exists
* @param array $ud_arr
- * If set [typically by update_directory_entry()] indicates a specific update table row and more particularly
+ * If set [typically by update_directory_entry()] indicates a specific update table row and more particularly
* contains a particular address (ud_addr) which needs to be updated in that table.
*
- * @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);
- $dirmode = intval(get_config('system','directory_mode'));
+ $dirmode = intval(get_config('system','directory_mode'));
$changed = false;
$what = '';
@@ -692,11 +685,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'],'/'));
@@ -705,14 +698,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');
+ $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']));
$hidden_changed = $adult_changed = $deleted_changed = $pubforum_changed = 0;
@@ -755,13 +747,12 @@ 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()))
+ if((($arr['site']['directory_mode'] === 'standalone')
+ || ($dirmode & DIRECTORY_MODE_STANDALONE))
+ && ($arr['site']['url'] != z_root()))
$arr['searchable'] = false;
$x = q("insert into xchan ( xchan_hash, xchan_guid, xchan_guid_sig, xchan_pubkey, xchan_photo_mimetype,
@@ -790,11 +781,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');
@@ -803,9 +792,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(
@@ -816,14 +805,13 @@ 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.
+ // This often happens when somebody joins the matrix with a bad cert.
$r = q("update xchan set xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s'
where xchan_hash = '%s'",
dbesc($photos[0]),
@@ -832,8 +820,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'])),
@@ -849,11 +836,10 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) {
}
}
- // what we are missing for true hub independence is for any changes in the primary hub to
+ // what we are missing for true hub independence is for any changes in the primary hub to
// get reflected not only in the hublocs, but also to update the URLs and addr in the appropriate xchan
-
- $s = sync_locations($arr,$arr);
+ $s = sync_locations($arr, $arr);
if($s) {
if($s['change_message'])
@@ -873,27 +859,25 @@ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) {
$other_realm = false;
$realm = get_directory_realm();
- if(array_key_exists('site',$arr)
- && array_key_exists('realm',$arr['site'])
+ if(array_key_exists('site',$arr)
+ && array_key_exists('realm',$arr['site'])
&& (strpos($arr['site']['realm'],$realm) === false))
$other_realm = true;
if($dirmode != DIRECTORY_MODE_NORMAL) {
// We're some kind of directory server. However we can only add directory information
- // if the entry is in the same realm (or is a sub-realm). Sub-realms are denoted by
- // including the parent realm in the name. e.g. 'RED_GLOBAL:foo' would allow an entry to
+ // if the entry is in the same realm (or is a sub-realm). Sub-realms are denoted by
+ // including the parent realm in the name. e.g. 'RED_GLOBAL:foo' would allow an entry to
// be in directories for the local realm (foo) and also the RED_GLOBAL realm.
-
if(array_key_exists('profile',$arr) && is_array($arr['profile']) && (! $other_realm)) {
$profile_changed = import_directory_profile($xchan_hash,$arr['profile'],$address,$ud_flags, 1);
if($profile_changed) {
$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'",
@@ -912,10 +896,9 @@ 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();
+ $guid = random_string() . '@' . get_app()->get_hostname();
update_modtime($xchan_hash,$guid,$address,$ud_flags);
logger('import_xchan: changed: ' . $what,LOGGER_DEBUG);
}
@@ -933,52 +916,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
+
+ 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'])
);
@@ -988,19 +971,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);
@@ -1023,41 +1007,46 @@ 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
- *
- * Process an incoming array of messages which were obtained via pickup, and
+ * @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);
+ $data = json_decode($arr['body'], true);
if(! $data) {
logger('zot_import: empty body');
return array();
}
- if(array_key_exists('iv',$data)) {
+ if(array_key_exists('iv', $data)) {
$data = json_decode(crypto_unencapsulate($data,get_config('system','prvkey')),true);
}
@@ -1080,7 +1069,7 @@ function zot_import($arr, $sender_url) {
logger('zot_import: notify: ' . print_r($i['notify'],true), LOGGER_DATA);
- $hub = zot_gethub($i['notify']['sender']);
+ $hub = zot_gethub($i['notify']['sender']);
if((! $hub) || ($hub['hubloc_url'] != $sender_url)) {
logger('zot_import: potential forgery: wrong site for sender: ' . $sender_url . ' != ' . print_r($i['notify'],true));
continue;
@@ -1116,16 +1105,16 @@ function zot_import($arr, $sender_url) {
continue;
}
- // It's a specifically targetted post. If we were sent a public_scope hint (likely),
- // get rid of it so that it doesn't get stored and cause trouble.
+ // It's a specifically targetted post. If we were sent a public_scope hint (likely),
+ // get rid of it so that it doesn't get stored and cause trouble.
- if(($i) && is_array($i) && array_key_exists('message',$i) && is_array($i['message'])
+ if(($i) && is_array($i) && array_key_exists('message',$i) && is_array($i['message'])
&& $i['message']['type'] === 'activity' && array_key_exists('public_scope',$i['message']))
unset($i['message']['public_scope']);
$deliveries = $r;
- // We found somebody on this site that's in the recipient list.
+ // We found somebody on this site that's in the recipient list.
}
else {
@@ -1137,7 +1126,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
@@ -1150,16 +1139,15 @@ function zot_import($arr, $sender_url) {
}
// if the scope is anything but 'public' we're going to store it as private regardless
- // of the private flag on the post.
+ // of the private flag on the post.
- if($i['message'] && array_key_exists('public_scope',$i['message'])
+ if($i['message'] && array_key_exists('public_scope',$i['message'])
&& $i['message']['public_scope'] !== 'public') {
- if(! array_key_exists('flags',$i['message']))
+ if(! array_key_exists('flags',$i['message']))
$i['message']['flags'] = array();
if(! in_array('private',$i['message']['flags']))
$i['message']['flags'][] = 'private';
-
}
}
@@ -1184,8 +1172,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']);
@@ -1199,7 +1187,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']);
@@ -1207,9 +1194,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']);
@@ -1218,9 +1203,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']);
@@ -1228,7 +1211,7 @@ function zot_import($arr, $sender_url) {
logger('Channel sync received: ' . print_r($arr,true), LOGGER_DATA);
logger('Channel sync recipients: ' . print_r($deliveries,true), LOGGER_DATA);
-
+
$result = process_channel_sync_delivery($i['notify']['sender'],$arr,$deliveries);
}
elseif($i['message']['type'] === 'location') {
@@ -1236,33 +1219,36 @@ function zot_import($arr, $sender_url) {
logger('Location message received: ' . print_r($arr,true), LOGGER_DATA);
logger('Location message recipients: ' . print_r($deliveries,true), LOGGER_DATA);
-
+
$result = process_location_delivery($i['notify']['sender'],$arr,$deliveries);
}
-
}
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, or PERMS_SITE and is one the same
-// site, or PERMS_SPECIFIC and the sender is a contact who is granted
-// permissions via their connection permissions in the address book.
-// Here we take a given message and construct a list of hashes of everybody
-// on the site that we should deliver to.
-
-
+/**
+ * @brief
+ *
+ * A public message with no listed recipients can be delivered to anybody who
+ * has PERMS_NETWORK for that type of post, PERMS_AUTHED (in-network senders are
+ * by definition authenticated) or PERMS_SITE and is one the same site,
+ * or PERMS_SPECIFIC and the sender is a contact who is granted permissions via
+ * their connection permissions in the address book.
+ * Here we take a given message and construct a list of hashes of everybody
+ * on the site that we should try and deliver to.
+ * Some of these will be rejected, but this gives us a place to start.
+ *
+ * @param array $msg
+ * @return NULL|array
+ */
function public_recips($msg) {
-
require_once('include/identity.php');
$check_mentions = false;
@@ -1277,11 +1263,31 @@ function public_recips($msg) {
$check_mentions = true;
}
else {
+
+ // This doesn't look like it works so I have to explain what happened. These are my
+ // notes (below) from when I got this section of code working. You would think that
+ // we only have to find those with the requisite stream or comment permissions,
+ // depending on whether this is a top-level post or a comment - but you would be wrong.
+
+ // ... so public_recips and allowed_public_recips is working so much better
+ // than before, but was still not quite right. We seem to be getting all the right
+ // results for top-level posts now, but comments aren't getting through on channels
+ // for which we've allowed them to send us their stream, but not comment on our posts.
+ // The reason is we were seeing if they could comment - and we only need to do that if
+ // we own the post. If they own the post, we only need to check if they can send us their stream.
+
// if this is a comment and it wasn't sent by the post owner, check to see who is allowing them to comment.
- // We should have one specific recipient and this step shouldn't be needed unless somebody stuffed up their software.
- // We may need this step to protect us from bad guys intentionally stuffing up their software.
- // If it is sent by the post owner, we don't need to do this. We only need to see who is receiving the
- // owner's stream (which was already set above) - as they control the comment permissions
+ // We should have one specific recipient and this step shouldn't be needed unless somebody stuffed up
+ // their software. We may need this step to protect us from bad guys intentionally stuffing up their software.
+ // If it is sent by the post owner, we don't need to do this. We only need to see who is receiving the
+ // owner's stream (which was already set above) - as they control the comment permissions, not us.
+
+ // Note that by doing this we introduce another bug because some public forums have channel_w_stream
+ // permissions set to themselves only. We also need in this function to add these public forums to the
+ // public recipient list based on if they are tagged or not and have tag permissions. This is complicated
+ // by the fact that this activity doesn't have the public forum tag. It's the parent activity that
+ // contains the tag. we'll solve that further below.
+
if($msg['notify']['sender']['guid_sig'] != $msg['message']['owner']['guid_sig']) {
$col = 'channel_w_comment';
$field = PERMS_W_COMMENT;
@@ -1296,23 +1302,40 @@ function public_recips($msg) {
if(! $col)
return NULL;
-
- if($msg['notify']['sender']['url'] === z_root())
- $sql = " where (( " . $col . " & " . PERMS_NETWORK . " )>0 or ( " . $col . " & " . PERMS_SITE . " )>0 or ( " . $col . " & " . PERMS_PUBLIC . ")>0) ";
- else
- $sql = " where (( " . $col . " & " . PERMS_NETWORK . " )>0 or ( " . $col . " & " . PERMS_PUBLIC . ")>0) ";
+ $col = dbesc($col);
+
+ // First find those channels who are accepting posts from anybody, or at least
+ // something greater than just their connections.
+ if($msg['notify']['sender']['url'] === z_root()) {
+ $sql = " where (( " . $col . " & " . intval(PERMS_NETWORK) . " ) > 0
+ or ( " . $col . " & " . intval(PERMS_SITE) . " ) > 0
+ or ( " . $col . " & " . intval(PERMS_PUBLIC) . ") > 0
+ or ( " . $col . " & " . intval(PERMS_AUTHED) . ") > 0 ) ";
+ } else {
+ $sql = " where (( " . $col . " & " . intval(PERMS_NETWORK) . " ) > 0
+ or ( " . $col . " & " . intval(PERMS_PUBLIC) . ") > 0
+ or ( " . $col . " & " . intval(PERMS_AUTHED) . ") > 0 ) ";
+ }
- $r = q("select channel_hash as hash from channel $sql or channel_hash = '%s' ",
+ $r = q("select channel_hash as hash from channel $sql or channel_hash = '%s'
+ and ( channel_pageflags & " . intval(PAGE_REMOVED) . " ) = 0 ",
dbesc($msg['notify']['sender']['hash'])
);
if(! $r)
$r = array();
- $x = q("select channel_hash as hash from channel left join abook on abook_channel = channel_id where abook_xchan = '%s' and not ( channel_pageflags & " . PAGE_REMOVED . " )>0 and (( " . $col . " & " . PERMS_SPECIFIC . " )>0 and ( abook_my_perms & " . $field . " )>0) OR ( " . $col . " & " . PERMS_PENDING . " )>0 OR (( " . $col . " & " . PERMS_CONTACTS . " )>0 and not ( abook_flags & " . ABOOK_FLAG_PENDING . " )>0) ",
+ // Now we have to get a bit dirty. Find every channel that has the sender in their connections (abook)
+ // and is allowing this sender at least at a high level.
+
+ $x = q("select channel_hash as hash from channel left join abook on abook_channel = channel_id
+ where abook_xchan = '%s' and ( channel_pageflags & " . intval(PAGE_REMOVED) . " ) = 0
+ and (( " . $col . " & " . intval(PERMS_SPECIFIC) . " ) > 0 and ( abook_my_perms & " . intval($field) . " ) > 0 )
+ OR ( " . $col . " & " . intval(PERMS_PENDING) . " ) > 0
+ OR (( " . $col . " & " . intval(PERMS_CONTACTS) . " ) > 0 and ( abook_flags & " . intval(ABOOK_FLAG_PENDING) . " ) = 0 ) ",
dbesc($msg['notify']['sender']['hash'])
- );
+ );
if(! $x)
$x = array();
@@ -1330,35 +1353,84 @@ function public_recips($msg) {
// look for any public mentions on this site
// They will get filtered by tgroup_check() so we don't need to check permissions now
- if($check_mentions && $msg['message']['tags']) {
- if(is_array($msg['message']['tags']) && $msg['message']['tags']) {
- foreach($msg['message']['tags'] as $tag) {
- if(($tag['type'] === 'mention') && (strpos($tag['url'],z_root()) !== false)) {
- $address = basename($tag['url']);
- if($address) {
- $z = q("select channel_hash as hash from channel where channel_address = '%s' limit 1",
- dbesc($address)
- );
- if($z)
- $r = array_merge($r,$z);
+ if($check_mentions) {
+ // It's a top level post. Look at the tags. See if any of them are mentions and are on this hub.
+ if($msg['message']['tags']) {
+ if(is_array($msg['message']['tags']) && $msg['message']['tags']) {
+ foreach($msg['message']['tags'] as $tag) {
+ if(($tag['type'] === 'mention') && (strpos($tag['url'],z_root()) !== false)) {
+ $address = basename($tag['url']);
+ if($address) {
+ $z = q("select channel_hash as hash from channel where channel_address = '%s' limit 1",
+ dbesc($address)
+ );
+ if($z)
+ $r = array_merge($r,$z);
+ }
}
}
}
}
}
+ else {
+ // This is a comment. We need to find any parent with ITEM_UPLINK set. But in fact, let's just return
+ // everybody that stored a copy of the parent. This way we know we're covered. We'll check the
+ // comment permissions when we deliver them.
+
+ if($msg['message']['message_top']) {
+ $z = q("select owner_xchan as hash from item where parent_mid = '%s' ",
+ dbesc($msg['message']['message_top']),
+ intval(ITEM_UPLINK)
+ );
+ if($z)
+ $r = array_merge($r,$z);
+ }
+ }
+
+ // There are probably a lot of duplicates in $r at this point. We need to filter those out.
+ // It's a bit of work since it's a multi-dimensional array
+
+ if($r) {
+ $uniq = array();
+
+ foreach($r as $rr) {
+ if(! in_array($rr['hash'],$uniq))
+ $uniq[] = $rr['hash'];
+ }
+ $r = array();
+ foreach($uniq as $rr) {
+ $r[] = array('hash' => $rr);
+ }
+ }
logger('public_recips: ' . print_r($r,true), LOGGER_DATA);
return $r;
}
-// This is the second part of the above function. We'll find all the channels willing to accept public posts from us,
-// then match them against the sender privacy scope and see who in that list that the sender is allowing.
-
+/**
+ * @brief
+ *
+ * This is the second part of public_recipes().
+ * We'll find all the channels willing to accept public posts from us, then
+ * match them against the sender privacy scope and see who in that list that
+ * the sender is allowing.
+ *
+ * @see public_recipes()
+ * @param array $msg
+ * @return array
+ */
function allowed_public_recips($msg) {
-
logger('allowed_public_recips: ' . print_r($msg,true),LOGGER_DATA);
+ if(array_key_exists('public_scope',$msg['message']))
+ $scope = $msg['message']['public_scope'];
+
+ // Mail won't have a public scope.
+ // in fact, it's doubtful mail will ever get here since it almost universally
+ // has a recipient, but in fact we don't require this, so it's technically
+ // possible to send mail to anybody that's listening.
+
$recips = public_recips($msg);
if(! $recips)
@@ -1367,11 +1439,6 @@ function allowed_public_recips($msg) {
if($msg['message']['type'] === 'mail')
return $recips;
- if(array_key_exists('public_scope',$msg['message']))
- $scope = $msg['message']['public_scope'];
-
- $hash = make_xchan_hash($msg['notify']['sender']['guid'],$msg['notify']['sender']['guid_sig']);
-
if($scope === 'public' || $scope === 'network: red' || $scope === 'authenticated')
return $recips;
@@ -1382,19 +1449,23 @@ function allowed_public_recips($msg) {
return array();
}
+ $hash = make_xchan_hash($msg['notify']['sender']['guid'],$msg['notify']['sender']['guid_sig']);
+
if($scope === 'self') {
foreach($recips as $r)
if($r['hash'] === $hash)
return array('hash' => $hash);
}
- if($scope === 'contacts') {
+ // note: we shouldn't ever see $scope === 'specific' in this function, but handle it anyway
+
+ if($scope === 'contacts' || $scope === 'any connections' || $scope === 'specific') {
$condensed_recips = array();
foreach($recips as $rr)
$condensed_recips[] = $rr['hash'];
$results = array();
- $r = q("select channel_hash as hash from channel left join abook on abook_channel = channel_id where abook_xchan = '%s' and not ( channel_pageflags & %d )>0 ",
+ $r = q("select channel_hash as hash from channel left join abook on abook_channel = channel_id where abook_xchan = '%s' and not ( channel_pageflags & %d ) > 0 ",
dbesc($hash),
intval(PAGE_REMOVED)
);
@@ -1409,12 +1480,21 @@ function allowed_public_recips($msg) {
return array();
}
-
-function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$request = false) {
+/**
+ * @brief
+ *
+ * @param array $sender
+ * @param array $arr
+ * @param array $deliveries
+ * @param boolean $relay
+ * @param boolean $public (optional) default false
+ * @param boolean $request (optional) default false
+ * @return array
+ */
+function process_delivery($sender, $arr, $deliveries, $relay, $public = false, $request = false) {
$result = array();
-
// We've validated the sender. Now make sure that the sender is the owner or author
if(! $public) {
@@ -1431,15 +1511,17 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque
);
if(! $r) {
- $result[] = array($d['hash'],'recipients not found');
+ $result[] = array($d['hash'], 'recipients not found');
continue;
}
-
$channel = $r[0];
- // allow public postings to the sys channel regardless of permissions
- if(($channel['channel_pageflags'] & PAGE_SYSTEM) && (! $arr['item_private'])) {
+ // allow public postings to the sys channel regardless of permissions, but not
+ // for comments travelling upstream. Wait and catch them on the way down.
+ // They may have been blocked by the owner.
+
+ if(($channel['channel_pageflags'] & PAGE_SYSTEM) && (! $arr['item_private']) && (! $relay)) {
$local_public = true;
$r = q("select xchan_selfcensored from xchan where xchan_hash = '%s' limit 1",
@@ -1478,7 +1560,7 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque
// We are only going to accept comments from this sender if the comment has the same route as the top-level-post,
// this is so that permissions mismatches between senders apply to the entire conversation
// As a side effect we will also do a preliminary check that we have the top-level-post, otherwise
- // processing it is pointless.
+ // processing it is pointless.
$r = q("select route, id from item where mid = '%s' and uid = %d limit 1",
dbesc($arr['parent_mid']),
@@ -1487,21 +1569,21 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque
if(! $r) {
$result[] = array($d['hash'],'comment parent not found',$channel['channel_name'] . ' <' . $channel['channel_address'] . '@' . get_app()->get_hostname() . '>',$arr['mid']);
- // We don't seem to have a copy of this conversation or at least the parent
+ // We don't seem to have a copy of this conversation or at least the parent
// - so request a copy of the entire conversation to date.
- // Don't do this if it's a relay post as we're the ones who are supposed to
+ // Don't do this if it's a relay post as we're the ones who are supposed to
// have the copy and we don't want the request to loop.
// Also don't do this if this comment came from a conversation request packet.
// It's possible that comments are allowed but posting isn't and that could
- // cause a conversation fetch loop. We can detect these packets since they are
- // delivered via a 'notify' packet type that has a message_id element in the
- // initial zot packet (just like the corresponding 'request' packet type which
+ // cause a conversation fetch loop. We can detect these packets since they are
+ // delivered via a 'notify' packet type that has a message_id element in the
+ // initial zot packet (just like the corresponding 'request' packet type which
// makes the request).
// We'll also check the send_stream permission - because if it isn't allowed,
// the top level post is unlikely to be imported and
- // this is just an exercise in futility.
+ // this is just an exercise in futility.
- if((! $relay) && (! $request) && (! $local_public)
+ if((! $relay) && (! $request) && (! $local_public)
&& perm_is_allowed($channel['channel_id'],$sender['hash'],'send_stream')) {
proc_run('php', 'include/notifier.php', 'request', $channel['channel_id'], $sender['hash'], $arr['parent_mid']);
}
@@ -1519,7 +1601,7 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque
// sent it to us originally. Ignore it if it came from another source
// (with potentially different permissions).
// only compare the last hop since it could have arrived at the last location any number of ways.
- // Always accept empty routes and firehose items (route contains 'undefined') .
+ // Always accept empty routes and firehose items (route contains 'undefined') .
$existing_route = explode(',', $r[0]['route']);
$routes = count($existing_route);
@@ -1531,7 +1613,7 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque
$last_hop = '';
$last_prior_route = '';
}
-
+
if(in_array('undefined',$existing_route) || $last_hop == 'undefined' || $sender['hash'] == 'undefined')
$last_hop = '';
@@ -1544,7 +1626,7 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque
continue;
}
- // we'll add sender['hash'] onto this when we deliver it. $last_prior_route now has the previously stored route
+ // we'll add sender['hash'] onto this when we deliver it. $last_prior_route now has the previously stored route
// *except* for the sender['hash'] which would've been the last hop before it got to us.
$arr['route'] = $last_prior_route;
@@ -1556,7 +1638,13 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque
// remove_community_tag is a no-op if this isn't a community tag activity
remove_community_tag($sender,$arr,$channel['channel_id']);
- $item_id = delete_imported_item($sender,$arr,$channel['channel_id']);
+ // set these just in case we need to store a fresh copy of the deleted post.
+ // This could happen if the delete got here before the original post did.
+
+ $arr['aid'] = $channel['channel_account_id'];
+ $arr['uid'] = $channel['channel_id'];
+
+ $item_id = delete_imported_item($sender,$arr,$channel['channel_id'],$relay);
$result[] = array($d['hash'],(($item_id) ? 'deleted' : 'delete_failed'),$channel['channel_name'] . ' <' . $channel['channel_address'] . '@' . get_app()->get_hostname() . '>',$arr['mid']);
if($relay && $item_id) {
@@ -1575,12 +1663,13 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque
if($r) {
// We already have this post.
$item_id = $r[0]['id'];
+
if(intval($r[0]['item_deleted'])) {
// It was deleted locally.
$result[] = array($d['hash'],'update ignored',$channel['channel_name'] . ' <' . $channel['channel_address'] . '@' . get_app()->get_hostname() . '>',$arr['mid']);
continue;
- }
- // Maybe it has been edited?
+ }
+ // Maybe it has been edited?
elseif($arr['edited'] > $r[0]['edited']) {
$arr['id'] = $r[0]['id'];
$arr['uid'] = $channel['channel_id'];
@@ -1591,6 +1680,7 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque
}
else {
$result[] = array($d['hash'],'update ignored',$channel['channel_name'] . ' <' . $channel['channel_address'] . '@' . get_app()->get_hostname() . '>',$arr['mid']);
+
// We need this line to ensure wall-to-wall comments are relayed (by falling through to the relay bit),
// and at the same time not relay any other relayable posts more than once, because to do so is very wasteful.
if(! intval($r[0]['item_origin']))
@@ -1600,6 +1690,13 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque
else {
$arr['aid'] = $channel['channel_account_id'];
$arr['uid'] = $channel['channel_id'];
+
+ // if it's a sourced post, call the post_local hooks as if it were
+ // posted locally so that crosspost connectors will be triggered.
+
+ if(check_item_source($arr['uid'], $arr))
+ call_hooks('post_local', $arr);
+
$item_result = item_store($arr);
$item_id = 0;
if($item_result['success']) {
@@ -1621,21 +1718,30 @@ function process_delivery($sender,$arr,$deliveries,$relay,$public = false,$reque
}
if(! $deliveries)
- $result[] = array('','no recipients','',$arr['mid']);
+ $result[] = array('', 'no recipients', '', $arr['mid']);
- logger('process_delivery: local results: ' . print_r($result,true), LOGGER_DEBUG);
+ logger('process_delivery: local results: ' . print_r($result, true), LOGGER_DEBUG);
return $result;
}
+/**
+ * @brief
+ *
+ * @param array $sender an associative array with
+ * * \e string \b hash a xchan_hash
+ * @param array $arr an associative array
+ * * \e int \b verb
+ * * \e int \b obj_type
+ * * \e int \b mid
+ * @param int $uid
+ */
+function remove_community_tag($sender, $arr, $uid) {
-function remove_community_tag($sender,$arr,$uid) {
-
- if(! (activity_match($arr['verb'],ACTIVITY_TAG) && ($arr['obj_type'] == ACTIVITY_OBJ_TAGTERM)))
+ if(! (activity_match($arr['verb'], ACTIVITY_TAG) && ($arr['obj_type'] == ACTIVITY_OBJ_TAGTERM)))
return;
logger('remove_community_tag: invoked');
-
if(! get_pconfig($uid,'system','blocktags')) {
logger('remove_community tag: permission denied.');
@@ -1678,8 +1784,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),
@@ -1687,23 +1793,43 @@ 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) {
+/**
+ * @brief Just calls item_store_update() and logs result.
+ *
+ * @see item_store_update()
+ * @param array $sender (unused)
+ * @param array $item
+ * @param int $uid (unused)
+ */
+function update_imported_item($sender, $item, $uid) {
$x = item_store_update($item);
if(! $x['item_id'])
logger('update_imported_item: failed: ' . $x['message']);
else
logger('update_imported_item');
-
}
-function delete_imported_item($sender,$item,$uid) {
+/**
+ * @brief Deletes an imported item.
+ *
+ * @param array $sender
+ * * \e string \b hash a xchan_hash
+ * @param array $item
+ * @param int $uid
+ * @param boolean $relay
+ * @return boolean|int post_id
+ */
+function delete_imported_item($sender, $item, $uid, $relay) {
+
+ logger('delete_imported_item invoked', LOGGER_DEBUG);
+
+ $ownership_valid = false;
+ $item_found = false;
+ $post_id = 0;
- logger('delete_imported_item invoked',LOGGER_DEBUG);
$r = q("select id, item_deleted from item where ( author_xchan = '%s' or owner_xchan = '%s' or source_xchan = '%s' )
and mid = '%s' and uid = %d limit 1",
@@ -1713,42 +1839,78 @@ function delete_imported_item($sender,$item,$uid) {
dbesc($item['mid']),
intval($uid)
);
+ if ($r) {
+ if ($r[0]['author_xchan'] === $sender['hash'] || $r[0]['owner_xchan'] === $sender['hash'] || $r[0]['source_xchan'] === $sender['hash'])
+ $ownership_valid = true;
- if(! $r) {
+ $post_id = $r[0]['id'];
+ $item_found = true;
+ } 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.
+ // This means we won't end up with potentially even more delivery threads trying to push this delete notification.
+ // But this will ensure that if the (undeleted) original post comes in at a later date, we'll reject it because it will have an older timestamp.
+
+ logger('delete received for non-existent item - storing item data.');
+
+ /** @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) {
logger('delete_imported_item: failed: ownership issue');
return false;
}
- if(intval($r[0]['item_deleted'])) {
- logger('delete_imported_item: item was already deleted');
- return false;
- }
-
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).
+ if ($item_found) {
+ if (intval($r[0]['item_deleted'])) {
+ logger('delete_imported_item: item was already deleted');
+ if (! $relay)
+ return false;
+
+ // This is a bit hackish, but may have to suffice until the notification/delivery loop is optimised
+ // a bit further. We're going to strip the ITEM_ORIGIN on this item if it's a comment, because
+ // it was already deleted, and we're already relaying, and this ensures that no other process or
+ // code path downstream can relay it again (causing a loop). Since it's already gone it's not coming
+ // back, and we aren't going to (or shouldn't at any rate) delete it again in the future - so losing
+ // this information from the metadata should have no other discernible impact.
+
+ if (($r[0]['id'] != $r[0]['parent']) && intval($r[0]['item_origin'])) {
+ q("update item set item_origin = 0 where id = %d and uid = %d",
+ intval($r[0]['id']),
+ intval($r[0]['uid'])
+ );
+ }
+ }
- drop_item($r[0]['id'],false, DROPITEM_PHASE1);
+ require_once('include/items.php');
- tag_deliver($uid,$r[0]['id']);
+ // 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).
- return $r[0]['id'];
-}
+ drop_item($post_id, false, DROPITEM_PHASE1);
+ tag_deliver($uid, $post_id);
+ }
-function process_mail_delivery($sender,$arr,$deliveries) {
+ return $post_id;
+}
+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'])
@@ -1766,7 +1928,7 @@ function process_mail_delivery($sender,$arr,$deliveries) {
$result[] = array($d['hash'],'permission denied',$channel['channel_name'],$arr['mid']);
continue;
}
-
+
$r = q("select id from mail where mid = '%s' and channel_id = %d limit 1",
dbesc($arr['mid']),
intval($channel['channel_id'])
@@ -1780,7 +1942,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');
}
@@ -1791,13 +1953,20 @@ function process_mail_delivery($sender,$arr,$deliveries) {
$arr['channel_id'] = $channel['channel_id'];
$item_id = mail_store($arr);
$result[] = array($d['hash'],'mail delivered',$channel['channel_name'],$arr['mid']);
-
}
}
+
return $result;
}
-function process_rating_delivery($sender,$arr) {
+/**
+ * @brief Processes delivery of rating.
+ *
+ * @param array $sender
+ * * \e string \b hash a xchan_hash
+ * @param array $arr
+ */
+function process_rating_delivery($sender, $arr) {
logger('process_rating_delivery: ' . print_r($arr,true));
@@ -1808,7 +1977,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;
@@ -1817,8 +1985,8 @@ function process_rating_delivery($sender,$arr) {
$r = q("select * from xlink where xlink_xchan = '%s' and xlink_link = '%s' and xlink_static = 1 limit 1",
dbesc($sender['hash']),
dbesc($arr['target'])
- );
-
+ );
+
if($r) {
if($r[0]['xlink_updated'] >= $arr['edited']) {
logger('rating message duplicate');
@@ -1836,7 +2004,7 @@ function process_rating_delivery($sender,$arr) {
}
else {
$x = q("insert into xlink ( xlink_xchan, xlink_link, xlink_rating, xlink_rating_text, xlink_sig, xlink_updated, xlink_static )
- values( '%s', '%s', %d, '%s', '%s', 1 ) ",
+ values( '%s', '%s', %d, '%s', '%s', '%s', 1 ) ",
dbesc($sender['hash']),
dbesc($arr['target']),
intval($arr['rating']),
@@ -1846,11 +2014,18 @@ function process_rating_delivery($sender,$arr) {
);
logger('rating created');
}
- return;
}
-
-function process_profile_delivery($sender,$arr,$deliveries) {
+/**
+ * @brief Processes delivery of profile.
+ *
+ * @see import_directory_profile()
+ * @param array $sender an associative array
+ * * \e string \b hash a xchan_hash
+ * @param array $arr
+ * @param array $deliveries (unused)
+ */
+function process_profile_delivery($sender, $arr, $deliveries) {
logger('process_profile_delivery', LOGGER_DEBUG);
@@ -1858,7 +2033,7 @@ function process_profile_delivery($sender,$arr,$deliveries) {
dbesc($sender['hash'])
);
if($r)
- import_directory_profile($sender['hash'],$arr,$r[0]['xchan_addr'], UPDATE_FLAGS_UPDATED, 0);
+ import_directory_profile($sender['hash'], $arr, $r[0]['xchan_addr'], UPDATE_FLAGS_UPDATED, 0);
}
function process_location_delivery($sender,$arr,$deliveries) {
@@ -1871,18 +2046,26 @@ function process_location_delivery($sender,$arr,$deliveries) {
);
if($r)
$sender['key'] = $r[0]['xchan_pubkey'];
+
if(array_key_exists('locations',$arr) && $arr['locations']) {
$x = sync_locations($sender,$arr,true);
logger('process_location_delivery: results: ' . print_r($x,true), LOGGER_DEBUG);
if($x['changed']) {
- $guid = random_string() . '@' . get_app()->get_hostname();
+ $guid = random_string() . '@' . get_app()->get_hostname();
update_modtime($sender['hash'],$sender['guid'],$arr['locations'][0]['address'],UPDATE_FLAGS_UPDATED);
}
}
}
-
-function sync_locations($sender,$arr,$absolute = false) {
+/**
+ * @brief Synchronises locations.
+ *
+ * @param array $sender
+ * @param array $arr
+ * @param boolean $absolute (optional) default false
+ * @return array
+ */
+function sync_locations($sender, $arr, $absolute = false) {
$ret = array();
@@ -1914,9 +2097,8 @@ function sync_locations($sender,$arr,$absolute = false) {
continue;
}
-
for($x = 0; $x < count($xisting); $x ++) {
- if(($xisting[$x]['hubloc_url'] === $location['url'])
+ if(($xisting[$x]['hubloc_url'] === $location['url'])
&& ($xisting[$x]['hubloc_sitekey'] === $location['sitekey'])) {
$xisting[$x]['updated'] = true;
}
@@ -1932,7 +2114,7 @@ function sync_locations($sender,$arr,$absolute = false) {
if(strpos($location['address'],'/') !== false)
$location['address'] = substr($location['address'],0,strpos($location['address'],'/'));
- // match as many fields as possible in case anything at all changed.
+ // match as many fields as possible in case anything at all changed.
$r = q("select * from hubloc where hubloc_hash = '%s' and hubloc_guid = '%s' and hubloc_guid_sig = '%s' and hubloc_url = '%s' and hubloc_url_sig = '%s' and hubloc_host = '%s' and hubloc_addr = '%s' and hubloc_callback = '%s' and hubloc_sitekey = '%s' ",
dbesc($sender['hash']),
@@ -1951,19 +2133,18 @@ function sync_locations($sender,$arr,$absolute = false) {
// update connection timestamp if this is the site we're talking to
// This only happens when called from import_xchan
+ $current_site = false;
+
if(array_key_exists('site',$arr) && $location['url'] == $arr['site']['url']) {
q("update hubloc set hubloc_connected = '%s', hubloc_updated = '%s' where hubloc_id = %d",
dbesc(datetime_convert()),
dbesc(datetime_convert()),
intval($r[0]['hubloc_id'])
);
+ $current_site = true;
}
-
- // if it's marked offline/dead, bring it back
- // Should we do this? It's basically saying that the channel knows better than
- // the directory server if the site is alive.
- if($r[0]['hubloc_error']) {
+ if($current_site && intval($r[0]['hubloc_error'])) {
q("update hubloc set hubloc_error = 0 where hubloc_id = %d",
intval($r[0]['hubloc_id'])
);
@@ -1975,7 +2156,7 @@ function sync_locations($sender,$arr,$absolute = false) {
q("update xchan set xchan_orphan = 0 where xchan_orphan = 1 and xchan_hash = '%s'",
dbesc($sender['hash'])
);
- }
+ }
// Remove pure duplicates
if(count($r) > 1) {
@@ -2037,7 +2218,7 @@ function sync_locations($sender,$arr,$absolute = false) {
continue;
}
- // Existing hubs are dealt with. Now let's process any new ones.
+ // Existing hubs are dealt with. Now let's process any new ones.
// New hub claiming to be primary. Make it so by removing any existing primaries.
if(intval($location['primary'])) {
@@ -2073,7 +2254,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.
@@ -2097,14 +2278,21 @@ 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 associative array which must contain
+ * * \e string \b channel_hash the hash of the channel
+ * @return array an array with associative arrays
+ */
function zot_encode_locations($channel) {
$ret = array();
$x = zot_get_hublocs($channel['channel_hash']);
+
if($x && count($x)) {
foreach($x as $hub) {
$ret[] = array(
@@ -2119,24 +2307,24 @@ function zot_encode_locations($channel) {
);
}
}
+
return $ret;
}
-
-
-
-
-/*
- * @function import_directory_profile
- *
- * @returns boolean $updated if something changed
+/**
+ * @brief Imports a directory profile.
*
+ * @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();
@@ -2157,11 +2345,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;
}
}
@@ -2169,7 +2357,7 @@ function import_directory_profile($hash,$profile,$addr,$ud_flags = UPDATE_FLAGS_
$arr['xprof_keywords'] = implode(' ',$clean);
// Self censored, make it so
- // These are not translated, so the German "erwachsenen" keyword will not censor the directory profile. Only the English form - "adult".
+ // These are not translated, so the German "erwachsenen" keyword will not censor the directory profile. Only the English form - "adult".
if(in_arrayi('nsfw',$clean) || in_arrayi('adult',$clean)) {
@@ -2178,30 +2366,35 @@ function import_directory_profile($hash,$profile,$addr,$ud_flags = UPDATE_FLAGS_
);
}
-
$r = q("select * from xprof where xprof_hash = '%s' limit 1",
dbesc($hash)
);
- if($r) {
+
+ if ($arr['xprof_age'] > 150)
+ $arr['xprof_age'] = 150;
+ if ($arr['xprof_age'] < 0)
+ $arr['xprof_age'] = 0;
+
+ if ($r) {
$update = false;
- foreach($r[0] as $k => $v) {
- 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
- xprof_desc = '%s',
- xprof_dob = '%s',
+ if ($update) {
+ q("update xprof set
+ xprof_desc = '%s',
+ xprof_dob = '%s',
xprof_age = %d,
- xprof_gender = '%s',
- xprof_marital = '%s',
- xprof_sexual = '%s',
- xprof_locale = '%s',
- xprof_region = '%s',
- xprof_postcode = '%s',
+ xprof_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',
@@ -2225,11 +2418,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']),
@@ -2251,12 +2443,19 @@ 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'];
}
-function import_directory_keywords($hash,$keywords) {
+/**
+ * @brief
+ *
+ * @param string $hash
+ * @param array $keywords
+ */
+function import_directory_keywords($hash, $keywords) {
$existing = array();
$r = q("select * from xtag where xtag_hash = '%s'",
@@ -2270,31 +2469,39 @@ function import_directory_keywords($hash,$keywords) {
$clean = array();
foreach($keywords as $kw) {
- $kw = trim(htmlspecialchars($kw,ENT_COMPAT,'UTF-8',false));
- $kw = trim($kw,',');
+ $kw = trim(htmlspecialchars($kw,ENT_COMPAT, 'UTF-8', false));
+ $kw = trim($kw, ',');
$clean[] = $kw;
}
foreach($existing as $x) {
- if(! in_array($x,$clean))
+ if(! in_array($x, $clean))
$r = q("delete from xtag where xtag_hash = '%s' and xtag_term = '%s'",
dbesc($hash),
dbesc($x)
);
}
foreach($clean as $x) {
- if(! in_array($x,$existing))
+ if(! in_array($x, $existing)) {
$r = q("insert into xtag ( xtag_hash, xtag_term) values ( '%s' ,'%s' )",
dbesc($hash),
dbesc($x)
);
+ }
}
}
+/**
+ * @brief
+ *
+ * @param string $hash
+ * @param string $guid
+ * @param string $addr
+ * @param int $flags (optional) default 0
+ */
+function update_modtime($hash, $guid, $addr, $flags = 0) {
-function update_modtime($hash,$guid,$addr,$flags = 0) {
-
- $dirmode = intval(get_config('system','directory_mode'));
+ $dirmode = intval(get_config('system', 'directory_mode'));
if($dirmode == DIRECTORY_MODE_NORMAL)
return;
@@ -2317,12 +2524,18 @@ function update_modtime($hash,$guid,$addr,$flags = 0) {
}
}
-
-function import_site($arr,$pubkey) {
+/**
+ * @brief
+ *
+ * @param array $arr
+ * @param string $pubkey
+ * @return boolean true if updated or inserted
+ */
+function import_site($arr, $pubkey) {
if( (! is_array($arr)) || (! $arr['url']) || (! $arr['url_sig']))
return false;
- if(! rsa_verify($arr['url'],base64url_decode($arr['url_sig']),$pubkey)) {
+ if(! rsa_verify($arr['url'], base64url_decode($arr['url_sig']), $pubkey)) {
logger('import_site: bad url_sig');
return false;
}
@@ -2341,7 +2554,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')
@@ -2379,13 +2591,23 @@ 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($arr['url'],ENT_COMPAT,'UTF-8',false);
+ $url = htmlspecialchars(strtolower($arr['url']),ENT_COMPAT,'UTF-8',false);
$sellpage = htmlspecialchars($arr['sellpage'],ENT_COMPAT,'UTF-8',false);
$site_location = htmlspecialchars($arr['location'],ENT_COMPAT,'UTF-8',false);
$site_realm = htmlspecialchars($arr['realm'],ENT_COMPAT,'UTF-8',false);
+ // You can have one and only one primary directory per realm.
+ // Downgrade any others claiming to be primary. As they have
+ // flubbed up this badly already, don't let them be directory servers at all.
+
+ if(($site_directory === DIRECTORY_MODE_PRIMARY)
+ && ($site_realm === get_directory_realm())
+ && ($arr['url'] != get_directory_primary())) {
+ $site_directory = DIRECTORY_MODE_NORMAL;
+ }
+
if($exists) {
if(($siterecord['site_flags'] != $site_directory)
|| ($siterecord['site_access'] != $access_policy)
@@ -2415,6 +2637,13 @@ function import_site($arr,$pubkey) {
logger('import_site: update failed. ' . print_r($arr,true));
}
}
+ else {
+ // update the timestamp to indicate we communicated with this site
+ q("update site set site_update = '%s' where site_url = '%s'",
+ dbesc(datetime_convert()),
+ dbesc($url)
+ );
+ }
}
else {
$update = true;
@@ -2436,16 +2665,17 @@ 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.
+ *
+ * @param int $uid
+ * @param array $packet (optional) default null
+ * @param boolean $groups_changed (optional) default false
*/
-
function build_sync_packet($uid = 0, $packet = null, $groups_changed = false) {
$a = get_app();
@@ -2453,7 +2683,7 @@ function build_sync_packet($uid = 0, $packet = null, $groups_changed = false) {
logger('build_sync_packet');
if($packet)
- logger('packet: ' . print_r($packet,true),LOGGER_DATA);
+ logger('packet: ' . print_r($packet, true),LOGGER_DATA);
if(! $uid)
$uid = local_channel();
@@ -2481,6 +2711,7 @@ function build_sync_packet($uid = 0, $packet = null, $groups_changed = false) {
foreach($h as $x) {
if($x['hubloc_host'] == $a->get_hostname())
continue;
+
$synchubs[] = $x;
}
@@ -2506,7 +2737,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) {
@@ -2538,10 +2769,9 @@ function build_sync_packet($uid = 0, $packet = null, $groups_changed = false) {
);
if($r)
$info['collection_members'] = $r;
-
}
- $interval = ((get_config('system','delivery_interval') !== false)
+ $interval = ((get_config('system','delivery_interval') !== false)
? intval(get_config('system','delivery_interval')) : 2 );
@@ -2563,27 +2793,32 @@ function build_sync_packet($uid = 0, $packet = null, $groups_changed = false) {
dbesc(json_encode($info))
);
- proc_run('php','include/deliver.php',$hash);
+ proc_run('php', 'include/deliver.php', $hash);
if($interval)
@time_sleep_until(microtime(true) + (float) $interval);
}
-
-
}
-function process_channel_sync_delivery($sender,$arr,$deliveries) {
-
-// FIXME - this will sync red structures (channel, pconfig and abook). Eventually we need to make this application agnostic.
+/**
+ * @brief
+ *
+ * @param array $sender
+ * @param array $arr
+ * @param array $deliveries
+ * @return array
+ */
+function process_channel_sync_delivery($sender, $arr, $deliveries) {
+ /** @FIXME this will sync red structures (channel, pconfig and abook). Eventually we need to make this application agnostic. */
$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;
}
@@ -2593,7 +2828,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'],'');
@@ -2618,14 +2852,12 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) {
}
if(count($clean)) {
foreach($clean as $k => $v) {
- $r = dbq("UPDATE channel set " . dbesc($k) . " = '" . dbesc($v)
+ $r = dbq("UPDATE channel set " . dbesc($k) . " = '" . dbesc($v)
. "' where channel_id = " . intval($channel['channel_id']) );
}
}
}
-
-
if(array_key_exists('abook',$arr) && is_array($arr['abook']) && count($arr['abook'])) {
$total_friends = 0;
$total_feeds = 0;
@@ -2649,7 +2881,7 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) {
if($abook['abook_xchan'] && $abook['entry_deleted']) {
logger('process_channel_sync_delivery: removing abook entry for ' . $abook['abook_xchan']);
require_once('include/Contact.php');
-
+
$r = q("select abook_id, abook_flags from abook where abook_xchan = '%s' and abook_channel = %d and not ( abook_flags & %d )>0 limit 1",
dbesc($abook['abook_xchan']),
intval($channel['channel_id']),
@@ -2714,7 +2946,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']),
@@ -2723,11 +2955,14 @@ 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) {
- $r = dbq("UPDATE abook set " . dbesc($k) . " = '" . dbesc($v)
+ if($k == 'abook_dob')
+ $v = dbescdate($v);
+
+ $r = dbq("UPDATE abook set " . dbesc($k) . " = '" . dbesc($v)
. "' where abook_xchan = '" . dbesc($clean['abook_xchan']) . "' and abook_channel = " . intval($channel['channel_id']));
}
}
@@ -2750,8 +2985,8 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) {
}
}
if($found) {
- if(($y['name'] != $cl['name'])
- || ($y['visible'] != $cl['visible'])
+ if(($y['name'] != $cl['name'])
+ || ($y['visible'] != $cl['visible'])
|| ($y['deleted'] != $cl['deleted'])) {
q("update groups set name = '%s', visible = %d, deleted = %d where hash = '%s' and uid = %d",
dbesc($cl['name']),
@@ -2764,7 +2999,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'])
- );
+ );
}
}
}
@@ -2792,10 +3027,10 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) {
break;
}
}
- if(! $found_local) {
+ if(! $found_local) {
q("delete from group_member where gid = %d",
intval($y['id'])
- );
+ );
q("update groups set deleted = 1 where id = %d and uid = %d",
intval($y['id']),
intval($channel['channel_id'])
@@ -2812,15 +3047,17 @@ function process_channel_sync_delivery($sender,$arr,$deliveries) {
// now sync the members
- if(array_key_exists('collection_members',$arr) &&
- is_array($arr['collection_members']) && count($arr['collection_members'])) {
+ if(array_key_exists('collection_members', $arr)
+ && is_array($arr['collection_members'])
+ && count($arr['collection_members'])) {
// first sort into groups keyed by the group hash
$members = array();
foreach($arr['collection_members'] as $cm) {
if(! array_key_exists($cm['collection'],$members))
$members[$cm['collection']] = array();
- $members[$cm['collection']][] = $cm['member'];
+
+ $members[$cm['collection']][] = $cm['member'];
}
// our group list is already synchronised
@@ -2884,7 +3121,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",
@@ -2898,83 +3135,102 @@ 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) {
- $r = dbq("UPDATE profile set " . dbesc($k) . " = '" . dbesc($v)
+ $r = dbq("UPDATE profile set " . dbesc($k) . " = '" . dbesc($v)
. "' where profile_guid = '" . dbesc($profile['profile_guid']) . "' and uid = " . intval($channel['channel_id']));
}
}
}
}
-
- $result[] = array($d['hash'],'channel sync updated',$channel['channel_name'],'');
-
+ $result[] = array($d['hash'],'channel sync updated',$channel['channel_name'],'');
}
+
return $result;
}
-// We probably should make rpost discoverable.
-
+/**
+ * @brief Returns path to /rpost
+ *
+ * @todo We probably should make rpost discoverable.
+ *
+ * @param array $observer
+ * * \e string \b xchan_url
+ * @return string
+ */
function get_rpost_path($observer) {
if(! $observer)
return '';
+
$parsed = parse_url($observer['xchan_url']);
- return $parsed['scheme'] . '://' . $parsed['host'] . (($parsed['port']) ? ':' . $parsed['port'] : '') . '/rpost?f=';
+ return $parsed['scheme'] . '://' . $parsed['host'] . (($parsed['port']) ? ':' . $parsed['port'] : '') . '/rpost?f=';
}
+/**
+ * @brief
+ *
+ * @param array $x
+ * @return boolean|string return false or a hash
+ */
function import_author_zot($x) {
+
$hash = make_xchan_hash($x['guid'],$x['guid_sig']);
$r = q("select hubloc_url from hubloc where hubloc_guid = '%s' and hubloc_guid_sig = '%s' and hubloc_primary = 1 limit 1",
dbesc($x['guid']),
dbesc($x['guid_sig'])
);
- 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.
*
- * include/deliver.php (for local delivery) and mod/post.php (for web delivery) detect the existence of
- * this 'message_list' at the destination and split it into individual messages which are
- * processed/delivered in order.
- *
+ * include/deliver.php (for local delivery) and mod/post.php (for web delivery) detect the existence of
+ * this 'message_list' at the destination and split it into individual messages which are
+ * processed/delivered in order.
+ *
* Called from mod/post.php
- */
-
-
+ *
+ * @param array $data
+ * @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)
@@ -2985,7 +3241,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;
@@ -2997,27 +3253,25 @@ 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 * from hubloc where hubloc_hash = '%s' and not hubloc_error and not hubloc_deleted
group by hubloc_sitekey",
dbesc($sender_hash)
);
- 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();
@@ -3026,8 +3280,8 @@ function zot_process_message_request($data) {
*/
$n = zot_build_packet($c[0],'notify',$env_recips,(($private) ? $hub['hubloc_sitekey'] : null),$hash,array('message_id' => $data['message_id']));
- q("insert into outq ( outq_hash, outq_account, outq_channel, outq_driver, outq_posturl, outq_async,
- outq_created, outq_updated, outq_notify, outq_msg )
+ q("insert into outq ( outq_hash, outq_account, outq_channel, outq_driver, outq_posturl, outq_async,
+ outq_created, outq_updated, outq_notify, outq_msg )
values ( '%s', %d, %d, '%s', '%s', %d, '%s', '%s', '%s', '%s' )",
dbesc($hash),
intval($c[0]['channel_account_id']),
@@ -3045,10 +3299,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;
}