// authorisation to do this.
function user_remove($uid) {
- if(! $uid)
+ if (! $uid)
return;
logger('Removing user: ' . $uid);
// Send an update to the directory
proc_run(PRIORITY_LOW, "include/directory.php", $r[0]['url']);
- if($uid == local_user()) {
+ if ($uid == local_user()) {
unset($_SESSION['authenticated']);
unset($_SESSION['uid']);
goaway(App::get_baseurl());
function mark_for_death($contact) {
- if($contact['archive'])
+ if ($contact['archive'])
return;
- if($contact['term-date'] == '0000-00-00 00:00:00') {
+ if ($contact['term-date'] == '0000-00-00 00:00:00') {
q("UPDATE `contact` SET `term-date` = '%s' WHERE `id` = %d",
dbesc(datetime_convert()),
intval($contact['id'])
/// Check for contact vitality via probing
$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.
// archive them rather than delete
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) ",
intval($uid),
intval($uid)
function formatted_location($profile) {
$location = '';
- if($profile['locality'])
+ if ($profile['locality'])
$location .= $profile['locality'];
- if($profile['region'] AND ($profile['locality'] != $profile['region'])) {
- if($location)
+ if ($profile['region'] AND ($profile['locality'] != $profile['region'])) {
+ if ($location)
$location .= ', ';
$location .= $profile['region'];
}
- if($profile['country-name']) {
- if($location)
+ if ($profile['country-name']) {
+ if ($location)
$location .= ', ';
$location .= $profile['country-name'];
// "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.
// "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['forum']) && intval($contact['forum']))
|| (isset($contact['prv']) && intval($contact['prv']))
*/
public static function global_search_by_name($search, $mode = '') {
- if($search) {
+ if ($search) {
// check supported networks
if (get_config('system','diaspora_enabled'))
$diaspora = NETWORK_DIASPORA;
$ostatus = NETWORK_DFRN;
// check if we search only communities or every contact
- if($mode === "community")
+ if ($mode === "community") {
$extra_sql = " AND `community`";
- else
+ } else {
$extra_sql = "";
+ }
$search .= "%";
*/
public static function widget($uid,$cid = 0) {
- if(! intval(feature_enabled(local_user(),'forumlist_widget')))
+ if (! intval(feature_enabled(local_user(),'forumlist_widget')))
return;
$o = '';
public static function profile_advanced($uid) {
$profile = intval(feature_enabled($uid,'forumlist_profile'));
- if(! $profile)
+ if (! $profile)
return;
$o = '';
foreach($contacts as $contact) {
$forumlist .= micropro($contact,false,'forumlist-profile-advanced');
$total_shown ++;
- if($total_shown == $show_total)
+
+ if ($total_shown == $show_total) {
break;
+ }
}
- if(count($contacts) > 0)
+ if (count($contacts) > 0) {
$o .= $forumlist;
- return $o;
+ }
+
+ return $o;
}
/**
}
$order_sql = implode(", ", $asOrder);
- if($limit!="")
+ if ($limit!="")
$limit = " LIMIT ".$limit;
$r = q("SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
private function networkTotal($seen = 0) {
$sql_seen = "";
- if($seen === 0)
+ if ($seen === 0)
$sql_seen = " AND `item`.`unseen` = 1 ";
$r = q("SELECT COUNT(*) AS `total`
$notifs = array();
$sql_seen = "";
- if($seen === 0)
+ if ($seen === 0)
$sql_seen = " AND `item`.`unseen` = 1 ";
private function systemTotal($seen = 0) {
$sql_seen = "";
- if($seen === 0)
+ if ($seen === 0)
$sql_seen = " AND `seen` = 0 ";
$r = q("SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen",
$notifs = array();
$sql_seen = "";
- if($seen === 0)
+ if ($seen === 0)
$sql_seen = " AND `seen` = 0 ";
$r = q("SELECT `id`, `url`, `photo`, `msg`, `date`, `seen` FROM `notify`
$sql_seen = "";
$sql_extra = $this->_personal_sql_extra();
- if($seen === 0)
+ if ($seen === 0)
$sql_seen = " AND `item`.`unseen` = 1 ";
$r = q("SELECT COUNT(*) AS `total`
$notifs = array();
$sql_seen = "";
- if($seen === 0)
+ if ($seen === 0)
$sql_seen = " AND `item`.`unseen` = 1 ";
$r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
private function homeTotal($seen = 0) {
$sql_seen = "";
- if($seen === 0)
+ if ($seen === 0)
$sql_seen = " AND `item`.`unseen` = 1 ";
$r = q("SELECT COUNT(*) AS `total` FROM `item`
$notifs = array();
$sql_seen = "";
- if($seen === 0)
+ if ($seen === 0)
$sql_seen = " AND `item`.`unseen` = 1 ";
$r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
private function introTotal($all = false) {
$sql_extra = "";
- if(!$all)
+ if (!$all)
$sql_extra = " AND `ignore` = 0 ";
$r = q("SELECT COUNT(*) AS `total` FROM `intro`
$notifs = array();
$sql_extra = "";
- if(!$all)
+ if (!$all)
$sql_extra = " AND `ignore` = 0 ";
/// @todo Fetch contact details by "get_contact_details_by_url" instead of queries to contact, fcontact and gcontact
// We have to distinguish between these two because they use different data.
// 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 : ''));
$it['gnetwork'] = $ret["network"];
// 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['gabout'] = "";
$it['ggender'] = "";
*/
public static function valid_dfrn($data) {
$errors = 0;
- if(!isset($data['key']))
+ if (!isset($data['key']))
$errors ++;
- if(!isset($data['dfrn-request']))
+ if (!isset($data['dfrn-request']))
$errors ++;
- if(!isset($data['dfrn-confirm']))
+ if (!isset($data['dfrn-confirm']))
$errors ++;
- if(!isset($data['dfrn-notify']))
+ if (!isset($data['dfrn-notify']))
$errors ++;
- if(!isset($data['dfrn-poll']))
+ if (!isset($data['dfrn-poll']))
$errors ++;
return $errors;
}
$password = '';
openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']);
$mbox = email_connect($mailbox,$r[0]['user'], $password);
- if(!mbox)
+ if (!$mbox) {
return false;
+ }
}
$msgs = email_poll($mbox, $uri);
logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
- if (!count($msgs))
+ if (!count($msgs)) {
return false;
+ }
$data = array();
$data["poll"] = 'email '.random_string();
$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, '');
- elseif(stristr($x[0]->to, $uri))
+ } elseif (stristr($x[0]->to, $uri)) {
$adr = imap_rfc822_parse_adrlist($x[0]->to, '');
- if(isset($adr)) {
+ }
+ if (isset($adr)) {
foreach($adr as $feadr) {
- if((strcasecmp($feadr->mailbox, $data["name"]) == 0)
+ if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
&&(strcasecmp($feadr->host, $phost) == 0)
&& (strlen($feadr->personal))) {
* @return string HML Output of the Smilie
*/
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'))))
return $s;
$params = self::get_list();
$params['string'] = $s;
- if($sample) {
+ if ($sample) {
$s = '<div class="smiley-sample">';
for($x = 0; $x < count($params['texts']); $x ++) {
$s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
* @todo: Rework because it doesn't work correctly
*/
private function preg_heart($x) {
- if(strlen($x[1]) == 1)
+ if (strlen($x[1]) == 1) {
return $x[0];
+ }
$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="<3" />';
+ }
$r = str_replace($x[0],$t,$x[0]);
return $r;
}
if (dbm::is_result($r)) {
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\" ";
else
$selected = '';
$networks = array(NETWORK_DFRN);
break;
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);
else
$networks = array(NETWORK_DFRN,NETWORK_FACEBOOK,NETWORK_MAIL, NETWORK_DIASPORA);
break;
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);
else
$networks = array(NETWORK_DFRN,NETWORK_FACEBOOK,NETWORK_MAIL,NETWORK_DIASPORA,NETWORK_OSTATUS);
$sql_extra = '';
- if($x['mutual']) {
+ if ($x['mutual']) {
$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']));
- if(is_array($x['networks']) && count($x['networks'])) {
+ if (is_array($x['networks']) && count($x['networks'])) {
for($y = 0; $y < count($x['networks']) ; $y ++)
$x['networks'][$y] = "'" . dbesc($x['networks'][$y]) . "'";
$str_nets = implode(',',$x['networks']);
$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";
else
$o .= "<select name=\"{$selname}[]\" id=\"$selclass\" class=\"$selclass\" multiple=\"multiple\" size=\"" . $x['size'] . "$\" $tabindex >\r\n";
$sql_extra = '';
- if($privmail || $celeb) {
+ if ($privmail || $celeb) {
$sql_extra .= sprintf(" AND `rel` = %d ", intval(CONTACT_IS_FRIEND));
}
- if($privmail)
+ if ($privmail)
$sql_extra .= sprintf(" AND `network` IN ('%s' , '%s') ",
NETWORK_DFRN, NETWORK_DIASPORA);
- elseif($privatenet)
+ elseif ($privatenet)
$sql_extra .= sprintf(" AND `network` IN ('%s' , '%s', '%s', '%s') ",
NETWORK_DFRN, NETWORK_MAIL, NETWORK_FACEBOOK, NETWORK_DIASPORA);
} else
$hidepreselected = "";
- if($privmail)
+ if ($privmail)
$o .= "<select name=\"$selname\" id=\"$selclass\" class=\"$selclass\" size=\"$size\" $tabindex $hidepreselected>\r\n";
else
$o .= "<select name=\"{$selname}[]\" id=\"$selclass\" class=\"$selclass\" multiple=\"multiple\" size=\"$size\" $tabindex >\r\n";
function get_acl_permissions($user = null) {
$allow_cid = $allow_gid = $deny_cid = $deny_gid = false;
- if(is_array($user)) {
+ if (is_array($user)) {
$allow_cid = ((strlen($user['allow_cid']))
? explode('><', $user['allow_cid']) : array() );
$allow_gid = ((strlen($user['allow_gid']))
$perms = get_acl_permissions($user);
$jotnets = '';
- if($show_jotnets) {
+ if ($show_jotnets) {
$mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
$mail_enabled = false;
$pubmail_enabled = false;
- if(! $mail_disabled) {
+ if (! $mail_disabled) {
$r = q("SELECT `pubmail` FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
intval(local_user())
);
if (dbm::is_result($r)) {
$mail_enabled = true;
- if(intval($r[0]['pubmail']))
+ if (intval($r[0]['pubmail']))
$pubmail_enabled = true;
}
}
if (!$user['hidewall']) {
- if($mail_enabled) {
+ if ($mail_enabled) {
$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>';
}
$user_defaults = get_acl_permissions($user);
- if($acl_data['groups']) {
+ if ($acl_data['groups']) {
foreach($acl_data['groups'] as $key=>$group) {
// 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']) )
$acl_data['groups'][$key]['selected'] = 1;
else
$acl_data['groups'][$key]['selected'] = 0;
}
}
- if($acl_data['contacts']) {
+ if ($acl_data['contacts']) {
foreach($acl_data['contacts'] as $key=>$contact) {
// 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']) )
$acl_data['contacts'][$key]['selected'] = 1;
else
// For use with jquery.textcomplete for private mail completion
- if(x($_REQUEST,'query') && strlen($_REQUEST['query'])) {
- if(! $type)
+ if (x($_REQUEST,'query') && strlen($_REQUEST['query'])) {
+ if (! $type)
$type = 'm';
$search = $_REQUEST['query'];
}
dbesc(NETWORK_STATUSNET)
);
}
- elseif($type == 'm') {
+ elseif ($type == 'm') {
$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`
AND `network` IN ('%s','%s','%s')
call_hooks('acl_lookup_end', $results);
- if($out_type === 'html') {
+ if ($out_type === 'html') {
$o = array(
'tot' => $results['tot'],
'start' => $results['start'],
// 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)) ;
- if(strlen($userpass)) {
+ if (strlen($userpass)) {
list($name, $password) = explode(':', $userpass);
$_SERVER['PHP_AUTH_USER'] = $name;
$_SERVER['PHP_AUTH_PW'] = $password;
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'];
}
else {
$record = $r[0];
}
- if((! $record) || (! count($record))) {
+ if ((! $record) || (! count($record))) {
logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
header('WWW-Authenticate: Basic realm="Friendica"');
#header('HTTP/1.0 401 Unauthorized');
logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
// 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));
$url = $user;
$extra_query = "AND `contact`.`nurl` = '%s' ";
}
// 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));
if ($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']));
if ($user == "")
$extra_query = "AND `contact`.`nurl` = '%s' ";
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']);
$nick = $user;
$extra_query = "AND `contact`.`nick` = '%s' ";
if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
$argid = count($called_api);
list($user, $null) = explode(".",$a->argv[$argid]);
- if(is_numeric($user)){
+ if (is_numeric($user)){
$user = dbesc(api_unique_id_to_url($user));
if ($user == "")
}
}
- if($uinfo[0]['self']) {
+ if ($uinfo[0]['self']) {
if ($uinfo[0]['network'] == "")
$uinfo[0]['network'] = NETWORK_DFRN;
$starred = $r[0]['count'];
- if(! $uinfo[0]['self']) {
+ if (! $uinfo[0]['self']) {
$countfriends = 0;
$countfollowers = 0;
$starred = 0;
$txt = requestdata('status');
//$txt = urldecode(requestdata('status'));
- if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
+ if ((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
$txt = html2bb_video($txt);
$config = HTMLPurifier_Config::createDefault();
// logger('api_post: ' . print_r($_POST,true));
- if(requestdata('htmlstatus')) {
+ if (requestdata('htmlstatus')) {
$txt = requestdata('htmlstatus');
- if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
+ if ((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
$txt = html2bb_video($txt);
$config = HTMLPurifier_Config::createDefault();
if ($parent == -1)
$parent = "";
- if(ctype_digit($parent))
+ if (ctype_digit($parent))
$_REQUEST['parent'] = $parent;
else
$_REQUEST['parent_uri'] = $parent;
- if(requestdata('lat') && requestdata('long'))
+ if (requestdata('lat') && requestdata('long'))
$_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
$_REQUEST['profile_uid'] = api_user();
- if($parent)
+ if ($parent)
$_REQUEST['type'] = 'net-comment';
else {
// Check for throttling (maximum posts per day, week and month)
$_REQUEST['type'] = 'wall';
}
- if(x($_FILES,'media')) {
+ if (x($_FILES,'media')) {
// upload the image if we have one
$_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
$media = wall_upload_post($a);
- if(strlen($media)>0)
+ if (strlen($media)>0)
$_REQUEST['body'] .= "\n\n".$media;
}
$user_info = api_get_user($a);
- if(!x($_FILES,'media')) {
+ if (!x($_FILES,'media')) {
// Output error
throw new BadRequestException("No media.");
}
$media = wall_upload_post($a, false);
- if(!$media) {
+ if (!$media) {
// Output error
throw new InternalServerErrorException();
}
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));
- if($qtype == 'followers')
+ if ($qtype == 'followers')
$sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
// friends and followers only for self
$closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
$private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
$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']);
$ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
$sslserver = (($ssl === 'true') ? str_replace('http:','https:',App::get_baseurl()) : '');
$a = get_app();
- if(! api_user()) throw new ForbiddenException();
+ if (! api_user()) throw new ForbiddenException();
$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));
- if($qtype == 'followers')
+ if ($qtype == 'followers')
$sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
if (!$user_info["self"])
if ($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). "'";
}
);
if ($verbose == "true") {
// stop execution and return error message if no mails available
- if($r == null) {
+ if ($r == null) {
$answer = array('result' => 'error', 'message' => 'no mails available');
return api_format_data("direct_messages_all", $type, array('$result' => $answer));
}
function api_fr_photo_detail($type) {
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_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
$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'];
$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'];
$dfrn_id = '0:' . $orig_id;
}
);
$dot = strpos($filename,'.');
- if($dot !== false) {
+ if ($dot !== false) {
$ext = strtolower(substr($filename,$dot+1));
if (array_key_exists($ext, $mime_types)) {
return $mime_types[$ext];
function format_event_diaspora($ev) {
- if(! ((is_array($ev)) && count($ev)))
+ if (! ((is_array($ev)) && count($ev)))
return '';
$bd_format = t('l F d, Y \@ g:i A') ; // Friday January 18, 2011 @ 8 AM
$ev['start'] , $bd_format)))
. '](' . App::get_baseurl() . '/localtime/?f=&time=' . urlencode(datetime_convert('UTC','UTC',$ev['start'])) . ")\n";
- if(! $ev['nofinish'])
+ if (! $ev['nofinish'])
$o .= t('Finishes:') . ' ' . '['
. (($ev['adjust']) ? day_translate(datetime_convert('UTC', 'UTC',
$ev['finish'] , $bd_format ))
$ev['finish'] , $bd_format )))
. '](' . 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'])
. "\n";
function bb_find_open_close($s, $open, $close, $occurance = 1) {
- if($occurance < 1)
+ if ($occurance < 1)
$occurance = 1;
$start_pos = -1;
for($i = 1; $i <= $occurance; $i++) {
- if( $start_pos !== false)
+ if ( $start_pos !== false)
$start_pos = strpos($s, $open, $start_pos + 1);
}
- if( $start_pos === false)
+ if ( $start_pos === false)
return false;
$end_pos = strpos($s, $close, $start_pos);
- if( $end_pos === false)
+ if ( $end_pos === false)
return false;
$res = array( 'start' => $start_pos, 'end' => $end_pos );
function get_bb_tag_pos($s, $name, $occurance = 1) {
- if($occurance < 1)
+ if ($occurance < 1)
$occurance = 1;
$start_open = -1;
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
}
- if( $start_open === false)
+ if ( $start_open === false)
return false;
$start_equal = strpos($s, '=', $start_open);
$start_close = strpos($s, ']', $start_open);
- if( $start_close === false)
+ if ( $start_close === false)
return false;
$start_close++;
$end_open = strpos($s, '[/' . $name . ']', $start_close);
- if( $end_open === false)
+ if ( $end_open === false)
return false;
$res = array( 'start' => array('open' => $start_open, 'close' => $start_close),
'end' => array('open' => $end_open, 'close' => $end_open + strlen('[/' . $name . ']')) );
- if( $start_equal !== false)
+ if ( $start_equal !== false)
$res['start']['equal'] = $start_equal + 1;
return $res;
$occurance = 1;
$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']);
$subject = substr($string, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
$end = substr($string, $pos['end']['close']);
- if($end === false)
+ if ($end === false)
$end = '';
$subject = preg_replace($pattern, $replace, $subject);
return $string;
}
-if(! function_exists('bb_extract_images')) {
+if (! function_exists('bb_extract_images')) {
function bb_extract_images($body) {
$saved_image = array();
$img_start = strpos($orig_body, '[img');
$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);
- 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_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
$saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
$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 = '';
$img_start = strpos($orig_body, '[img');
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) {
$newbody = $body;
function bb_RemovePictureLinks($match) {
$text = Cache::get($match[1]);
- if(is_null($text)){
+ if (is_null($text)){
$a = get_app();
$stamp1 = microtime(true);
function bb_CleanPictureLinksSub($match) {
$text = Cache::get($match[1]);
- if(is_null($text)){
+ if (is_null($text)){
$a = get_app();
$stamp1 = microtime(true);
}
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']))
return text_highlight($match[2],strtolower($match[1]));
return $match[0];
$Text = str_replace(array("\r","\n"), array('<br />','<br />'), $Text);
- if($preserve_nl)
+ if ($preserve_nl)
$Text = str_replace(array("\n","\r"), array('',''),$Text);
// Set up the parameters for a URL search string
// Summary (e.g. title) is required, earlier revisions only required description (in addition to
// start which is always required). Allow desc with a missing summary for compatibility.
- if((x($ev,'desc') || x($ev,'summary')) && x($ev,'start')) {
+ if ((x($ev,'desc') || x($ev,'summary')) && x($ev,'start')) {
$sub = format_event_html($ev, $simplehtml);
$Text = preg_replace("/\[event\-summary\](.*?)\[\/event\-summary\]/ism",'',$Text);
$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);
- if($saved_image) {
+ if ($saved_image) {
$Text = bb_replace_images($Text, $saved_image);
}
require_once("dba.php");
$db = new dba($db_host, $db_user, $db_pass, $db_data);
unset($db_host, $db_user, $db_pass, $db_data);
- };
+ };
require_once('include/session.php');
$a = get_app();
- if(get_config('system','invitation_only')) {
+ if (get_config('system','invitation_only')) {
$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">'
. sprintf( tt('%d invitation available','%d invitations available',$x), $x)
. '</div>' . $inv;
}
}
- if(count($nets) < 2)
+ if (count($nets) < 2)
return '';
return replace_macros(get_markup_template('nets.tpl'),array(
$matches = false;
$terms = array();
$cnt = preg_match_all('/<(.*?)>/',$saved,$matches,PREG_SET_ORDER);
- if($cnt) {
+ if ($cnt) {
foreach($matches as $mtch) {
$unescaped = xmlify(file_tag_decode($mtch[1]));
$terms[] = array('name' => $unescaped,'selected' => (($selected == $unescaped) ? 'selected' : ''));
$a = get_app();
- if(local_user() == $profile_uid)
+ if (local_user() == $profile_uid)
return;
$cid = $zcid = 0;
- if(is_array($_SESSION['remote'])) {
+ if (is_array($_SESSION['remote'])) {
foreach($_SESSION['remote'] as $visitor) {
- if($visitor['uid'] == $profile_uid) {
+ if ($visitor['uid'] == $profile_uid) {
$cid = $visitor['cid'];
break;
}
}
}
- if(! $cid) {
- if(get_my_url()) {
+ if (! $cid) {
+ if (get_my_url()) {
$r = q("select id from contact where nurl = '%s' and uid = %d limit 1",
dbesc(normalise_link(get_my_url())),
intval($profile_uid)
);
- if (dbm::is_result($r))
+ if (dbm::is_result($r)) {
$cid = $r[0]['id'];
- else {
+ } else {
$r = q("select id from gcontact where nurl = '%s' limit 1",
dbesc(normalise_link(get_my_url()))
);
}
}
- if($cid == 0 && $zcid == 0)
+ if ($cid == 0 && $zcid == 0) {
return;
+ }
require_once('include/socgraph.php');
- if($cid)
+ if ($cid) {
$t = count_common_friends($profile_uid,$cid);
- else
+ } else {
$t = count_common_friends_zcid($profile_uid,$zcid);
- if(! $t)
+ }
+ if (! $t) {
return;
+ }
- if($cid)
+ if ($cid) {
$r = common_friends($profile_uid,$cid,0,5,true);
- else
+ } else {
$r = common_friends_zcid($profile_uid,$zcid,0,5,true);
+ }
return replace_macros(get_markup_template('remote_friends_common.tpl'), array(
'$desc' => sprintf( tt("%d contact in common", "%d contacts in common", $t), $t),
// 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
// 'item_redir_and_replace_images'
-if(! function_exists('item_extract_images')) {
+if (! function_exists('item_extract_images')) {
function item_extract_images($body) {
$saved_image = array();
$img_start = strpos($orig_body, '[img');
$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);
- 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_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
$saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
$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 = '';
$img_start = strpos($orig_body, '[img');
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) {
$origbody = $body;
$cnt = 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';
$replace = '[url=' . z_path() . '/redir/' . $cid
$newbody .= substr($origbody, 0, $pos['start']['open']);
$subject = substr($origbody, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
$origbody = substr($origbody, $pos['end']['close']);
- if($origbody === false)
+ if ($origbody === false)
$origbody = '';
$subject = preg_replace($search, $replace, $subject);
function localize_item(&$item){
$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']);
$xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
}
break;
default:
- if($obj['resource-id']){
+ if ($obj['resource-id']){
$post_type = t('photo');
$m=array(); preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
$rr['plink'] = $m[1];
$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');
}
- 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');
}
- elseif(activity_match($item['verb'],ACTIVITY_ATTEND)) {
+ elseif (activity_match($item['verb'],ACTIVITY_ATTEND)) {
$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');
}
- 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');
}
$item['body'] = sprintf($bodyverb, $author, $objauthor, $plink);
}
if (stristr($item['verb'],ACTIVITY_POKE)) {
$verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
- if(! $verb)
+ if (! $verb)
return;
if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return;
}
if (stristr($item['verb'],ACTIVITY_MOOD)) {
$verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
- if(! $verb)
+ if (! $verb)
return;
$Aname = $item['author-name'];
}
break;
default:
- if($obj['resource-id']){
+ if ($obj['resource-id']){
$post_type = t('photo');
$m=array(); preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
$rr['plink'] = $m[1];
$xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
$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",
dbesc($obj->id),
intval($item['uid'])
}
}
$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) {
- if(! strpos($mtch[1],'zrl='))
+ if (! strpos($mtch[1],'zrl='))
$item['body'] = str_replace($mtch[0],'@[url=' . zrl($mtch[1]). ']',$item['body']);
}
}
// add zrl's to public images
$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]';
$item['body'] = bb_tag_preg_replace($photo_pattern, $photo_replace, 'url', $item['body']);
}
function count_descendants($item) {
$total = count($item['children']);
- if($total > 0) {
+ if ($total > 0) {
foreach($item['children'] as $child) {
- if(! visible_activity($child))
+ if (! visible_activity($child))
$total --;
$total += count_descendants($child);
}
$hidden_activities = array(ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE);
foreach($hidden_activities as $act) {
- if(activity_match($item['verb'],$act)) {
+ if (activity_match($item['verb'],$act)) {
return false;
}
}
- if(activity_match($item['verb'],ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE) {
- if(! (($item['self']) && ($item['uid'] == local_user()))) {
+ if (activity_match($item['verb'],ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE) {
+ if (! (($item['self']) && ($item['uid'] == local_user()))) {
return false;
}
}
*
*/
-if(!function_exists('conversation')) {
+if (!function_exists('conversation')) {
function conversation(App $a, $items, $mode, $update, $preview = false) {
require_once('include/bbcode.php');
$arr_blocked = null;
- if(local_user()) {
+ if (local_user()) {
$str_blocked = get_pconfig(local_user(),'system','blocked');
- if($str_blocked) {
+ if ($str_blocked) {
$arr_blocked = explode(',',$str_blocked);
for($x = 0; $x < count($arr_blocked); $x ++)
$arr_blocked[$x] = trim($arr_blocked[$x]);
$previewing = (($preview) ? ' preview ' : '');
- if($mode === 'network') {
+ if ($mode === 'network') {
$profile_owner = local_user();
$page_writeable = true;
- if(!$update) {
+ if (!$update) {
// The special div is needed for liveUpdate to kick in for this page.
// We only launch liveUpdate if you aren't filtering in some incompatible
// way and also you aren't writing a comment (discovered in javascript).
. "'; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
}
}
- else if($mode === 'profile') {
+ else if ($mode === 'profile') {
$profile_owner = $a->profile['profile_uid'];
$page_writeable = can_write_wall($a,$profile_owner);
- if(!$update) {
+ if (!$update) {
$tab = notags(trim($_GET['tab']));
$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,
// because browser prefetching might change it on us. We have to deliver it with the page.
}
}
}
- else if($mode === 'notes') {
+ else if ($mode === 'notes') {
$profile_owner = local_user();
$page_writeable = true;
- if(!$update) {
+ if (!$update) {
$live_update_div = '<div id="live-notes"></div>' . "\r\n"
. "<script> var profile_uid = " . local_user()
. "; 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'];
$page_writeable = can_write_wall($a,$profile_owner);
- if(!$update) {
+ if (!$update) {
$live_update_div = '<div id="live-display"></div>' . "\r\n"
. "<script> var profile_uid = " . $_SESSION['uid'] . ";"
. " var profile_page = 1; </script>";
}
}
- else if($mode === 'community') {
+ else if ($mode === 'community') {
$profile_owner = 0;
$page_writeable = false;
- if(!$update) {
+ if (!$update) {
$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";
}
}
- else if($mode === 'search') {
+ else if ($mode === 'search') {
$live_update_div = '<div id="live-search"></div>' . "\r\n";
}
$page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
- if($update)
+ if ($update)
$return_url = $_SESSION['return_url'];
else
$return_url = $_SESSION['return_url'] = $a->query_string;
$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
// - just loop through the items and format them minimally for display
foreach($items as $item) {
- if($arr_blocked) {
+ if ($arr_blocked) {
$blocked = false;
foreach($arr_blocked as $b) {
- if($b && link_compare($item['author-link'],$b)) {
+ if ($b && link_compare($item['author-link'],$b)) {
$blocked = true;
break;
}
}
- if($blocked)
+ if ($blocked)
continue;
}
$owner_name = '';
$sparkle = '';
- if($mode === 'search' || $mode === 'community') {
- if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE)))
+ if ($mode === 'search' || $mode === 'community') {
+ if (((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE)))
&& ($item['id'] != $item['parent']))
continue;
$nickname = $item['nickname'];
$nickname = $a->user['nickname'];
// prevent private email from leaking.
- if($item['network'] === NETWORK_MAIL && local_user() != $item['uid'])
+ if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid'])
continue;
$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'];
$sp = false;
$profile_link = best_link_url($item,$sp);
- if($profile_link === 'mailbox')
+ if ($profile_link === 'mailbox')
$profile_link = '';
- if($sp)
+ if ($sp)
$sparkle = ' sparkle';
else
$profile_link = zrl($profile_link);
$location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
localize_item($item);
- if($mode === 'network-new')
+ if ($mode === 'network-new')
$dropping = true;
else
$dropping = false;
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);
$item['title_e'] = template_escape($item['title']);
$body_e = template_escape($body);
$threads = array();
foreach($items as $item) {
- if($arr_blocked) {
+ if ($arr_blocked) {
$blocked = false;
foreach($arr_blocked as $b) {
- if($b && link_compare($item['author-link'],$b)) {
+ if ($b && link_compare($item['author-link'],$b)) {
$blocked = true;
break;
}
}
- if($blocked)
+ if ($blocked)
continue;
}
builtin_activity_puller($item, $conv_responses);
// Only add what is visible
- if($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
+ if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
continue;
}
- if(! visible_activity($item)) {
+ if (! visible_activity($item)) {
continue;
}
$item['pagedrop'] = $page_dropping;
- if($item['id'] == $item['parent']) {
+ if ($item['id'] == $item['parent']) {
$item_object = new Item($item);
$conv->add_thread($item_object);
}
$threads = $conv->get_template_data($conv_responses);
- if(!$threads) {
+ if (!$threads) {
logger('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG);
$threads = array();
}
$sparkle = true;
}
}
- if(! $best_url) {
- if(strlen($item['author-link']))
+ if (! $best_url) {
+ if (strlen($item['author-link']))
$best_url = $item['author-link'];
else
$best_url = $item['url'];
{
$ssl_state = false;
- if(local_user()) {
+ if (local_user()) {
$ssl_state = true;
}
$rel = $r[0]['rel'];
}
- if($sparkle) {
+ if ($sparkle) {
$status_link = $profile_link . '?url=status';
$photos_link = $profile_link . '?url=photos';
$profile_link = $profile_link . '?url=profile';
* @param array &$conv_responses (already created with builtin activity structure)
* @return void
*/
-if(! function_exists('builtin_activity_puller')) {
+if (! function_exists('builtin_activity_puller')) {
function builtin_activity_puller($item, &$conv_responses) {
foreach($conv_responses as $mode => $v) {
$url = '';
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'];
- 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'];
$sparkle = ' class="sparkle" ';
}
$url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
- if(! $item['thr-parent'])
+ if (! $item['thr-parent'])
$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']))))
$conv_responses[$mode][$item['thr-parent'] . '-l'] = array();
// 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;
- if(! isset($conv_responses[$mode][$item['thr-parent']]))
+ if (! isset($conv_responses[$mode][$item['thr-parent']]))
$conv_responses[$mode][$item['thr-parent']] = 1;
else
$conv_responses[$mode][$item['thr-parent']] ++;
// $id = item id
// returns formatted text
-if(! function_exists('format_like')) {
+if (! function_exists('format_like')) {
function format_like($cnt,$arr,$type,$id) {
$o = '';
$expanded = '';
- if($cnt == 1) {
+ if ($cnt == 1) {
$likers = $arr[0];
// Phrase if there is only one liker. In other cases it will be uses for the expanded
}
}
- if($cnt > 1) {
+ if ($cnt > 1) {
$total = count($arr);
- if($total >= MAX_LIKERS)
+ if ($total >= MAX_LIKERS)
$arr = array_slice($arr, 0, MAX_LIKERS - 1);
- if($total < MAX_LIKERS) {
+ if ($total < MAX_LIKERS) {
$last = t('and') . ' ' . $arr[count($arr)-1];
$arr2 = array_slice($arr, 0, -1);
$str = implode(', ', $arr2) . ' ' . $last;
}
- if($total >= MAX_LIKERS) {
+ if ($total >= MAX_LIKERS) {
$str = implode(', ', $arr);
$str .= sprintf( t(', and %d other people'), $total - MAX_LIKERS );
}
// Private/public post links for the non-JS ACL form
$private_post = 1;
- if($_REQUEST['public'])
+ if ($_REQUEST['public'])
$private_post = 0;
$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);
// 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
// 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';
else
$public_post_link = '&public=1';
$children = array();
$a = get_app();
foreach($arr as $item) {
- if($item['id'] != $item['parent']) {
- if(get_config('system','thread_allow') && $a->theme_thread_allow) {
+ if ($item['id'] != $item['parent']) {
+ if (get_config('system','thread_allow') && $a->theme_thread_allow) {
// Fallback to parent-uri if thr-parent is not set
$thr_parent = $item['thr-parent'];
- if($thr_parent == '')
+ if ($thr_parent == '')
$thr_parent = $item['parent-uri'];
- if($thr_parent == $parent['uri']) {
+ if ($thr_parent == $parent['uri']) {
$item['children'] = get_item_children($arr, $item);
$children[] = $item;
}
}
- else if($item['parent'] == $parent['id']) {
+ else if ($item['parent'] == $parent['id']) {
$children[] = $item;
}
}
$result = $items;
usort($result,'sort_thr_created_rev');
foreach($result as $k => $i) {
- if(count($result[$k]['children'])) {
+ if (count($result[$k]['children'])) {
$result[$k]['children'] = sort_item_children($result[$k]['children']);
}
}
function add_children_to_list($children, &$arr) {
foreach($children as $y) {
$arr[] = $y;
- if(count($y['children']))
+ if (count($y['children']))
add_children_to_list($y['children'], $arr);
}
}
function conv_sort($arr,$order) {
- if((!(is_array($arr) && count($arr))))
+ if ((!(is_array($arr) && count($arr))))
return array();
$parents = array();
$arr = $newarr;
foreach($arr as $x)
- if($x['id'] == $x['parent'])
+ if ($x['id'] == $x['parent'])
$parents[] = $x;
- if(stristr($order,'created'))
+ if (stristr($order,'created'))
usort($parents,'sort_thr_created');
- elseif(stristr($order,'commented'))
+ elseif (stristr($order,'commented'))
usort($parents,'sort_thr_commented');
- if(count($parents))
+ if (count($parents))
foreach($parents as $i=>$_x)
$parents[$i]['children'] = get_item_children($arr, $_x);
/*foreach($arr as $x) {
- if($x['id'] != $x['parent']) {
+ if ($x['id'] != $x['parent']) {
$p = find_thread_parent_index($parents,$x);
- if($p !== false)
+ if ($p !== false)
$parents[$p]['children'][] = $x;
}
}*/
- if(count($parents)) {
+ if (count($parents)) {
foreach($parents as $k => $v) {
- if(count($parents[$k]['children'])) {
+ if (count($parents[$k]['children'])) {
$parents[$k]['children'] = sort_item_children($parents[$k]['children']);
/*$y = $parents[$k]['children'];
usort($y,'sort_thr_created_rev');
}
$ret = array();
- if(count($parents)) {
+ if (count($parents)) {
foreach($parents as $x) {
$ret[] = $x;
- if(count($x['children']))
+ if (count($x['children']))
add_children_to_list($x['children'], $ret);
/*foreach($x['children'] as $y)
$ret[] = $y;*/
}
function find_thread_parent_index($arr,$x) {
- foreach($arr as $k => $v)
- if($v['id'] == $x['parent'])
+ foreach($arr as $k => $v) {
+ if ($v['id'] == $x['parent']) {
return $k;
+ }
+ }
return false;
}
$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]['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);
array_push($ret[$v]['list_part'], '<a href="#" data-toggle="modal" data-target="#' . $v . 'Modal-'
. (($ob) ? $ob->get_id() : $item['id']) . '"><b>' . t('View all') . '</b></a>');
- }
- else {
+ } else {
$ret[$v]['list_part'] = '';
}
$ret[$v]['button'] = get_response_button_text($v,$ret[$v]['count']);
$last = get_config('system','last_cron');
$poll_interval = intval(get_config('system','cron_interval'));
- if(! $poll_interval)
+ if (! $poll_interval)
$poll_interval = 10;
- if($last) {
+ if ($last) {
$next = $last + ($poll_interval * 60);
- if($next > time()) {
+ if ($next > time()) {
logger('cron intervall not reached');
return;
}
$d1 = get_config('system','last_expire_day');
$d2 = intval(datetime_convert('UTC','UTC','now','d'));
- if($d2 != intval($d1)) {
+ if ($d2 != intval($d1)) {
update_contact_birthdays();
// we are unable to match those posts with a Diaspora GUID and prevent duplicates.
$abandon_days = intval(get_config('system','account_abandon_days'));
- if($abandon_days < 1)
+ if ($abandon_days < 1)
$abandon_days = 0;
$abandon_sql = (($abandon_days)
$xml = false;
- if($manual_id)
+ if ($manual_id)
$contact['last-update'] = '0000-00-00 00:00:00';
- if(in_array($contact['network'], array(NETWORK_DFRN, NETWORK_ZOT, NETWORK_OSTATUS)))
+ if (in_array($contact['network'], array(NETWORK_DFRN, NETWORK_ZOT, NETWORK_OSTATUS)))
$contact['priority'] = 2;
- if($contact['subhub'] AND in_array($contact['network'], array(NETWORK_DFRN, NETWORK_ZOT, NETWORK_OSTATUS))) {
+ if ($contact['subhub'] AND in_array($contact['network'], array(NETWORK_DFRN, NETWORK_ZOT, NETWORK_OSTATUS))) {
// We should be getting everything via a hub. But just to be sure, let's check once a day.
// (You can make this more or less frequent if desired by setting 'pushpoll_frequency' appropriately)
// This also lets us update our subscription to the hub, and add or replace hubs in case it
$contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
}
- if($contact['priority'] AND !$force) {
+ if ($contact['priority'] AND !$force) {
$update = false;
switch ($contact['priority']) {
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;
break;
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;
break;
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;
break;
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;
break;
case 1:
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;
break;
}
$last = get_config('system','cache_last_cleared');
- if($last) {
+ if ($last) {
$next = $last + (3600); // Once per hour
$clear_cache = ($next <= time());
- } else
+ } else {
$clear_cache = true;
+ }
- if (!$clear_cache)
+ if (!$clear_cache) {
return;
+ }
// clear old cache
Cache::clear();
clear_cache($a->get_basepath(), $a->get_basepath()."/proxy");
$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);
}
// Maximum table size in megabyte
$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
+ }
if ($max_tablesize > 0) {
// Minimum fragmentation level in percent
$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%
+ }
// Optimize some tables that need to be optimized
$r = q("SHOW TABLE STATUS");
foreach($r as $table) {
// Don't optimize tables that are too large
- if ($table["Data_length"] > $max_tablesize)
+ if ($table["Data_length"] > $max_tablesize) {
continue;
+ }
// Don't optimize empty tables
- if ($table["Data_length"] == 0)
+ if ($table["Data_length"] == 0) {
continue;
+ }
// Calculate fragmentation
$fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]);
logger("Table ".$table["Name"]." - Fragmentation level: ".round($fragmentation * 100, 2), LOGGER_DEBUG);
// Don't optimize tables that needn't to be optimized
- if ($fragmentation < $fragmentation_level)
+ if ($fragmentation < $fragmentation_level) {
continue;
+ }
// So optimize it
logger("Optimize Table ".$table["Name"], LOGGER_DEBUG);
// 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`");
- if (dbm::is_result($r))
- foreach ($r AS $user)
+ if (dbm::is_result($r)) {
+ foreach ($r AS $user) {
update_gcontact_for_user($user["uid"]);
+ }
+ }
/// @todo
/// - remove thread entries without item
require_once('include/datetime.php');
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]) {
logger("Calling cron hook '".$hook[1]."'", LOGGER_DEBUG);
call_single_hook($a, $name, $hook, $data);
}
+ }
return;
}
$last = get_config('system', 'last_cronhook');
$poll_interval = intval(get_config('system','cronhook_interval'));
- if(! $poll_interval)
+ if (! $poll_interval) {
$poll_interval = 9;
+ }
- if($last) {
+ if ($last) {
$next = $last + ($poll_interval * 60);
- if($next > time()) {
+ if ($next > time()) {
logger('cronhook intervall not reached');
return;
}
openssl_sign($data,$sig,$key,(($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
}
else {
- if(strlen($key) < 1024 || extension_loaded('gmp')) {
+ if (strlen($key) < 1024 || extension_loaded('gmp')) {
require_once('library/phpsec/Crypt/RSA.php');
$rsa = new CRYPT_RSA();
$rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1;
$verify = openssl_verify($data,$sig,$key,(($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
}
else {
- if(strlen($key) <= 300 || extension_loaded('gmp')) {
+ if (strlen($key) <= 300 || extension_loaded('gmp')) {
require_once('library/phpsec/Crypt/RSA.php');
$rsa = new CRYPT_RSA();
$rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1;
-if(! function_exists('aes_decrypt')) {
+if (! function_exists('aes_decrypt')) {
// DEPRECATED IN 3.4.1
function aes_decrypt($val,$ky)
{
}}
-if(! function_exists('aes_encrypt')) {
+if (! function_exists('aes_encrypt')) {
// DEPRECATED IN 3.4.1
function aes_encrypt($val,$ky)
{
);
$conf = get_config('system','openssl_conf_file');
- if($conf)
+ if ($conf)
$openssl_options['config'] = $conf;
$result = openssl_pkey_new($openssl_options);
- if(empty($result)) {
+ if (empty($result)) {
logger('new_keypair: failed');
return false;
}
* @return int
*/
function timezone_cmp($a, $b) {
- if(strstr($a,'/') && strstr($b,'/')) {
+ if (strstr($a,'/') && strstr($b,'/')) {
if ( t($a) == t($b)) return 0;
return ( t($a) < t($b)) ? -1 : 1;
}
- if(strstr($a,'/')) return -1;
- if(strstr($b,'/')) return 1;
+ if (strstr($a,'/')) return -1;
+ if (strstr($b,'/')) return 1;
if ( t($a) == t($b)) return 0;
return ( t($a) < t($b)) ? -1 : 1;
$continent = '';
foreach($timezone_identifiers as $value) {
$ex = explode("/", $value);
- if(count($ex) > 1) {
- if($ex[0] != $continent) {
- if($continent != '')
+ if (count($ex) > 1) {
+ if ($ex[0] != $continent) {
+ if ($continent != '')
$o .= '</optgroup>';
$continent = $ex[0];
$o .= '<optgroup label="' . t($continent) . '">';
}
- if(count($ex) > 2)
+ if (count($ex) > 2)
$city = substr($value,strpos($value,'/')+1);
else
$city = $ex[1];
}
else {
$city = $ex[0];
- if($continent != t('Miscellaneous')) {
+ if ($continent != t('Miscellaneous')) {
$o .= '</optgroup>';
$continent = t('Miscellaneous');
$o .= '<optgroup label="' . t($continent) . '">';
// Defaults to UTC if nothing is set, but throws an exception if set to empty string.
// Provide some sane defaults regardless.
- if($from === '')
+ if ($from === '')
$from = 'UTC';
- if($to === '')
+ if ($to === '')
$to = 'UTC';
- if( ($s === '') || (! is_string($s)) )
+ if ( ($s === '') || (! is_string($s)) )
$s = 'now';
// Slight hackish adjustment so that 'zero' datetime actually returns what is intended
// 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.
- 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'));
return str_replace('1','0',$d->format($fmt));
}
list($year,$month,$day) = sscanf($dob,'%4d-%2d-%2d');
$f = get_config('system','birthday_input_format');
- if(! $f)
+ if (! $f)
$f = 'ymd';
- if($dob === '0000-00-00')
+ if ($dob === '0000-00-00')
$value = '';
else
$value = (($year) ? datetime_convert('UTC','UTC',$dob,'Y-m-d') : datetime_convert('UTC','UTC',$dob,'m-d'));
$o = '';
$dateformat = '';
- if($pickdate) $dateformat .= 'Y-m-d';
- if($pickdate && $picktime) $dateformat .= ' ';
- if($picktime) $dateformat .= 'H:i';
+ if ($pickdate) $dateformat .= 'Y-m-d';
+ if ($pickdate && $picktime) $dateformat .= ' ';
+ if ($picktime) $dateformat .= 'H:i';
$minjs = $min ? ",minDate: new Date({$min->getTimestamp()}*1000), yearStart: " . $min->format('Y') : '';
$maxjs = $max ? ",maxDate: new Date({$max->getTimestamp()}*1000), yearEnd: " . $max->format('Y') : '';
$defaultdatejs = $default ? ",defaultDate: new Date({$default->getTimestamp()}*1000)" : '';
$pickers = '';
- if(!$pickdate) $pickers .= ',datepicker: false';
- if(!$picktime) $pickers .= ',timepicker: false';
+ if (!$pickdate) $pickers .= ',datepicker: false';
+ if (!$picktime) $pickers .= ',timepicker: false';
$extra_js = '';
$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})}})";
- if($maxfrom != '')
+ if ($maxfrom != '')
$extra_js .= "\$('#id_$maxfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({maxDate: currentDateTime})}})";
$readable_format = $dateformat;
* @return int Age in years
*/
function age($dob,$owner_tz = '',$viewer_tz = '') {
- if(! intval($dob))
+ if (! intval($dob))
return 0;
- if(! $owner_tz)
+ if (! $owner_tz)
$owner_tz = date_default_timezone_get();
- if(! $viewer_tz)
+ if (! $viewer_tz)
$viewer_tz = date_default_timezone_get();
$birthdate = datetime_convert('UTC',$owner_tz,$dob . ' 00:00:00+00:00','Y-m-d');
$curr_month = datetime_convert('UTC',$viewer_tz,'now','m');
$curr_day = datetime_convert('UTC',$viewer_tz,'now','d');
- if(($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day)))
+ if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day)))
$year_diff--;
return $year_diff;
31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31);
- if($m != 2)
+ if ($m != 2)
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 $dim[2];
$thisyear = datetime_convert('UTC',date_default_timezone_get(),'now','Y');
$thismonth = datetime_convert('UTC',date_default_timezone_get(),'now','m');
- if(! $y)
+ if (! $y) {
$y = $thisyear;
- if(! $m)
+ }
+ if (! $m) {
$m = intval($thismonth);
+ }
$dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
$f = get_first_dim($y,$m);
$dow = 0;
$started = false;
- if(($y == $thisyear) && ($m == $thismonth))
+ if (($y == $thisyear) && ($m == $thismonth)) {
$tddate = intval(datetime_convert('UTC',date_default_timezone_get(),'now','j'));
+ }
$str_month = day_translate($mtab[$m]);
$o = '<table class="calendar' . $class . '">';
$o .= "<caption>$str_month $y</caption><tr>";
- for($a = 0; $a < 7; $a ++)
+ for($a = 0; $a < 7; $a ++) {
$o .= '<th>' . mb_substr(day_translate($dn[$a]),0,3,'UTF-8') . '</th>';
+ }
$o .= '</tr><tr>';
- while($d <= $l) {
- if(($dow == $f) && (! $started))
+ while ($d <= $l) {
+ if (($dow == $f) && (! $started)) {
$started = true;
+ }
$today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
$o .= "<td $today>";
$day = str_replace(' ',' ',sprintf('%2.2d', $d));
- if($started) {
- if(is_array($links) && isset($links[$d]))
+ if ($started) {
+ if (is_array($links) && isset($links[$d])) {
$o .= "<a href=\"{$links[$d]}\">$day</a>";
- else
+ } else {
$o .= $day;
+ }
$d ++;
} else {
$o .= '</td>';
$dow ++;
- if(($dow == 7) && ($d <= $l)) {
+ if (($dow == 7) && ($d <= $l)) {
$dow = 0;
$o .= '</tr><tr>';
}
}
- if($dow)
- for($a = $dow; $a < 7; $a ++)
+ if ($dow) {
+ for ($a = $dow; $a < 7; $a ++) {
$o .= '<td> </td>';
+ }
+ }
$o .= '</tr></table>'."\r\n";
*
*/
-if(! class_exists('dba')) {
+if (! class_exists('dba')) {
class dba {
private $debug = 0;
return;
}
- if($install) {
- if(strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
- if(! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
+ if ($install) {
+ if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
+ 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->connected = false;
$this->db = null;
\DDDBL\connect();
$this->db = \DDDBL\getDB();
- if(\DDDBL\isConnected()) {
+ if (\DDDBL\isConnected()) {
$this->connected = true;
}
- if(! $this->connected) {
+ if (! $this->connected) {
$this->db = null;
- if(! $install)
+ if (! $install)
system_unavailable();
}
$objPreparedQueryPool = new \DDDBL\DataObjectPool('Query-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,
'HANDLER' => $strHandler));
- if((! $this->db) || (! $this->connected))
+ if ((! $this->db) || (! $this->connected))
return false;
$this->error = '';
$r = \DDDBL\get($strQueryAlias);
# 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;
$intErrorCode = false;
$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"])) {
$duration = round($duration, 3);
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
}
}
- if($intErrorCode)
+ if ($intErrorCode)
$this->error = $intErrorCode;
- if(strlen($this->error)) {
+ if (strlen($this->error)) {
logger('dba: ' . $this->error);
}
- if($this->debug) {
+ if ($this->debug) {
$mesg = '';
- if($result === false)
+ if ($result === false)
$mesg = 'false';
- elseif($result === true)
+ elseif ($result === true)
$mesg = 'true';
else {
# this needs fixing, but is a bug itself
* 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);
- 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);
}
- if(isset($result) AND (($result === true) || ($result === false)))
+ if (isset($result) AND (($result === true) || ($result === false)))
return $result;
if ($onlyquery) {
//$a->save_timestamp($stamp1, "database");
- if($this->debug)
+ if ($this->debug)
logger('dba: ' . printable(print_r($r, true)));
return($r);
}
}
public function escape($str) {
- if($this->db && $this->connected) {
+ if ($this->db && $this->connected) {
$strQuoted = $this->db->quote($str);
# 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,
}
}}
-if(! function_exists('printable')) {
+if (! function_exists('printable')) {
function printable($s) {
$s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
$s = str_replace("\x00",'.',$s);
- if(x($_SERVER,'SERVER_NAME'))
+ if (x($_SERVER,'SERVER_NAME'))
$s = escape_tags($s);
return $s;
}}
// Procedural functions
-if(! function_exists('dbg')) {
+if (! function_exists('dbg')) {
function dbg($state) {
global $db;
- if($db)
+ if ($db)
$db->dbg($state);
}}
-if(! function_exists('dbesc')) {
+if (! function_exists('dbesc')) {
function dbesc($str) {
global $db;
- if($db && $db->connected)
+ if ($db && $db->connected)
return($db->escape($str));
else
return(str_replace("'","\\'",$str));
// Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
// 'user', 1);
-if(! function_exists('q')) {
+if (! function_exists('q')) {
function q($sql) {
global $db;
$args = func_get_args();
unset($args[0]);
- if($db && $db->connected) {
+ if ($db && $db->connected) {
$stmt = @vsprintf($sql,$args); // Disabled warnings
//logger("dba: q: $stmt", LOGGER_ALL);
- if($stmt === false)
+ if ($stmt === false)
logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
return $db->q($stmt);
}
*
*/
-if(! function_exists('dbq')) {
+if (! function_exists('dbq')) {
function dbq($sql) {
global $db;
- if($db && $db->connected)
+ if ($db && $db->connected)
$ret = $db->q($sql);
else
$ret = false;
// cast to int to avoid trouble.
-if(! function_exists('dbesc_array_cb')) {
+if (! function_exists('dbesc_array_cb')) {
function dbesc_array_cb(&$item, $key) {
- if(is_string($item))
+ if (is_string($item))
$item = dbesc($item);
}}
-if(! function_exists('dbesc_array')) {
+if (! function_exists('dbesc_array')) {
function dbesc_array(&$arr) {
- if(is_array($arr) && count($arr)) {
+ if (is_array($arr) && count($arr)) {
array_walk($arr,'dbesc_array_cb');
}
}}
-if(! function_exists('dba_timer')) {
+if (! function_exists('dba_timer')) {
function dba_timer() {
return microtime(true);
}}
function dbstructure_run(&$argv, &$argc) {
global $a, $db;
- if(is_null($a)){
+ if (is_null($a)){
$a = new App;
}
- if(is_null($db)) {
+ if (is_null($db)) {
@include(".htconfig.php");
require_once("include/dba.php");
$db = new dba($db_host, $db_user, $db_pass, $db_data);
// The signed text contains the content in Markdown, the sender handle and the signatur for the content
// It is needed for relayed comments to Diaspora.
- if($item['signed_text']) {
+ if ($item['signed_text']) {
$sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
}
$href = "";
$width = 0;
foreach ($avatar->attributes AS $attributes) {
- /// @TODO Rewrite these similar if() to one switch
+ /// @TODO Rewrite these similar if () to one switch
if ($attributes->name == "href") {
$href = $attributes->textContent;
}
if (edited_timestamp_is_newer($current, $item)) {
// do not accept (ignore) an earlier edit than one we currently have.
- if(datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"])
+ if (datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"])
return(false);
$r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
if ($item["parent-uri"] != $item["uri"]) {
$community = false;
- if($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
+ if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
$sql_extra = "";
$community = true;
logger("possible community action");
}
}
- if($Blink && link_compare($Blink,App::get_baseurl()."/profile/".$importer["nickname"])) {
+ if ($Blink && link_compare($Blink,App::get_baseurl()."/profile/".$importer["nickname"])) {
// send a notification
notification(array(
return false;
}
} else {
- if(($item["verb"] == ACTIVITY_LIKE)
+ if (($item["verb"] == ACTIVITY_LIKE)
|| ($item["verb"] == ACTIVITY_DISLIKE)
|| ($item["verb"] == ACTIVITY_ATTEND)
|| ($item["verb"] == ACTIVITY_ATTENDNO)
$title = "";
foreach ($links AS $link) {
foreach ($link->attributes AS $attributes) {
- /// @TODO Rewrite these repeated (same) if() statements to a switch()
+ /// @TODO Rewrite these repeated (same) if () statements to a switch()
if ($attributes->name == "href") {
$href = $attributes->textContent;
}
// When activated, forums don't work.
// And: Why should we disallow commenting by followers?
// the behaviour is now similar to the Diaspora part.
- //if($importer["rel"] == CONTACT_IS_FOLLOWER) {
+ //if ($importer["rel"] == CONTACT_IS_FOLLOWER) {
// logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
// return;
//}
logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
- if(stristr($item["verb"],ACTIVITY_POKE))
+ if (stristr($item["verb"],ACTIVITY_POKE))
self::do_poke($item, $importer, $posted_id);
}
}
}
}
- if($entrytype == DFRN_TOP_LEVEL) {
+ if ($entrytype == DFRN_TOP_LEVEL) {
$r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
`body` = '', `title` = ''
WHERE `parent-uri` = '%s' AND `uid` = %d",
create_tags_from_itemuri($uri, $importer["uid"]);
create_files_from_itemuri($uri, $importer["uid"]);
update_thread_uri($uri, $importer["importer_uid"]);
- if($item["last-child"]) {
+ if ($item["last-child"]) {
// ensure that last-child is set in case the comment that had it just got wiped.
q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
dbesc(datetime_convert()),
}
// if this is a relayed delete, propagate it to other recipients
- if($entrytype == DFRN_REPLY_RC) {
+ if ($entrytype == DFRN_REPLY_RC) {
logger("Notifying followers about deletion of post ".$item["id"], LOGGER_DEBUG);
proc_run(PRIORITY_HIGH, "include/notifier.php","drop", $item["id"]);
}
if ($xml == "")
return;
- if($importer["readonly"]) {
+ if ($importer["readonly"]) {
// We aren't receiving stuff from this person. But we will quietly ignore them
// rather than a blatant "go away" message.
logger('ignoring contact '.$importer["id"]);
$children = $basedom->children('https://joindiaspora.com/protocol');
- if($children->header) {
+ if ($children->header) {
$public = true;
$author_link = str_replace('acct:','',$children->header->author_id);
} else {
// figure out where in the DOM tree our data is hiding
- if($dom->provenance->data)
+ if ($dom->provenance->data)
$base = $dom->provenance;
- elseif($dom->env->data)
+ elseif ($dom->env->data)
$base = $dom->env;
- elseif($dom->data)
+ elseif ($dom->data)
$base = $dom;
if (!$base) {
$data = base64url_decode($data);
- if($public)
+ if ($public)
$inner_decrypted = $data;
else {
logger("Fetching diaspora key for: ".$handle);
$r = self::person_by_handle($handle);
- if($r)
+ if ($r)
return $r["pubkey"];
return "";
*/
private static function add_fcontact($arr, $update = false) {
- if($update) {
+ if ($update) {
$r = q("UPDATE `fcontact` SET
`name` = '%s',
`photo` = '%s',
// perhaps we were already sharing with this person. Now they're sharing with us.
// That makes us friends.
// 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",
intval(CONTACT_IS_FRIEND),
intval($contact["id"]),
logger("defining user ".$contact["nick"]." as friend");
}
- if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
+ if (($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
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;
- if($contact["rel"] == CONTACT_IS_FOLLOWER)
- if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
+ if ($contact["rel"] == CONTACT_IS_FOLLOWER)
+ if (($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
return true;
// Messages for the global users are always accepted
logger("Fetch post from ".$source_url, LOGGER_DEBUG);
$envelope = fetch_url($source_url);
- if($envelope) {
+ if ($envelope) {
logger("Envelope was fetched.", LOGGER_DEBUG);
$x = self::verify_magic_envelope($envelope);
if (!$x)
logger("Fetch post from ".$source_url, LOGGER_DEBUG);
$x = fetch_url($source_url);
- if(!$x)
+ if (!$x)
return false;
}
FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
intval($uid), dbesc($guid));
- if(!$r) {
+ if (!$r) {
$result = self::store_by_guid($guid, $contact["url"], $uid);
if (!$result) {
}
// 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.
// We now store the raw data so that we are more flexible.
intval($importer["uid"]),
dbesc($guid)
);
- if($c)
+ if ($c)
$conversation = $c[0];
else {
$r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
dbesc($subject),
dbesc($participants)
);
- if($r)
+ if ($r)
$c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
intval($importer["uid"]),
dbesc($guid)
);
- if($c)
+ if ($c)
$conversation = $c[0];
}
if (!$conversation) {
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($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.
// We now store the raw data so that we are more flexible.
$handle_parts = explode("@", $author);
$nick = $handle_parts[0];
- if($name === "")
+ if ($name === "")
$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;
update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
// 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(substr($birthday,5) === substr($contact["bd"],5))
+ if (substr($birthday,5) === substr($contact["bd"],5))
$birthday = $contact["bd"];
$r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
$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",
intval(CONTACT_IS_FRIEND),
intval($contact["id"]),
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",
intval($importer["uid"])
// 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["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
$arr["deny_gid"] = $user[0]["deny_gid"];
$i = item_store($arr);
- if($i)
+ if ($i)
proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
}
}
$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);
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);
);
$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);
$ret = self::send_share($u[0], $contact_record);
$a = get_app();
$enabled = intval(get_config("system", "diaspora_enabled"));
- if(!$enabled)
+ if (!$enabled)
return 200;
$logid = random_string(4);
$body = html_entity_decode(bb2diaspora($body));
// Adding the title
- if(strlen($title))
+ if (strlen($title))
$body = "## ".html_entity_decode($title)."\n\n".$body;
if ($item["attach"]) {
$cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
- if(cnt) {
+ if (cnt) {
$body .= "\n".t("Attachments:")."\n";
foreach($matches as $mtch)
$body .= "[".$mtch[3]."](".$mtch[1].")\n";
}
$r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
- if(!$r)
+ if (!dbm::is_result($r)) {
return false;
+ }
$contact["uprvkey"] = $r[0]['prvkey'];
$r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
- if (!$r)
+ if (!dbm::is_result($r)) {
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;
+ }
$message = self::construct_like($r[0], $contact);
$message["author_signature"] = self::signature($contact, $message);
$j = json_decode($x);
if (count($j->results)) {
- foreach($j->results as $jj) {
+ foreach ($j->results as $jj) {
// Check if the contact already exists
$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);
if (($exists[0]["last_contact"] < $exists[0]["last_failure"]) AND
require_once('include/quoteconvert.php');
function email_connect($mailbox,$username,$password) {
- if(! function_exists('imap_open'))
+ if (! function_exists('imap_open'))
return false;
$mbox = @imap_open($mailbox,$username,$password);
function email_poll($mbox,$email_addr) {
- if(! ($mbox && $email_addr))
+ if (! ($mbox && $email_addr))
return array();
$search1 = @imap_search($mbox,'FROM "' . $email_addr . '"', SE_UID);
- if(! $search1)
+ if (! $search1)
$search1 = array();
$search2 = @imap_search($mbox,'TO "' . $email_addr . '"', SE_UID);
- if(! $search2)
+ if (! $search2)
$search2 = array();
$search3 = @imap_search($mbox,'CC "' . $email_addr . '"', SE_UID);
- if(! $search3)
+ if (! $search3)
$search3 = array();
$search4 = @imap_search($mbox,'BCC "' . $email_addr . '"', SE_UID);
- if(! $search4)
+ if (! $search4)
$search4 = array();
$res = array_unique(array_merge($search1,$search2,$search3,$search4));
$raw_header = str_replace("\r",'',$raw_header);
$ret = array();
$h = explode("\n",$raw_header);
- if(count($h))
+ if (count($h))
foreach($h as $line ) {
if (preg_match("/^[a-zA-Z]/", $line)) {
$key = substr($line,0,strpos($line,':'));
$struc = (($mbox && $uid) ? @imap_fetchstructure($mbox,$uid,FT_UID) : null);
- if(! $struc)
+ if (! $struc)
return $ret;
- if(! $struc->parts) {
+ if (! $struc->parts) {
$ret['body'] = email_get_part($mbox,$uid,$struc,0, 'html');
$html = $ret['body'];
$need_to_convert = false;
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;
}
}
- if(! $need_to_convert)
+ if (! $need_to_convert)
return $in_str;
if ($out_str && $charset) {
$hash = random_string();
$r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
dbesc($hash));
- if (dbm::is_result($r))
+ if (dbm::is_result($r)) {
$dups = true;
- } while($dups == true);
+ }
+ } while ($dups == true);
+ /// @TODO One statement is enough
$datarray = array();
$datarray['hash'] = $hash;
$datarray['name'] = $params['source_name'];
function format_event_html($ev, $simple = false) {
- if(! ((is_array($ev)) && count($ev)))
+ if (! ((is_array($ev)) && count($ev)))
return '';
$bd_format = t('l F d, Y \@ g:i A') ; // Friday January 18, 2011 @ 8 AM
$o .= "<h4>".t('Starts:')."</h4><p>".$event_start."</p>";
- if(! $ev['nofinish'])
+ if (! $ev['nofinish'])
$o .= "<h4>".t('Finishes:')."</h4><p>".$event_end."</p>";
- if(strlen($ev['location']))
+ if (strlen($ev['location']))
$o .= "<h4>".t('Location:')."</h4><p>".$ev['location']."</p>";
return $o;
. '" >'.$event_start
. '</abbr></p>' . "\r\n";
- if(! $ev['nofinish'])
+ if (! $ev['nofinish'])
$o .= '<p class="event-end" >' . t('Finishes:') . ' <abbr class="dtend" title="'
. datetime_convert('UTC','UTC',$ev['finish'], (($ev['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' ))
. '" >'.$event_end
. '</abbr></p>' . "\r\n";
- if(strlen($ev['location'])){
+ if (strlen($ev['location'])){
$o .= '<p class="event-location"> ' . t('Location:') . ' <span class="location">'
. bbcode($ev['location'])
. '</span></p>' . "\r\n";
logger('parse_event: parse error: ' . $e);
}
- if(! $dom)
+ if (! $dom)
return $ret;
$items = $dom->getElementsByTagName('*');
foreach($items as $item) {
- if(attribute_contains($item->getAttribute('class'), 'vevent')) {
+ if (attribute_contains($item->getAttribute('class'), 'vevent')) {
$level2 = $item->getElementsByTagName('*');
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');
- if(! strpos($ret['start'],'Z'))
+ if (! strpos($ret['start'],'Z'))
$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');
- if(attribute_contains($x->getAttribute('class'),'description'))
+ if (attribute_contains($x->getAttribute('class'),'description'))
$ret['desc'] = $x->textContent;
- if(attribute_contains($x->getAttribute('class'),'location'))
+ if (attribute_contains($x->getAttribute('class'),'location'))
$ret['location'] = $x->textContent;
}
}
// 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->set('Cache.DefinitionImpl', null);
$purifier = new HTMLPurifier($config);
$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->set('Cache.DefinitionImpl', null);
$purifier = new HTMLPurifier($config);
$ret['location'] = html2bbcode($purifier->purify($ret['location']));
}
- if(x($ret,'start'))
+ if (x($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']);
return $ret;
$o = '';
- if($ev['summary'])
+ if ($ev['summary'])
$o .= '[event-summary]' . $ev['summary'] . '[/event-summary]';
- if($ev['desc'])
+ if ($ev['desc'])
$o .= '[event-description]' . $ev['desc'] . '[/event-description]';
- if($ev['start'])
+ if ($ev['start'])
$o .= '[event-start]' . $ev['start'] . '[/event-start]';
- if(($ev['finish']) && (! $ev['nofinish']))
+ if (($ev['finish']) && (! $ev['nofinish']))
$o .= '[event-finish]' . $ev['finish'] . '[/event-finish]';
- if($ev['location'])
+ if ($ev['location'])
$o .= '[event-location]' . $ev['location'] . '[/event-location]';
- if($ev['adjust'])
+ if ($ev['adjust'])
$o .= '[event-adjust]' . $ev['adjust'] . '[/event-adjust]';
function bbtovcal($s) {
$o = '';
$ev = bbtoevent($s);
- if($ev['desc'])
+ if ($ev['desc'])
$o = format_event_html($ev);
return $o;
}
$ev = array();
$match = '';
- if(preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is",$s,$match))
+ if (preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is",$s,$match))
$ev['summary'] = $match[1];
$match = '';
- if(preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is",$s,$match))
+ if (preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is",$s,$match))
$ev['desc'] = $match[1];
$match = '';
- if(preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is",$s,$match))
+ if (preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is",$s,$match))
$ev['start'] = $match[1];
$match = '';
- if(preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is",$s,$match))
+ if (preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is",$s,$match))
$ev['finish'] = $match[1];
$match = '';
- if(preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is",$s,$match))
+ if (preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is",$s,$match))
$ev['location'] = $match[1];
$match = '';
- if(preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is",$s,$match))
+ if (preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is",$s,$match))
$ev['adjust'] = $match[1];
$ev['nofinish'] = (((x($ev, 'start') && $ev['start']) && (!x($ev, 'finish') || !$ev['finish'])) ? 1 : 0);
return $ev;
$date_a = (($a['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$a['start']) : $a['start']);
$date_b = (($b['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$b['start']) : $b['start']);
- if($date_a === $date_b)
+ if ($date_a === $date_b)
return strcasecmp($a['desc'],$b['desc']);
return strcmp($date_a,$date_b);
$arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0);
$arr['guid'] = get_guid(32);
- if($arr['cid'])
+ if ($arr['cid'])
$c = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
intval($arr['cid']),
intval($arr['uid'])
intval($arr['uid'])
);
- if(count($c))
+ if (count($c))
$contact = $c[0];
// Existing event being modified
- if($arr['id']) {
+ if ($arr['id']) {
// has the event actually changed?
intval($arr['id']),
intval($arr['uid'])
);
- if((! dbm::is_result($r)) || ($r[0]['edited'] === $arr['edited'])) {
+ if ((! dbm::is_result($r)) || ($r[0]['edited'] === $arr['edited'])) {
// Nothing has changed. Grab the item id to return.
// $plink = App::get_baseurl() . '/display/' . $r[0]['nickname'] . '/' . $item_id;
- if($item_id) {
+ if ($item_id) {
//q("UPDATE `item` SET `plink` = '%s', `event-id` = %d WHERE `uid` = %d AND `id` = %d",
// dbesc($plink),
// intval($event['id']),
*/
function event_by_id($owner_uid = 0, $event_params, $sql_extra = '') {
// ownly allow events if there is a valid owner_id
- if($owner_uid == 0)
+ if ($owner_uid == 0)
return;
// query for the event by event id
*/
function events_by_date($owner_uid = 0, $event_params, $sql_extra = '') {
// ownly allow events if there is a valid owner_id
- if($owner_uid == 0)
+ if ($owner_uid == 0)
return;
// query for the event by date
$last_date = $d;
$edit = ((! $rr['cid']) ? array(App::get_baseurl().'/events/event/'.$rr['id'],t('Edit event'),'','') : null);
$title = strip_tags(html_entity_decode(bbcode($rr['summary']),ENT_QUOTES,'UTF-8'));
- if(! $title) {
+ if (! $title) {
list($title, $_trash) = explode("<br",bbcode($rr['desc']),2);
$title = strip_tags(html_entity_decode($title,ENT_QUOTES,'UTF-8'));
}
* @return string Content according to selected export format
*/
function event_format_export ($events, $format = 'ical', $timezone) {
- if(! ((is_array($events)) && count($events)))
+ if (! ((is_array($events)) && count($events)))
return;
switch ($format) {
* @return array Query results
*/
function events_by_uid($uid = 0, $sql_extra = '') {
- if($uid == 0)
+ if ($uid == 0) {
return;
+ }
// The permission condition if no condition was transmitted
- if($sql_extra == '')
+ if ($sql_extra == '') {
$sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' ";
+ }
// does the user who requests happen to be the owner of the events
// requested? then show all of your events, otherwise only those that
);
}
- if (dbm::is_result($r))
+ if (dbm::is_result($r)) {
return $r;
+ }
}
/**
// we are allowed to show events
// get the timezone the user is in
$r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
- if (dbm::is_result($r))
+ if (dbm::is_result($r)) {
$timezone = $r[0]['timezone'];
+ }
// get all events which are owned by a uid (respects permissions);
$events = events_by_uid($uid);
// we have the events that are available for the requestor
// now format the output according to the requested format
- if(count($events))
+ if (count($events)) {
$res = event_format_export($events, $format, $timezone);
+ }
// If there are results the precess was successfull
- if(x($res))
+ if (x($res)) {
$process = true;
+ }
// get the file extension for the format
switch ($format) {
// The permission testing is a little bit tricky because we have to respect many cases
// It's not the private events page (we don't get the $owner_uid for /events)
- if(! local_user() && ! $owner_uid)
+ if (! local_user() && ! $owner_uid) {
return;
+ }
// Cal logged in user (test permission at foreign profile page)
// If the $owner uid is available we know it is part of one of the profile pages (like /cal)
// or a foreign one. For foreign profile pages we need to check if the feature
// for exporting the cal is enabled (otherwise the widget would appear for logged in users
// on foreigen profile pages even if the widget is disabled)
- if(intval($owner_uid) && local_user() !== $owner_uid && ! feature_enabled($owner_uid, "export_calendar"))
+ if (intval($owner_uid) && local_user() !== $owner_uid && ! feature_enabled($owner_uid, "export_calendar")) {
return;
+ }
// If it's a kind of profile page (intval($owner_uid)) return if the user not logged in and
// export feature isn't enabled
- if(intval($owner_uid) && ! local_user() && ! feature_enabled($owner_uid, "export_calendar"))
+ if (intval($owner_uid) && ! local_user() && ! feature_enabled($owner_uid, "export_calendar")) {
return;
+ }
return replace_macros(get_markup_template("events_aside.tpl"), array(
'$etitle' => t("Export"),
// 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
- if(intval(get_config('system','optimize_items')))
- q("optimize table item");
+ if (intval(get_config('system','optimize_items'))) {
+ q("OPTIMIZE TABLE `item`");
+ }
logger('expire: start');
$f = get_features();
foreach($f as $cat) {
foreach($cat as $feat) {
- if(is_array($feat) && $feat[0] === $feature)
+ if (is_array($feat) && $feat[0] === $feature)
return $feat[3];
}
}
// removed any locked features and remove the entire category if this makes it empty
- if($filtered) {
+ if ($filtered) {
foreach($arr as $k => $x) {
$has_items = false;
$kquantity = count($arr[$k]);
for($y = 0; $y < $kquantity; $y ++) {
- if(is_array($arr[$k][$y])) {
- if($arr[$k][$y][4] === false) {
+ if (is_array($arr[$k][$y])) {
+ if ($arr[$k][$y][4] === false) {
$has_items = true;
}
else {
}
}
}
- if(! $has_items) {
+ if (! $has_items) {
unset($arr[$k]);
}
}
$header["contact-id"] = $contact["id"];
- if(!strlen($contact["notify"])) {
+ if (!strlen($contact["notify"])) {
// one way feed - no remote comment ability
$header["last-child"] = 0;
}
$type = $attributes->textContent;
}
}
- if(strlen($item["attach"]))
+ if (strlen($item["attach"])) {
$item["attach"] .= ',';
+ }
$attachments[] = array("link" => $href, "type" => $type, "length" => $length);
function create_files_from_itemuri($itemuri, $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)
create_files_from_item($message["id"]);
}
// setTemplateDir can be set to an array, which Smarty will parse in order.
// The order is thus very important here
$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('base' => "view/".SMARTY3_TEMPLATE_FOLDER."/");
$this->setTemplateDir($template_dirs);
}
function parsed($template = '') {
- if($template) {
+ if ($template) {
return $this->fetch('string:' . $template);
}
return $this->fetch('file:' . $this->filename);
static $name ="smarty3";
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();
}
}
// ITemplateEngine interface
public function replace_macros($s, $r) {
$template = '';
- if(gettype($s) === 'string') {
+ if (gettype($s) === 'string') {
$template = $s;
$s = new FriendicaSmarty();
}
$r = $arr['vars'];
foreach($r as $key=>$value) {
- if($key[0] === '$') {
+ if ($key[0] === '$') {
$key = substr($key, 1);
}
$s->assign($key, $value);
function group_add($uid,$name) {
$ret = false;
- if(x($uid) && x($name)) {
+ if (x($uid) && x($name)) {
$r = group_byname($uid,$name); // check for dups
- if($r !== false) {
+ if ($r !== false) {
// This could be a problem.
// Let's assume we've just created a group which we once deleted
$z = q("SELECT * FROM `group` WHERE `id` = %d LIMIT 1",
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'",
intval($uid),
dbesc($name)
function group_rmv($uid,$name) {
$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",
intval($uid),
dbesc($name)
);
if (dbm::is_result($r))
$group_id = $r[0]['id'];
- if(! $group_id)
+ if (! $group_id)
return false;
// remove group from default posting lists
$user_info = $r[0];
$change = false;
- if($user_info['def_gid'] == $group_id) {
+ if ($user_info['def_gid'] == $group_id) {
$user_info['def_gid'] = 0;
$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']);
$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']);
$change = true;
}
- if($change) {
+ if ($change) {
q("UPDATE user SET def_gid = %d, allow_gid = '%s', deny_gid = '%s' WHERE uid = %d",
intval($user_info['def_gid']),
dbesc($user_info['allow_gid']),
}
function group_byname($uid,$name) {
- if((! $uid) || (! strlen($name)))
+ if ((! $uid) || (! strlen($name)))
return false;
$r = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' LIMIT 1",
intval($uid),
function group_rmv_member($uid,$name,$member) {
$gid = group_byname($uid,$name);
- if(! $gid)
+ if (! $gid)
return false;
- if(! ( $uid && $gid && $member))
+ if (! ( $uid && $gid && $member))
return false;
$r = q("DELETE FROM `group_member` WHERE `uid` = %d AND `gid` = %d AND `contact-id` = %d",
intval($uid),
function group_add_member($uid,$name,$member,$gid = 0) {
- if(! $gid)
+ if (! $gid)
$gid = group_byname($uid,$name);
- if((! $gid) || (! $uid) || (! $member))
+ if ((! $gid) || (! $uid) || (! $member))
return false;
$r = q("SELECT * FROM `group_member` WHERE `uid` = %d AND `gid` = %d AND `contact-id` = %d LIMIT 1",
function group_get_members($gid) {
$ret = array();
- if(intval($gid)) {
+ if (intval($gid)) {
$r = q("SELECT `group_member`.`contact-id`, `contact`.* FROM `group_member`
INNER JOIN `contact` ON `contact`.`id` = `group_member`.`contact-id`
WHERE `gid` = %d AND `group_member`.`uid` = %d AND
function group_public_members($gid) {
$ret = 0;
- if(intval($gid)) {
+ if (intval($gid)) {
$r = q("SELECT `contact`.`id` AS `contact-id` FROM `group_member`
INNER JOIN `contact` ON `contact`.`id` = `group_member`.`contact-id`
WHERE `gid` = %d AND `group_member`.`uid` = %d
intval($_SESSION['uid'])
);
$member_of = array();
- if($cid) {
+ if ($cid) {
$member_of = groups_containing(local_user(),$cid);
}
}
function expand_groups($a,$check_dead = false, $use_gcontact = false) {
- if(! (is_array($a) && count($a)))
+ if (! (is_array($a) && count($a)))
return array();
$groups = implode(',', $a);
$groups = dbesc($groups);
if (dbm::is_result($r))
foreach($r as $rr)
$ret[] = $rr['contact-id'];
- if($check_dead AND !$use_gcontact) {
+ if ($check_dead AND !$use_gcontact) {
require_once('include/acl_selectors.php');
$ret = prune_deadguys($ret);
}
return $default_group;
$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"];
return $default_group;
dbesc($nickname)
);
- if(!$user && count($user) && !count($profiledata)) {
+ if (!$user && count($user) && !count($profiledata)) {
logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
notice( t('Requested account is not available.') . EOL );
$a->error = 404;
$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);
notice( t('Requested profile is not available.') . EOL );
$a->error = 404;
// 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",
intval($pdata['profile_uid'])
);
- if($x && count($x))
+ if ($x && count($x))
$pdata['pub_keywords'] = $x[0]['pub_keywords'];
}
require_once($theme_info_file);
}
- if(! (x($a->page,'aside')))
+ if (! (x($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(
'$editprofile' => t('Edit profile'),
'$profid' => $a->profile['id']
else
$a->page['aside'] .= profile_sidebar($a->profile, $block);
- /*if(! $block)
+ /*if (! $block)
$a->page['aside'] .= contact_block();*/
return;
* Includes all available profile data
*/
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) {
- if($visitor['uid'] == $uid) {
+ if ($visitor['uid'] == $uid) {
$r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
intval($visitor['cid'])
);
$r = null;
- if($profile) {
+ if ($profile) {
$profile_int = intval($profile);
$r = q("SELECT `contact`.`id` AS `contact_id`, `profile`.`uid` AS `profile_uid`, `profile`.*,
`contact`.`avatar-date` AS picdate, `contact`.`addr`, `user`.*
$address = false;
// $pdesc = true;
- if((! is_array($profile)) && (! count($profile)))
+ if ((! is_array($profile)) && (! count($profile)))
return $o;
$profile['picdate'] = urlencode($profile['picdate']);
$connect = (($profile['uid'] != local_user()) ? t('Connect') : False);
// 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) {
- if($visitor['uid'] == $profile['uid']) {
+ if ($visitor['uid'] == $profile['uid']) {
$connect = false;
break;
}
// Fetch the account type
$account_type = account_type($profile);
- if((x($profile,'address') == 1)
+ if ((x($profile,'address') == 1)
|| (x($profile,'location') == 1)
|| (x($profile,'locality') == 1)
|| (x($profile,'region') == 1)
$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;
}
if (!$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",
intval($a->profile['uid']));
if (dbm::is_result($r))
if (isset($p["photo"]))
$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);
$tpl = get_markup_template('profile_vcard.tpl');
$a = get_app();
$o = '';
- if(! local_user() || $a->is_mobile || $a->is_tablet)
+ if (! local_user() || $a->is_mobile || $a->is_tablet)
return $o;
// $mobile_detect = new Mobile_Detect();
// $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
-// if($is_mobile)
+// if ($is_mobile)
// return $o;
$bd_format = t('g A l F d') ; // 8 AM Friday January 18
$istoday = false;
foreach ($r as $rr) {
- if(strlen($rr['name']))
+ if (strlen($rr['name']))
$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;
}
$classtoday = $istoday ? ' birthday-today ' : '';
- if($total) {
+ if ($total) {
foreach($r as &$rr) {
- if(! strlen($rr['name']))
+ if (! strlen($rr['name']))
continue;
// avoid duplicates
- if(in_array($rr['cid'],$cids))
+ if (in_array($rr['cid'],$cids))
continue;
$cids[] = $rr['cid'];
$today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
$sparkle = '';
$url = $rr['url'];
- if($rr['network'] === NETWORK_DFRN) {
+ if ($rr['network'] === NETWORK_DFRN) {
$sparkle = " sparkle";
$url = App::get_baseurl() . '/redir/' . $rr['cid'];
}
$a = get_app();
- if(! local_user() || $a->is_mobile || $a->is_tablet)
+ if (! local_user() || $a->is_mobile || $a->is_tablet)
return $o;
// $mobile_detect = new Mobile_Detect();
// $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
-// if($is_mobile)
+// if ($is_mobile)
// return $o;
$bd_format = t('g A l F d') ; // 8 AM Friday January 18
$now = strtotime('now');
$istoday = false;
foreach ($r as $rr) {
- if(strlen($rr['name']))
+ if (strlen($rr['name']))
$total ++;
$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;
}
$classtoday = (($istoday) ? 'event-today' : '');
foreach($r as &$rr) {
$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) . '... ';
$description = substr(strip_tags(bbcode($rr['desc'])),0,32) . '... ';
- if(! $description)
+ if (! $description)
$description = t('[No description]');
$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++;
continue;
}
'$title' => t('Profile')
));
- if($a->profile['name']) {
+ if ($a->profile['name']) {
$tpl = get_markup_template('profile_advanced.tpl');
$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');
$short_bd_format = t('j F');
}
- 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?
if ($a->profile['with']) {
}
function get_my_url() {
- if(x($_SESSION,'my_url'))
+ if (x($_SESSION,'my_url'))
return $_SESSION['my_url'];
return false;
}
function zrl_init(App $a) {
$tmp_str = get_my_url();
- if(validate_url($tmp_str)) {
+ if (validate_url($tmp_str)) {
// Is it a DDoS attempt?
// The check fetches the cached value from gprobe to reduce the load for this system
}
function zrl($s,$force = false) {
- if(! strlen($s))
+ if (! strlen($s)) {
return $s;
- if((! strpos($s,'/profile/')) && (! $force))
+ }
+ if ((! strpos($s,'/profile/')) && (! $force)) {
return $s;
- if($force && substr($s,-1,1) !== '/')
+ }
+ if ($force && substr($s,-1,1) !== '/') {
$s = $s . '/';
+ }
$achar = strpos($s,'?') ? '&' : '?';
$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;
}
*/
function get_theme_uid() {
$uid = (($_REQUEST['puid']) ? intval($_REQUEST['puid']) : 0);
- if(local_user()) {
- if((get_pconfig(local_user(),'system','always_my_theme')) || (! $uid))
+ if (local_user()) {
+ if ((get_pconfig(local_user(),'system','always_my_theme')) || (! $uid)) {
return local_user();
+ }
}
return $uid;
$img_start = strpos($orig_body, '[img');
$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);
- 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_end += $img_start;
$img_start = strpos($orig_body, '[img');
$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);
- 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
$image = substr($orig_body, $img_start + $img_st_close, $img_len);
// Starting with the current month, get the first and last days of every
// 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));
$dstart = substr($dnow,0,8) . '01';
$dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
$ret = array();
// Starting with the current month, get the first and last days of every
// 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';
$dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
$start_month = datetime_convert('','',$dstart,'Y-m-d');
// Provide some ability to lock a PHP function so that multiple processes
// 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) {
- 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
$got_lock = false;
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'",
dbesc(datetime_convert()),
dbesc($fn_name)
q("UNLOCK TABLES");
- if(($block) && (! $got_lock))
+ if (($block) && (! $got_lock))
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);
}}
-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) {
- 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
$start = time();
do {
$r = q("SELECT locked FROM locks WHERE name = '%s' LIMIT 1",
- 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);
+ }
- } while(dbm::is_result($r) && $r[0]['locked'] && ((time() - $start) < $timeout));
+ } while (dbm::is_result($r) && $r[0]['locked'] && ((time() - $start) < $timeout));
return;
}}
-if(! function_exists('unlock_function')) {
+if (! function_exists('unlock_function')) {
function unlock_function($fn_name) {
$r = q("UPDATE `locks` SET `locked` = 0, `created` = '0000-00-00 00:00:00' WHERE `name` = '%s'",
dbesc($fn_name)
$a = get_app();
- if(! $recipient) return -1;
+ if (! $recipient) return -1;
- if(! strlen($subject))
+ if (! strlen($subject))
$subject = t('[no subject]');
$me = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
intval(local_user())
);
- if(! (count($me) && (count($contact)))) {
+ if (! (count($me) && (count($contact)))) {
return -2;
}
// look for any existing conversation structure
- if(strlen($replyto)) {
+ if (strlen($replyto)) {
$reply = true;
$r = q("select convid from mail where uid = %d and ( uri = '%s' or `parent-uri` = '%s' ) limit 1",
intval(local_user()),
$convid = $r[0]['convid'];
}
- if(! $convid) {
+ if (! $convid) {
// create a new conversation
$convid = $r[0]['id'];
}
- if(! $convid) {
+ if (! $convid) {
logger('send message: conversation not found.');
return -4;
}
- if(! strlen($replyto)) {
+ if (! strlen($replyto)) {
$replyto = $convuri;
}
*
*/
- if(!(x($a->page,'nav')))
+ if (!(x($a->page,'nav')))
$a->page['nav'] = '';
$a->page['htmlhead'] .= replace_macros(get_markup_template('nav_head.tpl'), array());
if (strlen(get_config('system', 'singleuser'))) {
$gdir = get_config('system', 'directory');
- if(strlen($gdir)) {
+ if (strlen($gdir)) {
$gdirpath = zrl($gdir, true);
}
} elseif (get_config('system', 'community_page_style') == CP_USERS_ON_SERVER) {
@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_COOKIEFILE, $opts["cookiejar"]);
}
@curl_setopt($ch, CURLOPT_RANGE, '0-'.$range);
}
- if(x($opts,'headers')){
+ if (x($opts,'headers')){
@curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
}
- if(x($opts,'nobody')){
+ if (x($opts,'nobody')){
@curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
}
- if(x($opts,'timeout')){
+ if (x($opts,'timeout')){
@curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
} else {
$curl_time = intval(get_config('system','curl_timeout'));
}
$prx = get_config('system','proxy');
- if(strlen($prx)) {
+ if (strlen($prx)) {
@curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
@curl_setopt($ch, CURLOPT_PROXY, $prx);
$prxusr = @get_config('system','proxyuser');
- if(strlen($prxusr))
+ if (strlen($prxusr))
@curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
}
- if($binary)
+ if ($binary)
@curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$a->set_curl_code(0);
// Pull out multiple headers, e.g. proxy and continuation headers
// 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);
$header .= $chunk;
$base = substr($base,strlen($chunk));
$a->set_curl_content_type($curl_info['content_type']);
$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"]);
$old_location_info = @parse_url($curl_info["url"]);
if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
$newurl = trim(array_pop($matches));
}
- if(strpos($newurl,'/') === 0)
+ if (strpos($newurl,'/') === 0)
$newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
if (filter_var($newurl, FILTER_VALIDATE_URL)) {
$redirects++;
$ret['return_code'] = $rc;
$ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
$ret['redirect_url'] = $url;
- if(! $ret['success']) {
+ if (! $ret['success']) {
$ret['error'] = curl_error($ch);
$ret['debug'] = $curl_info;
logger('z_fetch_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
}
$ret['body'] = substr($s,strlen($header));
$ret['header'] = $header;
- if(x($opts,'debug')) {
+ if (x($opts,'debug')) {
$ret['debug'] = $curl_info;
}
@curl_close($ch);
$a = get_app();
$ch = curl_init($url);
- if(($redirects > 8) || (! $ch))
+ if (($redirects > 8) || (! $ch))
return false;
logger("post_url: start ".$url, LOGGER_DATA);
curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
- if(intval($timeout)) {
+ if (intval($timeout)) {
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
}
else {
curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
}
- if(defined('LIGHTTPD')) {
- if(!is_array($headers)) {
+ if (defined('LIGHTTPD')) {
+ if (!is_array($headers)) {
$headers = array('Expect:');
} else {
- if(!in_array('Expect:', $headers)) {
+ if (!in_array('Expect:', $headers)) {
array_push($headers, 'Expect:');
}
}
}
- if($headers)
+ if ($headers)
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$check_cert = get_config('system','verifyssl');
@curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
}
$prx = get_config('system','proxy');
- if(strlen($prx)) {
+ if (strlen($prx)) {
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
curl_setopt($ch, CURLOPT_PROXY, $prx);
$prxusr = get_config('system','proxyuser');
- if(strlen($prxusr))
+ if (strlen($prxusr))
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
}
// Pull out multiple headers, e.g. proxy and continuation headers
// 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);
$header .= $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();
preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
$newurl = trim(array_pop($matches));
- if(strpos($newurl,'/') === 0)
+ if (strpos($newurl,'/') === 0)
$newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
if (filter_var($newurl, FILTER_VALIDATE_URL)) {
$redirects++;
$xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
- if($st)
+ if ($st)
logger('xml_status returning non_zero: ' . $st . " message=" . $message);
header( "Content-type: text/xml" );
*/
function http_status_exit($val, $description = array()) {
$err = '';
- if($val >= 400) {
+ if ($val >= 400) {
$err = 'Error';
if (!isset($description["title"]))
$description["title"] = $err." ".$val;
}
- if($val >= 200 && $val < 300)
+ if ($val >= 200 && $val < 300)
$err = 'OK';
logger('http_status_exit ' . $val);
* @return boolean True if it's a valid URL, fals if something wrong with it
*/
function validate_url(&$url) {
- if(get_config('system','disable_url_validation'))
+ if (get_config('system','disable_url_validation'))
return true;
// 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;
- if(substr($url,0,4) != 'http')
+ if (substr($url,0,4) != 'http')
$url = 'http://' . $url;
/// @TODO Really supress function outcomes? Why not find them + debug them?
$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;
}
*/
function validate_email($addr) {
- if(get_config('system','disable_email_validation'))
+ if (get_config('system','disable_email_validation'))
return true;
- if(! strpos($addr,'@'))
+ if (! strpos($addr,'@'))
return false;
$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 false;
$h = @parse_url($url);
- if(! $h) {
+ if (! $h) {
return false;
}
$str_allowed = get_config('system','allowed_sites');
- if(! $str_allowed)
+ if (! $str_allowed)
return true;
$found = false;
// always allow our own site
- if($host == strtolower($_SERVER['SERVER_NAME']))
+ if ($host == strtolower($_SERVER['SERVER_NAME']))
return true;
$fnmatch = function_exists('fnmatch');
$allowed = explode(',',$str_allowed);
- if(count($allowed)) {
+ if (count($allowed)) {
foreach($allowed as $a) {
$pat = strtolower(trim($a));
- if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
+ if (($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
$found = true;
break;
}
$domain = strtolower(substr($email,strpos($email,'@') + 1));
- if(! $domain)
+ if (! $domain)
return false;
$str_allowed = get_config('system','allowed_email');
- if(! $str_allowed)
+ if (! $str_allowed)
return true;
$found = false;
$fnmatch = function_exists('fnmatch');
$allowed = explode(',',$str_allowed);
- if(count($allowed)) {
+ if (count($allowed)) {
foreach($allowed as $a) {
$pat = strtolower(trim($a));
- if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
+ if (($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
$found = true;
break;
}
function parse_xml_string($s,$strict = true) {
/// @todo Move this function to the xml class
- if($strict) {
- if(! strstr($s,'<?xml'))
+ if ($strict) {
+ if (! strstr($s,'<?xml'))
return false;
$s2 = substr($s,strpos($s,'<?xml'));
}
//notice( t("Welcome back ") . $record['username'] . EOL);
$a->user = $record;
- if(strlen($a->user['timezone'])) {
+ if (strlen($a->user['timezone'])) {
date_default_timezone_set($a->user['timezone']);
$a->timezone = $a->user['timezone'];
}
$xattr = "@rel='oembed'";//oe_build_xpath("rel","oembed");
foreach($entries as $e) {
$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) );
} else {
intval($contact_id)
);
- if (! count($contacts)) {
+ if (! dbm::is_result($contacts)) {
return;
}
foreach ($category->attributes AS $attributes)
if ($attributes->name == "term") {
$term = $attributes->textContent;
- if(strlen($item["tag"]))
+ if (strlen($item["tag"]))
$item["tag"] .= ',';
$item["tag"] .= "#[url=".App::get_baseurl()."/search?tag=".$term."]".$term."[/url]";
}
break;
case "enclosure":
$enclosure = $href;
- if(strlen($item["attach"]))
+ if (strlen($item["attach"]))
$item["attach"] .= ',';
$item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
continue;
}
- /// @TODO One statment is okay (until if() )
+ /// @TODO One statment is okay (until if () )
$arr = array();
$arr["network"] = $details["network"];
$arr["uri"] = $single_conv->id;
$owner = $r[0];
- if(!strlen($last_update))
+ if (!strlen($last_update))
$last_update = 'now -30 days';
$check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
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
*/
// check if we have translations for the preferred languages and pick the 1st that has
for ($i=0; $i<count($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;
break;
}
$a->langsave = $lang;
- if($language === $lang)
+ if ($language === $lang)
return;
- if(isset($a->strings) && count($a->strings)) {
+ if (isset($a->strings) && count($a->strings)) {
$a->stringsave = $a->strings;
}
$a->strings = array();
function pop_lang() {
global $lang, $a;
- if($lang === $a->langsave)
+ if ($lang === $a->langsave)
return;
- if(isset($a->stringsave))
+ if (isset($a->stringsave))
$a->strings = $a->stringsave;
else
$a->strings = array();
// l
-if(! function_exists('load_translation_table')) {
+if (! function_exists('load_translation_table')) {
/**
* load string translation table for alternate language
*
if ($plugins!==false) {
foreach($plugins as $p) {
$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");
}
}
}
- if(file_exists("view/lang/$lang/strings.php")) {
+ if (file_exists("view/lang/$lang/strings.php")) {
include("view/lang/$lang/strings.php");
}
// translate string if translation exists
-if(! function_exists('t')) {
+if (! function_exists('t')) {
function t($s) {
$a = get_app();
- if(x($a->strings,$s)) {
+ if (x($a->strings,$s)) {
$t = $a->strings[$s];
return is_array($t)?$t[0]:$t;
}
return $s;
}}
-if(! function_exists('tt')){
+if (! function_exists('tt')){
function tt($singular, $plural, $count){
global $lang;
$a = get_app();
- if(x($a->strings,$singular)) {
+ if (x($a->strings,$singular)) {
$t = $a->strings[$singular];
$f = 'string_plural_select_' . str_replace('-','_',$lang);
- if(! function_exists($f))
+ if (! function_exists($f))
$f = 'string_plural_select_default';
$k = $f($count);
return is_array($t)?$t[$k]:$t;
// provide a fallback which will not collide with
// 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) {
return ($n != 1);
}}
);
@include_once('addon/' . $plugin . '/' . $plugin . '.php');
- if(function_exists($plugin . '_uninstall')) {
+ if (function_exists($plugin . '_uninstall')) {
$func = $plugin . '_uninstall';
$func();
}
function install_plugin($plugin) {
// silently fail if plugin was removed
- if(! file_exists('addon/' . $plugin . '/' . $plugin . '.php'))
+ if (! file_exists('addon/' . $plugin . '/' . $plugin . '.php'))
return false;
logger("Addons: installing " . $plugin);
$t = @filemtime('addon/' . $plugin . '/' . $plugin . '.php');
@include_once('addon/' . $plugin . '/' . $plugin . '.php');
- if(function_exists($plugin . '_install')) {
+ if (function_exists($plugin . '_install')) {
$func = $plugin . '_install';
$func();
// once most site tables have been updated.
// 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'",
dbesc($plugin)
);
// reload all updated plugins
-if(! function_exists('reload_plugins')) {
+if (! function_exists('reload_plugins')) {
function reload_plugins() {
$plugins = get_config('system','addon');
- if(strlen($plugins)) {
+ if (strlen($plugins)) {
$r = q("SELECT * FROM `addon` WHERE `installed` = 1");
if (dbm::is_result($r))
$parr = explode(',',$plugins);
- if(count($parr)) {
+ if (count($parr)) {
foreach($parr as $pl) {
$pl = trim($pl);
$fname = 'addon/' . $pl . '/' . $pl . '.php';
- if(file_exists($fname)) {
+ if (file_exists($fname)) {
$t = @filemtime($fname);
foreach($installed as $i) {
- if(($i['name'] == $pl) && ($i['timestamp'] != $t)) {
+ if (($i['name'] == $pl) && ($i['timestamp'] != $t)) {
logger('Reloading plugin: ' . $i['name']);
@include_once($fname);
- if(function_exists($pl . '_uninstall')) {
+ if (function_exists($pl . '_uninstall')) {
$func = $pl . '_uninstall';
$func();
}
- if(function_exists($pl . '_install')) {
+ if (function_exists($pl . '_install')) {
$func = $pl . '_install';
$func();
}
* @param int $priority A priority (defaults to 0)
* @return mixed|bool
*/
-if(! function_exists('register_hook')) {
+if (! function_exists('register_hook')) {
function register_hook($hook,$file,$function,$priority=0) {
$r = q("SELECT * FROM `hook` WHERE `hook` = '%s' AND `file` = '%s' AND `function` = '%s' LIMIT 1",
* @param string $function the name of the function that the hook called
* @return array
*/
-if(! function_exists('unregister_hook')) {
+if (! function_exists('unregister_hook')) {
function unregister_hook($hook,$file,$function) {
$r = q("DELETE FROM `hook` WHERE `hook` = '%s' AND `file` = '%s' AND `function` = '%s'",
}}
-if(! function_exists('load_hooks')) {
+if (! function_exists('load_hooks')) {
function load_hooks() {
$a = get_app();
$a->hooks = array();
if (dbm::is_result($r)) {
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($rr['file'],$rr['function']);
}
//check if an app_menu hook exist for plugin $name.
//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) {
$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) {
- if($hook[0] == 'addon/'.$name.'/'.$name.'.php')
+ if ($hook[0] == 'addon/'.$name.'/'.$name.'.php')
return true;
}
}
'unsupported' => false
);
- if(file_exists("view/theme/$theme/experimental"))
+ if (file_exists("view/theme/$theme/experimental"))
$info['experimental'] = true;
- if(file_exists("view/theme/$theme/unsupported"))
+ if (file_exists("view/theme/$theme/unsupported"))
$info['unsupported'] = true;
if (!is_file("view/theme/$theme/theme.php")) return $info;
$service_class = $r[0]['service_class'];
}
}
- if(! x($service_class))
+ if (! x($service_class))
return false; // everything is allowed
$arr = get_config('service_class',$service_class);
- if(! is_array($arr) || (! count($arr)))
+ if (! is_array($arr) || (! count($arr)))
return false;
return((array_key_exists($property,$arr)) ? $arr[$property] : false);
function upgrade_link($bbcode = false) {
$l = get_config('service_class','upgrade_link');
- if(! $l)
+ if (! $l) {
return '';
- if($bbcode)
+ }
+ if ($bbcode) {
$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);
+ }
return $t;
}
*/
function theme_include($file, $root = '') {
// 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 . '/';
+ }
$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'];
- else
+ } else {
$parent = 'NOPATH';
+ }
$theme = current_theme();
$thname = $theme;
$ext = substr($file,strrpos($file,'.')+1);
);
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)
- if(strpos($p,'NOPATH') !== false)
+ if (strpos($p,'NOPATH') !== false) {
continue;
- if(file_exists($p))
+ } elseif (file_exists($p)) {
return $p;
+ }
}
return '';
}
function poller_run($argv, $argc){
global $a, $db;
- if(is_null($a)) {
+ if (is_null($a)) {
$a = new App;
}
- if(is_null($db)) {
+ if (is_null($db)) {
@include(".htconfig.php");
require_once("include/dba.php");
$db = new dba($db_host, $db_user, $db_pass, $db_data);
return;
}
- if(($argc <= 1) OR ($argv[1] != "no_cron")) {
+ if (($argc <= 1) OR ($argv[1] != "no_cron")) {
poller_run_cron();
}
// Decrease the number of workers at higher load
$load = current_load();
- if($load) {
+ if ($load) {
$maxsysload = intval(Config::get("system", "maxloadavg", 50));
$maxworkers = $queues;
$o .= "<select name=\"gender$suffix\" id=\"gender-select$suffix\" size=\"1\" >";
foreach($select as $selection) {
- if($selection !== 'NOTRANSLATION') {
+ if ($selection !== 'NOTRANSLATION') {
$selected = (($selection == $current) ? ' selected="selected" ' : '');
$o .= "<option value=\"$selection\" $selected >$selection</option>";
}
$o .= "<select name=\"sexual$suffix\" id=\"sexual-select$suffix\" size=\"1\" >";
foreach($select as $selection) {
- if($selection !== 'NOTRANSLATION') {
+ if ($selection !== 'NOTRANSLATION') {
$selected = (($selection == $current) ? ' selected="selected" ' : '');
$o .= "<option value=\"$selection\" $selected >$selection</option>";
}
$o .= "<select name=\"marital\" id=\"marital-select\" size=\"1\" >";
foreach($select as $selection) {
- if($selection !== 'NOTRANSLATION') {
+ if ($selection !== 'NOTRANSLATION') {
$selected = (($selection == $current) ? ' selected="selected" ' : '');
$o .= "<option value=\"$selection\" $selected >$selection</option>";
}
global $a;
$r = q("SELECT * FROM `push_subscriber` WHERE `id` = %d", intval($id));
- if (!$r)
+
+ if (!dbm::is_result($r)) {
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);
// increment this until some upper limit where we give up
$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;
+ }
q("UPDATE `push_subscriber` SET `push` = %d WHERE id = %d",
$new_push,
function add_to_queue($cid,$network,$msg,$batch = false) {
$max_queue = get_config('system','max_contact_queue');
- if($max_queue < 1)
+ if ($max_queue < 1) {
$max_queue = 500;
+ }
$batch_queue = get_config('system','max_batch_queue');
- if($batch_queue < 1)
+ if ($batch_queue < 1) {
$batch_queue = 1000;
+ }
$r = q("SELECT COUNT(*) AS `total` FROM `queue` INNER JOIN `contact` ON `queue`.`cid` = `contact`.`id`
WHERE `queue`.`cid` = %d AND `contact`.`self` = 0 ",
intval($cid)
);
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');
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');
return;
}
$start = 0;
- while(($pos = strpos($message, '[quote', $start)) > 0) {
+ while (($pos = strpos($message, '[quote', $start)) > 0) {
$quotes[$pos] = -1;
$start = $pos + 7;
$startquotes++;
$endquotes = 0;
$start = 0;
- while(($pos = strpos($message, '[/quote]', $start)) > 0) {
+ while (($pos = strpos($message, '[/quote]', $start)) > 0) {
$start = $pos + 7;
$endquotes++;
}
$start = 0;
- while(($pos = strpos($message, '[/quote]', $start)) > 0) {
+ while (($pos = strpos($message, '[/quote]', $start)) > 0) {
$quotes[$pos] = 1;
$start = $pos + 7;
}
// prevent looping
- if(x($_REQUEST,'redir') && intval($_REQUEST['redir']))
+ if (x($_REQUEST,'redir') && intval($_REQUEST['redir']))
return;
- if((! $contact_nick) || ($contact_nick === $a->user['nickname']))
+ if ((! $contact_nick) || ($contact_nick === $a->user['nickname']))
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
// am a contact of that user. However, that user may have other contacts with the
$baseurl = App::get_baseurl();
$domain_st = strpos($baseurl, "://");
- if($domain_st === false)
+ if ($domain_st === false)
return;
$baseurl = substr($baseurl, $domain_st + 3);
$nurl = normalise_link($baseurl);
$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'];
$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'];
$dfrn_id = '0:' . $orig_id;
}
// 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
- if(strlen($dfrn_id) < 3)
+ if (strlen($dfrn_id) < 3)
return;
$sec = random_string();
$arr = Probe::lrdd($uri);
- if(is_array($arr)) {
+ if (is_array($arr)) {
foreach($arr as $a) {
- if($a['@attributes']['rel'] === 'magic-public-key') {
+ if ($a['@attributes']['rel'] === 'magic-public-key') {
$ret[] = $a['@attributes']['href'];
}
}
// does contact have a salmon endpoint?
- if(! strlen($url))
+ if (! strlen($url)) {
return;
+ }
- if(! $owner['sprvkey']) {
+ if (! $owner['sprvkey']) {
logger(sprintf("user '%s' (%d) does not have a salmon private key. Send failed.",
$owner['username'],$owner['uid']));
return;
// check for success, e.g. 2xx
- if($return_code > 299) {
+ if ($return_code > 299) {
logger('compliant salmon failed. Falling back to status.net hack2');
$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('slapper for '.$url.' returned ' . $return_code);
- if(! $return_code)
+ if (! $return_code) {
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 ((($return_code >= 200) && ($return_code < 300)) ? 0 : 1);
}
$a->user = $user_record;
- if($interactive) {
- if($a->user['login_date'] === '0000-00-00 00:00:00') {
+ if ($interactive) {
+ if ($a->user['login_date'] === '0000-00-00 00:00:00') {
$_SESSION['return_url'] = 'profile_photo/new';
$a->module = 'profile_photo';
info( t("Welcome ") . $a->user['username'] . EOL);
}
$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;
else
$_SESSION['new_member'] = false;
- if(strlen($a->user['timezone'])) {
+ if (strlen($a->user['timezone'])) {
date_default_timezone_set($a->user['timezone']);
$a->timezone = $a->user['timezone'];
}
$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",
intval($_SESSION['submanage'])
);
if (dbm::is_result($r))
$a->identities = array_merge($a->identities,$r);
- if($login_initial)
+ if ($login_initial)
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);
$r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
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",
dbesc(datetime_convert()),
* Profile owner - everything is visible
*/
- if(($local_user) && ($local_user == $owner_id)) {
+ if (($local_user) && ($local_user == $owner_id)) {
$sql = '';
}
* 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",
intval($remote_user),
intval($owner_id)
$groups = init_groups_visitor($remote_user);
}
}
- if($remote_verified) {
+ if ($remote_verified) {
$gs = '<<>>'; // should be impossible to match
- if(is_array($groups) && count($groups)) {
+ if (is_array($groups) && count($groups)) {
foreach($groups as $g)
$gs .= '|<' . intval($g) . '>';
}
* Profile owner - everything is visible
*/
- if($local_user && ($local_user == $owner_id)) {
+ if ($local_user && ($local_user == $owner_id)) {
$sql = '';
}
* 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",
intval($remote_user),
intval($owner_id)
$groups = init_groups_visitor($remote_user);
}
}
- if($remote_verified) {
+ if ($remote_verified) {
$gs = '<<>>'; // should be impossible to match
- if(is_array($groups) && count($groups)) {
+ if (is_array($groups) && count($groups)) {
foreach($groups as $g)
$gs .= '|<' . intval($g) . '>';
}
// 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) {
$groups = array();
$r = q("SELECT `gid` FROM `group_member`
$a = get_app();
- if($cid) {
- if((! $url) || (! $uid)) {
+ if ($cid) {
+ if ((! $url) || (! $uid)) {
$r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
intval($cid)
);
$uid = $r[0]['uid'];
}
}
- if(! $uid)
+ if (! $uid)
return;
}
- if(! $url)
+ if (! $url)
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') ;
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;
$j = json_decode($s);
logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
- if(! isset($j->entry))
+ if (! isset($j->entry))
return;
$total = 0;
$gcid = update_gcontact($gcontact);
- if(!$gcid)
+ if (!$gcid)
return $gcid;
$r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
}
$lines = explode("\n",$serverret["header"]);
- if(count($lines)) {
- foreach($lines as $line) {
+ if (count($lines)) {
+ foreach ($lines as $line) {
$line = trim($line);
- if(stristr($line,'X-Diaspora-Version:')) {
+ if (stristr($line,'X-Diaspora-Version:')) {
$platform = "Diaspora";
$version = trim(str_replace("X-Diaspora-Version:", "", $line));
$version = trim(str_replace("x-diaspora-version:", "", $version));
$last_contact = datetime_convert();
}
- if(stristr($line,'Server: Mastodon')) {
+ if (stristr($line,'Server: Mastodon')) {
$platform = "Mastodon";
$network = NETWORK_OSTATUS;
// Mastodon doesn't reveal version numbers
function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
- if($shuffle)
+ if ($shuffle)
$sql_extra = " order by rand() ";
else
$sql_extra = " order by `gcontact`.`name` asc ";
function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
- if($shuffle)
+ if ($shuffle)
$sql_extra = " order by rand() ";
else
$sql_extra = " order by `gcontact`.`name` asc ";
if (dbm::is_result($r)) {
foreach ($r as $rr) {
$base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
- if(! in_array($base,$done))
+ if (! in_array($base,$done))
poco_load(0,0,0,$base);
}
}
if ($last) {
$next = $last + (24 * 60 * 60);
- if($next > time())
+ if ($next > time())
return;
}
$updated = date("Y-m-d H:i:s", strtotime($entry->updated));
}
- if(isset($entry->network)) {
+ if (isset($entry->network)) {
$network = $entry->network;
}
- if(isset($entry->currentLocation)) {
+ if (isset($entry->currentLocation)) {
$location = $entry->currentLocation;
}
- if(isset($entry->aboutMe)) {
+ if (isset($entry->aboutMe)) {
$about = html2bbcode($entry->aboutMe);
}
- if(isset($entry->gender)) {
+ if (isset($entry->gender)) {
$gender = $entry->gender;
}
- if(isset($entry->generation) AND ($entry->generation > 0)) {
+ if (isset($entry->generation) AND ($entry->generation > 0)) {
$generation = ++$entry->generation;
}
- if(isset($entry->contactType) AND ($entry->contactType >= 0)) {
+ if (isset($entry->contactType) AND ($entry->contactType >= 0)) {
$contact_type = $entry->contactType;
}
- if(isset($entry->tags)) {
+ if (isset($entry->tags)) {
foreach ($entry->tags as $tag) {
$keywords = implode(", ", $tag);
}
if (substr(trim($tag), 0, 1) == "#") {
// 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;
// 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;
$type = TERM_HASHTAG;
$term = substr($tag, 1);
function create_tags_from_itemuri($itemuri, $uid) {
$messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid));
- if(count($messages)) {
- foreach ($messages as $message)
+ if (count($messages)) {
+ foreach ($messages as $message) {
create_tags_from_item($message["id"]);
+ }
}
}
function update_items() {
global $db;
- $messages = $db->q("SELECT `oid`,`item`.`guid`, `item`.`created`, `item`.`received` FROM `term` INNER JOIN `item` ON `item`.`id`=`term`.`oid` WHERE `term`.`otype` = 1 AND `term`.`guid` = ''", true);
+ $messages = $db->q("SELECT `oid`,`item`.`guid`, `item`.`created`, `item`.`received` FROM `term` INNER JOIN `item` ON `item`.`id`=`term`.`oid` WHERE `term`.`otype` = 1 AND `term`.`guid` = ''", true);
- logger("fetched messages: ".count($messages));
- while ($message = $db->qfetch()) {
+ logger("fetched messages: ".count($messages));
+ while ($message = $db->qfetch()) {
if ($message["uid"] == 0) {
$global = true;
intval($global), intval(TERM_OBJ_POST), intval($message["oid"]));
}
- $db->qclose();
+ $db->qclose();
$messages = $db->q("SELECT `guid` FROM `item` WHERE `uid` = 0", true);
* {{ 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) {
list($a, $b) = array_map("trim", explode("==", $args[2]));
$a = $this->_get_var($a);
require_once("mod/proxy.php");
-if(! function_exists('replace_macros')) {
+if (! function_exists('replace_macros')) {
/**
* This is our template processor
*
define('RANDOM_STRING_HEX', 0x00 );
define('RANDOM_STRING_TEXT', 0x01 );
-if(! function_exists('random_string')) {
+if (! function_exists('random_string')) {
function random_string($size = 64,$type = RANDOM_STRING_HEX) {
// generate a bit of entropy and run it through the whirlpool
$s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
return(substr($s,0,$size));
}}
-if(! function_exists('notags')) {
+if (! function_exists('notags')) {
/**
* This is our primary input filter.
*
-if(! function_exists('escape_tags')) {
+if (! function_exists('escape_tags')) {
/**
* use this on "body" or "content" input where angle chars shouldn't be removed,
* and allow them to be safely displayed.
// generate a string that's random, but usually pronounceable.
// used to generate initial passwords
-if(! function_exists('autoname')) {
+if (! function_exists('autoname')) {
/**
* generate a string that's random, but usually pronounceable.
* used to generate initial passwords
*/
function autoname($len) {
- if($len <= 0)
+ if ($len <= 0)
return '';
$vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
- if(mt_rand(0,5) == 4)
+ if (mt_rand(0,5) == 4)
$vowels[] = 'y';
$cons = array(
'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
$start = mt_rand(0,2);
- if($start == 0)
+ if ($start == 0)
$table = $vowels;
else
$table = $cons;
$r = mt_rand(0,count($table) - 1);
$word .= $table[$r];
- if($table == $vowels)
+ if ($table == $vowels)
$table = array_merge($cons,$midcons);
else
$table = $vowels;
$word = substr($word,0,$len);
foreach($noend as $noe) {
- if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
+ if ((strlen($word) > 2) && (substr($word,-2) == $noe)) {
$word = substr($word,0,-1);
break;
}
}
- if(substr($word,-1) == 'q')
+ if (substr($word,-1) == 'q')
$word = substr($word,0,-1);
return $word;
}}
// escape text ($str) for XML transport
// returns escaped text.
-if(! function_exists('xmlify')) {
+if (! function_exists('xmlify')) {
/**
* escape text ($str) for XML transport
* @param string $str
return($buffer);
}}
-if(! function_exists('unxmlify')) {
+if (! function_exists('unxmlify')) {
/**
* undo an xmlify
* @param string $s xml escaped text
return $ret;
}}
-if(! function_exists('hex2bin')) {
+if (! function_exists('hex2bin')) {
/**
* convenience wrapper, reverse the operation "bin2hex"
* @param string $s
* @return number
*/
function hex2bin($s) {
- if(! (is_string($s) && strlen($s)))
+ if (! (is_string($s) && strlen($s)))
return '';
- if(! ctype_xdigit($s)) {
+ if (! ctype_xdigit($s)) {
return($s);
}
return $data;
}
-if(! function_exists('paginate')) {
+if (! function_exists('paginate')) {
/**
* Automatic pagination.
*
}}
-if(! function_exists('alt_pager')) {
+if (! function_exists('alt_pager')) {
/**
* Alternative pager
* @param App $a App instance
}}
-if(! function_exists('scroll_loader')) {
+if (! function_exists('scroll_loader')) {
/**
* Loader for infinite scrolling
* @return string html for loader
));
}}
-if(! function_exists('expand_acl')) {
+if (! function_exists('expand_acl')) {
/**
* Turn user/group ACLs stored as angle bracketed text into arrays
*
// e.g. "<1><2><3>" => array(1,2,3);
$ret = array();
- if(strlen($s)) {
+ if (strlen($s)) {
$t = str_replace('<','',$s);
$a = explode('>',$t);
foreach($a as $aa) {
- if(intval($aa))
+ if (intval($aa))
$ret[] = intval($aa);
}
}
return $ret;
}}
-if(! function_exists('sanitise_acl')) {
+if (! function_exists('sanitise_acl')) {
/**
* Wrap ACL elements in angle brackets for storage
* @param string $item
*/
function sanitise_acl(&$item) {
- if(intval($item))
+ if (intval($item))
$item = '<' . intval(notags(trim($item))) . '>';
else
unset($item);
}}
-if(! function_exists('perms2str')) {
+if (! function_exists('perms2str')) {
/**
* Convert an ACL array to a storable string
*
*/
function perms2str($p) {
$ret = '';
- if(is_array($p))
+ if (is_array($p))
$tmp = $p;
else
$tmp = explode(',',$p);
- if(is_array($tmp)) {
+ if (is_array($tmp)) {
array_walk($tmp,'sanitise_acl');
$ret = implode('',$tmp);
}
}}
-if(! function_exists('item_new_uri')) {
+if (! function_exists('item_new_uri')) {
/**
* generate a guaranteed unique (for this domain) item ID for ATOM
* safe from birthday paradox
dbesc($uri));
if (dbm::is_result($r))
$dups = true;
- } while($dups == true);
+ } while ($dups == true);
return $uri;
}}
// Generate a guaranteed unique photo ID.
// safe from birthday paradox
-if(! function_exists('photo_new_resource')) {
+if (! function_exists('photo_new_resource')) {
/**
* Generate a guaranteed unique photo ID.
* safe from birthday paradox
);
if (dbm::is_result($r))
$found = true;
- } while($found == true);
+ } while ($found == true);
return $resource;
}}
-if(! function_exists('load_view_file')) {
+if (! function_exists('load_view_file')) {
/**
* @deprecated
* wrapper to load a view template, checking for alternate
*/
function load_view_file($s) {
global $lang, $a;
- if(! isset($lang))
+ if (! isset($lang))
$lang = 'en';
$b = basename($s);
$d = dirname($s);
- if(file_exists("$d/$lang/$b")) {
+ if (file_exists("$d/$lang/$b")) {
$stamp1 = microtime(true);
$content = file_get_contents("$d/$lang/$b");
$a->save_timestamp($stamp1, "file");
$theme = current_theme();
- if(file_exists("$d/theme/$theme/$b")) {
+ if (file_exists("$d/theme/$theme/$b")) {
$stamp1 = microtime(true);
$content = file_get_contents("$d/theme/$theme/$b");
$a->save_timestamp($stamp1, "file");
return $content;
}}
-if(! function_exists('get_intltext_template')) {
+if (! function_exists('get_intltext_template')) {
/**
* load a view template, checking for alternate
* languages before falling back to the default
$a = get_app();
$engine = '';
- if($a->theme['template_engine'] === 'smarty3')
+ if ($a->theme['template_engine'] === 'smarty3')
$engine = "/smarty3";
- if(! isset($lang))
+ if (! isset($lang))
$lang = 'en';
- if(file_exists("view/lang/$lang$engine/$s")) {
+ if (file_exists("view/lang/$lang$engine/$s")) {
$stamp1 = microtime(true);
$content = file_get_contents("view/lang/$lang$engine/$s");
$a->save_timestamp($stamp1, "file");
return $content;
- } elseif(file_exists("view/lang/en$engine/$s")) {
+ } elseif (file_exists("view/lang/en$engine/$s")) {
$stamp1 = microtime(true);
$content = file_get_contents("view/lang/en$engine/$s");
$a->save_timestamp($stamp1, "file");
}
}}
-if(! function_exists('get_markup_template')) {
+if (! function_exists('get_markup_template')) {
/**
* load template $s
*
return $template;
}}
-if(! function_exists("get_template_file")) {
+if (! function_exists("get_template_file")) {
/**
*
* @param App $a
$theme = current_theme();
// Make sure $root ends with a slash /
- if($root !== '' && $root[strlen($root)-1] !== '/')
+ if ($root !== '' && $root[strlen($root)-1] !== '/')
$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";
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";
-if(! function_exists('attribute_contains')) {
+if (! function_exists('attribute_contains')) {
/**
* for html,xml parsing - let's say you've got
* an attribute foobar="class1 class2 class3"
*/
function attribute_contains($attr,$s) {
$a = explode(' ', $attr);
- if(count($a) && in_array($s,$a))
+ if (count($a) && in_array($s,$a))
return true;
return false;
}}
}}
-if(! function_exists('activity_match')) {
+if (! function_exists('activity_match')) {
/**
* Compare activity uri. Knows about activity namespace.
*
* @return boolean
*/
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 false;
}}
//
-if(! function_exists('qp')) {
+if (! function_exists('qp')) {
/**
* quick and dirty quoted_printable encoding
*
return str_replace ("%","=",rawurlencode($s));
}}
-if(! function_exists('contact_block')) {
+if (! function_exists('contact_block')) {
/**
* Get html for contact block.
*
$a = get_app();
$shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
- if($shown === false)
+ if ($shown === false)
$shown = 24;
- if($shown == 0)
+ if ($shown == 0)
return;
- if((! is_array($a->profile)) || ($a->profile['hide-friends']))
+ if ((! is_array($a->profile)) || ($a->profile['hide-friends']))
return $o;
$r = q("SELECT COUNT(*) AS `total` FROM `contact`
WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
if (dbm::is_result($r)) {
$total = intval($r[0]['total']);
}
- if(! $total) {
+ if (! $total) {
$contacts = t('No contacts');
$micropro = Null;
$sparkle = '';
$redir = false;
- if($redirect) {
+ if ($redirect) {
$a = get_app();
$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;
$url = $redirect_url;
$sparkle = ' sparkle';
}
// If there is some js available we don't need the url
- if(x($contact,'click'))
+ if (x($contact,'click'))
$url = '';
return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),array(
-if(! function_exists('search')) {
+if (! function_exists('search')) {
/**
* search box
*
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
*
function valid_email($x){
// Removed because Fabio told me so.
- //if(get_config('system','disable_email_validation'))
+ //if (get_config('system','disable_email_validation'))
// 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 false;
}}
-if(! function_exists('linkify')) {
+if (! function_exists('linkify')) {
/**
* Replace naked text hyperlink with HTML formatted hyperlink
*
return $arr;
}
-if(! function_exists('day_translate')) {
+if (! function_exists('day_translate')) {
/**
* Translate days and months names
*
}}
-if(! function_exists('normalise_link')) {
+if (! function_exists('normalise_link')) {
/**
* Normalize url
*
-if(! function_exists('link_compare')) {
+if (! function_exists('link_compare')) {
/**
* Compare two URLs to see if they are the same, but ignore
* slight but hopefully insignificant differences such as if one
*
*/
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 false;
}}
// 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(! 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.
* If attach is true, also add icons for item attachments
call_hooks('prepare_body', $prep_arr);
$s = $prep_arr['html'];
- if(! $attach) {
+ if (! $attach) {
// 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;">';
$s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
$as = '';
$vhead = false;
$arr = explode('[/attach],',$item['attach']);
- if(count($arr)) {
+ if (count($arr)) {
$as .= '<div class="body-attach">';
foreach($arr as $r) {
$matches = false;
$icon = '';
$cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER);
- if($cnt) {
+ if ($cnt) {
foreach($matches as $mtch) {
$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];
else
$the_url = $mtch[1];
- if(strpos($mime, 'video') !== false) {
- if(!$vhead) {
+ if (strpos($mime, 'video') !== false) {
+ if (!$vhead) {
$vhead = true;
$a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array(
'$baseurl' => z_root(),
}
$filetype = strtolower(substr( $mime, 0, strpos($mime,'/') ));
- if($filetype) {
+ if ($filetype) {
$filesubtype = strtolower(substr( $mime, strpos($mime,'/') + 1 ));
$filesubtype = str_replace('.', '-', $filesubtype);
}
$s = $s . $as;
// 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']));
if ($x) {
$s = preg_replace('/\<div class\=\"map\"\>/','$0' . $x,$s);
}}
-if(! function_exists('prepare_text')) {
+if (! function_exists('prepare_text')) {
/**
* Given a text string, convert from bbcode to html and add smilie icons.
*
require_once('include/bbcode.php');
- if(stristr($text,'[nosmile]'))
+ if (stristr($text,'[nosmile]'))
$s = bbcode($text);
else
$s = Smilies::replace(bbcode($text));
$matches = false; $first = true;
$cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
- if($cnt) {
+ if ($cnt) {
foreach($matches as $mtch) {
$categories[] = array(
'name' => xmlify(file_tag_decode($mtch[1])),
if (count($categories)) $categories[count($categories)-1]['last'] = true;
- if(local_user() == $item['uid']) {
+ if (local_user() == $item['uid']) {
$matches = false; $first = true;
$cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
- if($cnt) {
+ if ($cnt) {
foreach($matches as $mtch) {
$folders[] = array(
'name' => xmlify(file_tag_decode($mtch[1])),
return array($categories, $folders);
}
-if(! function_exists('get_plink')) {
+if (! function_exists('get_plink')) {
/**
* get private link for item
* @param array $item
return($ret);
}}
-if(! function_exists('unamp')) {
+if (! function_exists('unamp')) {
/**
* replace html amp entity with amp char
* @param string $s
}}
-if(! function_exists('return_bytes')) {
+if (! function_exists('return_bytes')) {
/**
* return number of bytes in size (K, M, G)
* @param string $size_str
$x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
dbesc($guid)
);
- if(! count($x))
+ if (! count($x))
$found = false;
} while ($found == true );
return $guid;
$s = strtr(base64_encode($s),'+/','-_');
- if($strip_padding)
+ if ($strip_padding)
$s = str_replace('=','',$s);
return $s;
*/
function base64url_decode($s) {
- if(is_array($s)) {
+ if (is_array($s)) {
logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
return $s;
}
* // Uncomment if you find you need it.
*
* $l = strlen($s);
- * if(! strpos($s,'=')) {
+ * if (! strpos($s,'=')) {
* $m = $l % 4;
- * if($m == 2)
+ * if ($m == 2)
* $s .= '==';
- * if($m == 3)
+ * if ($m == 3)
* $s .= '=';
* }
*
$r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
if ($r) {
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);
- elseif(stristr($mtch[1],'vimeo'))
+ elseif (stristr($mtch[1],'vimeo'))
$s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
}
}
* @return string
*/
function item_post_type($item) {
- if(intval($item['event-id']))
+ if (intval($item['event-id']))
return t('event');
- if(strlen($item['resource-id']))
+ if (strlen($item['resource-id']))
return t('photo');
- if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
+ if (strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
return t('activity');
- if($item['id'] != $item['parent'])
+ if ($item['id'] != $item['parent'])
return t('comment');
return t('post');
}
function file_tag_file_query($table,$s,$type = 'file') {
- if($type == 'file')
+ if ($type == 'file')
$str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
else
$str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
// ex. given music,video return <music><video> or [music][video]
function file_tag_list_to_file($list,$type = 'file') {
$tag_list = '';
- if(strlen($list)) {
+ if (strlen($list)) {
$list_array = explode(",",$list);
- if($type == 'file') {
+ if ($type == 'file') {
$lbracket = '[';
$rbracket = ']';
}
}
foreach($list_array as $item) {
- if(strlen($item)) {
+ if (strlen($item)) {
$tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
}
}
function file_tag_file_to_list($file,$type = 'file') {
$matches = false;
$list = '';
- if($type == 'file') {
+ if ($type == 'file') {
$cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
}
else {
$cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
}
- if($cnt) {
+ if ($cnt) {
foreach($matches as $mtch) {
- if(strlen($list))
+ if (strlen($list))
$list .= ',';
$list .= file_tag_decode($mtch[1]);
}
// $file_old - categories previously associated with an item
// $file_new - new list of categories for an item
- if(! intval($uid))
+ if (! intval($uid))
return false;
- if($file_old == $file_new)
+ if ($file_old == $file_new)
return true;
$saved = get_pconfig($uid,'system','filetags');
- if(strlen($saved)) {
- if($type == 'file') {
+ if (strlen($saved)) {
+ if ($type == 'file') {
$lbracket = '[';
$rbracket = ']';
$termtype = TERM_FILE;
$check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
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;
}
$check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
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;
}
}
}
- if($saved != $filetags_updated) {
+ if ($saved != $filetags_updated) {
set_pconfig($uid,'system','filetags', $filetags_updated);
}
return true;
}
else
- if(strlen($file_new)) {
+ if (strlen($file_new)) {
set_pconfig($uid,'system','filetags', $file_new);
}
return true;
require_once("include/files.php");
$result = false;
- if(! intval($uid))
+ if (! intval($uid))
return false;
$r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
intval($item),
intval($uid)
);
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",
dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
intval($item),
create_files_from_item($item);
$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) . ']');
info( t('Item filed') );
}
require_once("include/files.php");
$result = false;
- if(! intval($uid))
+ if (! intval($uid))
return false;
- if($cat == true) {
+ if ($cat == true) {
$pattern = '<' . file_tag_encode($file) . '>' ;
$termtype = TERM_CATEGORY;
} else {
function undo_post_tagging($s) {
$matches = null;
$cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
- if($cnt) {
+ if ($cnt) {
foreach($matches as $mtch) {
$s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
}
function is_a_date_arg($s) {
$i = intval($s);
- if($i > 1900) {
+ if ($i > 1900) {
$y = date('Y');
- if($i <= $y+1 && strpos($s,'-') == 4) {
+ if ($i <= $y+1 && strpos($s,'-') == 4) {
$m = intval(substr($s,5));
- if($m > 0 && $m <= 12)
+ if ($m > 0 && $m <= 12)
return true;
}
}
* @return string Formated html
*/
function text_highlight($s,$lang) {
- if($lang === 'js')
+ if ($lang === 'js')
$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');
}
// 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($lang === 'php') {
- if(strpos('<?php',$s) !== 0) {
+ if ($lang === 'php') {
+ if (strpos('<?php',$s) !== 0) {
$s = '<?php' . "\n" . $s;
$tag_added = true;
}
$o = $hl->highlight($s);
$o = str_replace([" ","\n"],[" ",''],$o);
- if($tag_added) {
+ if ($tag_added) {
$b = substr($o,0,strpos($o,'<li>'));
$e = substr($o,strpos($o,'</li>'));
$o = $b . $e;
function update_thread_uri($itemuri, $uid) {
$messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid));
- if (dbm::is_result($messages))
- foreach ($messages as $message)
+ if (dbm::is_result($messages)) {
+ foreach ($messages as $message) {
update_thread($message["id"]);
+ }
+ }
}
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`,
`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;
+ }
$item = $items[0];
- if ($setmention)
+ if ($setmention) {
$item["mention"] = 1;
+ }
$sql = "";
foreach ($item AS $field => $data)
if (!in_array($field, array("guid", "title", "body", "rendered-html", "rendered-hash"))) {
- if ($sql != "")
+ if ($sql != "") {
$sql .= ", ";
+ }
$sql .= "`".$field."` = '".dbesc($data)."'";
}
// Updating a shadow item entry
$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;
+ }
$result = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `rendered-html` = '%s', `rendered-hash` = '%s' WHERE `id` = %d",
dbesc($item["title"]),
function delete_thread_uri($itemuri, $uid) {
$messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid));
- if(count($messages))
- foreach ($messages as $message)
+ if (dbm::is_result($messages)) {
+ foreach ($messages as $message) {
delete_thread($message["id"], $itemuri);
+ }
+ }
}
function delete_thread($itemid, $itemuri = "") {
$r = q("SELECT * FROM `gcontact` WHERE `id` = %d", intval($contact_id));
- if (!$r)
+ if (!dbm::is_result($r)) {
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;
+ }
$data = probe_url($r[0]["url"]);
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"]);
+ }
q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `id` = %d",
dbesc(datetime_convert()), intval($contact_id));
return;
}
- if (($data["name"] == "") AND ($r[0]['name'] != ""))
+ if (($data["name"] == "") AND ($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'];
+ }
- if (($data["addr"] == "") AND ($r[0]['addr'] != ""))
+ if (($data["addr"] == "") AND ($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'];
-
+ }
q("UPDATE `gcontact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `photo` = '%s'
WHERE `id` = %d",
$tmp_str = $openid_url;
- if($using_invites) {
- if(! $invite_id) {
+ if ($using_invites) {
+ if (! $invite_id) {
$result['message'] .= t('An invitation is required.') . EOL;
return $result;
}
$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;
return $result;
}
}
- if((! x($username)) || (! x($email)) || (! x($nickname))) {
- if($openid_url) {
- if(! validate_url($tmp_str)) {
+ if ((! x($username)) || (! x($email)) || (! x($nickname))) {
+ if ($openid_url) {
+ if (! validate_url($tmp_str)) {
$result['message'] .= t('Invalid OpenID url') . EOL;
return $result;
}
return;
}
- if(! validate_url($tmp_str))
+ if (! validate_url($tmp_str))
$openid_url = '';
// collapse multiple spaces in name
$username = preg_replace('/ +/',' ',$username);
- if(mb_strlen($username) > 48)
+ if (mb_strlen($username) > 48)
$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;
// I don't really like having this rule, but it cuts down
// So now we are just looking for a space in the full name.
$loose_reg = get_config('system','no_regfullname');
- if(! $loose_reg) {
+ if (! $loose_reg) {
$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;
}
- if(! allowed_email($email))
+ if (! allowed_email($email))
$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;
// Disallow somebody creating an account using openid that uses the admin email address,
$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')) && in_array(strtolower($email), $adminlist) && 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)) {
$r = q("SELECT * FROM `user` WHERE `email` = '%s' LIMIT 1",
dbesc($email)
);
$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;
$r = q("SELECT `uid` FROM `user`
if (dbm::is_result($r))
$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;
}
$keys = new_keypair(4096);
- if($keys === false) {
+ if ($keys === false) {
$result['message'] .= t('SERIOUS ERROR: Generation of security keys failed.') . EOL;
return $result;
}
$default_service_class = get_config('system','default_service_class');
- if(! $default_service_class)
+ if (! $default_service_class)
$default_service_class = '';
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` )
VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, %d ) ",
intval($newuid),
);
}
- 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",
dbesc("<" . $def_gid . ">"),
intval($newuid)
}
// if we have no OpenID photo try to look up an avatar
- if(! strlen($photo))
+ if (! strlen($photo))
$photo = avatar_img($email);
// unless there is no avatar-plugin loaded
- if(strlen($photo)) {
+ if (strlen($photo)) {
require_once('include/Photo.php');
$photo_failure = false;
$img = new Photo($img_str, $type);
- if($img->is_valid()) {
+ if ($img->is_valid()) {
$img->scaleImageSquare(175);
//Set the attributes too.
if (isset($attributes) and $get_attributes) {
foreach ($attributes as $attr => $val) {
- if($priority == 'tag') {
+ if ($priority == 'tag') {
$attributes_data[$attr] = $val;
} else {
$result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'