1
1
Fork 0

Merge pull request #3112 from Quix0r/rewrites/coding-convention

Coding convention applied - part 1
This commit is contained in:
Hypolite Petovan 2017-03-21 10:19:53 -04:00 committed by GitHub
commit 9c2c483996
181 changed files with 4338 additions and 3507 deletions

407
boot.php

File diff suppressed because it is too large Load diff

View file

@ -5,7 +5,7 @@
// authorisation to do this. // authorisation to do this.
function user_remove($uid) { function user_remove($uid) {
if(! $uid) if (! $uid)
return; return;
logger('Removing user: ' . $uid); logger('Removing user: ' . $uid);
@ -49,7 +49,7 @@ function user_remove($uid) {
// Send an update to the directory // Send an update to the directory
proc_run(PRIORITY_LOW, "include/directory.php", $r[0]['url']); proc_run(PRIORITY_LOW, "include/directory.php", $r[0]['url']);
if($uid == local_user()) { if ($uid == local_user()) {
unset($_SESSION['authenticated']); unset($_SESSION['authenticated']);
unset($_SESSION['uid']); unset($_SESSION['uid']);
goaway(App::get_baseurl()); goaway(App::get_baseurl());
@ -122,11 +122,13 @@ function terminate_friendship($user,$self,$contact) {
// This provides for the possibility that their database is temporarily messed // This provides for the possibility that their database is temporarily messed
// up or some other transient event and that there's a possibility we could recover from it. // up or some other transient event and that there's a possibility we could recover from it.
function mark_for_death($contact) { function mark_for_death(array $contact) {
if($contact['archive']) if ($contact['archive']) {
return; return;
}
/// @TODO Comparison of strings this way may lead to bugs/incompatibility, better switch to DateTime
if ($contact['term-date'] <= NULL_DATE) { if ($contact['term-date'] <= NULL_DATE) {
q("UPDATE `contact` SET `term-date` = '%s' WHERE `id` = %d", q("UPDATE `contact` SET `term-date` = '%s' WHERE `id` = %d",
dbesc(datetime_convert()), dbesc(datetime_convert()),
@ -151,7 +153,7 @@ function mark_for_death($contact) {
/// Check for contact vitality via probing /// Check for contact vitality via probing
$expiry = $contact['term-date'] . ' + 32 days '; $expiry = $contact['term-date'] . ' + 32 days ';
if(datetime_convert() > datetime_convert('UTC','UTC',$expiry)) { if (datetime_convert() > datetime_convert('UTC','UTC',$expiry)) {
// relationship is really truly dead. // relationship is really truly dead.
// archive them rather than delete // archive them rather than delete
@ -483,7 +485,7 @@ function random_profile() {
function contacts_not_grouped($uid,$start = 0,$count = 0) { function contacts_not_grouped($uid,$start = 0,$count = 0) {
if(! $count) { if (! $count) {
$r = q("select count(*) as total from contact where uid = %d and self = 0 and id not in (select distinct(`contact-id`) from group_member where uid = %d) ", $r = q("select count(*) as total from contact where uid = %d and self = 0 and id not in (select distinct(`contact-id`) from group_member where uid = %d) ",
intval($uid), intval($uid),
intval($uid) intval($uid)
@ -775,18 +777,18 @@ function posts_from_contact_url(App $a, $contact_url) {
function formatted_location($profile) { function formatted_location($profile) {
$location = ''; $location = '';
if($profile['locality']) if ($profile['locality'])
$location .= $profile['locality']; $location .= $profile['locality'];
if($profile['region'] AND ($profile['locality'] != $profile['region'])) { if ($profile['region'] AND ($profile['locality'] != $profile['region'])) {
if($location) if ($location)
$location .= ', '; $location .= ', ';
$location .= $profile['region']; $location .= $profile['region'];
} }
if($profile['country-name']) { if ($profile['country-name']) {
if($location) if ($location)
$location .= ', '; $location .= ', ';
$location .= $profile['country-name']; $location .= $profile['country-name'];
@ -808,7 +810,7 @@ function account_type($contact) {
// "page-flags" is a field in the user table, // "page-flags" is a field in the user table,
// "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP. // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
// "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP. // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
if((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY)) if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
|| (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP)) || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
|| (isset($contact['forum']) && intval($contact['forum'])) || (isset($contact['forum']) && intval($contact['forum']))
|| (isset($contact['prv']) && intval($contact['prv'])) || (isset($contact['prv']) && intval($contact['prv']))

View file

@ -44,7 +44,7 @@ class PConfig {
$a->config[$uid][$family][$k] = $rr['v']; $a->config[$uid][$family][$k] = $rr['v'];
self::$in_db[$uid][$family][$k] = true; self::$in_db[$uid][$family][$k] = true;
} }
} else if ($family != 'config') { } elseif ($family != 'config') {
// Negative caching // Negative caching
$a->config[$uid][$family] = "!<unset>!"; $a->config[$uid][$family] = "!<unset>!";
} }

View file

@ -20,7 +20,7 @@ class DirSearch {
*/ */
public static function global_search_by_name($search, $mode = '') { public static function global_search_by_name($search, $mode = '') {
if($search) { if ($search) {
// check supported networks // check supported networks
if (get_config('system','diaspora_enabled')) if (get_config('system','diaspora_enabled'))
$diaspora = NETWORK_DIASPORA; $diaspora = NETWORK_DIASPORA;
@ -33,10 +33,11 @@ class DirSearch {
$ostatus = NETWORK_DFRN; $ostatus = NETWORK_DFRN;
// check if we search only communities or every contact // check if we search only communities or every contact
if($mode === "community") if ($mode === "community") {
$extra_sql = " AND `community`"; $extra_sql = " AND `community`";
else } else {
$extra_sql = ""; $extra_sql = "";
}
$search .= "%"; $search .= "%";

View file

@ -50,7 +50,7 @@ class ForumManager {
if (!$contacts) if (!$contacts)
return($forumlist); return($forumlist);
foreach($contacts as $contact) { foreach ($contacts as $contact) {
$forumlist[] = array( $forumlist[] = array(
'url' => $contact['url'], 'url' => $contact['url'],
'name' => $contact['name'], 'name' => $contact['name'],
@ -76,7 +76,7 @@ class ForumManager {
*/ */
public static function widget($uid,$cid = 0) { public static function widget($uid,$cid = 0) {
if(! intval(feature_enabled(local_user(),'forumlist_widget'))) if (! intval(feature_enabled(local_user(),'forumlist_widget')))
return; return;
$o = ''; $o = '';
@ -92,7 +92,7 @@ class ForumManager {
$id = 0; $id = 0;
foreach($contacts as $contact) { foreach ($contacts as $contact) {
$selected = (($cid == $contact['id']) ? ' forum-selected' : ''); $selected = (($cid == $contact['id']) ? ' forum-selected' : '');
@ -136,7 +136,7 @@ class ForumManager {
public static function profile_advanced($uid) { public static function profile_advanced($uid) {
$profile = intval(feature_enabled($uid,'forumlist_profile')); $profile = intval(feature_enabled($uid,'forumlist_profile'));
if(! $profile) if (! $profile)
return; return;
$o = ''; $o = '';
@ -151,15 +151,19 @@ class ForumManager {
$total_shown = 0; $total_shown = 0;
foreach($contacts as $contact) { foreach ($contacts as $contact) {
$forumlist .= micropro($contact,false,'forumlist-profile-advanced'); $forumlist .= micropro($contact,false,'forumlist-profile-advanced');
$total_shown ++; $total_shown ++;
if($total_shown == $show_total)
if ($total_shown == $show_total) {
break; break;
} }
}
if(count($contacts) > 0) if (count($contacts) > 0) {
$o .= $forumlist; $o .= $forumlist;
}
return $o; return $o;
} }

View file

@ -33,7 +33,7 @@ class NotificationsManager {
*/ */
private function _set_extra($notes) { private function _set_extra($notes) {
$rets = array(); $rets = array();
foreach($notes as $n) { foreach ($notes as $n) {
$local_time = datetime_convert('UTC',date_default_timezone_get(),$n['date']); $local_time = datetime_convert('UTC',date_default_timezone_get(),$n['date']);
$n['timestamp'] = strtotime($local_time); $n['timestamp'] = strtotime($local_time);
$n['date_rel'] = relative_date($n['date']); $n['date_rel'] = relative_date($n['date']);
@ -58,7 +58,7 @@ class NotificationsManager {
public function getAll($filter = array(), $order="-date", $limit="") { public function getAll($filter = array(), $order="-date", $limit="") {
$filter_str = array(); $filter_str = array();
$filter_sql = ""; $filter_sql = "";
foreach($filter as $column => $value) { foreach ($filter as $column => $value) {
$filter_str[] = sprintf("`%s` = '%s'", $column, dbesc($value)); $filter_str[] = sprintf("`%s` = '%s'", $column, dbesc($value));
} }
if (count($filter_str)>0) { if (count($filter_str)>0) {
@ -67,7 +67,7 @@ class NotificationsManager {
$aOrder = explode(" ", $order); $aOrder = explode(" ", $order);
$asOrder = array(); $asOrder = array();
foreach($aOrder as $o) { foreach ($aOrder as $o) {
$dir = "asc"; $dir = "asc";
if ($o[0]==="-") { if ($o[0]==="-") {
$dir = "desc"; $dir = "desc";
@ -81,7 +81,7 @@ class NotificationsManager {
} }
$order_sql = implode(", ", $asOrder); $order_sql = implode(", ", $asOrder);
if($limit!="") if ($limit!="")
$limit = " LIMIT ".$limit; $limit = " LIMIT ".$limit;
$r = q("SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit", $r = q("SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
@ -369,7 +369,7 @@ class NotificationsManager {
private function networkTotal($seen = 0) { private function networkTotal($seen = 0) {
$sql_seen = ""; $sql_seen = "";
if($seen === 0) if ($seen === 0)
$sql_seen = " AND `item`.`unseen` = 1 "; $sql_seen = " AND `item`.`unseen` = 1 ";
$r = q("SELECT COUNT(*) AS `total` $r = q("SELECT COUNT(*) AS `total`
@ -406,7 +406,7 @@ class NotificationsManager {
$notifs = array(); $notifs = array();
$sql_seen = ""; $sql_seen = "";
if($seen === 0) if ($seen === 0)
$sql_seen = " AND `item`.`unseen` = 1 "; $sql_seen = " AND `item`.`unseen` = 1 ";
@ -445,7 +445,7 @@ class NotificationsManager {
private function systemTotal($seen = 0) { private function systemTotal($seen = 0) {
$sql_seen = ""; $sql_seen = "";
if($seen === 0) if ($seen === 0)
$sql_seen = " AND `seen` = 0 "; $sql_seen = " AND `seen` = 0 ";
$r = q("SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen", $r = q("SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen",
@ -478,7 +478,7 @@ class NotificationsManager {
$notifs = array(); $notifs = array();
$sql_seen = ""; $sql_seen = "";
if($seen === 0) if ($seen === 0)
$sql_seen = " AND `seen` = 0 "; $sql_seen = " AND `seen` = 0 ";
$r = q("SELECT `id`, `url`, `photo`, `msg`, `date`, `seen` FROM `notify` $r = q("SELECT `id`, `url`, `photo`, `msg`, `date`, `seen` FROM `notify`
@ -530,7 +530,7 @@ class NotificationsManager {
$sql_seen = ""; $sql_seen = "";
$sql_extra = $this->_personal_sql_extra(); $sql_extra = $this->_personal_sql_extra();
if($seen === 0) if ($seen === 0)
$sql_seen = " AND `item`.`unseen` = 1 "; $sql_seen = " AND `item`.`unseen` = 1 ";
$r = q("SELECT COUNT(*) AS `total` $r = q("SELECT COUNT(*) AS `total`
@ -569,7 +569,7 @@ class NotificationsManager {
$notifs = array(); $notifs = array();
$sql_seen = ""; $sql_seen = "";
if($seen === 0) if ($seen === 0)
$sql_seen = " AND `item`.`unseen` = 1 "; $sql_seen = " AND `item`.`unseen` = 1 ";
$r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`, $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
@ -608,7 +608,7 @@ class NotificationsManager {
private function homeTotal($seen = 0) { private function homeTotal($seen = 0) {
$sql_seen = ""; $sql_seen = "";
if($seen === 0) if ($seen === 0)
$sql_seen = " AND `item`.`unseen` = 1 "; $sql_seen = " AND `item`.`unseen` = 1 ";
$r = q("SELECT COUNT(*) AS `total` FROM `item` $r = q("SELECT COUNT(*) AS `total` FROM `item`
@ -644,7 +644,7 @@ class NotificationsManager {
$notifs = array(); $notifs = array();
$sql_seen = ""; $sql_seen = "";
if($seen === 0) if ($seen === 0)
$sql_seen = " AND `item`.`unseen` = 1 "; $sql_seen = " AND `item`.`unseen` = 1 ";
$r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`, $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
@ -682,7 +682,7 @@ class NotificationsManager {
private function introTotal($all = false) { private function introTotal($all = false) {
$sql_extra = ""; $sql_extra = "";
if(!$all) if (!$all)
$sql_extra = " AND `ignore` = 0 "; $sql_extra = " AND `ignore` = 0 ";
$r = q("SELECT COUNT(*) AS `total` FROM `intro` $r = q("SELECT COUNT(*) AS `total` FROM `intro`
@ -716,7 +716,7 @@ class NotificationsManager {
$notifs = array(); $notifs = array();
$sql_extra = ""; $sql_extra = "";
if(!$all) if (!$all)
$sql_extra = " AND `ignore` = 0 "; $sql_extra = " AND `ignore` = 0 ";
/// @todo Fetch contact details by "get_contact_details_by_url" instead of queries to contact, fcontact and gcontact /// @todo Fetch contact details by "get_contact_details_by_url" instead of queries to contact, fcontact and gcontact
@ -756,12 +756,12 @@ class NotificationsManager {
private function formatIntros($intros) { private function formatIntros($intros) {
$knowyou = ''; $knowyou = '';
foreach($intros as $it) { foreach ($intros as $it) {
// There are two kind of introduction. Contacts suggested by other contacts and normal connection requests. // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
// We have to distinguish between these two because they use different data. // We have to distinguish between these two because they use different data.
// Contact suggestions // Contact suggestions
if($it['fid']) { if ($it['fid']) {
$return_addr = bin2hex($this->a->user['nickname'] . '@' . $this->a->get_hostname() . (($this->a->path) ? '/' . $this->a->path : '')); $return_addr = bin2hex($this->a->user['nickname'] . '@' . $this->a->get_hostname() . (($this->a->path) ? '/' . $this->a->path : ''));
@ -793,7 +793,7 @@ class NotificationsManager {
$it['gnetwork'] = $ret["network"]; $it['gnetwork'] = $ret["network"];
// Don't show these data until you are connected. Diaspora is doing the same. // Don't show these data until you are connected. Diaspora is doing the same.
if($it['gnetwork'] === NETWORK_DIASPORA) { if ($it['gnetwork'] === NETWORK_DIASPORA) {
$it['glocation'] = ""; $it['glocation'] = "";
$it['gabout'] = ""; $it['gabout'] = "";
$it['ggender'] = ""; $it['ggender'] = "";

View file

@ -564,15 +564,15 @@ class Probe {
*/ */
public static function valid_dfrn($data) { public static function valid_dfrn($data) {
$errors = 0; $errors = 0;
if(!isset($data['key'])) if (!isset($data['key']))
$errors ++; $errors ++;
if(!isset($data['dfrn-request'])) if (!isset($data['dfrn-request']))
$errors ++; $errors ++;
if(!isset($data['dfrn-confirm'])) if (!isset($data['dfrn-confirm']))
$errors ++; $errors ++;
if(!isset($data['dfrn-notify'])) if (!isset($data['dfrn-notify']))
$errors ++; $errors ++;
if(!isset($data['dfrn-poll'])) if (!isset($data['dfrn-poll']))
$errors ++; $errors ++;
return $errors; return $errors;
} }
@ -858,7 +858,7 @@ class Probe {
$data = array(); $data = array();
if (is_array($webfinger["aliases"])) if (is_array($webfinger["aliases"]))
foreach($webfinger["aliases"] AS $alias) foreach ($webfinger["aliases"] AS $alias)
if (strstr($alias, "@")) if (strstr($alias, "@"))
$data["addr"] = str_replace('acct:', '', $alias); $data["addr"] = str_replace('acct:', '', $alias);
@ -1133,15 +1133,17 @@ class Probe {
$password = ''; $password = '';
openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']); openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']);
$mbox = email_connect($mailbox,$r[0]['user'], $password); $mbox = email_connect($mailbox,$r[0]['user'], $password);
if(!mbox) if (!$mbox) {
return false; return false;
} }
}
$msgs = email_poll($mbox, $uri); $msgs = email_poll($mbox, $uri);
logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG); logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
if (!count($msgs)) if (!count($msgs)) {
return false; return false;
}
$data = array(); $data = array();
@ -1157,23 +1159,26 @@ class Probe {
$data["poll"] = 'email '.random_string(); $data["poll"] = 'email '.random_string();
$x = email_msg_meta($mbox, $msgs[0]); $x = email_msg_meta($mbox, $msgs[0]);
if(stristr($x[0]->from, $uri)) if (stristr($x[0]->from, $uri)) {
$adr = imap_rfc822_parse_adrlist($x[0]->from, ''); $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
elseif(stristr($x[0]->to, $uri)) } elseif (stristr($x[0]->to, $uri)) {
$adr = imap_rfc822_parse_adrlist($x[0]->to, ''); $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
if(isset($adr)) { }
foreach($adr as $feadr) { if (isset($adr)) {
if((strcasecmp($feadr->mailbox, $data["name"]) == 0) foreach ($adr as $feadr) {
if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
&&(strcasecmp($feadr->host, $phost) == 0) &&(strcasecmp($feadr->host, $phost) == 0)
&& (strlen($feadr->personal))) { && (strlen($feadr->personal))) {
$personal = imap_mime_header_decode($feadr->personal); $personal = imap_mime_header_decode($feadr->personal);
$data["name"] = ""; $data["name"] = "";
foreach($personal as $perspart) foreach ($personal as $perspart) {
if ($perspart->charset != "default") if ($perspart->charset != "default") {
$data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text); $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
else } else {
$data["name"] .= $perspart->text; $data["name"] .= $perspart->text;
}
}
$data["name"] = notags($data["name"]); $data["name"] = notags($data["name"]);
} }

View file

@ -125,7 +125,7 @@ class Smilies {
* @return string HML Output of the Smilie * @return string HML Output of the Smilie
*/ */
public static function replace($s, $sample = false) { public static function replace($s, $sample = false) {
if(intval(get_config('system','no_smilies')) if (intval(get_config('system','no_smilies'))
|| (local_user() && intval(get_pconfig(local_user(),'system','no_smilies')))) || (local_user() && intval(get_pconfig(local_user(),'system','no_smilies'))))
return $s; return $s;
@ -135,9 +135,9 @@ class Smilies {
$params = self::get_list(); $params = self::get_list();
$params['string'] = $s; $params['string'] = $s;
if($sample) { if ($sample) {
$s = '<div class="smiley-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>'; $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
} }
} }
@ -170,11 +170,13 @@ class Smilies {
* @todo: Rework because it doesn't work correctly * @todo: Rework because it doesn't work correctly
*/ */
private function preg_heart($x) { private function preg_heart($x) {
if(strlen($x[1]) == 1) if (strlen($x[1]) == 1) {
return $x[0]; return $x[0];
}
$t = ''; $t = '';
for($cnt = 0; $cnt < strlen($x[1]); $cnt ++) for ($cnt = 0; $cnt < strlen($x[1]); $cnt ++) {
$t .= '<img class="smiley" src="' . app::get_baseurl() . '/images/smiley-heart.gif" alt="&lt;3" />'; $t .= '<img class="smiley" src="' . app::get_baseurl() . '/images/smiley-heart.gif" alt="&lt;3" />';
}
$r = str_replace($x[0],$t,$x[0]); $r = str_replace($x[0],$t,$x[0]);
return $r; return $r;
} }

View file

@ -35,7 +35,7 @@ function group_select($selname,$selclass,$preselected = false,$size = 4) {
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach ($r as $rr) { foreach ($r as $rr) {
if((is_array($preselected)) && in_array($rr['id'], $preselected)) if ((is_array($preselected)) && in_array($rr['id'], $preselected))
$selected = " selected=\"selected\" "; $selected = " selected=\"selected\" ";
else else
$selected = ''; $selected = '';
@ -88,13 +88,13 @@ function contact_selector($selname, $selclass, $preselected = false, $options) {
$networks = array(NETWORK_DFRN); $networks = array(NETWORK_DFRN);
break; break;
case 'PRIVATE': case 'PRIVATE':
if(is_array($a->user) && $a->user['prvnets']) if (is_array($a->user) && $a->user['prvnets'])
$networks = array(NETWORK_DFRN,NETWORK_MAIL,NETWORK_DIASPORA); $networks = array(NETWORK_DFRN,NETWORK_MAIL,NETWORK_DIASPORA);
else else
$networks = array(NETWORK_DFRN,NETWORK_FACEBOOK,NETWORK_MAIL, NETWORK_DIASPORA); $networks = array(NETWORK_DFRN,NETWORK_FACEBOOK,NETWORK_MAIL, NETWORK_DIASPORA);
break; break;
case 'TWO_WAY': case 'TWO_WAY':
if(is_array($a->user) && $a->user['prvnets']) if (is_array($a->user) && $a->user['prvnets'])
$networks = array(NETWORK_DFRN,NETWORK_MAIL,NETWORK_DIASPORA); $networks = array(NETWORK_DFRN,NETWORK_MAIL,NETWORK_DIASPORA);
else else
$networks = array(NETWORK_DFRN,NETWORK_FACEBOOK,NETWORK_MAIL,NETWORK_DIASPORA,NETWORK_OSTATUS); $networks = array(NETWORK_DFRN,NETWORK_FACEBOOK,NETWORK_MAIL,NETWORK_DIASPORA,NETWORK_OSTATUS);
@ -113,23 +113,24 @@ function contact_selector($selname, $selclass, $preselected = false, $options) {
$sql_extra = ''; $sql_extra = '';
if($x['mutual']) { if ($x['mutual']) {
$sql_extra .= sprintf(" AND `rel` = %d ", intval(CONTACT_IS_FRIEND)); $sql_extra .= sprintf(" AND `rel` = %d ", intval(CONTACT_IS_FRIEND));
} }
if(intval($x['exclude'])) if (intval($x['exclude']))
$sql_extra .= sprintf(" AND `id` != %d ", intval($x['exclude'])); $sql_extra .= sprintf(" AND `id` != %d ", intval($x['exclude']));
if(is_array($x['networks']) && count($x['networks'])) { if (is_array($x['networks']) && count($x['networks'])) {
for($y = 0; $y < count($x['networks']) ; $y ++) for ($y = 0; $y < count($x['networks']) ; $y ++) {
$x['networks'][$y] = "'" . dbesc($x['networks'][$y]) . "'"; $x['networks'][$y] = "'" . dbesc($x['networks'][$y]) . "'";
}
$str_nets = implode(',',$x['networks']); $str_nets = implode(',',$x['networks']);
$sql_extra .= " AND `network` IN ( $str_nets ) "; $sql_extra .= " AND `network` IN ( $str_nets ) ";
} }
$tabindex = (x($options, 'tabindex') ? "tabindex=\"" . $options["tabindex"] . "\"" : ""); $tabindex = (x($options, 'tabindex') ? "tabindex=\"" . $options["tabindex"] . "\"" : "");
if($x['single']) if ($x['single'])
$o .= "<select name=\"$selname\" id=\"$selclass\" class=\"$selclass\" size=\"" . $x['size'] . "\" $tabindex >\r\n"; $o .= "<select name=\"$selname\" id=\"$selclass\" class=\"$selclass\" size=\"" . $x['size'] . "\" $tabindex >\r\n";
else else
$o .= "<select name=\"{$selname}[]\" id=\"$selclass\" class=\"$selclass\" multiple=\"multiple\" size=\"" . $x['size'] . "$\" $tabindex >\r\n"; $o .= "<select name=\"{$selname}[]\" id=\"$selclass\" class=\"$selclass\" multiple=\"multiple\" size=\"" . $x['size'] . "$\" $tabindex >\r\n";
@ -185,14 +186,14 @@ function contact_select($selname, $selclass, $preselected = false, $size = 4, $p
$sql_extra = ''; $sql_extra = '';
if($privmail || $celeb) { if ($privmail || $celeb) {
$sql_extra .= sprintf(" AND `rel` = %d ", intval(CONTACT_IS_FRIEND)); $sql_extra .= sprintf(" AND `rel` = %d ", intval(CONTACT_IS_FRIEND));
} }
if($privmail) if ($privmail)
$sql_extra .= sprintf(" AND `network` IN ('%s' , '%s') ", $sql_extra .= sprintf(" AND `network` IN ('%s' , '%s') ",
NETWORK_DFRN, NETWORK_DIASPORA); NETWORK_DFRN, NETWORK_DIASPORA);
elseif($privatenet) elseif ($privatenet)
$sql_extra .= sprintf(" AND `network` IN ('%s' , '%s', '%s', '%s') ", $sql_extra .= sprintf(" AND `network` IN ('%s' , '%s', '%s', '%s') ",
NETWORK_DFRN, NETWORK_MAIL, NETWORK_FACEBOOK, NETWORK_DIASPORA); NETWORK_DFRN, NETWORK_MAIL, NETWORK_FACEBOOK, NETWORK_DIASPORA);
@ -204,7 +205,7 @@ function contact_select($selname, $selclass, $preselected = false, $size = 4, $p
} else } else
$hidepreselected = ""; $hidepreselected = "";
if($privmail) if ($privmail)
$o .= "<select name=\"$selname\" id=\"$selclass\" class=\"$selclass\" size=\"$size\" $tabindex $hidepreselected>\r\n"; $o .= "<select name=\"$selname\" id=\"$selclass\" class=\"$selclass\" size=\"$size\" $tabindex $hidepreselected>\r\n";
else else
$o .= "<select name=\"{$selname}[]\" id=\"$selclass\" class=\"$selclass\" multiple=\"multiple\" size=\"$size\" $tabindex >\r\n"; $o .= "<select name=\"{$selname}[]\" id=\"$selclass\" class=\"$selclass\" multiple=\"multiple\" size=\"$size\" $tabindex >\r\n";
@ -287,7 +288,7 @@ function prune_deadguys($arr) {
function get_acl_permissions($user = null) { function get_acl_permissions($user = null) {
$allow_cid = $allow_gid = $deny_cid = $deny_gid = false; $allow_cid = $allow_gid = $deny_cid = $deny_gid = false;
if(is_array($user)) { if (is_array($user)) {
$allow_cid = ((strlen($user['allow_cid'])) $allow_cid = ((strlen($user['allow_cid']))
? explode('><', $user['allow_cid']) : array() ); ? explode('><', $user['allow_cid']) : array() );
$allow_gid = ((strlen($user['allow_gid'])) $allow_gid = ((strlen($user['allow_gid']))
@ -318,25 +319,25 @@ function populate_acl($user = null, $show_jotnets = false) {
$perms = get_acl_permissions($user); $perms = get_acl_permissions($user);
$jotnets = ''; $jotnets = '';
if($show_jotnets) { if ($show_jotnets) {
$mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1); $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
$mail_enabled = false; $mail_enabled = false;
$pubmail_enabled = false; $pubmail_enabled = false;
if(! $mail_disabled) { if (! $mail_disabled) {
$r = q("SELECT `pubmail` FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", $r = q("SELECT `pubmail` FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
intval(local_user()) intval(local_user())
); );
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
$mail_enabled = true; $mail_enabled = true;
if(intval($r[0]['pubmail'])) if (intval($r[0]['pubmail']))
$pubmail_enabled = true; $pubmail_enabled = true;
} }
} }
if (!$user['hidewall']) { if (!$user['hidewall']) {
if($mail_enabled) { if ($mail_enabled) {
$selected = (($pubmail_enabled) ? ' checked="checked" ' : ''); $selected = (($pubmail_enabled) ? ' checked="checked" ' : '');
$jotnets .= '<div class="profile-jot-net"><input type="checkbox" name="pubmail_enable"' . $selected . ' value="1" /> ' . t("Post to Email") . '</div>'; $jotnets .= '<div class="profile-jot-net"><input type="checkbox" name="pubmail_enable"' . $selected . ' value="1" /> ' . t("Post to Email") . '</div>';
} }
@ -379,20 +380,20 @@ function construct_acl_data(App $a, $user) {
$user_defaults = get_acl_permissions($user); $user_defaults = get_acl_permissions($user);
if($acl_data['groups']) { if ($acl_data['groups']) {
foreach($acl_data['groups'] as $key=>$group) { foreach ($acl_data['groups'] as $key=>$group) {
// Add a "selected" flag to groups that are posted to by default // Add a "selected" flag to groups that are posted to by default
if($user_defaults['allow_gid'] && if ($user_defaults['allow_gid'] &&
in_array($group['id'], $user_defaults['allow_gid']) && !in_array($group['id'], $user_defaults['deny_gid']) ) in_array($group['id'], $user_defaults['allow_gid']) && !in_array($group['id'], $user_defaults['deny_gid']) )
$acl_data['groups'][$key]['selected'] = 1; $acl_data['groups'][$key]['selected'] = 1;
else else
$acl_data['groups'][$key]['selected'] = 0; $acl_data['groups'][$key]['selected'] = 0;
} }
} }
if($acl_data['contacts']) { if ($acl_data['contacts']) {
foreach($acl_data['contacts'] as $key=>$contact) { foreach ($acl_data['contacts'] as $key=>$contact) {
// Add a "selected" flag to groups that are posted to by default // Add a "selected" flag to groups that are posted to by default
if($user_defaults['allow_cid'] && if ($user_defaults['allow_cid'] &&
in_array($contact['id'], $user_defaults['allow_cid']) && !in_array($contact['id'], $user_defaults['deny_cid']) ) in_array($contact['id'], $user_defaults['allow_cid']) && !in_array($contact['id'], $user_defaults['deny_cid']) )
$acl_data['contacts'][$key]['selected'] = 1; $acl_data['contacts'][$key]['selected'] = 1;
else else
@ -419,8 +420,8 @@ function acl_lookup(App $a, $out_type = 'json') {
// For use with jquery.textcomplete for private mail completion // For use with jquery.textcomplete for private mail completion
if(x($_REQUEST,'query') && strlen($_REQUEST['query'])) { if (x($_REQUEST,'query') && strlen($_REQUEST['query'])) {
if(! $type) if (! $type)
$type = 'm'; $type = 'm';
$search = $_REQUEST['query']; $search = $_REQUEST['query'];
} }
@ -510,7 +511,7 @@ function acl_lookup(App $a, $out_type = 'json') {
intval($count) intval($count)
); );
foreach($r as $g){ foreach ($r as $g){
// logger('acl: group: ' . $g['name'] . ' members: ' . $g['uids']); // logger('acl: group: ' . $g['name'] . ' members: ' . $g['uids']);
$groups[] = array( $groups[] = array(
"type" => "g", "type" => "g",
@ -546,7 +547,7 @@ function acl_lookup(App $a, $out_type = 'json') {
dbesc(NETWORK_STATUSNET) dbesc(NETWORK_STATUSNET)
); );
} }
elseif($type == 'm') { elseif ($type == 'm') {
$r = q("SELECT `id`, `name`, `nick`, `micro`, `network`, `url`, `attag` FROM `contact` $r = q("SELECT `id`, `name`, `nick`, `micro`, `network`, `url`, `attag` FROM `contact`
WHERE `uid` = %d AND NOT `self` AND NOT `blocked` AND NOT `pending` AND NOT `archive` WHERE `uid` = %d AND NOT `self` AND NOT `blocked` AND NOT `pending` AND NOT `archive`
AND `network` IN ('%s','%s','%s') AND `network` IN ('%s','%s','%s')
@ -665,7 +666,7 @@ function acl_lookup(App $a, $out_type = 'json') {
call_hooks('acl_lookup_end', $results); call_hooks('acl_lookup_end', $results);
if($out_type === 'html') { if ($out_type === 'html') {
$o = array( $o = array(
'tot' => $results['tot'], 'tot' => $results['tot'],
'start' => $results['start'], 'start' => $results['start'],

View file

@ -154,9 +154,9 @@ use \Friendica\Core\Config;
// workaround for HTTP-auth in CGI mode // workaround for HTTP-auth in CGI mode
if(x($_SERVER,'REDIRECT_REMOTE_USER')) { if (x($_SERVER,'REDIRECT_REMOTE_USER')) {
$userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ; $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
if(strlen($userpass)) { if (strlen($userpass)) {
list($name, $password) = explode(':', $userpass); list($name, $password) = explode(':', $userpass);
$_SERVER['PHP_AUTH_USER'] = $name; $_SERVER['PHP_AUTH_USER'] = $name;
$_SERVER['PHP_AUTH_PW'] = $password; $_SERVER['PHP_AUTH_PW'] = $password;
@ -199,7 +199,7 @@ use \Friendica\Core\Config;
call_hooks('authenticate', $addon_auth); call_hooks('authenticate', $addon_auth);
if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) { if (($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
$record = $addon_auth['user_record']; $record = $addon_auth['user_record'];
} }
else { else {
@ -215,7 +215,7 @@ use \Friendica\Core\Config;
$record = $r[0]; $record = $r[0];
} }
if((! $record) || (! count($record))) { if ((! $record) || (! count($record))) {
logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG); logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
header('WWW-Authenticate: Basic realm="Friendica"'); header('WWW-Authenticate: Basic realm="Friendica"');
#header('HTTP/1.0 401 Unauthorized'); #header('HTTP/1.0 401 Unauthorized');
@ -334,7 +334,7 @@ use \Friendica\Core\Config;
break; break;
case "json": case "json":
header ("Content-Type: application/json"); header ("Content-Type: application/json");
foreach($r as $rr) foreach ($r as $rr)
$json = json_encode($rr); $json = json_encode($rr);
if ($_GET['callback']) if ($_GET['callback'])
$json = $_GET['callback']."(".$json.")"; $json = $_GET['callback']."(".$json.")";
@ -457,7 +457,7 @@ use \Friendica\Core\Config;
logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG); logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
// Searching for contact URL // Searching for contact URL
if(!is_null($contact_id) AND (intval($contact_id) == 0)){ if (!is_null($contact_id) AND (intval($contact_id) == 0)){
$user = dbesc(normalise_link($contact_id)); $user = dbesc(normalise_link($contact_id));
$url = $user; $url = $user;
$extra_query = "AND `contact`.`nurl` = '%s' "; $extra_query = "AND `contact`.`nurl` = '%s' ";
@ -465,7 +465,7 @@ use \Friendica\Core\Config;
} }
// Searching for contact id with uid = 0 // Searching for contact id with uid = 0
if(!is_null($contact_id) AND (intval($contact_id) != 0)){ if (!is_null($contact_id) AND (intval($contact_id) != 0)){
$user = dbesc(api_unique_id_to_url($contact_id)); $user = dbesc(api_unique_id_to_url($contact_id));
if ($user == "") if ($user == "")
@ -476,7 +476,7 @@ use \Friendica\Core\Config;
if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user()); if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
} }
if(is_null($user) && x($_GET, 'user_id')) { if (is_null($user) && x($_GET, 'user_id')) {
$user = dbesc(api_unique_id_to_url($_GET['user_id'])); $user = dbesc(api_unique_id_to_url($_GET['user_id']));
if ($user == "") if ($user == "")
@ -486,7 +486,7 @@ use \Friendica\Core\Config;
$extra_query = "AND `contact`.`nurl` = '%s' "; $extra_query = "AND `contact`.`nurl` = '%s' ";
if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user()); if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
} }
if(is_null($user) && x($_GET, 'screen_name')) { if (is_null($user) && x($_GET, 'screen_name')) {
$user = dbesc($_GET['screen_name']); $user = dbesc($_GET['screen_name']);
$nick = $user; $nick = $user;
$extra_query = "AND `contact`.`nick` = '%s' "; $extra_query = "AND `contact`.`nick` = '%s' ";
@ -496,7 +496,7 @@ use \Friendica\Core\Config;
if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){ if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
$argid = count($called_api); $argid = count($called_api);
list($user, $null) = explode(".",$a->argv[$argid]); list($user, $null) = explode(".",$a->argv[$argid]);
if(is_numeric($user)){ if (is_numeric($user)){
$user = dbesc(api_unique_id_to_url($user)); $user = dbesc(api_unique_id_to_url($user));
if ($user == "") if ($user == "")
@ -593,7 +593,7 @@ use \Friendica\Core\Config;
} }
} }
if($uinfo[0]['self']) { if ($uinfo[0]['self']) {
if ($uinfo[0]['network'] == "") if ($uinfo[0]['network'] == "")
$uinfo[0]['network'] = NETWORK_DFRN; $uinfo[0]['network'] = NETWORK_DFRN;
@ -648,7 +648,7 @@ use \Friendica\Core\Config;
$starred = $r[0]['count']; $starred = $r[0]['count'];
if(! $uinfo[0]['self']) { if (! $uinfo[0]['self']) {
$countfriends = 0; $countfriends = 0;
$countfollowers = 0; $countfollowers = 0;
$starred = 0; $starred = 0;
@ -923,7 +923,7 @@ use \Friendica\Core\Config;
$txt = requestdata('status'); $txt = requestdata('status');
//$txt = urldecode(requestdata('status')); //$txt = urldecode(requestdata('status'));
if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) { if ((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
$txt = html2bb_video($txt); $txt = html2bb_video($txt);
$config = HTMLPurifier_Config::createDefault(); $config = HTMLPurifier_Config::createDefault();
@ -964,9 +964,9 @@ use \Friendica\Core\Config;
// logger('api_post: ' . print_r($_POST,true)); // logger('api_post: ' . print_r($_POST,true));
if(requestdata('htmlstatus')) { if (requestdata('htmlstatus')) {
$txt = requestdata('htmlstatus'); $txt = requestdata('htmlstatus');
if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) { if ((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
$txt = html2bb_video($txt); $txt = html2bb_video($txt);
$config = HTMLPurifier_Config::createDefault(); $config = HTMLPurifier_Config::createDefault();
@ -989,16 +989,16 @@ use \Friendica\Core\Config;
if ($parent == -1) if ($parent == -1)
$parent = ""; $parent = "";
if(ctype_digit($parent)) if (ctype_digit($parent))
$_REQUEST['parent'] = $parent; $_REQUEST['parent'] = $parent;
else else
$_REQUEST['parent_uri'] = $parent; $_REQUEST['parent_uri'] = $parent;
if(requestdata('lat') && requestdata('long')) if (requestdata('lat') && requestdata('long'))
$_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long')); $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
$_REQUEST['profile_uid'] = api_user(); $_REQUEST['profile_uid'] = api_user();
if($parent) if ($parent)
$_REQUEST['type'] = 'net-comment'; $_REQUEST['type'] = 'net-comment';
else { else {
// Check for throttling (maximum posts per day, week and month) // Check for throttling (maximum posts per day, week and month)
@ -1066,11 +1066,11 @@ use \Friendica\Core\Config;
$_REQUEST['type'] = 'wall'; $_REQUEST['type'] = 'wall';
} }
if(x($_FILES,'media')) { if (x($_FILES,'media')) {
// upload the image if we have one // upload the image if we have one
$_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
$media = wall_upload_post($a); $media = wall_upload_post($a);
if(strlen($media)>0) if (strlen($media)>0)
$_REQUEST['body'] .= "\n\n".$media; $_REQUEST['body'] .= "\n\n".$media;
} }
@ -1115,13 +1115,13 @@ use \Friendica\Core\Config;
$user_info = api_get_user($a); $user_info = api_get_user($a);
if(!x($_FILES,'media')) { if (!x($_FILES,'media')) {
// Output error // Output error
throw new BadRequestException("No media."); throw new BadRequestException("No media.");
} }
$media = wall_upload_post($a, false); $media = wall_upload_post($a, false);
if(!$media) { if (!$media) {
// Output error // Output error
throw new InternalServerErrorException(); throw new InternalServerErrorException();
} }
@ -2469,7 +2469,7 @@ use \Friendica\Core\Config;
$ret = Array(); $ret = Array();
foreach($r as $item) { foreach ($r as $item) {
localize_item($item); localize_item($item);
list($status_user, $owner_user) = api_item_get_user($a,$item); list($status_user, $owner_user) = api_item_get_user($a,$item);
@ -2641,9 +2641,9 @@ use \Friendica\Core\Config;
return false; return false;
} }
if($qtype == 'friends') if ($qtype == 'friends')
$sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND)); $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
if($qtype == 'followers') if ($qtype == 'followers')
$sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND)); $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
// friends and followers only for self // friends and followers only for self
@ -2655,7 +2655,7 @@ use \Friendica\Core\Config;
); );
$ret = array(); $ret = array();
foreach($r as $cid){ foreach ($r as $cid){
$user = api_get_user($a, $cid['nurl']); $user = api_get_user($a, $cid['nurl']);
// "uid" and "self" are only needed for some internal stuff, so remove it from here // "uid" and "self" are only needed for some internal stuff, so remove it from here
unset($user["uid"]); unset($user["uid"]);
@ -2697,7 +2697,7 @@ use \Friendica\Core\Config;
$closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false'); $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
$private = ((Config::get('system', 'block_public')) ? 'true' : 'false'); $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
$textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000); $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
if($a->config['api_import_size']) if ($a->config['api_import_size'])
$texlimit = string($a->config['api_import_size']); $texlimit = string($a->config['api_import_size']);
$ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false'); $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
$sslserver = (($ssl === 'true') ? str_replace('http:','https:',App::get_baseurl()) : ''); $sslserver = (($ssl === 'true') ? str_replace('http:','https:',App::get_baseurl()) : '');
@ -2737,13 +2737,13 @@ use \Friendica\Core\Config;
$a = get_app(); $a = get_app();
if(! api_user()) throw new ForbiddenException(); if (! api_user()) throw new ForbiddenException();
$user_info = api_get_user($a); $user_info = api_get_user($a);
if($qtype == 'friends') if ($qtype == 'friends')
$sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND)); $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
if($qtype == 'followers') if ($qtype == 'followers')
$sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND)); $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
if (!$user_info["self"]) if (!$user_info["self"])
@ -2761,7 +2761,7 @@ use \Friendica\Core\Config;
return; return;
$ids = array(); $ids = array();
foreach($r as $rr) foreach ($r as $rr)
if ($stringify_ids) if ($stringify_ids)
$ids[] = $rr['id']; $ids[] = $rr['id'];
else else
@ -2967,7 +2967,7 @@ use \Friendica\Core\Config;
if ($user_id !="") { if ($user_id !="") {
$sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id); $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
} }
elseif($screen_name !=""){ elseif ($screen_name !=""){
$sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'"; $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
} }
@ -2978,14 +2978,14 @@ use \Friendica\Core\Config;
); );
if ($verbose == "true") { if ($verbose == "true") {
// stop execution and return error message if no mails available // stop execution and return error message if no mails available
if($r == null) { if ($r == null) {
$answer = array('result' => 'error', 'message' => 'no mails available'); $answer = array('result' => 'error', 'message' => 'no mails available');
return api_format_data("direct_messages_all", $type, array('$result' => $answer)); return api_format_data("direct_messages_all", $type, array('$result' => $answer));
} }
} }
$ret = Array(); $ret = Array();
foreach($r as $item) { foreach ($r as $item) {
if ($box == "inbox" || $item['from-url'] != $profile_url){ if ($box == "inbox" || $item['from-url'] != $profile_url){
$recipient = $user_info; $recipient = $user_info;
$sender = api_get_user($a,normalise_link($item['contact-url'])); $sender = api_get_user($a,normalise_link($item['contact-url']));
@ -3092,7 +3092,7 @@ use \Friendica\Core\Config;
function api_fr_photo_detail($type) { function api_fr_photo_detail($type) {
if (api_user()===false) throw new ForbiddenException(); if (api_user()===false) throw new ForbiddenException();
if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id."); if (!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
$scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false); $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
$scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale))); $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
@ -3183,11 +3183,11 @@ use \Friendica\Core\Config;
$dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']); $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
if($r[0]['duplex'] && $r[0]['issued-id']) { if ($r[0]['duplex'] && $r[0]['issued-id']) {
$orig_id = $r[0]['issued-id']; $orig_id = $r[0]['issued-id'];
$dfrn_id = '1:' . $orig_id; $dfrn_id = '1:' . $orig_id;
} }
if($r[0]['duplex'] && $r[0]['dfrn-id']) { if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
$orig_id = $r[0]['dfrn-id']; $orig_id = $r[0]['dfrn-id'];
$dfrn_id = '0:' . $orig_id; $dfrn_id = '0:' . $orig_id;
} }
@ -3927,7 +3927,7 @@ use \Friendica\Core\Config;
$success = array('success' => false, 'search_results' => 'nothing found'); $success = array('success' => false, 'search_results' => 'nothing found');
else { else {
$ret = Array(); $ret = Array();
foreach($r as $item) { foreach ($r as $item) {
if ($box == "inbox" || $item['from-url'] != $profile_url){ if ($box == "inbox" || $item['from-url'] != $profile_url){
$recipient = $user_info; $recipient = $user_info;
$sender = api_get_user($a,normalise_link($item['contact-url'])); $sender = api_get_user($a,normalise_link($item['contact-url']));

View file

@ -1061,7 +1061,7 @@ function z_mime_content_type($filename) {
); );
$dot = strpos($filename,'.'); $dot = strpos($filename,'.');
if($dot !== false) { if ($dot !== false) {
$ext = strtolower(substr($filename,$dot+1)); $ext = strtolower(substr($filename,$dot+1));
if (array_key_exists($ext, $mime_types)) { if (array_key_exists($ext, $mime_types)) {
return $mime_types[$ext]; return $mime_types[$ext];

View file

@ -141,7 +141,7 @@ function bb2diaspora($Text,$preserve_nl = false, $fordiaspora = true) {
// Add all tags that maybe were removed // Add all tags that maybe were removed
if (preg_match_all("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",$OriginalText, $tags)) { if (preg_match_all("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",$OriginalText, $tags)) {
$tagline = ""; $tagline = "";
foreach($tags[2] as $tag) { foreach ($tags[2] as $tag) {
$tag = html_entity_decode($tag, ENT_QUOTES, 'UTF-8'); $tag = html_entity_decode($tag, ENT_QUOTES, 'UTF-8');
if (!strpos(html_entity_decode($Text, ENT_QUOTES, 'UTF-8'), "#".$tag)) if (!strpos(html_entity_decode($Text, ENT_QUOTES, 'UTF-8'), "#".$tag))
$tagline .= "#".$tag." "; $tagline .= "#".$tag." ";
@ -193,7 +193,7 @@ function unescape_underscores_in_links($m) {
function format_event_diaspora($ev) { function format_event_diaspora($ev) {
if(! ((is_array($ev)) && count($ev))) if (! ((is_array($ev)) && count($ev)))
return ''; return '';
$bd_format = t('l F d, Y \@ g:i A') ; // Friday January 18, 2011 @ 8 AM $bd_format = t('l F d, Y \@ g:i A') ; // Friday January 18, 2011 @ 8 AM
@ -209,7 +209,7 @@ function format_event_diaspora($ev) {
$ev['start'] , $bd_format))) $ev['start'] , $bd_format)))
. '](' . App::get_baseurl() . '/localtime/?f=&time=' . urlencode(datetime_convert('UTC','UTC',$ev['start'])) . ")\n"; . '](' . App::get_baseurl() . '/localtime/?f=&time=' . urlencode(datetime_convert('UTC','UTC',$ev['start'])) . ")\n";
if(! $ev['nofinish']) if (! $ev['nofinish'])
$o .= t('Finishes:') . ' ' . '[' $o .= t('Finishes:') . ' ' . '['
. (($ev['adjust']) ? day_translate(datetime_convert('UTC', 'UTC', . (($ev['adjust']) ? day_translate(datetime_convert('UTC', 'UTC',
$ev['finish'] , $bd_format )) $ev['finish'] , $bd_format ))
@ -217,7 +217,7 @@ function format_event_diaspora($ev) {
$ev['finish'] , $bd_format ))) $ev['finish'] , $bd_format )))
. '](' . App::get_baseurl() . '/localtime/?f=&time=' . urlencode(datetime_convert('UTC','UTC',$ev['finish'])) . ")\n"; . '](' . App::get_baseurl() . '/localtime/?f=&time=' . urlencode(datetime_convert('UTC','UTC',$ev['finish'])) . ")\n";
if(strlen($ev['location'])) if (strlen($ev['location']))
$o .= t('Location:') . bb2diaspora($ev['location']) $o .= t('Location:') . bb2diaspora($ev['location'])
. "\n"; . "\n";

View file

@ -214,22 +214,25 @@ function bb_unspacefy_and_trim($st) {
function bb_find_open_close($s, $open, $close, $occurance = 1) { function bb_find_open_close($s, $open, $close, $occurance = 1) {
if($occurance < 1) if ($occurance < 1)
$occurance = 1; $occurance = 1;
$start_pos = -1; $start_pos = -1;
for($i = 1; $i <= $occurance; $i++) { for ($i = 1; $i <= $occurance; $i++) {
if( $start_pos !== false) if ( $start_pos !== false) {
$start_pos = strpos($s, $open, $start_pos + 1); $start_pos = strpos($s, $open, $start_pos + 1);
} }
}
if( $start_pos === false) if ( $start_pos === false) {
return false; return false;
}
$end_pos = strpos($s, $close, $start_pos); $end_pos = strpos($s, $close, $start_pos);
if( $end_pos === false) if ( $end_pos === false) {
return false; return false;
}
$res = array( 'start' => $start_pos, 'end' => $end_pos ); $res = array( 'start' => $start_pos, 'end' => $end_pos );
@ -238,34 +241,35 @@ function bb_find_open_close($s, $open, $close, $occurance = 1) {
function get_bb_tag_pos($s, $name, $occurance = 1) { function get_bb_tag_pos($s, $name, $occurance = 1) {
if($occurance < 1) if ($occurance < 1)
$occurance = 1; $occurance = 1;
$start_open = -1; $start_open = -1;
for($i = 1; $i <= $occurance; $i++) { for ($i = 1; $i <= $occurance; $i++) {
if( $start_open !== false) if ( $start_open !== false) {
$start_open = strpos($s, '[' . $name, $start_open + 1); // allow [name= type tags $start_open = strpos($s, '[' . $name, $start_open + 1); // allow [name= type tags
} }
}
if( $start_open === false) if ( $start_open === false)
return false; return false;
$start_equal = strpos($s, '=', $start_open); $start_equal = strpos($s, '=', $start_open);
$start_close = strpos($s, ']', $start_open); $start_close = strpos($s, ']', $start_open);
if( $start_close === false) if ( $start_close === false)
return false; return false;
$start_close++; $start_close++;
$end_open = strpos($s, '[/' . $name . ']', $start_close); $end_open = strpos($s, '[/' . $name . ']', $start_close);
if( $end_open === false) if ( $end_open === false)
return false; return false;
$res = array( 'start' => array('open' => $start_open, 'close' => $start_close), $res = array( 'start' => array('open' => $start_open, 'close' => $start_close),
'end' => array('open' => $end_open, 'close' => $end_open + strlen('[/' . $name . ']')) ); 'end' => array('open' => $end_open, 'close' => $end_open + strlen('[/' . $name . ']')) );
if( $start_equal !== false) if ( $start_equal !== false)
$res['start']['equal'] = $start_equal + 1; $res['start']['equal'] = $start_equal + 1;
return $res; return $res;
@ -277,12 +281,12 @@ function bb_tag_preg_replace($pattern, $replace, $name, $s) {
$occurance = 1; $occurance = 1;
$pos = get_bb_tag_pos($string, $name, $occurance); $pos = get_bb_tag_pos($string, $name, $occurance);
while($pos !== false && $occurance < 1000) { while ($pos !== false && $occurance < 1000) {
$start = substr($string, 0, $pos['start']['open']); $start = substr($string, 0, $pos['start']['open']);
$subject = substr($string, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']); $subject = substr($string, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
$end = substr($string, $pos['end']['close']); $end = substr($string, $pos['end']['close']);
if($end === false) if ($end === false)
$end = ''; $end = '';
$subject = preg_replace($pattern, $replace, $subject); $subject = preg_replace($pattern, $replace, $subject);
@ -295,7 +299,7 @@ function bb_tag_preg_replace($pattern, $replace, $name, $s) {
return $string; return $string;
} }
if(! function_exists('bb_extract_images')) { if (! function_exists('bb_extract_images')) {
function bb_extract_images($body) { function bb_extract_images($body) {
$saved_image = array(); $saved_image = array();
@ -306,12 +310,12 @@ function bb_extract_images($body) {
$img_start = strpos($orig_body, '[img'); $img_start = strpos($orig_body, '[img');
$img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false); $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
$img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false); $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
while(($img_st_close !== false) && ($img_end !== false)) { while (($img_st_close !== false) && ($img_end !== false)) {
$img_st_close++; // make it point to AFTER the closing bracket $img_st_close++; // make it point to AFTER the closing bracket
$img_end += $img_start; $img_end += $img_start;
if(! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) { if (! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
// This is an embedded image // This is an embedded image
$saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close)); $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
@ -324,7 +328,7 @@ function bb_extract_images($body) {
$orig_body = substr($orig_body, $img_end + strlen('[/img]')); $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
if($orig_body === false) // in case the body ends on a closing image tag if ($orig_body === false) // in case the body ends on a closing image tag
$orig_body = ''; $orig_body = '';
$img_start = strpos($orig_body, '[img'); $img_start = strpos($orig_body, '[img');
@ -337,7 +341,7 @@ function bb_extract_images($body) {
return array('body' => $new_body, 'images' => $saved_image); return array('body' => $new_body, 'images' => $saved_image);
}} }}
if(! function_exists('bb_replace_images')) { if (! function_exists('bb_replace_images')) {
function bb_replace_images($body, $images) { function bb_replace_images($body, $images) {
$newbody = $body; $newbody = $body;
@ -619,7 +623,7 @@ function bb_DiasporaLinks($match) {
function bb_RemovePictureLinks($match) { function bb_RemovePictureLinks($match) {
$text = Cache::get($match[1]); $text = Cache::get($match[1]);
if(is_null($text)){ if (is_null($text)){
$a = get_app(); $a = get_app();
$stamp1 = microtime(true); $stamp1 = microtime(true);
@ -673,7 +677,7 @@ function bb_expand_links($match) {
function bb_CleanPictureLinksSub($match) { function bb_CleanPictureLinksSub($match) {
$text = Cache::get($match[1]); $text = Cache::get($match[1]);
if(is_null($text)){ if (is_null($text)){
$a = get_app(); $a = get_app();
$stamp1 = microtime(true); $stamp1 = microtime(true);
@ -724,7 +728,7 @@ function bb_CleanPictureLinks($text) {
} }
function bb_highlight($match) { function bb_highlight($match) {
if(in_array(strtolower($match[1]),['php','css','mysql','sql','abap','diff','html','perl','ruby', if (in_array(strtolower($match[1]),['php','css','mysql','sql','abap','diff','html','perl','ruby',
'vbscript','avrc','dtd','java','xml','cpp','python','javascript','js','sh'])) 'vbscript','avrc','dtd','java','xml','cpp','python','javascript','js','sh']))
return text_highlight($match[2],strtolower($match[1])); return text_highlight($match[2],strtolower($match[1]));
return $match[0]; return $match[0];
@ -814,7 +818,7 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true, $simplehtml = fal
$Text = str_replace(array("\r","\n"), array('<br />','<br />'), $Text); $Text = str_replace(array("\r","\n"), array('<br />','<br />'), $Text);
if($preserve_nl) if ($preserve_nl)
$Text = str_replace(array("\n","\r"), array('',''),$Text); $Text = str_replace(array("\n","\r"), array('',''),$Text);
// Set up the parameters for a URL search string // Set up the parameters for a URL search string
@ -1132,7 +1136,7 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true, $simplehtml = fal
// Summary (e.g. title) is required, earlier revisions only required description (in addition to // Summary (e.g. title) is required, earlier revisions only required description (in addition to
// start which is always required). Allow desc with a missing summary for compatibility. // 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, $simplehtml); $sub = format_event_html($ev, $simplehtml);
$Text = preg_replace("/\[event\-summary\](.*?)\[\/event\-summary\]/ism",'',$Text); $Text = preg_replace("/\[event\-summary\](.*?)\[\/event\-summary\]/ism",'',$Text);
@ -1178,7 +1182,7 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true, $simplehtml = fal
$regex = '#<([^>]*?)(href)="(?!' . implode('|', $allowed_link_protocols) . ')(.*?)"(.*?)>#ism'; $regex = '#<([^>]*?)(href)="(?!' . implode('|', $allowed_link_protocols) . ')(.*?)"(.*?)>#ism';
$Text = preg_replace($regex, '<$1$2="javascript:void(0)"$4 class="invalid-href" title="' . t('Invalid link protocol') . '">', $Text); $Text = preg_replace($regex, '<$1$2="javascript:void(0)"$4 class="invalid-href" title="' . t('Invalid link protocol') . '">', $Text);
if($saved_image) { if ($saved_image) {
$Text = bb_replace_images($Text, $saved_image); $Text = bb_replace_images($Text, $saved_image);
} }

View file

@ -37,7 +37,7 @@ function contact_reputation($current) {
5 => t('Reputable, has my trust') 5 => t('Reputable, has my trust')
); );
foreach($rep as $k => $v) { foreach ($rep as $k => $v) {
$selected = (($k == $current) ? " selected=\"selected\" " : ""); $selected = (($k == $current) ? " selected=\"selected\" " : "");
$o .= "<option value=\"$k\" $selected >$v</option>\r\n"; $o .= "<option value=\"$k\" $selected >$v</option>\r\n";
} }
@ -61,7 +61,7 @@ function contact_poll_interval($current, $disabled = false) {
5 => t('Monthly') 5 => t('Monthly')
); );
foreach($rep as $k => $v) { foreach ($rep as $k => $v) {
$selected = (($k == $current) ? " selected=\"selected\" " : ""); $selected = (($k == $current) ? " selected=\"selected\" " : "");
$o .= "<option value=\"$k\" $selected >$v</option>\r\n"; $o .= "<option value=\"$k\" $selected >$v</option>\r\n";
} }

View file

@ -17,9 +17,9 @@ function findpeople_widget() {
$a = get_app(); $a = get_app();
if(get_config('system','invitation_only')) { if (get_config('system','invitation_only')) {
$x = get_pconfig(local_user(),'system','invites_remaining'); $x = get_pconfig(local_user(),'system','invites_remaining');
if($x || is_site_admin()) { if ($x || is_site_admin()) {
$a->page['aside'] .= '<div class="side-link" id="side-invite-remain">' $a->page['aside'] .= '<div class="side-link" id="side-invite-remain">'
. sprintf( tt('%d invitation available','%d invitations available',$x), $x) . sprintf( tt('%d invitation available','%d invitations available',$x), $x)
. '</div>' . $inv; . '</div>' . $inv;
@ -108,7 +108,7 @@ function networks_widget($baseurl,$selected = '') {
} }
} }
if(count($nets) < 2) if (count($nets) < 2)
return ''; return '';
return replace_macros(get_markup_template('nets.tpl'),array( return replace_macros(get_markup_template('nets.tpl'),array(
@ -140,7 +140,7 @@ function fileas_widget($baseurl,$selected = '') {
$terms = array(); $terms = array();
$cnt = preg_match_all('/\[(.*?)\]/',$saved,$matches,PREG_SET_ORDER); $cnt = preg_match_all('/\[(.*?)\]/',$saved,$matches,PREG_SET_ORDER);
if ($cnt) { if ($cnt) {
foreach($matches as $mtch) { foreach ($matches as $mtch) {
$unescaped = xmlify(file_tag_decode($mtch[1])); $unescaped = xmlify(file_tag_decode($mtch[1]));
$terms[] = array('name' => $unescaped,'selected' => (($selected == $unescaped) ? 'selected' : '')); $terms[] = array('name' => $unescaped,'selected' => (($selected == $unescaped) ? 'selected' : ''));
} }
@ -173,8 +173,9 @@ function categories_widget($baseurl,$selected = '') {
$matches = false; $matches = false;
$terms = array(); $terms = array();
$cnt = preg_match_all('/<(.*?)>/',$saved,$matches,PREG_SET_ORDER); $cnt = preg_match_all('/<(.*?)>/',$saved,$matches,PREG_SET_ORDER);
if($cnt) {
foreach($matches as $mtch) { if ($cnt) {
foreach ($matches as $mtch) {
$unescaped = xmlify(file_tag_decode($mtch[1])); $unescaped = xmlify(file_tag_decode($mtch[1]));
$terms[] = array('name' => $unescaped,'selected' => (($selected == $unescaped) ? 'selected' : '')); $terms[] = array('name' => $unescaped,'selected' => (($selected == $unescaped) ? 'selected' : ''));
} }
@ -195,29 +196,29 @@ function common_friends_visitor_widget($profile_uid) {
$a = get_app(); $a = get_app();
if(local_user() == $profile_uid) if (local_user() == $profile_uid)
return; return;
$cid = $zcid = 0; $cid = $zcid = 0;
if(is_array($_SESSION['remote'])) { if (is_array($_SESSION['remote'])) {
foreach($_SESSION['remote'] as $visitor) { foreach ($_SESSION['remote'] as $visitor) {
if($visitor['uid'] == $profile_uid) { if ($visitor['uid'] == $profile_uid) {
$cid = $visitor['cid']; $cid = $visitor['cid'];
break; break;
} }
} }
} }
if(! $cid) { if (! $cid) {
if(get_my_url()) { if (get_my_url()) {
$r = q("select id from contact where nurl = '%s' and uid = %d limit 1", $r = q("select id from contact where nurl = '%s' and uid = %d limit 1",
dbesc(normalise_link(get_my_url())), dbesc(normalise_link(get_my_url())),
intval($profile_uid) intval($profile_uid)
); );
if (dbm::is_result($r)) if (dbm::is_result($r)) {
$cid = $r[0]['id']; $cid = $r[0]['id'];
else { } else {
$r = q("select id from gcontact where nurl = '%s' limit 1", $r = q("select id from gcontact where nurl = '%s' limit 1",
dbesc(normalise_link(get_my_url())) dbesc(normalise_link(get_my_url()))
); );
@ -227,22 +228,26 @@ function common_friends_visitor_widget($profile_uid) {
} }
} }
if($cid == 0 && $zcid == 0) if ($cid == 0 && $zcid == 0) {
return; return;
}
require_once('include/socgraph.php'); require_once('include/socgraph.php');
if($cid) if ($cid) {
$t = count_common_friends($profile_uid,$cid); $t = count_common_friends($profile_uid,$cid);
else } else {
$t = count_common_friends_zcid($profile_uid,$zcid); $t = count_common_friends_zcid($profile_uid,$zcid);
if(! $t) }
if (! $t) {
return; return;
}
if($cid) if ($cid) {
$r = common_friends($profile_uid,$cid,0,5,true); $r = common_friends($profile_uid,$cid,0,5,true);
else } else {
$r = common_friends_zcid($profile_uid,$zcid,0,5,true); $r = common_friends_zcid($profile_uid,$zcid,0,5,true);
}
return replace_macros(get_markup_template('remote_friends_common.tpl'), array( return replace_macros(get_markup_template('remote_friends_common.tpl'), array(
'$desc' => sprintf( tt("%d contact in common", "%d contacts in common", $t), $t), '$desc' => sprintf( tt("%d contact in common", "%d contacts in common", $t), $t),

View file

@ -7,7 +7,7 @@ require_once("include/acl_selectors.php");
// Note: the code in 'item_extract_images' and 'item_redir_and_replace_images' // Note: the code in 'item_extract_images' and 'item_redir_and_replace_images'
// is identical to the code in mod/message.php for 'item_extract_images' and // is identical to the code in mod/message.php for 'item_extract_images' and
// 'item_redir_and_replace_images' // 'item_redir_and_replace_images'
if(! function_exists('item_extract_images')) { if (! function_exists('item_extract_images')) {
function item_extract_images($body) { function item_extract_images($body) {
$saved_image = array(); $saved_image = array();
@ -18,12 +18,12 @@ function item_extract_images($body) {
$img_start = strpos($orig_body, '[img'); $img_start = strpos($orig_body, '[img');
$img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false); $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
$img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false); $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
while(($img_st_close !== false) && ($img_end !== false)) { while (($img_st_close !== false) && ($img_end !== false)) {
$img_st_close++; // make it point to AFTER the closing bracket $img_st_close++; // make it point to AFTER the closing bracket
$img_end += $img_start; $img_end += $img_start;
if(! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) { if (! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
// This is an embedded image // This is an embedded image
$saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close)); $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
@ -36,7 +36,7 @@ function item_extract_images($body) {
$orig_body = substr($orig_body, $img_end + strlen('[/img]')); $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
if($orig_body === false) // in case the body ends on a closing image tag if ($orig_body === false) // in case the body ends on a closing image tag
$orig_body = ''; $orig_body = '';
$img_start = strpos($orig_body, '[img'); $img_start = strpos($orig_body, '[img');
@ -49,7 +49,7 @@ function item_extract_images($body) {
return array('body' => $new_body, 'images' => $saved_image); return array('body' => $new_body, 'images' => $saved_image);
}} }}
if(! function_exists('item_redir_and_replace_images')) { if (! function_exists('item_redir_and_replace_images')) {
function item_redir_and_replace_images($body, $images, $cid) { function item_redir_and_replace_images($body, $images, $cid) {
$origbody = $body; $origbody = $body;
@ -57,7 +57,7 @@ function item_redir_and_replace_images($body, $images, $cid) {
$cnt = 1; $cnt = 1;
$pos = get_bb_tag_pos($origbody, 'url', 1); $pos = get_bb_tag_pos($origbody, 'url', 1);
while($pos !== false && $cnt < 1000) { while ($pos !== false && $cnt < 1000) {
$search = '/\[url\=(.*?)\]\[!#saved_image([0-9]*)#!\]\[\/url\]' . '/is'; $search = '/\[url\=(.*?)\]\[!#saved_image([0-9]*)#!\]\[\/url\]' . '/is';
$replace = '[url=' . z_path() . '/redir/' . $cid $replace = '[url=' . z_path() . '/redir/' . $cid
@ -66,7 +66,7 @@ function item_redir_and_replace_images($body, $images, $cid) {
$newbody .= substr($origbody, 0, $pos['start']['open']); $newbody .= substr($origbody, 0, $pos['start']['open']);
$subject = substr($origbody, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']); $subject = substr($origbody, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
$origbody = substr($origbody, $pos['end']['close']); $origbody = substr($origbody, $pos['end']['close']);
if($origbody === false) if ($origbody === false)
$origbody = ''; $origbody = '';
$subject = preg_replace($search, $replace, $subject); $subject = preg_replace($search, $replace, $subject);
@ -96,7 +96,7 @@ function item_redir_and_replace_images($body, $images, $cid) {
function localize_item(&$item){ function localize_item(&$item){
$extracted = item_extract_images($item['body']); $extracted = item_extract_images($item['body']);
if($extracted['images']) if ($extracted['images'])
$item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']); $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
$xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">"; $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
@ -126,7 +126,7 @@ function localize_item(&$item){
} }
break; break;
default: default:
if($obj['resource-id']){ if ($obj['resource-id']){
$post_type = t('photo'); $post_type = t('photo');
$m=array(); preg_match("/\[url=([^]]*)\]/", $obj['body'], $m); $m=array(); preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
$rr['plink'] = $m[1]; $rr['plink'] = $m[1];
@ -137,19 +137,19 @@ function localize_item(&$item){
$plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]'; $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
if(activity_match($item['verb'],ACTIVITY_LIKE)) { if (activity_match($item['verb'],ACTIVITY_LIKE)) {
$bodyverb = t('%1$s likes %2$s\'s %3$s'); $bodyverb = t('%1$s likes %2$s\'s %3$s');
} }
elseif(activity_match($item['verb'],ACTIVITY_DISLIKE)) { elseif (activity_match($item['verb'],ACTIVITY_DISLIKE)) {
$bodyverb = t('%1$s doesn\'t like %2$s\'s %3$s'); $bodyverb = t('%1$s doesn\'t like %2$s\'s %3$s');
} }
elseif(activity_match($item['verb'],ACTIVITY_ATTEND)) { elseif (activity_match($item['verb'],ACTIVITY_ATTEND)) {
$bodyverb = t('%1$s attends %2$s\'s %3$s'); $bodyverb = t('%1$s attends %2$s\'s %3$s');
} }
elseif(activity_match($item['verb'],ACTIVITY_ATTENDNO)) { elseif (activity_match($item['verb'],ACTIVITY_ATTENDNO)) {
$bodyverb = t('%1$s doesn\'t attend %2$s\'s %3$s'); $bodyverb = t('%1$s doesn\'t attend %2$s\'s %3$s');
} }
elseif(activity_match($item['verb'],ACTIVITY_ATTENDMAYBE)) { elseif (activity_match($item['verb'],ACTIVITY_ATTENDMAYBE)) {
$bodyverb = t('%1$s attends maybe %2$s\'s %3$s'); $bodyverb = t('%1$s attends maybe %2$s\'s %3$s');
} }
$item['body'] = sprintf($bodyverb, $author, $objauthor, $plink); $item['body'] = sprintf($bodyverb, $author, $objauthor, $plink);
@ -187,7 +187,7 @@ function localize_item(&$item){
} }
if (stristr($item['verb'],ACTIVITY_POKE)) { if (stristr($item['verb'],ACTIVITY_POKE)) {
$verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1)); $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
if(! $verb) if (! $verb)
return; return;
if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return; if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return;
@ -229,7 +229,7 @@ function localize_item(&$item){
} }
if (stristr($item['verb'],ACTIVITY_MOOD)) { if (stristr($item['verb'],ACTIVITY_MOOD)) {
$verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1)); $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
if(! $verb) if (! $verb)
return; return;
$Aname = $item['author-name']; $Aname = $item['author-name'];
@ -262,7 +262,7 @@ function localize_item(&$item){
} }
break; break;
default: default:
if($obj['resource-id']){ if ($obj['resource-id']){
$post_type = t('photo'); $post_type = t('photo');
$m=array(); preg_match("/\[url=([^]]*)\]/", $obj['body'], $m); $m=array(); preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
$rr['plink'] = $m[1]; $rr['plink'] = $m[1];
@ -289,7 +289,7 @@ function localize_item(&$item){
$xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">"; $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
$obj = parse_xml_string($xmlhead.$item['object']); $obj = parse_xml_string($xmlhead.$item['object']);
if(strlen($obj->id)) { if (strlen($obj->id)) {
$r = q("select * from item where uri = '%s' and uid = %d limit 1", $r = q("select * from item where uri = '%s' and uid = %d limit 1",
dbesc($obj->id), dbesc($obj->id),
intval($item['uid']) intval($item['uid'])
@ -307,16 +307,17 @@ function localize_item(&$item){
} }
} }
$matches = null; $matches = null;
if(preg_match_all('/@\[url=(.*?)\]/is',$item['body'],$matches,PREG_SET_ORDER)) { if (preg_match_all('/@\[url=(.*?)\]/is',$item['body'],$matches,PREG_SET_ORDER)) {
foreach($matches as $mtch) { foreach ($matches as $mtch) {
if(! strpos($mtch[1],'zrl=')) if (! strpos($mtch[1],'zrl=')) {
$item['body'] = str_replace($mtch[0],'@[url=' . zrl($mtch[1]). ']',$item['body']); $item['body'] = str_replace($mtch[0],'@[url=' . zrl($mtch[1]). ']',$item['body']);
} }
} }
}
// add zrl's to public images // add zrl's to public images
$photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is"; $photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is";
if(preg_match($photo_pattern,$item['body'])) { if (preg_match($photo_pattern,$item['body'])) {
$photo_replace = '[url=' . zrl('$1' . '/photos/' . '$2' . '/image/' . '$3' ,true) . '][img' . '$4' . ']h' . '$5' . '[/img][/url]'; $photo_replace = '[url=' . zrl('$1' . '/photos/' . '$2' . '/image/' . '$3' ,true) . '][img' . '$4' . ']h' . '$5' . '[/img][/url]';
$item['body'] = bb_tag_preg_replace($photo_pattern, $photo_replace, 'url', $item['body']); $item['body'] = bb_tag_preg_replace($photo_pattern, $photo_replace, 'url', $item['body']);
} }
@ -343,9 +344,9 @@ function localize_item(&$item){
function count_descendants($item) { function count_descendants($item) {
$total = count($item['children']); $total = count($item['children']);
if($total > 0) { if ($total > 0) {
foreach($item['children'] as $child) { foreach ($item['children'] as $child) {
if(! visible_activity($child)) if (! visible_activity($child))
$total --; $total --;
$total += count_descendants($child); $total += count_descendants($child);
} }
@ -360,14 +361,14 @@ function visible_activity($item) {
// in which case we handle them specially // in which case we handle them specially
$hidden_activities = array(ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE); $hidden_activities = array(ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE);
foreach($hidden_activities as $act) { foreach ($hidden_activities as $act) {
if(activity_match($item['verb'],$act)) { if (activity_match($item['verb'],$act)) {
return false; return false;
} }
} }
if(activity_match($item['verb'],ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE) { if (activity_match($item['verb'],ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE) {
if(! (($item['self']) && ($item['uid'] == local_user()))) { if (! (($item['self']) && ($item['uid'] == local_user()))) {
return false; return false;
} }
} }
@ -465,7 +466,7 @@ function item_condition() {
* *
*/ */
if(!function_exists('conversation')) { if (!function_exists('conversation')) {
function conversation(App $a, $items, $mode, $update, $preview = false) { function conversation(App $a, $items, $mode, $update, $preview = false) {
require_once('include/bbcode.php'); require_once('include/bbcode.php');
@ -480,22 +481,23 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
$arr_blocked = null; $arr_blocked = null;
if(local_user()) { if (local_user()) {
$str_blocked = get_pconfig(local_user(),'system','blocked'); $str_blocked = get_pconfig(local_user(),'system','blocked');
if($str_blocked) { if ($str_blocked) {
$arr_blocked = explode(',',$str_blocked); $arr_blocked = explode(',',$str_blocked);
for($x = 0; $x < count($arr_blocked); $x ++) for ($x = 0; $x < count($arr_blocked); $x ++) {
$arr_blocked[$x] = trim($arr_blocked[$x]); $arr_blocked[$x] = trim($arr_blocked[$x]);
} }
}
} }
$previewing = (($preview) ? ' preview ' : ''); $previewing = (($preview) ? ' preview ' : '');
if($mode === 'network') { if ($mode === 'network') {
$profile_owner = local_user(); $profile_owner = local_user();
$page_writeable = true; $page_writeable = true;
if(!$update) { if (!$update) {
// The special div is needed for liveUpdate to kick in for this page. // 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 // We only launch liveUpdate if you aren't filtering in some incompatible
// way and also you aren't writing a comment (discovered in javascript). // way and also you aren't writing a comment (discovered in javascript).
@ -520,14 +522,14 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
. "'; var profile_page = " . $a->pager['page'] . "; </script>\r\n"; . "'; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
} }
} }
else if($mode === 'profile') { else if ($mode === 'profile') {
$profile_owner = $a->profile['profile_uid']; $profile_owner = $a->profile['profile_uid'];
$page_writeable = can_write_wall($a,$profile_owner); $page_writeable = can_write_wall($a,$profile_owner);
if(!$update) { if (!$update) {
$tab = notags(trim($_GET['tab'])); $tab = notags(trim($_GET['tab']));
$tab = ( $tab ? $tab : 'posts' ); $tab = ( $tab ? $tab : 'posts' );
if($tab === 'posts') { if ($tab === 'posts') {
// This is ugly, but we can't pass the profile_uid through the session to the ajax updater, // 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. // because browser prefetching might change it on us. We have to deliver it with the page.
@ -537,40 +539,40 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
} }
} }
} }
else if($mode === 'notes') { else if ($mode === 'notes') {
$profile_owner = local_user(); $profile_owner = local_user();
$page_writeable = true; $page_writeable = true;
if(!$update) { if (!$update) {
$live_update_div = '<div id="live-notes"></div>' . "\r\n" $live_update_div = '<div id="live-notes"></div>' . "\r\n"
. "<script> var profile_uid = " . local_user() . "<script> var profile_uid = " . local_user()
. "; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n"; . "; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
} }
} }
else if($mode === 'display') { else if ($mode === 'display') {
$profile_owner = $a->profile['uid']; $profile_owner = $a->profile['uid'];
$page_writeable = can_write_wall($a,$profile_owner); $page_writeable = can_write_wall($a,$profile_owner);
if(!$update) { if (!$update) {
$live_update_div = '<div id="live-display"></div>' . "\r\n" $live_update_div = '<div id="live-display"></div>' . "\r\n"
. "<script> var profile_uid = " . $_SESSION['uid'] . ";" . "<script> var profile_uid = " . $_SESSION['uid'] . ";"
. " var profile_page = 1; </script>"; . " var profile_page = 1; </script>";
} }
} }
else if($mode === 'community') { else if ($mode === 'community') {
$profile_owner = 0; $profile_owner = 0;
$page_writeable = false; $page_writeable = false;
if(!$update) { if (!$update) {
$live_update_div = '<div id="live-community"></div>' . "\r\n" $live_update_div = '<div id="live-community"></div>' . "\r\n"
. "<script> var profile_uid = -1; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n"; . "<script> var profile_uid = -1; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
} }
} }
else if($mode === 'search') { else if ($mode === 'search') {
$live_update_div = '<div id="live-search"></div>' . "\r\n"; $live_update_div = '<div id="live-search"></div>' . "\r\n";
} }
$page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false); $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
if($update) if ($update)
$return_url = $_SESSION['return_url']; $return_url = $_SESSION['return_url'];
else else
$return_url = $_SESSION['return_url'] = $a->query_string; $return_url = $_SESSION['return_url'] = $a->query_string;
@ -594,9 +596,9 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
$page_template = get_markup_template("conversation.tpl"); $page_template = get_markup_template("conversation.tpl");
if($items && count($items)) { if ($items && count($items)) {
if($mode === 'network-new' || $mode === 'search' || $mode === 'community') { if ($mode === 'network-new' || $mode === 'search' || $mode === 'community') {
// "New Item View" on network page or search page results // "New Item View" on network page or search page results
// - just loop through the items and format them minimally for display // - just loop through the items and format them minimally for display
@ -604,17 +606,17 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
// $tpl = get_markup_template('search_item.tpl'); // $tpl = get_markup_template('search_item.tpl');
$tpl = 'search_item.tpl'; $tpl = 'search_item.tpl';
foreach($items as $item) { foreach ($items as $item) {
if($arr_blocked) { if ($arr_blocked) {
$blocked = false; $blocked = false;
foreach($arr_blocked as $b) { foreach ($arr_blocked as $b) {
if($b && link_compare($item['author-link'],$b)) { if ($b && link_compare($item['author-link'],$b)) {
$blocked = true; $blocked = true;
break; break;
} }
} }
if($blocked) if ($blocked)
continue; continue;
} }
@ -626,8 +628,8 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
$owner_name = ''; $owner_name = '';
$sparkle = ''; $sparkle = '';
if($mode === 'search' || $mode === 'community') { if ($mode === 'search' || $mode === 'community') {
if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE))) if (((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE)))
&& ($item['id'] != $item['parent'])) && ($item['id'] != $item['parent']))
continue; continue;
$nickname = $item['nickname']; $nickname = $item['nickname'];
@ -636,11 +638,11 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
$nickname = $a->user['nickname']; $nickname = $a->user['nickname'];
// prevent private email from leaking. // prevent private email from leaking.
if($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid'])
continue; continue;
$profile_name = ((strlen($item['author-name'])) ? $item['author-name'] : $item['name']); $profile_name = ((strlen($item['author-name'])) ? $item['author-name'] : $item['name']);
if($item['author-link'] && (! $item['author-name'])) if ($item['author-link'] && (! $item['author-name']))
$profile_name = $item['author-link']; $profile_name = $item['author-link'];
@ -652,7 +654,7 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
$taglist = q("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d) ORDER BY `tid`", $taglist = q("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d) ORDER BY `tid`",
intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION)); intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
foreach($taglist as $tag) { foreach ($taglist as $tag) {
if ($tag["url"] == "") if ($tag["url"] == "")
$tag["url"] = $searchpath.strtolower($tag["term"]); $tag["url"] = $searchpath.strtolower($tag["term"]);
@ -669,9 +671,9 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
$sp = false; $sp = false;
$profile_link = best_link_url($item,$sp); $profile_link = best_link_url($item,$sp);
if($profile_link === 'mailbox') if ($profile_link === 'mailbox')
$profile_link = ''; $profile_link = '';
if($sp) if ($sp)
$sparkle = ' sparkle'; $sparkle = ' sparkle';
else else
$profile_link = zrl($profile_link); $profile_link = zrl($profile_link);
@ -698,7 +700,7 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
$location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate)); $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
localize_item($item); localize_item($item);
if($mode === 'network-new') if ($mode === 'network-new')
$dropping = true; $dropping = true;
else else
$dropping = false; $dropping = false;
@ -723,7 +725,7 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
list($categories, $folders) = get_cats_and_terms($item); list($categories, $folders) = get_cats_and_terms($item);
if($a->theme['template_engine'] === 'internal') { if ($a->theme['template_engine'] === 'internal') {
$profile_name_e = template_escape($profile_name); $profile_name_e = template_escape($profile_name);
$item['title_e'] = template_escape($item['title']); $item['title_e'] = template_escape($item['title']);
$body_e = template_escape($body); $body_e = template_escape($body);
@ -818,18 +820,18 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
// But for now, this array respects the old style, just in case // But for now, this array respects the old style, just in case
$threads = array(); $threads = array();
foreach($items as $item) { foreach ($items as $item) {
if($arr_blocked) { if ($arr_blocked) {
$blocked = false; $blocked = false;
foreach($arr_blocked as $b) { foreach ($arr_blocked as $b) {
if($b && link_compare($item['author-link'],$b)) { if ($b && link_compare($item['author-link'],$b)) {
$blocked = true; $blocked = true;
break; break;
} }
} }
if($blocked) if ($blocked)
continue; continue;
} }
@ -839,10 +841,10 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
builtin_activity_puller($item, $conv_responses); builtin_activity_puller($item, $conv_responses);
// Only add what is visible // Only add what is visible
if($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) { if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
continue; continue;
} }
if(! visible_activity($item)) { if (! visible_activity($item)) {
continue; continue;
} }
@ -850,7 +852,7 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
$item['pagedrop'] = $page_dropping; $item['pagedrop'] = $page_dropping;
if($item['id'] == $item['parent']) { if ($item['id'] == $item['parent']) {
$item_object = new Item($item); $item_object = new Item($item);
$conv->add_thread($item_object); $conv->add_thread($item_object);
} }
@ -858,7 +860,7 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
$threads = $conv->get_template_data($conv_responses); $threads = $conv->get_template_data($conv_responses);
if(!$threads) { if (!$threads) {
logger('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG); logger('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG);
$threads = array(); $threads = array();
} }
@ -894,8 +896,8 @@ function best_link_url($item,&$sparkle,$ssl_state = false) {
$sparkle = true; $sparkle = true;
} }
} }
if(! $best_url) { if (! $best_url) {
if(strlen($item['author-link'])) if (strlen($item['author-link']))
$best_url = $item['author-link']; $best_url = $item['author-link'];
else else
$best_url = $item['url']; $best_url = $item['url'];
@ -910,7 +912,7 @@ function item_photo_menu($item)
{ {
$ssl_state = false; $ssl_state = false;
if(local_user()) { if (local_user()) {
$ssl_state = true; $ssl_state = true;
} }
@ -944,7 +946,7 @@ function item_photo_menu($item)
$rel = $r[0]['rel']; $rel = $r[0]['rel'];
} }
if($sparkle) { if ($sparkle) {
$status_link = $profile_link . '?url=status'; $status_link = $profile_link . '?url=status';
$photos_link = $profile_link . '?url=photos'; $photos_link = $profile_link . '?url=photos';
$profile_link = $profile_link . '?url=profile'; $profile_link = $profile_link . '?url=profile';
@ -1012,9 +1014,9 @@ function item_photo_menu($item)
* @param array &$conv_responses (already created with builtin activity structure) * @param array &$conv_responses (already created with builtin activity structure)
* @return void * @return void
*/ */
if(! function_exists('builtin_activity_puller')) { if (! function_exists('builtin_activity_puller')) {
function builtin_activity_puller($item, &$conv_responses) { function builtin_activity_puller($item, &$conv_responses) {
foreach($conv_responses as $mode => $v) { foreach ($conv_responses as $mode => $v) {
$url = ''; $url = '';
$sparkle = ''; $sparkle = '';
@ -1039,9 +1041,9 @@ function builtin_activity_puller($item, &$conv_responses) {
break; break;
} }
if((activity_match($item['verb'], $verb)) && ($item['id'] != $item['parent'])) { if ((activity_match($item['verb'], $verb)) && ($item['id'] != $item['parent'])) {
$url = $item['author-link']; $url = $item['author-link'];
if((local_user()) && (local_user() == $item['uid']) && ($item['network'] === NETWORK_DFRN) && (! $item['self']) && (link_compare($item['author-link'],$item['url']))) { if ((local_user()) && (local_user() == $item['uid']) && ($item['network'] === NETWORK_DFRN) && (! $item['self']) && (link_compare($item['author-link'],$item['url']))) {
$url = 'redir/' . $item['contact-id']; $url = 'redir/' . $item['contact-id'];
$sparkle = ' class="sparkle" '; $sparkle = ' class="sparkle" ';
} }
@ -1050,18 +1052,18 @@ function builtin_activity_puller($item, &$conv_responses) {
$url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>'; $url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
if(! $item['thr-parent']) if (! $item['thr-parent'])
$item['thr-parent'] = $item['parent-uri']; $item['thr-parent'] = $item['parent-uri'];
if(! ((isset($conv_responses[$mode][$item['thr-parent'] . '-l'])) if (! ((isset($conv_responses[$mode][$item['thr-parent'] . '-l']))
&& (is_array($conv_responses[$mode][$item['thr-parent'] . '-l'])))) && (is_array($conv_responses[$mode][$item['thr-parent'] . '-l']))))
$conv_responses[$mode][$item['thr-parent'] . '-l'] = array(); $conv_responses[$mode][$item['thr-parent'] . '-l'] = array();
// only list each unique author once // only list each unique author once
if(in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l'])) if (in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l']))
continue; continue;
if(! isset($conv_responses[$mode][$item['thr-parent']])) if (! isset($conv_responses[$mode][$item['thr-parent']]))
$conv_responses[$mode][$item['thr-parent']] = 1; $conv_responses[$mode][$item['thr-parent']] = 1;
else else
$conv_responses[$mode][$item['thr-parent']] ++; $conv_responses[$mode][$item['thr-parent']] ++;
@ -1085,12 +1087,12 @@ function builtin_activity_puller($item, &$conv_responses) {
// $id = item id // $id = item id
// returns formatted text // returns formatted text
if(! function_exists('format_like')) { if (! function_exists('format_like')) {
function format_like($cnt,$arr,$type,$id) { function format_like($cnt,$arr,$type,$id) {
$o = ''; $o = '';
$expanded = ''; $expanded = '';
if($cnt == 1) { if ($cnt == 1) {
$likers = $arr[0]; $likers = $arr[0];
// Phrase if there is only one liker. In other cases it will be uses for the expanded // Phrase if there is only one liker. In other cases it will be uses for the expanded
@ -1114,16 +1116,16 @@ function format_like($cnt,$arr,$type,$id) {
} }
} }
if($cnt > 1) { if ($cnt > 1) {
$total = count($arr); $total = count($arr);
if($total >= MAX_LIKERS) if ($total >= MAX_LIKERS)
$arr = array_slice($arr, 0, MAX_LIKERS - 1); $arr = array_slice($arr, 0, MAX_LIKERS - 1);
if($total < MAX_LIKERS) { if ($total < MAX_LIKERS) {
$last = t('and') . ' ' . $arr[count($arr)-1]; $last = t('and') . ' ' . $arr[count($arr)-1];
$arr2 = array_slice($arr, 0, -1); $arr2 = array_slice($arr, 0, -1);
$str = implode(', ', $arr2) . ' ' . $last; $str = implode(', ', $arr2) . ' ' . $last;
} }
if($total >= MAX_LIKERS) { if ($total >= MAX_LIKERS) {
$str = implode(', ', $arr); $str = implode(', ', $arr);
$str .= sprintf( t(', and %d other people'), $total - MAX_LIKERS ); $str .= sprintf( t(', and %d other people'), $total - MAX_LIKERS );
} }
@ -1211,17 +1213,17 @@ function status_editor($a,$x, $notes_cid = 0, $popup=false) {
// Private/public post links for the non-JS ACL form // Private/public post links for the non-JS ACL form
$private_post = 1; $private_post = 1;
if($_REQUEST['public']) if ($_REQUEST['public'])
$private_post = 0; $private_post = 0;
$query_str = $a->query_string; $query_str = $a->query_string;
if(strpos($query_str, 'public=1') !== false) if (strpos($query_str, 'public=1') !== false)
$query_str = str_replace(array('?public=1', '&public=1'), array('', ''), $query_str); $query_str = str_replace(array('?public=1', '&public=1'), array('', ''), $query_str);
// I think $a->query_string may never have ? in it, but I could be wrong // I think $a->query_string may never have ? in it, but I could be wrong
// It looks like it's from the index.php?q=[etc] rewrite that the web // It looks like it's from the index.php?q=[etc] rewrite that the web
// server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61 // server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
if(strpos($query_str, '?') === false) if (strpos($query_str, '?') === false)
$public_post_link = '?public=1'; $public_post_link = '?public=1';
else else
$public_post_link = '&public=1'; $public_post_link = '&public=1';
@ -1302,20 +1304,20 @@ function status_editor($a,$x, $notes_cid = 0, $popup=false) {
function get_item_children($arr, $parent) { function get_item_children($arr, $parent) {
$children = array(); $children = array();
$a = get_app(); $a = get_app();
foreach($arr as $item) { foreach ($arr as $item) {
if($item['id'] != $item['parent']) { if ($item['id'] != $item['parent']) {
if(get_config('system','thread_allow') && $a->theme_thread_allow) { if (get_config('system','thread_allow') && $a->theme_thread_allow) {
// Fallback to parent-uri if thr-parent is not set // Fallback to parent-uri if thr-parent is not set
$thr_parent = $item['thr-parent']; $thr_parent = $item['thr-parent'];
if($thr_parent == '') if ($thr_parent == '')
$thr_parent = $item['parent-uri']; $thr_parent = $item['parent-uri'];
if($thr_parent == $parent['uri']) { if ($thr_parent == $parent['uri']) {
$item['children'] = get_item_children($arr, $item); $item['children'] = get_item_children($arr, $item);
$children[] = $item; $children[] = $item;
} }
} }
else if($item['parent'] == $parent['id']) { else if ($item['parent'] == $parent['id']) {
$children[] = $item; $children[] = $item;
} }
} }
@ -1326,8 +1328,8 @@ function get_item_children($arr, $parent) {
function sort_item_children($items) { function sort_item_children($items) {
$result = $items; $result = $items;
usort($result,'sort_thr_created_rev'); usort($result,'sort_thr_created_rev');
foreach($result as $k => $i) { foreach ($result as $k => $i) {
if(count($result[$k]['children'])) { if (count($result[$k]['children'])) {
$result[$k]['children'] = sort_item_children($result[$k]['children']); $result[$k]['children'] = sort_item_children($result[$k]['children']);
} }
} }
@ -1335,16 +1337,16 @@ function sort_item_children($items) {
} }
function add_children_to_list($children, &$arr) { function add_children_to_list($children, &$arr) {
foreach($children as $y) { foreach ($children as $y) {
$arr[] = $y; $arr[] = $y;
if(count($y['children'])) if (count($y['children']))
add_children_to_list($y['children'], $arr); add_children_to_list($y['children'], $arr);
} }
} }
function conv_sort($arr,$order) { function conv_sort($arr,$order) {
if((!(is_array($arr) && count($arr)))) if ((!(is_array($arr) && count($arr))))
return array(); return array();
$parents = array(); $parents = array();
@ -1353,35 +1355,40 @@ function conv_sort($arr,$order) {
// This is a preparation for having two different items with the same uri in one thread // This is a preparation for having two different items with the same uri in one thread
// This will otherwise lead to an endless loop. // This will otherwise lead to an endless loop.
foreach($arr as $x) foreach ($arr as $x)
if (!isset($newarr[$x['uri']])) if (!isset($newarr[$x['uri']]))
$newarr[$x['uri']] = $x; $newarr[$x['uri']] = $x;
$arr = $newarr; $arr = $newarr;
foreach($arr as $x) foreach ($arr as $x) {
if($x['id'] == $x['parent']) if ($x['id'] == $x['parent']) {
$parents[] = $x; $parents[] = $x;
}
}
if(stristr($order,'created')) if (stristr($order,'created')) {
usort($parents,'sort_thr_created'); usort($parents,'sort_thr_created');
elseif(stristr($order,'commented')) } elseif (stristr($order,'commented')) {
usort($parents,'sort_thr_commented'); usort($parents,'sort_thr_commented');
}
if(count($parents)) if (count($parents)) {
foreach($parents as $i=>$_x) foreach($parents as $i=>$_x) {
$parents[$i]['children'] = get_item_children($arr, $_x); $parents[$i]['children'] = get_item_children($arr, $_x);
}
}
/*foreach($arr as $x) { /*foreach ($arr as $x) {
if($x['id'] != $x['parent']) { if ($x['id'] != $x['parent']) {
$p = find_thread_parent_index($parents,$x); $p = find_thread_parent_index($parents,$x);
if($p !== false) if ($p !== false)
$parents[$p]['children'][] = $x; $parents[$p]['children'][] = $x;
} }
}*/ }*/
if(count($parents)) { if (count($parents)) {
foreach($parents as $k => $v) { foreach ($parents as $k => $v) {
if(count($parents[$k]['children'])) { if (count($parents[$k]['children'])) {
$parents[$k]['children'] = sort_item_children($parents[$k]['children']); $parents[$k]['children'] = sort_item_children($parents[$k]['children']);
/*$y = $parents[$k]['children']; /*$y = $parents[$k]['children'];
usort($y,'sort_thr_created_rev'); usort($y,'sort_thr_created_rev');
@ -1391,12 +1398,12 @@ function conv_sort($arr,$order) {
} }
$ret = array(); $ret = array();
if(count($parents)) { if (count($parents)) {
foreach($parents as $x) { foreach ($parents as $x) {
$ret[] = $x; $ret[] = $x;
if(count($x['children'])) if (count($x['children']))
add_children_to_list($x['children'], $ret); add_children_to_list($x['children'], $ret);
/*foreach($x['children'] as $y) /*foreach ($x['children'] as $y)
$ret[] = $y;*/ $ret[] = $y;*/
} }
} }
@ -1418,9 +1425,11 @@ function sort_thr_commented($a,$b) {
} }
function find_thread_parent_index($arr,$x) { function find_thread_parent_index($arr,$x) {
foreach($arr as $k => $v) foreach ($arr as $k => $v) {
if($v['id'] == $x['parent']) if ($v['id'] == $x['parent']) {
return $k; return $k;
}
}
return false; return false;
} }
@ -1434,17 +1443,16 @@ function render_location_dummy($item) {
function get_responses($conv_responses,$response_verbs,$ob,$item) { function get_responses($conv_responses,$response_verbs,$ob,$item) {
$ret = array(); $ret = array();
foreach($response_verbs as $v) { foreach ($response_verbs as $v) {
$ret[$v] = array(); $ret[$v] = array();
$ret[$v]['count'] = ((x($conv_responses[$v],$item['uri'])) ? $conv_responses[$v][$item['uri']] : ''); $ret[$v]['count'] = ((x($conv_responses[$v],$item['uri'])) ? $conv_responses[$v][$item['uri']] : '');
$ret[$v]['list'] = ((x($conv_responses[$v],$item['uri'])) ? $conv_responses[$v][$item['uri'] . '-l'] : ''); $ret[$v]['list'] = ((x($conv_responses[$v],$item['uri'])) ? $conv_responses[$v][$item['uri'] . '-l'] : '');
$ret[$v]['self'] = ((x($conv_responses[$v],$item['uri'])) ? $conv_responses[$v][$item['uri'] . '-self'] : '0'); $ret[$v]['self'] = ((x($conv_responses[$v],$item['uri'])) ? $conv_responses[$v][$item['uri'] . '-self'] : '0');
if(count($ret[$v]['list']) > MAX_LIKERS) { if (count($ret[$v]['list']) > MAX_LIKERS) {
$ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, 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-' 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>'); . (($ob) ? $ob->get_id() : $item['id']) . '"><b>' . t('View all') . '</b></a>');
} } else {
else {
$ret[$v]['list_part'] = ''; $ret[$v]['list_part'] = '';
} }
$ret[$v]['button'] = get_response_button_text($v,$ret[$v]['count']); $ret[$v]['button'] = get_response_button_text($v,$ret[$v]['count']);
@ -1452,10 +1460,11 @@ function get_responses($conv_responses,$response_verbs,$ob,$item) {
} }
$count = 0; $count = 0;
foreach($ret as $key) { foreach ($ret as $key) {
if ($key['count'] == true) if ($key['count'] == true) {
$count++; $count++;
} }
}
$ret['count'] = $count; $ret['count'] = $count;
return $ret; return $ret;

View file

@ -19,12 +19,12 @@ function cron_run(&$argv, &$argc){
$last = get_config('system','last_cron'); $last = get_config('system','last_cron');
$poll_interval = intval(get_config('system','cron_interval')); $poll_interval = intval(get_config('system','cron_interval'));
if(! $poll_interval) if (! $poll_interval)
$poll_interval = 10; $poll_interval = 10;
if($last) { if ($last) {
$next = $last + ($poll_interval * 60); $next = $last + ($poll_interval * 60);
if($next > time()) { if ($next > time()) {
logger('cron intervall not reached'); logger('cron intervall not reached');
return; return;
} }
@ -64,7 +64,7 @@ function cron_run(&$argv, &$argc){
$d1 = get_config('system','last_expire_day'); $d1 = get_config('system','last_expire_day');
$d2 = intval(datetime_convert('UTC','UTC','now','d')); $d2 = intval(datetime_convert('UTC','UTC','now','d'));
if($d2 != intval($d1)) { if ($d2 != intval($d1)) {
update_contact_birthdays(); update_contact_birthdays();
@ -126,7 +126,7 @@ function cron_expire_and_remove_users() {
// delete user and contact records for recently removed accounts // delete user and contact records for recently removed accounts
$r = q("SELECT * FROM `user` WHERE `account_removed` AND `account_expires_on` < UTC_TIMESTAMP() - INTERVAL 3 DAY"); $r = q("SELECT * FROM `user` WHERE `account_removed` AND `account_expires_on` < UTC_TIMESTAMP() - INTERVAL 3 DAY");
if ($r) { if ($r) {
foreach($r as $user) { foreach ($r as $user) {
q("DELETE FROM `contact` WHERE `uid` = %d", intval($user['uid'])); q("DELETE FROM `contact` WHERE `uid` = %d", intval($user['uid']));
q("DELETE FROM `user` WHERE `uid` = %d", intval($user['uid'])); q("DELETE FROM `user` WHERE `uid` = %d", intval($user['uid']));
} }
@ -171,7 +171,7 @@ function cron_poll_contacts($argc, $argv) {
// we are unable to match those posts with a Diaspora GUID and prevent duplicates. // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
$abandon_days = intval(get_config('system','account_abandon_days')); $abandon_days = intval(get_config('system','account_abandon_days'));
if($abandon_days < 1) if ($abandon_days < 1)
$abandon_days = 0; $abandon_days = 0;
$abandon_sql = (($abandon_days) $abandon_sql = (($abandon_days)
@ -210,7 +210,7 @@ function cron_poll_contacts($argc, $argv) {
continue; continue;
} }
foreach($res as $contact) { foreach ($res as $contact) {
$xml = false; $xml = false;
@ -232,7 +232,7 @@ function cron_poll_contacts($argc, $argv) {
$contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3); $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
} }
if($contact['priority'] AND !$force) { if ($contact['priority'] AND !$force) {
$update = false; $update = false;
@ -244,24 +244,24 @@ function cron_poll_contacts($argc, $argv) {
switch ($contact['priority']) { switch ($contact['priority']) {
case 5: case 5:
if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 month")) if (datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 month"))
$update = true; $update = true;
break; break;
case 4: case 4:
if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 week")) if (datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 week"))
$update = true; $update = true;
break; break;
case 3: case 3:
if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day")) if (datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
$update = true; $update = true;
break; break;
case 2: case 2:
if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 12 hour")) if (datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 12 hour"))
$update = true; $update = true;
break; break;
case 1: case 1:
default: default:
if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 hour")) if (datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 hour"))
$update = true; $update = true;
break; break;
} }
@ -289,14 +289,16 @@ function cron_clear_cache(App $a) {
$last = get_config('system','cache_last_cleared'); $last = get_config('system','cache_last_cleared');
if($last) { if ($last) {
$next = $last + (3600); // Once per hour $next = $last + (3600); // Once per hour
$clear_cache = ($next <= time()); $clear_cache = ($next <= time());
} else } else {
$clear_cache = true; $clear_cache = true;
}
if (!$clear_cache) if (!$clear_cache) {
return; return;
}
// clear old cache // clear old cache
Cache::clear(); Cache::clear();
@ -315,7 +317,9 @@ function cron_clear_cache(App $a) {
clear_cache($a->get_basepath(), $a->get_basepath()."/proxy"); clear_cache($a->get_basepath(), $a->get_basepath()."/proxy");
$cachetime = get_config('system','proxy_cache_time'); $cachetime = get_config('system','proxy_cache_time');
if (!$cachetime) $cachetime = PROXY_DEFAULT_TIME; if (!$cachetime) {
$cachetime = PROXY_DEFAULT_TIME;
}
q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%" AND `created` < NOW() - INTERVAL %d SECOND', $cachetime); q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%" AND `created` < NOW() - INTERVAL %d SECOND', $cachetime);
} }
@ -328,26 +332,30 @@ function cron_clear_cache(App $a) {
// Maximum table size in megabyte // Maximum table size in megabyte
$max_tablesize = intval(get_config('system','optimize_max_tablesize')) * 1000000; $max_tablesize = intval(get_config('system','optimize_max_tablesize')) * 1000000;
if ($max_tablesize == 0) if ($max_tablesize == 0) {
$max_tablesize = 100 * 1000000; // Default are 100 MB $max_tablesize = 100 * 1000000; // Default are 100 MB
}
if ($max_tablesize > 0) { if ($max_tablesize > 0) {
// Minimum fragmentation level in percent // Minimum fragmentation level in percent
$fragmentation_level = intval(get_config('system','optimize_fragmentation')) / 100; $fragmentation_level = intval(get_config('system','optimize_fragmentation')) / 100;
if ($fragmentation_level == 0) if ($fragmentation_level == 0) {
$fragmentation_level = 0.3; // Default value is 30% $fragmentation_level = 0.3; // Default value is 30%
}
// Optimize some tables that need to be optimized // Optimize some tables that need to be optimized
$r = q("SHOW TABLE STATUS"); $r = q("SHOW TABLE STATUS");
foreach($r as $table) { foreach ($r as $table) {
// Don't optimize tables that are too large // Don't optimize tables that are too large
if ($table["Data_length"] > $max_tablesize) if ($table["Data_length"] > $max_tablesize) {
continue; continue;
}
// Don't optimize empty tables // Don't optimize empty tables
if ($table["Data_length"] == 0) if ($table["Data_length"] == 0) {
continue; continue;
}
// Calculate fragmentation // Calculate fragmentation
$fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]); $fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]);
@ -355,8 +363,9 @@ function cron_clear_cache(App $a) {
logger("Table ".$table["Name"]." - Fragmentation level: ".round($fragmentation * 100, 2), LOGGER_DEBUG); logger("Table ".$table["Name"]." - Fragmentation level: ".round($fragmentation * 100, 2), LOGGER_DEBUG);
// Don't optimize tables that needn't to be optimized // Don't optimize tables that needn't to be optimized
if ($fragmentation < $fragmentation_level) if ($fragmentation < $fragmentation_level) {
continue; continue;
}
// So optimize it // So optimize it
logger("Optimize Table ".$table["Name"], LOGGER_DEBUG); logger("Optimize Table ".$table["Name"], LOGGER_DEBUG);
@ -416,9 +425,11 @@ function cron_repair_database() {
// Update the global contacts for local users // Update the global contacts for local users
$r = q("SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`"); $r = q("SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`");
if (dbm::is_result($r)) if (dbm::is_result($r)) {
foreach ($r AS $user) foreach ($r AS $user) {
update_gcontact_for_user($user["uid"]); update_gcontact_for_user($user["uid"]);
}
}
/// @todo /// @todo
/// - remove thread entries without item /// - remove thread entries without item

View file

@ -8,23 +8,25 @@ function cronhooks_run(&$argv, &$argc){
require_once('include/datetime.php'); require_once('include/datetime.php');
if (($argc == 2) AND is_array($a->hooks) AND array_key_exists("cron", $a->hooks)) { if (($argc == 2) AND is_array($a->hooks) AND array_key_exists("cron", $a->hooks)) {
foreach ($a->hooks["cron"] as $hook) foreach ($a->hooks["cron"] as $hook) {
if ($hook[1] == $argv[1]) { if ($hook[1] == $argv[1]) {
logger("Calling cron hook '".$hook[1]."'", LOGGER_DEBUG); logger("Calling cron hook '".$hook[1]."'", LOGGER_DEBUG);
call_single_hook($a, $name, $hook, $data); call_single_hook($a, $name, $hook, $data);
} }
}
return; return;
} }
$last = get_config('system', 'last_cronhook'); $last = get_config('system', 'last_cronhook');
$poll_interval = intval(get_config('system','cronhook_interval')); $poll_interval = intval(get_config('system','cronhook_interval'));
if(! $poll_interval) if (! $poll_interval) {
$poll_interval = 9; $poll_interval = 9;
}
if($last) { if ($last) {
$next = $last + ($poll_interval * 60); $next = $last + ($poll_interval * 60);
if($next > time()) { if ($next > time()) {
logger('cronhook intervall not reached'); logger('cronhook intervall not reached');
return; return;
} }

View file

@ -12,7 +12,7 @@ function rsa_sign($data,$key,$alg = 'sha256') {
openssl_sign($data,$sig,$key,(($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg)); openssl_sign($data,$sig,$key,(($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
} }
else { else {
if(strlen($key) < 1024 || extension_loaded('gmp')) { if (strlen($key) < 1024 || extension_loaded('gmp')) {
require_once('library/phpsec/Crypt/RSA.php'); require_once('library/phpsec/Crypt/RSA.php');
$rsa = new CRYPT_RSA(); $rsa = new CRYPT_RSA();
$rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1; $rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1;
@ -34,7 +34,7 @@ function rsa_verify($data,$sig,$key,$alg = 'sha256') {
$verify = openssl_verify($data,$sig,$key,(($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg)); $verify = openssl_verify($data,$sig,$key,(($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
} }
else { else {
if(strlen($key) <= 300 || extension_loaded('gmp')) { if (strlen($key) <= 300 || extension_loaded('gmp')) {
require_once('library/phpsec/Crypt/RSA.php'); require_once('library/phpsec/Crypt/RSA.php');
$rsa = new CRYPT_RSA(); $rsa = new CRYPT_RSA();
$rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1; $rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1;
@ -186,12 +186,12 @@ function salmon_key($pubkey) {
if(! function_exists('aes_decrypt')) { if (! function_exists('aes_decrypt')) {
// DEPRECATED IN 3.4.1 // DEPRECATED IN 3.4.1
function aes_decrypt($val,$ky) function aes_decrypt($val,$ky)
{ {
$key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; $key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
for($a=0;$a<strlen($ky);$a++) for ($a=0;$a<strlen($ky);$a++)
$key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a])); $key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
$mode = MCRYPT_MODE_ECB; $mode = MCRYPT_MODE_ECB;
$enc = MCRYPT_RIJNDAEL_128; $enc = MCRYPT_RIJNDAEL_128;
@ -200,12 +200,12 @@ function aes_decrypt($val,$ky)
}} }}
if(! function_exists('aes_encrypt')) { if (! function_exists('aes_encrypt')) {
// DEPRECATED IN 3.4.1 // DEPRECATED IN 3.4.1
function aes_encrypt($val,$ky) function aes_encrypt($val,$ky)
{ {
$key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; $key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
for($a=0;$a<strlen($ky);$a++) for ($a=0;$a<strlen($ky);$a++)
$key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a])); $key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
$mode=MCRYPT_MODE_ECB; $mode=MCRYPT_MODE_ECB;
$enc=MCRYPT_RIJNDAEL_128; $enc=MCRYPT_RIJNDAEL_128;
@ -237,12 +237,12 @@ function new_keypair($bits) {
); );
$conf = get_config('system','openssl_conf_file'); $conf = get_config('system','openssl_conf_file');
if($conf) if ($conf)
$openssl_options['config'] = $conf; $openssl_options['config'] = $conf;
$result = openssl_pkey_new($openssl_options); $result = openssl_pkey_new($openssl_options);
if(empty($result)) { if (empty($result)) {
logger('new_keypair: failed'); logger('new_keypair: failed');
return false; return false;
} }

View file

@ -14,12 +14,12 @@ use \Friendica\Core\Config;
* @return int * @return int
*/ */
function timezone_cmp($a, $b) { function timezone_cmp($a, $b) {
if(strstr($a,'/') && strstr($b,'/')) { if (strstr($a,'/') && strstr($b,'/')) {
if ( t($a) == t($b)) return 0; if ( t($a) == t($b)) return 0;
return ( t($a) < t($b)) ? -1 : 1; return ( t($a) < t($b)) ? -1 : 1;
} }
if(strstr($a,'/')) return -1; if (strstr($a,'/')) return -1;
if(strstr($b,'/')) return 1; if (strstr($b,'/')) return 1;
if ( t($a) == t($b)) return 0; if ( t($a) == t($b)) return 0;
return ( t($a) < t($b)) ? -1 : 1; return ( t($a) < t($b)) ? -1 : 1;
@ -39,23 +39,23 @@ function select_timezone($current = 'America/Los_Angeles') {
usort($timezone_identifiers, 'timezone_cmp'); usort($timezone_identifiers, 'timezone_cmp');
$continent = ''; $continent = '';
foreach($timezone_identifiers as $value) { foreach ($timezone_identifiers as $value) {
$ex = explode("/", $value); $ex = explode("/", $value);
if(count($ex) > 1) { if (count($ex) > 1) {
if($ex[0] != $continent) { if ($ex[0] != $continent) {
if($continent != '') if ($continent != '')
$o .= '</optgroup>'; $o .= '</optgroup>';
$continent = $ex[0]; $continent = $ex[0];
$o .= '<optgroup label="' . t($continent) . '">'; $o .= '<optgroup label="' . t($continent) . '">';
} }
if(count($ex) > 2) if (count($ex) > 2) {
$city = substr($value,strpos($value,'/')+1); $city = substr($value,strpos($value,'/')+1);
else } else {
$city = $ex[1]; $city = $ex[1];
} }
else { } else {
$city = $ex[0]; $city = $ex[0];
if($continent != t('Miscellaneous')) { if ($continent != t('Miscellaneous')) {
$o .= '</optgroup>'; $o .= '</optgroup>';
$continent = t('Miscellaneous'); $continent = t('Miscellaneous');
$o .= '<optgroup label="' . t($continent) . '">'; $o .= '<optgroup label="' . t($continent) . '">';
@ -114,11 +114,11 @@ function datetime_convert($from = 'UTC', $to = 'UTC', $s = 'now', $fmt = "Y-m-d
// Defaults to UTC if nothing is set, but throws an exception if set to empty string. // Defaults to UTC if nothing is set, but throws an exception if set to empty string.
// Provide some sane defaults regardless. // Provide some sane defaults regardless.
if($from === '') if ($from === '')
$from = 'UTC'; $from = 'UTC';
if($to === '') if ($to === '')
$to = 'UTC'; $to = 'UTC';
if( ($s === '') || (! is_string($s)) ) if ( ($s === '') || (! is_string($s)) )
$s = 'now'; $s = 'now';
// Slight hackish adjustment so that 'zero' datetime actually returns what is intended // Slight hackish adjustment so that 'zero' datetime actually returns what is intended
@ -126,7 +126,7 @@ function datetime_convert($from = 'UTC', $to = 'UTC', $s = 'now', $fmt = "Y-m-d
// add 32 days so that we at least get year 00, and then hack around the fact that // add 32 days so that we at least get year 00, and then hack around the fact that
// months and days always start with 1. // months and days always start with 1.
if(substr($s,0,10) == '0000-00-00') { if (substr($s,0,10) == '0000-00-00') {
$d = new DateTime($s . ' + 32 days', new DateTimeZone('UTC')); $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));
} }
@ -169,9 +169,9 @@ function dob($dob) {
list($year,$month,$day) = sscanf($dob,'%4d-%2d-%2d'); list($year,$month,$day) = sscanf($dob,'%4d-%2d-%2d');
$f = get_config('system','birthday_input_format'); $f = get_config('system','birthday_input_format');
if(! $f) if (! $f)
$f = 'ymd'; $f = 'ymd';
if($dob === '0000-00-00') if ($dob === '0000-00-00')
$value = ''; $value = '';
else else
$value = (($year) ? datetime_convert('UTC','UTC',$dob,'Y-m-d') : datetime_convert('UTC','UTC',$dob,'m-d')); $value = (($year) ? datetime_convert('UTC','UTC',$dob,'Y-m-d') : datetime_convert('UTC','UTC',$dob,'m-d'));
@ -279,9 +279,9 @@ function datetimesel($format, $min, $max, $default, $label, $id = 'datetimepicke
$o = ''; $o = '';
$dateformat = ''; $dateformat = '';
if($pickdate) $dateformat .= 'Y-m-d'; if ($pickdate) $dateformat .= 'Y-m-d';
if($pickdate && $picktime) $dateformat .= ' '; if ($pickdate && $picktime) $dateformat .= ' ';
if($picktime) $dateformat .= 'H:i'; if ($picktime) $dateformat .= 'H:i';
$minjs = $min ? ",minDate: new Date({$min->getTimestamp()}*1000), yearStart: " . $min->format('Y') : ''; $minjs = $min ? ",minDate: new Date({$min->getTimestamp()}*1000), yearStart: " . $min->format('Y') : '';
$maxjs = $max ? ",maxDate: new Date({$max->getTimestamp()}*1000), yearEnd: " . $max->format('Y') : ''; $maxjs = $max ? ",maxDate: new Date({$max->getTimestamp()}*1000), yearEnd: " . $max->format('Y') : '';
@ -290,14 +290,14 @@ function datetimesel($format, $min, $max, $default, $label, $id = 'datetimepicke
$defaultdatejs = $default ? ",defaultDate: new Date({$default->getTimestamp()}*1000)" : ''; $defaultdatejs = $default ? ",defaultDate: new Date({$default->getTimestamp()}*1000)" : '';
$pickers = ''; $pickers = '';
if(!$pickdate) $pickers .= ',datepicker: false'; if (!$pickdate) $pickers .= ',datepicker: false';
if(!$picktime) $pickers .= ',timepicker: false'; if (!$picktime) $pickers .= ',timepicker: false';
$extra_js = ''; $extra_js = '';
$pickers .= ",dayOfWeekStart: ".$firstDay.",lang:'".$lang."'"; $pickers .= ",dayOfWeekStart: ".$firstDay.",lang:'".$lang."'";
if($minfrom != '') if ($minfrom != '')
$extra_js .= "\$('#id_$minfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({minDate: currentDateTime})}})"; $extra_js .= "\$('#id_$minfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({minDate: currentDateTime})}})";
if($maxfrom != '') if ($maxfrom != '')
$extra_js .= "\$('#id_$maxfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({maxDate: currentDateTime})}})"; $extra_js .= "\$('#id_$maxfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({maxDate: currentDateTime})}})";
$readable_format = $dateformat; $readable_format = $dateformat;
@ -394,11 +394,11 @@ function relative_date($posted_date, $format = null) {
* @return int Age in years * @return int Age in years
*/ */
function age($dob,$owner_tz = '',$viewer_tz = '') { function age($dob,$owner_tz = '',$viewer_tz = '') {
if(! intval($dob)) if (! intval($dob))
return 0; return 0;
if(! $owner_tz) if (! $owner_tz)
$owner_tz = date_default_timezone_get(); $owner_tz = date_default_timezone_get();
if(! $viewer_tz) if (! $viewer_tz)
$viewer_tz = date_default_timezone_get(); $viewer_tz = date_default_timezone_get();
$birthdate = datetime_convert('UTC',$owner_tz,$dob . ' 00:00:00+00:00','Y-m-d'); $birthdate = datetime_convert('UTC',$owner_tz,$dob . ' 00:00:00+00:00','Y-m-d');
@ -407,7 +407,7 @@ function age($dob,$owner_tz = '',$viewer_tz = '') {
$curr_month = datetime_convert('UTC',$viewer_tz,'now','m'); $curr_month = datetime_convert('UTC',$viewer_tz,'now','m');
$curr_day = datetime_convert('UTC',$viewer_tz,'now','d'); $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--; $year_diff--;
return $year_diff; return $year_diff;
@ -430,10 +430,10 @@ function get_dim($y,$m) {
31, 28, 31, 30, 31, 30, 31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31); 31, 31, 30, 31, 30, 31);
if($m != 2) if ($m != 2)
return $dim[$m]; return $dim[$m];
if(((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0)) if (((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0))
return 29; return 29;
return $dim[2]; return $dim[2];
@ -486,10 +486,12 @@ function cal($y = 0,$m = 0, $links = false, $class='') {
$thisyear = datetime_convert('UTC',date_default_timezone_get(),'now','Y'); $thisyear = datetime_convert('UTC',date_default_timezone_get(),'now','Y');
$thismonth = datetime_convert('UTC',date_default_timezone_get(),'now','m'); $thismonth = datetime_convert('UTC',date_default_timezone_get(),'now','m');
if(! $y) if (! $y) {
$y = $thisyear; $y = $thisyear;
if(! $m) }
if (! $m) {
$m = intval($thismonth); $m = intval($thismonth);
}
$dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); $dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
$f = get_first_dim($y,$m); $f = get_first_dim($y,$m);
@ -498,29 +500,33 @@ function cal($y = 0,$m = 0, $links = false, $class='') {
$dow = 0; $dow = 0;
$started = false; $started = false;
if(($y == $thisyear) && ($m == $thismonth)) if (($y == $thisyear) && ($m == $thismonth)) {
$tddate = intval(datetime_convert('UTC',date_default_timezone_get(),'now','j')); $tddate = intval(datetime_convert('UTC',date_default_timezone_get(),'now','j'));
}
$str_month = day_translate($mtab[$m]); $str_month = day_translate($mtab[$m]);
$o = '<table class="calendar' . $class . '">'; $o = '<table class="calendar' . $class . '">';
$o .= "<caption>$str_month $y</caption><tr>"; $o .= "<caption>$str_month $y</caption><tr>";
for($a = 0; $a < 7; $a ++) for ($a = 0; $a < 7; $a ++) {
$o .= '<th>' . mb_substr(day_translate($dn[$a]),0,3,'UTF-8') . '</th>'; $o .= '<th>' . mb_substr(day_translate($dn[$a]),0,3,'UTF-8') . '</th>';
}
$o .= '</tr><tr>'; $o .= '</tr><tr>';
while($d <= $l) { while ($d <= $l) {
if(($dow == $f) && (! $started)) if (($dow == $f) && (! $started)) {
$started = true; $started = true;
}
$today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : ''); $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
$o .= "<td $today>"; $o .= "<td $today>";
$day = str_replace(' ','&nbsp;',sprintf('%2.2d', $d)); $day = str_replace(' ','&nbsp;',sprintf('%2.2d', $d));
if($started) { if ($started) {
if(is_array($links) && isset($links[$d])) if (is_array($links) && isset($links[$d])) {
$o .= "<a href=\"{$links[$d]}\">$day</a>"; $o .= "<a href=\"{$links[$d]}\">$day</a>";
else } else {
$o .= $day; $o .= $day;
}
$d ++; $d ++;
} else { } else {
@ -529,14 +535,16 @@ function cal($y = 0,$m = 0, $links = false, $class='') {
$o .= '</td>'; $o .= '</td>';
$dow ++; $dow ++;
if(($dow == 7) && ($d <= $l)) { if (($dow == 7) && ($d <= $l)) {
$dow = 0; $dow = 0;
$o .= '</tr><tr>'; $o .= '</tr><tr>';
} }
} }
if($dow) if ($dow) {
for($a = $dow; $a < 7; $a ++) for ($a = $dow; $a < 7; $a ++) {
$o .= '<td>&nbsp;</td>'; $o .= '<td>&nbsp;</td>';
}
}
$o .= '</tr></table>'."\r\n"; $o .= '</tr></table>'."\r\n";

View file

@ -34,7 +34,7 @@ $objDDDBLResultHandler->add('PDOStatement', array('HANDLER' => $cloPDOStatementR
* *
*/ */
if(! class_exists('dba')) { if (! class_exists('dba')) {
class dba { class dba {
private $debug = 0; private $debug = 0;
@ -66,9 +66,9 @@ class dba {
return; return;
} }
if($install) { if ($install) {
if(strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) { if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
if(! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) { if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
$this->error = sprintf( t('Cannot locate DNS info for database server \'%s\''), $server); $this->error = sprintf( t('Cannot locate DNS info for database server \'%s\''), $server);
$this->connected = false; $this->connected = false;
$this->db = null; $this->db = null;
@ -81,13 +81,13 @@ class dba {
\DDDBL\connect(); \DDDBL\connect();
$this->db = \DDDBL\getDB(); $this->db = \DDDBL\getDB();
if(\DDDBL\isConnected()) { if (\DDDBL\isConnected()) {
$this->connected = true; $this->connected = true;
} }
if(! $this->connected) { if (! $this->connected) {
$this->db = null; $this->db = null;
if(! $install) if (! $install)
system_unavailable(); system_unavailable();
} }
@ -109,11 +109,11 @@ class dba {
$objPreparedQueryPool = new \DDDBL\DataObjectPool('Query-Definition'); $objPreparedQueryPool = new \DDDBL\DataObjectPool('Query-Definition');
# check if query do not exists till now, if so create its definition # check if query do not exists till now, if so create its definition
if(!$objPreparedQueryPool->exists($strQueryAlias)) if (!$objPreparedQueryPool->exists($strQueryAlias))
$objPreparedQueryPool->add($strQueryAlias, array('QUERY' => $sql, $objPreparedQueryPool->add($strQueryAlias, array('QUERY' => $sql,
'HANDLER' => $strHandler)); 'HANDLER' => $strHandler));
if((! $this->db) || (! $this->connected)) if ((! $this->db) || (! $this->connected))
return false; return false;
$this->error = ''; $this->error = '';
@ -124,7 +124,7 @@ class dba {
$r = \DDDBL\get($strQueryAlias); $r = \DDDBL\get($strQueryAlias);
# bad workaround to emulate the bizzare behavior of mysql_query # bad workaround to emulate the bizzare behavior of mysql_query
if(in_array($strSQLType, array('INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'SET'))) if (in_array($strSQLType, array('INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'SET')))
$result = true; $result = true;
$intErrorCode = false; $intErrorCode = false;
@ -138,7 +138,7 @@ class dba {
$a->save_timestamp($stamp1, "database"); $a->save_timestamp($stamp1, "database");
if(x($a->config,'system') && x($a->config['system'],'db_log')) { if (x($a->config,'system') && x($a->config['system'],'db_log')) {
if (($duration > $a->config["system"]["db_loglimit"])) { if (($duration > $a->config["system"]["db_loglimit"])) {
$duration = round($duration, 3); $duration = round($duration, 3);
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
@ -149,20 +149,20 @@ class dba {
} }
} }
if($intErrorCode) if ($intErrorCode)
$this->error = $intErrorCode; $this->error = $intErrorCode;
if(strlen($this->error)) { if (strlen($this->error)) {
logger('dba: ' . $this->error); logger('dba: ' . $this->error);
} }
if($this->debug) { if ($this->debug) {
$mesg = ''; $mesg = '';
if($result === false) if ($result === false)
$mesg = 'false'; $mesg = 'false';
elseif($result === true) elseif ($result === true)
$mesg = 'true'; $mesg = 'true';
else { else {
# this needs fixing, but is a bug itself # this needs fixing, but is a bug itself
@ -182,13 +182,13 @@ class dba {
* These usually indicate SQL syntax errors that need to be resolved. * These usually indicate SQL syntax errors that need to be resolved.
*/ */
if(isset($result) AND ($result === false)) { if (isset($result) AND ($result === false)) {
logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error); logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
if(file_exists('dbfail.out')) if (file_exists('dbfail.out'))
file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND); file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
} }
if(isset($result) AND (($result === true) || ($result === false))) if (isset($result) AND (($result === true) || ($result === false)))
return $result; return $result;
if ($onlyquery) { if ($onlyquery) {
@ -199,7 +199,7 @@ class dba {
//$a->save_timestamp($stamp1, "database"); //$a->save_timestamp($stamp1, "database");
if($this->debug) if ($this->debug)
logger('dba: ' . printable(print_r($r, true))); logger('dba: ' . printable(print_r($r, true)));
return($r); return($r);
} }
@ -223,7 +223,7 @@ class dba {
} }
public function escape($str) { public function escape($str) {
if($this->db && $this->connected) { if ($this->db && $this->connected) {
$strQuoted = $this->db->quote($str); $strQuoted = $this->db->quote($str);
# this workaround is needed, because quote creates "'" and the beginning and the end # this workaround is needed, because quote creates "'" and the beginning and the end
# of the string, which is correct. but until now the queries set this delimiter manually, # of the string, which is correct. but until now the queries set this delimiter manually,
@ -238,27 +238,27 @@ class dba {
} }
}} }}
if(! function_exists('printable')) { if (! function_exists('printable')) {
function printable($s) { function printable($s) {
$s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s); $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
$s = str_replace("\x00",'.',$s); $s = str_replace("\x00",'.',$s);
if(x($_SERVER,'SERVER_NAME')) if (x($_SERVER,'SERVER_NAME'))
$s = escape_tags($s); $s = escape_tags($s);
return $s; return $s;
}} }}
// Procedural functions // Procedural functions
if(! function_exists('dbg')) { if (! function_exists('dbg')) {
function dbg($state) { function dbg($state) {
global $db; global $db;
if($db) if ($db)
$db->dbg($state); $db->dbg($state);
}} }}
if(! function_exists('dbesc')) { if (! function_exists('dbesc')) {
function dbesc($str) { function dbesc($str) {
global $db; global $db;
if($db && $db->connected) if ($db && $db->connected)
return($db->escape($str)); return($db->escape($str));
else else
return(str_replace("'","\\'",$str)); return(str_replace("'","\\'",$str));
@ -271,17 +271,17 @@ function dbesc($str) {
// Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d", // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
// 'user', 1); // 'user', 1);
if(! function_exists('q')) { if (! function_exists('q')) {
function q($sql) { function q($sql) {
global $db; global $db;
$args = func_get_args(); $args = func_get_args();
unset($args[0]); unset($args[0]);
if($db && $db->connected) { if ($db && $db->connected) {
$stmt = @vsprintf($sql,$args); // Disabled warnings $stmt = @vsprintf($sql,$args); // Disabled warnings
//logger("dba: q: $stmt", LOGGER_ALL); //logger("dba: q: $stmt", LOGGER_ALL);
if($stmt === false) if ($stmt === false)
logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG); logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
return $db->q($stmt); return $db->q($stmt);
} }
@ -303,11 +303,11 @@ function q($sql) {
* *
*/ */
if(! function_exists('dbq')) { if (! function_exists('dbq')) {
function dbq($sql) { function dbq($sql) {
global $db; global $db;
if($db && $db->connected) if ($db && $db->connected)
$ret = $db->q($sql); $ret = $db->q($sql);
else else
$ret = false; $ret = false;
@ -321,21 +321,21 @@ function dbq($sql) {
// cast to int to avoid trouble. // cast to int to avoid trouble.
if(! function_exists('dbesc_array_cb')) { if (! function_exists('dbesc_array_cb')) {
function dbesc_array_cb(&$item, $key) { function dbesc_array_cb(&$item, $key) {
if(is_string($item)) if (is_string($item))
$item = dbesc($item); $item = dbesc($item);
}} }}
if(! function_exists('dbesc_array')) { if (! function_exists('dbesc_array')) {
function dbesc_array(&$arr) { function dbesc_array(&$arr) {
if(is_array($arr) && count($arr)) { if (is_array($arr) && count($arr)) {
array_walk($arr,'dbesc_array_cb'); array_walk($arr,'dbesc_array_cb');
} }
}} }}
if(! function_exists('dba_timer')) { if (! function_exists('dba_timer')) {
function dba_timer() { function dba_timer() {
return microtime(true); return microtime(true);
}} }}

View file

@ -404,7 +404,7 @@ function db_create_table($name, $fields, $charset, $verbose, $action, $indexes=n
$sql_rows = array(); $sql_rows = array();
$primary_keys = array(); $primary_keys = array();
foreach($fields AS $fieldname => $field) { foreach ($fields AS $fieldname => $field) {
$sql_rows[] = "`".dbesc($fieldname)."` ".db_field_command($field); $sql_rows[] = "`".dbesc($fieldname)."` ".db_field_command($field);
if (x($field,'primary') and $field['primary']!=''){ if (x($field,'primary') and $field['primary']!=''){
$primary_keys[] = $fieldname; $primary_keys[] = $fieldname;
@ -1621,11 +1621,11 @@ function db_definition($charset) {
function dbstructure_run(&$argv, &$argc) { function dbstructure_run(&$argv, &$argc) {
global $a, $db; global $a, $db;
if(is_null($a)){ if (is_null($a)){
$a = new App; $a = new App;
} }
if(is_null($db)) { if (is_null($db)) {
@include(".htconfig.php"); @include(".htconfig.php");
require_once("include/dba.php"); require_once("include/dba.php");
$db = new dba($db_host, $db_user, $db_pass, $db_data); $db = new dba($db_host, $db_user, $db_pass, $db_data);
@ -1650,7 +1650,7 @@ function dbstructure_run(&$argv, &$argc) {
$current = intval(DB_UPDATE_VERSION); $current = intval(DB_UPDATE_VERSION);
// run any left update_nnnn functions in update.php // run any left update_nnnn functions in update.php
for($x = $stored; $x < $current; $x ++) { for ($x = $stored; $x < $current; $x ++) {
$r = run_update_function($x); $r = run_update_function($x);
if (!$r) break; if (!$r) break;
} }

File diff suppressed because it is too large Load diff

View file

@ -45,7 +45,7 @@ class Diaspora {
$servers = explode(",", $serverdata); $servers = explode(",", $serverdata);
foreach($servers AS $server) { foreach ($servers AS $server) {
$server = trim($server); $server = trim($server);
$addr = "relay@".str_replace("http://", "", normalise_link($server)); $addr = "relay@".str_replace("http://", "", normalise_link($server));
$batch = $server."/receive/public"; $batch = $server."/receive/public";
@ -181,7 +181,7 @@ class Diaspora {
$children = $basedom->children('https://joindiaspora.com/protocol'); $children = $basedom->children('https://joindiaspora.com/protocol');
if($children->header) { if ($children->header) {
$public = true; $public = true;
$author_link = str_replace('acct:','',$children->header->author_id); $author_link = str_replace('acct:','',$children->header->author_id);
} else { } else {
@ -217,11 +217,11 @@ class Diaspora {
// figure out where in the DOM tree our data is hiding // figure out where in the DOM tree our data is hiding
if($dom->provenance->data) if ($dom->provenance->data)
$base = $dom->provenance; $base = $dom->provenance;
elseif($dom->env->data) elseif ($dom->env->data)
$base = $dom->env; $base = $dom->env;
elseif($dom->data) elseif ($dom->data)
$base = $dom; $base = $dom;
if (!$base) { if (!$base) {
@ -254,7 +254,7 @@ class Diaspora {
$data = base64url_decode($data); $data = base64url_decode($data);
if($public) if ($public)
$inner_decrypted = $data; $inner_decrypted = $data;
else { else {
@ -556,7 +556,7 @@ class Diaspora {
logger("Fetching diaspora key for: ".$handle); logger("Fetching diaspora key for: ".$handle);
$r = self::person_by_handle($handle); $r = self::person_by_handle($handle);
if($r) if ($r)
return $r["pubkey"]; return $r["pubkey"];
return ""; return "";
@ -612,7 +612,7 @@ class Diaspora {
*/ */
private static function add_fcontact($arr, $update = false) { private static function add_fcontact($arr, $update = false) {
if($update) { if ($update) {
$r = q("UPDATE `fcontact` SET $r = q("UPDATE `fcontact` SET
`name` = '%s', `name` = '%s',
`photo` = '%s', `photo` = '%s',
@ -796,7 +796,7 @@ class Diaspora {
// perhaps we were already sharing with this person. Now they're sharing with us. // perhaps we were already sharing with this person. Now they're sharing with us.
// That makes us friends. // That makes us friends.
// Normally this should have handled by getting a request - but this could get lost // Normally this should have handled by getting a request - but this could get lost
if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) { if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d", q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
intval(CONTACT_IS_FRIEND), intval(CONTACT_IS_FRIEND),
intval($contact["id"]), intval($contact["id"]),
@ -806,12 +806,12 @@ class Diaspora {
logger("defining user ".$contact["nick"]." as friend"); logger("defining user ".$contact["nick"]." as friend");
} }
if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"])) if (($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
return false; return false;
if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND) if ($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
return true; return true;
if($contact["rel"] == CONTACT_IS_FOLLOWER) if ($contact["rel"] == CONTACT_IS_FOLLOWER)
if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment) if (($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
return true; return true;
// Messages for the global users are always accepted // Messages for the global users are always accepted
@ -969,7 +969,7 @@ class Diaspora {
logger("Fetch post from ".$source_url, LOGGER_DEBUG); logger("Fetch post from ".$source_url, LOGGER_DEBUG);
$envelope = fetch_url($source_url); $envelope = fetch_url($source_url);
if($envelope) { if ($envelope) {
logger("Envelope was fetched.", LOGGER_DEBUG); logger("Envelope was fetched.", LOGGER_DEBUG);
$x = self::verify_magic_envelope($envelope); $x = self::verify_magic_envelope($envelope);
if (!$x) if (!$x)
@ -985,7 +985,7 @@ class Diaspora {
logger("Fetch post from ".$source_url, LOGGER_DEBUG); logger("Fetch post from ".$source_url, LOGGER_DEBUG);
$x = fetch_url($source_url); $x = fetch_url($source_url);
if(!$x) if (!$x)
return false; return false;
} }
@ -1042,7 +1042,7 @@ class Diaspora {
FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1", FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
intval($uid), dbesc($guid)); intval($uid), dbesc($guid));
if(!$r) { if (!$r) {
$result = self::store_by_guid($guid, $contact["url"], $uid); $result = self::store_by_guid($guid, $contact["url"], $uid);
if (!$result) { if (!$result) {
@ -1303,7 +1303,7 @@ class Diaspora {
} }
// If we are the origin of the parent we store the original data and notify our followers // If we are the origin of the parent we store the original data and notify our followers
if($message_id AND $parent_item["origin"]) { if ($message_id AND $parent_item["origin"]) {
// Formerly we stored the signed text, the signature and the author in different fields. // Formerly we stored the signed text, the signature and the author in different fields.
// We now store the raw data so that we are more flexible. // We now store the raw data so that we are more flexible.
@ -1480,7 +1480,7 @@ class Diaspora {
intval($importer["uid"]), intval($importer["uid"]),
dbesc($guid) dbesc($guid)
); );
if($c) if ($c)
$conversation = $c[0]; $conversation = $c[0];
else { else {
$r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`) $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
@ -1493,13 +1493,13 @@ class Diaspora {
dbesc($subject), dbesc($subject),
dbesc($participants) dbesc($participants)
); );
if($r) if ($r)
$c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1", $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
intval($importer["uid"]), intval($importer["uid"]),
dbesc($guid) dbesc($guid)
); );
if($c) if ($c)
$conversation = $c[0]; $conversation = $c[0];
} }
if (!$conversation) { if (!$conversation) {
@ -1507,7 +1507,7 @@ class Diaspora {
return; return;
} }
foreach($messages as $mesg) foreach ($messages as $mesg)
self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation); self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
return true; return true;
@ -1637,7 +1637,7 @@ class Diaspora {
logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG); logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
// If we are the origin of the parent we store the original data and notify our followers // If we are the origin of the parent we store the original data and notify our followers
if($message_id AND $parent_item["origin"]) { if ($message_id AND $parent_item["origin"]) {
// Formerly we stored the signed text, the signature and the author in different fields. // Formerly we stored the signed text, the signature and the author in different fields.
// We now store the raw data so that we are more flexible. // We now store the raw data so that we are more flexible.
@ -1812,10 +1812,10 @@ class Diaspora {
$handle_parts = explode("@", $author); $handle_parts = explode("@", $author);
$nick = $handle_parts[0]; $nick = $handle_parts[0];
if($name === "") if ($name === "")
$name = $handle_parts[0]; $name = $handle_parts[0];
if( preg_match("|^https?://|", $image_url) === 0) if ( preg_match("|^https?://|", $image_url) === 0)
$image_url = "http://".$handle_parts[1].$image_url; $image_url = "http://".$handle_parts[1].$image_url;
update_contact_avatar($image_url, $importer["uid"], $contact["id"]); update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
@ -1830,7 +1830,7 @@ class Diaspora {
// this is to prevent multiple birthday notifications in a single year // this is to prevent multiple birthday notifications in a single year
// if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
if(substr($birthday,5) === substr($contact["bd"],5)) if (substr($birthday,5) === substr($contact["bd"],5))
$birthday = $contact["bd"]; $birthday = $contact["bd"];
$r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s', $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
@ -1876,7 +1876,7 @@ class Diaspora {
$a = get_app(); $a = get_app();
if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) { if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d", q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
intval(CONTACT_IS_FRIEND), intval(CONTACT_IS_FRIEND),
intval($contact["id"]), intval($contact["id"]),
@ -1889,7 +1889,7 @@ class Diaspora {
intval($importer["uid"]) intval($importer["uid"])
); );
if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) { if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
$self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1", $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
intval($importer["uid"]) intval($importer["uid"])
@ -1897,7 +1897,7 @@ class Diaspora {
// they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) { if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
$arr = array(); $arr = array();
$arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]); $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
@ -1928,7 +1928,7 @@ class Diaspora {
$arr["deny_gid"] = $user[0]["deny_gid"]; $arr["deny_gid"] = $user[0]["deny_gid"];
$i = item_store($arr); $i = item_store($arr);
if($i) if ($i)
proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i); proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
} }
} }
@ -2067,12 +2067,12 @@ class Diaspora {
$def_gid = get_default_group($importer['uid'], $ret["network"]); $def_gid = get_default_group($importer['uid'], $ret["network"]);
if(intval($def_gid)) if (intval($def_gid))
group_add_member($importer["uid"], "", $contact_record["id"], $def_gid); group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true); update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
if($importer["page-flags"] == PAGE_NORMAL) { if ($importer["page-flags"] == PAGE_NORMAL) {
logger("Sending intra message for author ".$author.".", LOGGER_DEBUG); logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
@ -2122,7 +2122,7 @@ class Diaspora {
); );
$u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"])); $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
if($u) { if ($u) {
logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG); logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
$ret = self::send_share($u[0], $contact_record); $ret = self::send_share($u[0], $contact_record);
@ -2748,7 +2748,7 @@ class Diaspora {
$a = get_app(); $a = get_app();
$enabled = intval(get_config("system", "diaspora_enabled")); $enabled = intval(get_config("system", "diaspora_enabled"));
if(!$enabled) if (!$enabled)
return 200; return 200;
$logid = random_string(4); $logid = random_string(4);
@ -3087,14 +3087,14 @@ class Diaspora {
$body = html_entity_decode(bb2diaspora($body)); $body = html_entity_decode(bb2diaspora($body));
// Adding the title // Adding the title
if(strlen($title)) if (strlen($title))
$body = "## ".html_entity_decode($title)."\n\n".$body; $body = "## ".html_entity_decode($title)."\n\n".$body;
if ($item["attach"]) { if ($item["attach"]) {
$cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER); $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
if(cnt) { if (cnt) {
$body .= "\n".t("Attachments:")."\n"; $body .= "\n".t("Attachments:")."\n";
foreach($matches as $mtch) foreach ($matches as $mtch)
$body .= "[".$mtch[3]."](".$mtch[1].")\n"; $body .= "[".$mtch[3]."](".$mtch[1].")\n";
} }
} }
@ -3587,7 +3587,7 @@ class Diaspora {
$kw = str_replace(' ',' ',$kw); $kw = str_replace(' ',' ',$kw);
$arr = explode(' ',$profile['pub_keywords']); $arr = explode(' ',$profile['pub_keywords']);
if (count($arr)) { if (count($arr)) {
for($x = 0; $x < 5; $x ++) { for ($x = 0; $x < 5; $x ++) {
if (trim($arr[$x])) if (trim($arr[$x]))
$tags .= '#'. trim($arr[$x]) .' '; $tags .= '#'. trim($arr[$x]) .' ';
} }
@ -3609,7 +3609,7 @@ class Diaspora {
"searchable" => $searchable, "searchable" => $searchable,
"tag_string" => $tags); "tag_string" => $tags);
foreach($recips as $recip) { foreach ($recips as $recip) {
logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG); logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
self::build_and_transmit($profile, $recip, "profile", $message, false, "", true); self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
} }
@ -3632,17 +3632,20 @@ class Diaspora {
} }
$r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid'])); $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
if(!$r) if (!dbm::is_result($r)) {
return false; return false;
}
$contact["uprvkey"] = $r[0]['prvkey']; $contact["uprvkey"] = $r[0]['prvkey'];
$r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id)); $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
if (!$r) if (!dbm::is_result($r)) {
return false; return false;
}
if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
return false; return false;
}
$message = self::construct_like($r[0], $contact); $message = self::construct_like($r[0], $contact);
$message["author_signature"] = self::signature($contact, $message); $message["author_signature"] = self::signature($contact, $message);

View file

@ -189,10 +189,10 @@ function discover_directory($search) {
$j = json_decode($x); $j = json_decode($x);
if (count($j->results)) { if (count($j->results)) {
foreach($j->results as $jj) { foreach ($j->results as $jj) {
// Check if the contact already exists // Check if the contact already exists
$exists = q("SELECT `id`, `last_contact`, `last_failure`, `updated` FROM `gcontact` WHERE `nurl` = '%s'", normalise_link($jj->url)); $exists = q("SELECT `id`, `last_contact`, `last_failure`, `updated` FROM `gcontact` WHERE `nurl` = '%s'", normalise_link($jj->url));
if ($exists) { if (dbm::is_result($exists)) {
logger("Profile ".$jj->url." already exists (".$search.")", LOGGER_DEBUG); logger("Profile ".$jj->url." already exists (".$search.")", LOGGER_DEBUG);
if (($exists[0]["last_contact"] < $exists[0]["last_failure"]) AND if (($exists[0]["last_contact"] < $exists[0]["last_failure"]) AND
@ -245,12 +245,14 @@ function gs_search_user($search) {
if (!$result["success"]) { if (!$result["success"]) {
return false; return false;
} }
$contacts = json_decode($result["body"]); $contacts = json_decode($result["body"]);
if ($contacts->status == 'ERROR') { if ($contacts->status == 'ERROR') {
return false; return false;
} }
foreach($contacts->data AS $user) {
foreach ($contacts->data AS $user) {
$contact = probe_url($user->site_address."/".$user->name); $contact = probe_url($user->site_address."/".$user->name);
if ($contact["network"] != NETWORK_PHANTOM) { if ($contact["network"] != NETWORK_PHANTOM) {
$contact["about"] = $user->description; $contact["about"] = $user->description;

View file

@ -4,7 +4,7 @@ require_once('include/msgclean.php');
require_once('include/quoteconvert.php'); require_once('include/quoteconvert.php');
function email_connect($mailbox,$username,$password) { function email_connect($mailbox,$username,$password) {
if(! function_exists('imap_open')) if (! function_exists('imap_open'))
return false; return false;
$mbox = @imap_open($mailbox,$username,$password); $mbox = @imap_open($mailbox,$username,$password);
@ -14,23 +14,23 @@ function email_connect($mailbox,$username,$password) {
function email_poll($mbox,$email_addr) { function email_poll($mbox,$email_addr) {
if(! ($mbox && $email_addr)) if (! ($mbox && $email_addr))
return array(); return array();
$search1 = @imap_search($mbox,'FROM "' . $email_addr . '"', SE_UID); $search1 = @imap_search($mbox,'FROM "' . $email_addr . '"', SE_UID);
if(! $search1) if (! $search1)
$search1 = array(); $search1 = array();
$search2 = @imap_search($mbox,'TO "' . $email_addr . '"', SE_UID); $search2 = @imap_search($mbox,'TO "' . $email_addr . '"', SE_UID);
if(! $search2) if (! $search2)
$search2 = array(); $search2 = array();
$search3 = @imap_search($mbox,'CC "' . $email_addr . '"', SE_UID); $search3 = @imap_search($mbox,'CC "' . $email_addr . '"', SE_UID);
if(! $search3) if (! $search3)
$search3 = array(); $search3 = array();
$search4 = @imap_search($mbox,'BCC "' . $email_addr . '"', SE_UID); $search4 = @imap_search($mbox,'BCC "' . $email_addr . '"', SE_UID);
if(! $search4) if (! $search4)
$search4 = array(); $search4 = array();
$res = array_unique(array_merge($search1,$search2,$search3,$search4)); $res = array_unique(array_merge($search1,$search2,$search3,$search4));
@ -57,8 +57,8 @@ function email_msg_headers($mbox,$uid) {
$raw_header = str_replace("\r",'',$raw_header); $raw_header = str_replace("\r",'',$raw_header);
$ret = array(); $ret = array();
$h = explode("\n",$raw_header); $h = explode("\n",$raw_header);
if(count($h)) if (count($h))
foreach($h as $line ) { foreach ($h as $line ) {
if (preg_match("/^[a-zA-Z]/", $line)) { if (preg_match("/^[a-zA-Z]/", $line)) {
$key = substr($line,0,strpos($line,':')); $key = substr($line,0,strpos($line,':'));
$value = substr($line,strpos($line,':')+1); $value = substr($line,strpos($line,':')+1);
@ -79,10 +79,10 @@ function email_get_msg($mbox,$uid, $reply) {
$struc = (($mbox && $uid) ? @imap_fetchstructure($mbox,$uid,FT_UID) : null); $struc = (($mbox && $uid) ? @imap_fetchstructure($mbox,$uid,FT_UID) : null);
if(! $struc) if (! $struc)
return $ret; return $ret;
if(! $struc->parts) { if (! $struc->parts) {
$ret['body'] = email_get_part($mbox,$uid,$struc,0, 'html'); $ret['body'] = email_get_part($mbox,$uid,$struc,0, 'html');
$html = $ret['body']; $html = $ret['body'];
@ -94,7 +94,7 @@ function email_get_msg($mbox,$uid, $reply) {
else { else {
$text = ''; $text = '';
$html = ''; $html = '';
foreach($struc->parts as $ptop => $p) { foreach ($struc->parts as $ptop => $p) {
$x = email_get_part($mbox,$uid,$p,$ptop + 1, 'plain'); $x = email_get_part($mbox,$uid,$p,$ptop + 1, 'plain');
if ($x) { if ($x) {
$text .= $x; $text .= $x;
@ -209,13 +209,13 @@ function email_header_encode($in_str, $charset) {
$out_str = $in_str; $out_str = $in_str;
$need_to_convert = false; $need_to_convert = false;
for($x = 0; $x < strlen($in_str); $x ++) { for ($x = 0; $x < strlen($in_str); $x ++) {
if((ord($in_str[$x]) == 0) || ((ord($in_str[$x]) > 128))) { if ((ord($in_str[$x]) == 0) || ((ord($in_str[$x]) > 128))) {
$need_to_convert = true; $need_to_convert = true;
} }
} }
if(! $need_to_convert) if (! $need_to_convert)
return $in_str; return $in_str;
if ($out_str && $charset) { if ($out_str && $charset) {

View file

@ -411,10 +411,12 @@ function notification($params) {
$hash = random_string(); $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)); dbesc($hash));
if (dbm::is_result($r)) if (dbm::is_result($r)) {
$dups = true; $dups = true;
} while($dups == true); }
} while ($dups == true);
/// @TODO One statement is enough
$datarray = array(); $datarray = array();
$datarray['hash'] = $hash; $datarray['hash'] = $hash;
$datarray['name'] = $params['source_name']; $datarray['name'] = $params['source_name'];

View file

@ -10,7 +10,7 @@ require_once 'include/datetime.php';
function format_event_html($ev, $simple = false) { function format_event_html($ev, $simple = false) {
if(! ((is_array($ev)) && count($ev))) { if (! ((is_array($ev)) && count($ev))) {
return ''; return '';
} }
@ -98,26 +98,26 @@ function parse_event($h) {
logger('parse_event: parse error: ' . $e); logger('parse_event: parse error: ' . $e);
} }
if(! $dom) if (! $dom)
return $ret; return $ret;
$items = $dom->getElementsByTagName('*'); $items = $dom->getElementsByTagName('*');
foreach($items as $item) { foreach ($items as $item) {
if(attribute_contains($item->getAttribute('class'), 'vevent')) { if (attribute_contains($item->getAttribute('class'), 'vevent')) {
$level2 = $item->getElementsByTagName('*'); $level2 = $item->getElementsByTagName('*');
foreach($level2 as $x) { foreach ($level2 as $x) {
if(attribute_contains($x->getAttribute('class'),'dtstart') && $x->getAttribute('title')) { if (attribute_contains($x->getAttribute('class'),'dtstart') && $x->getAttribute('title')) {
$ret['start'] = $x->getAttribute('title'); $ret['start'] = $x->getAttribute('title');
if(! strpos($ret['start'],'Z')) if (! strpos($ret['start'],'Z'))
$ret['adjust'] = true; $ret['adjust'] = true;
} }
if(attribute_contains($x->getAttribute('class'),'dtend') && $x->getAttribute('title')) if (attribute_contains($x->getAttribute('class'),'dtend') && $x->getAttribute('title'))
$ret['finish'] = $x->getAttribute('title'); $ret['finish'] = $x->getAttribute('title');
if(attribute_contains($x->getAttribute('class'),'description')) if (attribute_contains($x->getAttribute('class'),'description'))
$ret['desc'] = $x->textContent; $ret['desc'] = $x->textContent;
if(attribute_contains($x->getAttribute('class'),'location')) if (attribute_contains($x->getAttribute('class'),'location'))
$ret['location'] = $x->textContent; $ret['location'] = $x->textContent;
} }
} }
@ -125,23 +125,23 @@ function parse_event($h) {
// sanitise // sanitise
if((x($ret,'desc')) && ((strpos($ret['desc'],'<') !== false) || (strpos($ret['desc'],'>') !== false))) { if ((x($ret,'desc')) && ((strpos($ret['desc'],'<') !== false) || (strpos($ret['desc'],'>') !== false))) {
$config = HTMLPurifier_Config::createDefault(); $config = HTMLPurifier_Config::createDefault();
$config->set('Cache.DefinitionImpl', null); $config->set('Cache.DefinitionImpl', null);
$purifier = new HTMLPurifier($config); $purifier = new HTMLPurifier($config);
$ret['desc'] = html2bbcode($purifier->purify($ret['desc'])); $ret['desc'] = html2bbcode($purifier->purify($ret['desc']));
} }
if((x($ret,'location')) && ((strpos($ret['location'],'<') !== false) || (strpos($ret['location'],'>') !== false))) { if ((x($ret,'location')) && ((strpos($ret['location'],'<') !== false) || (strpos($ret['location'],'>') !== false))) {
$config = HTMLPurifier_Config::createDefault(); $config = HTMLPurifier_Config::createDefault();
$config->set('Cache.DefinitionImpl', null); $config->set('Cache.DefinitionImpl', null);
$purifier = new HTMLPurifier($config); $purifier = new HTMLPurifier($config);
$ret['location'] = html2bbcode($purifier->purify($ret['location'])); $ret['location'] = html2bbcode($purifier->purify($ret['location']));
} }
if(x($ret,'start')) if (x($ret,'start'))
$ret['start'] = datetime_convert('UTC','UTC',$ret['start']); $ret['start'] = datetime_convert('UTC','UTC',$ret['start']);
if(x($ret,'finish')) if (x($ret,'finish'))
$ret['finish'] = datetime_convert('UTC','UTC',$ret['finish']); $ret['finish'] = datetime_convert('UTC','UTC',$ret['finish']);
return $ret; return $ret;
@ -595,7 +595,7 @@ function event_by_id($owner_uid = 0, $event_params, $sql_extra = '') {
*/ */
function events_by_date($owner_uid = 0, $event_params, $sql_extra = '') { function events_by_date($owner_uid = 0, $event_params, $sql_extra = '') {
// Only allow events if there is a valid owner_id // Only allow events if there is a valid owner_id
if($owner_uid == 0) { if ($owner_uid == 0) {
return; return;
} }
@ -629,7 +629,7 @@ function events_by_date($owner_uid = 0, $event_params, $sql_extra = '') {
* @return array Event array for the template * @return array Event array for the template
*/ */
function process_events($arr) { function process_events($arr) {
$events=array(); $events = array();
$last_date = ''; $last_date = '';
$fmt = t('l, F j'); $fmt = t('l, F j');

View file

@ -11,12 +11,13 @@ function expire_run(&$argv, &$argc){
// physically remove anything that has been deleted for more than two months // physically remove anything that has been deleted for more than two months
$r = q("delete from item where deleted = 1 and changed < UTC_TIMESTAMP() - INTERVAL 60 DAY"); $r = q("DELETE FROM `item` WHERE `deleted` = 1 AND `changed` < UTC_TIMESTAMP() - INTERVAL 60 DAY");
// make this optional as it could have a performance impact on large sites // 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"); q("OPTIMIZE TABLE `item`");
}
logger('expire: start'); logger('expire: start');

View file

@ -36,9 +36,9 @@ function feature_enabled($uid, $feature) {
*/ */
function get_feature_default($feature) { function get_feature_default($feature) {
$f = get_features(); $f = get_features();
foreach($f as $cat) { foreach ($f as $cat) {
foreach($cat as $feat) { foreach ($cat as $feat) {
if(is_array($feat) && $feat[0] === $feature) if (is_array($feat) && $feat[0] === $feature)
return $feat[3]; return $feat[3];
} }
} }
@ -116,13 +116,13 @@ function get_features($filtered = true) {
// removed any locked features and remove the entire category if this makes it empty // removed any locked features and remove the entire category if this makes it empty
if($filtered) { if ($filtered) {
foreach($arr as $k => $x) { foreach ($arr as $k => $x) {
$has_items = false; $has_items = false;
$kquantity = count($arr[$k]); $kquantity = count($arr[$k]);
for($y = 0; $y < $kquantity; $y ++) { for ($y = 0; $y < $kquantity; $y ++) {
if(is_array($arr[$k][$y])) { if (is_array($arr[$k][$y])) {
if($arr[$k][$y][4] === false) { if ($arr[$k][$y][4] === false) {
$has_items = true; $has_items = true;
} }
else { else {
@ -130,7 +130,7 @@ function get_features($filtered = true) {
} }
} }
} }
if(! $has_items) { if (! $has_items) {
unset($arr[$k]); unset($arr[$k]);
} }
} }

View file

@ -163,7 +163,7 @@ function feed_import($xml,$importer,&$contact, &$hub, $simulate = false) {
$header["contact-id"] = $contact["id"]; $header["contact-id"] = $contact["id"];
if(!strlen($contact["notify"])) { if (!strlen($contact["notify"])) {
// one way feed - no remote comment ability // one way feed - no remote comment ability
$header["last-child"] = 0; $header["last-child"] = 0;
} }
@ -280,7 +280,7 @@ function feed_import($xml,$importer,&$contact, &$hub, $simulate = false) {
$type = ""; $type = "";
$title = ""; $title = "";
foreach($enclosure->attributes AS $attributes) { foreach ($enclosure->attributes AS $attributes) {
if ($attributes->name == "url") { if ($attributes->name == "url") {
$href = $attributes->textContent; $href = $attributes->textContent;
} elseif ($attributes->name == "length") { } elseif ($attributes->name == "length") {
@ -289,8 +289,9 @@ function feed_import($xml,$importer,&$contact, &$hub, $simulate = false) {
$type = $attributes->textContent; $type = $attributes->textContent;
} }
} }
if(strlen($item["attach"])) if (strlen($item["attach"])) {
$item["attach"] .= ','; $item["attach"] .= ',';
}
$attachments[] = array("link" => $href, "type" => $type, "length" => $length); $attachments[] = array("link" => $href, "type" => $type, "length" => $length);

View file

@ -33,7 +33,7 @@ function create_files_from_item($itemid) {
function create_files_from_itemuri($itemuri, $uid) { function create_files_from_itemuri($itemuri, $uid) {
$messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid)); $messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid));
if(count($messages)) { if (count($messages)) {
foreach ($messages as $message) foreach ($messages as $message)
create_files_from_item($message["id"]); create_files_from_item($message["id"]);
} }

View file

@ -18,7 +18,7 @@ class FriendicaSmarty extends Smarty {
// setTemplateDir can be set to an array, which Smarty will parse in order. // setTemplateDir can be set to an array, which Smarty will parse in order.
// The order is thus very important here // The order is thus very important here
$template_dirs = array('theme' => "view/theme/$theme/".SMARTY3_TEMPLATE_FOLDER."/"); $template_dirs = array('theme' => "view/theme/$theme/".SMARTY3_TEMPLATE_FOLDER."/");
if( x($a->theme_info,"extends") ) if ( x($a->theme_info,"extends") )
$template_dirs = $template_dirs + array('extends' => "view/theme/".$a->theme_info["extends"]."/".SMARTY3_TEMPLATE_FOLDER."/"); $template_dirs = $template_dirs + array('extends' => "view/theme/".$a->theme_info["extends"]."/".SMARTY3_TEMPLATE_FOLDER."/");
$template_dirs = $template_dirs + array('base' => "view/".SMARTY3_TEMPLATE_FOLDER."/"); $template_dirs = $template_dirs + array('base' => "view/".SMARTY3_TEMPLATE_FOLDER."/");
$this->setTemplateDir($template_dirs); $this->setTemplateDir($template_dirs);
@ -35,7 +35,7 @@ class FriendicaSmarty extends Smarty {
} }
function parsed($template = '') { function parsed($template = '') {
if($template) { if ($template) {
return $this->fetch('string:' . $template); return $this->fetch('string:' . $template);
} }
return $this->fetch('file:' . $this->filename); return $this->fetch('file:' . $this->filename);
@ -48,7 +48,7 @@ class FriendicaSmartyEngine implements ITemplateEngine {
static $name ="smarty3"; static $name ="smarty3";
public function __construct(){ public function __construct(){
if(!is_writable('view/smarty3/')){ if (!is_writable('view/smarty3/')){
echo "<b>ERROR:</b> folder <tt>view/smarty3/</tt> must be writable by webserver."; killme(); echo "<b>ERROR:</b> folder <tt>view/smarty3/</tt> must be writable by webserver."; killme();
} }
} }
@ -56,7 +56,7 @@ class FriendicaSmartyEngine implements ITemplateEngine {
// ITemplateEngine interface // ITemplateEngine interface
public function replace_macros($s, $r) { public function replace_macros($s, $r) {
$template = ''; $template = '';
if(gettype($s) === 'string') { if (gettype($s) === 'string') {
$template = $s; $template = $s;
$s = new FriendicaSmarty(); $s = new FriendicaSmarty();
} }
@ -71,8 +71,8 @@ class FriendicaSmartyEngine implements ITemplateEngine {
call_hooks("template_vars", $arr); call_hooks("template_vars", $arr);
$r = $arr['vars']; $r = $arr['vars'];
foreach($r as $key=>$value) { foreach ($r as $key=>$value) {
if($key[0] === '$') { if ($key[0] === '$') {
$key = substr($key, 1); $key = substr($key, 1);
} }
$s->assign($key, $value); $s->assign($key, $value);

View file

@ -4,9 +4,9 @@
function group_add($uid,$name) { function group_add($uid,$name) {
$ret = false; $ret = false;
if(x($uid) && x($name)) { if (x($uid) && x($name)) {
$r = group_byname($uid,$name); // check for dups $r = group_byname($uid,$name); // check for dups
if($r !== false) { if ($r !== false) {
// This could be a problem. // This could be a problem.
// Let's assume we've just created a group which we once deleted // Let's assume we've just created a group which we once deleted
@ -17,7 +17,7 @@ function group_add($uid,$name) {
$z = q("SELECT * FROM `group` WHERE `id` = %d LIMIT 1", $z = q("SELECT * FROM `group` WHERE `id` = %d LIMIT 1",
intval($r) intval($r)
); );
if(count($z) && $z[0]['deleted']) { if (count($z) && $z[0]['deleted']) {
$r = q("UPDATE `group` SET `deleted` = 0 WHERE `uid` = %d AND `name` = '%s'", $r = q("UPDATE `group` SET `deleted` = 0 WHERE `uid` = %d AND `name` = '%s'",
intval($uid), intval($uid),
dbesc($name) dbesc($name)
@ -39,14 +39,14 @@ function group_add($uid,$name) {
function group_rmv($uid,$name) { function group_rmv($uid,$name) {
$ret = false; $ret = false;
if(x($uid) && x($name)) { if (x($uid) && x($name)) {
$r = q("SELECT id FROM `group` WHERE `uid` = %d AND `name` = '%s' LIMIT 1", $r = q("SELECT id FROM `group` WHERE `uid` = %d AND `name` = '%s' LIMIT 1",
intval($uid), intval($uid),
dbesc($name) dbesc($name)
); );
if (dbm::is_result($r)) if (dbm::is_result($r))
$group_id = $r[0]['id']; $group_id = $r[0]['id'];
if(! $group_id) if (! $group_id)
return false; return false;
// remove group from default posting lists // remove group from default posting lists
@ -57,20 +57,20 @@ function group_rmv($uid,$name) {
$user_info = $r[0]; $user_info = $r[0];
$change = false; $change = false;
if($user_info['def_gid'] == $group_id) { if ($user_info['def_gid'] == $group_id) {
$user_info['def_gid'] = 0; $user_info['def_gid'] = 0;
$change = true; $change = true;
} }
if(strpos($user_info['allow_gid'], '<' . $group_id . '>') !== false) { if (strpos($user_info['allow_gid'], '<' . $group_id . '>') !== false) {
$user_info['allow_gid'] = str_replace('<' . $group_id . '>', '', $user_info['allow_gid']); $user_info['allow_gid'] = str_replace('<' . $group_id . '>', '', $user_info['allow_gid']);
$change = true; $change = true;
} }
if(strpos($user_info['deny_gid'], '<' . $group_id . '>') !== false) { if (strpos($user_info['deny_gid'], '<' . $group_id . '>') !== false) {
$user_info['deny_gid'] = str_replace('<' . $group_id . '>', '', $user_info['deny_gid']); $user_info['deny_gid'] = str_replace('<' . $group_id . '>', '', $user_info['deny_gid']);
$change = true; $change = true;
} }
if($change) { if ($change) {
q("UPDATE user SET def_gid = %d, allow_gid = '%s', deny_gid = '%s' WHERE uid = %d", q("UPDATE user SET def_gid = %d, allow_gid = '%s', deny_gid = '%s' WHERE uid = %d",
intval($user_info['def_gid']), intval($user_info['def_gid']),
dbesc($user_info['allow_gid']), dbesc($user_info['allow_gid']),
@ -100,7 +100,7 @@ function group_rmv($uid,$name) {
} }
function group_byname($uid,$name) { function group_byname($uid,$name) {
if((! $uid) || (! strlen($name))) if ((! $uid) || (! strlen($name)))
return false; return false;
$r = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' LIMIT 1", $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' LIMIT 1",
intval($uid), intval($uid),
@ -113,9 +113,9 @@ function group_byname($uid,$name) {
function group_rmv_member($uid,$name,$member) { function group_rmv_member($uid,$name,$member) {
$gid = group_byname($uid,$name); $gid = group_byname($uid,$name);
if(! $gid) if (! $gid)
return false; return false;
if(! ( $uid && $gid && $member)) if (! ( $uid && $gid && $member))
return false; return false;
$r = q("DELETE FROM `group_member` WHERE `uid` = %d AND `gid` = %d AND `contact-id` = %d", $r = q("DELETE FROM `group_member` WHERE `uid` = %d AND `gid` = %d AND `contact-id` = %d",
intval($uid), intval($uid),
@ -129,9 +129,9 @@ function group_rmv_member($uid,$name,$member) {
function group_add_member($uid,$name,$member,$gid = 0) { function group_add_member($uid,$name,$member,$gid = 0) {
if(! $gid) if (! $gid)
$gid = group_byname($uid,$name); $gid = group_byname($uid,$name);
if((! $gid) || (! $uid) || (! $member)) if ((! $gid) || (! $uid) || (! $member))
return false; return false;
$r = q("SELECT * FROM `group_member` WHERE `uid` = %d AND `gid` = %d AND `contact-id` = %d LIMIT 1", $r = q("SELECT * FROM `group_member` WHERE `uid` = %d AND `gid` = %d AND `contact-id` = %d LIMIT 1",
@ -156,7 +156,7 @@ function group_add_member($uid,$name,$member,$gid = 0) {
function group_get_members($gid) { function group_get_members($gid) {
$ret = array(); $ret = array();
if(intval($gid)) { if (intval($gid)) {
$r = q("SELECT `group_member`.`contact-id`, `contact`.* FROM `group_member` $r = q("SELECT `group_member`.`contact-id`, `contact`.* FROM `group_member`
INNER JOIN `contact` ON `contact`.`id` = `group_member`.`contact-id` INNER JOIN `contact` ON `contact`.`id` = `group_member`.`contact-id`
WHERE `gid` = %d AND `group_member`.`uid` = %d AND WHERE `gid` = %d AND `group_member`.`uid` = %d AND
@ -173,7 +173,7 @@ function group_get_members($gid) {
function group_public_members($gid) { function group_public_members($gid) {
$ret = 0; $ret = 0;
if(intval($gid)) { if (intval($gid)) {
$r = q("SELECT `contact`.`id` AS `contact-id` FROM `group_member` $r = q("SELECT `contact`.`id` AS `contact-id` FROM `group_member`
INNER JOIN `contact` ON `contact`.`id` = `group_member`.`contact-id` INNER JOIN `contact` ON `contact`.`id` = `group_member`.`contact-id`
WHERE `gid` = %d AND `group_member`.`uid` = %d WHERE `gid` = %d AND `group_member`.`uid` = %d
@ -252,7 +252,7 @@ function group_side($every="contacts",$each="group",$editmode = "standard", $gro
intval($_SESSION['uid']) intval($_SESSION['uid'])
); );
$member_of = array(); $member_of = array();
if($cid) { if ($cid) {
$member_of = groups_containing(local_user(),$cid); $member_of = groups_containing(local_user(),$cid);
} }
@ -302,7 +302,7 @@ function group_side($every="contacts",$each="group",$editmode = "standard", $gro
} }
function expand_groups($a,$check_dead = false, $use_gcontact = false) { function expand_groups($a,$check_dead = false, $use_gcontact = false) {
if(! (is_array($a) && count($a))) if (! (is_array($a) && count($a)))
return array(); return array();
$groups = implode(',', $a); $groups = implode(',', $a);
$groups = dbesc($groups); $groups = dbesc($groups);
@ -318,9 +318,9 @@ function expand_groups($a,$check_dead = false, $use_gcontact = false) {
$ret = array(); $ret = array();
if (dbm::is_result($r)) if (dbm::is_result($r))
foreach($r as $rr) foreach ($r as $rr)
$ret[] = $rr['contact-id']; $ret[] = $rr['contact-id'];
if($check_dead AND !$use_gcontact) { if ($check_dead AND !$use_gcontact) {
require_once('include/acl_selectors.php'); require_once('include/acl_selectors.php');
$ret = prune_deadguys($ret); $ret = prune_deadguys($ret);
} }
@ -347,9 +347,10 @@ function groups_containing($uid,$c) {
$ret = array(); $ret = array();
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach($r as $rr) foreach ($r as $rr) {
$ret[] = $rr['gid']; $ret[] = $rr['gid'];
} }
}
return $ret; return $ret;
} }
@ -399,7 +400,7 @@ function get_default_group($uid, $network = "") {
return $default_group; return $default_group;
$g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid)); $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
if($g && intval($g[0]["def_gid"])) if ($g && intval($g[0]["def_gid"]))
$default_group = $g[0]["def_gid"]; $default_group = $g[0]["def_gid"];
return $default_group; return $default_group;

View file

@ -49,7 +49,7 @@ function quotelevel($message, $wraplength = 75)
$newlines = array(); $newlines = array();
$level = 0; $level = 0;
foreach($lines as $line) {; foreach ($lines as $line) {;
$line = trim($line); $line = trim($line);
$startquote = false; $startquote = false;
while (strpos("*".$line, '[quote]') > 0) { while (strpos("*".$line, '[quote]') > 0) {

View file

@ -38,7 +38,7 @@ function profile_load(App $a, $nickname, $profile = 0, $profiledata = array()) {
dbesc($nickname) dbesc($nickname)
); );
if(!$user && count($user) && !count($profiledata)) { if (!$user && count($user) && !count($profiledata)) {
logger('profile error: ' . $a->query_string, LOGGER_DEBUG); logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
notice( t('Requested account is not available.') . EOL ); notice( t('Requested account is not available.') . EOL );
$a->error = 404; $a->error = 404;
@ -47,7 +47,7 @@ function profile_load(App $a, $nickname, $profile = 0, $profiledata = array()) {
$pdata = get_profiledata_by_nick($nickname, $user[0]['uid'], $profile); $pdata = get_profiledata_by_nick($nickname, $user[0]['uid'], $profile);
if(($pdata === false) || (!count($pdata)) && !count($profiledata)) { if (($pdata === false) || (!count($pdata)) && !count($profiledata)) {
logger('profile error: ' . $a->query_string, LOGGER_DEBUG); logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
notice( t('Requested profile is not available.') . EOL ); notice( t('Requested profile is not available.') . EOL );
$a->error = 404; $a->error = 404;
@ -56,11 +56,11 @@ function profile_load(App $a, $nickname, $profile = 0, $profiledata = array()) {
// fetch user tags if this isn't the default profile // fetch user tags if this isn't the default profile
if(!$pdata['is-default']) { if (!$pdata['is-default']) {
$x = q("SELECT `pub_keywords` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1", $x = q("SELECT `pub_keywords` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
intval($pdata['profile_uid']) intval($pdata['profile_uid'])
); );
if($x && count($x)) if ($x && count($x))
$pdata['pub_keywords'] = $x[0]['pub_keywords']; $pdata['pub_keywords'] = $x[0]['pub_keywords'];
} }
@ -88,10 +88,10 @@ function profile_load(App $a, $nickname, $profile = 0, $profiledata = array()) {
require_once($theme_info_file); require_once($theme_info_file);
} }
if(! (x($a->page,'aside'))) if (! (x($a->page,'aside')))
$a->page['aside'] = ''; $a->page['aside'] = '';
if(local_user() && local_user() == $a->profile['uid'] && $profiledata) { if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
$a->page['aside'] .= replace_macros(get_markup_template('profile_edlink.tpl'),array( $a->page['aside'] .= replace_macros(get_markup_template('profile_edlink.tpl'),array(
'$editprofile' => t('Edit profile'), '$editprofile' => t('Edit profile'),
'$profid' => $a->profile['id'] '$profid' => $a->profile['id']
@ -110,7 +110,7 @@ function profile_load(App $a, $nickname, $profile = 0, $profiledata = array()) {
else else
$a->page['aside'] .= profile_sidebar($a->profile, $block); $a->page['aside'] .= profile_sidebar($a->profile, $block);
/*if(! $block) /*if (! $block)
$a->page['aside'] .= contact_block();*/ $a->page['aside'] .= contact_block();*/
return; return;
@ -133,9 +133,9 @@ function profile_load(App $a, $nickname, $profile = 0, $profiledata = array()) {
* Includes all available profile data * Includes all available profile data
*/ */
function get_profiledata_by_nick($nickname, $uid = 0, $profile = 0) { function get_profiledata_by_nick($nickname, $uid = 0, $profile = 0) {
if(remote_user() && count($_SESSION['remote'])) { if (remote_user() && count($_SESSION['remote'])) {
foreach($_SESSION['remote'] as $visitor) { foreach ($_SESSION['remote'] as $visitor) {
if($visitor['uid'] == $uid) { if ($visitor['uid'] == $uid) {
$r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1", $r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
intval($visitor['cid']) intval($visitor['cid'])
); );
@ -148,7 +148,7 @@ function get_profiledata_by_nick($nickname, $uid = 0, $profile = 0) {
$r = null; $r = null;
if($profile) { if ($profile) {
$profile_int = intval($profile); $profile_int = intval($profile);
$r = q("SELECT `contact`.`id` AS `contact_id`, `profile`.`uid` AS `profile_uid`, `profile`.*, $r = q("SELECT `contact`.`id` AS `contact_id`, `profile`.`uid` AS `profile_uid`, `profile`.*,
`contact`.`avatar-date` AS picdate, `contact`.`addr`, `user`.* `contact`.`avatar-date` AS picdate, `contact`.`addr`, `user`.*
@ -202,7 +202,7 @@ function profile_sidebar($profile, $block = 0) {
$address = false; $address = false;
// $pdesc = true; // $pdesc = true;
if((! is_array($profile)) && (! count($profile))) if ((! is_array($profile)) && (! count($profile)))
return $o; return $o;
$profile['picdate'] = urlencode($profile['picdate']); $profile['picdate'] = urlencode($profile['picdate']);
@ -219,9 +219,9 @@ function profile_sidebar($profile, $block = 0) {
$connect = (($profile['uid'] != local_user()) ? t('Connect') : False); $connect = (($profile['uid'] != local_user()) ? t('Connect') : False);
// don't show connect link to authenticated visitors either // don't show connect link to authenticated visitors either
if(remote_user() && count($_SESSION['remote'])) { if (remote_user() && count($_SESSION['remote'])) {
foreach($_SESSION['remote'] as $visitor) { foreach ($_SESSION['remote'] as $visitor) {
if($visitor['uid'] == $profile['uid']) { if ($visitor['uid'] == $profile['uid']) {
$connect = false; $connect = false;
break; break;
} }
@ -322,7 +322,7 @@ function profile_sidebar($profile, $block = 0) {
// Fetch the account type // Fetch the account type
$account_type = account_type($profile); $account_type = account_type($profile);
if((x($profile,'address') == 1) if ((x($profile,'address') == 1)
|| (x($profile,'location') == 1) || (x($profile,'location') == 1)
|| (x($profile,'locality') == 1) || (x($profile,'locality') == 1)
|| (x($profile,'region') == 1) || (x($profile,'region') == 1)
@ -341,7 +341,7 @@ function profile_sidebar($profile, $block = 0) {
$xmpp = ((x($profile,'xmpp') == 1) ? t('XMPP:') : False); $xmpp = ((x($profile,'xmpp') == 1) ? t('XMPP:') : False);
if(($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) { if (($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
$location = $pdesc = $gender = $marital = $homepage = $about = False; $location = $pdesc = $gender = $marital = $homepage = $about = False;
} }
@ -368,7 +368,7 @@ function profile_sidebar($profile, $block = 0) {
if (!$block){ if (!$block){
$contact_block = contact_block(); $contact_block = contact_block();
if(is_array($a->profile) AND !$a->profile['hide-friends']) { if (is_array($a->profile) AND !$a->profile['hide-friends']) {
$r = q("SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1", $r = q("SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
intval($a->profile['uid'])); intval($a->profile['uid']));
if (dbm::is_result($r)) if (dbm::is_result($r))
@ -390,7 +390,7 @@ function profile_sidebar($profile, $block = 0) {
} }
$p = array(); $p = array();
foreach($profile as $k => $v) { foreach ($profile as $k => $v) {
$k = str_replace('-','_',$k); $k = str_replace('-','_',$k);
$p[$k] = $v; $p[$k] = $v;
} }
@ -406,7 +406,7 @@ function profile_sidebar($profile, $block = 0) {
if (isset($p["photo"])) if (isset($p["photo"]))
$p["photo"] = proxy_url($p["photo"], false, PROXY_SIZE_SMALL); $p["photo"] = proxy_url($p["photo"], false, PROXY_SIZE_SMALL);
if($a->theme['template_engine'] === 'internal') if ($a->theme['template_engine'] === 'internal')
$location = template_escape($location); $location = template_escape($location);
$tpl = get_markup_template('profile_vcard.tpl'); $tpl = get_markup_template('profile_vcard.tpl');
@ -445,13 +445,13 @@ function get_birthdays() {
$a = get_app(); $a = get_app();
$o = ''; $o = '';
if(! local_user() || $a->is_mobile || $a->is_tablet) if (! local_user() || $a->is_mobile || $a->is_tablet)
return $o; return $o;
// $mobile_detect = new Mobile_Detect(); // $mobile_detect = new Mobile_Detect();
// $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet(); // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
// if($is_mobile) // if ($is_mobile)
// return $o; // return $o;
$bd_format = t('g A l F d') ; // 8 AM Friday January 18 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
@ -479,27 +479,27 @@ function get_birthdays() {
$istoday = false; $istoday = false;
foreach ($r as $rr) { foreach ($r as $rr) {
if(strlen($rr['name'])) if (strlen($rr['name']))
$total ++; $total ++;
if((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now))
$istoday = true; $istoday = true;
} }
$classtoday = $istoday ? ' birthday-today ' : ''; $classtoday = $istoday ? ' birthday-today ' : '';
if($total) { if ($total) {
foreach($r as &$rr) { foreach ($r as &$rr) {
if(! strlen($rr['name'])) if (! strlen($rr['name']))
continue; continue;
// avoid duplicates // avoid duplicates
if(in_array($rr['cid'],$cids)) if (in_array($rr['cid'],$cids))
continue; continue;
$cids[] = $rr['cid']; $cids[] = $rr['cid'];
$today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false); $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
$sparkle = ''; $sparkle = '';
$url = $rr['url']; $url = $rr['url'];
if($rr['network'] === NETWORK_DFRN) { if ($rr['network'] === NETWORK_DFRN) {
$sparkle = " sparkle"; $sparkle = " sparkle";
$url = App::get_baseurl() . '/redir/' . $rr['cid']; $url = App::get_baseurl() . '/redir/' . $rr['cid'];
} }
@ -534,14 +534,14 @@ function get_events() {
$a = get_app(); $a = get_app();
if(! local_user() || $a->is_mobile || $a->is_tablet) if (! local_user() || $a->is_mobile || $a->is_tablet)
return $o; return $o;
// $mobile_detect = new Mobile_Detect(); // $mobile_detect = new Mobile_Detect();
// $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet(); // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
// if($is_mobile) // if ($is_mobile)
// return $o; // return $o;
$bd_format = t('g A l F d') ; // 8 AM Friday January 18 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
@ -559,30 +559,30 @@ function get_events() {
$now = strtotime('now'); $now = strtotime('now');
$istoday = false; $istoday = false;
foreach ($r as $rr) { foreach ($r as $rr) {
if(strlen($rr['name'])) if (strlen($rr['name']))
$total ++; $total ++;
$strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start'],'Y-m-d'); $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start'],'Y-m-d');
if($strt === datetime_convert('UTC',$a->timezone,'now','Y-m-d')) if ($strt === datetime_convert('UTC',$a->timezone,'now','Y-m-d'))
$istoday = true; $istoday = true;
} }
$classtoday = (($istoday) ? 'event-today' : ''); $classtoday = (($istoday) ? 'event-today' : '');
$skip = 0; $skip = 0;
foreach($r as &$rr) { foreach ($r as &$rr) {
$title = strip_tags(html_entity_decode(bbcode($rr['summary']),ENT_QUOTES,'UTF-8')); $title = strip_tags(html_entity_decode(bbcode($rr['summary']),ENT_QUOTES,'UTF-8'));
if(strlen($title) > 35) if (strlen($title) > 35)
$title = substr($title,0,32) . '... '; $title = substr($title,0,32) . '... ';
$description = substr(strip_tags(bbcode($rr['desc'])),0,32) . '... '; $description = substr(strip_tags(bbcode($rr['desc'])),0,32) . '... ';
if(! $description) if (! $description)
$description = t('[No description]'); $description = t('[No description]');
$strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start']); $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start']);
if(substr($strt,0,10) < datetime_convert('UTC',$a->timezone,'now','Y-m-d')) { if (substr($strt,0,10) < datetime_convert('UTC',$a->timezone,'now','Y-m-d')) {
$skip++; $skip++;
continue; continue;
} }
@ -617,7 +617,7 @@ function advanced_profile(App $a) {
'$title' => t('Profile') '$title' => t('Profile')
)); ));
if($a->profile['name']) { if ($a->profile['name']) {
$tpl = get_markup_template('profile_advanced.tpl'); $tpl = get_markup_template('profile_advanced.tpl');
@ -625,10 +625,10 @@ function advanced_profile(App $a) {
$profile['fullname'] = array( t('Full Name:'), $a->profile['name'] ) ; $profile['fullname'] = array( t('Full Name:'), $a->profile['name'] ) ;
if($a->profile['gender']) $profile['gender'] = array( t('Gender:'), $a->profile['gender'] ); if ($a->profile['gender']) $profile['gender'] = array( t('Gender:'), $a->profile['gender'] );
if(($a->profile['dob']) && ($a->profile['dob'] != '0000-00-00')) { if (($a->profile['dob']) && ($a->profile['dob'] != '0000-00-00')) {
$year_bd_format = t('j F, Y'); $year_bd_format = t('j F, Y');
$short_bd_format = t('j F'); $short_bd_format = t('j F');
@ -642,10 +642,10 @@ function advanced_profile(App $a) {
} }
if($age = age($a->profile['dob'],$a->profile['timezone'],'')) $profile['age'] = array( t('Age:'), $age ); 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['marital']) $profile['marital'] = array( t('Status:'), $a->profile['marital']);
/// @TODO Maybe use x() here, plus below? /// @TODO Maybe use x() here, plus below?
if ($a->profile['with']) { if ($a->profile['with']) {
@ -850,14 +850,14 @@ function profile_tabs($a, $is_owner=False, $nickname=Null){
} }
function get_my_url() { function get_my_url() {
if(x($_SESSION,'my_url')) if (x($_SESSION,'my_url'))
return $_SESSION['my_url']; return $_SESSION['my_url'];
return false; return false;
} }
function zrl_init(App $a) { function zrl_init(App $a) {
$tmp_str = get_my_url(); $tmp_str = get_my_url();
if(validate_url($tmp_str)) { if (validate_url($tmp_str)) {
// Is it a DDoS attempt? // Is it a DDoS attempt?
// The check fetches the cached value from gprobe to reduce the load for this system // The check fetches the cached value from gprobe to reduce the load for this system
@ -878,16 +878,20 @@ function zrl_init(App $a) {
} }
function zrl($s,$force = false) { function zrl($s,$force = false) {
if(! strlen($s)) if (! strlen($s)) {
return $s; return $s;
if((! strpos($s,'/profile/')) && (! $force)) }
if ((! strpos($s,'/profile/')) && (! $force)) {
return $s; return $s;
if($force && substr($s,-1,1) !== '/') }
if ($force && substr($s,-1,1) !== '/') {
$s = $s . '/'; $s = $s . '/';
}
$achar = strpos($s,'?') ? '&' : '?'; $achar = strpos($s,'?') ? '&' : '?';
$mine = get_my_url(); $mine = get_my_url();
if($mine and ! link_compare($mine,$s)) if ($mine and ! link_compare($mine,$s)) {
return $s . $achar . 'zrl=' . urlencode($mine); return $s . $achar . 'zrl=' . urlencode($mine);
}
return $s; return $s;
} }
@ -907,10 +911,11 @@ function zrl($s,$force = false) {
*/ */
function get_theme_uid() { function get_theme_uid() {
$uid = (($_REQUEST['puid']) ? intval($_REQUEST['puid']) : 0); $uid = (($_REQUEST['puid']) ? intval($_REQUEST['puid']) : 0);
if(local_user()) { if (local_user()) {
if((get_pconfig(local_user(),'system','always_my_theme')) || (! $uid)) if ((get_pconfig(local_user(),'system','always_my_theme')) || (! $uid)) {
return local_user(); return local_user();
} }
}
return $uid; return $uid;
} }

View file

@ -60,7 +60,7 @@ function limit_body_size($body) {
$img_start = strpos($orig_body, '[img'); $img_start = strpos($orig_body, '[img');
$img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false); $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
$img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false); $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
while(($img_st_close !== false) && ($img_end !== false)) { while (($img_st_close !== false) && ($img_end !== false)) {
$img_st_close++; // make it point to AFTER the closing bracket $img_st_close++; // make it point to AFTER the closing bracket
$img_end += $img_start; $img_end += $img_start;
@ -1099,7 +1099,7 @@ function item_body_set_hashtags(&$item) {
"&num;$2", $item["body"]); "&num;$2", $item["body"]);
foreach($tags as $tag) { foreach ($tags as $tag) {
if (strpos($tag,'#') !== 0) if (strpos($tag,'#') !== 0)
continue; continue;
@ -1170,7 +1170,7 @@ function get_item_id($guid, $uid = 0) {
function get_item_contact($item,$contacts) { function get_item_contact($item,$contacts) {
if (! count($contacts) || (! is_array($item))) if (! count($contacts) || (! is_array($item)))
return false; return false;
foreach($contacts as $contact) { foreach ($contacts as $contact) {
if ($contact['id'] == $item['contact-id']) { if ($contact['id'] == $item['contact-id']) {
return $contact; return $contact;
break; // NOTREACHED break; // NOTREACHED
@ -1224,7 +1224,7 @@ function tag_deliver($uid,$item_id) {
$cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER); $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
if ($cnt) { if ($cnt) {
foreach($matches as $mtch) { foreach ($matches as $mtch) {
if (link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) { if (link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
$mention = true; $mention = true;
logger('tag_deliver: mention found: ' . $mtch[2]); logger('tag_deliver: mention found: ' . $mtch[2]);
@ -1681,7 +1681,7 @@ function fix_private_photos($s, $uid, $item = null, $cid = 0) {
$img_start = strpos($orig_body, '[img'); $img_start = strpos($orig_body, '[img');
$img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false); $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
$img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false); $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
while( ($img_st_close !== false) && ($img_len !== false) ) { while ( ($img_st_close !== false) && ($img_len !== false) ) {
$img_st_close++; // make it point to AFTER the closing bracket $img_st_close++; // make it point to AFTER the closing bracket
$image = substr($orig_body, $img_start + $img_st_close, $img_len); $image = substr($orig_body, $img_start + $img_st_close, $img_len);
@ -1810,7 +1810,7 @@ function item_getfeedtags($item) {
$matches = false; $matches = false;
$cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches); $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
if ($cnt) { if ($cnt) {
for($x = 0; $x < $cnt; $x ++) { for ($x = 0; $x < $cnt; $x ++) {
if ($matches[1][$x]) if ($matches[1][$x])
$ret[$matches[2][$x]] = array('#',$matches[1][$x], $matches[2][$x]); $ret[$matches[2][$x]] = array('#',$matches[1][$x], $matches[2][$x]);
} }
@ -1818,7 +1818,7 @@ function item_getfeedtags($item) {
$matches = false; $matches = false;
$cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches); $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
if ($cnt) { if ($cnt) {
for($x = 0; $x < $cnt; $x ++) { for ($x = 0; $x < $cnt; $x ++) {
if ($matches[1][$x]) if ($matches[1][$x])
$ret[] = array('@',$matches[1][$x], $matches[2][$x]); $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
} }
@ -1876,7 +1876,7 @@ function item_expire($uid, $days, $network = "", $force = false) {
logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos"); logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
foreach($r as $item) { foreach ($r as $item) {
// don't expire filed items // don't expire filed items
@ -1909,7 +1909,7 @@ function drop_items($items) {
return; return;
if (count($items)) { if (count($items)) {
foreach($items as $item) { foreach ($items as $item) {
$owner = drop_item($item,false); $owner = drop_item($item,false);
if ($owner && ! $uid) if ($owner && ! $uid)
$uid = $owner; $uid = $owner;
@ -1949,7 +1949,7 @@ function drop_item($id,$interactive = true) {
// check if logged in user is either the author or owner of this item // check if logged in user is either the author or owner of this item
if (is_array($_SESSION['remote'])) { if (is_array($_SESSION['remote'])) {
foreach($_SESSION['remote'] as $visitor) { foreach ($_SESSION['remote'] as $visitor) {
if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) { if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
$contact_id = $visitor['cid']; $contact_id = $visitor['cid'];
break; break;
@ -1966,7 +1966,7 @@ function drop_item($id,$interactive = true) {
// so add any arguments as hidden inputs // so add any arguments as hidden inputs
$query = explode_querystring($a->query_string); $query = explode_querystring($a->query_string);
$inputs = array(); $inputs = array();
foreach($query['args'] as $arg) { foreach ($query['args'] as $arg) {
if (strpos($arg, 'confirm=') === false) { if (strpos($arg, 'confirm=') === false) {
$arg_parts = explode('=', $arg); $arg_parts = explode('=', $arg);
$inputs[] = array('name' => $arg_parts[0], 'value' => $arg_parts[1]); $inputs[] = array('name' => $arg_parts[0], 'value' => $arg_parts[1]);
@ -2005,7 +2005,7 @@ function drop_item($id,$interactive = true) {
$matches = false; $matches = false;
$cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER); $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
if ($cnt) { if ($cnt) {
foreach($matches as $mtch) { foreach ($matches as $mtch) {
file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true); file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
} }
} }
@ -2014,7 +2014,7 @@ function drop_item($id,$interactive = true) {
$cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER); $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
if ($cnt) { if ($cnt) {
foreach($matches as $mtch) { foreach ($matches as $mtch) {
file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false); file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
} }
} }
@ -2044,7 +2044,7 @@ function drop_item($id,$interactive = true) {
// If item has attachments, drop them // If item has attachments, drop them
foreach(explode(",",$item['attach']) as $attach){ foreach (explode(",",$item['attach']) as $attach){
preg_match("|attach/(\d+)|", $attach, $matches); preg_match("|attach/(\d+)|", $attach, $matches);
q("DELETE FROM `attach` WHERE `id` = %d AND `uid` = %d", q("DELETE FROM `attach` WHERE `id` = %d AND `uid` = %d",
intval($matches[1]), intval($matches[1]),
@ -2179,7 +2179,7 @@ function list_post_dates($uid, $wall) {
// Starting with the current month, get the first and last days of every // Starting with the current month, get the first and last days of every
// month down to and including the month of the first post // month down to and including the month of the first post
while(substr($dnow, 0, 7) >= substr($dthen, 0, 7)) { while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
$dyear = intval(substr($dnow,0,4)); $dyear = intval(substr($dnow,0,4));
$dstart = substr($dnow,0,8) . '01'; $dstart = substr($dnow,0,8) . '01';
$dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5))); $dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
@ -2208,7 +2208,7 @@ function posted_dates($uid,$wall) {
$ret = array(); $ret = array();
// Starting with the current month, get the first and last days of every // Starting with the current month, get the first and last days of every
// month down to and including the month of the first post // month down to and including the month of the first post
while(substr($dnow, 0, 7) >= substr($dthen, 0, 7)) { while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
$dstart = substr($dnow,0,8) . '01'; $dstart = substr($dnow,0,8) . '01';
$dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5))); $dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
$start_month = datetime_convert('','',$dstart,'Y-m-d'); $start_month = datetime_convert('','',$dstart,'Y-m-d');

View file

@ -2,9 +2,9 @@
// Provide some ability to lock a PHP function so that multiple processes // Provide some ability to lock a PHP function so that multiple processes
// can't run the function concurrently // can't run the function concurrently
if(! function_exists('lock_function')) { if (! function_exists('lock_function')) {
function lock_function($fn_name, $block = true, $wait_sec = 2, $timeout = 30) { function lock_function($fn_name, $block = true, $wait_sec = 2, $timeout = 30) {
if( $wait_sec == 0 ) if ( $wait_sec == 0 )
$wait_sec = 2; // don't let the user pick a value that's likely to crash the system $wait_sec = 2; // don't let the user pick a value that's likely to crash the system
$got_lock = false; $got_lock = false;
@ -16,7 +16,7 @@ function lock_function($fn_name, $block = true, $wait_sec = 2, $timeout = 30) {
dbesc($fn_name) dbesc($fn_name)
); );
if((dbm::is_result($r)) AND (!$r[0]['locked'] OR (strtotime($r[0]['created']) < time() - 3600))) { if ((dbm::is_result($r)) AND (!$r[0]['locked'] OR (strtotime($r[0]['created']) < time() - 3600))) {
q("UPDATE `locks` SET `locked` = 1, `created` = '%s' WHERE `name` = '%s'", q("UPDATE `locks` SET `locked` = 1, `created` = '%s' WHERE `name` = '%s'",
dbesc(datetime_convert()), dbesc(datetime_convert()),
dbesc($fn_name) dbesc($fn_name)
@ -34,10 +34,10 @@ function lock_function($fn_name, $block = true, $wait_sec = 2, $timeout = 30) {
q("UNLOCK TABLES"); q("UNLOCK TABLES");
if(($block) && (! $got_lock)) if (($block) && (! $got_lock))
sleep($wait_sec); sleep($wait_sec);
} while(($block) && (! $got_lock) && ((time() - $start) < $timeout)); } while (($block) && (! $got_lock) && ((time() - $start) < $timeout));
logger('lock_function: function ' . $fn_name . ' with blocking = ' . $block . ' got_lock = ' . $got_lock . ' time = ' . (time() - $start), LOGGER_DEBUG); logger('lock_function: function ' . $fn_name . ' with blocking = ' . $block . ' got_lock = ' . $got_lock . ' time = ' . (time() - $start), LOGGER_DEBUG);
@ -45,9 +45,9 @@ function lock_function($fn_name, $block = true, $wait_sec = 2, $timeout = 30) {
}} }}
if(! function_exists('block_on_function_lock')) { if (! function_exists('block_on_function_lock')) {
function block_on_function_lock($fn_name, $wait_sec = 2, $timeout = 30) { function block_on_function_lock($fn_name, $wait_sec = 2, $timeout = 30) {
if( $wait_sec == 0 ) if ( $wait_sec == 0 )
$wait_sec = 2; // don't let the user pick a value that's likely to crash the system $wait_sec = 2; // don't let the user pick a value that's likely to crash the system
$start = time(); $start = time();
@ -57,16 +57,17 @@ function block_on_function_lock($fn_name, $wait_sec = 2, $timeout = 30) {
dbesc($fn_name) dbesc($fn_name)
); );
if (dbm::is_result($r) && $r[0]['locked']) if (dbm::is_result($r) && $r[0]['locked']) {
sleep($wait_sec); sleep($wait_sec);
}
} while(dbm::is_result($r) && $r[0]['locked'] && ((time() - $start) < $timeout)); } while (dbm::is_result($r) && $r[0]['locked'] && ((time() - $start) < $timeout));
return; return;
}} }}
if(! function_exists('unlock_function')) { if (! function_exists('unlock_function')) {
function unlock_function($fn_name) { function unlock_function($fn_name) {
$r = q("UPDATE `locks` SET `locked` = 0, `created` = '%s' WHERE `name` = '%s'", $r = q("UPDATE `locks` SET `locked` = 0, `created` = '%s' WHERE `name` = '%s'",
dbesc(NULL_DATE), dbesc(NULL_DATE),

View file

@ -9,9 +9,9 @@ function send_message($recipient=0, $body='', $subject='', $replyto=''){
$a = get_app(); $a = get_app();
if(! $recipient) return -1; if (! $recipient) return -1;
if(! strlen($subject)) if (! strlen($subject))
$subject = t('[no subject]'); $subject = t('[no subject]');
$me = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1", $me = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
@ -22,7 +22,7 @@ function send_message($recipient=0, $body='', $subject='', $replyto=''){
intval(local_user()) intval(local_user())
); );
if(! (count($me) && (count($contact)))) { if (! (count($me) && (count($contact)))) {
return -2; return -2;
} }
@ -34,7 +34,7 @@ function send_message($recipient=0, $body='', $subject='', $replyto=''){
// look for any existing conversation structure // look for any existing conversation structure
if(strlen($replyto)) { if (strlen($replyto)) {
$reply = true; $reply = true;
$r = q("select convid from mail where uid = %d and ( uri = '%s' or `parent-uri` = '%s' ) limit 1", $r = q("select convid from mail where uid = %d and ( uri = '%s' or `parent-uri` = '%s' ) limit 1",
intval(local_user()), intval(local_user()),
@ -45,7 +45,7 @@ function send_message($recipient=0, $body='', $subject='', $replyto=''){
$convid = $r[0]['convid']; $convid = $r[0]['convid'];
} }
if(! $convid) { if (! $convid) {
// create a new conversation // create a new conversation
@ -78,12 +78,12 @@ function send_message($recipient=0, $body='', $subject='', $replyto=''){
$convid = $r[0]['id']; $convid = $r[0]['id'];
} }
if(! $convid) { if (! $convid) {
logger('send message: conversation not found.'); logger('send message: conversation not found.');
return -4; return -4;
} }
if(! strlen($replyto)) { if (! strlen($replyto)) {
$replyto = $convuri; $replyto = $convuri;
} }

View file

@ -154,7 +154,7 @@ function removelinebreak($message)
$lines = array(); $lines = array();
$lineno = 0; $lineno = 0;
foreach($arrbody as $i => $line) { foreach ($arrbody as $i => $line) {
$currquotelevel = 0; $currquotelevel = 0;
$currline = $line; $currline = $line;
while ((strlen($currline)>0) and ((substr($currline, 0, 1) == '>') while ((strlen($currline)>0) and ((substr($currline, 0, 1) == '>')

View file

@ -8,7 +8,7 @@ function nav(App $a) {
* *
*/ */
if(!(x($a->page,'nav'))) if (!(x($a->page,'nav')))
$a->page['nav'] = ''; $a->page['nav'] = '';
$a->page['htmlhead'] .= replace_macros(get_markup_template('nav_head.tpl'), array()); $a->page['htmlhead'] .= replace_macros(get_markup_template('nav_head.tpl'), array());
@ -136,7 +136,7 @@ function nav_info(App $a)
if (strlen(get_config('system', 'singleuser'))) { if (strlen(get_config('system', 'singleuser'))) {
$gdir = get_config('system', 'directory'); $gdir = get_config('system', 'directory');
if(strlen($gdir)) { if (strlen($gdir)) {
$gdirpath = zrl($gdir, true); $gdirpath = zrl($gdir, true);
} }
} elseif (get_config('system', 'community_page_style') == CP_USERS_ON_SERVER) { } elseif (get_config('system', 'community_page_style') == CP_USERS_ON_SERVER) {

View file

@ -78,7 +78,7 @@ function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
@curl_setopt($ch, CURLOPT_HEADER, true); @curl_setopt($ch, CURLOPT_HEADER, true);
if(x($opts,"cookiejar")) { if (x($opts,"cookiejar")) {
curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]); curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]); curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
} }
@ -101,13 +101,13 @@ function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
@curl_setopt($ch, CURLOPT_RANGE, '0-'.$range); @curl_setopt($ch, CURLOPT_RANGE, '0-'.$range);
} }
if(x($opts,'headers')){ if (x($opts,'headers')){
@curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']); @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
} }
if(x($opts,'nobody')){ if (x($opts,'nobody')){
@curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']); @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
} }
if(x($opts,'timeout')){ if (x($opts,'timeout')){
@curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']); @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
} else { } else {
$curl_time = intval(get_config('system','curl_timeout')); $curl_time = intval(get_config('system','curl_timeout'));
@ -124,14 +124,14 @@ function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
} }
$prx = get_config('system','proxy'); $prx = get_config('system','proxy');
if(strlen($prx)) { if (strlen($prx)) {
@curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
@curl_setopt($ch, CURLOPT_PROXY, $prx); @curl_setopt($ch, CURLOPT_PROXY, $prx);
$prxusr = @get_config('system','proxyuser'); $prxusr = @get_config('system','proxyuser');
if(strlen($prxusr)) if (strlen($prxusr))
@curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr); @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
} }
if($binary) if ($binary)
@curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$a->set_curl_code(0); $a->set_curl_code(0);
@ -156,7 +156,7 @@ function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
// Pull out multiple headers, e.g. proxy and continuation headers // Pull out multiple headers, e.g. proxy and continuation headers
// allow for HTTP/2.x without fixing code // allow for HTTP/2.x without fixing code
while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) { while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
$chunk = substr($base,0,strpos($base,"\r\n\r\n")+4); $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
$header .= $chunk; $header .= $chunk;
$base = substr($base,strlen($chunk)); $base = substr($base,strlen($chunk));
@ -166,7 +166,7 @@ function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
$a->set_curl_content_type($curl_info['content_type']); $a->set_curl_content_type($curl_info['content_type']);
$a->set_curl_headers($header); $a->set_curl_headers($header);
if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) { if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
$new_location_info = @parse_url($curl_info["redirect_url"]); $new_location_info = @parse_url($curl_info["redirect_url"]);
$old_location_info = @parse_url($curl_info["url"]); $old_location_info = @parse_url($curl_info["url"]);
@ -179,7 +179,7 @@ function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) { if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
$newurl = trim(array_pop($matches)); $newurl = trim(array_pop($matches));
} }
if(strpos($newurl,'/') === 0) if (strpos($newurl,'/') === 0)
$newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl; $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
if (filter_var($newurl, FILTER_VALIDATE_URL)) { if (filter_var($newurl, FILTER_VALIDATE_URL)) {
$redirects++; $redirects++;
@ -200,7 +200,7 @@ function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
$ret['return_code'] = $rc; $ret['return_code'] = $rc;
$ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false); $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
$ret['redirect_url'] = $url; $ret['redirect_url'] = $url;
if(! $ret['success']) { if (! $ret['success']) {
$ret['error'] = curl_error($ch); $ret['error'] = curl_error($ch);
$ret['debug'] = $curl_info; $ret['debug'] = $curl_info;
logger('z_fetch_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG); logger('z_fetch_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
@ -208,7 +208,7 @@ function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
} }
$ret['body'] = substr($s,strlen($header)); $ret['body'] = substr($s,strlen($header));
$ret['header'] = $header; $ret['header'] = $header;
if(x($opts,'debug')) { if (x($opts,'debug')) {
$ret['debug'] = $curl_info; $ret['debug'] = $curl_info;
} }
@curl_close($ch); @curl_close($ch);
@ -237,7 +237,7 @@ function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0)
$a = get_app(); $a = get_app();
$ch = curl_init($url); $ch = curl_init($url);
if(($redirects > 8) || (! $ch)) if (($redirects > 8) || (! $ch))
return false; return false;
logger("post_url: start ".$url, LOGGER_DATA); logger("post_url: start ".$url, LOGGER_DATA);
@ -248,7 +248,7 @@ function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0)
curl_setopt($ch, CURLOPT_POSTFIELDS,$params); curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent()); curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
if(intval($timeout)) { if (intval($timeout)) {
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
} }
else { else {
@ -256,16 +256,16 @@ function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0)
curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60)); curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
} }
if(defined('LIGHTTPD')) { if (defined('LIGHTTPD')) {
if(!is_array($headers)) { if (!is_array($headers)) {
$headers = array('Expect:'); $headers = array('Expect:');
} else { } else {
if(!in_array('Expect:', $headers)) { if (!in_array('Expect:', $headers)) {
array_push($headers, 'Expect:'); array_push($headers, 'Expect:');
} }
} }
} }
if($headers) if ($headers)
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$check_cert = get_config('system','verifyssl'); $check_cert = get_config('system','verifyssl');
@ -274,11 +274,11 @@ function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0)
@curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
} }
$prx = get_config('system','proxy'); $prx = get_config('system','proxy');
if(strlen($prx)) { if (strlen($prx)) {
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
curl_setopt($ch, CURLOPT_PROXY, $prx); curl_setopt($ch, CURLOPT_PROXY, $prx);
$prxusr = get_config('system','proxyuser'); $prxusr = get_config('system','proxyuser');
if(strlen($prxusr)) if (strlen($prxusr))
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr); curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
} }
@ -300,17 +300,17 @@ function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0)
// Pull out multiple headers, e.g. proxy and continuation headers // Pull out multiple headers, e.g. proxy and continuation headers
// allow for HTTP/2.x without fixing code // allow for HTTP/2.x without fixing code
while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) { while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
$chunk = substr($base,0,strpos($base,"\r\n\r\n")+4); $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
$header .= $chunk; $header .= $chunk;
$base = substr($base,strlen($chunk)); $base = substr($base,strlen($chunk));
} }
if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) { if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
$matches = array(); $matches = array();
preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches); preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
$newurl = trim(array_pop($matches)); $newurl = trim(array_pop($matches));
if(strpos($newurl,'/') === 0) if (strpos($newurl,'/') === 0)
$newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl; $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
if (filter_var($newurl, FILTER_VALIDATE_URL)) { if (filter_var($newurl, FILTER_VALIDATE_URL)) {
$redirects++; $redirects++;
@ -341,7 +341,7 @@ function xml_status($st, $message = '') {
$xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : ''); $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
if($st) if ($st)
logger('xml_status returning non_zero: ' . $st . " message=" . $message); logger('xml_status returning non_zero: ' . $st . " message=" . $message);
header( "Content-type: text/xml" ); header( "Content-type: text/xml" );
@ -369,12 +369,12 @@ function xml_status($st, $message = '') {
*/ */
function http_status_exit($val, $description = array()) { function http_status_exit($val, $description = array()) {
$err = ''; $err = '';
if($val >= 400) { if ($val >= 400) {
$err = 'Error'; $err = 'Error';
if (!isset($description["title"])) if (!isset($description["title"]))
$description["title"] = $err." ".$val; $description["title"] = $err." ".$val;
} }
if($val >= 200 && $val < 300) if ($val >= 200 && $val < 300)
$err = 'OK'; $err = 'OK';
logger('http_status_exit ' . $val); logger('http_status_exit ' . $val);
@ -400,20 +400,20 @@ function http_status_exit($val, $description = array()) {
* @return boolean True if it's a valid URL, fals if something wrong with it * @return boolean True if it's a valid URL, fals if something wrong with it
*/ */
function validate_url(&$url) { function validate_url(&$url) {
if(get_config('system','disable_url_validation')) if (get_config('system','disable_url_validation'))
return true; return true;
// no naked subdomains (allow localhost for tests) // no naked subdomains (allow localhost for tests)
if(strpos($url,'.') === false && strpos($url,'/localhost/') === false) if (strpos($url,'.') === false && strpos($url,'/localhost/') === false)
return false; return false;
if(substr($url,0,4) != 'http') if (substr($url,0,4) != 'http')
$url = 'http://' . $url; $url = 'http://' . $url;
/// @TODO Really supress function outcomes? Why not find them + debug them? /// @TODO Really supress function outcomes? Why not find them + debug them?
$h = @parse_url($url); $h = @parse_url($url);
if((is_array($h)) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) { if ((is_array($h)) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
return true; return true;
} }
@ -428,14 +428,14 @@ function validate_url(&$url) {
*/ */
function validate_email($addr) { function validate_email($addr) {
if(get_config('system','disable_email_validation')) if (get_config('system','disable_email_validation'))
return true; return true;
if(! strpos($addr,'@')) if (! strpos($addr,'@'))
return false; return false;
$h = substr($addr,strpos($addr,'@') + 1); $h = substr($addr,strpos($addr,'@') + 1);
if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) { if (($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
return true; return true;
} }
return false; return false;
@ -454,12 +454,12 @@ function allowed_url($url) {
$h = @parse_url($url); $h = @parse_url($url);
if(! $h) { if (! $h) {
return false; return false;
} }
$str_allowed = get_config('system','allowed_sites'); $str_allowed = get_config('system','allowed_sites');
if(! $str_allowed) if (! $str_allowed)
return true; return true;
$found = false; $found = false;
@ -468,16 +468,16 @@ function allowed_url($url) {
// always allow our own site // always allow our own site
if($host == strtolower($_SERVER['SERVER_NAME'])) if ($host == strtolower($_SERVER['SERVER_NAME']))
return true; return true;
$fnmatch = function_exists('fnmatch'); $fnmatch = function_exists('fnmatch');
$allowed = explode(',',$str_allowed); $allowed = explode(',',$str_allowed);
if(count($allowed)) { if (count($allowed)) {
foreach($allowed as $a) { foreach ($allowed as $a) {
$pat = strtolower(trim($a)); $pat = strtolower(trim($a));
if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) { if (($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
$found = true; $found = true;
break; break;
} }
@ -497,24 +497,25 @@ function allowed_url($url) {
*/ */
function allowed_email($email) { function allowed_email($email) {
$domain = strtolower(substr($email,strpos($email,'@') + 1)); $domain = strtolower(substr($email,strpos($email,'@') + 1));
if(! $domain) if (! $domain) {
return false; return false;
}
$str_allowed = get_config('system','allowed_email'); $str_allowed = get_config('system','allowed_email');
if(! $str_allowed) if (! $str_allowed) {
return true; return true;
}
$found = false; $found = false;
$fnmatch = function_exists('fnmatch'); $fnmatch = function_exists('fnmatch');
$allowed = explode(',',$str_allowed); $allowed = explode(',',$str_allowed);
if(count($allowed)) { if (count($allowed)) {
foreach($allowed as $a) { foreach ($allowed as $a) {
$pat = strtolower(trim($a)); $pat = strtolower(trim($a));
if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) { if (($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
$found = true; $found = true;
break; break;
} }
@ -543,8 +544,8 @@ function avatar_img($email) {
function parse_xml_string($s,$strict = true) { function parse_xml_string($s,$strict = true) {
/// @todo Move this function to the xml class /// @todo Move this function to the xml class
if($strict) { if ($strict) {
if(! strstr($s,'<?xml')) if (! strstr($s,'<?xml'))
return false; return false;
$s2 = substr($s,strpos($s,'<?xml')); $s2 = substr($s,strpos($s,'<?xml'));
} }

View file

@ -155,7 +155,7 @@ class FKOAuth1 extends OAuthServer {
//notice( t("Welcome back ") . $record['username'] . EOL); //notice( t("Welcome back ") . $record['username'] . EOL);
$a->user = $record; $a->user = $record;
if(strlen($a->user['timezone'])) { if (strlen($a->user['timezone'])) {
date_default_timezone_set($a->user['timezone']); date_default_timezone_set($a->user['timezone']);
$a->timezone = $a->user['timezone']; $a->timezone = $a->user['timezone'];
} }

View file

@ -314,9 +314,11 @@ function oembed_html2bbcode($text) {
$entries = $xpath->query("//span[$xattr]"); $entries = $xpath->query("//span[$xattr]");
$xattr = "@rel='oembed'";//oe_build_xpath("rel","oembed"); $xattr = "@rel='oembed'";//oe_build_xpath("rel","oembed");
foreach($entries as $e) { foreach ($entries as $e) {
$href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue; $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
if(!is_null($href)) $e->parentNode->replaceChild(new DOMText("[embed]".$href."[/embed]"), $e); if (!is_null($href)) {
$e->parentNode->replaceChild(new DOMText("[embed]".$href."[/embed]"), $e);
}
} }
return oe_get_inner_html( $dom->getElementsByTagName("body")->item(0) ); return oe_get_inner_html( $dom->getElementsByTagName("body")->item(0) );
} else { } else {

View file

@ -61,7 +61,7 @@ function onepoll_run(&$argv, &$argc){
intval($contact_id) intval($contact_id)
); );
if (! count($contacts)) { if (! dbm::is_result($contacts)) {
return; return;
} }
@ -437,16 +437,18 @@ function onepoll_run(&$argv, &$argc){
if ($raw_refs) { if ($raw_refs) {
$refs_arr = explode(' ', $raw_refs); $refs_arr = explode(' ', $raw_refs);
if (count($refs_arr)) { if (count($refs_arr)) {
for($x = 0; $x < count($refs_arr); $x ++) for ($x = 0; $x < count($refs_arr); $x ++) {
$refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'"; $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
} }
}
$qstr = implode(',',$refs_arr); $qstr = implode(',',$refs_arr);
$r = q("SELECT `uri` , `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1", $r = q("SELECT `uri` , `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1",
intval($importer_uid) intval($importer_uid)
); );
if (dbm::is_result($r)) if (dbm::is_result($r)) {
$datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
// $datarray['parent-uri'] = $r[0]['uri']; //$datarray['parent-uri'] = $r[0]['uri'];
}
} }
// Decoding the header // Decoding the header

File diff suppressed because it is too large Load diff

View file

@ -14,7 +14,7 @@ use \Friendica\Core\Config;
require_once("include/dba.php"); require_once("include/dba.php");
if(! function_exists('get_browser_language')) { if (! function_exists('get_browser_language')) {
/** /**
* @brief get the prefered language from the HTTP_ACCEPT_LANGUAGE header * @brief get the prefered language from the HTTP_ACCEPT_LANGUAGE header
*/ */
@ -44,7 +44,7 @@ function get_browser_language() {
// check if we have translations for the preferred languages and pick the 1st that has // check if we have translations for the preferred languages and pick the 1st that has
for ($i=0; $i<count($lang_list); $i++) { for ($i=0; $i<count($lang_list); $i++) {
$lang = $lang_list[$i]; $lang = $lang_list[$i];
if(file_exists("view/lang/$lang") && is_dir("view/lang/$lang")) { if (file_exists("view/lang/$lang") && is_dir("view/lang/$lang")) {
$preferred = $lang; $preferred = $lang;
break; break;
} }
@ -63,10 +63,10 @@ function push_lang($language) {
$a->langsave = $lang; $a->langsave = $lang;
if($language === $lang) if ($language === $lang)
return; return;
if(isset($a->strings) && count($a->strings)) { if (isset($a->strings) && count($a->strings)) {
$a->stringsave = $a->strings; $a->stringsave = $a->strings;
} }
$a->strings = array(); $a->strings = array();
@ -77,10 +77,10 @@ function push_lang($language) {
function pop_lang() { function pop_lang() {
global $lang, $a; global $lang, $a;
if($lang === $a->langsave) if ($lang === $a->langsave)
return; return;
if(isset($a->stringsave)) if (isset($a->stringsave))
$a->strings = $a->stringsave; $a->strings = $a->stringsave;
else else
$a->strings = array(); $a->strings = array();
@ -91,7 +91,7 @@ function pop_lang() {
// l // l
if(! function_exists('load_translation_table')) { if (! function_exists('load_translation_table')) {
/** /**
* load string translation table for alternate language * load string translation table for alternate language
* *
@ -106,15 +106,15 @@ function load_translation_table($lang) {
// load enabled plugins strings // load enabled plugins strings
$plugins = q("SELECT name FROM addon WHERE installed=1;"); $plugins = q("SELECT name FROM addon WHERE installed=1;");
if ($plugins!==false) { if ($plugins!==false) {
foreach($plugins as $p) { foreach ($plugins as $p) {
$name = $p['name']; $name = $p['name'];
if(file_exists("addon/$name/lang/$lang/strings.php")) { if (file_exists("addon/$name/lang/$lang/strings.php")) {
include("addon/$name/lang/$lang/strings.php"); include("addon/$name/lang/$lang/strings.php");
} }
} }
} }
if(file_exists("view/lang/$lang/strings.php")) { if (file_exists("view/lang/$lang/strings.php")) {
include("view/lang/$lang/strings.php"); include("view/lang/$lang/strings.php");
} }
@ -122,27 +122,27 @@ function load_translation_table($lang) {
// translate string if translation exists // translate string if translation exists
if(! function_exists('t')) { if (! function_exists('t')) {
function t($s) { function t($s) {
$a = get_app(); $a = get_app();
if(x($a->strings,$s)) { if (x($a->strings,$s)) {
$t = $a->strings[$s]; $t = $a->strings[$s];
return is_array($t)?$t[0]:$t; return is_array($t)?$t[0]:$t;
} }
return $s; return $s;
}} }}
if(! function_exists('tt')){ if (! function_exists('tt')){
function tt($singular, $plural, $count){ function tt($singular, $plural, $count){
global $lang; global $lang;
$a = get_app(); $a = get_app();
if(x($a->strings,$singular)) { if (x($a->strings,$singular)) {
$t = $a->strings[$singular]; $t = $a->strings[$singular];
$f = 'string_plural_select_' . str_replace('-','_',$lang); $f = 'string_plural_select_' . str_replace('-','_',$lang);
if(! function_exists($f)) if (! function_exists($f))
$f = 'string_plural_select_default'; $f = 'string_plural_select_default';
$k = $f($count); $k = $f($count);
return is_array($t)?$t[$k]:$t; return is_array($t)?$t[$k]:$t;
@ -158,7 +158,7 @@ function tt($singular, $plural, $count){
// provide a fallback which will not collide with // provide a fallback which will not collide with
// a function defined in any language file // a function defined in any language file
if(! function_exists('string_plural_select_default')) { if (! function_exists('string_plural_select_default')) {
function string_plural_select_default($n) { function string_plural_select_default($n) {
return ($n != 1); return ($n != 1);
}} }}
@ -185,7 +185,7 @@ function get_available_languages() {
$strings_file_paths[] = 'view/lang/en/strings.php'; $strings_file_paths[] = 'view/lang/en/strings.php';
} }
asort($strings_file_paths); asort($strings_file_paths);
foreach($strings_file_paths as $strings_file_path) { foreach ($strings_file_paths as $strings_file_path) {
$path_array = explode('/', $strings_file_path); $path_array = explode('/', $strings_file_path);
$langs[$path_array[2]] = $path_array[2]; $langs[$path_array[2]] = $path_array[2];
} }

View file

@ -20,7 +20,7 @@ function uninstall_plugin($plugin){
); );
@include_once('addon/' . $plugin . '/' . $plugin . '.php'); @include_once('addon/' . $plugin . '/' . $plugin . '.php');
if(function_exists($plugin . '_uninstall')) { if (function_exists($plugin . '_uninstall')) {
$func = $plugin . '_uninstall'; $func = $plugin . '_uninstall';
$func(); $func();
} }
@ -36,12 +36,12 @@ if (! function_exists('install_plugin')){
function install_plugin($plugin) { function install_plugin($plugin) {
// silently fail if plugin was removed // silently fail if plugin was removed
if(! file_exists('addon/' . $plugin . '/' . $plugin . '.php')) if (! file_exists('addon/' . $plugin . '/' . $plugin . '.php'))
return false; return false;
logger("Addons: installing " . $plugin); logger("Addons: installing " . $plugin);
$t = @filemtime('addon/' . $plugin . '/' . $plugin . '.php'); $t = @filemtime('addon/' . $plugin . '/' . $plugin . '.php');
@include_once('addon/' . $plugin . '/' . $plugin . '.php'); @include_once('addon/' . $plugin . '/' . $plugin . '.php');
if(function_exists($plugin . '_install')) { if (function_exists($plugin . '_install')) {
$func = $plugin . '_install'; $func = $plugin . '_install';
$func(); $func();
@ -57,7 +57,7 @@ function install_plugin($plugin) {
// once most site tables have been updated. // once most site tables have been updated.
// This way the system won't fall over dead during the update. // This way the system won't fall over dead during the update.
if(file_exists('addon/' . $plugin . '/.hidden')) { if (file_exists('addon/' . $plugin . '/.hidden')) {
q("UPDATE `addon` SET `hidden` = 1 WHERE `name` = '%s'", q("UPDATE `addon` SET `hidden` = 1 WHERE `name` = '%s'",
dbesc($plugin) dbesc($plugin)
); );
@ -73,10 +73,10 @@ function install_plugin($plugin) {
// reload all updated plugins // reload all updated plugins
if(! function_exists('reload_plugins')) { if (! function_exists('reload_plugins')) {
function reload_plugins() { function reload_plugins() {
$plugins = get_config('system','addon'); $plugins = get_config('system','addon');
if(strlen($plugins)) { if (strlen($plugins)) {
$r = q("SELECT * FROM `addon` WHERE `installed` = 1"); $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
if (dbm::is_result($r)) if (dbm::is_result($r))
@ -86,25 +86,25 @@ function reload_plugins() {
$parr = explode(',',$plugins); $parr = explode(',',$plugins);
if(count($parr)) { if (count($parr)) {
foreach($parr as $pl) { foreach ($parr as $pl) {
$pl = trim($pl); $pl = trim($pl);
$fname = 'addon/' . $pl . '/' . $pl . '.php'; $fname = 'addon/' . $pl . '/' . $pl . '.php';
if(file_exists($fname)) { if (file_exists($fname)) {
$t = @filemtime($fname); $t = @filemtime($fname);
foreach($installed as $i) { foreach ($installed as $i) {
if(($i['name'] == $pl) && ($i['timestamp'] != $t)) { if (($i['name'] == $pl) && ($i['timestamp'] != $t)) {
logger('Reloading plugin: ' . $i['name']); logger('Reloading plugin: ' . $i['name']);
@include_once($fname); @include_once($fname);
if(function_exists($pl . '_uninstall')) { if (function_exists($pl . '_uninstall')) {
$func = $pl . '_uninstall'; $func = $pl . '_uninstall';
$func(); $func();
} }
if(function_exists($pl . '_install')) { if (function_exists($pl . '_install')) {
$func = $pl . '_install'; $func = $pl . '_install';
$func(); $func();
} }
@ -142,7 +142,7 @@ function plugin_enabled($plugin) {
* @param int $priority A priority (defaults to 0) * @param int $priority A priority (defaults to 0)
* @return mixed|bool * @return mixed|bool
*/ */
if(! function_exists('register_hook')) { if (! function_exists('register_hook')) {
function register_hook($hook,$file,$function,$priority=0) { function register_hook($hook,$file,$function,$priority=0) {
$r = q("SELECT * FROM `hook` WHERE `hook` = '%s' AND `file` = '%s' AND `function` = '%s' LIMIT 1", $r = q("SELECT * FROM `hook` WHERE `hook` = '%s' AND `file` = '%s' AND `function` = '%s' LIMIT 1",
@ -170,7 +170,7 @@ function register_hook($hook,$file,$function,$priority=0) {
* @param string $function the name of the function that the hook called * @param string $function the name of the function that the hook called
* @return array * @return array
*/ */
if(! function_exists('unregister_hook')) { if (! function_exists('unregister_hook')) {
function unregister_hook($hook,$file,$function) { function unregister_hook($hook,$file,$function) {
$r = q("DELETE FROM `hook` WHERE `hook` = '%s' AND `file` = '%s' AND `function` = '%s'", $r = q("DELETE FROM `hook` WHERE `hook` = '%s' AND `file` = '%s' AND `function` = '%s'",
@ -182,7 +182,7 @@ function unregister_hook($hook,$file,$function) {
}} }}
if(! function_exists('load_hooks')) { if (! function_exists('load_hooks')) {
function load_hooks() { function load_hooks() {
$a = get_app(); $a = get_app();
$a->hooks = array(); $a->hooks = array();
@ -190,7 +190,7 @@ function load_hooks() {
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach ($r as $rr) { foreach ($r as $rr) {
if(! array_key_exists($rr['hook'],$a->hooks)) if (! array_key_exists($rr['hook'],$a->hooks))
$a->hooks[$rr['hook']] = array(); $a->hooks[$rr['hook']] = array();
$a->hooks[$rr['hook']][] = array($rr['file'],$rr['function']); $a->hooks[$rr['hook']][] = array($rr['file'],$rr['function']);
} }
@ -244,13 +244,13 @@ function call_single_hook($a, $name, $hook, &$data = null) {
//check if an app_menu hook exist for plugin $name. //check if an app_menu hook exist for plugin $name.
//Return true if the plugin is an app //Return true if the plugin is an app
if(! function_exists('plugin_is_app')) { if (! function_exists('plugin_is_app')) {
function plugin_is_app($name) { function plugin_is_app($name) {
$a = get_app(); $a = get_app();
if(is_array($a->hooks) && (array_key_exists('app_menu',$a->hooks))) { if (is_array($a->hooks) && (array_key_exists('app_menu',$a->hooks))) {
foreach($a->hooks['app_menu'] as $hook) { foreach ($a->hooks['app_menu'] as $hook) {
if($hook[0] == 'addon/'.$name.'/'.$name.'.php') if ($hook[0] == 'addon/'.$name.'/'.$name.'.php')
return true; return true;
} }
} }
@ -297,7 +297,7 @@ function get_plugin_info($plugin){
if ($r){ if ($r){
$ll = explode("\n", $m[0]); $ll = explode("\n", $m[0]);
foreach( $ll as $l ) { foreach ( $ll as $l ) {
$l = trim($l,"\t\n\r */"); $l = trim($l,"\t\n\r */");
if ($l!=""){ if ($l!=""){
list($k,$v) = array_map("trim", explode(":",$l,2)); list($k,$v) = array_map("trim", explode(":",$l,2));
@ -352,9 +352,9 @@ function get_theme_info($theme){
'unsupported' => false 'unsupported' => false
); );
if(file_exists("view/theme/$theme/experimental")) if (file_exists("view/theme/$theme/experimental"))
$info['experimental'] = true; $info['experimental'] = true;
if(file_exists("view/theme/$theme/unsupported")) if (file_exists("view/theme/$theme/unsupported"))
$info['unsupported'] = true; $info['unsupported'] = true;
if (!is_file("view/theme/$theme/theme.php")) return $info; if (!is_file("view/theme/$theme/theme.php")) return $info;
@ -368,7 +368,7 @@ function get_theme_info($theme){
if ($r){ if ($r){
$ll = explode("\n", $m[0]); $ll = explode("\n", $m[0]);
foreach( $ll as $l ) { foreach ( $ll as $l ) {
$l = trim($l,"\t\n\r */"); $l = trim($l,"\t\n\r */");
if ($l!=""){ if ($l!=""){
list($k,$v) = array_map("trim", explode(":",$l,2)); list($k,$v) = array_map("trim", explode(":",$l,2));
@ -412,7 +412,7 @@ function get_theme_info($theme){
*/ */
function get_theme_screenshot($theme) { function get_theme_screenshot($theme) {
$exts = array('.png','.jpg'); $exts = array('.png','.jpg');
foreach($exts as $ext) { foreach ($exts as $ext) {
if (file_exists('view/theme/' . $theme . '/screenshot' . $ext)) { if (file_exists('view/theme/' . $theme . '/screenshot' . $ext)) {
return(App::get_baseurl() . '/view/theme/' . $theme . '/screenshot' . $ext); return(App::get_baseurl() . '/view/theme/' . $theme . '/screenshot' . $ext);
} }
@ -511,11 +511,11 @@ function service_class_fetch($uid,$property) {
$service_class = $r[0]['service_class']; $service_class = $r[0]['service_class'];
} }
} }
if(! x($service_class)) if (! x($service_class))
return false; // everything is allowed 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))) if (! is_array($arr) || (! count($arr)))
return false; return false;
return((array_key_exists($property,$arr)) ? $arr[$property] : false); return((array_key_exists($property,$arr)) ? $arr[$property] : false);
@ -524,12 +524,14 @@ function service_class_fetch($uid,$property) {
function upgrade_link($bbcode = false) { function upgrade_link($bbcode = false) {
$l = get_config('service_class','upgrade_link'); $l = get_config('service_class','upgrade_link');
if(! $l) if (! $l) {
return ''; return '';
if($bbcode) }
if ($bbcode) {
$t = sprintf('[url=%s]' . t('Click here to upgrade.') . '[/url]', $l); $t = sprintf('[url=%s]' . t('Click here to upgrade.') . '[/url]', $l);
else } else {
$t = sprintf('<a href="%s">' . t('Click here to upgrade.') . '</div>', $l); $t = sprintf('<a href="%s">' . t('Click here to upgrade.') . '</div>', $l);
}
return $t; return $t;
} }
@ -556,13 +558,15 @@ function upgrade_bool_message($bbcode = false) {
*/ */
function theme_include($file, $root = '') { function theme_include($file, $root = '') {
// Make sure $root ends with a slash / if it's not blank // Make sure $root ends with a slash / if it's not blank
if($root !== '' && $root[strlen($root)-1] !== '/') if ($root !== '' && $root[strlen($root)-1] !== '/') {
$root = $root . '/'; $root = $root . '/';
}
$theme_info = $a->theme_info; $theme_info = $a->theme_info;
if(is_array($theme_info) AND array_key_exists('extends',$theme_info)) if (is_array($theme_info) AND array_key_exists('extends',$theme_info)) {
$parent = $theme_info['extends']; $parent = $theme_info['extends'];
else } else {
$parent = 'NOPATH'; $parent = 'NOPATH';
}
$theme = current_theme(); $theme = current_theme();
$thname = $theme; $thname = $theme;
$ext = substr($file,strrpos($file,'.')+1); $ext = substr($file,strrpos($file,'.')+1);
@ -571,12 +575,13 @@ function theme_include($file, $root = '') {
"{$root}view/theme/$parent/$ext/$file", "{$root}view/theme/$parent/$ext/$file",
"{$root}view/$ext/$file", "{$root}view/$ext/$file",
); );
foreach($paths as $p) { foreach ($paths as $p) {
// strpos() is faster than strstr when checking if one string is in another (http://php.net/manual/en/function.strstr.php) // strpos() is faster than strstr when checking if one string is in another (http://php.net/manual/en/function.strstr.php)
if(strpos($p,'NOPATH') !== false) if (strpos($p,'NOPATH') !== false) {
continue; continue;
if(file_exists($p)) } elseif (file_exists($p)) {
return $p; return $p;
} }
}
return ''; return '';
} }

View file

@ -17,11 +17,11 @@ require_once("boot.php");
function poller_run($argv, $argc){ function poller_run($argv, $argc){
global $a, $db; global $a, $db;
if(is_null($a)) { if (is_null($a)) {
$a = new App; $a = new App;
} }
if(is_null($db)) { if (is_null($db)) {
@include(".htconfig.php"); @include(".htconfig.php");
require_once("include/dba.php"); require_once("include/dba.php");
$db = new dba($db_host, $db_user, $db_pass, $db_data); $db = new dba($db_host, $db_user, $db_pass, $db_data);
@ -49,7 +49,7 @@ function poller_run($argv, $argc){
return; return;
} }
if(($argc <= 1) OR ($argv[1] != "no_cron")) { if (($argc <= 1) OR ($argv[1] != "no_cron")) {
poller_run_cron(); poller_run_cron();
} }
@ -364,7 +364,7 @@ function poller_kill_stale_workers() {
return; return;
} }
foreach ($r AS $pid) { foreach ($r AS $pid)
if (!posix_kill($pid["pid"], 0)) { if (!posix_kill($pid["pid"], 0)) {
q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = 0 WHERE `pid` = %d", q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = 0 WHERE `pid` = %d",
dbesc(NULL_DATE), intval($pid["pid"])); dbesc(NULL_DATE), intval($pid["pid"]));
@ -372,8 +372,9 @@ function poller_kill_stale_workers() {
// Kill long running processes // Kill long running processes
// Check if the priority is in a valid range // Check if the priority is in a valid range
if (!in_array($pid["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) if (!in_array($pid["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
$pid["priority"] = PRIORITY_MEDIUM; $pid["priority"] = PRIORITY_MEDIUM;
}
// Define the maximum durations // Define the maximum durations
$max_duration_defaults = array(PRIORITY_CRITICAL => 360, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 360); $max_duration_defaults = array(PRIORITY_CRITICAL => 360, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 360);
@ -418,7 +419,7 @@ function poller_too_much_workers() {
// Decrease the number of workers at higher load // Decrease the number of workers at higher load
$load = current_load(); $load = current_load();
if($load) { if ($load) {
$maxsysload = intval(Config::get("system", "maxloadavg", 50)); $maxsysload = intval(Config::get("system", "maxloadavg", 50));
$maxworkers = $queues; $maxworkers = $queues;

View file

@ -68,7 +68,7 @@ function post_update_1192() {
} }
// Set the "gcontact-id" in the item table and add a new gcontact entry if needed // Set the "gcontact-id" in the item table and add a new gcontact entry if needed
foreach($item_arr AS $item) { foreach ($item_arr AS $item) {
$gcontact_id = get_gcontact_id(array("url" => $item['author-link'], "network" => $item['network'], $gcontact_id = get_gcontact_id(array("url" => $item['author-link'], "network" => $item['network'],
"photo" => $item['author-avatar'], "name" => $item['author-name'])); "photo" => $item['author-avatar'], "name" => $item['author-name']));
q("UPDATE `item` SET `gcontact-id` = %d WHERE `uid` = %d AND `author-link` = '%s' AND `gcontact-id` = 0", q("UPDATE `item` SET `gcontact-id` = %d WHERE `uid` = %d AND `author-link` = '%s' AND `gcontact-id` = 0",
@ -204,7 +204,7 @@ function post_update_1198() {
} }
// Set the "gcontact-id" in the item table and add a new gcontact entry if needed // Set the "gcontact-id" in the item table and add a new gcontact entry if needed
foreach($item_arr AS $item) { foreach ($item_arr AS $item) {
$author_id = get_contact($item["author-link"], 0); $author_id = get_contact($item["author-link"], 0);
$owner_id = get_contact($item["owner-link"], 0); $owner_id = get_contact($item["owner-link"], 0);

View file

@ -8,8 +8,8 @@ function gender_selector($current="",$suffix="") {
call_hooks('gender_selector', $select); call_hooks('gender_selector', $select);
$o .= "<select name=\"gender$suffix\" id=\"gender-select$suffix\" size=\"1\" >"; $o .= "<select name=\"gender$suffix\" id=\"gender-select$suffix\" size=\"1\" >";
foreach($select as $selection) { foreach ($select as $selection) {
if($selection !== 'NOTRANSLATION') { if ($selection !== 'NOTRANSLATION') {
$selected = (($selection == $current) ? ' selected="selected" ' : ''); $selected = (($selection == $current) ? ' selected="selected" ' : '');
$o .= "<option value=\"$selection\" $selected >$selection</option>"; $o .= "<option value=\"$selection\" $selected >$selection</option>";
} }
@ -26,8 +26,8 @@ function sexpref_selector($current="",$suffix="") {
call_hooks('sexpref_selector', $select); call_hooks('sexpref_selector', $select);
$o .= "<select name=\"sexual$suffix\" id=\"sexual-select$suffix\" size=\"1\" >"; $o .= "<select name=\"sexual$suffix\" id=\"sexual-select$suffix\" size=\"1\" >";
foreach($select as $selection) { foreach ($select as $selection) {
if($selection !== 'NOTRANSLATION') { if ($selection !== 'NOTRANSLATION') {
$selected = (($selection == $current) ? ' selected="selected" ' : ''); $selected = (($selection == $current) ? ' selected="selected" ' : '');
$o .= "<option value=\"$selection\" $selected >$selection</option>"; $o .= "<option value=\"$selection\" $selected >$selection</option>";
} }
@ -44,8 +44,8 @@ function marital_selector($current="",$suffix="") {
call_hooks('marital_selector', $select); call_hooks('marital_selector', $select);
$o .= "<select name=\"marital\" id=\"marital-select\" size=\"1\" >"; $o .= "<select name=\"marital\" id=\"marital-select\" size=\"1\" >";
foreach($select as $selection) { foreach ($select as $selection) {
if($selection !== 'NOTRANSLATION') { if ($selection !== 'NOTRANSLATION') {
$selected = (($selection == $current) ? ' selected="selected" ' : ''); $selected = (($selection == $current) ? ' selected="selected" ' : '');
$o .= "<option value=\"$selection\" $selected >$selection</option>"; $o .= "<option value=\"$selection\" $selected >$selection</option>";
} }

View file

@ -28,9 +28,11 @@ function handle_pubsubhubbub($id) {
global $a; global $a;
$r = q("SELECT * FROM `push_subscriber` WHERE `id` = %d", intval($id)); $r = q("SELECT * FROM `push_subscriber` WHERE `id` = %d", intval($id));
if (!$r)
if (!dbm::is_result($r)) {
return; return;
else }
$rr = $r[0]; $rr = $r[0];
logger("Generate feed of user ".$rr['nickname']." to ".$rr['callback_url']." - last updated ".$rr['last_update'], LOGGER_DEBUG); logger("Generate feed of user ".$rr['nickname']." to ".$rr['callback_url']." - last updated ".$rr['last_update'], LOGGER_DEBUG);
@ -65,8 +67,10 @@ function handle_pubsubhubbub($id) {
// increment this until some upper limit where we give up // increment this until some upper limit where we give up
$new_push = intval($rr['push']) + 1; $new_push = intval($rr['push']) + 1;
if ($new_push > 30) // OK, let's give up if ($new_push > 30) {
// OK, let's give up
$new_push = 0; $new_push = 0;
}
q("UPDATE `push_subscriber` SET `push` = %d WHERE id = %d", q("UPDATE `push_subscriber` SET `push` = %d WHERE id = %d",
$new_push, $new_push,

View file

@ -49,23 +49,24 @@ function was_recently_delayed($cid) {
function add_to_queue($cid,$network,$msg,$batch = false) { function add_to_queue($cid,$network,$msg,$batch = false) {
$max_queue = get_config('system','max_contact_queue'); $max_queue = get_config('system','max_contact_queue');
if($max_queue < 1) if ($max_queue < 1) {
$max_queue = 500; $max_queue = 500;
}
$batch_queue = get_config('system','max_batch_queue'); $batch_queue = get_config('system','max_batch_queue');
if($batch_queue < 1) if ($batch_queue < 1) {
$batch_queue = 1000; $batch_queue = 1000;
}
$r = q("SELECT COUNT(*) AS `total` FROM `queue` INNER JOIN `contact` ON `queue`.`cid` = `contact`.`id` $r = q("SELECT COUNT(*) AS `total` FROM `queue` INNER JOIN `contact` ON `queue`.`cid` = `contact`.`id`
WHERE `queue`.`cid` = %d AND `contact`.`self` = 0 ", WHERE `queue`.`cid` = %d AND `contact`.`self` = 0 ",
intval($cid) intval($cid)
); );
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
if($batch && ($r[0]['total'] > $batch_queue)) { if ($batch && ($r[0]['total'] > $batch_queue)) {
logger('add_to_queue: too many queued items for batch server ' . $cid . ' - discarding message'); logger('add_to_queue: too many queued items for batch server ' . $cid . ' - discarding message');
return; return;
} } elseif ((! $batch) && ($r[0]['total'] > $max_queue)) {
elseif((! $batch) && ($r[0]['total'] > $max_queue)) {
logger('add_to_queue: too many queued items for contact ' . $cid . ' - discarding message'); logger('add_to_queue: too many queued items for contact ' . $cid . ' - discarding message');
return; return;
} }

View file

@ -83,7 +83,7 @@ function removetofu($message)
$start = 0; $start = 0;
while(($pos = strpos($message, '[quote', $start)) > 0) { while (($pos = strpos($message, '[quote', $start)) > 0) {
$quotes[$pos] = -1; $quotes[$pos] = -1;
$start = $pos + 7; $start = $pos + 7;
$startquotes++; $startquotes++;
@ -92,7 +92,7 @@ function removetofu($message)
$endquotes = 0; $endquotes = 0;
$start = 0; $start = 0;
while(($pos = strpos($message, '[/quote]', $start)) > 0) { while (($pos = strpos($message, '[/quote]', $start)) > 0) {
$start = $pos + 7; $start = $pos + 7;
$endquotes++; $endquotes++;
} }
@ -104,7 +104,7 @@ function removetofu($message)
$start = 0; $start = 0;
while(($pos = strpos($message, '[/quote]', $start)) > 0) { while (($pos = strpos($message, '[/quote]', $start)) > 0) {
$quotes[$pos] = 1; $quotes[$pos] = 1;
$start = $pos + 7; $start = $pos + 7;
} }

View file

@ -4,13 +4,13 @@ function auto_redir(App $a, $contact_nick) {
// prevent looping // prevent looping
if(x($_REQUEST,'redir') && intval($_REQUEST['redir'])) if (x($_REQUEST,'redir') && intval($_REQUEST['redir']))
return; return;
if((! $contact_nick) || ($contact_nick === $a->user['nickname'])) if ((! $contact_nick) || ($contact_nick === $a->user['nickname']))
return; return;
if(local_user()) { if (local_user()) {
// We need to find out if $contact_nick is a user on this hub, and if so, if I // We need to find out if $contact_nick is a user on this hub, and if so, if I
// am a contact of that user. However, that user may have other contacts with the // am a contact of that user. However, that user may have other contacts with the
@ -22,7 +22,7 @@ function auto_redir(App $a, $contact_nick) {
$baseurl = App::get_baseurl(); $baseurl = App::get_baseurl();
$domain_st = strpos($baseurl, "://"); $domain_st = strpos($baseurl, "://");
if($domain_st === false) if ($domain_st === false)
return; return;
$baseurl = substr($baseurl, $domain_st + 3); $baseurl = substr($baseurl, $domain_st + 3);
$nurl = normalise_link($baseurl); $nurl = normalise_link($baseurl);
@ -56,11 +56,11 @@ function auto_redir(App $a, $contact_nick) {
$dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']); $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
if($r[0]['duplex'] && $r[0]['issued-id']) { if ($r[0]['duplex'] && $r[0]['issued-id']) {
$orig_id = $r[0]['issued-id']; $orig_id = $r[0]['issued-id'];
$dfrn_id = '1:' . $orig_id; $dfrn_id = '1:' . $orig_id;
} }
if($r[0]['duplex'] && $r[0]['dfrn-id']) { if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
$orig_id = $r[0]['dfrn-id']; $orig_id = $r[0]['dfrn-id'];
$dfrn_id = '0:' . $orig_id; $dfrn_id = '0:' . $orig_id;
} }
@ -68,7 +68,7 @@ function auto_redir(App $a, $contact_nick) {
// ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
// that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
if(strlen($dfrn_id) < 3) if (strlen($dfrn_id) < 3)
return; return;
$sec = random_string(); $sec = random_string();

View file

@ -10,14 +10,13 @@ function get_salmon_key($uri,$keyhash) {
$arr = Probe::lrdd($uri); $arr = Probe::lrdd($uri);
if(is_array($arr)) { if (is_array($arr)) {
foreach($arr as $a) { foreach ($arr as $a) {
if($a['@attributes']['rel'] === 'magic-public-key') { if ($a['@attributes']['rel'] === 'magic-public-key') {
$ret[] = $a['@attributes']['href']; $ret[] = $a['@attributes']['href'];
} }
} }
} } else {
else {
return ''; return '';
} }
@ -69,11 +68,12 @@ function slapper($owner,$url,$slap) {
// does contact have a salmon endpoint? // does contact have a salmon endpoint?
if(! strlen($url)) if (! strlen($url)) {
return; return;
}
if(! $owner['sprvkey']) { if (! $owner['sprvkey']) {
logger(sprintf("user '%s' (%d) does not have a salmon private key. Send failed.", logger(sprintf("user '%s' (%d) does not have a salmon private key. Send failed.",
$owner['username'],$owner['uid'])); $owner['username'],$owner['uid']));
return; return;
@ -120,7 +120,7 @@ function slapper($owner,$url,$slap) {
// check for success, e.g. 2xx // check for success, e.g. 2xx
if($return_code > 299) { if ($return_code > 299) {
logger('compliant salmon failed. Falling back to status.net hack2'); logger('compliant salmon failed. Falling back to status.net hack2');
@ -144,7 +144,7 @@ function slapper($owner,$url,$slap) {
$return_code = $a->get_curl_code(); $return_code = $a->get_curl_code();
if($return_code > 299) { if ($return_code > 299) {
logger('compliant salmon failed. Falling back to status.net hack3'); logger('compliant salmon failed. Falling back to status.net hack3');
@ -169,10 +169,12 @@ function slapper($owner,$url,$slap) {
} }
} }
logger('slapper for '.$url.' returned ' . $return_code); logger('slapper for '.$url.' returned ' . $return_code);
if(! $return_code) if (! $return_code) {
return(-1); return(-1);
if(($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after'))) }
if (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after'))) {
return(-1); return(-1);
}
return ((($return_code >= 200) && ($return_code < 300)) ? 0 : 1); return ((($return_code >= 200) && ($return_code < 300)) ? 0 : 1);
} }

View file

@ -54,30 +54,34 @@ function authenticate_success($user_record, $login_initial = false, $interactive
$a->user = $user_record; $a->user = $user_record;
if($interactive) { if ($interactive) {
/// @TODO Comparison of strings this way may lead to bugs/incompatiblities
if ($a->user['login_date'] <= NULL_DATE) { if ($a->user['login_date'] <= NULL_DATE) {
$_SESSION['return_url'] = 'profile_photo/new'; $_SESSION['return_url'] = 'profile_photo/new';
$a->module = 'profile_photo'; $a->module = 'profile_photo';
info( t("Welcome ") . $a->user['username'] . EOL); info( t("Welcome ") . $a->user['username'] . EOL);
info( t('Please upload a profile photo.') . EOL); info( t('Please upload a profile photo.') . EOL);
} } else {
else
info( t("Welcome back ") . $a->user['username'] . EOL); info( t("Welcome back ") . $a->user['username'] . EOL);
} }
}
$member_since = strtotime($a->user['register_date']); $member_since = strtotime($a->user['register_date']);
if(time() < ($member_since + ( 60 * 60 * 24 * 14)))
if (time() < ($member_since + ( 60 * 60 * 24 * 14))) {
$_SESSION['new_member'] = true; $_SESSION['new_member'] = true;
else } else {
$_SESSION['new_member'] = false; $_SESSION['new_member'] = false;
if(strlen($a->user['timezone'])) { }
if (strlen($a->user['timezone'])) {
date_default_timezone_set($a->user['timezone']); date_default_timezone_set($a->user['timezone']);
$a->timezone = $a->user['timezone']; $a->timezone = $a->user['timezone'];
} }
$master_record = $a->user; $master_record = $a->user;
if((x($_SESSION,'submanage')) && intval($_SESSION['submanage'])) { if ((x($_SESSION,'submanage')) && intval($_SESSION['submanage'])) {
$r = q("select * from user where uid = %d limit 1", $r = q("select * from user where uid = %d limit 1",
intval($_SESSION['submanage']) intval($_SESSION['submanage'])
); );
@ -102,9 +106,9 @@ function authenticate_success($user_record, $login_initial = false, $interactive
if (dbm::is_result($r)) if (dbm::is_result($r))
$a->identities = array_merge($a->identities,$r); $a->identities = array_merge($a->identities,$r);
if($login_initial) if ($login_initial)
logger('auth_identities: ' . print_r($a->identities,true), LOGGER_DEBUG); logger('auth_identities: ' . print_r($a->identities,true), LOGGER_DEBUG);
if($login_refresh) if ($login_refresh)
logger('auth_identities refresh: ' . print_r($a->identities,true), LOGGER_DEBUG); logger('auth_identities refresh: ' . print_r($a->identities,true), LOGGER_DEBUG);
$r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1", $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
@ -117,7 +121,7 @@ function authenticate_success($user_record, $login_initial = false, $interactive
header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] .'"'); header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] .'"');
if($login_initial || $login_refresh) { if ($login_initial || $login_refresh) {
q("UPDATE `user` SET `login_date` = '%s' WHERE `uid` = %d", q("UPDATE `user` SET `login_date` = '%s' WHERE `uid` = %d",
dbesc(datetime_convert()), dbesc(datetime_convert()),
@ -247,7 +251,7 @@ function permissions_sql($owner_id,$remote_verified = false,$groups = null) {
* Profile owner - everything is visible * Profile owner - everything is visible
*/ */
if(($local_user) && ($local_user == $owner_id)) { if (($local_user) && ($local_user == $owner_id)) {
$sql = ''; $sql = '';
} }
@ -259,9 +263,9 @@ function permissions_sql($owner_id,$remote_verified = false,$groups = null) {
* done this and passed the groups into this function. * done this and passed the groups into this function.
*/ */
elseif($remote_user) { elseif ($remote_user) {
if(! $remote_verified) { if (! $remote_verified) {
$r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1", $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
intval($remote_user), intval($remote_user),
intval($owner_id) intval($owner_id)
@ -271,12 +275,12 @@ function permissions_sql($owner_id,$remote_verified = false,$groups = null) {
$groups = init_groups_visitor($remote_user); $groups = init_groups_visitor($remote_user);
} }
} }
if($remote_verified) { if ($remote_verified) {
$gs = '<<>>'; // should be impossible to match $gs = '<<>>'; // should be impossible to match
if(is_array($groups) && count($groups)) { if (is_array($groups) && count($groups)) {
foreach($groups as $g) foreach ($groups as $g)
$gs .= '|<' . intval($g) . '>'; $gs .= '|<' . intval($g) . '>';
} }
@ -329,7 +333,7 @@ function item_permissions_sql($owner_id,$remote_verified = false,$groups = null)
* Profile owner - everything is visible * Profile owner - everything is visible
*/ */
if($local_user && ($local_user == $owner_id)) { if ($local_user && ($local_user == $owner_id)) {
$sql = ''; $sql = '';
} }
@ -341,9 +345,9 @@ function item_permissions_sql($owner_id,$remote_verified = false,$groups = null)
* done this and passed the groups into this function. * done this and passed the groups into this function.
*/ */
elseif($remote_user) { elseif ($remote_user) {
if(! $remote_verified) { if (! $remote_verified) {
$r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1", $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
intval($remote_user), intval($remote_user),
intval($owner_id) intval($owner_id)
@ -353,14 +357,15 @@ function item_permissions_sql($owner_id,$remote_verified = false,$groups = null)
$groups = init_groups_visitor($remote_user); $groups = init_groups_visitor($remote_user);
} }
} }
if($remote_verified) { if ($remote_verified) {
$gs = '<<>>'; // should be impossible to match $gs = '<<>>'; // should be impossible to match
if(is_array($groups) && count($groups)) { if (is_array($groups) && count($groups)) {
foreach($groups as $g) foreach ($groups as $g) {
$gs .= '|<' . intval($g) . '>'; $gs .= '|<' . intval($g) . '>';
} }
}
$sql = sprintf( $sql = sprintf(
/*" AND ( private = 0 OR ( private in (1,2) AND wall = 1 AND ( allow_cid = '' OR allow_cid REGEXP '<%d>' ) /*" AND ( private = 0 OR ( private in (1,2) AND wall = 1 AND ( allow_cid = '' OR allow_cid REGEXP '<%d>' )
@ -452,7 +457,7 @@ function check_form_security_token_ForbiddenOnErr($typename = '', $formname = 'f
// DFRN contact. They are *not* neccessarily unique across the entire site. // DFRN contact. They are *not* neccessarily unique across the entire site.
if(! function_exists('init_groups_visitor')) { if (! function_exists('init_groups_visitor')) {
function init_groups_visitor($contact_id) { function init_groups_visitor($contact_id) {
$groups = array(); $groups = array();
$r = q("SELECT `gid` FROM `group_member` $r = q("SELECT `gid` FROM `group_member`
@ -460,7 +465,7 @@ function init_groups_visitor($contact_id) {
intval($contact_id) intval($contact_id)
); );
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach($r as $rr) foreach ($r as $rr)
$groups[] = $rr['gid']; $groups[] = $rr['gid'];
} }
return $groups; return $groups;

View file

@ -49,8 +49,8 @@ function poco_load($cid, $uid = 0, $zcid = 0, $url = null) {
function poco_load_worker($cid, $uid, $zcid, $url) { function poco_load_worker($cid, $uid, $zcid, $url) {
$a = get_app(); $a = get_app();
if($cid) { if ($cid) {
if((! $url) || (! $uid)) { if ((! $url) || (! $uid)) {
$r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1", $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
intval($cid) intval($cid)
); );
@ -59,11 +59,11 @@ function poco_load_worker($cid, $uid, $zcid, $url) {
$uid = $r[0]['uid']; $uid = $r[0]['uid'];
} }
} }
if(! $uid) if (! $uid)
return; return;
} }
if(! $url) if (! $url)
return; return;
$url = $url . (($uid) ? '/@me/@all?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation' : '?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation') ; $url = $url . (($uid) ? '/@me/@all?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation' : '?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation') ;
@ -76,18 +76,18 @@ function poco_load_worker($cid, $uid, $zcid, $url) {
logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG); logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
if(($a->get_curl_code() > 299) || (! $s)) if (($a->get_curl_code() > 299) || (! $s))
return; return;
$j = json_decode($s); $j = json_decode($s);
logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA); logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
if(! isset($j->entry)) if (! isset($j->entry))
return; return;
$total = 0; $total = 0;
foreach($j->entry as $entry) { foreach ($j->entry as $entry) {
$total ++; $total ++;
$profile_url = ''; $profile_url = '';
@ -151,7 +151,7 @@ function poco_load_worker($cid, $uid, $zcid, $url) {
} }
if (isset($entry->tags)) { if (isset($entry->tags)) {
foreach($entry->tags as $tag) { foreach ($entry->tags as $tag) {
$keywords = implode(", ", $tag); $keywords = implode(", ", $tag);
} }
} }
@ -354,7 +354,7 @@ function poco_check($profile_url, $name, $network, $profile_photo, $about, $loca
$gcid = update_gcontact($gcontact); $gcid = update_gcontact($gcontact);
if(!$gcid) if (!$gcid)
return $gcid; return $gcid;
$r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1", $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
@ -1091,10 +1091,10 @@ function poco_check_server($server_url, $network = "", $force = false) {
} }
$lines = explode("\n",$serverret["header"]); $lines = explode("\n",$serverret["header"]);
if(count($lines)) { if (count($lines)) {
foreach($lines as $line) { foreach ($lines as $line) {
$line = trim($line); $line = trim($line);
if(stristr($line,'X-Diaspora-Version:')) { if (stristr($line,'X-Diaspora-Version:')) {
$platform = "Diaspora"; $platform = "Diaspora";
$version = trim(str_replace("X-Diaspora-Version:", "", $line)); $version = trim(str_replace("X-Diaspora-Version:", "", $line));
$version = trim(str_replace("x-diaspora-version:", "", $version)); $version = trim(str_replace("x-diaspora-version:", "", $version));
@ -1104,7 +1104,7 @@ function poco_check_server($server_url, $network = "", $force = false) {
$last_contact = datetime_convert(); $last_contact = datetime_convert();
} }
if(stristr($line,'Server: Mastodon')) { if (stristr($line,'Server: Mastodon')) {
$platform = "Mastodon"; $platform = "Mastodon";
$network = NETWORK_OSTATUS; $network = NETWORK_OSTATUS;
// Mastodon doesn't reveal version numbers // Mastodon doesn't reveal version numbers
@ -1383,7 +1383,7 @@ function count_common_friends($uid,$cid) {
function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) { function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
if($shuffle) if ($shuffle)
$sql_extra = " order by rand() "; $sql_extra = " order by rand() ";
else else
$sql_extra = " order by `gcontact`.`name` asc "; $sql_extra = " order by `gcontact`.`name` asc ";
@ -1428,7 +1428,7 @@ function count_common_friends_zcid($uid,$zcid) {
function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) { function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
if($shuffle) if ($shuffle)
$sql_extra = " order by rand() "; $sql_extra = " order by rand() ";
else else
$sql_extra = " order by `gcontact`.`name` asc "; $sql_extra = " order by `gcontact`.`name` asc ";
@ -1611,7 +1611,7 @@ function update_suggestions() {
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach ($r as $rr) { foreach ($r as $rr) {
$base = substr($rr['poco'],0,strrpos($rr['poco'],'/')); $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
if(! in_array($base,$done)) if (! in_array($base,$done))
poco_load(0,0,0,$base); poco_load(0,0,0,$base);
} }
} }
@ -1649,7 +1649,7 @@ function poco_discover_federation() {
if ($last) { if ($last) {
$next = $last + (24 * 60 * 60); $next = $last + (24 * 60 * 60);
if($next > time()) if ($next > time())
return; return;
} }
@ -1664,20 +1664,22 @@ function poco_discover_federation() {
} }
} }
// Currently disabled, since the service isn't available anymore. /*
// It is not removed since I hope that there will be a successor. * Currently disabled, since the service isn't available anymore.
// Discover GNU Social Servers. * It is not removed since I hope that there will be a successor.
//if (!get_config('system','ostatus_disabled')) { * Discover GNU Social Servers.
// $serverdata = "http://gstools.org/api/get_open_instances/"; if (!get_config('system','ostatus_disabled')) {
$serverdata = "http://gstools.org/api/get_open_instances/";
// $result = z_fetch_url($serverdata); $result = z_fetch_url($serverdata);
// if ($result["success"]) { if ($result["success"]) {
// $servers = json_decode($result["body"]); $servers = json_decode($result["body"]);
// foreach($servers->data AS $server) foreach($servers->data AS $server)
// poco_check_server($server->instance_address); poco_check_server($server->instance_address);
// } }
//} }
*/
set_config('poco','last_federation_discovery', time()); set_config('poco','last_federation_discovery', time());
} }
@ -1786,7 +1788,7 @@ function poco_discover_server_users($data, $server) {
foreach ($data->entry AS $entry) { foreach ($data->entry AS $entry) {
$username = ""; $username = "";
if (isset($entry->urls)) { if (isset($entry->urls)) {
foreach($entry->urls as $url) foreach ($entry->urls as $url)
if ($url->type == 'profile') { if ($url->type == 'profile') {
$profile_url = $url->value; $profile_url = $url->value;
$urlparts = parse_url($profile_url); $urlparts = parse_url($profile_url);
@ -1830,7 +1832,7 @@ function poco_discover_server($data, $default_generation = 0) {
$name = $entry->displayName; $name = $entry->displayName;
if (isset($entry->urls)) { if (isset($entry->urls)) {
foreach($entry->urls as $url) { foreach ($entry->urls as $url) {
if ($url->type == 'profile') { if ($url->type == 'profile') {
$profile_url = $url->value; $profile_url = $url->value;
continue; continue;
@ -1855,31 +1857,31 @@ function poco_discover_server($data, $default_generation = 0) {
$updated = date("Y-m-d H:i:s", strtotime($entry->updated)); $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
} }
if(isset($entry->network)) { if (isset($entry->network)) {
$network = $entry->network; $network = $entry->network;
} }
if(isset($entry->currentLocation)) { if (isset($entry->currentLocation)) {
$location = $entry->currentLocation; $location = $entry->currentLocation;
} }
if(isset($entry->aboutMe)) { if (isset($entry->aboutMe)) {
$about = html2bbcode($entry->aboutMe); $about = html2bbcode($entry->aboutMe);
} }
if(isset($entry->gender)) { if (isset($entry->gender)) {
$gender = $entry->gender; $gender = $entry->gender;
} }
if(isset($entry->generation) AND ($entry->generation > 0)) { if (isset($entry->generation) AND ($entry->generation > 0)) {
$generation = ++$entry->generation; $generation = ++$entry->generation;
} }
if(isset($entry->contactType) AND ($entry->contactType >= 0)) { if (isset($entry->contactType) AND ($entry->contactType >= 0)) {
$contact_type = $entry->contactType; $contact_type = $entry->contactType;
} }
if(isset($entry->tags)) { if (isset($entry->tags)) {
foreach ($entry->tags as $tag) { foreach ($entry->tags as $tag) {
$keywords = implode(", ", $tag); $keywords = implode(", ", $tag);
} }

View file

@ -55,10 +55,10 @@ function create_tags_from_item($itemid) {
if (substr(trim($tag), 0, 1) == "#") { if (substr(trim($tag), 0, 1) == "#") {
// try to ignore #039 or #1 or anything like that // try to ignore #039 or #1 or anything like that
if(ctype_digit(substr(trim($tag),1))) if (ctype_digit(substr(trim($tag),1)))
continue; continue;
// try to ignore html hex escapes, e.g. #x2317 // try to ignore html hex escapes, e.g. #x2317
if((substr(trim($tag),1,1) == 'x' || substr(trim($tag),1,1) == 'X') && ctype_digit(substr(trim($tag),2))) if ((substr(trim($tag),1,1) == 'x' || substr(trim($tag),1,1) == 'X') && ctype_digit(substr(trim($tag),2)))
continue; continue;
$type = TERM_HASHTAG; $type = TERM_HASHTAG;
$term = substr($tag, 1); $term = substr($tag, 1);
@ -104,10 +104,11 @@ function create_tags_from_item($itemid) {
function create_tags_from_itemuri($itemuri, $uid) { function create_tags_from_itemuri($itemuri, $uid) {
$messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid)); $messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid));
if(count($messages)) { if (count($messages)) {
foreach ($messages as $message) foreach ($messages as $message) {
create_tags_from_item($message["id"]); create_tags_from_item($message["id"]);
} }
}
} }
function update_items() { function update_items() {

View file

@ -53,8 +53,9 @@ class Template implements ITemplateEngine {
private function _get_var($name, $retNoKey = false) { private function _get_var($name, $retNoKey = false) {
$keys = array_map('trim', explode(".", $name)); $keys = array_map('trim', explode(".", $name));
if ($retNoKey && !array_key_exists($keys[0], $this->r)) if ($retNoKey && !array_key_exists($keys[0], $this->r)) {
return KEY_NOT_EXISTS; return KEY_NOT_EXISTS;
}
$val = $this->r; $val = $this->r;
foreach ($keys as $k) { foreach ($keys as $k) {
$val = (isset($val[$k]) ? $val[$k] : null); $val = (isset($val[$k]) ? $val[$k] : null);
@ -69,18 +70,20 @@ class Template implements ITemplateEngine {
* {{ if <$var>==<val|$var> }}...[{{ else }} ...]{{ endif }} * {{ if <$var>==<val|$var> }}...[{{ else }} ...]{{ endif }}
* {{ if <$var>!=<val|$var> }}...[{{ else }} ...]{{ endif }} * {{ if <$var>!=<val|$var> }}...[{{ else }} ...]{{ endif }}
*/ */
private function _replcb_if($args) { private function _replcb_if ($args) {
if (strpos($args[2], "==") > 0) { if (strpos($args[2], "==") > 0) {
list($a, $b) = array_map("trim", explode("==", $args[2])); list($a, $b) = array_map("trim", explode("==", $args[2]));
$a = $this->_get_var($a); $a = $this->_get_var($a);
if ($b[0] == "$") if ($b[0] == "$") {
$b = $this->_get_var($b); $b = $this->_get_var($b);
}
$val = ($a == $b); $val = ($a == $b);
} else if (strpos($args[2], "!=") > 0) { } elseif (strpos($args[2], "!=") > 0) {
list($a, $b) = array_map("trim", explode("!=", $args[2])); list($a, $b) = array_map("trim", explode("!=", $args[2]));
$a = $this->_get_var($a); $a = $this->_get_var($a);
if ($b[0] == "$") if ($b[0] == "$") {
$b = $this->_get_var($b); $b = $this->_get_var($b);
}
$val = ($a != $b); $val = ($a != $b);
} else { } else {
$val = $this->_get_var($args[2]); $val = $this->_get_var($args[2]);
@ -95,7 +98,7 @@ class Template implements ITemplateEngine {
* {{ for <$var> as $name }}...{{ endfor }} * {{ for <$var> as $name }}...{{ endfor }}
* {{ for <$var> as $key=>$name }}...{{ endfor }} * {{ for <$var> as $key=>$name }}...{{ endfor }}
*/ */
private function _replcb_for($args) { private function _replcb_for ($args) {
$m = array_map('trim', explode(" as ", $args[2])); $m = array_map('trim', explode(" as ", $args[2]));
$x = explode("=>", $m[1]); $x = explode("=>", $m[1]);
if (count($x) == 1) { if (count($x) == 1) {
@ -109,14 +112,16 @@ class Template implements ITemplateEngine {
//$vals = $this->r[$m[0]]; //$vals = $this->r[$m[0]];
$vals = $this->_get_var($m[0]); $vals = $this->_get_var($m[0]);
$ret = ""; $ret = "";
if (!is_array($vals)) if (!is_array($vals)) {
return $ret; return $ret;
}
foreach ($vals as $k => $v) { foreach ($vals as $k => $v) {
$this->_push_stack(); $this->_push_stack();
$r = $this->r; $r = $this->r;
$r[$varname] = $v; $r[$varname] = $v;
if ($keyname != '') if ($keyname != '') {
$r[$keyname] = (($k === 0) ? '0' : $k); $r[$keyname] = (($k === 0) ? '0' : $k);
}
$ret .= $this->replace($args[3], $r); $ret .= $this->replace($args[3], $r);
$this->_pop_stack(); $this->_pop_stack();
} }
@ -136,8 +141,9 @@ class Template implements ITemplateEngine {
$newctx = null; $newctx = null;
} }
if ($tplfile[0] == "$") if ($tplfile[0] == "$") {
$tplfile = $this->_get_var($tplfile); $tplfile = $this->_get_var($tplfile);
}
$this->_push_stack(); $this->_push_stack();
$r = $this->r; $r = $this->r;

View file

@ -7,7 +7,7 @@ require_once("include/map.php");
require_once("mod/proxy.php"); require_once("mod/proxy.php");
if(! function_exists('replace_macros')) { if (! function_exists('replace_macros')) {
/** /**
* This is our template processor * This is our template processor
* *
@ -45,7 +45,7 @@ function replace_macros($s,$r) {
define('RANDOM_STRING_HEX', 0x00 ); define('RANDOM_STRING_HEX', 0x00 );
define('RANDOM_STRING_TEXT', 0x01 ); define('RANDOM_STRING_TEXT', 0x01 );
if(! function_exists('random_string')) { if (! function_exists('random_string')) {
function random_string($size = 64,$type = RANDOM_STRING_HEX) { function random_string($size = 64,$type = RANDOM_STRING_HEX) {
// generate a bit of entropy and run it through the whirlpool // 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 = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
@ -53,7 +53,7 @@ function random_string($size = 64,$type = RANDOM_STRING_HEX) {
return(substr($s,0,$size)); return(substr($s,0,$size));
}} }}
if(! function_exists('notags')) { if (! function_exists('notags')) {
/** /**
* This is our primary input filter. * This is our primary input filter.
* *
@ -81,7 +81,7 @@ function notags($string) {
if(! function_exists('escape_tags')) { if (! function_exists('escape_tags')) {
/** /**
* use this on "body" or "content" input where angle chars shouldn't be removed, * use this on "body" or "content" input where angle chars shouldn't be removed,
* and allow them to be safely displayed. * and allow them to be safely displayed.
@ -97,7 +97,7 @@ function escape_tags($string) {
// generate a string that's random, but usually pronounceable. // generate a string that's random, but usually pronounceable.
// used to generate initial passwords // used to generate initial passwords
if(! function_exists('autoname')) { if (! function_exists('autoname')) {
/** /**
* generate a string that's random, but usually pronounceable. * generate a string that's random, but usually pronounceable.
* used to generate initial passwords * used to generate initial passwords
@ -106,11 +106,11 @@ if(! function_exists('autoname')) {
*/ */
function autoname($len) { function autoname($len) {
if($len <= 0) if ($len <= 0)
return ''; return '';
$vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u'); $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'; $vowels[] = 'y';
$cons = array( $cons = array(
@ -143,7 +143,7 @@ function autoname($len) {
'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh'); 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
$start = mt_rand(0,2); $start = mt_rand(0,2);
if($start == 0) if ($start == 0)
$table = $vowels; $table = $vowels;
else else
$table = $cons; $table = $cons;
@ -154,7 +154,7 @@ function autoname($len) {
$r = mt_rand(0,count($table) - 1); $r = mt_rand(0,count($table) - 1);
$word .= $table[$r]; $word .= $table[$r];
if($table == $vowels) if ($table == $vowels)
$table = array_merge($cons,$midcons); $table = array_merge($cons,$midcons);
else else
$table = $vowels; $table = $vowels;
@ -163,13 +163,13 @@ function autoname($len) {
$word = substr($word,0,$len); $word = substr($word,0,$len);
foreach($noend as $noe) { foreach ($noend as $noe) {
if((strlen($word) > 2) && (substr($word,-2) == $noe)) { if ((strlen($word) > 2) && (substr($word,-2) == $noe)) {
$word = substr($word,0,-1); $word = substr($word,0,-1);
break; break;
} }
} }
if(substr($word,-1) == 'q') if (substr($word,-1) == 'q')
$word = substr($word,0,-1); $word = substr($word,0,-1);
return $word; return $word;
}} }}
@ -178,7 +178,7 @@ function autoname($len) {
// escape text ($str) for XML transport // escape text ($str) for XML transport
// returns escaped text. // returns escaped text.
if(! function_exists('xmlify')) { if (! function_exists('xmlify')) {
/** /**
* escape text ($str) for XML transport * escape text ($str) for XML transport
* @param string $str * @param string $str
@ -188,7 +188,7 @@ function xmlify($str) {
/* $buffer = ''; /* $buffer = '';
$len = mb_strlen($str); $len = mb_strlen($str);
for($x = 0; $x < $len; $x ++) { for ($x = 0; $x < $len; $x ++) {
$char = mb_substr($str,$x,1); $char = mb_substr($str,$x,1);
switch( $char ) { switch( $char ) {
@ -231,7 +231,7 @@ function xmlify($str) {
return($buffer); return($buffer);
}} }}
if(! function_exists('unxmlify')) { if (! function_exists('unxmlify')) {
/** /**
* undo an xmlify * undo an xmlify
* @param string $s xml escaped text * @param string $s xml escaped text
@ -250,17 +250,17 @@ function unxmlify($s) {
return $ret; return $ret;
}} }}
if(! function_exists('hex2bin')) { if (! function_exists('hex2bin')) {
/** /**
* convenience wrapper, reverse the operation "bin2hex" * convenience wrapper, reverse the operation "bin2hex"
* @param string $s * @param string $s
* @return number * @return number
*/ */
function hex2bin($s) { function hex2bin($s) {
if(! (is_string($s) && strlen($s))) if (! (is_string($s) && strlen($s)))
return ''; return '';
if(! ctype_xdigit($s)) { if (! ctype_xdigit($s)) {
return($s); return($s);
} }
@ -353,7 +353,7 @@ function paginate_data(App $a, $count = null) {
return $data; return $data;
} }
if(! function_exists('paginate')) { if (! function_exists('paginate')) {
/** /**
* Automatic pagination. * Automatic pagination.
* *
@ -377,7 +377,7 @@ function paginate(App $a) {
}} }}
if(! function_exists('alt_pager')) { if (! function_exists('alt_pager')) {
/** /**
* Alternative pager * Alternative pager
* @param App $a App instance * @param App $a App instance
@ -392,7 +392,7 @@ function alt_pager(App $a, $i) {
}} }}
if(! function_exists('scroll_loader')) { if (! function_exists('scroll_loader')) {
/** /**
* Loader for infinite scrolling * Loader for infinite scrolling
* @return string html for loader * @return string html for loader
@ -405,7 +405,7 @@ function scroll_loader() {
)); ));
}} }}
if(! function_exists('expand_acl')) { if (! function_exists('expand_acl')) {
/** /**
* Turn user/group ACLs stored as angle bracketed text into arrays * Turn user/group ACLs stored as angle bracketed text into arrays
* *
@ -417,31 +417,32 @@ function expand_acl($s) {
// e.g. "<1><2><3>" => array(1,2,3); // e.g. "<1><2><3>" => array(1,2,3);
$ret = array(); $ret = array();
if(strlen($s)) { if (strlen($s)) {
$t = str_replace('<','',$s); $t = str_replace('<','',$s);
$a = explode('>',$t); $a = explode('>',$t);
foreach($a as $aa) { foreach ($a as $aa) {
if(intval($aa)) if (intval($aa)) {
$ret[] = intval($aa); $ret[] = intval($aa);
} }
} }
}
return $ret; return $ret;
}} }}
if(! function_exists('sanitise_acl')) { if (! function_exists('sanitise_acl')) {
/** /**
* Wrap ACL elements in angle brackets for storage * Wrap ACL elements in angle brackets for storage
* @param string $item * @param string $item
*/ */
function sanitise_acl(&$item) { function sanitise_acl(&$item) {
if(intval($item)) if (intval($item))
$item = '<' . intval(notags(trim($item))) . '>'; $item = '<' . intval(notags(trim($item))) . '>';
else else
unset($item); unset($item);
}} }}
if(! function_exists('perms2str')) { if (! function_exists('perms2str')) {
/** /**
* Convert an ACL array to a storable string * Convert an ACL array to a storable string
* *
@ -453,12 +454,12 @@ if(! function_exists('perms2str')) {
*/ */
function perms2str($p) { function perms2str($p) {
$ret = ''; $ret = '';
if(is_array($p)) if (is_array($p))
$tmp = $p; $tmp = $p;
else else
$tmp = explode(',',$p); $tmp = explode(',',$p);
if(is_array($tmp)) { if (is_array($tmp)) {
array_walk($tmp,'sanitise_acl'); array_walk($tmp,'sanitise_acl');
$ret = implode('',$tmp); $ret = implode('',$tmp);
} }
@ -466,7 +467,7 @@ function perms2str($p) {
}} }}
if(! function_exists('item_new_uri')) { if (! function_exists('item_new_uri')) {
/** /**
* generate a guaranteed unique (for this domain) item ID for ATOM * generate a guaranteed unique (for this domain) item ID for ATOM
* safe from birthday paradox * safe from birthday paradox
@ -493,14 +494,14 @@ function item_new_uri($hostname,$uid, $guid = "") {
dbesc($uri)); dbesc($uri));
if (dbm::is_result($r)) if (dbm::is_result($r))
$dups = true; $dups = true;
} while($dups == true); } while ($dups == true);
return $uri; return $uri;
}} }}
// Generate a guaranteed unique photo ID. // Generate a guaranteed unique photo ID.
// safe from birthday paradox // safe from birthday paradox
if(! function_exists('photo_new_resource')) { if (! function_exists('photo_new_resource')) {
/** /**
* Generate a guaranteed unique photo ID. * Generate a guaranteed unique photo ID.
* safe from birthday paradox * safe from birthday paradox
@ -517,12 +518,12 @@ function photo_new_resource() {
); );
if (dbm::is_result($r)) if (dbm::is_result($r))
$found = true; $found = true;
} while($found == true); } while ($found == true);
return $resource; return $resource;
}} }}
if(! function_exists('load_view_file')) { if (! function_exists('load_view_file')) {
/** /**
* @deprecated * @deprecated
* wrapper to load a view template, checking for alternate * wrapper to load a view template, checking for alternate
@ -535,11 +536,11 @@ if(! function_exists('load_view_file')) {
*/ */
function load_view_file($s) { function load_view_file($s) {
global $lang, $a; global $lang, $a;
if(! isset($lang)) if (! isset($lang))
$lang = 'en'; $lang = 'en';
$b = basename($s); $b = basename($s);
$d = dirname($s); $d = dirname($s);
if(file_exists("$d/$lang/$b")) { if (file_exists("$d/$lang/$b")) {
$stamp1 = microtime(true); $stamp1 = microtime(true);
$content = file_get_contents("$d/$lang/$b"); $content = file_get_contents("$d/$lang/$b");
$a->save_timestamp($stamp1, "file"); $a->save_timestamp($stamp1, "file");
@ -548,7 +549,7 @@ function load_view_file($s) {
$theme = current_theme(); $theme = current_theme();
if(file_exists("$d/theme/$theme/$b")) { if (file_exists("$d/theme/$theme/$b")) {
$stamp1 = microtime(true); $stamp1 = microtime(true);
$content = file_get_contents("$d/theme/$theme/$b"); $content = file_get_contents("$d/theme/$theme/$b");
$a->save_timestamp($stamp1, "file"); $a->save_timestamp($stamp1, "file");
@ -561,7 +562,7 @@ function load_view_file($s) {
return $content; return $content;
}} }}
if(! function_exists('get_intltext_template')) { if (! function_exists('get_intltext_template')) {
/** /**
* load a view template, checking for alternate * load a view template, checking for alternate
* languages before falling back to the default * languages before falling back to the default
@ -575,18 +576,18 @@ function get_intltext_template($s) {
$a = get_app(); $a = get_app();
$engine = ''; $engine = '';
if($a->theme['template_engine'] === 'smarty3') if ($a->theme['template_engine'] === 'smarty3')
$engine = "/smarty3"; $engine = "/smarty3";
if(! isset($lang)) if (! isset($lang))
$lang = 'en'; $lang = 'en';
if(file_exists("view/lang/$lang$engine/$s")) { if (file_exists("view/lang/$lang$engine/$s")) {
$stamp1 = microtime(true); $stamp1 = microtime(true);
$content = file_get_contents("view/lang/$lang$engine/$s"); $content = file_get_contents("view/lang/$lang$engine/$s");
$a->save_timestamp($stamp1, "file"); $a->save_timestamp($stamp1, "file");
return $content; return $content;
} elseif(file_exists("view/lang/en$engine/$s")) { } elseif (file_exists("view/lang/en$engine/$s")) {
$stamp1 = microtime(true); $stamp1 = microtime(true);
$content = file_get_contents("view/lang/en$engine/$s"); $content = file_get_contents("view/lang/en$engine/$s");
$a->save_timestamp($stamp1, "file"); $a->save_timestamp($stamp1, "file");
@ -599,7 +600,7 @@ function get_intltext_template($s) {
} }
}} }}
if(! function_exists('get_markup_template')) { if (! function_exists('get_markup_template')) {
/** /**
* load template $s * load template $s
* *
@ -623,7 +624,7 @@ function get_markup_template($s, $root = '') {
return $template; return $template;
}} }}
if(! function_exists("get_template_file")) { if (! function_exists("get_template_file")) {
/** /**
* *
* @param App $a * @param App $a
@ -635,10 +636,10 @@ function get_template_file($a, $filename, $root = '') {
$theme = current_theme(); $theme = current_theme();
// Make sure $root ends with a slash / // Make sure $root ends with a slash /
if($root !== '' && $root[strlen($root)-1] !== '/') if ($root !== '' && $root[strlen($root)-1] !== '/')
$root = $root . '/'; $root = $root . '/';
if(file_exists("{$root}view/theme/$theme/$filename")) if (file_exists("{$root}view/theme/$theme/$filename"))
$template_file = "{$root}view/theme/$theme/$filename"; $template_file = "{$root}view/theme/$theme/$filename";
elseif (x($a->theme_info,"extends") && file_exists("{$root}view/theme/{$a->theme_info["extends"]}/$filename")) elseif (x($a->theme_info,"extends") && file_exists("{$root}view/theme/{$a->theme_info["extends"]}/$filename"))
$template_file = "{$root}view/theme/{$a->theme_info["extends"]}/$filename"; $template_file = "{$root}view/theme/{$a->theme_info["extends"]}/$filename";
@ -656,7 +657,7 @@ function get_template_file($a, $filename, $root = '') {
if(! function_exists('attribute_contains')) { if (! function_exists('attribute_contains')) {
/** /**
* for html,xml parsing - let's say you've got * for html,xml parsing - let's say you've got
* an attribute foobar="class1 class2 class3" * an attribute foobar="class1 class2 class3"
@ -673,7 +674,7 @@ if(! function_exists('attribute_contains')) {
*/ */
function attribute_contains($attr,$s) { function attribute_contains($attr,$s) {
$a = explode(' ', $attr); $a = explode(' ', $attr);
if(count($a) && in_array($s,$a)) if (count($a) && in_array($s,$a))
return true; return true;
return false; return false;
}} }}
@ -754,7 +755,7 @@ function logger($msg, $level = 0) {
}} }}
if(! function_exists('activity_match')) { if (! function_exists('activity_match')) {
/** /**
* Compare activity uri. Knows about activity namespace. * Compare activity uri. Knows about activity namespace.
* *
@ -763,7 +764,7 @@ if(! function_exists('activity_match')) {
* @return boolean * @return boolean
*/ */
function activity_match($haystack,$needle) { function activity_match($haystack,$needle) {
if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA))) if (($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
return true; return true;
return false; return false;
}} }}
@ -817,7 +818,7 @@ function get_tags($string) {
// and #hash tags. // and #hash tags.
if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) { if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
foreach($matches[1] as $match) { foreach ($matches[1] as $match) {
if (strstr($match, ']')) { if (strstr($match, ']')) {
// we might be inside a bbcode color tag - leave it alone // we might be inside a bbcode color tag - leave it alone
continue; continue;
@ -842,7 +843,7 @@ function get_tags($string) {
// //
if(! function_exists('qp')) { if (! function_exists('qp')) {
/** /**
* quick and dirty quoted_printable encoding * quick and dirty quoted_printable encoding
* *
@ -853,7 +854,7 @@ function qp($s) {
return str_replace ("%","=",rawurlencode($s)); return str_replace ("%","=",rawurlencode($s));
}} }}
if(! function_exists('contact_block')) { if (! function_exists('contact_block')) {
/** /**
* Get html for contact block. * Get html for contact block.
* *
@ -866,12 +867,12 @@ function contact_block() {
$a = get_app(); $a = get_app();
$shown = get_pconfig($a->profile['uid'],'system','display_friend_count'); $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
if($shown === false) if ($shown === false)
$shown = 24; $shown = 24;
if($shown == 0) if ($shown == 0)
return; return;
if((! is_array($a->profile)) || ($a->profile['hide-friends'])) if ((! is_array($a->profile)) || ($a->profile['hide-friends']))
return $o; return $o;
$r = q("SELECT COUNT(*) AS `total` FROM `contact` $r = q("SELECT COUNT(*) AS `total` FROM `contact`
WHERE `uid` = %d AND NOT `self` AND NOT `blocked` WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
@ -885,7 +886,7 @@ function contact_block() {
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
$total = intval($r[0]['total']); $total = intval($r[0]['total']);
} }
if(! $total) { if (! $total) {
$contacts = t('No contacts'); $contacts = t('No contacts');
$micropro = Null; $micropro = Null;
@ -964,10 +965,10 @@ function micropro($contact, $redirect = false, $class = '', $textmode = false) {
$sparkle = ''; $sparkle = '';
$redir = false; $redir = false;
if($redirect) { if ($redirect) {
$a = get_app(); $a = get_app();
$redirect_url = 'redir/' . $contact['id']; $redirect_url = 'redir/' . $contact['id'];
if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) { if (local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
$redir = true; $redir = true;
$url = $redirect_url; $url = $redirect_url;
$sparkle = ' sparkle'; $sparkle = ' sparkle';
@ -977,7 +978,7 @@ function micropro($contact, $redirect = false, $class = '', $textmode = false) {
} }
// If there is some js available we don't need the url // If there is some js available we don't need the url
if(x($contact,'click')) if (x($contact,'click'))
$url = ''; $url = '';
return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),array( return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),array(
@ -995,7 +996,7 @@ function micropro($contact, $redirect = false, $class = '', $textmode = false) {
if(! function_exists('search')) { if (! function_exists('search')) {
/** /**
* search box * search box
* *
@ -1030,7 +1031,7 @@ function search($s,$id='search-box',$url='search',$save = false, $aside = true)
return replace_macros(get_markup_template('searchbox.tpl'), $values); return replace_macros(get_markup_template('searchbox.tpl'), $values);
}} }}
if(! function_exists('valid_email')) { if (! function_exists('valid_email')) {
/** /**
* Check if $x is a valid email string * Check if $x is a valid email string
* *
@ -1040,16 +1041,16 @@ if(! function_exists('valid_email')) {
function valid_email($x){ function valid_email($x){
// Removed because Fabio told me so. // Removed because Fabio told me so.
//if(get_config('system','disable_email_validation')) //if (get_config('system','disable_email_validation'))
// return true; // return true;
if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x)) if (preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
return true; return true;
return false; return false;
}} }}
if(! function_exists('linkify')) { if (! function_exists('linkify')) {
/** /**
* Replace naked text hyperlink with HTML formatted hyperlink * Replace naked text hyperlink with HTML formatted hyperlink
* *
@ -1120,7 +1121,7 @@ function get_mood_verbs() {
return $arr; return $arr;
} }
if(! function_exists('day_translate')) { if (! function_exists('day_translate')) {
/** /**
* Translate days and months names * Translate days and months names
* *
@ -1140,7 +1141,7 @@ function day_translate($s) {
}} }}
if(! function_exists('normalise_link')) { if (! function_exists('normalise_link')) {
/** /**
* Normalize url * Normalize url
* *
@ -1154,7 +1155,7 @@ function normalise_link($url) {
if(! function_exists('link_compare')) { if (! function_exists('link_compare')) {
/** /**
* Compare two URLs to see if they are the same, but ignore * Compare two URLs to see if they are the same, but ignore
* slight but hopefully insignificant differences such as if one * slight but hopefully insignificant differences such as if one
@ -1167,7 +1168,7 @@ if(! function_exists('link_compare')) {
* *
*/ */
function link_compare($a,$b) { function link_compare($a,$b) {
if(strcasecmp(normalise_link($a),normalise_link($b)) === 0) if (strcasecmp(normalise_link($a),normalise_link($b)) === 0)
return true; return true;
return false; return false;
}} }}
@ -1222,7 +1223,7 @@ function put_item_in_cache(&$item, $update = false) {
// Given an item array, convert the body element from bbcode to html and add smilie icons. // Given an item array, convert the body element from bbcode to html and add smilie icons.
// If attach is true, also add icons for item attachments // If attach is true, also add icons for item attachments
if(! function_exists('prepare_body')) { if (! function_exists('prepare_body')) {
/** /**
* Given an item array, convert the body element from bbcode to html and add smilie icons. * Given an item array, convert the body element from bbcode to html and add smilie icons.
* If attach is true, also add icons for item attachments * If attach is true, also add icons for item attachments
@ -1249,7 +1250,7 @@ function prepare_body(&$item,$attach = false, $preview = false) {
$taglist = q("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d) ORDER BY `tid`", $taglist = q("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d) ORDER BY `tid`",
intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION)); intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
foreach($taglist as $tag) { foreach ($taglist as $tag) {
if ($tag["url"] == "") if ($tag["url"] == "")
$tag["url"] = $searchpath.strtolower($tag["term"]); $tag["url"] = $searchpath.strtolower($tag["term"]);
@ -1283,7 +1284,7 @@ function prepare_body(&$item,$attach = false, $preview = false) {
call_hooks('prepare_body', $prep_arr); call_hooks('prepare_body', $prep_arr);
$s = $prep_arr['html']; $s = $prep_arr['html'];
if(! $attach) { if (! $attach) {
// Replace the blockquotes with quotes that are used in mails // Replace the blockquotes with quotes that are used in mails
$mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">'; $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
$s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s); $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
@ -1293,23 +1294,23 @@ function prepare_body(&$item,$attach = false, $preview = false) {
$as = ''; $as = '';
$vhead = false; $vhead = false;
$arr = explode('[/attach],',$item['attach']); $arr = explode('[/attach],',$item['attach']);
if(count($arr)) { if (count($arr)) {
$as .= '<div class="body-attach">'; $as .= '<div class="body-attach">';
foreach($arr as $r) { foreach ($arr as $r) {
$matches = false; $matches = false;
$icon = ''; $icon = '';
$cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER); $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER);
if($cnt) { if ($cnt) {
foreach($matches as $mtch) { foreach ($matches as $mtch) {
$mime = $mtch[3]; $mime = $mtch[3];
if((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) if ((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN))
$the_url = 'redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1]; $the_url = 'redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
else else
$the_url = $mtch[1]; $the_url = $mtch[1];
if(strpos($mime, 'video') !== false) { if (strpos($mime, 'video') !== false) {
if(!$vhead) { if (!$vhead) {
$vhead = true; $vhead = true;
$a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array( $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array(
'$baseurl' => z_root(), '$baseurl' => z_root(),
@ -1331,7 +1332,7 @@ function prepare_body(&$item,$attach = false, $preview = false) {
} }
$filetype = strtolower(substr( $mime, 0, strpos($mime,'/') )); $filetype = strtolower(substr( $mime, 0, strpos($mime,'/') ));
if($filetype) { if ($filetype) {
$filesubtype = strtolower(substr( $mime, strpos($mime,'/') + 1 )); $filesubtype = strtolower(substr( $mime, strpos($mime,'/') + 1 ));
$filesubtype = str_replace('.', '-', $filesubtype); $filesubtype = str_replace('.', '-', $filesubtype);
} }
@ -1366,7 +1367,7 @@ function prepare_body(&$item,$attach = false, $preview = false) {
$s = $s . $as; $s = $s . $as;
// map // map
if(strpos($s,'<div class="map">') !== false && $item['coord']) { if (strpos($s,'<div class="map">') !== false && $item['coord']) {
$x = generate_map(trim($item['coord'])); $x = generate_map(trim($item['coord']));
if ($x) { if ($x) {
$s = preg_replace('/\<div class\=\"map\"\>/','$0' . $x,$s); $s = preg_replace('/\<div class\=\"map\"\>/','$0' . $x,$s);
@ -1418,7 +1419,7 @@ function prepare_body(&$item,$attach = false, $preview = false) {
}} }}
if(! function_exists('prepare_text')) { if (! function_exists('prepare_text')) {
/** /**
* Given a text string, convert from bbcode to html and add smilie icons. * Given a text string, convert from bbcode to html and add smilie icons.
* *
@ -1429,7 +1430,7 @@ function prepare_text($text) {
require_once('include/bbcode.php'); require_once('include/bbcode.php');
if(stristr($text,'[nosmile]')) if (stristr($text,'[nosmile]'))
$s = bbcode($text); $s = bbcode($text);
else else
$s = Smilies::replace(bbcode($text)); $s = Smilies::replace(bbcode($text));
@ -1474,8 +1475,8 @@ function get_cats_and_terms($item) {
$matches = false; $first = true; $matches = false; $first = true;
$cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER); $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
if($cnt) { if ($cnt) {
foreach($matches as $mtch) { foreach ($matches as $mtch) {
$categories[] = array( $categories[] = array(
'name' => xmlify(file_tag_decode($mtch[1])), 'name' => xmlify(file_tag_decode($mtch[1])),
'url' => "#", 'url' => "#",
@ -1489,11 +1490,11 @@ function get_cats_and_terms($item) {
if (count($categories)) $categories[count($categories)-1]['last'] = true; if (count($categories)) $categories[count($categories)-1]['last'] = true;
if(local_user() == $item['uid']) { if (local_user() == $item['uid']) {
$matches = false; $first = true; $matches = false; $first = true;
$cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER); $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
if($cnt) { if ($cnt) {
foreach($matches as $mtch) { foreach ($matches as $mtch) {
$folders[] = array( $folders[] = array(
'name' => xmlify(file_tag_decode($mtch[1])), 'name' => xmlify(file_tag_decode($mtch[1])),
'url' => "#", 'url' => "#",
@ -1511,7 +1512,7 @@ function get_cats_and_terms($item) {
return array($categories, $folders); return array($categories, $folders);
} }
if(! function_exists('get_plink')) { if (! function_exists('get_plink')) {
/** /**
* get private link for item * get private link for item
* @param array $item * @param array $item
@ -1548,7 +1549,7 @@ function get_plink($item) {
return($ret); return($ret);
}} }}
if(! function_exists('unamp')) { if (! function_exists('unamp')) {
/** /**
* replace html amp entity with amp char * replace html amp entity with amp char
* @param string $s * @param string $s
@ -1559,7 +1560,7 @@ function unamp($s) {
}} }}
if(! function_exists('return_bytes')) { if (! function_exists('return_bytes')) {
/** /**
* return number of bytes in size (K, M, G) * return number of bytes in size (K, M, G)
* @param string $size_str * @param string $size_str
@ -1584,7 +1585,7 @@ function generate_user_guid() {
$x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1", $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
dbesc($guid) dbesc($guid)
); );
if(! count($x)) if (! count($x))
$found = false; $found = false;
} while ($found == true ); } while ($found == true );
return $guid; return $guid;
@ -1600,7 +1601,7 @@ function base64url_encode($s, $strip_padding = false) {
$s = strtr(base64_encode($s),'+/','-_'); $s = strtr(base64_encode($s),'+/','-_');
if($strip_padding) if ($strip_padding)
$s = str_replace('=','',$s); $s = str_replace('=','',$s);
return $s; return $s;
@ -1612,7 +1613,7 @@ function base64url_encode($s, $strip_padding = false) {
*/ */
function base64url_decode($s) { function base64url_decode($s) {
if(is_array($s)) { if (is_array($s)) {
logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true)); logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
return $s; return $s;
} }
@ -1623,11 +1624,11 @@ function base64url_decode($s) {
* // Uncomment if you find you need it. * // Uncomment if you find you need it.
* *
* $l = strlen($s); * $l = strlen($s);
* if(! strpos($s,'=')) { * if (! strpos($s,'=')) {
* $m = $l % 4; * $m = $l % 4;
* if($m == 2) * if ($m == 2)
* $s .= '=='; * $s .= '==';
* if($m == 3) * if ($m == 3)
* $s .= '='; * $s .= '=';
* } * }
* *
@ -1719,10 +1720,10 @@ function bb_translate_video($s) {
$matches = null; $matches = null;
$r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER); $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
if ($r) { if ($r) {
foreach($matches as $mtch) { foreach ($matches as $mtch) {
if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be'))) if ((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
$s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s); $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
elseif(stristr($mtch[1],'vimeo')) elseif (stristr($mtch[1],'vimeo'))
$s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s); $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
} }
} }
@ -1800,13 +1801,13 @@ function reltoabs($text, $base) {
* @return string * @return string
*/ */
function item_post_type($item) { function item_post_type($item) {
if(intval($item['event-id'])) if (intval($item['event-id']))
return t('event'); return t('event');
if(strlen($item['resource-id'])) if (strlen($item['resource-id']))
return t('photo'); return t('photo');
if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST) if (strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
return t('activity'); return t('activity');
if($item['id'] != $item['parent']) if ($item['id'] != $item['parent'])
return t('comment'); return t('comment');
return t('post'); return t('post');
} }
@ -1826,7 +1827,7 @@ function file_tag_decode($s) {
function file_tag_file_query($table,$s,$type = 'file') { function file_tag_file_query($table,$s,$type = 'file') {
if($type == 'file') if ($type == 'file')
$str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' ); $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
else else
$str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' ); $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
@ -1836,9 +1837,9 @@ function file_tag_file_query($table,$s,$type = 'file') {
// ex. given music,video return <music><video> or [music][video] // ex. given music,video return <music><video> or [music][video]
function file_tag_list_to_file($list,$type = 'file') { function file_tag_list_to_file($list,$type = 'file') {
$tag_list = ''; $tag_list = '';
if(strlen($list)) { if (strlen($list)) {
$list_array = explode(",",$list); $list_array = explode(",",$list);
if($type == 'file') { if ($type == 'file') {
$lbracket = '['; $lbracket = '[';
$rbracket = ']'; $rbracket = ']';
} }
@ -1847,8 +1848,8 @@ function file_tag_list_to_file($list,$type = 'file') {
$rbracket = '>'; $rbracket = '>';
} }
foreach($list_array as $item) { foreach ($list_array as $item) {
if(strlen($item)) { if (strlen($item)) {
$tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket; $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
} }
} }
@ -1860,15 +1861,15 @@ function file_tag_list_to_file($list,$type = 'file') {
function file_tag_file_to_list($file,$type = 'file') { function file_tag_file_to_list($file,$type = 'file') {
$matches = false; $matches = false;
$list = ''; $list = '';
if($type == 'file') { if ($type == 'file') {
$cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER); $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
} }
else { else {
$cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER); $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
} }
if($cnt) { if ($cnt) {
foreach($matches as $mtch) { foreach ($matches as $mtch) {
if(strlen($list)) if (strlen($list))
$list .= ','; $list .= ',';
$list .= file_tag_decode($mtch[1]); $list .= file_tag_decode($mtch[1]);
} }
@ -1881,15 +1882,15 @@ function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
// $file_old - categories previously associated with an item // $file_old - categories previously associated with an item
// $file_new - new list of categories for an item // $file_new - new list of categories for an item
if(! intval($uid)) if (! intval($uid))
return false; return false;
if($file_old == $file_new) if ($file_old == $file_new)
return true; return true;
$saved = get_pconfig($uid,'system','filetags'); $saved = get_pconfig($uid,'system','filetags');
if(strlen($saved)) { if (strlen($saved)) {
if($type == 'file') { if ($type == 'file') {
$lbracket = '['; $lbracket = '[';
$rbracket = ']'; $rbracket = ']';
$termtype = TERM_FILE; $termtype = TERM_FILE;
@ -1906,8 +1907,8 @@ function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
$new_tags = array(); $new_tags = array();
$check_new_tags = explode(",",file_tag_file_to_list($file_new,$type)); $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
foreach($check_new_tags as $tag) { foreach ($check_new_tags as $tag) {
if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket)) if (! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
$new_tags[] = $tag; $new_tags[] = $tag;
} }
@ -1917,12 +1918,12 @@ function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
$deleted_tags = array(); $deleted_tags = array();
$check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type)); $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
foreach($check_deleted_tags as $tag) { foreach ($check_deleted_tags as $tag) {
if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket)) if (! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
$deleted_tags[] = $tag; $deleted_tags[] = $tag;
} }
foreach($deleted_tags as $key => $tag) { foreach ($deleted_tags as $key => $tag) {
$r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d", $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
dbesc($tag), dbesc($tag),
intval(TERM_OBJ_POST), intval(TERM_OBJ_POST),
@ -1941,13 +1942,13 @@ function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
} }
} }
if($saved != $filetags_updated) { if ($saved != $filetags_updated) {
set_pconfig($uid,'system','filetags', $filetags_updated); set_pconfig($uid,'system','filetags', $filetags_updated);
} }
return true; return true;
} }
else else
if(strlen($file_new)) { if (strlen($file_new)) {
set_pconfig($uid,'system','filetags', $file_new); set_pconfig($uid,'system','filetags', $file_new);
} }
return true; return true;
@ -1957,14 +1958,14 @@ function file_tag_save_file($uid,$item,$file) {
require_once("include/files.php"); require_once("include/files.php");
$result = false; $result = false;
if(! intval($uid)) if (! intval($uid))
return false; return false;
$r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
intval($item), intval($item),
intval($uid) intval($uid)
); );
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']')) if (! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d", q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'), dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
intval($item), intval($item),
@ -1974,7 +1975,7 @@ function file_tag_save_file($uid,$item,$file) {
create_files_from_item($item); create_files_from_item($item);
$saved = get_pconfig($uid,'system','filetags'); $saved = get_pconfig($uid,'system','filetags');
if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']'))) if ((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']'); set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
info( t('Item filed') ); info( t('Item filed') );
} }
@ -1985,10 +1986,10 @@ function file_tag_unsave_file($uid,$item,$file,$cat = false) {
require_once("include/files.php"); require_once("include/files.php");
$result = false; $result = false;
if(! intval($uid)) if (! intval($uid))
return false; return false;
if($cat == true) { if ($cat == true) {
$pattern = '<' . file_tag_encode($file) . '>' ; $pattern = '<' . file_tag_encode($file) . '>' ;
$termtype = TERM_CATEGORY; $termtype = TERM_CATEGORY;
} else { } else {
@ -2038,8 +2039,8 @@ function normalise_openid($s) {
function undo_post_tagging($s) { function undo_post_tagging($s) {
$matches = null; $matches = null;
$cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER); $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
if($cnt) { if ($cnt) {
foreach($matches as $mtch) { foreach ($matches as $mtch) {
$s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s); $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
} }
} }
@ -2053,11 +2054,11 @@ function protect_sprintf($s) {
function is_a_date_arg($s) { function is_a_date_arg($s) {
$i = intval($s); $i = intval($s);
if($i > 1900) { if ($i > 1900) {
$y = date('Y'); $y = date('Y');
if($i <= $y+1 && strpos($s,'-') == 4) { if ($i <= $y+1 && strpos($s,'-') == 4) {
$m = intval(substr($s,5)); $m = intval(substr($s,5));
if($m > 0 && $m <= 12) if ($m > 0 && $m <= 12)
return true; return true;
} }
} }
@ -2126,10 +2127,10 @@ function format_network_name($network, $url = 0) {
* @return string Formated html * @return string Formated html
*/ */
function text_highlight($s,$lang) { function text_highlight($s,$lang) {
if($lang === 'js') if ($lang === 'js')
$lang = 'javascript'; $lang = 'javascript';
if(! strpos('Text_Highlighter',get_include_path())) { if (! strpos('Text_Highlighter',get_include_path())) {
set_include_path(get_include_path() . PATH_SEPARATOR . 'library/Text_Highlighter'); set_include_path(get_include_path() . PATH_SEPARATOR . 'library/Text_Highlighter');
} }
@ -2148,8 +2149,8 @@ function text_highlight($s,$lang) {
// it isn't present, nothing is highlighted. So we're going to see if it's present. // it isn't present, nothing is highlighted. So we're going to see if it's present.
// If not, we'll add it, and then quietly remove it after we get the processed output back. // If not, we'll add it, and then quietly remove it after we get the processed output back.
if($lang === 'php') { if ($lang === 'php') {
if(strpos('<?php',$s) !== 0) { if (strpos('<?php',$s) !== 0) {
$s = '<?php' . "\n" . $s; $s = '<?php' . "\n" . $s;
$tag_added = true; $tag_added = true;
} }
@ -2161,7 +2162,7 @@ function text_highlight($s,$lang) {
$o = $hl->highlight($s); $o = $hl->highlight($s);
$o = str_replace([" ","\n"],["&nbsp;&nbsp;&nbsp;&nbsp;",''],$o); $o = str_replace([" ","\n"],["&nbsp;&nbsp;&nbsp;&nbsp;",''],$o);
if($tag_added) { if ($tag_added) {
$b = substr($o,0,strpos($o,'<li>')); $b = substr($o,0,strpos($o,'<li>'));
$e = substr($o,strpos($o,'</li>')); $e = substr($o,strpos($o,'</li>'));
$o = $b . $e; $o = $b . $e;

View file

@ -174,29 +174,34 @@ function add_shadow_entry($itemid) {
function update_thread_uri($itemuri, $uid) { function update_thread_uri($itemuri, $uid) {
$messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid)); $messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid));
if (dbm::is_result($messages)) if (dbm::is_result($messages)) {
foreach ($messages as $message) foreach ($messages as $message) {
update_thread($message["id"]); update_thread($message["id"]);
}
}
} }
function update_thread($itemid, $setmention = false) { function update_thread($itemid, $setmention = false) {
$items = q("SELECT `uid`, `guid`, `title`, `body`, `created`, `edited`, `commented`, `received`, `changed`, `wall`, `private`, `pubmail`, `moderated`, `visible`, `spam`, `starred`, `bookmark`, `contact-id`, `gcontact-id`, $items = q("SELECT `uid`, `guid`, `title`, `body`, `created`, `edited`, `commented`, `received`, `changed`, `wall`, `private`, `pubmail`, `moderated`, `visible`, `spam`, `starred`, `bookmark`, `contact-id`, `gcontact-id`,
`deleted`, `origin`, `forum_mode`, `network`, `rendered-html`, `rendered-hash` FROM `item` WHERE `id` = %d AND (`parent` = %d OR `parent` = 0) LIMIT 1", intval($itemid), intval($itemid)); `deleted`, `origin`, `forum_mode`, `network`, `rendered-html`, `rendered-hash` FROM `item` WHERE `id` = %d AND (`parent` = %d OR `parent` = 0) LIMIT 1", intval($itemid), intval($itemid));
if (!dbm::is_result($items)) if (!dbm::is_result($items)) {
return; return;
}
$item = $items[0]; $item = $items[0];
if ($setmention) if ($setmention) {
$item["mention"] = 1; $item["mention"] = 1;
}
$sql = ""; $sql = "";
foreach ($item AS $field => $data) foreach ($item AS $field => $data)
if (!in_array($field, array("guid", "title", "body", "rendered-html", "rendered-hash"))) { if (!in_array($field, array("guid", "title", "body", "rendered-html", "rendered-hash"))) {
if ($sql != "") if ($sql != "") {
$sql .= ", "; $sql .= ", ";
}
$sql .= "`".$field."` = '".dbesc($data)."'"; $sql .= "`".$field."` = '".dbesc($data)."'";
} }
@ -208,8 +213,9 @@ function update_thread($itemid, $setmention = false) {
// Updating a shadow item entry // Updating a shadow item entry
$items = q("SELECT `id` FROM `item` WHERE `guid` = '%s' AND `uid` = 0 LIMIT 1", dbesc($item["guid"])); $items = q("SELECT `id` FROM `item` WHERE `guid` = '%s' AND `uid` = 0 LIMIT 1", dbesc($item["guid"]));
if (!$items) if (!dbm::is_result($items)) {
return; return;
}
$result = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `rendered-html` = '%s', `rendered-hash` = '%s' WHERE `id` = %d", $result = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `rendered-html` = '%s', `rendered-hash` = '%s' WHERE `id` = %d",
dbesc($item["title"]), dbesc($item["title"]),
@ -224,9 +230,11 @@ function update_thread($itemid, $setmention = false) {
function delete_thread_uri($itemuri, $uid) { function delete_thread_uri($itemuri, $uid) {
$messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid)); $messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid));
if(count($messages)) if (dbm::is_result($messages)) {
foreach ($messages as $message) foreach ($messages as $message) {
delete_thread($message["id"], $itemuri); delete_thread($message["id"], $itemuri);
}
}
} }
function delete_thread($itemid, $itemuri = "") { function delete_thread($itemid, $itemuri = "") {

View file

@ -21,35 +21,41 @@ function update_gcontact_run(&$argv, &$argc){
$r = q("SELECT * FROM `gcontact` WHERE `id` = %d", intval($contact_id)); $r = q("SELECT * FROM `gcontact` WHERE `id` = %d", intval($contact_id));
if (!$r) if (!dbm::is_result($r)) {
return; return;
}
if (!in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) if (!in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) }
return; return;
}
$data = probe_url($r[0]["url"]); $data = probe_url($r[0]["url"]);
if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) { if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
if ($r[0]["server_url"] != "") if ($r[0]["server_url"] != "") {
poco_check_server($r[0]["server_url"], $r[0]["network"]); poco_check_server($r[0]["server_url"], $r[0]["network"]);
}
q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `id` = %d", q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `id` = %d",
dbesc(datetime_convert()), intval($contact_id)); dbesc(datetime_convert()), intval($contact_id));
return; return;
} }
if (($data["name"] == "") AND ($r[0]['name'] != "")) if (($data["name"] == "") AND ($r[0]['name'] != "")) {
$data["name"] = $r[0]['name']; $data["name"] = $r[0]['name'];
}
if (($data["nick"] == "") AND ($r[0]['nick'] != "")) if (($data["nick"] == "") AND ($r[0]['nick'] != "")) {
$data["nick"] = $r[0]['nick']; $data["nick"] = $r[0]['nick'];
}
if (($data["addr"] == "") AND ($r[0]['addr'] != "")) if (($data["addr"] == "") AND ($r[0]['addr'] != "")) {
$data["addr"] = $r[0]['addr']; $data["addr"] = $r[0]['addr'];
}
if (($data["photo"] == "") AND ($r[0]['photo'] != "")) if (($data["photo"] == "") AND ($r[0]['photo'] != "")) {
$data["photo"] = $r[0]['photo']; $data["photo"] = $r[0]['photo'];
}
q("UPDATE `gcontact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `photo` = '%s' q("UPDATE `gcontact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `photo` = '%s'
WHERE `id` = %d", WHERE `id` = %d",

View file

@ -43,21 +43,21 @@ function create_user($arr) {
$tmp_str = $openid_url; $tmp_str = $openid_url;
if($using_invites) { if ($using_invites) {
if(! $invite_id) { if (! $invite_id) {
$result['message'] .= t('An invitation is required.') . EOL; $result['message'] .= t('An invitation is required.') . EOL;
return $result; return $result;
} }
$r = q("SELECT * FROM `register` WHERE `hash` = '%s' LIMIT 1", dbesc($invite_id)); $r = q("SELECT * FROM `register` WHERE `hash` = '%s' LIMIT 1", dbesc($invite_id));
if(! results($r)) { if (! results($r)) {
$result['message'] .= t('Invitation could not be verified.') . EOL; $result['message'] .= t('Invitation could not be verified.') . EOL;
return $result; return $result;
} }
} }
if((! x($username)) || (! x($email)) || (! x($nickname))) { if ((! x($username)) || (! x($email)) || (! x($nickname))) {
if($openid_url) { if ($openid_url) {
if(! validate_url($tmp_str)) { if (! validate_url($tmp_str)) {
$result['message'] .= t('Invalid OpenID url') . EOL; $result['message'] .= t('Invalid OpenID url') . EOL;
return $result; return $result;
} }
@ -83,7 +83,7 @@ function create_user($arr) {
return; return;
} }
if(! validate_url($tmp_str)) if (! validate_url($tmp_str))
$openid_url = ''; $openid_url = '';
@ -92,9 +92,9 @@ function create_user($arr) {
// collapse multiple spaces in name // collapse multiple spaces in name
$username = preg_replace('/ +/',' ',$username); $username = preg_replace('/ +/',' ',$username);
if(mb_strlen($username) > 48) if (mb_strlen($username) > 48)
$result['message'] .= t('Please use a shorter name.') . EOL; $result['message'] .= t('Please use a shorter name.') . EOL;
if(mb_strlen($username) < 3) if (mb_strlen($username) < 3)
$result['message'] .= t('Name too short.') . EOL; $result['message'] .= t('Name too short.') . EOL;
// I don't really like having this rule, but it cuts down // I don't really like having this rule, but it cuts down
@ -107,17 +107,17 @@ function create_user($arr) {
// So now we are just looking for a space in the full name. // So now we are just looking for a space in the full name.
$loose_reg = get_config('system','no_regfullname'); $loose_reg = get_config('system','no_regfullname');
if(! $loose_reg) { if (! $loose_reg) {
$username = mb_convert_case($username,MB_CASE_TITLE,'UTF-8'); $username = mb_convert_case($username,MB_CASE_TITLE,'UTF-8');
if(! strpos($username,' ')) if (! strpos($username,' '))
$result['message'] .= t("That doesn't appear to be your full \x28First Last\x29 name.") . EOL; $result['message'] .= t("That doesn't appear to be your full \x28First Last\x29 name.") . EOL;
} }
if(! allowed_email($email)) if (! allowed_email($email))
$result['message'] .= t('Your email domain is not among those allowed on this site.') . EOL; $result['message'] .= t('Your email domain is not among those allowed on this site.') . EOL;
if((! valid_email($email)) || (! validate_email($email))) if ((! valid_email($email)) || (! validate_email($email)))
$result['message'] .= t('Not a valid email address.') . EOL; $result['message'] .= t('Not a valid email address.') . EOL;
// Disallow somebody creating an account using openid that uses the admin email address, // Disallow somebody creating an account using openid that uses the admin email address,
@ -125,8 +125,8 @@ function create_user($arr) {
$adminlist = explode(",", str_replace(" ", "", strtolower($a->config['admin_email']))); $adminlist = explode(",", str_replace(" ", "", strtolower($a->config['admin_email'])));
//if((x($a->config,'admin_email')) && (strcasecmp($email,$a->config['admin_email']) == 0) && strlen($openid_url)) { //if ((x($a->config,'admin_email')) && (strcasecmp($email,$a->config['admin_email']) == 0) && strlen($openid_url)) {
if((x($a->config,'admin_email')) && in_array(strtolower($email), $adminlist) && strlen($openid_url)) { if ((x($a->config,'admin_email')) && in_array(strtolower($email), $adminlist) && strlen($openid_url)) {
$r = q("SELECT * FROM `user` WHERE `email` = '%s' LIMIT 1", $r = q("SELECT * FROM `user` WHERE `email` = '%s' LIMIT 1",
dbesc($email) dbesc($email)
); );
@ -136,7 +136,7 @@ function create_user($arr) {
$nickname = $arr['nickname'] = strtolower($nickname); $nickname = $arr['nickname'] = strtolower($nickname);
if(! preg_match("/^[a-z0-9][a-z0-9\_]*$/",$nickname)) if (! preg_match("/^[a-z0-9][a-z0-9\_]*$/",$nickname))
$result['message'] .= t('Your "nickname" can only contain "a-z", "0-9" and "_".') . EOL; $result['message'] .= t('Your "nickname" can only contain "a-z", "0-9" and "_".') . EOL;
$r = q("SELECT `uid` FROM `user` $r = q("SELECT `uid` FROM `user`
@ -156,7 +156,7 @@ function create_user($arr) {
if (dbm::is_result($r)) if (dbm::is_result($r))
$result['message'] .= t('Nickname was once registered here and may not be re-used. Please choose another.') . EOL; $result['message'] .= t('Nickname was once registered here and may not be re-used. Please choose another.') . EOL;
if(strlen($result['message'])) { if (strlen($result['message'])) {
return $result; return $result;
} }
@ -169,13 +169,13 @@ function create_user($arr) {
$keys = new_keypair(4096); $keys = new_keypair(4096);
if($keys === false) { if ($keys === false) {
$result['message'] .= t('SERIOUS ERROR: Generation of security keys failed.') . EOL; $result['message'] .= t('SERIOUS ERROR: Generation of security keys failed.') . EOL;
return $result; return $result;
} }
$default_service_class = get_config('system','default_service_class'); $default_service_class = get_config('system','default_service_class');
if(! $default_service_class) if (! $default_service_class)
$default_service_class = ''; $default_service_class = '';
@ -249,7 +249,7 @@ function create_user($arr) {
return $result; return $result;
} }
if(x($newuid) !== false) { if (x($newuid) !== false) {
$r = q("INSERT INTO `profile` ( `uid`, `profile-name`, `is-default`, `name`, `photo`, `thumb`, `publish`, `net-publish` ) $r = q("INSERT INTO `profile` ( `uid`, `profile-name`, `is-default`, `name`, `photo`, `thumb`, `publish`, `net-publish` )
VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, %d ) ", VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, %d ) ",
intval($newuid), intval($newuid),
@ -292,7 +292,7 @@ function create_user($arr) {
); );
} }
if(get_config('system', 'newuser_private') && $def_gid) { if (get_config('system', 'newuser_private') && $def_gid) {
q("UPDATE `user` SET `allow_gid` = '%s' WHERE `uid` = %d", q("UPDATE `user` SET `allow_gid` = '%s' WHERE `uid` = %d",
dbesc("<" . $def_gid . ">"), dbesc("<" . $def_gid . ">"),
intval($newuid) intval($newuid)
@ -302,11 +302,11 @@ function create_user($arr) {
} }
// if we have no OpenID photo try to look up an avatar // if we have no OpenID photo try to look up an avatar
if(! strlen($photo)) if (! strlen($photo))
$photo = avatar_img($email); $photo = avatar_img($email);
// unless there is no avatar-plugin loaded // unless there is no avatar-plugin loaded
if(strlen($photo)) { if (strlen($photo)) {
require_once('include/Photo.php'); require_once('include/Photo.php');
$photo_failure = false; $photo_failure = false;
@ -317,7 +317,7 @@ function create_user($arr) {
$img = new Photo($img_str, $type); $img = new Photo($img_str, $type);
if($img->is_valid()) { if ($img->is_valid()) {
$img->scaleImageSquare(175); $img->scaleImageSquare(175);

View file

@ -50,7 +50,7 @@ class xml {
} }
} }
foreach($array as $key => $value) { foreach ($array as $key => $value) {
if (!isset($element) AND isset($xml)) { if (!isset($element) AND isset($xml)) {
$element = $xml; $element = $xml;
} }
@ -305,7 +305,7 @@ class xml {
//Set the attributes too. //Set the attributes too.
if (isset($attributes) and $get_attributes) { if (isset($attributes) and $get_attributes) {
foreach ($attributes as $attr => $val) { foreach ($attributes as $attr => $val) {
if($priority == 'tag') { if ($priority == 'tag') {
$attributes_data[$attr] = $val; $attributes_data[$attr] = $val;
} else { } else {
$result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr' $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'

View file

@ -28,17 +28,17 @@ $a->backend = false;
/** /**
* *
* Load the configuration file which contains our DB credentials. * Load the configuration file which contains our DB credentials.
* Ignore errors. If the file doesn't exist or is empty, we are running in installation mode. * Ignore errors. If the file doesn't exist or is empty, we are running in
* installation mode.
* *
*/ */
$install = ((file_exists('.htconfig.php') && filesize('.htconfig.php')) ? false : true); $install = ((file_exists('.htconfig.php') && filesize('.htconfig.php')) ? false : true);
@include(".htconfig.php"); // Only load config if found, don't surpress errors
if (!$install) {
include(".htconfig.php");
}
/** /**
* *
@ -48,7 +48,7 @@ $install = ((file_exists('.htconfig.php') && filesize('.htconfig.php')) ? false
require_once("include/dba.php"); require_once("include/dba.php");
if(!$install) { if (!$install) {
$db = new dba($db_host, $db_user, $db_pass, $db_data, $install); $db = new dba($db_host, $db_user, $db_pass, $db_data, $install);
unset($db_host, $db_user, $db_pass, $db_data); unset($db_host, $db_user, $db_pass, $db_data);
@ -117,12 +117,12 @@ if (x($_SESSION,'authenticated') && !x($_SESSION,'language')) {
if (dbm::is_result($r)) $_SESSION['language'] = $r[0]['language']; if (dbm::is_result($r)) $_SESSION['language'] = $r[0]['language'];
} }
if((x($_SESSION,'language')) && ($_SESSION['language'] !== $lang)) { if ((x($_SESSION,'language')) && ($_SESSION['language'] !== $lang)) {
$lang = $_SESSION['language']; $lang = $_SESSION['language'];
load_translation_table($lang); load_translation_table($lang);
} }
if((x($_GET,'zrl')) && (!$install && !$maintenance)) { if ((x($_GET,'zrl')) && (!$install && !$maintenance)) {
// Only continue when the given profile link seems valid // Only continue when the given profile link seems valid
// Valid profile links contain a path with "/profile/" and no query parameters // Valid profile links contain a path with "/profile/" and no query parameters
if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") AND if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") AND
@ -223,7 +223,7 @@ if ((local_user()) || (! $privateapps === "1")) {
* further processing. * further processing.
*/ */
if(strlen($a->module)) { if (strlen($a->module)) {
/** /**
* *
@ -233,12 +233,14 @@ if(strlen($a->module)) {
*/ */
// Compatibility with the Android Diaspora client // Compatibility with the Android Diaspora client
if ($a->module == "stream") if ($a->module == "stream") {
$a->module = "network"; $a->module = "network";
}
// Compatibility with the Firefox App // Compatibility with the Firefox App
if (($a->module == "users") AND ($a->cmd == "users/sign_in")) if (($a->module == "users") AND ($a->cmd == "users/sign_in")) {
$a->module = "login"; $a->module = "login";
}
$privateapps = get_config('config','private_addons'); $privateapps = get_config('config','private_addons');
@ -246,13 +248,13 @@ if(strlen($a->module)) {
//Check if module is an app and if public access to apps is allowed or not //Check if module is an app and if public access to apps is allowed or not
if ((!local_user()) && plugin_is_app($a->module) && $privateapps === "1") { if ((!local_user()) && plugin_is_app($a->module) && $privateapps === "1") {
info( t("You must be logged in to use addons. ")); info( t("You must be logged in to use addons. "));
} } else {
else {
include_once("addon/{$a->module}/{$a->module}.php"); include_once("addon/{$a->module}/{$a->module}.php");
if(function_exists($a->module . '_module')) if (function_exists($a->module . '_module')) {
$a->module_loaded = true; $a->module_loaded = true;
} }
} }
}
/** /**
* If not, next look for a 'standard' program module in the 'mod' directory * If not, next look for a 'standard' program module in the 'mod' directory
@ -320,29 +322,29 @@ if (!$install && !$maintenance) {
* Call module functions * Call module functions
*/ */
if($a->module_loaded) { if ($a->module_loaded) {
$a->page['page_title'] = $a->module; $a->page['page_title'] = $a->module;
$placeholder = ''; $placeholder = '';
if(function_exists($a->module . '_init')) { if (function_exists($a->module . '_init')) {
call_hooks($a->module . '_mod_init', $placeholder); call_hooks($a->module . '_mod_init', $placeholder);
$func = $a->module . '_init'; $func = $a->module . '_init';
$func($a); $func($a);
} }
if(function_exists(str_replace('-','_',current_theme()) . '_init')) { if (function_exists(str_replace('-','_',current_theme()) . '_init')) {
$func = str_replace('-','_',current_theme()) . '_init'; $func = str_replace('-','_',current_theme()) . '_init';
$func($a); $func($a);
} }
// elseif (x($a->theme_info,"extends") && file_exists("view/theme/".$a->theme_info["extends"]."/theme.php")) { // elseif (x($a->theme_info,"extends") && file_exists("view/theme/".$a->theme_info["extends"]."/theme.php")) {
// require_once("view/theme/".$a->theme_info["extends"]."/theme.php"); // require_once("view/theme/".$a->theme_info["extends"]."/theme.php");
// if(function_exists(str_replace('-','_',$a->theme_info["extends"]) . '_init')) { // if (function_exists(str_replace('-','_',$a->theme_info["extends"]) . '_init')) {
// $func = str_replace('-','_',$a->theme_info["extends"]) . '_init'; // $func = str_replace('-','_',$a->theme_info["extends"]) . '_init';
// $func($a); // $func($a);
// } // }
// } // }
if(($_SERVER['REQUEST_METHOD'] === 'POST') && (! $a->error) if (($_SERVER['REQUEST_METHOD'] === 'POST') && (! $a->error)
&& (function_exists($a->module . '_post')) && (function_exists($a->module . '_post'))
&& (! x($_POST,'auth-params'))) { && (! x($_POST,'auth-params'))) {
call_hooks($a->module . '_mod_post', $_POST); call_hooks($a->module . '_mod_post', $_POST);
@ -350,13 +352,13 @@ if($a->module_loaded) {
$func($a); $func($a);
} }
if((! $a->error) && (function_exists($a->module . '_afterpost'))) { if ((! $a->error) && (function_exists($a->module . '_afterpost'))) {
call_hooks($a->module . '_mod_afterpost',$placeholder); call_hooks($a->module . '_mod_afterpost',$placeholder);
$func = $a->module . '_afterpost'; $func = $a->module . '_afterpost';
$func($a); $func($a);
} }
if((! $a->error) && (function_exists($a->module . '_content'))) { if ((! $a->error) && (function_exists($a->module . '_content'))) {
$arr = array('content' => $a->page['content']); $arr = array('content' => $a->page['content']);
call_hooks($a->module . '_mod_content', $arr); call_hooks($a->module . '_mod_content', $arr);
$a->page['content'] = $arr['content']; $a->page['content'] = $arr['content'];
@ -366,7 +368,7 @@ if($a->module_loaded) {
$a->page['content'] .= $arr['content']; $a->page['content'] .= $arr['content'];
} }
if(function_exists(str_replace('-','_',current_theme()) . '_content_loaded')) { if (function_exists(str_replace('-','_',current_theme()) . '_content_loaded')) {
$func = str_replace('-','_',current_theme()) . '_content_loaded'; $func = str_replace('-','_',current_theme()) . '_content_loaded';
$func($a); $func($a);
} }
@ -392,18 +394,20 @@ $a->init_page_end();
// If you're just visiting, let javascript take you home // If you're just visiting, let javascript take you home
if(x($_SESSION,'visitor_home')) if (x($_SESSION,'visitor_home')) {
$homebase = $_SESSION['visitor_home']; $homebase = $_SESSION['visitor_home'];
elseif(local_user()) } elseif (local_user()) {
$homebase = 'profile/' . $a->user['nickname']; $homebase = 'profile/' . $a->user['nickname'];
}
if(isset($homebase)) if (isset($homebase)) {
$a->page['content'] .= '<script>var homebase="' . $homebase . '" ; </script>'; $a->page['content'] .= '<script>var homebase="' . $homebase . '" ; </script>';
}
// now that we've been through the module content, see if the page reported // now that we've been through the module content, see if the page reported
// a permission problem and if so, a 403 response would seem to be in order. // a permission problem and if so, a 403 response would seem to be in order.
if(stristr( implode("",$_SESSION['sysmsg']), t('Permission denied'))) { if (stristr( implode("",$_SESSION['sysmsg']), t('Permission denied'))) {
header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . t('Permission denied.')); header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . t('Permission denied.'));
} }
@ -413,13 +417,13 @@ if(stristr( implode("",$_SESSION['sysmsg']), t('Permission denied'))) {
* *
*/ */
/*if(x($_SESSION,'sysmsg')) { /*if (x($_SESSION,'sysmsg')) {
$a->page['content'] = "<div id=\"sysmsg\" class=\"error-message\">{$_SESSION['sysmsg']}</div>\r\n" $a->page['content'] = "<div id=\"sysmsg\" class=\"error-message\">{$_SESSION['sysmsg']}</div>\r\n"
. ((x($a->page,'content')) ? $a->page['content'] : ''); . ((x($a->page,'content')) ? $a->page['content'] : '');
$_SESSION['sysmsg']=""; $_SESSION['sysmsg']="";
unset($_SESSION['sysmsg']); unset($_SESSION['sysmsg']);
} }
if(x($_SESSION,'sysmsg_info')) { if (x($_SESSION,'sysmsg_info')) {
$a->page['content'] = "<div id=\"sysmsg_info\" class=\"info-message\">{$_SESSION['sysmsg_info']}</div>\r\n" $a->page['content'] = "<div id=\"sysmsg_info\" class=\"info-message\">{$_SESSION['sysmsg_info']}</div>\r\n"
. ((x($a->page,'content')) ? $a->page['content'] : ''); . ((x($a->page,'content')) ? $a->page['content'] : '');
$_SESSION['sysmsg_info']=""; $_SESSION['sysmsg_info']="";
@ -437,7 +441,7 @@ call_hooks('page_end', $a->page['content']);
* *
*/ */
if($a->module != 'install' && $a->module != 'maintenance') { if ($a->module != 'install' && $a->module != 'maintenance') {
nav($a); nav($a);
} }
@ -445,11 +449,10 @@ if($a->module != 'install' && $a->module != 'maintenance') {
* Add a "toggle mobile" link if we're using a mobile device * Add a "toggle mobile" link if we're using a mobile device
*/ */
if($a->is_mobile || $a->is_tablet) { if ($a->is_mobile || $a->is_tablet) {
if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) { if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
$link = 'toggle_mobile?address=' . curPageURL(); $link = 'toggle_mobile?address=' . curPageURL();
} } else {
else {
$link = 'toggle_mobile?off=1&address=' . curPageURL(); $link = 'toggle_mobile?off=1&address=' . curPageURL();
} }
$a->page['footer'] = replace_macros(get_markup_template("toggle_mobile_footer.tpl"), array( $a->page['footer'] = replace_macros(get_markup_template("toggle_mobile_footer.tpl"), array(
@ -462,10 +465,11 @@ if($a->is_mobile || $a->is_tablet) {
* Build the page - now that we have all the components * Build the page - now that we have all the components
*/ */
if(!$a->theme['stylesheet']) if (!$a->theme['stylesheet']) {
$stylesheet = current_theme_url(); $stylesheet = current_theme_url();
else } else {
$stylesheet = $a->theme['stylesheet']; $stylesheet = $a->theme['stylesheet'];
}
$a->page['htmlhead'] = str_replace('{{$stylesheet}}',$stylesheet,$a->page['htmlhead']); $a->page['htmlhead'] = str_replace('{{$stylesheet}}',$stylesheet,$a->page['htmlhead']);
//$a->page['htmlhead'] = replace_macros($a->page['htmlhead'], array('$stylesheet' => $stylesheet)); //$a->page['htmlhead'] = replace_macros($a->page['htmlhead'], array('$stylesheet' => $stylesheet));
@ -499,8 +503,9 @@ if (isset($_GET["mode"]) AND ($_GET["mode"] == "raw")) {
echo substr($target->saveHTML(), 6, -8); echo substr($target->saveHTML(), 6, -8);
if (!$a->is_backend()) if (!$a->is_backend()) {
session_write_close(); session_write_close();
}
exit; exit;
} }
@ -519,7 +524,7 @@ if (isset($_GET["mode"])) {
} }
// If there is no page template use the default page template // If there is no page template use the default page template
if(!$template) { if (!$template) {
$template = theme_include("default.php"); $template = theme_include("default.php");
} }

View file

@ -54,7 +54,7 @@ function wk_social_relay(App $a) {
} }
$taglist = array(); $taglist = array();
foreach($tags AS $tag) { foreach ($tags AS $tag) {
$taglist[] = $tag; $taglist[] = $tag;
} }

View file

@ -4,11 +4,11 @@ require_once('include/Scrape.php');
function acctlink_init(App $a) { function acctlink_init(App $a) {
if(x($_GET,'addr')) { if (x($_GET,'addr')) {
$addr = trim($_GET['addr']); $addr = trim($_GET['addr']);
$res = probe_url($addr); $res = probe_url($addr);
//logger('acctlink: ' . print_r($res,true)); //logger('acctlink: ' . print_r($res,true));
if($res['url']) { if ($res['url']) {
goaway($res['url']); goaway($res['url']);
killme(); killme();
} }

View file

@ -859,8 +859,9 @@ function admin_page_site(App $a) {
$allowed_theme_list = Config::get('system', 'allowed_themes'); $allowed_theme_list = Config::get('system', 'allowed_themes');
foreach ($files as $file) { foreach ($files as $file) {
if (intval(file_exists($file.'/unsupported'))) if (file_exists($file.'/unsupported'))
continue; continue;
}
$f = basename($file); $f = basename($file);
@ -1274,7 +1275,7 @@ function admin_page_users(App $a) {
if ($a->argc>2) { if ($a->argc>2) {
$uid = $a->argv[3]; $uid = $a->argv[3];
$user = q("SELECT `username`, `blocked` FROM `user` WHERE `uid` = %d", intval($uid)); $user = q("SELECT `username`, `blocked` FROM `user` WHERE `uid` = %d", intval($uid));
if (count($user) == 0) { if (!dbm::is_result($user)) {
notice('User not found'.EOL); notice('User not found'.EOL);
goaway('admin/users'); goaway('admin/users');
return ''; // NOTREACHED return ''; // NOTREACHED
@ -1609,7 +1610,7 @@ function admin_page_plugins(App $a) {
* @param int $result * @param int $result
*/ */
function toggle_theme(&$themes,$th,&$result) { function toggle_theme(&$themes,$th,&$result) {
for($x = 0; $x < count($themes); $x ++) { for ($x = 0; $x < count($themes); $x ++) {
if ($themes[$x]['name'] === $th) { if ($themes[$x]['name'] === $th) {
if ($themes[$x]['allowed']) { if ($themes[$x]['allowed']) {
$themes[$x]['allowed'] = 0; $themes[$x]['allowed'] = 0;
@ -1629,7 +1630,7 @@ function toggle_theme(&$themes,$th,&$result) {
* @return int * @return int
*/ */
function theme_status($themes,$th) { function theme_status($themes,$th) {
for($x = 0; $x < count($themes); $x ++) { for ($x = 0; $x < count($themes); $x ++) {
if ($themes[$x]['name'] === $th) { if ($themes[$x]['name'] === $th) {
if ($themes[$x]['allowed']) { if ($themes[$x]['allowed']) {
return 1; return 1;
@ -1706,9 +1707,9 @@ function admin_page_themes(App $a) {
continue; continue;
} }
$is_experimental = intval(file_exists($file.'/experimental')); $is_experimental = file_exists($file.'/experimental');
$is_supported = 1-(intval(file_exists($file.'/unsupported'))); $is_supported = (!file_exists($file.'/unsupported'));
$is_allowed = intval(in_array($f,$allowed_themes)); $is_allowed = in_array($f,$allowed_themes);
if ($is_allowed OR $is_supported OR get_config("system", "show_unsupported_themes")) { if ($is_allowed OR $is_supported OR get_config("system", "show_unsupported_themes")) {
$themes[] = array('name' => $f, 'experimental' => $is_experimental, 'supported' => $is_supported, 'allowed' => $is_allowed); $themes[] = array('name' => $f, 'experimental' => $is_experimental, 'supported' => $is_supported, 'allowed' => $is_allowed);
@ -1761,7 +1762,7 @@ function admin_page_themes(App $a) {
$status="off"; $action= t("Enable"); $status="off"; $action= t("Enable");
} }
$readme = Null; $readme = null;
if (is_file("view/theme/$theme/README.md")) { if (is_file("view/theme/$theme/README.md")) {
$readme = file_get_contents("view/theme/$theme/README.md"); $readme = file_get_contents("view/theme/$theme/README.md");
$readme = Markdown($readme); $readme = Markdown($readme);

View file

@ -37,8 +37,9 @@ function allfriends_content(App $a) {
$total = count_all_friends(local_user(), $cid); $total = count_all_friends(local_user(), $cid);
if(count($total)) if (count($total)) {
$a->set_pager_total($total); $a->set_pager_total($total);
}
$r = all_friends(local_user(), $cid, $a->pager['start'], $a->pager['itemspage']); $r = all_friends(local_user(), $cid, $a->pager['start'], $a->pager['itemspage']);

View file

@ -27,7 +27,7 @@ function api_post(App $a) {
return; return;
} }
if(count($a->user) && x($a->user,'uid') && $a->user['uid'] != local_user()) { if (count($a->user) && x($a->user,'uid') && $a->user['uid'] != local_user()) {
notice( t('Permission denied.') . EOL); notice( t('Permission denied.') . EOL);
return; return;
} }

View file

@ -3,23 +3,21 @@
function apps_content(App $a) { function apps_content(App $a) {
$privateaddons = get_config('config','private_addons'); $privateaddons = get_config('config','private_addons');
if ($privateaddons === "1") { if ($privateaddons === "1") {
if((! (local_user()))) { if ((! (local_user()))) {
info( t("You must be logged in to use addons. ")); info( t("You must be logged in to use addons. "));
return;}; return;
} }
}
$title = t('Applications'); $title = t('Applications');
if(count($a->apps)==0) if (count($a->apps) == 0) {
notice( t('No installed applications.') . EOL); notice( t('No installed applications.') . EOL);
}
$tpl = get_markup_template("apps.tpl"); $tpl = get_markup_template("apps.tpl");
return replace_macros($tpl, array( return replace_macros($tpl, array(
'$title' => $title, '$title' => $title,
'$apps' => $a->apps, '$apps' => $a->apps,
)); ));
} }

View file

@ -4,7 +4,7 @@ require_once('include/security.php');
function attach_init(App $a) { function attach_init(App $a) {
if($a->argc != 2) { if ($a->argc != 2) {
notice( t('Item not available.') . EOL); notice( t('Item not available.') . EOL);
return; return;
} }
@ -38,7 +38,7 @@ function attach_init(App $a) {
// error in Chrome for filenames with commas in them // error in Chrome for filenames with commas in them
header('Content-type: ' . $r[0]['filetype']); header('Content-type: ' . $r[0]['filetype']);
header('Content-length: ' . $r[0]['filesize']); header('Content-length: ' . $r[0]['filesize']);
if(isset($_GET['attachment']) && $_GET['attachment'] === '0') if (isset($_GET['attachment']) && $_GET['attachment'] === '0')
header('Content-disposition: filename="' . $r[0]['filename'] . '"'); header('Content-disposition: filename="' . $r[0]['filename'] . '"');
else else
header('Content-disposition: attachment; filename="' . $r[0]['filename'] . '"'); header('Content-disposition: attachment; filename="' . $r[0]['filename'] . '"');

View file

@ -25,7 +25,7 @@ function babel_content(App $a) {
$o .= '<br /><br />'; $o .= '<br /><br />';
if(x($_REQUEST,'text')) { if (x($_REQUEST,'text')) {
$text = trim($_REQUEST['text']); $text = trim($_REQUEST['text']);
$o .= "<h2>" . t("Source input: ") . "</h2>" . EOL. EOL; $o .= "<h2>" . t("Source input: ") . "</h2>" . EOL. EOL;
@ -63,7 +63,7 @@ function babel_content(App $a) {
} }
if(x($_REQUEST,'d2bbtext')) { if (x($_REQUEST,'d2bbtext')) {
$d2bbtext = trim($_REQUEST['d2bbtext']); $d2bbtext = trim($_REQUEST['d2bbtext']);
$o .= "<h2>" . t("Source input (Diaspora format): ") . "</h2>" . EOL. EOL; $o .= "<h2>" . t("Source input (Diaspora format): ") . "</h2>" . EOL. EOL;

View file

@ -10,10 +10,10 @@ require_once('include/event.php');
require_once('include/redir.php'); require_once('include/redir.php');
function cal_init(App $a) { function cal_init(App $a) {
if($a->argc > 1) if ($a->argc > 1)
auto_redir($a, $a->argv[1]); auto_redir($a, $a->argv[1]);
if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) { if ((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
return; return;
} }
@ -21,13 +21,13 @@ function cal_init(App $a) {
$o = ''; $o = '';
if($a->argc > 1) { if ($a->argc > 1) {
$nick = $a->argv[1]; $nick = $a->argv[1];
$user = q("SELECT * FROM `user` WHERE `nickname` = '%s' AND `blocked` = 0 LIMIT 1", $user = q("SELECT * FROM `user` WHERE `nickname` = '%s' AND `blocked` = 0 LIMIT 1",
dbesc($nick) dbesc($nick)
); );
if(! count($user)) if (! count($user))
return; return;
$a->data['user'] = $user[0]; $a->data['user'] = $user[0];
@ -54,7 +54,7 @@ function cal_init(App $a) {
$cal_widget = widget_events(); $cal_widget = widget_events();
if(! x($a->page,'aside')) if (! x($a->page,'aside'))
$a->page['aside'] = ''; $a->page['aside'] = '';
$a->page['aside'] .= $vcard_widget; $a->page['aside'] .= $vcard_widget;
@ -69,6 +69,7 @@ function cal_content(App $a) {
// First day of the week (0 = Sunday) // First day of the week (0 = Sunday)
$firstDay = get_pconfig(local_user(),'system','first_day_of_week'); $firstDay = get_pconfig(local_user(),'system','first_day_of_week');
/// @TODO Convert all these to with curly braces
if ($firstDay === false) $firstDay=0; if ($firstDay === false) $firstDay=0;
// get the translation strings for the callendar // get the translation strings for the callendar
@ -94,8 +95,9 @@ function cal_content(App $a) {
$m = 0; $m = 0;
$ignored = ((x($_REQUEST,'ignored')) ? intval($_REQUEST['ignored']) : 0); $ignored = ((x($_REQUEST,'ignored')) ? intval($_REQUEST['ignored']) : 0);
if($a->argc == 4) { /// @TODO Convert to one if() statement
if($a->argv[2] == 'export') { if ($a->argc == 4) {
if ($a->argv[2] == 'export') {
$mode = 'export'; $mode = 'export';
$format = $a->argv[3]; $format = $a->argv[3];
} }
@ -112,15 +114,15 @@ function cal_content(App $a) {
$owner_uid = $a->data['user']['uid']; $owner_uid = $a->data['user']['uid'];
$nick = $a->data['user']['nickname']; $nick = $a->data['user']['nickname'];
if(is_array($_SESSION['remote'])) { if (is_array($_SESSION['remote'])) {
foreach($_SESSION['remote'] as $v) { foreach ($_SESSION['remote'] as $v) {
if($v['uid'] == $a->profile['profile_uid']) { if ($v['uid'] == $a->profile['profile_uid']) {
$contact_id = $v['cid']; $contact_id = $v['cid'];
break; break;
} }
} }
} }
if($contact_id) { if ($contact_id) {
$groups = init_groups_visitor($contact_id); $groups = init_groups_visitor($contact_id);
$r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1", $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
intval($contact_id), intval($contact_id),
@ -131,15 +133,15 @@ function cal_content(App $a) {
$remote_contact = true; $remote_contact = true;
} }
} }
if(! $remote_contact) { if (! $remote_contact) {
if(local_user()) { if (local_user()) {
$contact_id = $_SESSION['cid']; $contact_id = $_SESSION['cid'];
$contact = $a->contact; $contact = $a->contact;
} }
} }
$is_owner = ((local_user()) && (local_user() == $a->profile['profile_uid']) ? true : false); $is_owner = ((local_user()) && (local_user() == $a->profile['profile_uid']) ? true : false);
if($a->profile['hidewall'] && (! $is_owner) && (! $remote_contact)) { if ($a->profile['hidewall'] && (! $is_owner) && (! $remote_contact)) {
notice( t('Access to this profile has been restricted.') . EOL); notice( t('Access to this profile has been restricted.') . EOL);
return; return;
} }
@ -153,33 +155,33 @@ function cal_content(App $a) {
$tabs .= profile_tabs($a,false, $a->data['user']['nickname']); $tabs .= profile_tabs($a,false, $a->data['user']['nickname']);
// The view mode part is similiar to /mod/events.php // The view mode part is similiar to /mod/events.php
if($mode == 'view') { if ($mode == 'view') {
$thisyear = datetime_convert('UTC',date_default_timezone_get(),'now','Y'); $thisyear = datetime_convert('UTC',date_default_timezone_get(),'now','Y');
$thismonth = datetime_convert('UTC',date_default_timezone_get(),'now','m'); $thismonth = datetime_convert('UTC',date_default_timezone_get(),'now','m');
if(! $y) if (! $y)
$y = intval($thisyear); $y = intval($thisyear);
if(! $m) if (! $m)
$m = intval($thismonth); $m = intval($thismonth);
// Put some limits on dates. The PHP date functions don't seem to do so well before 1900. // Put some limits on dates. The PHP date functions don't seem to do so well before 1900.
// An upper limit was chosen to keep search engines from exploring links millions of years in the future. // An upper limit was chosen to keep search engines from exploring links millions of years in the future.
if($y < 1901) if ($y < 1901)
$y = 1900; $y = 1900;
if($y > 2099) if ($y > 2099)
$y = 2100; $y = 2100;
$nextyear = $y; $nextyear = $y;
$nextmonth = $m + 1; $nextmonth = $m + 1;
if($nextmonth > 12) { if ($nextmonth > 12) {
$nextmonth = 1; $nextmonth = 1;
$nextyear ++; $nextyear ++;
} }
$prevyear = $y; $prevyear = $y;
if($m > 1) if ($m > 1)
$prevmonth = $m - 1; $prevmonth = $m - 1;
else { else {
$prevmonth = 12; $prevmonth = 12;
@ -235,9 +237,10 @@ function cal_content(App $a) {
$events=array(); $events=array();
// transform the event in a usable array // transform the event in a usable array
if (dbm::is_result($r)) if (dbm::is_result($r)) {
$r = sort_by_date($r); $r = sort_by_date($r);
$events = process_events($r); $events = process_events($r);
}
if ($a->argv[2] === 'json'){ if ($a->argv[2] === 'json'){
echo json_encode($events); killme(); echo json_encode($events); killme();
@ -255,9 +258,9 @@ function cal_content(App $a) {
} }
// Get rid of dashes in key names, Smarty3 can't handle them // Get rid of dashes in key names, Smarty3 can't handle them
foreach($events as $key => $event) { foreach ($events as $key => $event) {
$event_item = array(); $event_item = array();
foreach($event['item'] as $k => $v) { foreach ($event['item'] as $k => $v) {
$k = str_replace('-','_',$k); $k = str_replace('-','_',$k);
$event_item[$k] = $v; $event_item[$k] = $v;
} }
@ -287,15 +290,15 @@ function cal_content(App $a) {
return $o; return $o;
} }
if($mode == 'export') { if ($mode == 'export') {
if(! (intval($owner_uid))) { if (! (intval($owner_uid))) {
notice( t('User not found')); notice( t('User not found'));
return; return;
} }
// Test permissions // Test permissions
// Respect the export feature setting for all other /cal pages if it's not the own profile // Respect the export feature setting for all other /cal pages if it's not the own profile
if( ((local_user() !== intval($owner_uid))) && ! feature_enabled($owner_uid, "export_calendar")) { if ( ((local_user() !== intval($owner_uid))) && ! feature_enabled($owner_uid, "export_calendar")) {
notice( t('Permission denied.') . EOL); notice( t('Permission denied.') . EOL);
goaway('cal/' . $nick); goaway('cal/' . $nick);
} }
@ -304,7 +307,7 @@ function cal_content(App $a) {
$evexport = event_export($owner_uid, $format); $evexport = event_export($owner_uid, $format);
if (!$evexport["success"]) { if (!$evexport["success"]) {
if($evexport["content"]) if ($evexport["content"])
notice( t('This calendar format is not supported') ); notice( t('This calendar format is not supported') );
else else
notice( t('No exportable data found')); notice( t('No exportable data found'));

View file

@ -57,23 +57,24 @@ function common_content(App $a) {
return; return;
} }
if(! $cid) { if (! $cid) {
if(get_my_url()) { if (get_my_url()) {
$r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1", $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
dbesc(normalise_link(get_my_url())), dbesc(normalise_link(get_my_url())),
intval($profile_uid) intval($profile_uid)
); );
if (dbm::is_result($r)) if (dbm::is_result($r)) {
$cid = $r[0]['id']; $cid = $r[0]['id'];
else { } else {
$r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1", $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
dbesc(normalise_link(get_my_url())) dbesc(normalise_link(get_my_url()))
); );
if (dbm::is_result($r)) if (dbm::is_result($r)) {
$zcid = $r[0]['id']; $zcid = $r[0]['id'];
} }
} }
} }
}
if ($cid == 0 && $zcid == 0) { if ($cid == 0 && $zcid == 0) {
return; return;

View file

@ -18,12 +18,12 @@ function community_content(App $a, $update = 0) {
if ($update) if ($update)
return; return;
if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) { if ((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
notice( t('Public access denied.') . EOL); notice( t('Public access denied.') . EOL);
return; return;
} }
if(get_config('system','community_page_style') == CP_NO_COMMUNITY_PAGE) { if (get_config('system','community_page_style') == CP_NO_COMMUNITY_PAGE) {
notice( t('Not available.') . EOL); notice( t('Not available.') . EOL);
return; return;
} }
@ -34,11 +34,11 @@ function community_content(App $a, $update = 0) {
$o .= '<h3>' . t('Community') . '</h3>'; $o .= '<h3>' . t('Community') . '</h3>';
if(! $update) { if (! $update) {
nav_set_selected('community'); nav_set_selected('community');
} }
if(x($a->data,'search')) if (x($a->data,'search'))
$search = notags(trim($a->data['search'])); $search = notags(trim($a->data['search']));
else else
$search = ((x($_GET,'search')) ? notags(trim(rawurldecode($_GET['search']))) : ''); $search = ((x($_GET,'search')) ? notags(trim(rawurldecode($_GET['search']))) : '');
@ -79,8 +79,9 @@ function community_content(App $a, $update = 0) {
$r = community_getitems($a->pager['start'] + ($count * $a->pager['itemspage']), $a->pager['itemspage']); $r = community_getitems($a->pager['start'] + ($count * $a->pager['itemspage']), $a->pager['itemspage']);
} while ((sizeof($s) < $a->pager['itemspage']) AND (++$count < 50) AND (sizeof($r) > 0)); } while ((sizeof($s) < $a->pager['itemspage']) AND (++$count < 50) AND (sizeof($r) > 0));
} else } else {
$s = $r; $s = $r;
}
// we behave the same in message lists as the search module // we behave the same in message lists as the search module

View file

@ -9,16 +9,17 @@ function contactgroup_content(App $a) {
killme(); killme();
} }
if(($a->argc > 2) && intval($a->argv[1]) && intval($a->argv[2])) { if (($a->argc > 2) && intval($a->argv[1]) && intval($a->argv[2])) {
$r = q("SELECT `id` FROM `contact` WHERE `id` = %d AND `uid` = %d and `self` = 0 and `blocked` = 0 AND `pending` = 0 LIMIT 1", $r = q("SELECT `id` FROM `contact` WHERE `id` = %d AND `uid` = %d and `self` = 0 and `blocked` = 0 AND `pending` = 0 LIMIT 1",
intval($a->argv[2]), intval($a->argv[2]),
intval(local_user()) intval(local_user())
); );
if (dbm::is_result($r)) if (dbm::is_result($r)) {
$change = intval($a->argv[2]); $change = intval($a->argv[2]);
} }
}
if(($a->argc > 1) && (intval($a->argv[1]))) { if (($a->argc > 1) && (intval($a->argv[1]))) {
$r = q("SELECT * FROM `group` WHERE `id` = %d AND `uid` = %d AND `deleted` = 0 LIMIT 1", $r = q("SELECT * FROM `group` WHERE `id` = %d AND `uid` = %d AND `deleted` = 0 LIMIT 1",
intval($a->argv[1]), intval($a->argv[1]),
@ -31,16 +32,16 @@ function contactgroup_content(App $a) {
$group = $r[0]; $group = $r[0];
$members = group_get_members($group['id']); $members = group_get_members($group['id']);
$preselected = array(); $preselected = array();
if(count($members)) { if (count($members)) {
foreach($members as $member) foreach ($members as $member) {
$preselected[] = $member['id']; $preselected[] = $member['id'];
} }
if($change) {
if(in_array($change,$preselected)) {
group_rmv_member(local_user(),$group['name'],$change);
} }
else {
if ($change) {
if (in_array($change,$preselected)) {
group_rmv_member(local_user(),$group['name'],$change);
} else {
group_add_member(local_user(),$group['name'],$change); group_add_member(local_user(),$group['name'],$change);
} }
} }

View file

@ -14,7 +14,7 @@ function contacts_init(App $a) {
$contact_id = 0; $contact_id = 0;
if((($a->argc == 2) && intval($a->argv[1])) OR (($a->argc == 3) && intval($a->argv[1]) && ($a->argv[2] == "posts"))) { if ((($a->argc == 2) && intval($a->argv[1])) OR (($a->argc == 3) && intval($a->argv[1]) && ($a->argv[2] == "posts"))) {
$contact_id = intval($a->argv[1]); $contact_id = intval($a->argv[1]);
$r = q("SELECT * FROM `contact` WHERE `uid` = %d and `id` = %d LIMIT 1", $r = q("SELECT * FROM `contact` WHERE `uid` = %d and `id` = %d LIMIT 1",
intval(local_user()), intval(local_user()),
@ -99,15 +99,24 @@ function contacts_init(App $a) {
function contacts_batch_actions(App $a) { function contacts_batch_actions(App $a) {
$contacts_id = $_POST['contact_batch']; $contacts_id = $_POST['contact_batch'];
if (!is_array($contacts_id)) return; if (!is_array($contacts_id)) {
return;
}
$orig_records = q("SELECT * FROM `contact` WHERE `id` IN (%s) AND `uid` = %d AND `self` = 0", $orig_records = q("SELECT * FROM `contact` WHERE `id` IN (%s) AND `uid` = %d AND `self` = 0",
implode(",", $contacts_id), implode(",", $contacts_id),
intval(local_user()) intval(local_user())
); );
if (!dbm::is_result($orig_records)) {
/// @TODO EOL really needed?
notice( t('Could not access contact record(s).') . EOL);
goaway('contacts');
return; // NOTREACHED
}
$count_actions=0; $count_actions=0;
foreach($orig_records as $orig_record) { foreach ($orig_records as $orig_record) {
$contact_id = $orig_record['id']; $contact_id = $orig_record['id'];
if (x($_POST, 'contacts_batch_update')) { if (x($_POST, 'contacts_batch_update')) {
_contact_update($contact_id); _contact_update($contact_id);
@ -130,14 +139,14 @@ function contacts_batch_actions(App $a) {
$count_actions++; $count_actions++;
} }
} }
if ($count_actions>0) {
if ($count_actions > 0) {
info ( sprintf( tt("%d contact edited.", "%d contacts edited.", $count_actions), $count_actions) ); info ( sprintf( tt("%d contact edited.", "%d contacts edited.", $count_actions), $count_actions) );
} }
if (x($_SESSION,'return_url')) { if (x($_SESSION,'return_url')) {
goaway('' . $_SESSION['return_url']); goaway('' . $_SESSION['return_url']);
} } else {
else {
goaway('contacts'); goaway('contacts');
} }
@ -165,7 +174,8 @@ function contacts_post(App $a) {
intval(local_user()) intval(local_user())
); );
if (! count($orig_record)) { if (! dbm::is_result($orig_record)) {
/// @TODO EOL really needed?
notice( t('Could not access contact record.') . EOL); notice( t('Could not access contact record.') . EOL);
goaway('contacts'); goaway('contacts');
return; // NOTREACHED return; // NOTREACHED
@ -194,8 +204,10 @@ function contacts_post(App $a) {
$ffi_keyword_blacklist = escape_tags(trim($_POST['ffi_keyword_blacklist'])); $ffi_keyword_blacklist = escape_tags(trim($_POST['ffi_keyword_blacklist']));
$priority = intval($_POST['poll']); $priority = intval($_POST['poll']);
if($priority > 5 || $priority < 0)
if ($priority > 5 || $priority < 0) {
$priority = 0; $priority = 0;
}
$info = escape_tags(trim($_POST['info'])); $info = escape_tags(trim($_POST['info']));
@ -212,17 +224,21 @@ function contacts_post(App $a) {
intval($contact_id), intval($contact_id),
intval(local_user()) intval(local_user())
); );
if($r) /// @TODO Decide to use dbm::is_result() here, what does $r include?
if ($r) {
info( t('Contact updated.') . EOL); info( t('Contact updated.') . EOL);
else } else {
notice( t('Failed to update contact record.') . EOL); notice( t('Failed to update contact record.') . EOL);
}
$r = q("select * from contact where id = %d and uid = %d limit 1", $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
intval($contact_id), intval($contact_id),
intval(local_user()) intval(local_user())
); );
if($r && dbm::is_result($r))
if (dbm::is_result($r)) {
$a->data['contact'] = $r[0]; $a->data['contact'] = $r[0];
}
return; return;
@ -231,40 +247,47 @@ function contacts_post(App $a) {
/*contact actions*/ /*contact actions*/
function _contact_update($contact_id) { function _contact_update($contact_id) {
$r = q("SELECT `uid`, `url`, `network` FROM `contact` WHERE `id` = %d", intval($contact_id)); $r = q("SELECT `uid`, `url`, `network` FROM `contact` WHERE `id` = %d", intval($contact_id));
if (!$r) if (!dbm::is_result($r)) {
return; return;
}
$uid = $r[0]["uid"]; $uid = $r[0]["uid"];
if ($uid != local_user()) if ($uid != local_user()) {
return; return;
}
if ($r[0]["network"] == NETWORK_OSTATUS) { if ($r[0]["network"] == NETWORK_OSTATUS) {
$result = new_contact($uid, $r[0]["url"], false); $result = new_contact($uid, $r[0]["url"], false);
if ($result['success']) if ($result['success']) {
$r = q("UPDATE `contact` SET `subhub` = 1 WHERE `id` = %d", $r = q("UPDATE `contact` SET `subhub` = 1 WHERE `id` = %d",
intval($contact_id)); intval($contact_id));
} else }
} else {
// pull feed and consume it, which should subscribe to the hub. // pull feed and consume it, which should subscribe to the hub.
proc_run(PRIORITY_HIGH, "include/onepoll.php", $contact_id, "force"); proc_run(PRIORITY_HIGH, "include/onepoll.php", $contact_id, "force");
}
} }
function _contact_update_profile($contact_id) { function _contact_update_profile($contact_id) {
$r = q("SELECT `uid`, `url`, `network` FROM `contact` WHERE `id` = %d", intval($contact_id)); $r = q("SELECT `uid`, `url`, `network` FROM `contact` WHERE `id` = %d", intval($contact_id));
if (!$r) if (!dbm::is_result($r)) {
return; return;
}
$uid = $r[0]["uid"]; $uid = $r[0]["uid"];
if ($uid != local_user()) if ($uid != local_user()) {
return; return;
}
$data = probe_url($r[0]["url"]); $data = probe_url($r[0]["url"]);
// "Feed" or "Unknown" is mostly a sign of communication problems // "Feed" or "Unknown" is mostly a sign of communication problems
if ((in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM))) AND ($data["network"] != $r[0]["network"])) if ((in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM))) AND ($data["network"] != $r[0]["network"])) {
return; return;
}
$updatefields = array("name", "nick", "url", "addr", "batch", "notify", "poll", "request", "confirm", $updatefields = array("name", "nick", "url", "addr", "batch", "notify", "poll", "request", "confirm",
"poco", "network", "alias"); "poco", "network", "alias");
@ -273,30 +296,36 @@ function _contact_update_profile($contact_id) {
if ($data["network"] == NETWORK_OSTATUS) { if ($data["network"] == NETWORK_OSTATUS) {
$result = new_contact($uid, $data["url"], false); $result = new_contact($uid, $data["url"], false);
if ($result['success']) if ($result['success']) {
$update["subhub"] = true; $update["subhub"] = true;
} }
}
foreach($updatefields AS $field) foreach ($updatefields AS $field) {
if (isset($data[$field]) AND ($data[$field] != "")) if (isset($data[$field]) AND ($data[$field] != "")) {
$update[$field] = $data[$field]; $update[$field] = $data[$field];
}
}
$update["nurl"] = normalise_link($data["url"]); $update["nurl"] = normalise_link($data["url"]);
$query = ""; $query = "";
if (isset($data["priority"]) AND ($data["priority"] != 0)) if (isset($data["priority"]) AND ($data["priority"] != 0)) {
$query = "`priority` = ".intval($data["priority"]); $query = "`priority` = ".intval($data["priority"]);
}
foreach($update AS $key => $value) { foreach ($update AS $key => $value) {
if ($query != "") if ($query != "") {
$query .= ", "; $query .= ", ";
}
$query .= "`".$key."` = '".dbesc($value)."'"; $query .= "`".$key."` = '".dbesc($value)."'";
} }
if ($query == "") if ($query == "") {
return; return;
}
$r = q("UPDATE `contact` SET $query WHERE `id` = %d AND `uid` = %d", $r = q("UPDATE `contact` SET $query WHERE `id` = %d AND `uid` = %d",
intval($contact_id), intval($contact_id),
@ -361,11 +390,12 @@ function contacts_content(App $a) {
return; return;
} }
if($a->argc == 3) { if ($a->argc == 3) {
$contact_id = intval($a->argv[1]); $contact_id = intval($a->argv[1]);
if(! $contact_id) if (! $contact_id) {
return; return;
}
$cmd = $a->argv[2]; $cmd = $a->argv[2];
@ -374,26 +404,27 @@ function contacts_content(App $a) {
intval(local_user()) intval(local_user())
); );
if(! count($orig_record)) { if (! dbm::is_result($orig_record)) {
notice( t('Could not access contact record.') . EOL); notice( t('Could not access contact record.') . EOL);
goaway('contacts'); goaway('contacts');
return; // NOTREACHED return; // NOTREACHED
} }
if($cmd === 'update') { if ($cmd === 'update') {
_contact_update($contact_id); _contact_update($contact_id);
goaway('contacts/' . $contact_id); goaway('contacts/' . $contact_id);
// NOTREACHED // NOTREACHED
} }
if($cmd === 'updateprofile') { if ($cmd === 'updateprofile') {
_contact_update_profile($contact_id); _contact_update_profile($contact_id);
goaway('crepair/' . $contact_id); goaway('crepair/' . $contact_id);
// NOTREACHED // NOTREACHED
} }
if($cmd === 'block') { if ($cmd === 'block') {
$r = _contact_block($contact_id, $orig_record[0]); $r = _contact_block($contact_id, $orig_record[0]);
/// @TODO is $r a database result?
if ($r) { if ($r) {
$blocked = (($orig_record[0]['blocked']) ? 0 : 1); $blocked = (($orig_record[0]['blocked']) ? 0 : 1);
info((($blocked) ? t('Contact has been blocked') : t('Contact has been unblocked')).EOL); info((($blocked) ? t('Contact has been blocked') : t('Contact has been unblocked')).EOL);
@ -403,8 +434,9 @@ function contacts_content(App $a) {
return; // NOTREACHED return; // NOTREACHED
} }
if($cmd === 'ignore') { if ($cmd === 'ignore') {
$r = _contact_ignore($contact_id, $orig_record[0]); $r = _contact_ignore($contact_id, $orig_record[0]);
/// @TODO is $r a database result?
if ($r) { if ($r) {
$readonly = (($orig_record[0]['readonly']) ? 0 : 1); $readonly = (($orig_record[0]['readonly']) ? 0 : 1);
info((($readonly) ? t('Contact has been ignored') : t('Contact has been unignored')).EOL); info((($readonly) ? t('Contact has been ignored') : t('Contact has been unignored')).EOL);
@ -415,8 +447,9 @@ function contacts_content(App $a) {
} }
if($cmd === 'archive') { if ($cmd === 'archive') {
$r = _contact_archive($contact_id, $orig_record[0]); $r = _contact_archive($contact_id, $orig_record[0]);
/// @TODO is $r a database result?
if ($r) { if ($r) {
$archived = (($orig_record[0]['archive']) ? 0 : 1); $archived = (($orig_record[0]['archive']) ? 0 : 1);
info((($archived) ? t('Contact has been archived') : t('Contact has been unarchived')).EOL); info((($archived) ? t('Contact has been archived') : t('Contact has been unarchived')).EOL);
@ -426,16 +459,16 @@ function contacts_content(App $a) {
return; // NOTREACHED return; // NOTREACHED
} }
if($cmd === 'drop') { if ($cmd === 'drop') {
// Check if we should do HTML-based delete confirmation // Check if we should do HTML-based delete confirmation
if($_REQUEST['confirm']) { if ($_REQUEST['confirm']) {
// <form> can't take arguments in its "action" parameter // <form> can't take arguments in its "action" parameter
// so add any arguments as hidden inputs // so add any arguments as hidden inputs
$query = explode_querystring($a->query_string); $query = explode_querystring($a->query_string);
$inputs = array(); $inputs = array();
foreach($query['args'] as $arg) { foreach ($query['args'] as $arg) {
if(strpos($arg, 'confirm=') === false) { if (strpos($arg, 'confirm=') === false) {
$arg_parts = explode('=', $arg); $arg_parts = explode('=', $arg);
$inputs[] = array('name' => $arg_parts[0], 'value' => $arg_parts[1]); $inputs[] = array('name' => $arg_parts[0], 'value' => $arg_parts[1]);
} }
@ -459,8 +492,7 @@ function contacts_content(App $a) {
if ($_REQUEST['canceled']) { if ($_REQUEST['canceled']) {
if (x($_SESSION,'return_url')) { if (x($_SESSION,'return_url')) {
goaway('' . $_SESSION['return_url']); goaway('' . $_SESSION['return_url']);
} } else {
else {
goaway('contacts'); goaway('contacts');
} }
} }
@ -469,8 +501,7 @@ function contacts_content(App $a) {
info( t('Contact has been removed.') . EOL ); info( t('Contact has been removed.') . EOL );
if (x($_SESSION,'return_url')) { if (x($_SESSION,'return_url')) {
goaway('' . $_SESSION['return_url']); goaway('' . $_SESSION['return_url']);
} } else {
else {
goaway('contacts'); goaway('contacts');
} }
return; // NOTREACHED return; // NOTREACHED
@ -484,7 +515,7 @@ function contacts_content(App $a) {
$_SESSION['return_url'] = $a->query_string; $_SESSION['return_url'] = $a->query_string;
if((x($a->data,'contact')) && (is_array($a->data['contact']))) { if ((x($a->data,'contact')) && (is_array($a->data['contact']))) {
$contact_id = $a->data['contact']['id']; $contact_id = $a->data['contact']['id'];
$contact = $a->data['contact']; $contact = $a->data['contact'];
@ -518,12 +549,12 @@ function contacts_content(App $a) {
break; break;
} }
if(!in_array($contact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) if (!in_array($contact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
$relation_text = ""; $relation_text = "";
$relation_text = sprintf($relation_text,htmlentities($contact['name'])); $relation_text = sprintf($relation_text,htmlentities($contact['name']));
if(($contact['network'] === NETWORK_DFRN) && ($contact['rel'])) { if (($contact['network'] === NETWORK_DFRN) && ($contact['rel'])) {
$url = "redir/{$contact['id']}"; $url = "redir/{$contact['id']}";
$sparkle = ' class="sparkle" '; $sparkle = ' class="sparkle" ';
} }
@ -538,7 +569,7 @@ function contacts_content(App $a) {
? t('Never') ? t('Never')
: datetime_convert('UTC',date_default_timezone_get(),$contact['last-update'],'D, j M Y, g:i A')); : datetime_convert('UTC',date_default_timezone_get(),$contact['last-update'],'D, j M Y, g:i A'));
if ($contact['last-update'] > NULL_DATE) { if ($contact['last-update'] !== NULL_DATE) {
$last_update .= ' ' . (($contact['last-update'] <= $contact['success_update']) ? t("\x28Update was successful\x29") : t("\x28Update was not successful\x29")); $last_update .= ' ' . (($contact['last-update'] <= $contact['success_update']) ? t("\x28Update was successful\x29") : t("\x28Update was not successful\x29"));
} }
$lblsuggest = (($contact['network'] === NETWORK_DFRN) ? t('Suggest friends') : ''); $lblsuggest = (($contact['network'] === NETWORK_DFRN) ? t('Suggest friends') : '');
@ -564,20 +595,22 @@ function contacts_content(App $a) {
$fetch_further_information = array('fetch_further_information', t('Fetch further information for feeds'), $contact['fetch_further_information'], t('Fetch further information for feeds'), $fetch_further_information = array('fetch_further_information', t('Fetch further information for feeds'), $contact['fetch_further_information'], t('Fetch further information for feeds'),
array('0'=>t('Disabled'), '1'=>t('Fetch information'), '2'=>t('Fetch information and keywords'))); array('0'=>t('Disabled'), '1'=>t('Fetch information'), '2'=>t('Fetch information and keywords')));
} }
if (in_array($contact['network'], array(NETWORK_FEED, NETWORK_MAIL, NETWORK_MAIL2))) if (in_array($contact['network'], array(NETWORK_FEED, NETWORK_MAIL, NETWORK_MAIL2))) {
$poll_interval = contact_poll_interval($contact['priority'],(! $poll_enabled)); $poll_interval = contact_poll_interval($contact['priority'],(! $poll_enabled));
}
if ($contact['network'] == NETWORK_DFRN) if ($contact['network'] == NETWORK_DFRN) {
$profile_select = contact_profile_assign($contact['profile-id'],(($contact['network'] !== NETWORK_DFRN) ? true : false)); $profile_select = contact_profile_assign($contact['profile-id'],(($contact['network'] !== NETWORK_DFRN) ? true : false));
}
if (in_array($contact['network'], array(NETWORK_DIASPORA, NETWORK_OSTATUS)) AND if (in_array($contact['network'], array(NETWORK_DIASPORA, NETWORK_OSTATUS)) AND
($contact['rel'] == CONTACT_IS_FOLLOWER)) ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
$follow = App::get_baseurl(true)."/follow?url=".urlencode($contact["url"]); $follow = App::get_baseurl(true)."/follow?url=".urlencode($contact["url"]);
}
// Load contactact related actions like hide, suggest, delete and others // Load contactact related actions like hide, suggest, delete and others
$contact_actions = contact_actions($contact); $contact_actions = contact_actions($contact);
$o .= replace_macros($tpl, array( $o .= replace_macros($tpl, array(
//'$header' => t('Contact Editor'), //'$header' => t('Contact Editor'),
'$header' => t("Contact"), '$header' => t("Contact"),
@ -661,28 +694,24 @@ function contacts_content(App $a) {
$ignored = false; $ignored = false;
$all = false; $all = false;
if(($a->argc == 2) && ($a->argv[1] === 'all')) { if (($a->argc == 2) && ($a->argv[1] === 'all')) {
$sql_extra = ''; $sql_extra = '';
$all = true; $all = true;
} } elseif (($a->argc == 2) && ($a->argv[1] === 'blocked')) {
elseif(($a->argc == 2) && ($a->argv[1] === 'blocked')) {
$sql_extra = " AND `blocked` = 1 "; $sql_extra = " AND `blocked` = 1 ";
$blocked = true; $blocked = true;
} } elseif (($a->argc == 2) && ($a->argv[1] === 'hidden')) {
elseif(($a->argc == 2) && ($a->argv[1] === 'hidden')) {
$sql_extra = " AND `hidden` = 1 "; $sql_extra = " AND `hidden` = 1 ";
$hidden = true; $hidden = true;
} } elseif (($a->argc == 2) && ($a->argv[1] === 'ignored')) {
elseif(($a->argc == 2) && ($a->argv[1] === 'ignored')) {
$sql_extra = " AND `readonly` = 1 "; $sql_extra = " AND `readonly` = 1 ";
$ignored = true; $ignored = true;
} } elseif (($a->argc == 2) && ($a->argv[1] === 'archived')) {
elseif(($a->argc == 2) && ($a->argv[1] === 'archived')) {
$sql_extra = " AND `archive` = 1 "; $sql_extra = " AND `archive` = 1 ";
$archived = true; $archived = true;
} } else {
else
$sql_extra = " AND `blocked` = 0 "; $sql_extra = " AND `blocked` = 0 ";
}
$search = ((x($_GET,'search')) ? notags(trim($_GET['search'])) : ''); $search = ((x($_GET,'search')) ? notags(trim($_GET['search'])) : '');
$nets = ((x($_GET,'nets')) ? notags(trim($_GET['nets'])) : ''); $nets = ((x($_GET,'nets')) ? notags(trim($_GET['nets'])) : '');
@ -754,22 +783,20 @@ function contacts_content(App $a) {
$tab_tpl = get_markup_template('common_tabs.tpl'); $tab_tpl = get_markup_template('common_tabs.tpl');
$t = replace_macros($tab_tpl, array('$tabs'=>$tabs)); $t = replace_macros($tab_tpl, array('$tabs'=>$tabs));
$searching = false; $searching = false;
if($search) { if ($search) {
$search_hdr = $search; $search_hdr = $search;
$search_txt = dbesc(protect_sprintf(preg_quote($search))); $search_txt = dbesc(protect_sprintf(preg_quote($search)));
$searching = true; $searching = true;
} }
$sql_extra .= (($searching) ? " AND (name REGEXP '$search_txt' OR url REGEXP '$search_txt' OR nick REGEXP '$search_txt') " : ""); $sql_extra .= (($searching) ? " AND (name REGEXP '$search_txt' OR url REGEXP '$search_txt' OR nick REGEXP '$search_txt') " : "");
if($nets) if ($nets) {
$sql_extra .= sprintf(" AND network = '%s' ", dbesc($nets)); $sql_extra .= sprintf(" AND network = '%s' ", dbesc($nets));
}
$sql_extra2 = ((($sort_type > 0) && ($sort_type <= CONTACT_IS_FRIEND)) ? sprintf(" AND `rel` = %d ",intval($sort_type)) : ''); $sql_extra2 = ((($sort_type > 0) && ($sort_type <= CONTACT_IS_FRIEND)) ? sprintf(" AND `rel` = %d ",intval($sort_type)) : '');
$r = q("SELECT COUNT(*) AS `total` FROM `contact` $r = q("SELECT COUNT(*) AS `total` FROM `contact`
WHERE `uid` = %d AND `self` = 0 AND `pending` = 0 $sql_extra $sql_extra2 ", WHERE `uid` = %d AND `self` = 0 AND `pending` = 0 $sql_extra $sql_extra2 ",
intval($_SESSION['uid'])); intval($_SESSION['uid']));
@ -857,23 +884,25 @@ function contacts_tab($a, $contact_id, $active_tab) {
// Show this tab only if there is visible friend list // Show this tab only if there is visible friend list
$x = count_all_friends(local_user(), $contact_id); $x = count_all_friends(local_user(), $contact_id);
if ($x) if ($x) {
$tabs[] = array('label'=>t('Contacts'), $tabs[] = array('label'=>t('Contacts'),
'url' => "allfriends/".$contact_id, 'url' => "allfriends/".$contact_id,
'sel' => (($active_tab == 3)?'active':''), 'sel' => (($active_tab == 3)?'active':''),
'title' => t('View all contacts'), 'title' => t('View all contacts'),
'id' => 'allfriends-tab', 'id' => 'allfriends-tab',
'accesskey' => 't'); 'accesskey' => 't');
}
// Show this tab only if there is visible common friend list // Show this tab only if there is visible common friend list
$common = count_common_friends(local_user(),$contact_id); $common = count_common_friends(local_user(),$contact_id);
if ($common) if ($common) {
$tabs[] = array('label'=>t('Common Friends'), $tabs[] = array('label'=>t('Common Friends'),
'url' => "common/loc/".local_user()."/".$contact_id, 'url' => "common/loc/".local_user()."/".$contact_id,
'sel' => (($active_tab == 4)?'active':''), 'sel' => (($active_tab == 4)?'active':''),
'title' => t('View all common friends'), 'title' => t('View all common friends'),
'id' => 'common-loc-tab', 'id' => 'common-loc-tab',
'accesskey' => 'd'); 'accesskey' => 'd');
}
$tabs[] = array('label' => t('Advanced'), $tabs[] = array('label' => t('Advanced'),
'url' => 'crepair/' . $contact_id, 'url' => 'crepair/' . $contact_id,
@ -891,12 +920,13 @@ function contacts_tab($a, $contact_id, $active_tab) {
function contact_posts($a, $contact_id) { function contact_posts($a, $contact_id) {
$r = q("SELECT `url` FROM `contact` WHERE `id` = %d", intval($contact_id)); $r = q("SELECT `url` FROM `contact` WHERE `id` = %d", intval($contact_id));
if ($r) { if (dbm::is_result($r)) {
$contact = $r[0]; $contact = $r[0];
$a->page['aside'] = ""; $a->page['aside'] = "";
profile_load($a, "", 0, get_contact_details_by_url($contact["url"])); profile_load($a, "", 0, get_contact_details_by_url($contact["url"]));
} else } else {
$profile = ""; $profile = "";
}
$tab_str = contacts_tab($a, $contact_id, 1); $tab_str = contacts_tab($a, $contact_id, 1);
@ -925,11 +955,10 @@ function _contact_detail_for_template($rr){
default: default:
break; break;
} }
if(($rr['network'] === NETWORK_DFRN) && ($rr['rel'])) { if (($rr['network'] === NETWORK_DFRN) && ($rr['rel'])) {
$url = "redir/{$rr['id']}"; $url = "redir/{$rr['id']}";
$sparkle = ' class="sparkle" '; $sparkle = ' class="sparkle" ';
} } else {
else {
$url = $rr['url']; $url = $rr['url'];
$sparkle = ''; $sparkle = '';
} }
@ -967,7 +996,7 @@ function contact_actions($contact) {
$contact_action = array(); $contact_action = array();
// Provide friend suggestion only for Friendica contacts // Provide friend suggestion only for Friendica contacts
if($contact['network'] === NETWORK_DFRN) { if ($contact['network'] === NETWORK_DFRN) {
$contact_actions['suggest'] = array( $contact_actions['suggest'] = array(
'label' => t('Suggest friends'), 'label' => t('Suggest friends'),
'url' => 'fsuggest/' . $contact['id'], 'url' => 'fsuggest/' . $contact['id'],
@ -977,7 +1006,7 @@ function contact_actions($contact) {
); );
} }
if($poll_enabled) { if ($poll_enabled) {
$contact_actions['update'] = array( $contact_actions['update'] = array(
'label' => t('Update now'), 'label' => t('Update now'),
'url' => 'contacts/' . $contact['id'] . '/update', 'url' => 'contacts/' . $contact['id'] . '/update',

View file

@ -38,20 +38,18 @@ function content_content(App $a, $update = 0) {
$nouveau = false; $nouveau = false;
if($a->argc > 1) { if ($a->argc > 1) {
for($x = 1; $x < $a->argc; $x ++) { for ($x = 1; $x < $a->argc; $x ++) {
if(is_a_date_arg($a->argv[$x])) { if (is_a_date_arg($a->argv[$x])) {
if($datequery) if ($datequery) {
$datequery2 = escape_tags($a->argv[$x]); $datequery2 = escape_tags($a->argv[$x]);
else { } else {
$datequery = escape_tags($a->argv[$x]); $datequery = escape_tags($a->argv[$x]);
$_GET['order'] = 'post'; $_GET['order'] = 'post';
} }
} } elseif ($a->argv[$x] === 'new') {
elseif($a->argv[$x] === 'new') {
$nouveau = true; $nouveau = true;
} } elseif (intval($a->argv[$x])) {
elseif(intval($a->argv[$x])) {
$group = intval($a->argv[$x]); $group = intval($a->argv[$x]);
$def_acl = array('allow_gid' => '<' . $group . '>'); $def_acl = array('allow_gid' => '<' . $group . '>');
} }
@ -81,12 +79,12 @@ function content_content(App $a, $update = 0) {
if(x($_GET,'search') || x($_GET,'file')) if (x($_GET,'search') || x($_GET,'file'))
$nouveau = true; $nouveau = true;
if($cid) if ($cid)
$def_acl = array('allow_cid' => '<' . intval($cid) . '>'); $def_acl = array('allow_cid' => '<' . intval($cid) . '>');
if($nets) { if ($nets) {
$r = q("select id from contact where uid = %d and network = '%s' and self = 0", $r = q("select id from contact where uid = %d and network = '%s' and self = 0",
intval(local_user()), intval(local_user()),
dbesc($nets) dbesc($nets)
@ -94,9 +92,9 @@ function content_content(App $a, $update = 0) {
$str = ''; $str = '';
if (dbm::is_result($r)) if (dbm::is_result($r))
foreach($r as $rr) foreach ($r as $rr)
$str .= '<' . $rr['id'] . '>'; $str .= '<' . $rr['id'] . '>';
if(strlen($str)) if (strlen($str))
$def_acl = array('allow_cid' => $str); $def_acl = array('allow_cid' => $str);
} }
@ -108,13 +106,13 @@ function content_content(App $a, $update = 0) {
$sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` $sql_options ) "; $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` $sql_options ) ";
if($group) { if ($group) {
$r = q("SELECT `name`, `id` FROM `group` WHERE `id` = %d AND `uid` = %d LIMIT 1", $r = q("SELECT `name`, `id` FROM `group` WHERE `id` = %d AND `uid` = %d LIMIT 1",
intval($group), intval($group),
intval($_SESSION['uid']) intval($_SESSION['uid'])
); );
if (! dbm::is_result($r)) { if (! dbm::is_result($r)) {
if($update) if ($update)
killme(); killme();
notice( t('No such group') . EOL ); notice( t('No such group') . EOL );
goaway(App::get_baseurl(true) . '/network'); goaway(App::get_baseurl(true) . '/network');
@ -122,7 +120,7 @@ function content_content(App $a, $update = 0) {
} }
$contacts = expand_groups(array($group)); $contacts = expand_groups(array($group));
if((is_array($contacts)) && count($contacts)) { if ((is_array($contacts)) && count($contacts)) {
$contact_str = implode(',',$contacts); $contact_str = implode(',',$contacts);
} }
else { else {
@ -135,7 +133,7 @@ function content_content(App $a, $update = 0) {
'$title' => sprintf( t('Group: %s'), $r[0]['name']) '$title' => sprintf( t('Group: %s'), $r[0]['name'])
)) . $o; )) . $o;
} }
elseif($cid) { elseif ($cid) {
$r = q("SELECT `id`,`name`,`network`,`writable`,`nurl` FROM `contact` WHERE `id` = %d $r = q("SELECT `id`,`name`,`network`,`writable`,`nurl` FROM `contact` WHERE `id` = %d
AND `blocked` = 0 AND `pending` = 0 LIMIT 1", AND `blocked` = 0 AND `pending` = 0 LIMIT 1",
@ -153,10 +151,10 @@ function content_content(App $a, $update = 0) {
$sql_extra3 = ''; $sql_extra3 = '';
if($datequery) { if ($datequery) {
$sql_extra3 .= protect_sprintf(sprintf(" AND item.created <= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$datequery)))); $sql_extra3 .= protect_sprintf(sprintf(" AND item.created <= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$datequery))));
} }
if($datequery2) { if ($datequery2) {
$sql_extra3 .= protect_sprintf(sprintf(" AND item.created >= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$datequery2)))); $sql_extra3 .= protect_sprintf(sprintf(" AND item.created >= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$datequery2))));
} }
@ -164,10 +162,10 @@ function content_content(App $a, $update = 0) {
$sql_extra3 = (($nouveau) ? '' : $sql_extra3); $sql_extra3 = (($nouveau) ? '' : $sql_extra3);
$sql_table = "`item`"; $sql_table = "`item`";
if(x($_GET,'search')) { if (x($_GET,'search')) {
$search = escape_tags($_GET['search']); $search = escape_tags($_GET['search']);
if(strpos($search,'#') === 0) { if (strpos($search,'#') === 0) {
$tag = true; $tag = true;
$search = substr($search,1); $search = substr($search,1);
} }
@ -175,7 +173,7 @@ function content_content(App $a, $update = 0) {
if (get_config('system','only_tag_search')) if (get_config('system','only_tag_search'))
$tag = true; $tag = true;
if($tag) { if ($tag) {
//$sql_extra = sprintf(" AND `term`.`term` = '%s' AND `term`.`otype` = %d AND `term`.`type` = %d ", //$sql_extra = sprintf(" AND `term`.`term` = '%s' AND `term`.`otype` = %d AND `term`.`type` = %d ",
// dbesc(protect_sprintf($search)), intval(TERM_OBJ_POST), intval(TERM_HASHTAG)); // dbesc(protect_sprintf($search)), intval(TERM_OBJ_POST), intval(TERM_HASHTAG));
//$sql_table = "`term` INNER JOIN `item` ON `item`.`id` = `term`.`oid` AND `item`.`uid` = `term`.`uid` "; //$sql_table = "`term` INNER JOIN `item` ON `item`.`id` = `term`.`oid` AND `item`.`uid` = `term`.`uid` ";
@ -192,11 +190,11 @@ function content_content(App $a, $update = 0) {
} }
} }
if(strlen($file)) { if (strlen($file)) {
$sql_extra .= file_tag_file_query('item',unxmlify($file)); $sql_extra .= file_tag_file_query('item',unxmlify($file));
} }
if($conv) { if ($conv) {
$myurl = App::get_baseurl() . '/profile/'. $a->user['nickname']; $myurl = App::get_baseurl() . '/profile/'. $a->user['nickname'];
$myurl = substr($myurl,strpos($myurl,'://')+3); $myurl = substr($myurl,strpos($myurl,'://')+3);
$myurl = str_replace('www.','',$myurl); $myurl = str_replace('www.','',$myurl);
@ -211,7 +209,7 @@ function content_content(App $a, $update = 0) {
$pager_sql = sprintf(" LIMIT %d, %d ",intval($a->pager['start']), intval($a->pager['itemspage'])); $pager_sql = sprintf(" LIMIT %d, %d ",intval($a->pager['start']), intval($a->pager['itemspage']));
if($nouveau) { if ($nouveau) {
// "New Item View" - show all items unthreaded in reverse created date order // "New Item View" - show all items unthreaded in reverse created date order
$items = q("SELECT `item`.*, `item`.`id` AS `item_id`, $items = q("SELECT `item`.*, `item`.`id` AS `item_id`,
@ -234,7 +232,7 @@ function content_content(App $a, $update = 0) {
// Normal conversation view // Normal conversation view
if($order === 'post') if ($order === 'post')
$ordering = "`created`"; $ordering = "`created`";
else else
$ordering = "`commented`"; $ordering = "`commented`";
@ -260,8 +258,8 @@ function content_content(App $a, $update = 0) {
$parents_str = ''; $parents_str = '';
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach($r as $rr) foreach ($r as $rr)
if(! in_array($rr['item_id'],$parents_arr)) if (! in_array($rr['item_id'],$parents_arr))
$parents_arr[] = $rr['item_id']; $parents_arr[] = $rr['item_id'];
$parents_str = implode(', ', $parents_arr); $parents_str = implode(', ', $parents_arr);
@ -328,32 +326,32 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
); );
} }
if($mode === 'network') { if ($mode === 'network') {
$profile_owner = local_user(); $profile_owner = local_user();
$page_writeable = true; $page_writeable = true;
} }
if($mode === 'profile') { if ($mode === 'profile') {
$profile_owner = $a->profile['profile_uid']; $profile_owner = $a->profile['profile_uid'];
$page_writeable = can_write_wall($a,$profile_owner); $page_writeable = can_write_wall($a,$profile_owner);
} }
if($mode === 'notes') { if ($mode === 'notes') {
$profile_owner = local_user(); $profile_owner = local_user();
$page_writeable = true; $page_writeable = true;
} }
if($mode === 'display') { if ($mode === 'display') {
$profile_owner = $a->profile['uid']; $profile_owner = $a->profile['uid'];
$page_writeable = can_write_wall($a,$profile_owner); $page_writeable = can_write_wall($a,$profile_owner);
} }
if($mode === 'community') { if ($mode === 'community') {
$profile_owner = 0; $profile_owner = 0;
$page_writeable = false; $page_writeable = false;
} }
if($update) if ($update)
$return_url = $_SESSION['return_url']; $return_url = $_SESSION['return_url'];
else else
$return_url = $_SESSION['return_url'] = $a->query_string; $return_url = $_SESSION['return_url'] = $a->query_string;
@ -378,9 +376,9 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$threads = array(); $threads = array();
$threadsid = -1; $threadsid = -1;
if($items && count($items)) { if ($items && count($items)) {
if($mode === 'network-new' || $mode === 'search' || $mode === 'community') { if ($mode === 'network-new' || $mode === 'search' || $mode === 'community') {
// "New Item View" on network page or search page results // "New Item View" on network page or search page results
// - just loop through the items and format them minimally for display // - just loop through the items and format them minimally for display
@ -388,7 +386,7 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
//$tpl = get_markup_template('search_item.tpl'); //$tpl = get_markup_template('search_item.tpl');
$tpl = 'search_item.tpl'; $tpl = 'search_item.tpl';
foreach($items as $item) { foreach ($items as $item) {
$threadsid++; $threadsid++;
$comment = ''; $comment = '';
@ -397,8 +395,8 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$owner_name = ''; $owner_name = '';
$sparkle = ''; $sparkle = '';
if($mode === 'search' || $mode === 'community') { if ($mode === 'search' || $mode === 'community') {
if(((activity_match($item['verb'],ACTIVITY_LIKE)) if (((activity_match($item['verb'],ACTIVITY_LIKE))
|| (activity_match($item['verb'],ACTIVITY_DISLIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE))
|| activity_match($item['verb'],ACTIVITY_ATTEND) || activity_match($item['verb'],ACTIVITY_ATTEND)
|| activity_match($item['verb'],ACTIVITY_ATTENDNO) || activity_match($item['verb'],ACTIVITY_ATTENDNO)
@ -411,20 +409,20 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$nickname = $a->user['nickname']; $nickname = $a->user['nickname'];
// prevent private email from leaking. // prevent private email from leaking.
if($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid'])
continue; continue;
$profile_name = ((strlen($item['author-name'])) ? $item['author-name'] : $item['name']); $profile_name = ((strlen($item['author-name'])) ? $item['author-name'] : $item['name']);
if($item['author-link'] && (! $item['author-name'])) if ($item['author-link'] && (! $item['author-name']))
$profile_name = $item['author-link']; $profile_name = $item['author-link'];
$sp = false; $sp = false;
$profile_link = best_link_url($item,$sp); $profile_link = best_link_url($item,$sp);
if($profile_link === 'mailbox') if ($profile_link === 'mailbox')
$profile_link = ''; $profile_link = '';
if($sp) if ($sp)
$sparkle = ' sparkle'; $sparkle = ' sparkle';
else else
$profile_link = zrl($profile_link); $profile_link = zrl($profile_link);
@ -442,7 +440,7 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate)); $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
localize_item($item); localize_item($item);
if($mode === 'network-new') if ($mode === 'network-new')
$dropping = true; $dropping = true;
else else
$dropping = false; $dropping = false;
@ -463,7 +461,7 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$body = prepare_body($item,true); $body = prepare_body($item,true);
if($a->theme['template_engine'] === 'internal') { if ($a->theme['template_engine'] === 'internal') {
$name_e = template_escape($profile_name); $name_e = template_escape($profile_name);
$title_e = template_escape($item['title']); $title_e = template_escape($item['title']);
$body_e = template_escape($body); $body_e = template_escape($body);
@ -534,20 +532,20 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
// Store the result in the $comments array // Store the result in the $comments array
$comments = array(); $comments = array();
foreach($items as $item) { foreach ($items as $item) {
if((intval($item['gravity']) == 6) && ($item['id'] != $item['parent'])) { if ((intval($item['gravity']) == 6) && ($item['id'] != $item['parent'])) {
if(! x($comments,$item['parent'])) if (! x($comments,$item['parent']))
$comments[$item['parent']] = 1; $comments[$item['parent']] = 1;
else else
$comments[$item['parent']] += 1; $comments[$item['parent']] += 1;
} elseif(! x($comments,$item['parent'])) } elseif (! x($comments,$item['parent']))
$comments[$item['parent']] = 0; // avoid notices later on $comments[$item['parent']] = 0; // avoid notices later on
} }
// map all the like/dislike/attendance activities for each parent item // map all the like/dislike/attendance activities for each parent item
// Store these in the $alike and $dlike arrays // Store these in the $alike and $dlike arrays
foreach($items as $item) { foreach ($items as $item) {
builtin_activity_puller($item, $conv_responses); builtin_activity_puller($item, $conv_responses);
} }
@ -559,7 +557,7 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$blowhard_count = 0; $blowhard_count = 0;
foreach($items as $item) { foreach ($items as $item) {
$comment = ''; $comment = '';
$template = $tpl; $template = $tpl;
@ -569,7 +567,7 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
// We've already parsed out like/dislike for special treatment. We can ignore them now // We've already parsed out like/dislike for special treatment. We can ignore them now
if(((activity_match($item['verb'],ACTIVITY_LIKE)) if (((activity_match($item['verb'],ACTIVITY_LIKE))
|| (activity_match($item['verb'],ACTIVITY_DISLIKE) || (activity_match($item['verb'],ACTIVITY_DISLIKE)
|| activity_match($item['verb'],ACTIVITY_ATTEND) || activity_match($item['verb'],ACTIVITY_ATTEND)
|| activity_match($item['verb'],ACTIVITY_ATTENDNO) || activity_match($item['verb'],ACTIVITY_ATTENDNO)
@ -585,7 +583,7 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
// If a single author has more than 3 consecutive top-level posts, squash the remaining ones. // If a single author has more than 3 consecutive top-level posts, squash the remaining ones.
// If there are more than two comments, squash all but the last 2. // If there are more than two comments, squash all but the last 2.
if($toplevelpost) { if ($toplevelpost) {
$item_writeable = (($item['writable'] || $item['self']) ? true : false); $item_writeable = (($item['writable'] || $item['self']) ? true : false);
@ -603,7 +601,7 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
else { else {
// prevent private email reply to public conversation from leaking. // prevent private email reply to public conversation from leaking.
if($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid'])
continue; continue;
$comments_seen ++; $comments_seen ++;
@ -615,7 +613,7 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$show_comment_box = ((($page_writeable) && ($item_writeable) && ($comments_seen == $comments[$item['parent']])) ? true : false); $show_comment_box = ((($page_writeable) && ($item_writeable) && ($comments_seen == $comments[$item['parent']])) ? true : false);
if(($comments[$item['parent']] > 2) && ($comments_seen <= ($comments[$item['parent']] - 2)) && ($item['gravity'] == 6)) { if (($comments[$item['parent']] > 2) && ($comments_seen <= ($comments[$item['parent']] - 2)) && ($item['gravity'] == 6)) {
if (!$comments_collapsed){ if (!$comments_collapsed){
$threads[$threadsid]['num_comments'] = sprintf( tt('%d comment','%d comments',$comments[$item['parent']]),$comments[$item['parent']] ); $threads[$threadsid]['num_comments'] = sprintf( tt('%d comment','%d comments',$comments[$item['parent']]),$comments[$item['parent']] );
@ -626,7 +624,7 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$comment_firstcollapsed = true; $comment_firstcollapsed = true;
} }
} }
if(($comments[$item['parent']] > 2) && ($comments_seen == ($comments[$item['parent']] - 1))) { if (($comments[$item['parent']] > 2) && ($comments_seen == ($comments[$item['parent']] - 1))) {
$comment_lastcollapsed = true; $comment_lastcollapsed = true;
} }
@ -644,9 +642,9 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$osparkle = ''; $osparkle = '';
if(($toplevelpost) && (! $item['self']) && ($mode !== 'profile')) { if (($toplevelpost) && (! $item['self']) && ($mode !== 'profile')) {
if($item['wall']) { if ($item['wall']) {
// On the network page, I am the owner. On the display page it will be the profile owner. // On the network page, I am the owner. On the display page it will be the profile owner.
// This will have been stored in $a->page_contact by our calling page. // This will have been stored in $a->page_contact by our calling page.
@ -659,12 +657,12 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$commentww = 'ww'; $commentww = 'ww';
} }
if((! $item['wall']) && $item['owner-link']) { if ((! $item['wall']) && $item['owner-link']) {
$owner_linkmatch = (($item['owner-link']) && link_compare($item['owner-link'],$item['author-link'])); $owner_linkmatch = (($item['owner-link']) && link_compare($item['owner-link'],$item['author-link']));
$alias_linkmatch = (($item['alias']) && link_compare($item['alias'],$item['author-link'])); $alias_linkmatch = (($item['alias']) && link_compare($item['alias'],$item['author-link']));
$owner_namematch = (($item['owner-name']) && $item['owner-name'] == $item['author-name']); $owner_namematch = (($item['owner-name']) && $item['owner-name'] == $item['author-name']);
if((! $owner_linkmatch) && (! $alias_linkmatch) && (! $owner_namematch)) { if ((! $owner_linkmatch) && (! $alias_linkmatch) && (! $owner_namematch)) {
// The author url doesn't match the owner (typically the contact) // The author url doesn't match the owner (typically the contact)
// and also doesn't match the contact alias. // and also doesn't match the contact alias.
@ -682,7 +680,7 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$template = $wallwall; $template = $wallwall;
$commentww = 'ww'; $commentww = 'ww';
// If it is our contact, use a friendly redirect link // If it is our contact, use a friendly redirect link
if((link_compare($item['owner-link'],$item['url'])) if ((link_compare($item['owner-link'],$item['url']))
&& ($item['network'] === NETWORK_DFRN)) { && ($item['network'] === NETWORK_DFRN)) {
$owner_url = $redirect_url; $owner_url = $redirect_url;
$osparkle = ' sparkle'; $osparkle = ' sparkle';
@ -696,8 +694,8 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$likebuttons = ''; $likebuttons = '';
$shareable = ((($profile_owner == local_user()) && ($item['private'] != 1)) ? true : false); $shareable = ((($profile_owner == local_user()) && ($item['private'] != 1)) ? true : false);
if($page_writeable) { if ($page_writeable) {
/* if($toplevelpost) { */ /* if ($toplevelpost) { */
$likebuttons = array( $likebuttons = array(
'like' => array( t("I like this \x28toggle\x29"), t("like")), 'like' => array( t("I like this \x28toggle\x29"), t("like")),
'dislike' => array( t("I don't like this \x28toggle\x29"), t("dislike")), 'dislike' => array( t("I don't like this \x28toggle\x29"), t("dislike")),
@ -707,12 +705,12 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$qc = $qcomment = null; $qc = $qcomment = null;
if(in_array('qcomment',$a->plugins)) { if (in_array('qcomment',$a->plugins)) {
$qc = ((local_user()) ? get_pconfig(local_user(),'qcomment','words') : null); $qc = ((local_user()) ? get_pconfig(local_user(),'qcomment','words') : null);
$qcomment = (($qc) ? explode("\n",$qc) : null); $qcomment = (($qc) ? explode("\n",$qc) : null);
} }
if(($show_comment_box) || (($show_comment_box == false) && ($override_comment_box == false) && ($item['last-child']))) { if (($show_comment_box) || (($show_comment_box == false) && ($override_comment_box == false) && ($item['last-child']))) {
$comment = replace_macros($cmnt_tpl,array( $comment = replace_macros($cmnt_tpl,array(
'$return_path' => '', '$return_path' => '',
'$jsreload' => (($mode === 'display') ? $_SESSION['return_url'] : ''), '$jsreload' => (($mode === 'display') ? $_SESSION['return_url'] : ''),
@ -751,7 +749,7 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$drop = ''; $drop = '';
$dropping = false; $dropping = false;
if((intval($item['contact-id']) && $item['contact-id'] == remote_user()) || ($item['uid'] == local_user())) if ((intval($item['contact-id']) && $item['contact-id'] == remote_user()) || ($item['uid'] == local_user()))
$dropping = true; $dropping = true;
$drop = array( $drop = array(
@ -815,7 +813,7 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$profile_name = (((strlen($item['author-name'])) && $diff_author) ? $item['author-name'] : $item['name']); $profile_name = (((strlen($item['author-name'])) && $diff_author) ? $item['author-name'] : $item['name']);
if($item['author-link'] && (! $item['author-name'])) if ($item['author-link'] && (! $item['author-name']))
$profile_name = $item['author-link']; $profile_name = $item['author-link'];
$sp = false; $sp = false;
@ -842,13 +840,14 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
// process action responses - e.g. like/dislike/attend/agree/whatever // process action responses - e.g. like/dislike/attend/agree/whatever
$response_verbs = array('like'); $response_verbs = array('like');
if(feature_enabled($profile_owner,'dislike')) if (feature_enabled($profile_owner,'dislike')) {
$response_verbs[] = 'dislike'; $response_verbs[] = 'dislike';
if($item['object-type'] === ACTIVITY_OBJ_EVENT) { }
if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
$response_verbs[] = 'attendyes'; $response_verbs[] = 'attendyes';
$response_verbs[] = 'attendno'; $response_verbs[] = 'attendno';
$response_verbs[] = 'attendmaybe'; $response_verbs[] = 'attendmaybe';
if($page_writeable) { if ($page_writeable) {
$isevent = true; $isevent = true;
$attend = array( t('I will attend'), t('I will not attend'), t('I might attend')); $attend = array( t('I will attend'), t('I will not attend'), t('I might attend'));
} }
@ -863,17 +862,20 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$indent = (($toplevelpost) ? '' : ' comment'); $indent = (($toplevelpost) ? '' : ' comment');
$shiny = ""; $shiny = "";
if(strcmp(datetime_convert('UTC','UTC',$item['created']),datetime_convert('UTC','UTC','now - 12 hours')) > 0) if (strcmp(datetime_convert('UTC','UTC',$item['created']),datetime_convert('UTC','UTC','now - 12 hours')) > 0) {
$shiny = 'shiny'; $shiny = 'shiny';
}
// //
localize_item($item); localize_item($item);
$tags=array(); $tags=array();
foreach(explode(',',$item['tag']) as $tag){ foreach (explode(',',$item['tag']) as $tag){
$tag = trim($tag); $tag = trim($tag);
if ($tag!="") $tags[] = bbcode($tag); if ($tag!="") {
$tags[] = bbcode($tag);
}
} }
// Build the HTML // Build the HTML
@ -881,15 +883,14 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$body = prepare_body($item,true); $body = prepare_body($item,true);
//$tmp_item = replace_macros($template, //$tmp_item = replace_macros($template,
if($a->theme['template_engine'] === 'internal') { if ($a->theme['template_engine'] === 'internal') {
$body_e = template_escape($body); $body_e = template_escape($body);
$text_e = strip_tags(template_escape($body)); $text_e = strip_tags(template_escape($body));
$name_e = template_escape($profile_name); $name_e = template_escape($profile_name);
$title_e = template_escape($item['title']); $title_e = template_escape($item['title']);
$location_e = template_escape($location); $location_e = template_escape($location);
$owner_name_e = template_escape($owner_name); $owner_name_e = template_escape($owner_name);
} } else {
else {
$body_e = $body; $body_e = $body;
$text_e = strip_tags($body); $text_e = strip_tags($body);
$name_e = $profile_name; $name_e = $profile_name;

View file

@ -9,7 +9,7 @@ function crepair_init(App $a) {
$contact_id = 0; $contact_id = 0;
if(($a->argc == 2) && intval($a->argv[1])) { if (($a->argc == 2) && intval($a->argv[1])) {
$contact_id = intval($a->argv[1]); $contact_id = intval($a->argv[1]);
$r = q("SELECT * FROM `contact` WHERE `uid` = %d and `id` = %d LIMIT 1", $r = q("SELECT * FROM `contact` WHERE `uid` = %d and `id` = %d LIMIT 1",
intval(local_user()), intval(local_user()),
@ -20,10 +20,11 @@ function crepair_init(App $a) {
} }
} }
if(! x($a->page,'aside')) if (! x($a->page,'aside')) {
$a->page['aside'] = ''; $a->page['aside'] = '';
}
if($contact_id) { if ($contact_id) {
$a->data['contact'] = $r[0]; $a->data['contact'] = $r[0];
$contact = $r[0]; $contact = $r[0];
profile_load($a, "", 0, get_contact_details_by_url($contact["url"])); profile_load($a, "", 0, get_contact_details_by_url($contact["url"]));
@ -35,9 +36,12 @@ function crepair_post(App $a) {
return; return;
} }
// Init $r here if $cid is not set
$r = false;
$cid = (($a->argc > 1) ? intval($a->argv[1]) : 0); $cid = (($a->argc > 1) ? intval($a->argv[1]) : 0);
if($cid) { if ($cid) {
$r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1", $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
intval($cid), intval($cid),
intval(local_user()) intval(local_user())
@ -78,18 +82,18 @@ function crepair_post(App $a) {
local_user() local_user()
); );
if($photo) { if ($photo) {
logger('mod-crepair: updating photo from ' . $photo); logger('mod-crepair: updating photo from ' . $photo);
require_once("include/Photo.php"); require_once("include/Photo.php");
update_contact_avatar($photo,local_user(),$contact['id']); update_contact_avatar($photo,local_user(),$contact['id']);
} }
if($r) if ($r) {
info( t('Contact settings applied.') . EOL); info( t('Contact settings applied.') . EOL);
else } else {
notice( t('Contact update failed.') . EOL); notice( t('Contact update failed.') . EOL);
}
return; return;
} }
@ -105,7 +109,7 @@ function crepair_content(App $a) {
$cid = (($a->argc > 1) ? intval($a->argv[1]) : 0); $cid = (($a->argc > 1) ? intval($a->argv[1]) : 0);
if($cid) { if ($cid) {
$r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1", $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
intval($cid), intval($cid),
intval(local_user()) intval(local_user())

View file

@ -23,16 +23,16 @@ function delegate_content(App $a) {
$id = $a->argv[2]; $id = $a->argv[2];
$r = q("select `nickname` from user where uid = %d limit 1", $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
intval($id) intval($id)
); );
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
$r = q("select id from contact where uid = %d and nurl = '%s' limit 1", $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
intval(local_user()), intval(local_user()),
dbesc(normalise_link(App::get_baseurl() . '/profile/' . $r[0]['nickname'])) dbesc(normalise_link(App::get_baseurl() . '/profile/' . $r[0]['nickname']))
); );
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
q("insert into manage ( uid, mid ) values ( %d , %d ) ", q("INSERT INTO `manage` ( `uid`, `mid` ) VALUES ( %d , %d ) ",
intval($a->argv[2]), intval($a->argv[2]),
intval(local_user()) intval(local_user())
); );
@ -64,34 +64,40 @@ function delegate_content(App $a) {
dbesc($a->user['email']), dbesc($a->user['email']),
dbesc($a->user['password']) dbesc($a->user['password'])
); );
if (dbm::is_result($r)) if (dbm::is_result($r)) {
$full_managers = $r; $full_managers = $r;
}
$delegates = array(); $delegates = array();
// find everybody that currently has delegated management to this account/page // find everybody that currently has delegated management to this account/page
$r = q("select * from user where uid in ( select uid from manage where mid = %d ) ", $r = q("SELECT * FROM `user` WHERE `uid` IN ( SELECT `uid` FROM `manage` WHERE `mid` = %d ) ",
intval(local_user()) intval(local_user())
); );
if (dbm::is_result($r)) if (dbm::is_result($r)) {
$delegates = $r; $delegates = $r;
}
$uids = array(); $uids = array();
if(count($full_managers)) if (count($full_managers)) {
foreach($full_managers as $rr) foreach ($full_managers as $rr) {
$uids[] = $rr['uid']; $uids[] = $rr['uid'];
}
}
if(count($delegates)) if (count($delegates)) {
foreach($delegates as $rr) foreach ($delegates as $rr) {
$uids[] = $rr['uid']; $uids[] = $rr['uid'];
}
}
// find every contact who might be a candidate for delegation // find every contact who might be a candidate for delegation
$r = q("select nurl from contact where substring_index(contact.nurl,'/',3) = '%s' $r = q("SELECT `nurl` FROM `contact` WHERE SUBSTRING_INDEX(`contact`.`nurl`,'/',3) = '%s'
and contact.uid = %d and contact.self = 0 and network = '%s' ", AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `network` = '%s' ",
dbesc(normalise_link(App::get_baseurl())), dbesc(normalise_link(App::get_baseurl())),
intval(local_user()), intval(local_user()),
dbesc(NETWORK_DFRN) dbesc(NETWORK_DFRN)
@ -116,12 +122,15 @@ function delegate_content(App $a) {
// get user records for all potential page delegates who are not already delegates or managers // get user records for all potential page delegates who are not already delegates or managers
$r = q("select `uid`, `username`, `nickname` from user where nickname in ( $nicks )"); $r = q("SELECT `uid`, `username`, `nickname` FROM `user` WHERE `nickname` IN ( $nicks )");
if (dbm::is_result($r)) if (dbm::is_result($r)) {
foreach($r as $rr) foreach ($r as $rr) {
if(! in_array($rr['uid'],$uids)) if (! in_array($rr['uid'],$uids)) {
$potentials[] = $rr; $potentials[] = $rr;
}
}
}
require_once("mod/settings.php"); require_once("mod/settings.php");
settings_init($a); settings_init($a);

View file

@ -24,7 +24,7 @@ require_once('include/Probe.php');
function dfrn_confirm_post(App $a, $handsfree = null) { function dfrn_confirm_post(App $a, $handsfree = null) {
if(is_array($handsfree)) { if (is_array($handsfree)) {
/* /*
* We were called directly from dfrn_request due to automatic friend acceptance. * We were called directly from dfrn_request due to automatic friend acceptance.
@ -37,7 +37,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
} }
else { else {
if($a->argc > 1) if ($a->argc > 1)
$node = $a->argv[1]; $node = $a->argv[1];
} }
@ -53,11 +53,11 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
* *
*/ */
if(! x($_POST,'source_url')) { if (! x($_POST,'source_url')) {
$uid = ((is_array($handsfree)) ? $handsfree['uid'] : local_user()); $uid = ((is_array($handsfree)) ? $handsfree['uid'] : local_user());
if(! $uid) { if (! $uid) {
notice( t('Permission denied.') . EOL ); notice( t('Permission denied.') . EOL );
return; return;
} }
@ -66,7 +66,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
intval($uid) intval($uid)
); );
if(! $user) { if (! $user) {
notice( t('Profile not found.') . EOL ); notice( t('Profile not found.') . EOL );
return; return;
} }
@ -74,7 +74,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
// These data elements may come from either the friend request notification form or $handsfree array. // These data elements may come from either the friend request notification form or $handsfree array.
if(is_array($handsfree)) { if (is_array($handsfree)) {
logger('Confirm in handsfree mode'); logger('Confirm in handsfree mode');
$dfrn_id = $handsfree['dfrn_id']; $dfrn_id = $handsfree['dfrn_id'];
$intro_id = $handsfree['intro_id']; $intro_id = $handsfree['intro_id'];
@ -99,11 +99,11 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
* *
*/ */
if(strlen($dfrn_id)) if (strlen($dfrn_id))
$cid = 0; $cid = 0;
logger('Confirming request for dfrn_id (issued) ' . $dfrn_id); logger('Confirming request for dfrn_id (issued) ' . $dfrn_id);
if($cid) if ($cid)
logger('Confirming follower with contact_id: ' . $cid); logger('Confirming follower with contact_id: ' . $cid);
@ -138,10 +138,10 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
$network = ((strlen($contact['issued-id'])) ? NETWORK_DFRN : NETWORK_OSTATUS); $network = ((strlen($contact['issued-id'])) ? NETWORK_DFRN : NETWORK_OSTATUS);
if($contact['network']) if ($contact['network'])
$network = $contact['network']; $network = $contact['network'];
if($network === NETWORK_DFRN) { if ($network === NETWORK_DFRN) {
/* /*
* *
@ -199,19 +199,19 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey); openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
$params['source_url'] = bin2hex($params['source_url']); $params['source_url'] = bin2hex($params['source_url']);
if($aes_allow && function_exists('openssl_encrypt')) { if ($aes_allow && function_exists('openssl_encrypt')) {
openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey); openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
$params['aes_key'] = bin2hex($params['aes_key']); $params['aes_key'] = bin2hex($params['aes_key']);
$params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key)); $params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key));
} }
$params['dfrn_version'] = DFRN_PROTOCOL_VERSION ; $params['dfrn_version'] = DFRN_PROTOCOL_VERSION ;
if($duplex == 1) if ($duplex == 1)
$params['duplex'] = 1; $params['duplex'] = 1;
if($user[0]['page-flags'] == PAGE_COMMUNITY) if ($user[0]['page-flags'] == PAGE_COMMUNITY)
$params['page'] = 1; $params['page'] = 1;
if($user[0]['page-flags'] == PAGE_PRVGROUP) if ($user[0]['page-flags'] == PAGE_PRVGROUP)
$params['page'] = 2; $params['page'] = 2;
logger('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params,true), LOGGER_DATA); logger('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params,true), LOGGER_DATA);
@ -234,7 +234,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
$leading_junk = substr($res,0,strpos($res,'<?xml')); $leading_junk = substr($res,0,strpos($res,'<?xml'));
$res = substr($res,strpos($res,'<?xml')); $res = substr($res,strpos($res,'<?xml'));
if(! strlen($res)) { if (! strlen($res)) {
// No XML at all, this exchange is messed up really bad. // No XML at all, this exchange is messed up really bad.
// We shouldn't proceed, because the xml parser might choke, // We shouldn't proceed, because the xml parser might choke,
@ -245,7 +245,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
return; return;
} }
if(strlen($leading_junk) && get_config('system','debugging')) { if (strlen($leading_junk) && get_config('system','debugging')) {
// This might be more common. Mixed error text and some XML. // This might be more common. Mixed error text and some XML.
// If we're configured for debugging, show the text. Proceed in either case. // If we're configured for debugging, show the text. Proceed in either case.
@ -253,7 +253,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL ); notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
} }
if(stristr($res, "<status")===false) { if (stristr($res, "<status")===false) {
// wrong xml! stop here! // wrong xml! stop here!
notice( t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL ); notice( t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL );
return; return;
@ -265,7 +265,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
switch($status) { switch($status) {
case 0: case 0:
info( t("Confirmation completed successfully.") . EOL); info( t("Confirmation completed successfully.") . EOL);
if(strlen($message)) if (strlen($message))
notice( t('Remote site reported: ') . $message . EOL); notice( t('Remote site reported: ') . $message . EOL);
break; break;
case 1: case 1:
@ -279,19 +279,19 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
case 2: case 2:
notice( t("Temporary failure. Please wait and try again.") . EOL); notice( t("Temporary failure. Please wait and try again.") . EOL);
if(strlen($message)) if (strlen($message))
notice( t('Remote site reported: ') . $message . EOL); notice( t('Remote site reported: ') . $message . EOL);
break; break;
case 3: case 3:
notice( t("Introduction failed or was revoked.") . EOL); notice( t("Introduction failed or was revoked.") . EOL);
if(strlen($message)) if (strlen($message))
notice( t('Remote site reported: ') . $message . EOL); notice( t('Remote site reported: ') . $message . EOL);
break; break;
} }
if(($status == 0) && ($intro_id)) { if (($status == 0) && ($intro_id)) {
// Success. Delete the notification. // Success. Delete the notification.
@ -302,7 +302,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
} }
if($status != 0) if ($status != 0)
return; return;
} }
@ -323,13 +323,13 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
logger('dfrn_confirm: confirm - imported photos'); logger('dfrn_confirm: confirm - imported photos');
if($network === NETWORK_DFRN) { if ($network === NETWORK_DFRN) {
$new_relation = CONTACT_IS_FOLLOWER; $new_relation = CONTACT_IS_FOLLOWER;
if(($relation == CONTACT_IS_SHARING) || ($duplex)) if (($relation == CONTACT_IS_SHARING) || ($duplex))
$new_relation = CONTACT_IS_FRIEND; $new_relation = CONTACT_IS_FRIEND;
if(($relation == CONTACT_IS_SHARING) && ($duplex)) if (($relation == CONTACT_IS_SHARING) && ($duplex))
$duplex = 0; $duplex = 0;
$r = q("UPDATE `contact` SET `rel` = %d, $r = q("UPDATE `contact` SET `rel` = %d,
@ -349,8 +349,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
dbesc(NETWORK_DFRN), dbesc(NETWORK_DFRN),
intval($contact_id) intval($contact_id)
); );
} } else {
else {
// $network !== NETWORK_DFRN // $network !== NETWORK_DFRN
@ -358,13 +357,13 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
$notify = (($contact['notify']) ? $contact['notify'] : ''); $notify = (($contact['notify']) ? $contact['notify'] : '');
$poll = (($contact['poll']) ? $contact['poll'] : ''); $poll = (($contact['poll']) ? $contact['poll'] : '');
if((! $contact['notify']) || (! $contact['poll'])) { if ((! $contact['notify']) || (! $contact['poll'])) {
$arr = Probe::lrdd($contact['url']); $arr = Probe::lrdd($contact['url']);
if(count($arr)) { if (count($arr)) {
foreach($arr as $link) { foreach ($arr as $link) {
if($link['@attributes']['rel'] === 'salmon') if ($link['@attributes']['rel'] === 'salmon')
$notify = $link['@attributes']['href']; $notify = $link['@attributes']['href'];
if($link['@attributes']['rel'] === NAMESPACE_FEED) if ($link['@attributes']['rel'] === NAMESPACE_FEED)
$poll = $link['@attributes']['href']; $poll = $link['@attributes']['href'];
} }
} }
@ -373,13 +372,13 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
$new_relation = $contact['rel']; $new_relation = $contact['rel'];
$writable = $contact['writable']; $writable = $contact['writable'];
if($network === NETWORK_DIASPORA) { if ($network === NETWORK_DIASPORA) {
if($duplex) if ($duplex)
$new_relation = CONTACT_IS_FRIEND; $new_relation = CONTACT_IS_FRIEND;
else else
$new_relation = CONTACT_IS_FOLLOWER; $new_relation = CONTACT_IS_FOLLOWER;
if($new_relation != CONTACT_IS_FOLLOWER) if ($new_relation != CONTACT_IS_FOLLOWER)
$writable = 1; $writable = 1;
} }
@ -444,7 +443,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
intval($uid) intval($uid)
); );
if((dbm::is_result($r)) && ($r[0]['hide-friends'] == 0) && ($activity) && (! $hidden)) { if ((dbm::is_result($r)) && ($r[0]['hide-friends'] == 0) && ($activity) && (! $hidden)) {
require_once('include/items.php'); require_once('include/items.php');
@ -452,7 +451,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
intval($uid) intval($uid)
); );
if(count($self)) { if (count($self)) {
$arr = array(); $arr = array();
$arr['guid'] = get_guid(32); $arr['guid'] = get_guid(32);
@ -491,14 +490,14 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
$arr['deny_gid'] = $user[0]['deny_gid']; $arr['deny_gid'] = $user[0]['deny_gid'];
$i = item_store($arr); $i = item_store($arr);
if($i) if ($i)
proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i); proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
} }
} }
} }
$def_gid = get_default_group($uid, $contact["network"]); $def_gid = get_default_group($uid, $contact["network"]);
if($contact && intval($def_gid)) if ($contact && intval($def_gid))
group_add_member($uid, '', $contact['id'], $def_gid); group_add_member($uid, '', $contact['id'], $def_gid);
// Let's send our user to the contact editor in case they want to // Let's send our user to the contact editor in case they want to
@ -565,7 +564,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
$local_uid = $r[0]['uid']; $local_uid = $r[0]['uid'];
if(! strstr($my_prvkey,'PRIVATE KEY')) { if (! strstr($my_prvkey,'PRIVATE KEY')) {
$message = t('Our site encryption key is apparently messed up.'); $message = t('Our site encryption key is apparently messed up.');
xml_status(3,$message); xml_status(3,$message);
} }
@ -576,7 +575,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey); openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
if(! strlen($decrypted_source_url)) { if (! strlen($decrypted_source_url)) {
$message = t('Empty site URL was provided or URL could not be decrypted by us.'); $message = t('Empty site URL was provided or URL could not be decrypted by us.');
xml_status(3,$message); xml_status(3,$message);
// NOTREACHED // NOTREACHED
@ -586,17 +585,18 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
dbesc($decrypted_source_url), dbesc($decrypted_source_url),
intval($local_uid) intval($local_uid)
); );
if(! count($ret)) { if (!dbm::is_result($ret)) {
if(strstr($decrypted_source_url,'http:')) if (strstr($decrypted_source_url,'http:')) {
$newurl = str_replace('http:','https:',$decrypted_source_url); $newurl = str_replace('http:','https:',$decrypted_source_url);
else } else {
$newurl = str_replace('https:','http:',$decrypted_source_url); $newurl = str_replace('https:','http:',$decrypted_source_url);
}
$ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1", $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
dbesc($newurl), dbesc($newurl),
intval($local_uid) intval($local_uid)
); );
if(! count($ret)) { if (!dbm::is_result($ret)) {
// this is either a bogus confirmation (?) or we deleted the original introduction. // this is either a bogus confirmation (?) or we deleted the original introduction.
$message = t('Contact record was not found for you on our site.'); $message = t('Contact record was not found for you on our site.');
xml_status(3,$message); xml_status(3,$message);
@ -611,7 +611,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
$foreign_pubkey = $ret[0]['site-pubkey']; $foreign_pubkey = $ret[0]['site-pubkey'];
$dfrn_record = $ret[0]['id']; $dfrn_record = $ret[0]['id'];
if(! $foreign_pubkey) { if (! $foreign_pubkey) {
$message = sprintf( t('Site public key not available in contact record for URL %s.'), $newurl); $message = sprintf( t('Site public key not available in contact record for URL %s.'), $newurl);
xml_status(3,$message); xml_status(3,$message);
} }
@ -619,7 +619,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
$decrypted_dfrn_id = ""; $decrypted_dfrn_id = "";
openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey); openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
if(strlen($aes_key)) { if (strlen($aes_key)) {
$decrypted_aes_key = ""; $decrypted_aes_key = "";
openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey); openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
$dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key); $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
@ -650,7 +650,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
// It's possible that the other person also requested friendship. // It's possible that the other person also requested friendship.
// If it is a duplex relationship, ditch the issued-id if one exists. // If it is a duplex relationship, ditch the issued-id if one exists.
if($duplex) { if ($duplex) {
$r = q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d", $r = q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
intval($dfrn_record) intval($dfrn_record)
); );
@ -722,7 +722,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
if (dbm::is_result($r)) if (dbm::is_result($r))
$combined = $r[0]; $combined = $r[0];
if((dbm::is_result($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) { if ((dbm::is_result($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
$mutual = ($new_relation == CONTACT_IS_FRIEND); $mutual = ($new_relation == CONTACT_IS_FRIEND);
notification(array( notification(array(
'type' => NOTIFY_CONFIRM, 'type' => NOTIFY_CONFIRM,
@ -742,12 +742,12 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
// Send a new friend post if we are allowed to... // Send a new friend post if we are allowed to...
if($page && intval(get_pconfig($local_uid,'system','post_joingroup'))) { if ($page && intval(get_pconfig($local_uid,'system','post_joingroup'))) {
$r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1", $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
intval($local_uid) intval($local_uid)
); );
if((dbm::is_result($r)) && ($r[0]['hide-friends'] == 0)) { if ((dbm::is_result($r)) && ($r[0]['hide-friends'] == 0)) {
require_once('include/items.php'); require_once('include/items.php');
@ -755,7 +755,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
intval($local_uid) intval($local_uid)
); );
if(count($self)) { if (dbm::is_result($self)) {
$arr = array(); $arr = array();
$arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $local_uid); $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $local_uid);
@ -792,8 +792,9 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
$arr['deny_gid'] = $user[0]['deny_gid']; $arr['deny_gid'] = $user[0]['deny_gid'];
$i = item_store($arr); $i = item_store($arr);
if($i) if ($i) {
proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i); proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
}
} }
} }

View file

@ -28,12 +28,12 @@ function dfrn_notify_post(App $a) {
$prv = (($page == 2) ? 1 : 0); $prv = (($page == 2) ? 1 : 0);
$writable = (-1); $writable = (-1);
if($dfrn_version >= 2.21) { if ($dfrn_version >= 2.21) {
$writable = (($perm === 'rw') ? 1 : 0); $writable = (($perm === 'rw') ? 1 : 0);
} }
$direction = (-1); $direction = (-1);
if(strpos($dfrn_id,':') == 1) { if (strpos($dfrn_id,':') == 1) {
$direction = intval(substr($dfrn_id,0,1)); $direction = intval(substr($dfrn_id,0,1));
$dfrn_id = substr($dfrn_id,2); $dfrn_id = substr($dfrn_id,2);
} }
@ -100,14 +100,14 @@ function dfrn_notify_post(App $a) {
logger("Remote rino version: ".$rino_remote." for ".$importer["url"], LOGGER_DEBUG); logger("Remote rino version: ".$rino_remote." for ".$importer["url"], LOGGER_DEBUG);
if((($writable != (-1)) && ($writable != $importer['writable'])) || ($importer['forum'] != $forum) || ($importer['prv'] != $prv)) { if ((($writable != (-1)) && ($writable != $importer['writable'])) || ($importer['forum'] != $forum) || ($importer['prv'] != $prv)) {
q("UPDATE `contact` SET `writable` = %d, forum = %d, prv = %d WHERE `id` = %d", q("UPDATE `contact` SET `writable` = %d, forum = %d, prv = %d WHERE `id` = %d",
intval(($writable == (-1)) ? $importer['writable'] : $writable), intval(($writable == (-1)) ? $importer['writable'] : $writable),
intval($forum), intval($forum),
intval($prv), intval($prv),
intval($importer['id']) intval($importer['id'])
); );
if($writable != (-1)) if ($writable != (-1))
$importer['writable'] = $writable; $importer['writable'] = $writable;
$importer['forum'] = $page; $importer['forum'] = $page;
} }
@ -120,7 +120,7 @@ function dfrn_notify_post(App $a) {
logger('dfrn_notify: received notify from ' . $importer['name'] . ' for ' . $importer['username']); logger('dfrn_notify: received notify from ' . $importer['name'] . ' for ' . $importer['username']);
logger('dfrn_notify: data: ' . $data, LOGGER_DATA); logger('dfrn_notify: data: ' . $data, LOGGER_DATA);
if($dissolve == 1) { if ($dissolve == 1) {
/* /*
* Relationship is dissolved permanently * Relationship is dissolved permanently
@ -137,17 +137,19 @@ function dfrn_notify_post(App $a) {
// If we are setup as a soapbox we aren't accepting input from this person // If we are setup as a soapbox we aren't accepting input from this person
// This behaviour is deactivated since it really doesn't make sense to even disallow comments // This behaviour is deactivated since it really doesn't make sense to even disallow comments
// The check if someone is a friend or simply a follower is done in a later place so it needn't to be done here // The check if someone is a friend or simply a follower is done in a later place so it needn't to be done here
//if($importer['page-flags'] == PAGE_SOAPBOX) //if ($importer['page-flags'] == PAGE_SOAPBOX)
// xml_status(0); // xml_status(0);
$rino = get_config('system','rino_encrypt'); $rino = get_config('system','rino_encrypt');
$rino = intval($rino); $rino = intval($rino);
// use RINO1 if mcrypt isn't installed and RINO2 was selected // use RINO1 if mcrypt isn't installed and RINO2 was selected
if ($rino==2 and !function_exists('mcrypt_create_iv')) $rino=1; if ($rino == 2 and !function_exists('mcrypt_create_iv')) {
$rino=1;
}
logger("Local rino version: ". $rino, LOGGER_DEBUG); logger("Local rino version: ". $rino, LOGGER_DEBUG);
if(strlen($key)) { if (strlen($key)) {
// if local rino is lower than remote rino, abort: should not happen! // if local rino is lower than remote rino, abort: should not happen!
// but only for $remote_rino > 1, because old code did't send rino version // but only for $remote_rino > 1, because old code did't send rino version
@ -160,8 +162,8 @@ function dfrn_notify_post(App $a) {
logger('rino: md5 raw key: ' . md5($rawkey)); logger('rino: md5 raw key: ' . md5($rawkey));
$final_key = ''; $final_key = '';
if($dfrn_version >= 2.1) { if ($dfrn_version >= 2.1) {
if((($importer['duplex']) && strlen($importer['cprvkey'])) || (! strlen($importer['cpubkey']))) { if ((($importer['duplex']) && strlen($importer['cprvkey'])) || (! strlen($importer['cpubkey']))) {
openssl_private_decrypt($rawkey,$final_key,$importer['cprvkey']); openssl_private_decrypt($rawkey,$final_key,$importer['cprvkey']);
} }
else { else {
@ -169,7 +171,7 @@ function dfrn_notify_post(App $a) {
} }
} }
else { else {
if((($importer['duplex']) && strlen($importer['cpubkey'])) || (! strlen($importer['cprvkey']))) { if ((($importer['duplex']) && strlen($importer['cpubkey'])) || (! strlen($importer['cprvkey']))) {
openssl_public_decrypt($rawkey,$final_key,$importer['cpubkey']); openssl_public_decrypt($rawkey,$final_key,$importer['cpubkey']);
} }
else { else {
@ -223,7 +225,7 @@ function dfrn_notify_post(App $a) {
function dfrn_notify_content(App $a) { function dfrn_notify_content(App $a) {
if(x($_GET,'dfrn_id')) { if (x($_GET,'dfrn_id')) {
// initial communication from external contact, $direction is their direction. // initial communication from external contact, $direction is their direction.
// If this is a duplex communication, ours will be the opposite. // If this is a duplex communication, ours will be the opposite.
@ -237,7 +239,7 @@ function dfrn_notify_content(App $a) {
logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id); logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id);
$direction = (-1); $direction = (-1);
if(strpos($dfrn_id,':') == 1) { if (strpos($dfrn_id,':') == 1) {
$direction = intval(substr($dfrn_id,0,1)); $direction = intval(substr($dfrn_id,0,1));
$dfrn_id = substr($dfrn_id,2); $dfrn_id = substr($dfrn_id,2);
} }
@ -298,16 +300,15 @@ function dfrn_notify_content(App $a) {
$pub_key = trim($r[0]['pubkey']); $pub_key = trim($r[0]['pubkey']);
$dplx = intval($r[0]['duplex']); $dplx = intval($r[0]['duplex']);
if((($dplx) && (strlen($prv_key))) || ((strlen($prv_key)) && (!(strlen($pub_key))))) { if ((($dplx) && (strlen($prv_key))) || ((strlen($prv_key)) && (!(strlen($pub_key))))) {
openssl_private_encrypt($hash,$challenge,$prv_key); openssl_private_encrypt($hash,$challenge,$prv_key);
openssl_private_encrypt($id_str,$encrypted_id,$prv_key); openssl_private_encrypt($id_str,$encrypted_id,$prv_key);
} } elseif (strlen($pub_key)) {
elseif(strlen($pub_key)) {
openssl_public_encrypt($hash,$challenge,$pub_key); openssl_public_encrypt($hash,$challenge,$pub_key);
openssl_public_encrypt($id_str,$encrypted_id,$pub_key); openssl_public_encrypt($id_str,$encrypted_id,$pub_key);
} } else {
else
$status = 1; $status = 1;
}
$challenge = bin2hex($challenge); $challenge = bin2hex($challenge);
$encrypted_id = bin2hex($encrypted_id); $encrypted_id = bin2hex($encrypted_id);
@ -316,7 +317,9 @@ function dfrn_notify_content(App $a) {
$rino = get_config('system','rino_encrypt'); $rino = get_config('system','rino_encrypt');
$rino = intval($rino); $rino = intval($rino);
// use RINO1 if mcrypt isn't installed and RINO2 was selected // use RINO1 if mcrypt isn't installed and RINO2 was selected
if ($rino==2 and !function_exists('mcrypt_create_iv')) $rino=1; if ($rino == 2 and !function_exists('mcrypt_create_iv')) {
$rino=1;
}
logger("Local rino version: ". $rino, LOGGER_DEBUG); logger("Local rino version: ". $rino, LOGGER_DEBUG);
@ -324,10 +327,9 @@ function dfrn_notify_content(App $a) {
// if requested rino is higher than enabled local rino, reply with local rino // if requested rino is higher than enabled local rino, reply with local rino
if ($rino_remote < $rino) $rino = $rino_remote; if ($rino_remote < $rino) $rino = $rino_remote;
if((($r[0]['rel']) && ($r[0]['rel'] != CONTACT_IS_SHARING)) || ($r[0]['page-flags'] == PAGE_COMMUNITY)) { if ((($r[0]['rel']) && ($r[0]['rel'] != CONTACT_IS_SHARING)) || ($r[0]['page-flags'] == PAGE_COMMUNITY)) {
$perm = 'rw'; $perm = 'rw';
} } else {
else {
$perm = 'r'; $perm = 'r';
} }

View file

@ -20,20 +20,20 @@ function dfrn_poll_init(App $a) {
$direction = (-1); $direction = (-1);
if(strpos($dfrn_id,':') == 1) { if (strpos($dfrn_id,':') == 1) {
$direction = intval(substr($dfrn_id,0,1)); $direction = intval(substr($dfrn_id,0,1));
$dfrn_id = substr($dfrn_id,2); $dfrn_id = substr($dfrn_id,2);
} }
$hidewall = false; $hidewall = false;
if(($dfrn_id === '') && (! x($_POST,'dfrn_id'))) { if (($dfrn_id === '') && (! x($_POST,'dfrn_id'))) {
if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) { if ((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
http_status_exit(403); http_status_exit(403);
} }
$user = ''; $user = '';
if($a->argc > 1) { if ($a->argc > 1) {
$r = q("SELECT `hidewall`,`nickname` FROM `user` WHERE `user`.`nickname` = '%s' LIMIT 1", $r = q("SELECT `hidewall`,`nickname` FROM `user` WHERE `user`.`nickname` = '%s' LIMIT 1",
dbesc($a->argv[1]) dbesc($a->argv[1])
); );
@ -51,7 +51,7 @@ function dfrn_poll_init(App $a) {
killme(); killme();
} }
if(($type === 'profile') && (! strlen($sec))) { if (($type === 'profile') && (! strlen($sec))) {
$sql_extra = ''; $sql_extra = '';
switch($direction) { switch($direction) {
@ -85,13 +85,13 @@ function dfrn_poll_init(App $a) {
logger("dfrn_poll: old profile returns " . $s, LOGGER_DATA); logger("dfrn_poll: old profile returns " . $s, LOGGER_DATA);
if(strlen($s)) { if (strlen($s)) {
$xml = parse_xml_string($s); $xml = parse_xml_string($s);
if((int) $xml->status == 1) { if ((int) $xml->status == 1) {
$_SESSION['authenticated'] = 1; $_SESSION['authenticated'] = 1;
if(! x($_SESSION,'remote')) if (! x($_SESSION,'remote'))
$_SESSION['remote'] = array(); $_SESSION['remote'] = array();
$_SESSION['remote'][] = array('cid' => $r[0]['id'],'uid' => $r[0]['uid'],'url' => $r[0]['url']); $_SESSION['remote'][] = array('cid' => $r[0]['id'],'uid' => $r[0]['uid'],'url' => $r[0]['url']);
@ -100,7 +100,7 @@ function dfrn_poll_init(App $a) {
$_SESSION['visitor_home'] = $r[0]['url']; $_SESSION['visitor_home'] = $r[0]['url'];
$_SESSION['visitor_handle'] = $r[0]['addr']; $_SESSION['visitor_handle'] = $r[0]['addr'];
$_SESSION['visitor_visiting'] = $r[0]['uid']; $_SESSION['visitor_visiting'] = $r[0]['uid'];
if(!$quiet) if (!$quiet)
info( sprintf(t('%1$s welcomes %2$s'), $r[0]['username'] , $r[0]['name']) . EOL); info( sprintf(t('%1$s welcomes %2$s'), $r[0]['username'] , $r[0]['name']) . EOL);
// Visitors get 1 day session. // Visitors get 1 day session.
$session_id = session_id(); $session_id = session_id();
@ -118,9 +118,9 @@ function dfrn_poll_init(App $a) {
} }
if($type === 'profile-check' && $dfrn_version < 2.2 ) { if ($type === 'profile-check' && $dfrn_version < 2.2 ) {
if((strlen($challenge)) && (strlen($sec))) { if ((strlen($challenge)) && (strlen($sec))) {
q("DELETE FROM `profile_check` WHERE `expire` < " . intval(time())); q("DELETE FROM `profile_check` WHERE `expire` < " . intval(time()));
$r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1", $r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1",
@ -131,7 +131,7 @@ function dfrn_poll_init(App $a) {
// NOTREACHED // NOTREACHED
} }
$orig_id = $r[0]['dfrn_id']; $orig_id = $r[0]['dfrn_id'];
if(strpos($orig_id, ':')) if (strpos($orig_id, ':'))
$orig_id = substr($orig_id,2); $orig_id = substr($orig_id,2);
$c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", $c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
@ -147,7 +147,7 @@ function dfrn_poll_init(App $a) {
$final_dfrn_id = ''; $final_dfrn_id = '';
if(($contact['duplex']) && strlen($contact['prvkey'])) { if (($contact['duplex']) && strlen($contact['prvkey'])) {
openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']); openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
openssl_private_decrypt($challenge,$decoded_challenge,$contact['prvkey']); openssl_private_decrypt($challenge,$decoded_challenge,$contact['prvkey']);
} }
@ -158,10 +158,10 @@ function dfrn_poll_init(App $a) {
$final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.')); $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
if(strpos($final_dfrn_id,':') == 1) if (strpos($final_dfrn_id,':') == 1)
$final_dfrn_id = substr($final_dfrn_id,2); $final_dfrn_id = substr($final_dfrn_id,2);
if($final_dfrn_id != $orig_id) { if ($final_dfrn_id != $orig_id) {
logger('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, LOGGER_DEBUG); logger('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, LOGGER_DEBUG);
// did not decode properly - cannot trust this site // did not decode properly - cannot trust this site
xml_status(3, 'Bad decryption'); xml_status(3, 'Bad decryption');
@ -213,9 +213,9 @@ function dfrn_poll_post(App $a) {
$dfrn_version = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version'] : 2.0); $dfrn_version = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version'] : 2.0);
$perm = ((x($_POST,'perm')) ? $_POST['perm'] : 'r'); $perm = ((x($_POST,'perm')) ? $_POST['perm'] : 'r');
if($ptype === 'profile-check') { if ($ptype === 'profile-check') {
if((strlen($challenge)) && (strlen($sec))) { if ((strlen($challenge)) && (strlen($sec))) {
logger('dfrn_poll: POST: profile-check'); logger('dfrn_poll: POST: profile-check');
@ -228,7 +228,7 @@ function dfrn_poll_post(App $a) {
// NOTREACHED // NOTREACHED
} }
$orig_id = $r[0]['dfrn_id']; $orig_id = $r[0]['dfrn_id'];
if(strpos($orig_id, ':')) if (strpos($orig_id, ':'))
$orig_id = substr($orig_id,2); $orig_id = substr($orig_id,2);
$c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", $c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
@ -244,7 +244,7 @@ function dfrn_poll_post(App $a) {
$final_dfrn_id = ''; $final_dfrn_id = '';
if(($contact['duplex']) && strlen($contact['prvkey'])) { if (($contact['duplex']) && strlen($contact['prvkey'])) {
openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']); openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
openssl_private_decrypt($challenge,$decoded_challenge,$contact['prvkey']); openssl_private_decrypt($challenge,$decoded_challenge,$contact['prvkey']);
} }
@ -255,10 +255,10 @@ function dfrn_poll_post(App $a) {
$final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.')); $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
if(strpos($final_dfrn_id,':') == 1) if (strpos($final_dfrn_id,':') == 1)
$final_dfrn_id = substr($final_dfrn_id,2); $final_dfrn_id = substr($final_dfrn_id,2);
if($final_dfrn_id != $orig_id) { if ($final_dfrn_id != $orig_id) {
logger('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, LOGGER_DEBUG); logger('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, LOGGER_DEBUG);
// did not decode properly - cannot trust this site // did not decode properly - cannot trust this site
xml_status(3, 'Bad decryption'); xml_status(3, 'Bad decryption');
@ -273,7 +273,7 @@ function dfrn_poll_post(App $a) {
} }
$direction = (-1); $direction = (-1);
if(strpos($dfrn_id,':') == 1) { if (strpos($dfrn_id,':') == 1) {
$direction = intval(substr($dfrn_id,0,1)); $direction = intval(substr($dfrn_id,0,1));
$dfrn_id = substr($dfrn_id,2); $dfrn_id = substr($dfrn_id,2);
} }
@ -329,7 +329,7 @@ function dfrn_poll_post(App $a) {
$contact_id = $r[0]['id']; $contact_id = $r[0]['id'];
if($type === 'reputation' && strlen($url)) { if ($type === 'reputation' && strlen($url)) {
$r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1", $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
dbesc($url), dbesc($url),
intval($owner_uid) intval($owner_uid)
@ -341,7 +341,7 @@ function dfrn_poll_post(App $a) {
$reputation = $r[0]['rating']; $reputation = $r[0]['rating'];
$text = $r[0]['reason']; $text = $r[0]['reason'];
if($r[0]['id'] == $contact_id) { // inquiring about own reputation not allowed if ($r[0]['id'] == $contact_id) { // inquiring about own reputation not allowed
$reputation = 0; $reputation = 0;
$text = ''; $text = '';
} }
@ -361,13 +361,13 @@ function dfrn_poll_post(App $a) {
// Update the writable flag if it changed // Update the writable flag if it changed
logger('dfrn_poll: post request feed: ' . print_r($_POST,true),LOGGER_DATA); logger('dfrn_poll: post request feed: ' . print_r($_POST,true),LOGGER_DATA);
if($dfrn_version >= 2.21) { if ($dfrn_version >= 2.21) {
if($perm === 'rw') if ($perm === 'rw')
$writable = 1; $writable = 1;
else else
$writable = 0; $writable = 0;
if($writable != $contact['writable']) { if ($writable != $contact['writable']) {
q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d", q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d",
intval($writable), intval($writable),
intval($contact_id) intval($contact_id)
@ -395,13 +395,13 @@ function dfrn_poll_content(App $a) {
$quiet = ((x($_GET,'quiet')) ? true : false); $quiet = ((x($_GET,'quiet')) ? true : false);
$direction = (-1); $direction = (-1);
if(strpos($dfrn_id,':') == 1) { if (strpos($dfrn_id,':') == 1) {
$direction = intval(substr($dfrn_id,0,1)); $direction = intval(substr($dfrn_id,0,1));
$dfrn_id = substr($dfrn_id,2); $dfrn_id = substr($dfrn_id,2);
} }
if($dfrn_id != '') { if ($dfrn_id != '') {
// initial communication from external contact // initial communication from external contact
$hash = random_string(); $hash = random_string();
@ -409,7 +409,7 @@ function dfrn_poll_content(App $a) {
$r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time())); $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
if($type !== 'profile') { if ($type !== 'profile') {
$r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` , `type`, `last_update` ) $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` , `type`, `last_update` )
VALUES( '%s', '%s', '%s', '%s', '%s' ) ", VALUES( '%s', '%s', '%s', '%s', '%s' ) ",
dbesc($hash), dbesc($hash),
@ -422,7 +422,7 @@ function dfrn_poll_content(App $a) {
$sql_extra = ''; $sql_extra = '';
switch($direction) { switch($direction) {
case (-1): case (-1):
if($type === 'profile') if ($type === 'profile')
$sql_extra = sprintf(" AND ( `dfrn-id` = '%s' OR `issued-id` = '%s' ) ", dbesc($dfrn_id),dbesc($dfrn_id)); $sql_extra = sprintf(" AND ( `dfrn-id` = '%s' OR `issued-id` = '%s' ) ", dbesc($dfrn_id),dbesc($dfrn_id));
else else
$sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id)); $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
@ -456,7 +456,7 @@ function dfrn_poll_content(App $a) {
$encrypted_id = ''; $encrypted_id = '';
$id_str = $my_id . '.' . mt_rand(1000,9999); $id_str = $my_id . '.' . mt_rand(1000,9999);
if(($r[0]['duplex'] && strlen($r[0]['pubkey'])) || (! strlen($r[0]['prvkey']))) { if (($r[0]['duplex'] && strlen($r[0]['pubkey'])) || (! strlen($r[0]['prvkey']))) {
openssl_public_encrypt($hash,$challenge,$r[0]['pubkey']); openssl_public_encrypt($hash,$challenge,$r[0]['pubkey']);
openssl_public_encrypt($id_str,$encrypted_id,$r[0]['pubkey']); openssl_public_encrypt($id_str,$encrypted_id,$r[0]['pubkey']);
} }
@ -474,11 +474,11 @@ function dfrn_poll_content(App $a) {
$encrypted_id = ''; $encrypted_id = '';
} }
if(($type === 'profile') && (strlen($sec))) { if (($type === 'profile') && (strlen($sec))) {
// URL reply // URL reply
if($dfrn_version < 2.2) { if ($dfrn_version < 2.2) {
$s = fetch_url($r[0]['poll'] $s = fetch_url($r[0]['poll']
. '?dfrn_id=' . $encrypted_id . '?dfrn_id=' . $encrypted_id
. '&type=profile-check' . '&type=profile-check'
@ -517,7 +517,7 @@ function dfrn_poll_content(App $a) {
logger("dfrn_poll: sec profile: " . $s, LOGGER_DATA); logger("dfrn_poll: sec profile: " . $s, LOGGER_DATA);
if(strlen($s) && strstr($s,'<?xml')) { if (strlen($s) && strstr($s,'<?xml')) {
$xml = parse_xml_string($s); $xml = parse_xml_string($s);
@ -527,15 +527,15 @@ function dfrn_poll_content(App $a) {
logger('dfrn_poll: secure profile: sec: ' . $xml->sec . ' expecting ' . $sec); logger('dfrn_poll: secure profile: sec: ' . $xml->sec . ' expecting ' . $sec);
if(((int) $xml->status == 0) && ($xml->challenge == $hash) && ($xml->sec == $sec)) { if (((int) $xml->status == 0) && ($xml->challenge == $hash) && ($xml->sec == $sec)) {
$_SESSION['authenticated'] = 1; $_SESSION['authenticated'] = 1;
if(! x($_SESSION,'remote')) if (! x($_SESSION,'remote'))
$_SESSION['remote'] = array(); $_SESSION['remote'] = array();
$_SESSION['remote'][] = array('cid' => $r[0]['id'],'uid' => $r[0]['uid'],'url' => $r[0]['url']); $_SESSION['remote'][] = array('cid' => $r[0]['id'],'uid' => $r[0]['uid'],'url' => $r[0]['url']);
$_SESSION['visitor_id'] = $r[0]['id']; $_SESSION['visitor_id'] = $r[0]['id'];
$_SESSION['visitor_home'] = $r[0]['url']; $_SESSION['visitor_home'] = $r[0]['url'];
$_SESSION['visitor_visiting'] = $r[0]['uid']; $_SESSION['visitor_visiting'] = $r[0]['uid'];
if(!$quiet) if (!$quiet)
info( sprintf(t('%1$s welcomes %2$s'), $r[0]['username'] , $r[0]['name']) . EOL); info( sprintf(t('%1$s welcomes %2$s'), $r[0]['username'] , $r[0]['name']) . EOL);
// Visitors get 1 day session. // Visitors get 1 day session.
$session_id = session_id(); $session_id = session_id();

View file

@ -19,7 +19,7 @@ require_once('include/group.php');
function dfrn_request_init(App $a) { function dfrn_request_init(App $a) {
if($a->argc > 1) if ($a->argc > 1)
$which = $a->argv[1]; $which = $a->argv[1];
profile_load($a,$which); profile_load($a,$which);
@ -44,13 +44,13 @@ function dfrn_request_init(App $a) {
*/ */
function dfrn_request_post(App $a) { function dfrn_request_post(App $a) {
if(($a->argc != 2) || (! count($a->profile))) { if (($a->argc != 2) || (! count($a->profile))) {
logger('Wrong count of argc or profiles: argc=' . $a->argc . ',profile()=' . count($a->profile)); logger('Wrong count of argc or profiles: argc=' . $a->argc . ',profile()=' . count($a->profile));
return; return;
} }
if(x($_POST, 'cancel')) { if (x($_POST, 'cancel')) {
goaway(z_root()); goaway(z_root());
} }
@ -63,13 +63,13 @@ function dfrn_request_post(App $a) {
* *
*/ */
if((x($_POST,'localconfirm')) && ($_POST['localconfirm'] == 1)) { if ((x($_POST,'localconfirm')) && ($_POST['localconfirm'] == 1)) {
/* /*
* Ensure this is a valid request * Ensure this is a valid request
*/ */
if(local_user() && ($a->user['nickname'] == $a->argv[1]) && (x($_POST,'dfrn_url'))) { if (local_user() && ($a->user['nickname'] == $a->argv[1]) && (x($_POST,'dfrn_url'))) {
$dfrn_url = notags(trim($_POST['dfrn_url'])); $dfrn_url = notags(trim($_POST['dfrn_url']));
@ -80,7 +80,7 @@ function dfrn_request_post(App $a) {
$blocked = 1; $blocked = 1;
$pending = 1; $pending = 1;
if(x($dfrn_url)) { if (x($dfrn_url)) {
/* /*
* Lookup the contact based on their URL (which is the only unique thing we have at the moment) * Lookup the contact based on their URL (which is the only unique thing we have at the moment)
@ -92,7 +92,7 @@ function dfrn_request_post(App $a) {
); );
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
if(strlen($r[0]['dfrn-id'])) { if (strlen($r[0]['dfrn-id'])) {
/* /*
* We don't need to be here. It has already happened. * We don't need to be here. It has already happened.
@ -105,7 +105,7 @@ function dfrn_request_post(App $a) {
$contact_record = $r[0]; $contact_record = $r[0];
} }
if(is_array($contact_record)) { if (is_array($contact_record)) {
$r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d", $r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d",
intval($aes_allow), intval($aes_allow),
intval($hidden), intval($hidden),
@ -187,7 +187,7 @@ function dfrn_request_post(App $a) {
); );
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
$def_gid = get_default_group(local_user(), $r[0]["network"]); $def_gid = get_default_group(local_user(), $r[0]["network"]);
if(intval($def_gid)) if (intval($def_gid))
group_add_member(local_user(), '', $r[0]['id'], $def_gid); group_add_member(local_user(), '', $r[0]['id'], $def_gid);
if (isset($photo)) if (isset($photo))
@ -249,7 +249,7 @@ function dfrn_request_post(App $a) {
* *
*/ */
if(! (is_array($a->profile) && count($a->profile))) { if (! (is_array($a->profile) && count($a->profile))) {
notice( t('Profile unavailable.') . EOL); notice( t('Profile unavailable.') . EOL);
return; return;
} }
@ -265,13 +265,13 @@ function dfrn_request_post(App $a) {
$pending = 1; $pending = 1;
if( x($_POST,'dfrn_url')) { if ( x($_POST,'dfrn_url')) {
/* /*
* Block friend request spam * Block friend request spam
*/ */
if($maxreq) { if ($maxreq) {
$r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d", $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
dbesc(datetime_convert('UTC','UTC','now - 24 hours')), dbesc(datetime_convert('UTC','UTC','now - 24 hours')),
intval($uid) intval($uid)
@ -300,7 +300,7 @@ function dfrn_request_post(App $a) {
); );
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach ($r as $rr) { foreach ($r as $rr) {
if(! $rr['rel']) { if (! $rr['rel']) {
q("DELETE FROM `contact` WHERE `id` = %d AND NOT `self`", q("DELETE FROM `contact` WHERE `id` = %d AND NOT `self`",
intval($rr['cid']) intval($rr['cid'])
); );
@ -325,7 +325,7 @@ function dfrn_request_post(App $a) {
); );
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach ($r as $rr) { foreach ($r as $rr) {
if(! $rr['rel']) { if (! $rr['rel']) {
q("DELETE FROM `contact` WHERE `id` = %d AND NOT `self`", q("DELETE FROM `contact` WHERE `id` = %d AND NOT `self`",
intval($rr['cid']) intval($rr['cid'])
); );
@ -340,16 +340,16 @@ function dfrn_request_post(App $a) {
$real_name = (x($_POST,'realname') ? notags(trim($_POST['realname'])) : ''); $real_name = (x($_POST,'realname') ? notags(trim($_POST['realname'])) : '');
$url = trim($_POST['dfrn_url']); $url = trim($_POST['dfrn_url']);
if(! strlen($url)) { if (! strlen($url)) {
notice( t("Invalid locator") . EOL ); notice( t("Invalid locator") . EOL );
return; return;
} }
$hcard = ''; $hcard = '';
if($email_follow) { if ($email_follow) {
if(! validate_email($url)) { if (! validate_email($url)) {
notice( t('Invalid email address.') . EOL); notice( t('Invalid email address.') . EOL);
return; return;
} }
@ -365,10 +365,10 @@ function dfrn_request_post(App $a) {
$rel = CONTACT_IS_FOLLOWER; $rel = CONTACT_IS_FOLLOWER;
$mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1); $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
if(get_config('system','dfrn_only')) if (get_config('system','dfrn_only'))
$mail_disabled = 1; $mail_disabled = 1;
if(! $mail_disabled) { if (! $mail_disabled) {
$failed = false; $failed = false;
$r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1", $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
intval($uid) intval($uid)
@ -470,18 +470,18 @@ function dfrn_request_post(App $a) {
logger('dfrn_request: url: ' . $url . ',network=' . $network, LOGGER_DEBUG); logger('dfrn_request: url: ' . $url . ',network=' . $network, LOGGER_DEBUG);
if($network === NETWORK_DFRN) { if ($network === NETWORK_DFRN) {
$ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1", $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
intval($uid), intval($uid),
dbesc($url) dbesc($url)
); );
if (dbm::is_result($ret)) { if (dbm::is_result($ret)) {
if(strlen($ret[0]['issued-id'])) { if (strlen($ret[0]['issued-id'])) {
notice( t('You have already introduced yourself here.') . EOL ); notice( t('You have already introduced yourself here.') . EOL );
return; return;
} }
elseif($ret[0]['rel'] == CONTACT_IS_FRIEND) { elseif ($ret[0]['rel'] == CONTACT_IS_FRIEND) {
notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL); notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
return; return;
} }
@ -493,7 +493,7 @@ function dfrn_request_post(App $a) {
$issued_id = random_string(); $issued_id = random_string();
if(is_array($contact_record)) { if (is_array($contact_record)) {
// There is a contact record but no issued-id, so this // There is a contact record but no issued-id, so this
// is a reciprocal introduction from a known contact // is a reciprocal introduction from a known contact
$r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d", $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
@ -718,7 +718,7 @@ function dfrn_request_content(App $a) {
return $o; return $o;
} }
elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) { elseif ((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) {
// we are the requestee and it is now safe to send our user their introduction, // we are the requestee and it is now safe to send our user their introduction,
// We could just unblock it, but first we have to jump through a few hoops to // We could just unblock it, but first we have to jump through a few hoops to
@ -738,10 +738,10 @@ function dfrn_request_content(App $a) {
$auto_confirm = false; $auto_confirm = false;
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
if(($r[0]['page-flags'] != PAGE_NORMAL) && ($r[0]['page-flags'] != PAGE_PRVGROUP)) if (($r[0]['page-flags'] != PAGE_NORMAL) && ($r[0]['page-flags'] != PAGE_PRVGROUP))
$auto_confirm = true; $auto_confirm = true;
if(! $auto_confirm) { if (! $auto_confirm) {
notification(array( notification(array(
'type' => NOTIFY_INTRO, 'type' => NOTIFY_INTRO,
@ -759,7 +759,7 @@ function dfrn_request_content(App $a) {
)); ));
} }
if($auto_confirm) { if ($auto_confirm) {
require_once('mod/dfrn_confirm.php'); require_once('mod/dfrn_confirm.php');
$handsfree = array( $handsfree = array(
'uid' => $r[0]['uid'], 'uid' => $r[0]['uid'],
@ -774,7 +774,7 @@ function dfrn_request_content(App $a) {
} }
if(! $auto_confirm) { if (! $auto_confirm) {
// If we are auto_confirming, this record will have already been nuked // If we are auto_confirming, this record will have already been nuked
// in dfrn_confirm_post() // in dfrn_confirm_post()
@ -794,8 +794,8 @@ function dfrn_request_content(App $a) {
* Normal web request. Display our user's introduction form. * Normal web request. Display our user's introduction form.
*/ */
if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) { if ((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
if(! get_config('system','local_block')) { if (! get_config('system','local_block')) {
notice( t('Public access denied.') . EOL); notice( t('Public access denied.') . EOL);
return; return;
} }

View file

@ -3,7 +3,7 @@
function directory_init(App $a) { function directory_init(App $a) {
$a->set_pager_itemspage(60); $a->set_pager_itemspage(60);
if(local_user()) { if (local_user()) {
require_once('include/contact_widgets.php'); require_once('include/contact_widgets.php');
$a->page['aside'] .= findpeople_widget(); $a->page['aside'] .= findpeople_widget();
@ -21,7 +21,7 @@ function directory_init(App $a) {
function directory_post(App $a) { function directory_post(App $a) {
if(x($_POST,'search')) if (x($_POST,'search'))
$a->data['search'] = $_POST['search']; $a->data['search'] = $_POST['search'];
} }
@ -32,7 +32,7 @@ function directory_content(App $a) {
require_once("mod/proxy.php"); require_once("mod/proxy.php");
if((get_config('system','block_public')) && (! local_user()) && (! remote_user()) || if ((get_config('system','block_public')) && (! local_user()) && (! remote_user()) ||
(get_config('system','block_local_dir')) && (! local_user()) && (! remote_user())) { (get_config('system','block_local_dir')) && (! local_user()) && (! remote_user())) {
notice( t('Public access denied.') . EOL); notice( t('Public access denied.') . EOL);
return; return;
@ -41,18 +41,18 @@ function directory_content(App $a) {
$o = ''; $o = '';
nav_set_selected('directory'); nav_set_selected('directory');
if(x($a->data,'search')) if (x($a->data,'search'))
$search = notags(trim($a->data['search'])); $search = notags(trim($a->data['search']));
else else
$search = ((x($_GET,'search')) ? notags(trim(rawurldecode($_GET['search']))) : ''); $search = ((x($_GET,'search')) ? notags(trim(rawurldecode($_GET['search']))) : '');
$gdirpath = ''; $gdirpath = '';
$dirurl = get_config('system','directory'); $dirurl = get_config('system','directory');
if(strlen($dirurl)) { if (strlen($dirurl)) {
$gdirpath = zrl($dirurl,true); $gdirpath = zrl($dirurl,true);
} }
if($search) { if ($search) {
$search = dbesc($search); $search = dbesc($search);
$sql_extra = " AND ((`profile`.`name` LIKE '%$search%') OR $sql_extra = " AND ((`profile`.`name` LIKE '%$search%') OR
@ -110,28 +110,28 @@ function directory_content(App $a) {
$pdesc = (($rr['pdesc']) ? $rr['pdesc'] . '<br />' : ''); $pdesc = (($rr['pdesc']) ? $rr['pdesc'] . '<br />' : '');
$details = ''; $details = '';
if(strlen($rr['locality'])) if (strlen($rr['locality']))
$details .= $rr['locality']; $details .= $rr['locality'];
if(strlen($rr['region'])) { if (strlen($rr['region'])) {
if(strlen($rr['locality'])) if (strlen($rr['locality']))
$details .= ', '; $details .= ', ';
$details .= $rr['region']; $details .= $rr['region'];
} }
if(strlen($rr['country-name'])) { if (strlen($rr['country-name'])) {
if(strlen($details)) if (strlen($details))
$details .= ', '; $details .= ', ';
$details .= $rr['country-name']; $details .= $rr['country-name'];
} }
// if(strlen($rr['dob'])) { // if (strlen($rr['dob'])) {
// if(($years = age($rr['dob'],$rr['timezone'],'')) != 0) // if (($years = age($rr['dob'],$rr['timezone'],'')) != 0)
// $details .= '<br />' . t('Age: ') . $years ; // $details .= '<br />' . t('Age: ') . $years ;
// } // }
// if(strlen($rr['gender'])) // if (strlen($rr['gender']))
// $details .= '<br />' . t('Gender: ') . $rr['gender']; // $details .= '<br />' . t('Gender: ') . $rr['gender'];
$profile = $rr; $profile = $rr;
if((x($profile,'address') == 1) if ((x($profile,'address') == 1)
|| (x($profile,'locality') == 1) || (x($profile,'locality') == 1)
|| (x($profile,'region') == 1) || (x($profile,'region') == 1)
|| (x($profile,'postal-code') == 1) || (x($profile,'postal-code') == 1)
@ -146,7 +146,7 @@ function directory_content(App $a) {
$about = ((x($profile,'about') == 1) ? t('About:') : False); $about = ((x($profile,'about') == 1) ? t('About:') : False);
if($a->theme['template_engine'] === 'internal') { if ($a->theme['template_engine'] === 'internal') {
$location_e = template_escape($location); $location_e = template_escape($location);
} }
else { else {
@ -185,8 +185,9 @@ function directory_content(App $a) {
unset($profile); unset($profile);
unset($location); unset($location);
if(! $arr['entry']) if (! $arr['entry']) {
continue; continue;
}
$entries[] = $arr['entry']; $entries[] = $arr['entry'];

View file

@ -166,8 +166,9 @@ function dirfind_content(App $a, $prefix = "") {
$p = (($a->pager['page'] != 1) ? '&p=' . $a->pager['page'] : ''); $p = (($a->pager['page'] != 1) ? '&p=' . $a->pager['page'] : '');
if(strlen(get_config('system','directory'))) if (strlen(get_config('system','directory'))) {
$x = fetch_url(get_server().'/lsearch?f=' . $p . '&search=' . urlencode($search)); $x = fetch_url(get_server().'/lsearch?f=' . $p . '&search=' . urlencode($search));
}
$j = json_decode($x); $j = json_decode($x);
} }

View file

@ -51,7 +51,7 @@ function editpost_content(App $a) {
$tpl = get_markup_template("jot.tpl"); $tpl = get_markup_template("jot.tpl");
if(($group) || (is_array($a->user) && ((strlen($a->user['allow_cid'])) || (strlen($a->user['allow_gid'])) || (strlen($a->user['deny_cid'])) || (strlen($a->user['deny_gid']))))) if (($group) || (is_array($a->user) && ((strlen($a->user['allow_cid'])) || (strlen($a->user['allow_gid'])) || (strlen($a->user['deny_cid'])) || (strlen($a->user['deny_gid'])))))
$lockstate = 'lock'; $lockstate = 'lock';
else else
$lockstate = 'unlock'; $lockstate = 'unlock';
@ -64,13 +64,13 @@ function editpost_content(App $a) {
$mail_enabled = false; $mail_enabled = false;
$pubmail_enabled = false; $pubmail_enabled = false;
if(! $mail_disabled) { if (! $mail_disabled) {
$r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
intval(local_user()) intval(local_user())
); );
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
$mail_enabled = true; $mail_enabled = true;
if(intval($r[0]['pubmail'])) if (intval($r[0]['pubmail']))
$pubmail_enabled = true; $pubmail_enabled = true;
} }
} }
@ -78,7 +78,7 @@ function editpost_content(App $a) {
// I don't think there's any need for the $jotnets when editing the post, // I don't think there's any need for the $jotnets when editing the post,
// and including them makes it difficult for the JS-free theme, so let's // and including them makes it difficult for the JS-free theme, so let's
// disable them // disable them
/* if($mail_enabled) { /* if ($mail_enabled) {
$selected = (($pubmail_enabled) ? ' checked="checked" ' : ''); $selected = (($pubmail_enabled) ? ' checked="checked" ' : '');
$jotnets .= '<div class="profile-jot-net"><input type="checkbox" name="pubmail_enable"' . $selected . ' value="1" /> ' $jotnets .= '<div class="profile-jot-net"><input type="checkbox" name="pubmail_enable"' . $selected . ' value="1" /> '
. t("Post to Email") . '</div>'; . t("Post to Email") . '</div>';

View file

@ -112,7 +112,7 @@ function events_post(App $a) {
$c = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1", $c = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
intval(local_user()) intval(local_user())
); );
if (count($c)) { if (dbm::is_result($c)) {
$self = $c[0]['id']; $self = $c[0]['id'];
} else { } else {
$self = 0; $self = 0;
@ -126,7 +126,7 @@ function events_post(App $a) {
$str_contact_deny = perms2str($_POST['contact_deny']); $str_contact_deny = perms2str($_POST['contact_deny']);
// Undo the pseudo-contact of self, since there are real contacts now // Undo the pseudo-contact of self, since there are real contacts now
if (strpos($str_contact_allow, '<' . $self . '>') !== false ) { if (strpos($str_contact_allow, '<' . $self . '>') !== false) {
$str_contact_allow = str_replace('<' . $self . '>', '', $str_contact_allow); $str_contact_allow = str_replace('<' . $self . '>', '', $str_contact_allow);
} }
// Make sure to set the `private` field as true. This is necessary to // Make sure to set the `private` field as true. This is necessary to
@ -142,7 +142,7 @@ function events_post(App $a) {
$str_group_allow = $str_contact_deny = $str_group_deny = ''; $str_group_allow = $str_contact_deny = $str_group_deny = '';
} }
/// @TODO One-time array initialization, one large block
$datarray = array(); $datarray = array();
$datarray['guid'] = get_guid(32); $datarray['guid'] = get_guid(32);
$datarray['start'] = $start; $datarray['start'] = $start;
@ -407,7 +407,9 @@ function events_content(App $a) {
// Passed parameters overrides anything found in the DB // Passed parameters overrides anything found in the DB
if ($mode === 'edit' || $mode === 'new') { if ($mode === 'edit' || $mode === 'new') {
if (!x($orig_event)) {$orig_event = array();} if (!x($orig_event)) {
$orig_event = array();
}
// In case of an error the browser is redirected back here, with these parameters filled in with the previous values // In case of an error the browser is redirected back here, with these parameters filled in with the previous values
if (x($_REQUEST, 'nofinish')) {$orig_event['nofinish'] = $_REQUEST['nofinish'];} if (x($_REQUEST, 'nofinish')) {$orig_event['nofinish'] = $_REQUEST['nofinish'];}
if (x($_REQUEST, 'adjust')) {$orig_event['adjust'] = $_REQUEST['adjust'];} if (x($_REQUEST, 'adjust')) {$orig_event['adjust'] = $_REQUEST['adjust'];}

View file

@ -66,10 +66,9 @@ function fbrowser_content(App $a) {
$types = Photo::supportedTypes(); $types = Photo::supportedTypes();
$ext = $types[$rr['type']]; $ext = $types[$rr['type']];
if($a->theme['template_engine'] === 'internal') { if ($a->theme['template_engine'] === 'internal') {
$filename_e = template_escape($rr['filename']); $filename_e = template_escape($rr['filename']);
} } else {
else {
$filename_e = $rr['filename']; $filename_e = $rr['filename'];
} }

View file

@ -16,7 +16,7 @@ function filer_content(App $a) {
logger('filer: tag ' . $term . ' item ' . $item_id); logger('filer: tag ' . $term . ' item ' . $item_id);
if($item_id && strlen($term)){ if ($item_id && strlen($term)){
// file item // file item
file_tag_save_file(local_user(),$item_id,$term); file_tag_save_file(local_user(),$item_id,$term);
} else { } else {

View file

@ -7,7 +7,7 @@ function friendica_init(App $a) {
$register_policy = Array('REGISTER_CLOSED', 'REGISTER_APPROVE', 'REGISTER_OPEN'); $register_policy = Array('REGISTER_CLOSED', 'REGISTER_APPROVE', 'REGISTER_OPEN');
$sql_extra = ''; $sql_extra = '';
if(x($a->config,'admin_nickname')) { if (x($a->config,'admin_nickname')) {
$sql_extra = sprintf(" AND nickname = '%s' ",dbesc($a->config['admin_nickname'])); $sql_extra = sprintf(" AND nickname = '%s' ",dbesc($a->config['admin_nickname']));
} }
if (isset($a->config['admin_email']) && $a->config['admin_email']!=''){ if (isset($a->config['admin_email']) && $a->config['admin_email']!=''){
@ -24,18 +24,18 @@ function friendica_init(App $a) {
} }
$visible_plugins = array(); $visible_plugins = array();
if(is_array($a->plugins) && count($a->plugins)) { if (is_array($a->plugins) && count($a->plugins)) {
$r = q("select * from addon where hidden = 0"); $r = q("select * from addon where hidden = 0");
if (dbm::is_result($r)) if (dbm::is_result($r))
foreach($r as $rr) foreach ($r as $rr)
$visible_plugins[] = $rr['name']; $visible_plugins[] = $rr['name'];
} }
Config::load('feature_lock'); Config::load('feature_lock');
$locked_features = array(); $locked_features = array();
if(is_array($a->config['feature_lock']) && count($a->config['feature_lock'])) { if (is_array($a->config['feature_lock']) && count($a->config['feature_lock'])) {
foreach($a->config['feature_lock'] as $k => $v) { foreach ($a->config['feature_lock'] as $k => $v) {
if($k === 'config_loaded') if ($k === 'config_loaded')
continue; continue;
$locked_features[$k] = intval($v); $locked_features[$k] = intval($v);
} }
@ -80,22 +80,24 @@ function friendica_content(App $a) {
$o .= '<p></p>'; $o .= '<p></p>';
$visible_plugins = array(); $visible_plugins = array();
if(is_array($a->plugins) && count($a->plugins)) { if (is_array($a->plugins) && count($a->plugins)) {
$r = q("select * from addon where hidden = 0"); $r = q("select * from addon where hidden = 0");
if (dbm::is_result($r)) if (dbm::is_result($r))
foreach($r as $rr) foreach ($r as $rr)
$visible_plugins[] = $rr['name']; $visible_plugins[] = $rr['name'];
} }
if(count($visible_plugins)) { if (count($visible_plugins)) {
$o .= '<p>' . t('Installed plugins/addons/apps:') . '</p>'; $o .= '<p>' . t('Installed plugins/addons/apps:') . '</p>';
$sorted = $visible_plugins; $sorted = $visible_plugins;
$s = ''; $s = '';
sort($sorted); sort($sorted);
foreach($sorted as $p) { foreach ($sorted as $p) {
if(strlen($p)) { if (strlen($p)) {
if(strlen($s)) $s .= ', '; if (strlen($s)) {
$s .= ', ';
}
$s .= $p; $s .= $p;
} }
} }

View file

@ -29,7 +29,7 @@ function fsuggest_post(App $a) {
$note = escape_tags(trim($_POST['note'])); $note = escape_tags(trim($_POST['note']));
if($new_contact) { if ($new_contact) {
$r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1", $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
intval($new_contact), intval($new_contact),
intval(local_user()) intval(local_user())
@ -80,8 +80,9 @@ function fsuggest_content(App $a) {
return; return;
} }
if($a->argc != 2) if ($a->argc != 2) {
return; return;
}
$contact_id = intval($a->argv[1]); $contact_id = intval($a->argv[1]);

View file

@ -5,7 +5,7 @@ function validate_members(&$item) {
} }
function group_init(App $a) { function group_init(App $a) {
if(local_user()) { if (local_user()) {
require_once('include/group.php'); require_once('include/group.php');
$a->page['aside'] = group_side('contacts','group','extended',(($a->argc > 1) ? intval($a->argv[1]) : 0)); $a->page['aside'] = group_side('contacts','group','extended',(($a->argc > 1) ? intval($a->argv[1]) : 0));
} }
@ -20,7 +20,7 @@ function group_post(App $a) {
return; return;
} }
if(($a->argc == 2) && ($a->argv[1] === 'new')) { if (($a->argc == 2) && ($a->argv[1] === 'new')) {
check_form_security_token_redirectOnErr('/group/new', 'group_edit'); check_form_security_token_redirectOnErr('/group/new', 'group_edit');
$name = notags(trim($_POST['groupname'])); $name = notags(trim($_POST['groupname']));
@ -80,10 +80,12 @@ function group_content(App $a) {
// Switch to text mode interface if we have more than 'n' contacts or group members // Switch to text mode interface if we have more than 'n' contacts or group members
$switchtotext = get_pconfig(local_user(),'system','groupedit_image_limit'); $switchtotext = get_pconfig(local_user(),'system','groupedit_image_limit');
if($switchtotext === false) if ($switchtotext === false) {
$switchtotext = get_config('system','groupedit_image_limit'); $switchtotext = get_config('system','groupedit_image_limit');
if($switchtotext === false) }
if ($switchtotext === false) {
$switchtotext = 400; $switchtotext = 400;
}
$tpl = get_markup_template('group_edit.tpl'); $tpl = get_markup_template('group_edit.tpl');
@ -99,8 +101,6 @@ function group_content(App $a) {
'$gid' => 'new', '$gid' => 'new',
'$form_security_token' => get_form_security_token("group_edit"), '$form_security_token' => get_form_security_token("group_edit"),
)); ));
} }
if (($a->argc == 3) && ($a->argv[1] === 'drop')) { if (($a->argc == 3) && ($a->argv[1] === 'drop')) {
@ -135,9 +135,10 @@ function group_content(App $a) {
intval($a->argv[2]), intval($a->argv[2]),
intval(local_user()) intval(local_user())
); );
if (dbm::is_result($r)) if (dbm::is_result($r)) {
$change = intval($a->argv[2]); $change = intval($a->argv[2]);
} }
}
if (($a->argc > 1) && (intval($a->argv[1]))) { if (($a->argc > 1) && (intval($a->argv[1]))) {
@ -153,23 +154,23 @@ function group_content(App $a) {
$group = $r[0]; $group = $r[0];
$members = group_get_members($group['id']); $members = group_get_members($group['id']);
$preselected = array(); $preselected = array();
if(count($members)) { if (count($members)) {
foreach($members as $member) foreach ($members as $member) {
$preselected[] = $member['id']; $preselected[] = $member['id'];
} }
if($change) {
if(in_array($change,$preselected)) {
group_rmv_member(local_user(),$group['name'],$change);
} }
else {
if ($change) {
if (in_array($change,$preselected)) {
group_rmv_member(local_user(),$group['name'],$change);
} else {
group_add_member(local_user(),$group['name'],$change); group_add_member(local_user(),$group['name'],$change);
} }
$members = group_get_members($group['id']); $members = group_get_members($group['id']);
$preselected = array(); $preselected = array();
if(count($members)) { if (count($members)) {
foreach($members as $member) foreach ($members as $member)
$preselected[] = $member['id']; $preselected[] = $member['id'];
} }
} }
@ -193,8 +194,9 @@ function group_content(App $a) {
} }
if(! isset($group)) if (! isset($group)) {
return; return;
}
$groupeditor = array( $groupeditor = array(
'label_members' => t('Members'), 'label_members' => t('Members'),
@ -206,14 +208,14 @@ function group_content(App $a) {
$sec_token = addslashes(get_form_security_token('group_member_change')); $sec_token = addslashes(get_form_security_token('group_member_change'));
$textmode = (($switchtotext && (count($members) > $switchtotext)) ? true : false); $textmode = (($switchtotext && (count($members) > $switchtotext)) ? true : false);
foreach($members as $member) { foreach ($members as $member) {
if($member['url']) { if ($member['url']) {
$member['click'] = 'groupChangeMember(' . $group['id'] . ',' . $member['id'] . ',\'' . $sec_token . '\'); return true;'; $member['click'] = 'groupChangeMember(' . $group['id'] . ',' . $member['id'] . ',\'' . $sec_token . '\'); return true;';
$groupeditor['members'][] = micropro($member,true,'mpgroup', $textmode); $groupeditor['members'][] = micropro($member,true,'mpgroup', $textmode);
} } else {
else
group_rmv_member(local_user(),$group['name'],$member['id']); group_rmv_member(local_user(),$group['name'],$member['id']);
} }
}
$r = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `blocked` AND NOT `pending` AND NOT `self` ORDER BY `name` ASC", $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `blocked` AND NOT `pending` AND NOT `self` ORDER BY `name` ASC",
intval(local_user()) intval(local_user())
@ -221,8 +223,8 @@ function group_content(App $a) {
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
$textmode = (($switchtotext && (count($r) > $switchtotext)) ? true : false); $textmode = (($switchtotext && (count($r) > $switchtotext)) ? true : false);
foreach($r as $member) { foreach ($r as $member) {
if(! in_array($member['id'],$preselected)) { if (! in_array($member['id'],$preselected)) {
$member['click'] = 'groupChangeMember(' . $group['id'] . ',' . $member['id'] . ',\'' . $sec_token . '\'); return true;'; $member['click'] = 'groupChangeMember(' . $group['id'] . ',' . $member['id'] . ',\'' . $sec_token . '\'); return true;';
$groupeditor['contacts'][] = micropro($member,true,'mpall', $textmode); $groupeditor['contacts'][] = micropro($member,true,'mpall', $textmode);
} }
@ -232,7 +234,7 @@ function group_content(App $a) {
$context['$groupeditor'] = $groupeditor; $context['$groupeditor'] = $groupeditor;
$context['$desc'] = t('Click on a contact to add or remove.'); $context['$desc'] = t('Click on a contact to add or remove.');
if($change) { if ($change) {
$tpl = get_markup_template('groupeditor.tpl'); $tpl = get_markup_template('groupeditor.tpl');
echo replace_macros($tpl, $context); echo replace_macros($tpl, $context);
killme(); killme();

View file

@ -30,9 +30,10 @@ function help_content(App $a) {
$path = ''; $path = '';
// looping through the argv keys bigger than 0 to build // looping through the argv keys bigger than 0 to build
// a path relative to /help // a path relative to /help
for($x = 1; $x < argc(); $x ++) { for ($x = 1; $x < argc(); $x ++) {
if(strlen($path)) if (strlen($path)) {
$path .= '/'; $path .= '/';
}
$path .= argv($x); $path .= argv($x);
} }
$title = basename($path); $title = basename($path);
@ -65,16 +66,22 @@ function help_content(App $a) {
$toc="<style>aside ul {padding-left: 1em;}aside h1{font-size:2em}</style><h2>TOC</h2><ul id='toc'>"; $toc="<style>aside ul {padding-left: 1em;}aside h1{font-size:2em}</style><h2>TOC</h2><ul id='toc'>";
$lastlevel=1; $lastlevel=1;
$idnum = array(0,0,0,0,0,0,0); $idnum = array(0,0,0,0,0,0,0);
foreach($lines as &$line){ foreach ($lines as &$line){
if (substr($line,0,2)=="<h") { if (substr($line,0,2)=="<h") {
$level = substr($line,2,1); $level = substr($line,2,1);
if ($level!="r") { if ($level!="r") {
$level = intval($level); $level = intval($level);
if ($level<$lastlevel) { if ($level<$lastlevel) {
for($k=$level;$k<$lastlevel; $k++) $toc.="</ul>"; for ($k=$level;$k<$lastlevel; $k++) {
for($k=$level+1;$k<count($idnum);$k++) $idnum[$k]=0; $toc.="</ul>";
}
for ($k=$level+1;$k<count($idnum);$k++) {
$idnum[$k]=0;
}
}
if ($level>$lastlevel) {
$toc.="<ul>";
} }
if ($level>$lastlevel) $toc.="<ul>";
$idnum[$level]++; $idnum[$level]++;
$id = implode("_", array_slice($idnum,1,$level)); $id = implode("_", array_slice($idnum,1,$level));
$href = App::get_baseurl()."/help/{$filename}#{$id}"; $href = App::get_baseurl()."/help/{$filename}#{$id}";
@ -84,7 +91,7 @@ function help_content(App $a) {
} }
} }
} }
for($k=0;$k<$lastlevel; $k++) $toc.="</ul>"; for ($k=0;$k<$lastlevel; $k++) $toc.="</ul>";
$html = implode("\n",$lines); $html = implode("\n",$lines);
$a->page['aside'] = $toc.$a->page['aside']; $a->page['aside'] = $toc.$a->page['aside'];

View file

@ -1,6 +1,6 @@
<?php <?php
if(! function_exists('home_init')) { if (! function_exists('home_init')) {
function home_init(App $a) { function home_init(App $a) {
$ret = array(); $ret = array();
@ -16,7 +16,7 @@ function home_init(App $a) {
}} }}
if(! function_exists('home_content')) { if (! function_exists('home_content')) {
function home_content(App $a) { function home_content(App $a) {
$o = ''; $o = '';

View file

@ -7,7 +7,7 @@ function hostxrd_init(App $a) {
header("Content-type: text/xml"); header("Content-type: text/xml");
$pubkey = get_config('system','site_pubkey'); $pubkey = get_config('system','site_pubkey');
if(! $pubkey) { if (! $pubkey) {
$res = new_keypair(1024); $res = new_keypair(1024);
set_config('system','site_prvkey', $res['prvkey']); set_config('system','site_prvkey', $res['prvkey']);

View file

@ -20,7 +20,7 @@ function hovercard_content() {
$datatype = (x($_REQUEST,'datatype') ?$_REQUEST['datatype'] : "json"); $datatype = (x($_REQUEST,'datatype') ?$_REQUEST['datatype'] : "json");
// Get out if the system doesn't have public access allowed // Get out if the system doesn't have public access allowed
if(intval(get_config('system','block_public'))) if (intval(get_config('system','block_public')))
http_status_exit(401); http_status_exit(401);
// Return the raw content of the template. We use this to make templates usable for js functions. // Return the raw content of the template. We use this to make templates usable for js functions.
@ -36,7 +36,7 @@ function hovercard_content() {
// If a contact is connected the url is internally changed to "redir/CID". We need the pure url to search for // If a contact is connected the url is internally changed to "redir/CID". We need the pure url to search for
// the contact. So we strip out the contact id from the internal url and look in the contact table for // the contact. So we strip out the contact id from the internal url and look in the contact table for
// the real url (nurl) // the real url (nurl)
if(local_user() && strpos($profileurl, "redir/") === 0) { if (local_user() && strpos($profileurl, "redir/") === 0) {
$cid = intval(substr($profileurl, 6)); $cid = intval(substr($profileurl, 6));
$r = q("SELECT `nurl`, `self` FROM `contact` WHERE `id` = '%d' LIMIT 1", intval($cid)); $r = q("SELECT `nurl`, `self` FROM `contact` WHERE `id` = '%d' LIMIT 1", intval($cid));
$profileurl = ($r[0]["nurl"] ? $r[0]["nurl"] : ""); $profileurl = ($r[0]["nurl"] ? $r[0]["nurl"] : "");
@ -45,16 +45,16 @@ function hovercard_content() {
// if it's the url containing https it should be converted to http // if it's the url containing https it should be converted to http
$nurl = normalise_link(clean_contact_url($profileurl)); $nurl = normalise_link(clean_contact_url($profileurl));
if($nurl) { if ($nurl) {
// Search for contact data // Search for contact data
$contact = get_contact_details_by_url($nurl); $contact = get_contact_details_by_url($nurl);
} }
if(!is_array($contact)) if (!is_array($contact))
return; return;
// Get the photo_menu - the menu if possible contact actions // Get the photo_menu - the menu if possible contact actions
if(local_user()) if (local_user())
$actions = contact_photo_menu($contact); $actions = contact_photo_menu($contact);
@ -80,7 +80,7 @@ function hovercard_content() {
'account_type' => account_type($contact), 'account_type' => account_type($contact),
'actions' => $actions, 'actions' => $actions,
); );
if($datatype == "html") { if ($datatype == "html") {
$t = get_markup_template("hovercard.tpl"); $t = get_markup_template("hovercard.tpl");
$o = replace_macros($t, array( $o = replace_macros($t, array(
@ -110,7 +110,7 @@ function get_template_content($template, $root = "") {
$filename = $t->filename; $filename = $t->filename;
// Get the content of the template file // Get the content of the template file
if(file_exists($filename)) { if (file_exists($filename)) {
$content = file_get_contents($filename); $content = file_get_contents($filename);
return $content; return $content;

View file

@ -37,8 +37,11 @@ function ignored_init(App $a) {
$return_path = ((x($_REQUEST,'return')) ? $_REQUEST['return'] : ''); $return_path = ((x($_REQUEST,'return')) ? $_REQUEST['return'] : '');
if ($return_path) { if ($return_path) {
$rand = '_=' . time(); $rand = '_=' . time();
if(strpos($return_path, '?')) $rand = "&$rand"; if (strpos($return_path, '?')) {
else $rand = "?$rand"; $rand = "&$rand";
} else {
$rand = "?$rand";
}
goaway(App::get_baseurl() . "/" . $return_path . $rand); goaway(App::get_baseurl() . "/" . $return_path . $rand);
} }

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