1
0
Fork 0

Merge remote-tracking branch 'upstream/develop' into rewrites/coding-convention-split2-6-2

Signed-off-by: Roland Häder <roland@mxchange.org>
This commit is contained in:
Roland Häder 2017-06-13 23:26:06 +02:00
commit 4e49939421
No known key found for this signature in database
GPG key ID: B72F8185C6C7BD78
165 changed files with 63565 additions and 40577 deletions

View file

@ -262,33 +262,33 @@ function get_contact_details_by_url($url, $uid = -1, $default = array()) {
$profile = $default;
}
if (($profile["photo"] == "") AND isset($default["photo"])) {
if (($profile["photo"] == "") && isset($default["photo"])) {
$profile["photo"] = $default["photo"];
}
if (($profile["name"] == "") AND isset($default["name"])) {
if (($profile["name"] == "") && isset($default["name"])) {
$profile["name"] = $default["name"];
}
if (($profile["network"] == "") AND isset($default["network"])) {
if (($profile["network"] == "") && isset($default["network"])) {
$profile["network"] = $default["network"];
}
if (($profile["thumb"] == "") AND isset($profile["photo"])) {
if (($profile["thumb"] == "") && isset($profile["photo"])) {
$profile["thumb"] = $profile["photo"];
}
if (($profile["micro"] == "") AND isset($profile["thumb"])) {
if (($profile["micro"] == "") && isset($profile["thumb"])) {
$profile["micro"] = $profile["thumb"];
}
if ((($profile["addr"] == "") OR ($profile["name"] == "")) AND ($profile["gid"] != 0) AND
if ((($profile["addr"] == "") || ($profile["name"] == "")) && ($profile["gid"] != 0) &&
in_array($profile["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
proc_run(PRIORITY_LOW, "include/update_gcontact.php", $profile["gid"]);
}
// Show contact details of Diaspora contacts only if connected
if (($profile["cid"] == 0) AND ($profile["network"] == NETWORK_DIASPORA)) {
if (($profile["cid"] == 0) && ($profile["network"] == NETWORK_DIASPORA)) {
$profile["location"] = "";
$profile["about"] = "";
$profile["gender"] = "";
@ -559,7 +559,7 @@ function get_contact($url, $uid = 0, $no_update = false) {
// Update the contact every 7 days
$update_photo = ($contacts[0]['avatar-date'] < datetime_convert('','','now -7 days'));
if (!$update_photo OR $no_update) {
if (!$update_photo || $no_update) {
return $contact_id;
}
} elseif ($uid != 0) {
@ -636,7 +636,7 @@ function get_contact($url, $uid = 0, $no_update = false) {
}
}
if (count($contacts) > 1 AND $uid == 0 AND $contact_id != 0 AND $url != "") {
if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $url != "") {
q("DELETE FROM `contact` WHERE `nurl` = '%s' AND `id` != %d AND NOT `self`",
dbesc(normalise_link($url)),
intval($contact_id));
@ -654,9 +654,9 @@ function get_contact($url, $uid = 0, $no_update = false) {
}
// Only update if there had something been changed
if ($data["addr"] != $contacts[0]["addr"] OR
$data["alias"] != $contacts[0]["alias"] OR
$data["name"] != $contacts[0]["name"] OR
if ($data["addr"] != $contacts[0]["addr"] ||
$data["alias"] != $contacts[0]["alias"] ||
$data["name"] != $contacts[0]["name"] ||
$data["nick"] != $contacts[0]["nick"]) {
q("UPDATE `contact` SET `addr` = '%s', `alias` = '%s', `name` = '%s', `nick` = '%s',
`name-date` = '%s', `uri-date` = '%s' WHERE `id` = %d",
@ -769,7 +769,7 @@ function formatted_location($profile) {
if($profile['locality'])
$location .= $profile['locality'];
if($profile['region'] AND ($profile['locality'] != $profile['region'])) {
if($profile['region'] && ($profile['locality'] != $profile['region'])) {
if($location)
$location .= ', ';

View file

@ -4,10 +4,12 @@
* @brief Methods for read and write notifications from/to database
* or for formatting notifications
*/
require_once 'include/html2plain.php';
require_once 'include/probe.php';
require_once 'include/datetime.php';
require_once 'include/bbcode.php';
require_once 'include/Contact.php';
/**
* @brief Methods for read and write notifications from/to database
@ -510,7 +512,7 @@ class NotificationsManager {
$myurl = substr($myurl,strpos($myurl,'://')+3);
$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
$diasp_url = str_replace('/profile/','/u/',$myurl);
$sql_extra = sprintf(" AND ( `item`.`author-link` regexp '%s' or `item`.`tag` regexp '%s' or `item`.`tag` regexp '%s' ) ",
$sql_extra = sprintf(" AND ( `item`.`author-link` regexp '%s' OR `item`.`tag` regexp '%s' OR `item`.`tag` regexp '%s' ) ",
dbesc($myurl . '$'),
dbesc($myurl . '\\]'),
dbesc($diasp_url . '\\]')
@ -720,10 +722,12 @@ class NotificationsManager {
$sql_extra = " AND `ignore` = 0 ";
/// @todo Fetch contact details by "get_contact_details_by_url" instead of queries to contact, fcontact and gcontact
$r = q("SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*, `fcontact`.`name` AS `fname`,`fcontact`.`url` AS `furl`,`fcontact`.`photo` AS `fphoto`,`fcontact`.`request` AS `frequest`,
$r = q("SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
`fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`,
`fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
`gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
`gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
`gcontact`.`network` AS `gnetwork`
`gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
FROM `intro`
LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
@ -786,11 +790,7 @@ class NotificationsManager {
// Normal connection requests
} else {
// Probe the contact url to get missing data
$ret = probe_url($it["url"]);
if ($it['gnetwork'] == "")
$it['gnetwork'] = $ret["network"];
$it = $this->getMissingIntroData($it);
// Don't show these data until you are connected. Diaspora is doing the same.
if($it['gnetwork'] === NETWORK_DIASPORA) {
@ -815,7 +815,7 @@ class NotificationsManager {
'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
'url' => $it['url'],
'zrl' => zrl($it['url']),
'addr' => $ret['addr'],
'addr' => $it['gaddr'],
'network' => $it['gnetwork'],
'knowyou' => $it['knowyou'],
'note' => $it['note'],
@ -827,4 +827,38 @@ class NotificationsManager {
return $arr;
}
/**
* @brief Check for missing contact data and try to fetch the data from
* from other sources
*
* @param array $arr The input array with the intro data
*
* @return array The array with the intro data
*/
private function getMissingIntroData($arr) {
// If the network and the addr isn't available from the gcontact
// table entry, take the one of the contact table entry
if ($arr['gnetwork'] == "") {
$arr['gnetwork'] = $arr['network'];
}
if ($arr['gaddr'] == "") {
$arr['gaddr'] = $arr['addr'];
}
// If the network and addr is still not available
// get the missing data data from other sources
if ($arr['gnetwork'] == "" || $arr['gaddr'] == "") {
$ret = get_contact_details_by_url($arr['url']);
if ($arr['gnetwork'] == "" && $ret['network'] != "") {
$arr['gnetwork'] = $ret['network'];
}
if ($arr['gaddr'] == "" && $ret['addr'] != "") {
$arr['gaddr'] = $ret['addr'];
}
}
return $arr;
}
}

View file

@ -778,21 +778,29 @@ function guess_image_type($filename, $fromcurl=false) {
* @return array Returns array of the different avatar sizes
*/
function update_contact_avatar($avatar, $uid, $cid, $force = false) {
$r = q("SELECT `avatar`, `photo`, `thumb`, `micro` FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
$r = q("SELECT `avatar`, `photo`, `thumb`, `micro`, `nurl` FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
if (!dbm::is_result($r)) {
return false;
} else {
$data = array($r[0]["photo"], $r[0]["thumb"], $r[0]["micro"]);
}
if (($r[0]["avatar"] != $avatar) OR $force) {
if (($r[0]["avatar"] != $avatar) || $force) {
$photos = import_profile_photo($avatar, $uid, $cid, true);
if ($photos) {
q("UPDATE `contact` SET `avatar` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' WHERE `id` = %d",
dbesc($avatar), dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]),
dbesc(datetime_convert()), intval($cid));
// Update the public contact (contact id = 0)
if ($uid != 0) {
$pcontact = dba::select('contact', array('id'), array('nurl' => $r[0]['nurl']), array('limit' => 1));
if (dbm::is_result($pcontact)) {
update_contact_avatar($avatar, 0, $pcontact['id'], $force);
}
}
return $photos;
}
}
@ -817,7 +825,7 @@ function import_profile_photo($photo, $uid, $cid, $quit_on_error = false) {
$filename = basename($photo);
$img_str = fetch_url($photo, true);
if ($quit_on_error AND ($img_str == "")) {
if ($quit_on_error && ($img_str == "")) {
return false;
}
@ -847,14 +855,35 @@ function import_profile_photo($photo, $uid, $cid, $quit_on_error = false) {
$photo_failure = true;
}
$photo = App::get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
$thumb = App::get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
$micro = App::get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
$suffix = '?ts='.time();
$photo = App::get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt() . $suffix;
$thumb = App::get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt() . $suffix;
$micro = App::get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt() . $suffix;
// Remove the cached photo
$a = get_app();
$basepath = $a->get_basepath();
if (is_dir($basepath."/photo")) {
$filename = $basepath.'/photo/'.$hash.'-4.'.$img->getExt();
if (file_exists($filename)) {
unlink($filename);
}
$filename = $basepath.'/photo/'.$hash.'-5.'.$img->getExt();
if (file_exists($filename)) {
unlink($filename);
}
$filename = $basepath.'/photo/'.$hash.'-6.'.$img->getExt();
if (file_exists($filename)) {
unlink($filename);
}
}
} else {
$photo_failure = true;
}
if ($photo_failure AND $quit_on_error) {
if ($photo_failure && $quit_on_error) {
return false;
}
@ -873,7 +902,7 @@ function get_photo_info($url) {
$data = Cache::get($url);
if (is_null($data) OR !$data OR !is_array($data)) {
if (is_null($data) || !$data || !is_array($data)) {
$img_str = fetch_url($url, true, $redirects, 4);
$filesize = strlen($img_str);
@ -967,7 +996,7 @@ function store_photo(App $a, $uid, $imagedata = "", $url = "") {
/// $default_cid = $r[0]['id'];
/// $community_page = (($r[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
if ((strlen($imagedata) == 0) AND ($url == "")) {
if ((strlen($imagedata) == 0) && ($url == "")) {
logger("No image data and no url provided", LOGGER_DEBUG);
return(array());
} elseif (strlen($imagedata) == 0) {
@ -1073,7 +1102,7 @@ function store_photo(App $a, $uid, $imagedata = "", $url = "") {
}
}
if ($width > 160 AND $height > 160) {
if ($width > 160 && $height > 160) {
$x = 0;
$y = 0;

View file

@ -209,7 +209,7 @@ function contact_select($selname, $selclass, $preselected = false, $size = 4, $p
$tabindex = ($tabindex > 0 ? "tabindex=\"$tabindex\"" : "");
if ($privmail AND $preselected) {
if ($privmail && $preselected) {
$sql_extra .= " AND `id` IN (".implode(",", $preselected).")";
$hidepreselected = ' style="display: none;"';
} else {
@ -261,7 +261,7 @@ function contact_select($selname, $selclass, $preselected = false, $size = 4, $p
$o .= "</select>\r\n";
if ($privmail AND $preselected) {
if ($privmail && $preselected) {
$o .= implode(", ", $receiverlist);
}
@ -388,6 +388,9 @@ function populate_acl($user = null, $show_jotnets = false) {
}
function construct_acl_data(App $a, $user) {
// This function is now deactivated. It seems as if the generated data isn't used anywhere.
/// @todo Remove this function and all function calls before releasing Friendica 3.5.3
return;
// Get group and contact information for html ACL selector
$acl_data = acl_lookup($a, 'html');

View file

@ -456,10 +456,13 @@ $called_api = null;
* Contact url or False if contact id is unknown
*/
function api_unique_id_to_url($id) {
$r = q("SELECT `url` FROM `contact` WHERE `uid` = 0 AND `id` = %d LIMIT 1",
intval($id));
$r = dba::select('contact', array('url'), array('uid' => 0, 'id' => $id), array('limit' => 1));
return (dbm::is_result($r) && $r[0]["url"]);
if (dbm::is_result($r)) {
return $r["url"];
} else {
return false;
}
}
/**
@ -480,7 +483,7 @@ $called_api = null;
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) && (intval($contact_id) == 0)) {
$user = dbesc(normalise_link($contact_id));
$url = $user;
$extra_query = "AND `contact`.`nurl` = '%s' ";
@ -490,7 +493,7 @@ $called_api = null;
}
// Searching for contact id with uid = 0
if (!is_null($contact_id) AND (intval($contact_id) != 0)) {
if (!is_null($contact_id) && (intval($contact_id) != 0)) {
$user = dbesc(api_unique_id_to_url($contact_id));
if ($user == "") {
@ -535,7 +538,7 @@ $called_api = null;
}
}
if (is_null($user) AND ($a->argc > (count($called_api) - 1)) AND (count($called_api) > 0)) {
if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
$argid = count($called_api);
list($user, $null) = explode(".", $a->argv[$argid]);
if (is_numeric($user)) {
@ -597,7 +600,7 @@ $called_api = null;
$network_name = network_to_name($r[0]['network'], $r[0]['url']);
// If no nick where given, extract it from the address
if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick'])) {
if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
$r[0]['nick'] = api_get_nick($r[0]["url"]);
}
@ -713,7 +716,7 @@ $called_api = null;
$starred = 0;
// Add a nick if it isn't present there
if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
$uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
}
@ -746,7 +749,7 @@ $called_api = null;
'contributors_enabled' => false,
'is_translator' => false,
'is_translation_enabled' => false,
'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
'follow_request_sent' => false,
'statusnet_blocking' => false,
'notifications' => false,
@ -774,10 +777,10 @@ $called_api = null;
$status_user = api_get_user($a, $item["author-link"]);
$status_user["protected"] = (($item["allow_cid"] != "") OR
($item["allow_gid"] != "") OR
($item["deny_cid"] != "") OR
($item["deny_gid"] != "") OR
$status_user["protected"] = (($item["allow_cid"] != "") ||
($item["allow_gid"] != "") ||
($item["deny_cid"] != "") ||
($item["deny_gid"] != "") ||
$item["private"]);
if ($item['thr-parent'] == $item['uri']) {
@ -1302,9 +1305,9 @@ $called_api = null;
$status_info["entities"] = $converted["entities"];
}
if (($lastwall['item_network'] != "") AND ($status["source"] == 'web')) {
if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
$status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
} elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
} elseif (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
$status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
}
@ -1390,11 +1393,11 @@ $called_api = null;
$user_info["status"]["entities"] = $converted["entities"];
}
if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web')) {
if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
$user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
}
if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
$user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
}
@ -2175,7 +2178,7 @@ $called_api = null;
`contact`.`id` AS `cid`
FROM `item`, `contact`
WHERE `item`.`uid` = %d
AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
AND `item`.`starred` = 1
AND `contact`.`id` = `item`.`contact-id`
AND (NOT `contact`.`blocked` OR `contact`.`pending`)
@ -2260,13 +2263,13 @@ $called_api = null;
$statustitle = trim($item['title']);
if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false)) {
if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
$statustext = trim($statusbody);
} else {
$statustext = trim($statustitle."\n\n".$statusbody);
}
if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000)) {
if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
$statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
}
@ -2286,6 +2289,11 @@ $called_api = null;
$statushtml = "<h4>" . bbcode($item['title']) . "</h4>\n" . $statushtml;
}
// feeds without body should contain the link
if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
$statushtml .= bbcode($item['plink']);
}
$entities = api_get_entitities($statustext, $body);
return array(
@ -2394,8 +2402,8 @@ $called_api = null;
$offset = 0;
//foreach ($urls[1] AS $id=>$url) {
foreach ($ordered_urls AS $url) {
if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
!strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://") &&
!strpos($url["title"], "http://") && !strpos($url["title"], "https://"))
$display_url = $url["title"];
else {
$display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
@ -2447,7 +2455,7 @@ $called_api = null;
$scale = scale_image($image[0], $image[1], 150);
$sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
if (($image[0] > 150) OR ($image[1] > 150)) {
if (($image[0] > 150) || ($image[1] > 150)) {
$scale = scale_image($image[0], $image[1], 340);
$sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
}
@ -2455,7 +2463,7 @@ $called_api = null;
$scale = scale_image($image[0], $image[1], 600);
$sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
if (($image[0] > 600) OR ($image[1] > 600)) {
if (($image[0] > 600) || ($image[1] > 600)) {
$scale = scale_image($image[0], $image[1], 1024);
$sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
}
@ -2660,7 +2668,7 @@ $called_api = null;
list($status_user, $owner_user) = api_item_get_user($a, $item);
// Look if the posts are matching if they should be filtered by user id
if ($filter_user AND ($status_user["id"] != $user_info["id"])) {
if ($filter_user && ($status_user["id"] != $user_info["id"])) {
continue;
}
@ -2704,9 +2712,9 @@ $called_api = null;
$status["entities"] = $converted["entities"];
}
if (($item['item_network'] != "") AND ($status["source"] == 'web')) {
if (($item['item_network'] != "") && ($status["source"] == 'web')) {
$status["source"] = network_to_name($item['item_network'], $user_info['url']);
} elseif (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
} elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
$status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
}
@ -2715,7 +2723,7 @@ $called_api = null;
// It doesn't work reliable with the link if its a feed
//$IsRetweet = ($item['owner-link'] != $item['author-link']);
//if ($IsRetweet)
// $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
// $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
if ($item["id"] == $item["parent"]) {
@ -3014,7 +3022,7 @@ $called_api = null;
if (api_user() === false) throw new ForbiddenException();
if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
if (!x($_POST, "text") || (!x($_POST,"screen_name") && !x($_POST,"user_id"))) return;
$sender = api_get_user($a);
@ -3027,8 +3035,9 @@ $called_api = null;
api_best_nickname($r);
$recipient = api_get_user($a, $r[0]['nurl']);
} else
} else {
$recipient = api_get_user($a, $_POST['user_id']);
}
$replyto = '';
$sub = '';
@ -3740,8 +3749,7 @@ $called_api = null;
proc_run(PRIORITY_LOW, "include/directory.php", $url);
}
require_once 'include/profile_update.php';
profile_change();
proc_run(PRIORITY_LOW, 'include/profile_update.php', api_user());
// output for client
if ($data) {
@ -3974,7 +3982,7 @@ $called_api = null;
}
function prepare_photo_data($type, $scale, $photo_id) {
$scale_sql = ($scale === false ? "" : sprintf("and scale=%d", intval($scale)));
$scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
$data_sql = ($scale === false ? "" : "data, ");
// added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
@ -4326,7 +4334,7 @@ $called_api = null;
$in_reply_to['user_id_str'] = NULL;
$in_reply_to['screen_name'] = NULL;
if (($item['thr-parent'] != $item['uri']) AND (intval($item['parent']) != intval($item['id']))) {
if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
$r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
intval($item['uid']),
dbesc($item['thr-parent']));
@ -4407,7 +4415,7 @@ $called_api = null;
if (isset($data["text"]))
$body = $data["text"];
if (($body == "") AND (isset($data["title"])))
if (($body == "") && (isset($data["title"])))
$body = $data["title"];
if (isset($data["url"]))

View file

@ -29,7 +29,7 @@ if (isset($_COOKIE["Friendica"])) {
new_cookie($authcookiedays*24*60*60, $r[0]);
// Do the authentification if not done by now
if (!isset($_SESSION) OR !isset($_SESSION['authenticated'])) {
if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
authenticate_success($r[0]);
if (get_config('system','paranoia'))

View file

@ -89,7 +89,7 @@ class exAuth {
// Open the logfile if the logfile name is defined
if ($this->sLogFile != '')
$this->rLogFile = fopen($this->sLogFile, "a") or die("Error opening log file: ". $this->sLogFile);
$this->rLogFile = fopen($this->sLogFile, "a") || die("Error opening log file: ". $this->sLogFile);
$this->writeLog("[exAuth] start");

View file

@ -49,14 +49,14 @@ function bb_attachment($Text, $simplehtml = false, $tryoembed = true) {
$data["title"] = str_replace(array("http://", "https://"), "", $data["title"]);
}
if (((strpos($data["text"], "[img=") !== false) OR (strpos($data["text"], "[img]") !== false)) AND ($data["image"] != "")) {
if (((strpos($data["text"], "[img=") !== false) || (strpos($data["text"], "[img]") !== false)) && ($data["image"] != "")) {
$data["preview"] = $data["image"];
$data["image"] = "";
}
if ($simplehtml == 7) {
$text = style_url_for_mastodon($data["url"]);
} elseif (($simplehtml != 4) AND ($simplehtml != 0)) {
} elseif (($simplehtml != 4) && ($simplehtml != 0)) {
$text = sprintf('<a href="%s" target="_blank">%s</a><br>', $data["url"], $data["title"]);
} else {
$text = sprintf('<span class="type-%s">', $data["type"]);
@ -71,13 +71,13 @@ function bb_attachment($Text, $simplehtml = false, $tryoembed = true) {
if (strstr(strtolower($oembed), "<iframe ")) {
$text = $oembed;
} else {
if (($data["image"] != "") AND !strstr(strtolower($oembed), "<img ")) {
if (($data["image"] != "") && !strstr(strtolower($oembed), "<img ")) {
$text .= sprintf('<a href="%s" target="_blank"><img src="%s" alt="" title="%s" class="attachment-image" /></a><br />', $data["url"], proxy_url($data["image"]), $data["title"]);
} elseif (($data["preview"] != "") AND !strstr(strtolower($oembed), "<img ")) {
} elseif (($data["preview"] != "") && !strstr(strtolower($oembed), "<img ")) {
$text .= sprintf('<a href="%s" target="_blank"><img src="%s" alt="" title="%s" class="attachment-preview" /></a><br />', $data["url"], proxy_url($data["preview"]), $data["title"]);
}
if (($data["type"] == "photo") AND ($data["url"] != "") AND ($data["image"] != "")) {
if (($data["type"] == "photo") && ($data["url"] != "") && ($data["image"] != "")) {
$text .= sprintf('<a href="%s" target="_blank"><img src="%s" alt="" title="%s" class="attachment-image" /></a>', $data["url"], proxy_url($data["image"]), $data["title"]);
} else {
$text .= $oembed;
@ -103,25 +103,25 @@ function bb_remove_share_information($Text, $plaintext = false, $nolink = false)
$title = htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false);
$text = htmlentities($data["text"], ENT_QUOTES, 'UTF-8', false);
if ($plaintext OR (($title != "") AND strstr($text, $title))) {
if ($plaintext || (($title != "") && strstr($text, $title))) {
$data["title"] = $data["url"];
} elseif (($text != "") AND strstr($title, $text)) {
} elseif (($text != "") && strstr($title, $text)) {
$data["text"] = $data["title"];
$data["title"] = $data["url"];
}
if (($data["text"] == "") AND ($data["title"] != "") AND ($data["url"] == "")) {
if (($data["text"] == "") && ($data["title"] != "") && ($data["url"] == "")) {
return $data["title"] . $data["after"];
}
// If the link already is included in the post, don't add it again
if (($data["url"] != "") AND strpos($data["text"], $data["url"])) {
if (($data["url"] != "") && strpos($data["text"], $data["url"])) {
return $data["text"] . $data["after"];
}
$text = $data["text"];
if (($data["url"] != "") AND ($data["title"] != "")) {
if (($data["url"] != "") && ($data["title"] != "")) {
$text .= "\n[url=" . $data["url"] . "]" . $data["title"] . "[/url]";
} elseif (($data["url"] != "")) {
$text .= "\n" . $data["url"];
@ -147,7 +147,7 @@ function cleancss($input) {
for ($i = 0; $i < strlen($input); $i++) {
$char = substr($input, $i, 1);
if (($char >= "a") and ($char <= "z")) {
if (($char >= "a") && ($char <= "z")) {
$cleaned .= $char;
}
@ -167,7 +167,7 @@ function cleancss($input) {
function bb_style_url($match) {
$url = $match[1];
if (isset($match[2]) AND ($match[1] != $match[2])) {
if (isset($match[2]) && ($match[1] != $match[2])) {
return $match[0];
}
@ -485,20 +485,20 @@ function bb_ShareAttributes($share, $simplehtml) {
$data = get_contact_details_by_url($profile);
if (isset($data["name"]) AND ($data["name"] != "") AND isset($data["addr"]) AND ($data["addr"] != ""))
if (isset($data["name"]) && ($data["name"] != "") && isset($data["addr"]) && ($data["addr"] != ""))
$userid_compact = $data["name"]." (".$data["addr"].")";
else
$userid_compact = GetProfileUsername($profile,$author, true);
if (isset($data["addr"]) AND ($data["addr"] != ""))
if (isset($data["addr"]) && ($data["addr"] != ""))
$userid = $data["addr"];
else
$userid = GetProfileUsername($profile,$author, false);
if (isset($data["name"]) AND ($data["name"] != ""))
if (isset($data["name"]) && ($data["name"] != ""))
$author = $data["name"];
if (isset($data["micro"]) AND ($data["micro"] != ""))
if (isset($data["micro"]) && ($data["micro"] != ""))
$avatar = $data["micro"];
$preshare = trim($share[1]);
@ -744,7 +744,7 @@ function bb_RemovePictureLinks($match) {
}
function bb_expand_links($match) {
if (($match[3] == "") OR ($match[2] == $match[3]) OR stristr($match[2], $match[3])) {
if (($match[3] == "") || ($match[2] == $match[3]) || stristr($match[2], $match[3])) {
return ($match[1] . "[url]" . $match[2] . "[/url]");
} else {
return ($match[1] . $match[3] . " [url]" . $match[2] . "[/url]");
@ -930,7 +930,7 @@ function bbcode($Text, $preserve_nl = false, $tryoembed = true, $simplehtml = fa
$MAILSearchString = $URLSearchString;
// Remove all hashtag addresses
if ((!$tryoembed OR $simplehtml) AND !in_array($simplehtml, array(3, 7))) {
if ((!$tryoembed || $simplehtml) && !in_array($simplehtml, array(3, 7))) {
$Text = preg_replace("/([#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
} elseif ($simplehtml == 3) {
$Text = preg_replace("/([@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
@ -1126,7 +1126,7 @@ function bbcode($Text, $preserve_nl = false, $tryoembed = true, $simplehtml = fa
// Check for [spoiler] text
// handle nested quotes
$endlessloop = 0;
while ((strpos($Text, "[/spoiler]") !== false) and (strpos($Text, "[spoiler]") !== false) and (++$endlessloop < 20)) {
while ((strpos($Text, "[/spoiler]") !== false) && (strpos($Text, "[spoiler]") !== false) && (++$endlessloop < 20)) {
$Text = preg_replace("/\[spoiler\](.*?)\[\/spoiler\]/ism", "$SpoilerLayout", $Text);
}
@ -1136,7 +1136,7 @@ function bbcode($Text, $preserve_nl = false, $tryoembed = true, $simplehtml = fa
// handle nested quotes
$endlessloop = 0;
while ((strpos($Text, "[/spoiler]")!== false) and (strpos($Text, "[spoiler=") !== false) and (++$endlessloop < 20)) {
while ((strpos($Text, "[/spoiler]")!== false) && (strpos($Text, "[spoiler=") !== false) && (++$endlessloop < 20)) {
$Text = preg_replace("/\[spoiler=[\"\']*(.*?)[\"\']*\](.*?)\[\/spoiler\]/ism",
"<br /><strong class=".'"spoiler"'.">" . $t_wrote . "</strong><blockquote class=".'"spoiler"'.">$2</blockquote>",
$Text);
@ -1148,7 +1148,7 @@ function bbcode($Text, $preserve_nl = false, $tryoembed = true, $simplehtml = fa
// Check for [quote] text
// handle nested quotes
$endlessloop = 0;
while ((strpos($Text, "[/quote]") !== false) and (strpos($Text, "[quote]") !== false) and (++$endlessloop < 20)) {
while ((strpos($Text, "[/quote]") !== false) && (strpos($Text, "[quote]") !== false) && (++$endlessloop < 20)) {
$Text = preg_replace("/\[quote\](.*?)\[\/quote\]/ism", "$QuoteLayout", $Text);
}
@ -1158,7 +1158,7 @@ function bbcode($Text, $preserve_nl = false, $tryoembed = true, $simplehtml = fa
// handle nested quotes
$endlessloop = 0;
while ((strpos($Text, "[/quote]")!== false) and (strpos($Text, "[quote=") !== false) and (++$endlessloop < 20)) {
while ((strpos($Text, "[/quote]")!== false) && (strpos($Text, "[quote=") !== false) && (++$endlessloop < 20)) {
$Text = preg_replace("/\[quote=[\"\']*(.*?)[\"\']*\](.*?)\[\/quote\]/ism",
"<br /><strong class=".'"author"'.">" . $t_wrote . "</strong><blockquote>$2</blockquote>",
$Text);
@ -1319,7 +1319,7 @@ function bbcode($Text, $preserve_nl = false, $tryoembed = true, $simplehtml = fa
// Clean up the HTML by loading and saving the HTML with the DOM.
// Bad structured html can break a whole page.
// For performance reasons do it only with ativated item cache or at export.
if (!$tryoembed OR (get_itemcachepath() != "")) {
if (!$tryoembed || (get_itemcachepath() != "")) {
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;

View file

@ -172,35 +172,35 @@ class Cache {
set_config("system", "cache_cleared_day", time());
}
if (($max_level <= CACHE_HOUR) AND (get_config("system", "cache_cleared_hour")) < time() - self::duration(CACHE_HOUR)) {
if (($max_level <= CACHE_HOUR) && (get_config("system", "cache_cleared_hour")) < time() - self::duration(CACHE_HOUR)) {
q("DELETE FROM `cache` WHERE `updated` < '%s' AND `expire_mode` = %d",
dbesc(datetime_convert('UTC','UTC',"now - 1 hours")), intval(CACHE_HOUR));
set_config("system", "cache_cleared_hour", time());
}
if (($max_level <= CACHE_HALF_HOUR) AND (get_config("system", "cache_cleared_half_hour")) < time() - self::duration(CACHE_HALF_HOUR)) {
if (($max_level <= CACHE_HALF_HOUR) && (get_config("system", "cache_cleared_half_hour")) < time() - self::duration(CACHE_HALF_HOUR)) {
q("DELETE FROM `cache` WHERE `updated` < '%s' AND `expire_mode` = %d",
dbesc(datetime_convert('UTC','UTC',"now - 30 minutes")), intval(CACHE_HALF_HOUR));
set_config("system", "cache_cleared_half_hour", time());
}
if (($max_level <= CACHE_QUARTER_HOUR) AND (get_config("system", "cache_cleared_quarter_hour")) < time() - self::duration(CACHE_QUARTER_HOUR)) {
if (($max_level <= CACHE_QUARTER_HOUR) && (get_config("system", "cache_cleared_quarter_hour")) < time() - self::duration(CACHE_QUARTER_HOUR)) {
q("DELETE FROM `cache` WHERE `updated` < '%s' AND `expire_mode` = %d",
dbesc(datetime_convert('UTC','UTC',"now - 15 minutes")), intval(CACHE_QUARTER_HOUR));
set_config("system", "cache_cleared_quarter_hour", time());
}
if (($max_level <= CACHE_FIVE_MINUTES) AND (get_config("system", "cache_cleared_five_minute")) < time() - self::duration(CACHE_FIVE_MINUTES)) {
if (($max_level <= CACHE_FIVE_MINUTES) && (get_config("system", "cache_cleared_five_minute")) < time() - self::duration(CACHE_FIVE_MINUTES)) {
q("DELETE FROM `cache` WHERE `updated` < '%s' AND `expire_mode` = %d",
dbesc(datetime_convert('UTC','UTC',"now - 5 minutes")), intval(CACHE_FIVE_MINUTES));
set_config("system", "cache_cleared_five_minute", time());
}
if (($max_level <= CACHE_MINUTE) AND (get_config("system", "cache_cleared_minute")) < time() - self::duration(CACHE_MINUTE)) {
if (($max_level <= CACHE_MINUTE) && (get_config("system", "cache_cleared_minute")) < time() - self::duration(CACHE_MINUTE)) {
q("DELETE FROM `cache` WHERE `updated` < '%s' AND `expire_mode` = %d",
dbesc(datetime_convert('UTC','UTC',"now - 1 minutes")), intval(CACHE_MINUTE));

View file

@ -100,7 +100,7 @@ function network_to_name($s, $profile = "") {
$networkname = str_replace($search, $replace, $s);
if ((in_array($s, array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) AND ($profile != "")) {
if ((in_array($s, array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) && ($profile != "")) {
$r = q("SELECT `gserver`.`platform` FROM `gcontact`
INNER JOIN `gserver` ON `gserver`.`nurl` = `gcontact`.`server_url`
WHERE `gcontact`.`nurl` = '%s' AND `platform` != ''",

View file

@ -51,7 +51,7 @@ function unavailable_networks() {
$networks[] = NETWORK_APPNET;
}
if (!plugin_enabled("fbpost") AND !plugin_enabled("facebook")) {
if (!plugin_enabled("fbpost") && !plugin_enabled("facebook")) {
$networks[] = NETWORK_FACEBOOK;
}

View file

@ -712,7 +712,7 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
$profile_link = zrl($profile_link);
}
if (!x($item, 'author-thumb') OR ($item['author-thumb'] == "")) {
if (!x($item, 'author-thumb') || ($item['author-thumb'] == "")) {
$author_contact = get_contact_details_by_url($item['author-link'], $profile_owner);
if ($author_contact["thumb"]) {
$item['author-thumb'] = $author_contact["thumb"];
@ -721,7 +721,7 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
}
}
if (!isset($item['owner-thumb']) OR ($item['owner-thumb'] == "")) {
if (!isset($item['owner-thumb']) || ($item['owner-thumb'] == "")) {
$owner_contact = get_contact_details_by_url($item['owner-link'], $profile_owner);
if ($owner_contact["thumb"]) {
$item['owner-thumb'] = $owner_contact["thumb"];
@ -1013,7 +1013,7 @@ function item_photo_menu($item) {
$menu[t("Poke")] = $poke_link;
}
if ((($cid == 0) OR ($rel == CONTACT_IS_FOLLOWER)) AND
if ((($cid == 0) || ($rel == CONTACT_IS_FOLLOWER)) &&
in_array($item['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
$menu[t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']);
}

View file

@ -122,6 +122,8 @@ function cron_poll_contacts($argc, $argv) {
$force = true;
}
$min_poll_interval = Config::get('system', 'min_poll_interval', 1);
$sql_extra = (($manual_id) ? " AND `id` = $manual_id " : "");
reload_plugins();
@ -184,7 +186,7 @@ function cron_poll_contacts($argc, $argv) {
$contact['priority'] = 2;
}
if ($contact['subhub'] AND in_array($contact['network'], array(NETWORK_DFRN, NETWORK_ZOT, NETWORK_OSTATUS))) {
if ($contact['subhub'] && 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)
@ -195,7 +197,7 @@ function cron_poll_contacts($argc, $argv) {
$contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
}
if ($contact['priority'] AND !$force) {
if (($contact['priority'] >= 0) && !$force) {
$update = false;
$t = $contact['last-update'];
@ -225,11 +227,16 @@ function cron_poll_contacts($argc, $argv) {
}
break;
case 1:
default:
if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + 1 hour")) {
$update = true;
}
break;
case 0:
default:
if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + ".$min_poll_interval." minute")) {
$update = true;
}
break;
}
if (!$update) {
continue;
@ -238,11 +245,12 @@ function cron_poll_contacts($argc, $argv) {
logger("Polling " . $contact["network"] . " " . $contact["id"] . " " . $contact["nick"] . " " . $contact["name"]);
if (($contact['network'] == NETWORK_FEED) AND ($contact['priority'] <= 3)) {
proc_run(PRIORITY_MEDIUM, 'include/onepoll.php', intval($contact['id']));
if (($contact['network'] == NETWORK_FEED) && ($contact['priority'] <= 3)) {
$priority = PRIORITY_MEDIUM;
} else {
proc_run(PRIORITY_LOW, 'include/onepoll.php', intval($contact['id']));
$priority = PRIORITY_LOW;
}
proc_run(array('priority' => $priority, 'dont_fork' => true), 'include/onepoll.php', intval($contact['id']));
}
}
}

View file

@ -7,7 +7,7 @@ function cronhooks_run(&$argv, &$argc) {
require_once 'include/datetime.php';
if (($argc == 2) AND is_array($a->hooks) AND array_key_exists("cron", $a->hooks)) {
if (($argc == 2) && is_array($a->hooks) && array_key_exists("cron", $a->hooks)) {
foreach ($a->hooks["cron"] as $hook) {
if ($hook[1] == $argv[1]) {
logger("Calling cron hook '" . $hook[1] . "'", LOGGER_DEBUG);
@ -38,7 +38,7 @@ function cronhooks_run(&$argv, &$argc) {
$d = datetime_convert();
if (is_array($a->hooks) AND array_key_exists("cron", $a->hooks)) {
if (is_array($a->hooks) && array_key_exists("cron", $a->hooks)) {
foreach ($a->hooks["cron"] as $hook) {
logger("Calling cronhooks for '" . $hook[1] . "'", LOGGER_DEBUG);
proc_run(PRIORITY_MEDIUM, "include/cronhooks.php", $hook[1]);

View file

@ -117,7 +117,7 @@ class dba {
/**
* @brief Returns the MySQL server version string
*
*
* This function discriminate between the deprecated mysql API and the current
* object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
*
@ -183,17 +183,17 @@ class dba {
foreach ($r AS $row) {
if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
$log = (in_array($row['key'], $watchlist) AND
$log = (in_array($row['key'], $watchlist) &&
($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
} else {
$log = false;
}
if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) AND ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
$log = true;
}
if (in_array($row['key'], $blacklist) OR ($row['key'] == "")) {
if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
$log = false;
}
@ -363,7 +363,7 @@ class dba {
// PDO doesn't return "true" on successful operations - like mysqli does
// Emulate this behaviour by checking if the query returned data and had columns
// This should be reliable enough
if (($this->driver == 'pdo') AND (count($r) == 0) AND ($columns == 0)) {
if (($this->driver == 'pdo') && (count($r) == 0) && ($columns == 0)) {
return true;
}
@ -459,6 +459,27 @@ class dba {
return $sql;
}
/**
* @brief beautifies the query - useful for "SHOW PROCESSLIST"
*
* This is safe when we bind the parameters later.
* The parameter values aren't part of the SQL.
*
* @param string $sql An SQL string without the values
* @return string The input SQL string modified if necessary.
*/
public function clean_query($sql) {
$search = array("\t", "\n", "\r", " ");
$replace = array(' ', ' ', ' ', ' ');
do {
$oldsql = $sql;
$sql = str_replace($search, $replace, $sql);
} while ($oldsql != $sql);
return $sql;
}
/**
* @brief Replaces the ? placeholders with the parameters in the $args array
*
@ -469,7 +490,7 @@ class dba {
static private function replace_parameters($sql, $args) {
$offset = 0;
foreach ($args AS $param => $value) {
if (is_int($args[$param]) OR is_float($args[$param])) {
if (is_int($args[$param]) || is_float($args[$param])) {
$replace = intval($args[$param]);
} else {
$replace = "'".self::$dbo->escape($args[$param])."'";
@ -499,7 +520,7 @@ class dba {
unset($args[0]);
// When the second function parameter is an array then use this as the parameter array
if ((count($args) > 0) AND (is_array($args[1]))) {
if ((count($args) > 0) && (is_array($args[1]))) {
$params = $args[1];
} else {
$params = $args;
@ -512,7 +533,7 @@ class dba {
$args[++$i] = $param;
}
if (!self::$dbo OR !self::$dbo->connected) {
if (!self::$dbo || !self::$dbo->connected) {
return false;
}
@ -521,6 +542,7 @@ class dba {
logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
}
$sql = self::$dbo->clean_query($sql);
$sql = self::$dbo->any_value_fallback($sql);
if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
@ -708,6 +730,9 @@ class dba {
* @return int Number of rows
*/
static public function num_rows($stmt) {
if (!is_object($stmt)) {
return 0;
}
switch (self::$dbo->driver) {
case 'pdo':
return $stmt->rowCount();
@ -781,6 +806,41 @@ class dba {
return self::e($sql, $param);
}
/**
* @brief Locks a table for exclusive write access
*
* This function can be extended in the future to accept a table array as well.
*
* @param string $table Table name
*
* @return boolean was the lock successful?
*/
static public function lock($table) {
// See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
self::e("SET autocommit=0");
$success = self::e("LOCK TABLES `".self::$dbo->escape($table)."` WRITE");
if (!$success) {
self::e("SET autocommit=1");
} else {
self::$in_transaction = true;
}
return $success;
}
/**
* @brief Unlocks all locked tables
*
* @return boolean was the unlock successful?
*/
static public function unlock() {
// See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
self::e("COMMIT");
$success = self::e("UNLOCK TABLES");
self::e("SET autocommit=1");
self::$in_transaction = false;
return $success;
}
/**
* @brief Starts a transaction
*
@ -888,7 +948,7 @@ class dba {
// When the search field is the relation field, we don't need to fetch the rows
// This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
if ((count($param) == 1) AND ($field == array_keys($param)[0])) {
if ((count($param) == 1) && ($field == array_keys($param)[0])) {
foreach ($rel_def AS $rel_table => $rel_fields) {
foreach ($rel_fields AS $rel_field) {
$retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
@ -1050,7 +1110,7 @@ class dba {
}
}
if (!$do_update OR (count($fields) == 0)) {
if (!$do_update || (count($fields) == 0)) {
return true;
}
@ -1130,7 +1190,7 @@ class dba {
$result = self::p($sql, $condition);
if (is_bool($result) OR !$single_row) {
if (is_bool($result) || !$single_row) {
return $result;
} else {
$row = self::fetch($result);
@ -1200,6 +1260,7 @@ function q($sql) {
unset($args[0]);
if ($db && $db->connected) {
$sql = $db->clean_query($sql);
$sql = $db->any_value_fallback($sql);
$stmt = @vsprintf($sql,$args); // Disabled warnings
//logger("dba: q: $stmt", LOGGER_ALL);
@ -1237,6 +1298,7 @@ function qu($sql) {
unset($args[0]);
if ($db && $db->connected) {
$sql = $db->clean_query($sql);
$sql = $db->any_value_fallback($sql);
$stmt = @vsprintf($sql,$args); // Disabled warnings
if ($stmt === false)

View file

@ -190,14 +190,14 @@ class dba {
* regardless of any logging that may or may nor be in effect.
* These usually indicate SQL syntax errors that need to be resolved.
*/
if (isset($result) AND ($result === false)) {
if (isset($result) && ($result === false)) {
logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
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) && (($result === true) || ($result === false))) {
return $result;
}

View file

@ -17,9 +17,14 @@ function dbclean_run(&$argv, &$argc) {
$stage = 0;
}
// Get the expire days for step 8 and 9
$days = Config::get('system', 'dbclean-expire-days', 0);
if ($stage == 0) {
for ($i = 1; $i <= 7; $i++) {
if (!Config::get('system', 'finished-dbclean-'.$i)) {
for ($i = 1; $i <= 9; $i++) {
// Execute the background script for a step when it isn't finished.
// Execute step 8 and 9 only when $days is defined.
if (!Config::get('system', 'finished-dbclean-'.$i, false) && (($i < 8) || ($days > 0))) {
proc_run(PRIORITY_LOW, 'include/dbclean.php', $i);
}
}
@ -30,6 +35,19 @@ function dbclean_run(&$argv, &$argc) {
/**
* @brief Remove orphaned database entries
* @param integer $stage What should be deleted?
*
* Values for $stage:
* ------------------
* 1: Old global item entries from item table without user copy.
* 2: Items without parents.
* 3: Orphaned data from thread table.
* 4: Orphaned data from notify table.
* 5: Orphaned data from notify-threads table.
* 6: Orphaned data from sign table.
* 7: Orphaned data from term table.
* 8: Expired threads.
* 9: Old global item entries from expired threads
*/
function remove_orphans($stage = 0) {
global $db;
@ -39,141 +57,246 @@ function remove_orphans($stage = 0) {
// We split the deletion in many small tasks
$limit = 1000;
// Get the expire days for step 8 and 9
$days = Config::get('system', 'dbclean-expire-days', 0);
if ($stage == 1) {
logger("Deleting old global item entries from item table without user copy");
$r = dba::p("SELECT `id` FROM `item` WHERE `uid` = 0
AND NOT EXISTS (SELECT `guid` FROM `item` AS `i` WHERE `item`.`guid` = `i`.`guid` AND `i`.`uid` != 0)
AND `received` < UTC_TIMESTAMP() - INTERVAL 90 DAY LIMIT ".intval($limit));
$last_id = Config::get('system', 'dbclean-last-id-1', 0);
logger("Deleting old global item entries from item table without user copy. Last ID: ".$last_id);
$r = dba::p("SELECT `id` FROM `item` WHERE `uid` = 0 AND
NOT EXISTS (SELECT `guid` FROM `item` AS `i` WHERE `item`.`guid` = `i`.`guid` AND `i`.`uid` != 0) AND
`received` < UTC_TIMESTAMP() - INTERVAL 90 DAY AND `id` >= ?
ORDER BY `id` LIMIT ".intval($limit), $last_id);
$count = dba::num_rows($r);
if ($count > 0) {
logger("found global item orphans: ".$count);
while ($orphan = dba::fetch($r)) {
$last_id = $orphan["id"];
dba::delete('item', array('id' => $orphan["id"]));
}
} else {
logger("No global item orphans found");
}
dba::close($r);
logger("Done deleting ".$count." old global item entries from item table without user copy");
logger("Done deleting ".$count." old global item entries from item table without user copy. Last ID: ".$last_id);
// We will eventually set this value when we found a good way to delete these items in another way.
// if ($count < $limit) {
// Config::set('system', 'finished-dbclean-1', true);
// }
Config::set('system', 'dbclean-last-id-1', $last_id);
} elseif ($stage == 2) {
logger("Deleting items without parents");
$r = dba::p("SELECT `id` FROM `item` WHERE NOT EXISTS (SELECT `id` FROM `item` AS `i` WHERE `item`.`parent` = `i`.`id`) LIMIT ".intval($limit));
$last_id = Config::get('system', 'dbclean-last-id-2', 0);
logger("Deleting items without parents. Last ID: ".$last_id);
$r = dba::p("SELECT `id` FROM `item`
WHERE NOT EXISTS (SELECT `id` FROM `item` AS `i` WHERE `item`.`parent` = `i`.`id`)
AND `id` >= ? ORDER BY `id` LIMIT ".intval($limit), $last_id);
$count = dba::num_rows($r);
if ($count > 0) {
logger("found item orphans without parents: ".$count);
while ($orphan = dba::fetch($r)) {
$last_id = $orphan["id"];
dba::delete('item', array('id' => $orphan["id"]));
}
} else {
logger("No item orphans without parents found");
}
dba::close($r);
logger("Done deleting ".$count." items without parents");
logger("Done deleting ".$count." items without parents. Last ID: ".$last_id);
Config::set('system', 'dbclean-last-id-2', $last_id);
if ($count < $limit) {
Config::set('system', 'finished-dbclean-2', true);
}
} elseif ($stage == 3) {
logger("Deleting orphaned data from thread table");
$r = dba::p("SELECT `iid` FROM `thread` WHERE NOT EXISTS (SELECT `id` FROM `item` WHERE `item`.`parent` = `thread`.`iid`) LIMIT ".intval($limit));
$last_id = Config::get('system', 'dbclean-last-id-3', 0);
logger("Deleting orphaned data from thread table. Last ID: ".$last_id);
$r = dba::p("SELECT `iid` FROM `thread`
WHERE NOT EXISTS (SELECT `id` FROM `item` WHERE `item`.`parent` = `thread`.`iid`) AND `iid` >= ?
ORDER BY `iid` LIMIT ".intval($limit), $last_id);
$count = dba::num_rows($r);
if ($count > 0) {
logger("found thread orphans: ".$count);
while ($orphan = dba::fetch($r)) {
$last_id = $orphan["iid"];
dba::delete('thread', array('iid' => $orphan["iid"]));
}
} else {
logger("No thread orphans found");
}
dba::close($r);
logger("Done deleting ".$count." orphaned data from thread table");
logger("Done deleting ".$count." orphaned data from thread table. Last ID: ".$last_id);
Config::set('system', 'dbclean-last-id-3', $last_id);
if ($count < $limit) {
Config::set('system', 'finished-dbclean-3', true);
}
} elseif ($stage == 4) {
logger("Deleting orphaned data from notify table");
$r = dba::p("SELECT `iid` FROM `notify` WHERE NOT EXISTS (SELECT `id` FROM `item` WHERE `item`.`id` = `notify`.`iid`) LIMIT ".intval($limit));
$last_id = Config::get('system', 'dbclean-last-id-4', 0);
logger("Deleting orphaned data from notify table. Last ID: ".$last_id);
$r = dba::p("SELECT `iid`, `id` FROM `notify`
WHERE NOT EXISTS (SELECT `id` FROM `item` WHERE `item`.`id` = `notify`.`iid`) AND `id` >= ?
ORDER BY `id` LIMIT ".intval($limit), $last_id);
$count = dba::num_rows($r);
if ($count > 0) {
logger("found notify orphans: ".$count);
while ($orphan = dba::fetch($r)) {
$last_id = $orphan["id"];
dba::delete('notify', array('iid' => $orphan["iid"]));
}
} else {
logger("No notify orphans found");
}
dba::close($r);
logger("Done deleting ".$count." orphaned data from notify table");
logger("Done deleting ".$count." orphaned data from notify table. Last ID: ".$last_id);
Config::set('system', 'dbclean-last-id-4', $last_id);
if ($count < $limit) {
Config::set('system', 'finished-dbclean-4', true);
}
} elseif ($stage == 5) {
logger("Deleting orphaned data from notify-threads table");
$r = dba::p("SELECT `id` FROM `notify-threads` WHERE NOT EXISTS (SELECT `id` FROM `item` WHERE `item`.`parent` = `notify-threads`.`master-parent-item`) LIMIT ".intval($limit));
$last_id = Config::get('system', 'dbclean-last-id-5', 0);
logger("Deleting orphaned data from notify-threads table. Last ID: ".$last_id);
$r = dba::p("SELECT `id` FROM `notify-threads`
WHERE NOT EXISTS (SELECT `id` FROM `item` WHERE `item`.`parent` = `notify-threads`.`master-parent-item`) AND `id` >= ?
ORDER BY `id` LIMIT ".intval($limit), $last_id);
$count = dba::num_rows($r);
if ($count > 0) {
logger("found notify-threads orphans: ".$count);
while ($orphan = dba::fetch($r)) {
$last_id = $orphan["id"];
dba::delete('notify-threads', array('id' => $orphan["id"]));
}
} else {
logger("No notify-threads orphans found");
}
dba::close($r);
logger("Done deleting ".$count." orphaned data from notify-threads table");
logger("Done deleting ".$count." orphaned data from notify-threads table. Last ID: ".$last_id);
Config::set('system', 'dbclean-last-id-5', $last_id);
if ($count < $limit) {
Config::set('system', 'finished-dbclean-5', true);
}
} elseif ($stage == 6) {
logger("Deleting orphaned data from sign table");
$r = dba::p("SELECT `iid` FROM `sign` WHERE NOT EXISTS (SELECT `id` FROM `item` WHERE `item`.`id` = `sign`.`iid`) LIMIT ".intval($limit));
$last_id = Config::get('system', 'dbclean-last-id-6', 0);
logger("Deleting orphaned data from sign table. Last ID: ".$last_id);
$r = dba::p("SELECT `iid`, `id` FROM `sign`
WHERE NOT EXISTS (SELECT `id` FROM `item` WHERE `item`.`id` = `sign`.`iid`) AND `id` >= ?
ORDER BY `id` LIMIT ".intval($limit), $last_id);
$count = dba::num_rows($r);
if ($count > 0) {
logger("found sign orphans: ".$count);
while ($orphan = dba::fetch($r)) {
$last_id = $orphan["id"];
dba::delete('sign', array('iid' => $orphan["iid"]));
}
} else {
logger("No sign orphans found");
}
dba::close($r);
logger("Done deleting ".$count." orphaned data from sign table");
logger("Done deleting ".$count." orphaned data from sign table. Last ID: ".$last_id);
Config::set('system', 'dbclean-last-id-6', $last_id);
if ($count < $limit) {
Config::set('system', 'finished-dbclean-6', true);
}
} elseif ($stage == 7) {
logger("Deleting orphaned data from term table");
$r = dba::p("SELECT `oid` FROM `term` WHERE NOT EXISTS (SELECT `id` FROM `item` WHERE `item`.`id` = `term`.`oid`) LIMIT ".intval($limit));
$last_id = Config::get('system', 'dbclean-last-id-7', 0);
logger("Deleting orphaned data from term table. Last ID: ".$last_id);
$r = dba::p("SELECT `oid`, `tid` FROM `term`
WHERE NOT EXISTS (SELECT `id` FROM `item` WHERE `item`.`id` = `term`.`oid`) AND `tid` >= ?
ORDER BY `tid` LIMIT ".intval($limit), $last_id);
$count = dba::num_rows($r);
if ($count > 0) {
logger("found term orphans: ".$count);
while ($orphan = dba::fetch($r)) {
$last_id = $orphan["tid"];
dba::delete('term', array('oid' => $orphan["oid"]));
}
} else {
logger("No term orphans found");
}
dba::close($r);
logger("Done deleting ".$count." orphaned data from term table");
logger("Done deleting ".$count." orphaned data from term table. Last ID: ".$last_id);
Config::set('system', 'dbclean-last-id-7', $last_id);
if ($count < $limit) {
Config::set('system', 'finished-dbclean-7', true);
}
} elseif ($stage == 8) {
if ($days <= 0) {
return;
}
$last_id = Config::get('system', 'dbclean-last-id-8', 0);
logger("Deleting expired threads. Last ID: ".$last_id);
$r = dba::p("SELECT `thread`.`iid` FROM `thread`
INNER JOIN `contact` ON `thread`.`contact-id` = `contact`.`id` AND NOT `notify_new_posts`
WHERE `thread`.`received` < UTC_TIMESTAMP() - INTERVAL ? DAY
AND NOT `thread`.`mention` AND NOT `thread`.`starred`
AND NOT `thread`.`wall` AND NOT `thread`.`origin`
AND `thread`.`uid` != 0 AND `thread`.`iid` >= ?
AND NOT `thread`.`iid` IN (SELECT `parent` FROM `item`
WHERE (`item`.`starred` OR (`item`.`resource-id` != '')
OR (`item`.`file` != '') OR (`item`.`event-id` != '')
OR (`item`.`attach` != '') OR `item`.`wall` OR `item`.`origin`)
AND `item`.`parent` = `thread`.`iid`)
ORDER BY `thread`.`iid` LIMIT 1000", $days, $last_id);
$count = dba::num_rows($r);
if ($count > 0) {
logger("found expired threads: ".$count);
while ($thread = dba::fetch($r)) {
$last_id = $thread["iid"];
dba::delete('thread', array('iid' => $thread["iid"]));
}
} else {
logger("No expired threads found");
}
dba::close($r);
logger("Done deleting ".$count." expired threads. Last ID: ".$last_id);
Config::set('system', 'dbclean-last-id-8', $last_id);
} elseif ($stage == 9) {
if ($days <= 0) {
return;
}
$last_id = Config::get('system', 'dbclean-last-id-9', 0);
$till_id = Config::get('system', 'dbclean-last-id-8', 0);
logger("Deleting old global item entries from expired threads from ID ".$last_id." to ID ".$till_id);
$r = dba::p("SELECT `id` FROM `item` WHERE `uid` = 0 AND
NOT EXISTS (SELECT `guid` FROM `item` AS `i` WHERE `item`.`guid` = `i`.`guid` AND `i`.`uid` != 0) AND
`received` < UTC_TIMESTAMP() - INTERVAL 90 DAY AND `id` >= ? AND `id` <= ?
ORDER BY `id` LIMIT ".intval($limit), $last_id, $till_id);
$count = dba::num_rows($r);
if ($count > 0) {
logger("found global item entries from expired threads: ".$count);
while ($orphan = dba::fetch($r)) {
$last_id = $orphan["id"];
dba::delete('item', array('id' => $orphan["id"]));
}
} else {
logger("No global item entries from expired threads");
}
dba::close($r);
logger("Done deleting ".$count." old global item entries from expired threads. Last ID: ".$last_id);
Config::set('system', 'dbclean-last-id-9', $last_id);
}
// Call it again if not all entries were purged
if (($stage != 0) AND ($count > 0)) {
if (($stage != 0) && ($count > 0)) {
proc_run(PRIORITY_MEDIUM, 'include/dbclean.php');
}
}

View file

@ -76,7 +76,7 @@ class dbm {
if (is_bool($value)) {
$value = ($value ? 'true' : 'false');
} elseif (is_float($value) OR is_integer($value)) {
} elseif (is_float($value) || is_integer($value)) {
$value = (string)$value;
} else {
$value = "'".dbesc($value)."'";

View file

@ -8,7 +8,11 @@ require_once "include/text.php";
define('NEW_UPDATE_ROUTINE_VERSION', 1170);
/**
const DB_UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
const DB_UPDATE_SUCCESSFUL = 1; // Database check was successful
const DB_UPDATE_FAILED = 2; // Database check failed
/*
* Converts all tables from MyISAM to InnoDB
*/
function convert_to_innodb() {
@ -130,7 +134,7 @@ function table_structure($table) {
// On utf8mb4 a varchar index can only have a length of 191
// The "show index" command sometimes returns this value although this value wasn't added manually.
// Because we don't want to add this number to every index, we ignore bigger numbers
if (($index["Sub_part"] != "") AND (($index["Sub_part"] < 191) OR ($index["Key_name"] == "PRIMARY"))) {
if (($index["Sub_part"] != "") && (($index["Sub_part"] < 191) || ($index["Key_name"] == "PRIMARY"))) {
$column .= "(".$index["Sub_part"].")";
}
@ -229,7 +233,7 @@ function update_structure($verbose, $action, $tables=null, $definition=null) {
}
// MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
if ((version_compare($db->server_info(), '5.7.4') >= 0) AND
if ((version_compare($db->server_info(), '5.7.4') >= 0) &&
!(strpos($db->server_info(), 'MariaDB') !== false)) {
$ignore = '';
} else {
@ -378,7 +382,7 @@ function update_structure($verbose, $action, $tables=null, $definition=null) {
$field_definition = $database[$name]["fields"][$fieldname];
// Define the default collation if not given
if (!isset($parameters['Collation']) AND !is_null($field_definition['Collation'])) {
if (!isset($parameters['Collation']) && !is_null($field_definition['Collation'])) {
$parameters['Collation'] = 'utf8mb4_general_ci';
} else {
$parameters['Collation'] = null;
@ -386,7 +390,7 @@ function update_structure($verbose, $action, $tables=null, $definition=null) {
if ($field_definition['Collation'] != $parameters['Collation']) {
$sql2 = db_modify_table_field($fieldname, $parameters);
if (($sql3 == "") OR (substr($sql3, -2, 2) == "; ")) {
if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
$sql3 .= "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
} else {
$sql3 .= ", ".$sql2;
@ -481,6 +485,12 @@ function update_structure($verbose, $action, $tables=null, $definition=null) {
Config::set('system', 'maintenance_reason', '');
}
if ($errors) {
Config::set('system', 'dbupdate', DB_UPDATE_FAILED);
} else {
Config::set('system', 'dbupdate', DB_UPDATE_SUCCESSFUL);
}
return $errors;
}
@ -504,7 +514,7 @@ function db_field_command($parameters, $create = true) {
if ($parameters["extra"] != "")
$fieldstruct .= " ".$parameters["extra"];
/*if (($parameters["primary"] != "") AND $create)
/*if (($parameters["primary"] != "") && $create)
$fieldstruct .= " PRIMARY KEY";*/
return($fieldstruct);
@ -521,7 +531,7 @@ function db_create_table($name, $fields, $verbose, $action, $indexes=null) {
$primary_keys = array();
foreach ($fields AS $fieldname => $field) {
$sql_rows[] = "`".dbesc($fieldname)."` ".db_field_command($field);
if (x($field,'primary') and $field['primary']!='') {
if (x($field,'primary') && $field['primary']!='') {
$primary_keys[] = $fieldname;
}
}
@ -809,7 +819,7 @@ function db_definition() {
$database["conv"] = array(
"fields" => array(
"id" => array("type" => "int(10) unsigned", "not null" => "1", "extra" => "auto_increment", "primary" => "1"),
"guid" => array("type" => "varchar(64)", "not null" => "1", "default" => ""),
"guid" => array("type" => "varchar(255)", "not null" => "1", "default" => ""),
"recips" => array("type" => "text"),
"uid" => array("type" => "int(11)", "not null" => "1", "default" => "0", "relation" => array("user" => "uid")),
"creator" => array("type" => "varchar(255)", "not null" => "1", "default" => ""),
@ -1196,7 +1206,7 @@ function db_definition() {
"id" => array("type" => "int(11)", "not null" => "1", "extra" => "auto_increment", "primary" => "1"),
"name" => array("type" => "varchar(128)", "not null" => "1", "default" => ""),
"locked" => array("type" => "tinyint(1)", "not null" => "1", "default" => "0"),
"created" => array("type" => "datetime", "default" => NULL_DATE),
"pid" => array("type" => "int(10) unsigned", "not null" => "1", "default" => "0"),
),
"indexes" => array(
"PRIMARY" => array("id"),
@ -1206,7 +1216,7 @@ function db_definition() {
"fields" => array(
"id" => array("type" => "int(10) unsigned", "not null" => "1", "extra" => "auto_increment", "primary" => "1"),
"uid" => array("type" => "int(10) unsigned", "not null" => "1", "default" => "0", "relation" => array("user" => "uid")),
"guid" => array("type" => "varchar(64)", "not null" => "1", "default" => ""),
"guid" => array("type" => "varchar(255)", "not null" => "1", "default" => ""),
"from-name" => array("type" => "varchar(255)", "not null" => "1", "default" => ""),
"from-photo" => array("type" => "varchar(255)", "not null" => "1", "default" => ""),
"from-url" => array("type" => "varchar(255)", "not null" => "1", "default" => ""),
@ -1733,6 +1743,9 @@ function db_definition() {
),
"indexes" => array(
"PRIMARY" => array("id"),
"pid" => array("pid"),
"parameter" => array("parameter(64)"),
"priority_created" => array("priority", "created"),
)
);

View file

@ -91,7 +91,7 @@ function delivery_run(&$argv, &$argc){
$uid = $item_id;
} else {
// find ancestors
$r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1",
$r = q("SELECT * FROM `item` WHERE `id` = %d AND visible = 1 AND moderated = 0 LIMIT 1",
intval($item_id)
);
@ -105,7 +105,7 @@ function delivery_run(&$argv, &$argc){
$updated = $r[0]['edited'];
$items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible = 1 AND moderated = 0 ORDER BY `id` ASC",
intval($parent_id)
);
@ -339,7 +339,7 @@ function delivery_run(&$argv, &$argc){
// If we are setup as a soapbox we aren't accepting top level posts from this person
if (($x[0]['page-flags'] == PAGE_SOAPBOX) AND $top_level) {
if (($x[0]['page-flags'] == PAGE_SOAPBOX) && $top_level) {
break;
}
logger('mod-delivery: local delivery');
@ -453,7 +453,7 @@ function delivery_run(&$argv, &$argc){
$headers .= "References: <".iri2msgid($it["parent-uri"]).">";
// If Threading is enabled, write down the correct parent
if (($it["thr-parent"] != "") and ($it["thr-parent"] != $it["parent-uri"]))
if (($it["thr-parent"] != "") && ($it["thr-parent"] != $it["parent-uri"]))
$headers .= " <".iri2msgid($it["thr-parent"]).">";
$headers .= "\n";
@ -462,14 +462,14 @@ function delivery_run(&$argv, &$argc){
dbesc($it['parent-uri']),
intval($uid));
if (dbm::is_result($r) AND ($r[0]['title'] != '')) {
if (dbm::is_result($r) && ($r[0]['title'] != '')) {
$subject = $r[0]['title'];
} else {
$r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
dbesc($it['parent-uri']),
intval($uid));
if (dbm::is_result($r) AND ($r[0]['title'] != ''))
if (dbm::is_result($r) && ($r[0]['title'] != ''))
$subject = $r[0]['title'];
}
}

View file

@ -245,7 +245,7 @@ class dfrn {
/// @TODO This hook can't work anymore
// call_hooks('atom_feed', $atom);
if (!dbm::is_result($items) OR $onlyheader) {
if (!dbm::is_result($items) || $onlyheader) {
$atom = trim($doc->saveXML());
call_hooks('atom_feed_end', $atom);
@ -284,6 +284,62 @@ class dfrn {
return $atom;
}
/**
* @brief Generate an atom entry for a given item id
*
* @param int $item_id The item id
*
* @return string DFRN feed entry
*/
public static function itemFeed($item_id) {
$r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
`contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
`contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
`contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
`sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
FROM `item`
STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
AND (NOT `contact`.`blocked` OR `contact`.`pending`)
LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
WHERE `item`.`id` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
AND `item`.`wall` AND NOT `item`.`private`",
intval($item_id)
);
if (!dbm::is_result($r)) {
killme();
}
$item = $r[0];
$r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
WHERE `contact`.`self` AND `user`.`uid` = %d LIMIT 1",
intval($item['uid'])
);
if (!dbm::is_result($r)) {
killme();
}
$owner = $r[0];
$doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;
$alternatelink = $owner['url'];
$root = self::add_header($doc, $owner, 'dfrn:owner', $alternatelink, true);
$type = 'html';
$entry = self::entry($doc, $type, $item, $owner, true);
$root->appendChild($entry);
$atom = trim($doc->saveXML());
return $atom;
}
/**
* @brief Create XML text for DFRN mails
*
@ -508,7 +564,7 @@ class dfrn {
$attributes = array();
if (!$public OR !$hidewall) {
if (!$public || !$hidewall) {
$attributes = array("dfrn:updated" => $namdate);
}
@ -519,7 +575,7 @@ class dfrn {
$attributes = array("rel" => "photo", "type" => "image/jpeg",
"media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
if (!$public OR !$hidewall) {
if (!$public || !$hidewall) {
$attributes["dfrn:updated"] = $picdate;
}
@ -921,7 +977,7 @@ class dfrn {
if (count($tags)) {
foreach ($tags as $t) {
if (($type != 'html') OR ($t[0] != "@")) {
if (($type != 'html') || ($t[0] != "@")) {
xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
}
}
@ -940,7 +996,7 @@ class dfrn {
intval($owner["uid"]),
dbesc(normalise_link($mention)));
if (dbm::is_result($r) AND ($r[0]["forum"] OR $r[0]["prv"])) {
if (dbm::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
"ostatus:object-type" => ACTIVITY_OBJ_GROUP,
"href" => $mention));
@ -1323,7 +1379,7 @@ class dfrn {
$contact["avatar-date"] = $attributes->textContent;
}
}
if (($width > 0) AND ($href != "")) {
if (($width > 0) && ($href != "")) {
$avatarlist[$width] = $href;
}
}
@ -1332,7 +1388,7 @@ class dfrn {
$author["avatar"] = current($avatarlist);
}
if (dbm::is_result($r) AND !$onlyfetch) {
if (dbm::is_result($r) && !$onlyfetch) {
logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
$poco = array("url" => $contact["url"]);
@ -1774,7 +1830,7 @@ class dfrn {
$relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
$relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
if (($relocate["avatar"] == "") AND ($relocate["photo"] != "")) {
if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
$relocate["avatar"] = $relocate["photo"];
}
@ -1922,7 +1978,7 @@ class dfrn {
}
// update last-child if it changes
if ($item["last-child"] AND ($item["last-child"] != $current["last-child"])) {
if ($item["last-child"] && ($item["last-child"] != $current["last-child"])) {
$r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
dbesc(datetime_convert()),
dbesc($item["parent-uri"]),
@ -2206,7 +2262,7 @@ class dfrn {
$title = $attributes->textContent;
}
}
if (($rel != "") AND ($href != "")) {
if (($rel != "") && ($href != "")) {
switch ($rel) {
case "alternate":
$item["plink"] = $href;
@ -2254,7 +2310,7 @@ class dfrn {
);
// Is there an existing item?
if (dbm::is_result($current) AND edited_timestamp_is_newer($current[0], $item) AND
if (dbm::is_result($current) && edited_timestamp_is_newer($current[0], $item) &&
(datetime_convert("UTC","UTC",$item["edited"]) < $current[0]["edited"])) {
logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
return;
@ -2328,7 +2384,7 @@ class dfrn {
}
$notice_info = $xpath->query("statusnet:notice_info", $entry);
if ($notice_info AND ($notice_info->length > 0)) {
if ($notice_info && ($notice_info->length > 0)) {
foreach ($notice_info->item(0)->attributes AS $attributes) {
if ($attributes->name == "source") {
$item["app"] = strip_tags($attributes->textContent);
@ -2378,9 +2434,9 @@ class dfrn {
}
}
if (($term != "") AND ($scheme != "")) {
if (($term != "") && ($scheme != "")) {
$parts = explode(":", $scheme);
if ((count($parts) >= 4) AND (array_shift($parts) == "X-DFRN")) {
if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
$termhash = array_shift($parts);
$termurl = implode(":", $parts);
@ -2440,7 +2496,7 @@ class dfrn {
$item["contact-id"] = $owner["contact-id"];
}
if (($item["network"] != $owner["network"]) AND ($owner["network"] != "")) {
if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
$item["network"] = $owner["network"];
}
@ -2448,7 +2504,7 @@ class dfrn {
$item["contact-id"] = $author["contact-id"];
}
if (($item["network"] != $author["network"]) AND ($author["network"] != "")) {
if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
$item["network"] = $author["network"];
}
@ -2548,7 +2604,7 @@ class dfrn {
);
}
if ($posted_id AND $parent AND ($entrytype == DFRN_REPLY_RC)) {
if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $posted_id);
}
@ -2613,7 +2669,7 @@ class dfrn {
$when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
}
if (!$uri OR !$importer["id"]) {
if (!$uri || !$importer["id"]) {
return false;
}

View file

@ -416,7 +416,7 @@ class Diaspora {
$fields = $postdata['fields'];
// Is it a an action (comment, like, ...) for our own post?
if (isset($fields->parent_guid) AND !$postdata["relayed"]) {
if (isset($fields->parent_guid) && !$postdata["relayed"]) {
$guid = notags(unxmlify($fields->parent_guid));
$importer = self::importer_for_guid($guid);
if (is_array($importer)) {
@ -612,9 +612,9 @@ class Diaspora {
}
}
if (($fieldname == "author_signature") AND ($entry != ""))
if (($fieldname == "author_signature") && ($entry != ""))
$author_signature = base64_decode($entry);
elseif (($fieldname == "parent_author_signature") AND ($entry != ""))
elseif (($fieldname == "parent_author_signature") && ($entry != ""))
$parent_author_signature = base64_decode($entry);
elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
if ($signed_data != "") {
@ -624,7 +624,7 @@ class Diaspora {
$signed_data .= $entry;
}
if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) ||
($orig_type == "relayable_retraction"))
xml::copy($entry, $fields, $fieldname);
}
@ -714,13 +714,13 @@ class Diaspora {
$update = true;
}
if (!$person OR $update) {
if (!$person || $update) {
logger("create or refresh", LOGGER_DEBUG);
$r = probe_url($handle, PROBE_DIASPORA);
// Note that Friendica contacts will return a "Diaspora person"
// if Diaspora connectivity is enabled on their server
if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
if ($r && ($r["network"] === NETWORK_DIASPORA)) {
self::add_fcontact($r, $update);
$person = $r;
}
@ -1151,7 +1151,7 @@ class Diaspora {
// Fetch the author - for the old and the new Diaspora version
if ($source_xml->post->status_message->diaspora_handle)
$author = (string)$source_xml->post->status_message->diaspora_handle;
elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
elseif ($source_xml->author && ($source_xml->getName() == "status_message"))
$author = (string)$source_xml->author;
// If this isn't a "status_message" then quit
@ -1403,7 +1403,7 @@ class Diaspora {
$message_id = self::message_exists($importer["uid"], $guid);
if ($message_id) {
return $message_id;
return true;
}
$parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
@ -1462,12 +1462,16 @@ class Diaspora {
$message_id = item_store($datarray);
if ($message_id <= 0) {
return false;
}
if ($message_id) {
logger("Stored comment ".$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 && $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.
@ -1480,7 +1484,7 @@ class Diaspora {
proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
}
return $message_id;
return true;
}
/**
@ -1631,7 +1635,7 @@ class Diaspora {
}
if (!$conversation) {
logger("unable to create conversation.");
return;
return false;
}
foreach ($messages as $mesg)
@ -1709,7 +1713,7 @@ class Diaspora {
$message_id = self::message_exists($importer["uid"], $guid);
if ($message_id)
return $message_id;
return true;
$parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
if (!$parent_item)
@ -1762,11 +1766,16 @@ class Diaspora {
$message_id = item_store($datarray);
if ($message_id)
if ($message_id <= 0) {
return false;
}
if ($message_id) {
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 && $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.
@ -1779,7 +1788,7 @@ class Diaspora {
proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
}
return $message_id;
return true;
}
/**
@ -2115,7 +2124,7 @@ class Diaspora {
// perhaps we were already sharing with this person. Now they're sharing with us.
// That makes us friends.
if ($contact) {
if ($following AND $sharing) {
if ($following && $sharing) {
logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
self::receive_request_make_friend($importer, $contact);
@ -2138,17 +2147,17 @@ class Diaspora {
}
}
if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
if (!$following && $sharing && in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
return false;
} elseif (!$following AND !$sharing) {
} elseif (!$following && !$sharing) {
logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
return false;
} elseif (!$following AND $sharing) {
} elseif (!$following && $sharing) {
logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
} elseif ($following AND $sharing) {
} elseif ($following && $sharing) {
logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
} elseif ($following AND !$sharing) {
} elseif ($following && !$sharing) {
logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
}
@ -2226,9 +2235,9 @@ class Diaspora {
// but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
// we are going to change the relationship and make them a follower.
if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following)
$new_relation = CONTACT_IS_FRIEND;
elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing)
$new_relation = CONTACT_IS_SHARING;
else
$new_relation = CONTACT_IS_FOLLOWER;
@ -2356,7 +2365,7 @@ class Diaspora {
$message_id = self::message_exists($importer["uid"], $guid);
if ($message_id) {
return $message_id;
return true;
}
$original_item = self::original_item($root_guid, $root_author, $author);
@ -2407,9 +2416,10 @@ class Diaspora {
if ($message_id) {
logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
return true;
} else {
return false;
}
return $message_id;
}
/**
@ -2450,7 +2460,7 @@ class Diaspora {
intval($r[0]["parent"]));
// Only delete it if the parent author really fits
if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
if (!link_compare($p[0]["author-link"], $contact["url"]) && !link_compare($r[0]["author-link"], $contact["url"])) {
logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
return false;
}
@ -2487,7 +2497,7 @@ class Diaspora {
$target_type = notags(unxmlify($data->target_type));
$contact = self::contact_by_handle($importer["uid"], $sender);
if (!$contact AND (in_array($target_type, array("Contact", "Person")))) {
if (!$contact && (in_array($target_type, array("Contact", "Person")))) {
logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
return false;
}
@ -2540,7 +2550,7 @@ class Diaspora {
$message_id = self::message_exists($importer["uid"], $guid);
if ($message_id) {
return $message_id;
return true;
}
$address = array();
@ -2615,7 +2625,7 @@ class Diaspora {
$datarray["location"] = $address["address"];
}
if (isset($address["lat"]) AND isset($address["lng"])) {
if (isset($address["lat"]) && isset($address["lng"])) {
$datarray["coord"] = $address["lat"]." ".$address["lng"];
}
@ -2624,9 +2634,10 @@ class Diaspora {
if ($message_id) {
logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
return true;
} else {
return false;
}
return $message_id;
}
/* ************************************************************************************** *
@ -2927,7 +2938,7 @@ class Diaspora {
// The message could not be delivered. We mark the contact as "dead"
mark_for_death($contact);
}
} elseif (($return_code >= 200) AND ($return_code <= 299)) {
} elseif (($return_code >= 200) && ($return_code <= 299)) {
// We successfully delivered a message, the contact is alive
unmark_for_death($contact);
}
@ -3037,7 +3048,7 @@ class Diaspora {
// Skip if it isn't a pure repeated messages
// Does it start with a share?
if ((strpos($body, "[share") > 0) AND $complete)
if ((strpos($body, "[share") > 0) && $complete)
return(false);
// Does it end with a share?
@ -3085,7 +3096,7 @@ class Diaspora {
$ret= array();
$ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == ""))
return(false);
$link = "";
@ -3098,7 +3109,7 @@ class Diaspora {
$link = $matches[1];
$ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == ""))
return(false);
return($ret);
@ -3158,7 +3169,7 @@ class Diaspora {
if ($event['start']) {
$eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
}
if ($event['finish'] AND !$event['nofinish']) {
if ($event['finish'] && !$event['nofinish']) {
$eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
}
if ($event['summary']) {
@ -3204,7 +3215,7 @@ class Diaspora {
$created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
// Detect a share element and do a reshare
if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
if (!$item['private'] && ($ret = self::is_reshare($item["body"]))) {
$message = array("root_diaspora_id" => $ret["root_handle"],
"root_guid" => $ret["root_guid"],
"guid" => $item["guid"],
@ -3254,7 +3265,7 @@ class Diaspora {
"provider_display_name" => $item["app"]);
// Diaspora rejects messages when they contain a location without "lat" or "lng"
if (!isset($location["lat"]) OR !isset($location["lng"])) {
if (!isset($location["lat"]) || !isset($location["lng"])) {
unset($message["location"]);
}
@ -3529,7 +3540,7 @@ class Diaspora {
// Old way - is used by the internal Friendica functions
/// @todo Change all signatur storing functions to the new format
if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
if ($signature['signed_text'] && $signature['signature'] && $signature['signer'])
$message = self::message_from_signature($item, $signature);
else {// New way
$msg = json_decode($signature['signed_text'], true);
@ -3581,7 +3592,7 @@ class Diaspora {
$target_type = "StatusMessage";
}
if ($relay AND ($item["uri"] !== $item["parent-uri"]))
if ($relay && ($item["uri"] !== $item["parent-uri"]))
$signature = "parent_author_signature";
else
$signature = "target_author_signature";
@ -3761,7 +3772,7 @@ class Diaspora {
public static function store_like_signature($contact, $post_id) {
// Is the contact the owner? Then fetch the private key
if (!$contact['self'] OR ($contact['uid'] == 0)) {
if (!$contact['self'] || ($contact['uid'] == 0)) {
logger("No owner post, so not storing signature", LOGGER_DEBUG);
return false;
}

View file

@ -81,12 +81,12 @@ function discover_poco_run(&$argv, &$argc) {
logger($result, LOGGER_DEBUG);
} elseif ($mode == 3) {
update_suggestions();
} elseif (($mode == 2) AND get_config('system','poco_completion')) {
} elseif (($mode == 2) && get_config('system','poco_completion')) {
discover_users();
} elseif (($mode == 1) AND ($search != "") and get_config('system','poco_local_search')) {
} elseif (($mode == 1) && ($search != "") && get_config('system','poco_local_search')) {
discover_directory($search);
gs_search_user($search);
} elseif (($mode == 0) AND ($search == "") and (get_config('system','poco_discovery') > 0)) {
} elseif (($mode == 0) && ($search == "") && (get_config('system','poco_discovery') > 0)) {
// Query Friendica and Hubzilla servers for their users
poco_discover();
@ -176,7 +176,7 @@ function discover_users() {
$server_url = $user["server_url"];
}
if ((($server_url == "") AND ($user["network"] == NETWORK_FEED)) OR $force_update OR poco_check_server($server_url, $user["network"])) {
if ((($server_url == "") && ($user["network"] == NETWORK_FEED)) || $force_update || poco_check_server($server_url, $user["network"])) {
logger('Check profile '.$user["url"]);
proc_run(PRIORITY_LOW, "include/discover_poco.php", "check_profile", base64_encode($user["url"]));
@ -216,7 +216,7 @@ function discover_directory($search) {
if (dbm::is_result($exists)) {
logger("Profile ".$jj->url." already exists (".$search.")", LOGGER_DEBUG);
if (($exists[0]["last_contact"] < $exists[0]["last_failure"]) AND
if (($exists[0]["last_contact"] < $exists[0]["last_failure"]) &&
($exists[0]["updated"] < $exists[0]["last_failure"])) {
continue;
}

View file

@ -152,7 +152,7 @@ function email_get_part($mbox,$uid,$p,$partno, $subtype) {
if ($p->parameters)
foreach ($p->parameters as $x)
$params[strtolower($x->attribute)] = $x->value;
if (isset($p->dparameters) and $p->dparameters)
if (isset($p->dparameters) && $p->dparameters)
foreach ($p->dparameters as $x)
$params[strtolower($x->attribute)] = $x->value;
@ -160,7 +160,7 @@ function email_get_part($mbox,$uid,$p,$partno, $subtype) {
// Any part with a filename is an attachment,
// so an attached text file (type 0) is not mistaken as the message.
if ((isset($params['filename']) and $params['filename']) || (isset($params['name']) and $params['name'])) {
if ((isset($params['filename']) && $params['filename']) || (isset($params['name']) && $params['name'])) {
// filename may be given as 'Filename' or 'Name' or both
$filename = ($params['filename'])? $params['filename'] : $params['name'];
// filename may be encoded, so see imap_mime_header_decode()
@ -191,7 +191,7 @@ function email_get_part($mbox,$uid,$p,$partno, $subtype) {
// }
// SUBPART RECURSION
if (isset($p->parts) and $p->parts) {
if (isset($p->parts) && $p->parts) {
$x = "";
foreach ($p->parts as $partno0=>$p2) {
$x .= email_get_part($mbox,$uid,$p2,$partno . '.' . ($partno0+1), $subtype); // 1.2, 1.2.1, etc.

View file

@ -99,7 +99,7 @@ function notification($params) {
intval($parent_id),
intval($params['uid'])
);
if ($p AND count($p) AND ($p[0]["ignored"])) {
if ($p && count($p) && ($p[0]["ignored"])) {
logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
return;
}
@ -115,7 +115,7 @@ function notification($params) {
dbesc($params['link']),
intval($params['uid'])
);
if ($p and count($p)) {
if ($p && count($p)) {
pop_lang();
return;
}
@ -515,7 +515,7 @@ function notification($params) {
logger('sending notification email');
if (isset($params['parent']) AND (intval($params['parent']) != 0)) {
if (isset($params['parent']) && (intval($params['parent']) != 0)) {
$id_for_parent = $params['parent']."@".$hostname;
// Is this the first email notification for this parent item and user?
@ -676,7 +676,7 @@ function check_item_notification($itemid, $uid, $defaulttype = "") {
// Check for invalid profile urls. 13 should be the shortest possible profile length:
// http://a.bc/d
// Additionally check for invalid urls that would return the normalised value "http:"
if ((strlen($profile) >= 13) AND (normalise_link($profile) != "http:")) {
if ((strlen($profile) >= 13) && (normalise_link($profile) != "http:")) {
if (!in_array($profile, $profiles2))
$profiles2[] = $profile;
@ -760,11 +760,11 @@ function check_item_notification($itemid, $uid, $defaulttype = "") {
$tagged = false;
foreach ($profiles AS $profile) {
if (strpos($item[0]["tag"], "=".$profile."]") OR strpos($item[0]["body"], "=".$profile."]"))
if (strpos($item[0]["tag"], "=".$profile."]") || strpos($item[0]["body"], "=".$profile."]"))
$tagged = true;
}
if ($item[0]["mention"] OR $tagged OR ($defaulttype == NOTIFY_TAGSELF)) {
if ($item[0]["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
$params["type"] = NOTIFY_TAGSELF;
$params["verb"] = ACTIVITY_TAG;
}
@ -776,7 +776,7 @@ function check_item_notification($itemid, $uid, $defaulttype = "") {
LIMIT 1",
intval($item[0]["parent"]), intval($uid));
if ($parent AND !isset($params["type"])) {
if ($parent && !isset($params["type"])) {
$params["type"] = NOTIFY_COMMENT;
$params["verb"] = ACTIVITY_POST;
}

View file

@ -30,10 +30,10 @@ function update_contact($id) {
// make sure to not overwrite existing values with blank entries
foreach ($ret AS $key => $val) {
if (isset($r[0][$key]) AND ($r[0][$key] != "") AND ($val == ""))
if (isset($r[0][$key]) && ($r[0][$key] != "") && ($val == ""))
$ret[$key] = $r[0][$key];
if (isset($r[0][$key]) AND ($ret[$key] != $r[0][$key]))
if (isset($r[0][$key]) && ($ret[$key] != $r[0][$key]))
$update = true;
}

View file

@ -47,7 +47,7 @@ function gprobe_run(&$argv, &$argc){
}
if (dbm::is_result($r)) {
// Check for accessibility and do a poco discovery
if (poco_last_updated($r[0]['url'], true) AND ($r[0]["network"] == NETWORK_DFRN))
if (poco_last_updated($r[0]['url'], true) && ($r[0]["network"] == NETWORK_DFRN))
poco_load(0,0,$r[0]['id'], str_replace('/profile/','/poco/',$r[0]['url']));
}

View file

@ -22,7 +22,7 @@ function group_add($uid,$name) {
intval($uid),
dbesc($name)
);
notice( t('A deleted group with this name was revived. Existing item permissions <strong>may</strong> apply to this group and any future members. If this is not what you intended, please create another group with a different name.') . EOL);
notice( t('A deleted group with this name was revived. Existing item permissions <strong>may</strong> apply to this group and any future members. If this is not what you intended, please create another group with a different name.') . EOL);
}
return true;
}
@ -320,7 +320,7 @@ function expand_groups($a,$check_dead = false, $use_gcontact = false) {
if (dbm::is_result($r))
foreach ($r as $rr)
$ret[] = $rr['contact-id'];
if ($check_dead AND !$use_gcontact) {
if ($check_dead && !$use_gcontact) {
require_once('include/acl_selectors.php');
$ret = prune_deadguys($ret);
}

View file

@ -44,7 +44,7 @@ function node2bbcodesub(&$doc, $oldnode, $attributes, $startbb, $endbb)
if (strpos('*'.$startbb, '$1') > 0) {
if ($replace and (@$attr[$attribute] != '')) {
if ($replace && (@$attr[$attribute] != '')) {
$startbb = preg_replace($value, $startbb, $attr[$attribute], -1, $count);

View file

@ -23,7 +23,7 @@ function breaklines($line, $level, $wraplength = 75)
if ($pos == 0)
$pos = strpos($line, ' ');
if (($pos > 0) and strlen($line) > $wraplen) {
if (($pos > 0) && strlen($line) > $wraplen) {
$newline = trim(substr($line, 0, $pos));
if ($level > 0)
$newline = str_repeat(">", $level).' '.$newline;
@ -32,7 +32,7 @@ function breaklines($line, $level, $wraplength = 75)
$line = substr($line, $pos+1);
}
} while ((strlen($line) > $wraplen) and !($oldline == $line));
} while ((strlen($line) > $wraplen) && !($oldline == $line));
if ($level > 0)
$line = str_repeat(">", $level).' '.$line;
@ -70,7 +70,7 @@ function quotelevel($message, $wraplength = 75)
$line = substr($line, 0, $pos).substr($line, $pos+8);
}
if (!$startquote or ($line != ''))
if (!$startquote || ($line != ''))
$newlines[] = breaklines($line, $currlevel, $wraplength);
}
return(implode($newlines, "\n"));
@ -92,13 +92,13 @@ function collecturls($message) {
if (strpos($treffer[1], $listitem) !== false)
$ignore = true;
if ((strpos($treffer[1], "//twitter.com/") !== false) and (strpos($treffer[1], "/status/") !== false))
if ((strpos($treffer[1], "//twitter.com/") !== false) && (strpos($treffer[1], "/status/") !== false))
$ignore = false;
if ((strpos($treffer[1], "//plus.google.com/") !== false) and (strpos($treffer[1], "/posts") !== false))
if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/posts") !== false))
$ignore = false;
if ((strpos($treffer[1], "//plus.google.com/") !== false) and (strpos($treffer[1], "/photos") !== false))
if ((strpos($treffer[1], "//plus.google.com/") !== false) && (strpos($treffer[1], "/photos") !== false))
$ignore = false;
if (!$ignore)
@ -212,7 +212,7 @@ function html2plain($html, $wraplength = 75, $compact = false)
$message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
if (!$compact AND ($message != "")) {
if (!$compact && ($message != "")) {
$counter = 1;
foreach ($urls as $id=>$url)
if ($url != "")

View file

@ -152,7 +152,9 @@ function get_profiledata_by_nick($nickname, $uid = 0, $profile = 0) {
if ($profile) {
$profile_int = intval($profile);
$r = q("SELECT `contact`.`id` AS `contact_id`, `profile`.`uid` AS `profile_uid`, `profile`.*,
$r = q("SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` AS `contact_photo`,
`contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
`profile`.`uid` AS `profile_uid`, `profile`.*,
`contact`.`avatar-date` AS picdate, `contact`.`addr`, `user`.*
FROM `profile`
INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
@ -163,7 +165,9 @@ function get_profiledata_by_nick($nickname, $uid = 0, $profile = 0) {
);
}
if (!dbm::is_result($r)) {
$r = q("SELECT `contact`.`id` AS `contact_id`, `profile`.`uid` AS `profile_uid`, `profile`.*,
$r = q("SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` as `contact_photo`,
`contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
`profile`.`uid` AS `profile_uid`, `profile`.*,
`contact`.`avatar-date` AS picdate, `contact`.`addr`, `user`.*
FROM `profile`
INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
@ -213,7 +217,7 @@ function profile_sidebar($profile, $block = 0) {
$profile['picdate'] = urlencode($profile['picdate']);
if (($profile['network'] != "") AND ($profile['network'] != NETWORK_DFRN)) {
if (($profile['network'] != "") && ($profile['network'] != NETWORK_DFRN)) {
$profile['network_name'] = format_network_name($profile['network'], $profile['url']);
} else {
$profile['network_name'] = "";
@ -236,7 +240,7 @@ function profile_sidebar($profile, $block = 0) {
}
// Is the local user already connected to that user?
if ($connect AND local_user()) {
if ($connect && local_user()) {
if (isset($profile["url"])) {
$profile_url = normalise_link($profile["url"]);
} else {
@ -250,19 +254,19 @@ function profile_sidebar($profile, $block = 0) {
$connect = false;
}
if ($connect AND ($profile['network'] != NETWORK_DFRN) AND !isset($profile['remoteconnect']))
if ($connect && ($profile['network'] != NETWORK_DFRN) && !isset($profile['remoteconnect']))
$connect = false;
$remoteconnect = NULL;
if (isset($profile['remoteconnect']))
$remoteconnect = $profile['remoteconnect'];
if ($connect AND ($profile['network'] == NETWORK_DFRN) AND !isset($remoteconnect))
if ($connect && ($profile['network'] == NETWORK_DFRN) && !isset($remoteconnect))
$subscribe_feed = t("Atom feed");
else
$subscribe_feed = false;
if (remote_user() OR (get_my_url() && $profile['unkmail'] && ($profile['uid'] != local_user()))) {
if (remote_user() || (get_my_url() && $profile['unkmail'] && ($profile['uid'] != local_user()))) {
$wallmessage = t('Message');
$wallmessage_link = "wallmessage/".$profile["nickname"];
@ -365,9 +369,9 @@ function profile_sidebar($profile, $block = 0) {
'fullname' => $profile['name'],
'firstname' => $firstname,
'lastname' => $lastname,
'photo300' => App::get_baseurl() . '/photo/custom/300/' . $profile['uid'] . '.jpg',
'photo100' => App::get_baseurl() . '/photo/custom/100/' . $profile['uid'] . '.jpg',
'photo50' => App::get_baseurl() . '/photo/custom/50/' . $profile['uid'] . '.jpg',
'photo300' => $profile['contact_photo'],
'photo100' => $profile['contact_thumb'],
'photo50' => $profile['contact_micro'],
);
else
$diaspora = false;
@ -375,7 +379,7 @@ function profile_sidebar($profile, $block = 0) {
if (!$block) {
$contact_block = contact_block();
if (is_array($a->profile) AND !$a->profile['hide-friends']) {
if (is_array($a->profile) && !$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))
@ -410,9 +414,9 @@ function profile_sidebar($profile, $block = 0) {
else
$p["address"] = bbcode($p["location"]);
if (isset($p["photo"]))
if (isset($p["photo"])) {
$p["photo"] = proxy_url($p["photo"], false, PROXY_SIZE_SMALL);
}
if ($a->theme['template_engine'] === 'internal')
$location = template_escape($location);

View file

@ -143,7 +143,7 @@ function title_is_body($title, $body) {
$body = substr($body, 0, strlen($title));
}
if (($title != $body) and (substr($title, -3) == "...")) {
if (($title != $body) && (substr($title, -3) == "...")) {
$pos = strrpos($title, "...");
if ($pos > 0) {
$title = substr($title, 0, $pos);
@ -159,16 +159,16 @@ function add_page_info_data($data) {
// It maybe is a rich content, but if it does have everything that a link has,
// then treat it that way
if (($data["type"] == "rich") AND is_string($data["title"]) AND
is_string($data["text"]) AND (sizeof($data["images"]) > 0)) {
if (($data["type"] == "rich") && is_string($data["title"]) &&
is_string($data["text"]) && (sizeof($data["images"]) > 0)) {
$data["type"] = "link";
}
if ((($data["type"] != "link") AND ($data["type"] != "video") AND ($data["type"] != "photo")) OR ($data["title"] == $data["url"])) {
if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
return "";
}
if ($no_photos AND ($data["type"] == "photo")) {
if ($no_photos && ($data["type"] == "photo")) {
return "";
}
@ -204,7 +204,7 @@ function add_page_info_data($data) {
$preview = str_replace(array("[", "]"), array("&#91;", "&#93;"), htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
// if the preview picture is larger than 500 pixels then show it in a larger mode
// But only, if the picture isn't higher than large (To prevent huge posts)
if (($data["images"][0]["width"] >= 500) AND ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
if (($data["images"][0]["width"] >= 500) && ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
$text .= " image='".$preview."'";
} else {
$text .= " preview='".$preview."'";
@ -214,7 +214,7 @@ function add_page_info_data($data) {
$text .= "]".$data["text"]."[/attachment]";
$hashtags = "";
if (isset($data["keywords"]) AND count($data["keywords"])) {
if (isset($data["keywords"]) && count($data["keywords"])) {
$hashtags = "\n";
foreach ($data["keywords"] AS $keyword) {
/// @todo make a positive list of allowed characters
@ -237,11 +237,11 @@ function query_page_info($url, $no_photos = false, $photo = "", $keywords = fals
logger('fetch page info for ' . $url . ' ' . print_r($data, true), LOGGER_DEBUG);
if (!$keywords AND isset($data["keywords"])) {
if (!$keywords && isset($data["keywords"])) {
unset($data["keywords"]);
}
if (($keyword_blacklist != "") AND isset($data["keywords"])) {
if (($keyword_blacklist != "") && isset($data["keywords"])) {
$list = explode(", ", $keyword_blacklist);
foreach ($list AS $keyword) {
$keyword = trim($keyword);
@ -259,7 +259,7 @@ function add_page_keywords($url, $no_photos = false, $photo = "", $keywords = fa
$data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
$tags = "";
if (isset($data["keywords"]) AND count($data["keywords"])) {
if (isset($data["keywords"]) && count($data["keywords"])) {
foreach ($data["keywords"] AS $keyword) {
$hashtag = str_replace(array(" ", "+", "/", ".", "#", "'"),
array("", "", "", "", "", ""), $keyword);
@ -301,7 +301,7 @@ function add_page_info_to_body($body, $texturl = false, $no_photos = false) {
}
// Convert urls without bbcode elements
if (!$matches AND $texturl) {
if (!$matches && $texturl) {
preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
// Yeah, a hack. I really hate regular expressions :)
@ -315,21 +315,21 @@ function add_page_info_to_body($body, $texturl = false, $no_photos = false) {
}
// Remove the link from the body if the link is attached at the end of the post
if (isset($footer) AND (trim($footer) != "") AND (strpos($footer, $matches[1]))) {
if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
$removedlink = trim(str_replace($matches[1], "", $body));
if (($removedlink == "") OR strstr($body, $removedlink)) {
if (($removedlink == "") || strstr($body, $removedlink)) {
$body = $removedlink;
}
$url = str_replace(array('/', '.'), array('\/', '\.'), $matches[1]);
$removedlink = preg_replace("/\[url\=" . $url . "\](.*?)\[\/url\]/ism", '', $body);
if (($removedlink == "") OR strstr($body, $removedlink)) {
if (($removedlink == "") || strstr($body, $removedlink)) {
$body = $removedlink;
}
}
// Add the page information to the bottom
if (isset($footer) AND (trim($footer) != "")) {
if (isset($footer) && (trim($footer) != "")) {
$body .= $footer;
}
@ -421,10 +421,10 @@ function store_conversation($arr) {
if (in_array($arr['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
$conversation = array('item-uri' => $arr['uri'], 'received' => dbm::date());
if (isset($arr['parent-uri']) AND ($arr['parent-uri'] != $arr['uri'])) {
if (isset($arr['parent-uri']) && ($arr['parent-uri'] != $arr['uri'])) {
$conversation['reply-to-uri'] = $arr['parent-uri'];
}
if (isset($arr['thr-parent']) AND ($arr['thr-parent'] != $arr['uri'])) {
if (isset($arr['thr-parent']) && ($arr['thr-parent'] != $arr['uri'])) {
$conversation['reply-to-uri'] = $arr['thr-parent'];
}
@ -453,7 +453,7 @@ function store_conversation($arr) {
unset($old_conv['source']);
}
// Update structure data all the time but the source only when its from a better protocol.
if (($old_conv['protocol'] < $conversation['protocol']) AND ($old_conv['protocol'] != 0)) {
if (($old_conv['protocol'] < $conversation['protocol']) && ($old_conv['protocol'] != 0)) {
unset($conversation['protocol']);
unset($conversation['source']);
}
@ -503,9 +503,9 @@ function item_store($arr, $force_parent = false, $notify = false, $dontcache = f
if ($notify) {
$guid_prefix = "";
} elseif ((trim($arr['guid']) == "") AND (trim($arr['plink']) != "")) {
} elseif ((trim($arr['guid']) == "") && (trim($arr['plink']) != "")) {
$arr['guid'] = uri_to_guid($arr['plink']);
} elseif ((trim($arr['guid']) == "") AND (trim($arr['uri']) != "")) {
} elseif ((trim($arr['guid']) == "") && (trim($arr['uri']) != "")) {
$arr['guid'] = uri_to_guid($arr['uri']);
} else {
$parsed = parse_url($arr["author-link"]);
@ -653,7 +653,7 @@ function item_store($arr, $force_parent = false, $notify = false, $dontcache = f
$arr['edited'] = datetime_convert();
}
if (($arr['author-link'] == "") AND ($arr['owner-link'] == "")) {
if (($arr['author-link'] == "") && ($arr['owner-link'] == "")) {
logger("Both author-link and owner-link are empty. Called by: " . App::callstack(), LOGGER_DEBUG);
}
@ -832,7 +832,7 @@ function item_store($arr, $force_parent = false, $notify = false, $dontcache = f
$a = get_app();
$self = normalise_link(App::get_baseurl() . '/profile/' . $u[0]['nickname']);
logger("item_store: 'myself' is ".$self." for parent ".$parent_id." checking against ".$arr['author-link']." and ".$arr['owner-link'], LOGGER_DEBUG);
if ((normalise_link($arr['author-link']) == $self) OR (normalise_link($arr['owner-link']) == $self)) {
if ((normalise_link($arr['author-link']) == $self) || (normalise_link($arr['owner-link']) == $self)) {
q("UPDATE `thread` SET `mention` = 1 WHERE `iid` = %d", intval($parent_id));
logger("item_store: tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
}
@ -1051,7 +1051,7 @@ function item_store($arr, $force_parent = false, $notify = false, $dontcache = f
// update the commented timestamp on the parent
// Only update "commented" if it is really a comment
if (($arr['verb'] == ACTIVITY_POST) OR !get_config("system", "like_no_comment")) {
if (($arr['verb'] == ACTIVITY_POST) || !get_config("system", "like_no_comment")) {
q("UPDATE `item` SET `commented` = '%s', `changed` = '%s' WHERE `id` = %d",
dbesc(datetime_convert()),
dbesc(datetime_convert()),
@ -1089,7 +1089,7 @@ function item_store($arr, $force_parent = false, $notify = false, $dontcache = f
* current post can be deleted if is for a community page and no mention are
* in it.
*/
if (!$deleted AND !$dontcache) {
if (!$deleted && !$dontcache) {
$r = q('SELECT * FROM `item` WHERE `id` = %d', intval($current_post));
if ((dbm::is_result($r)) && (count($r) == 1)) {
@ -1156,10 +1156,10 @@ function item_store($arr, $force_parent = false, $notify = false, $dontcache = f
*/
function item_set_last_item($arr) {
$update = (!$arr['private'] AND (($arr["author-link"] === $arr["owner-link"]) OR ($arr["parent-uri"] === $arr["uri"])));
$update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
// Is it a forum? Then we don't care about the rules from above
if (!$update AND ($arr["network"] == NETWORK_DFRN) AND ($arr["parent-uri"] === $arr["uri"])) {
if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
$isforum = q("SELECT `forum` FROM `contact` WHERE `id` = %d AND `forum`",
intval($arr['contact-id']));
if (dbm::is_result($isforum)) {
@ -1282,7 +1282,7 @@ function get_item_id($guid, $uid = 0) {
// Does the given user have this item?
if ($uid) {
$r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 AND `item`.`moderated` = 0
AND `item`.`guid` = '%s' AND `item`.`uid` = %d", dbesc($guid), intval($uid));
if (dbm::is_result($r)) {
$id = $r[0]["id"];
@ -1293,7 +1293,7 @@ function get_item_id($guid, $uid = 0) {
// Or is it anywhere on the server?
if ($nick == "") {
$r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 AND `item`.`moderated` = 0
AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
AND `item`.`private` = 0 AND `item`.`wall` = 1
@ -1600,7 +1600,7 @@ function item_is_remote_self($contact, &$datarray) {
return false;
}
if (($contact['network'] != NETWORK_FEED) AND $datarray['private']) {
if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
return false;
}
@ -1701,7 +1701,7 @@ function new_follower($importer, $contact, $datarray, $item, $sharing = false) {
intval($importer['uid'])
);
if (dbm::is_result($r) AND !in_array($r[0]['page-flags'], array(PAGE_SOAPBOX, PAGE_FREELOVE))) {
if (dbm::is_result($r) && !in_array($r[0]['page-flags'], array(PAGE_SOAPBOX, PAGE_FREELOVE))) {
// create notification
$hash = random_string();
@ -1741,7 +1741,7 @@ function new_follower($importer, $contact, $datarray, $item, $sharing = false) {
));
}
} elseif (dbm::is_result($r) AND in_array($r[0]['page-flags'], array(PAGE_SOAPBOX, PAGE_FREELOVE))) {
} elseif (dbm::is_result($r) && in_array($r[0]['page-flags'], array(PAGE_SOAPBOX, PAGE_FREELOVE))) {
$r = q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1",
intval($importer['uid']),
dbesc($url)
@ -1803,7 +1803,7 @@ function subscribe_to_hub($url, $importer, $contact, $hubmode = 'subscribe') {
logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
if (!strlen($contact['hub-verify']) OR ($contact['hub-verify'] != $verify_token)) {
if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
$r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d",
dbesc($verify_token),
intval($contact['id'])
@ -2076,7 +2076,7 @@ function item_expire($uid, $days, $network = "", $force = false) {
drop_item($item['id'], false);
}
proc_run(PRIORITY_HIGH, "include/notifier.php", "expire", $uid);
proc_run(PRIORITY_LOW, "include/notifier.php", "expire", $uid);
}
@ -2099,7 +2099,7 @@ function drop_items($items) {
// multiple threads may have been deleted, send an expire notification
if ($uid) {
proc_run(PRIORITY_HIGH, "include/notifier.php", "expire", $uid);
proc_run(PRIORITY_LOW, "include/notifier.php", "expire", $uid);
}
}
@ -2290,11 +2290,12 @@ function drop_item($id, $interactive = true) {
}
}
// send the notification upstream/downstream
// The priority depends on how the deletion is done.
$drop_id = intval($item['id']);
$priority = ($interactive ? PRIORITY_HIGH : PRIORITY_LOW);
// send the notification upstream/downstream as the case may be
proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $drop_id);
proc_run($priority, "include/notifier.php", "drop", $drop_id);
if (! $interactive) {
return $owner;

View file

@ -1,80 +0,0 @@
<?php
// Provide some ability to lock a PHP function so that multiple processes
// can't run the function concurrently
if (! function_exists('lock_function')) {
function lock_function($fn_name, $block = true, $wait_sec = 2, $timeout = 30) {
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;
$start = time();
do {
q("LOCK TABLE `locks` WRITE");
$r = q("SELECT `locked`, `created` FROM `locks` WHERE `name` = '%s' LIMIT 1",
dbesc($fn_name)
);
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)
);
$got_lock = true;
}
elseif (! dbm::is_result($r)) {
/// @TODO the Boolean value for count($r) should be equivalent to the Boolean value of $r
q("INSERT INTO `locks` (`name`, `created`, `locked`) VALUES ('%s', '%s', 1)",
dbesc($fn_name),
dbesc(datetime_convert())
);
$got_lock = true;
}
q("UNLOCK TABLES");
if (($block) && (! $got_lock))
sleep($wait_sec);
} 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);
return $got_lock;
}}
if (! function_exists('block_on_function_lock')) {
function block_on_function_lock($fn_name, $wait_sec = 2, $timeout = 30) {
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)
);
if (dbm::is_result($r) && $r[0]['locked']) {
sleep($wait_sec);
}
} while (dbm::is_result($r) && $r[0]['locked'] && ((time() - $start) < $timeout));
return;
}}
if (! function_exists('unlock_function')) {
function unlock_function($fn_name) {
$r = q("UPDATE `locks` SET `locked` = 0, `created` = '%s' WHERE `name` = '%s'",
dbesc(NULL_DATE),
dbesc($fn_name)
);
logger('unlock_function: released lock for function ' . $fn_name, LOGGER_DEBUG);
return;
}}

View file

@ -108,7 +108,7 @@ function send_message($recipient=0, $body='', $subject='', $replyto=''){
);
$r = q("SELECT * FROM `mail` WHERE `uri` = '%s' and `uid` = %d LIMIT 1",
$r = q("SELECT * FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
dbesc($uri),
intval(local_user())
);

View file

@ -124,7 +124,7 @@ function removesig($message)
// Sollte sich der Signaturtrenner innerhalb eines Quotes befinden
// wird keine Signaturtrennung ausgefuehrt
if (($sigpos < $quotepos) and ($sigpos != 0))
if (($sigpos < $quotepos) && ($sigpos != 0))
return(array('body' => $message, 'sig' => ''));
/// @TODO Regexp umstellen, so dass auf 1 oder kein Leerzeichen
@ -135,7 +135,7 @@ function removesig($message)
preg_match($pattern, $message, $result);
if (($result[1] != '') and ($result[2] != '')) {
if (($result[1] != '') && ($result[2] != '')) {
$cleaned = trim($result[1])."\n";
$sig = trim($result[2]);
// '[hr][size=x-small][color=darkblue]'.trim($result[2]).'[/color][/size]';
@ -157,8 +157,8 @@ function removelinebreak($message)
foreach ($arrbody as $i => $line) {
$currquotelevel = 0;
$currline = $line;
while ((strlen($currline)>0) and ((substr($currline, 0, 1) == '>')
or (substr($currline, 0, 1) == ' '))) {
while ((strlen($currline)>0) && ((substr($currline, 0, 1) == '>')
|| (substr($currline, 0, 1) == ' '))) {
if (substr($currline, 0, 1) == '>')
$currquotelevel++;
@ -167,8 +167,8 @@ function removelinebreak($message)
$quotelevel = 0;
$nextline = trim($arrbody[$i+1]);
while ((strlen($nextline)>0) and ((substr($nextline, 0, 1) == '>')
or (substr($nextline, 0, 1) == ' '))) {
while ((strlen($nextline)>0) && ((substr($nextline, 0, 1) == '>')
|| (substr($nextline, 0, 1) == ' '))) {
if (substr($nextline, 0, 1) == '>')
$quotelevel++;
@ -178,21 +178,21 @@ function removelinebreak($message)
$len = strlen($line);
$firstword = strpos($nextline.' ', ' ');
$specialchars = ((substr(trim($nextline), 0, 1) == '-') or
(substr(trim($nextline), 0, 1) == '=') or
(substr(trim($nextline), 0, 1) == '*') or
(substr(trim($nextline), 0, 1) == '·') or
(substr(trim($nextline), 0, 4) == '[url') or
(substr(trim($nextline), 0, 5) == '[size') or
(substr(trim($nextline), 0, 7) == 'http://') or
$specialchars = ((substr(trim($nextline), 0, 1) == '-') ||
(substr(trim($nextline), 0, 1) == '=') ||
(substr(trim($nextline), 0, 1) == '*') ||
(substr(trim($nextline), 0, 1) == '·') ||
(substr(trim($nextline), 0, 4) == '[url') ||
(substr(trim($nextline), 0, 5) == '[size') ||
(substr(trim($nextline), 0, 7) == 'http://') ||
(substr(trim($nextline), 0, 8) == 'https://'));
if (!$specialchars)
$specialchars = ((substr(rtrim($line), -1) == '-') or
(substr(rtrim($line), -1) == '=') or
(substr(rtrim($line), -1) == '*') or
(substr(rtrim($line), -1) == '·') or
(substr(rtrim($line), -6) == '[/url]') or
$specialchars = ((substr(rtrim($line), -1) == '-') ||
(substr(rtrim($line), -1) == '=') ||
(substr(rtrim($line), -1) == '*') ||
(substr(rtrim($line), -1) == '·') ||
(substr(rtrim($line), -6) == '[/url]') ||
(substr(rtrim($line), -7) == '[/size]'));
//if ($specialchars)
@ -202,8 +202,8 @@ function removelinebreak($message)
if (substr($lines[$lineno], -1) != ' ')
$lines[$lineno] .= ' ';
while ((strlen($line)>0) and ((substr($line, 0, 1) == '>')
or (substr($line, 0, 1) == ' '))) {
while ((strlen($line)>0) && ((substr($line, 0, 1) == '>')
|| (substr($line, 0, 1) == ' '))) {
$line = ltrim(substr($line, 1));
}
@ -213,10 +213,10 @@ function removelinebreak($message)
// $lines[$lineno] = $quotelevel.'-'.$len.'-'.$firstword.'-';
$lines[$lineno] .= $line;
//if ((($len + $firstword < 68) and (substr($line, -1, 1) != ' '))
// or ($quotelevel != $currquotelevel) or $specialchars)
//if ((($len + $firstword < 68) && (substr($line, -1, 1) != ' '))
// || ($quotelevel != $currquotelevel) || $specialchars)
if (((substr($line, -1, 1) != ' '))
or ($quotelevel != $currquotelevel))
|| ($quotelevel != $currquotelevel))
$lineno++;
}
return(implode("\n", $lines));

View file

@ -121,7 +121,7 @@ function nav_info(App $a)
$nav['apps'] = array('apps', t('Apps'), '', t('Addon applications, utilities, games'));
}
if (local_user() OR !get_config('system', 'local_search')) {
if (local_user() || !get_config('system', 'local_search')) {
$nav['search'] = array('search', t('Search'), '', t('Search site content'));
$nav['searchoption'] = array(

View file

@ -187,7 +187,7 @@ function z_fetch_url($url, $binary = false, &$redirects = 0, $opts = array()) {
$newurl = $curl_info['redirect_url'];
if (($new_location_info['path'] == '') AND ( $new_location_info['host'] != '')) {
if (($new_location_info['path'] == '') && ( $new_location_info['host'] != '')) {
$newurl = $new_location_info['scheme'] . '://' . $new_location_info['host'] . $old_location_info['path'];
}
@ -818,8 +818,8 @@ function original_url($url, $depth = 1, $fetchbody = false) {
if ($http_code == 0)
return($url);
if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
if ((($curl_info['http_code'] == "301") || ($curl_info['http_code'] == "302"))
&& (($curl_info['redirect_url'] != "") || ($curl_info['location'] != ""))) {
if ($curl_info['redirect_url'] != "")
return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
else
@ -835,7 +835,7 @@ function original_url($url, $depth = 1, $fetchbody = false) {
return($url);
// if it isn't a HTML file then exit
if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]),"html"))
return($url);
$stamp1 = microtime(true);
@ -929,7 +929,7 @@ function json_return_and_die($x) {
*/
function matching_url($url1, $url2) {
if (($url1 == "") OR ($url2 == ""))
if (($url1 == "") || ($url2 == ""))
return "";
$url1 = normalise_link($url1);
@ -938,7 +938,7 @@ function matching_url($url1, $url2) {
$parts1 = parse_url($url1);
$parts2 = parse_url($url2);
if (!isset($parts1["host"]) OR !isset($parts2["host"]))
if (!isset($parts1["host"]) || !isset($parts2["host"]))
return "";
if ($parts1["scheme"] != $parts2["scheme"])
@ -967,7 +967,7 @@ function matching_url($url1, $url2) {
if ($path1 == $path2)
$path .= $path1."/";
} while (($path1 == $path2) AND ($i++ <= count($pathparts1)));
} while (($path1 == $path2) && ($i++ <= count($pathparts1)));
$match .= $path;

View file

@ -55,6 +55,17 @@ function notifier_run(&$argv, &$argc){
return;
}
// Inherit the priority
$queue = dba::select('workerqueue', array('priority'), array('pid' => getmypid()), array('limit' => 1));
if (dbm::is_result($queue)) {
$priority = (int)$queue['priority'];
logger('inherited priority: '.$priority);
} else {
// Normally this shouldn't happen.
$priority = PRIORITY_HIGH;
logger('no inherited priority! Something is wrong.');
}
logger('notifier: invoked: ' . print_r($argv,true), LOGGER_DEBUG);
$cmd = $argv[1];
@ -152,7 +163,7 @@ function notifier_run(&$argv, &$argc){
$recipients_relocate = q("SELECT * FROM contact WHERE uid = %d AND self = 0 AND network = '%s'" , intval($uid), NETWORK_DFRN);
} else {
// find ancestors
$r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1",
$r = q("SELECT * FROM `item` WHERE `id` = %d AND visible = 1 AND moderated = 0 LIMIT 1",
intval($item_id)
);
@ -166,7 +177,7 @@ function notifier_run(&$argv, &$argc){
$updated = $r[0]['edited'];
$items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible = 1 AND moderated = 0 ORDER BY `id` ASC",
intval($parent_id)
);
@ -295,13 +306,13 @@ function notifier_run(&$argv, &$argc){
$recipients = array($parent['contact-id']);
$recipients_followup = array($parent['contact-id']);
//if (!$target_item['private'] AND $target_item['wall'] AND
if (!$target_item['private'] AND
//if (!$target_item['private'] && $target_item['wall'] &&
if (!$target_item['private'] &&
(strlen($target_item['allow_cid'].$target_item['allow_gid'].
$target_item['deny_cid'].$target_item['deny_gid']) == 0))
$push_notify = true;
if (($thr_parent AND ($thr_parent[0]['network'] == NETWORK_OSTATUS)) OR ($parent['network'] == NETWORK_OSTATUS)) {
if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
$push_notify = true;
@ -348,7 +359,7 @@ function notifier_run(&$argv, &$argc){
// a delivery fork. private groups (forum_mode == 2) do not uplink
if ((intval($parent['forum_mode']) == 1) && (! $top_level) && ($cmd !== 'uplink')) {
proc_run(PRIORITY_HIGH,'include/notifier.php','uplink',$item_id);
proc_run($priority, 'include/notifier.php', 'uplink', $item_id);
}
$conversants = array();
@ -385,7 +396,7 @@ function notifier_run(&$argv, &$argc){
// If the thread parent is OStatus then do some magic to distribute the messages.
// We have not only to look at the parent, since it could be a Friendica thread.
if (($thr_parent AND ($thr_parent[0]['network'] == NETWORK_OSTATUS)) OR ($parent['network'] == NETWORK_OSTATUS)) {
if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
$diaspora_delivery = false;
@ -487,7 +498,7 @@ function notifier_run(&$argv, &$argc){
}
logger("Deliver ".$target_item["guid"]." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
proc_run(PRIORITY_HIGH,'include/delivery.php', $cmd, $item_id, $contact['id']);
proc_run(array('priority' => $priority, 'dont_fork' => true), 'include/delivery.php', $cmd, $item_id, $contact['id']);
}
}
@ -552,7 +563,7 @@ function notifier_run(&$argv, &$argc){
if ((! $mail) && (! $fsuggest) && (! $followup)) {
logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
proc_run(PRIORITY_HIGH,'include/delivery.php',$cmd,$item_id,$rr['id']);
proc_run(array('priority' => $priority, 'dont_fork' => true), 'include/delivery.php', $cmd, $item_id, $rr['id']);
}
}
}
@ -562,7 +573,7 @@ function notifier_run(&$argv, &$argc){
}
// Notify PuSH subscribers (Used for OStatus distribution of regular posts)
if ($push_notify AND strlen($hub)) {
if ($push_notify && strlen($hub)) {
$hubs = explode(',', $hub);
if (count($hubs)) {
foreach ($hubs as $h) {
@ -592,7 +603,7 @@ function notifier_run(&$argv, &$argc){
}
// Handling the pubsubhubbub requests
proc_run(PRIORITY_HIGH,'include/pubsubpublish.php');
proc_run(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), 'include/pubsubpublish.php');
}
logger('notifier: calling hooks', LOGGER_DEBUG);

View file

@ -108,7 +108,7 @@ function oembed_fetch_url($embedurl, $no_rich_type = false){
$j->embedurl = $embedurl;
// If fetching information doesn't work, then improve via internal functions
if (($j->type == "error") OR ($no_rich_type AND ($j->type == "rich"))) {
if (($j->type == "error") || ($no_rich_type && ($j->type == "rich"))) {
$data = ParseUrl::getSiteinfoCached($embedurl, true, false);
$j->type = $data["type"];
@ -194,7 +194,7 @@ function oembed_format_object($j){
if (isset($j->author_name)) {
$ret.=" (".$j->author_name.")";
}
} elseif (isset($j->provider_name) OR isset($j->author_name)) {
} elseif (isset($j->provider_name) || isset($j->author_name)) {
$embedlink = "";
if (isset($j->provider_name)) {
$embedlink .= $j->provider_name;

View file

@ -68,9 +68,9 @@ function onepoll_run(&$argv, &$argc){
$contact = $contacts[0];
// load current friends if possible.
if (($contact['poco'] != "") AND ($contact['success_update'] > $contact['failure_update'])) {
$r = q("SELECT count(*) as total from glink
where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
if (($contact['poco'] != "") && ($contact['success_update'] > $contact['failure_update'])) {
$r = q("SELECT count(*) AS total FROM glink
WHERE `cid` = %d AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
intval($contact['id'])
);
if (dbm::is_result($r)) {
@ -395,7 +395,7 @@ function onepoll_run(&$argv, &$argc){
logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
// Only delete when mails aren't automatically moved or deleted
if (($mailconf[0]['action'] != 1) AND ($mailconf[0]['action'] != 3))
if (($mailconf[0]['action'] != 1) && ($mailconf[0]['action'] != 3))
if ($meta->deleted && ! $r[0]['deleted']) {
q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d",
dbesc(datetime_convert()),
@ -467,15 +467,15 @@ function onepoll_run(&$argv, &$argc){
$datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
// Is it a reply?
$reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
(substr(strtolower($datarray['title']), 0, 3) == "re-") or
$reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
(substr(strtolower($datarray['title']), 0, 3) == "re-") ||
($raw_refs != ""));
// Remove Reply-signs in the subject
$datarray['title'] = RemoveReply($datarray['title']);
// If it seems to be a reply but a header couldn't be found take the last message with matching subject
if (!x($datarray,'parent-uri') and $reply) {
if (!x($datarray,'parent-uri') && $reply) {
$r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d AND `network` = '%s' ORDER BY `created` DESC LIMIT 1",
dbesc(protect_sprintf($datarray['title'])),
intval($importer_uid),

View file

@ -54,7 +54,7 @@ class ostatus {
$alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
if (is_object($alternate)) {
foreach ($alternate AS $attributes) {
if (($attributes->name == "href") AND ($attributes->textContent != "")) {
if (($attributes->name == "href") && ($attributes->textContent != "")) {
$author["author-link"] = $attributes->textContent;
}
}
@ -100,7 +100,7 @@ class ostatus {
$width = $attributes->textContent;
}
}
if (($width > 0) AND ($href != "")) {
if (($width > 0) && ($href != "")) {
$avatarlist[$width] = $href;
}
}
@ -119,7 +119,7 @@ class ostatus {
$author["owner-avatar"] = $author["author-avatar"];
// Only update the contacts if it is an OStatus contact
if ($r AND !$onlyfetch AND ($contact["network"] == NETWORK_OSTATUS)) {
if ($r && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
// Update contact data
@ -153,8 +153,8 @@ class ostatus {
if ($value != "")
$contact["location"] = $value;
if (($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["about"] != $r[0]["about"]) OR
($contact["alias"] != $r[0]["alias"]) OR ($contact["location"] != $r[0]["location"])) {
if (($contact["name"] != $r[0]["name"]) || ($contact["nick"] != $r[0]["nick"]) || ($contact["about"] != $r[0]["about"]) ||
($contact["alias"] != $r[0]["alias"]) || ($contact["location"] != $r[0]["location"])) {
logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
@ -164,7 +164,7 @@ class ostatus {
dbesc(datetime_convert()), intval($contact["id"]));
}
if (isset($author["author-avatar"]) AND ($author["author-avatar"] != $r[0]['avatar'])) {
if (isset($author["author-avatar"]) && ($author["author-avatar"] != $r[0]['avatar'])) {
logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
@ -354,13 +354,13 @@ class ostatus {
$item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
// Mastodon Content Warning
if (($item["verb"] == ACTIVITY_POST) AND $xpath->evaluate('boolean(atom:summary)', $entry)) {
if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
$clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
$item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
}
if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
$item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
$item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
} elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
@ -469,11 +469,11 @@ class ostatus {
foreach ($links AS $link) {
$attribute = self::read_attributes($link);
if (($attribute['rel'] != "") AND ($attribute['href'] != "")) {
if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
switch ($attribute['rel']) {
case "alternate":
$item["plink"] = $attribute['href'];
if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) ||
($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
$item["body"] .= add_page_info($attribute['href']);
}
@ -525,7 +525,7 @@ class ostatus {
$repeat_of = "";
$notice_info = $xpath->query('statusnet:notice_info', $entry);
if ($notice_info AND ($notice_info->length > 0)) {
if ($notice_info && ($notice_info->length > 0)) {
foreach ($notice_info->item(0)->attributes AS $attributes) {
if ($attributes->name == "source") {
$item["app"] = strip_tags($attributes->textContent);
@ -540,7 +540,7 @@ class ostatus {
}
// Is it a repeated post?
if (($repeat_of != "") OR ($item["verb"] == ACTIVITY_SHARE)) {
if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
$activityobjects = $xpath->query('activity:object', $entry)->item(0);
if (is_object($activityobjects)) {
@ -550,7 +550,7 @@ class ostatus {
$orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
}
$orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
if ($orig_links AND ($orig_links->length > 0)) {
if ($orig_links && ($orig_links->length > 0)) {
foreach ($orig_links->item(0)->attributes AS $attributes) {
if ($attributes->name == "href") {
$orig_link = $attributes->textContent;
@ -621,8 +621,8 @@ class ostatus {
intval($importer["uid"]), dbesc($item["parent-uri"]));
// Only fetch missing stuff if it is a comment or reshare.
if (in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_SHARE)) AND
!dbm::is_result($r) AND ($related != "")) {
if (in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_SHARE)) &&
!dbm::is_result($r) && ($related != "")) {
$reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
if ($reply_path != $related) {
@ -647,6 +647,9 @@ class ostatus {
$item_id = self::completion($conversation, $importer["uid"], $item, $self);
if (!$item_id) {
// Store the conversation data. This is normally done in "item_store"
// but since something went wrong, we want to be sure to save the data.
store_conversation($item);
logger("Error storing item", LOGGER_DEBUG);
continue;
}
@ -665,16 +668,16 @@ class ostatus {
public static function convert_href($href) {
$elements = explode(":",$href);
if ((count($elements) <= 2) OR ($elements[0] != "tag"))
if ((count($elements) <= 2) || ($elements[0] != "tag"))
return $href;
$server = explode(",", $elements[1]);
$conversation = explode("=", $elements[2]);
if ((count($elements) == 4) AND ($elements[2] == "post"))
if ((count($elements) == 4) && ($elements[2] == "post"))
return "http://".$server[0]."/notice/".$elements[3];
if ((count($conversation) != 2) OR ($conversation[1] ==""))
if ((count($conversation) != 2) || ($conversation[1] ==""))
return $href;
if ($elements[3] == "objectType=thread")
@ -700,7 +703,7 @@ class ostatus {
}
// Don't poll if the interval is set negative
if (($poll_interval < 0) AND !$override) {
if (($poll_interval < 0) && !$override) {
return;
}
@ -717,7 +720,7 @@ class ostatus {
}
if ($last AND !$override) {
if ($last && !$override) {
$next = $last + ($poll_interval * 60);
if ($next > time()) {
logger('poll interval not reached');
@ -815,7 +818,7 @@ class ostatus {
if ($conversation_id != "") {
$elements = explode(":", $conversation_id);
if ((count($elements) <= 2) OR ($elements[0] != "tag"))
if ((count($elements) <= 2) || ($elements[0] != "tag"))
return $conversation_id;
}
@ -840,6 +843,30 @@ class ostatus {
return $base_url."/conversation/".$conversation_id;
}
/**
* @brief Fetches a shared object from a given conversation object
*
* Sometimes GNU Social seems to fail when returning shared objects.
* Then they don't contains all needed data.
* We then try to find this object in the conversation
*
* @param string $id Message id
* @param object $conversation Conversation object
*
* @return object The shared object
*/
private function shared_object($id, $conversation) {
if (!is_array($conversation->items)) {
return false;
}
foreach ($conversation->items AS $single_conv) {
if ($single_conv->id == $id) {
return $single_conv;
}
}
return false;
}
/**
* @brief Fetches actor details of a given actor and user id
*
@ -906,12 +933,10 @@ class ostatus {
// If the thread shouldn't be completed then store the item and go away
// Don't do a completion on liked content
if (((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) OR
($item["verb"] == ACTIVITY_LIKE) OR ($conversation_url == "")) {
if (((intval(get_config('system','ostatus_poll_interval')) == -2) && (count($item) > 0)) ||
($item["verb"] == ACTIVITY_LIKE) || ($conversation_url == "")) {
$item_stored = item_store($item, $all_threads);
return $item_stored;
} elseif (count($item) > 0) {
$item = store_conversation($item);
}
// Get the parent
@ -921,14 +946,6 @@ class ostatus {
STRAIGHT_JOIN `item` ON `item`.`parent` = `thritem`.`parent`
WHERE `term`.`uid` = %d AND `term`.`otype` = %d AND `term`.`type` = %d AND `term`.`url` = '%s'",
intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
/* 2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
$parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
(SELECT `parent` FROM `item` WHERE `id` IN
(SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
*/
if ($parents)
$parent = $parents[0];
elseif (count($item) > 0) {
@ -962,10 +979,10 @@ class ostatus {
$conv_arr = z_fetch_url($conv."?page=".$pageno);
// If it is a non-ssl site and there is an error, then try ssl or vice versa
if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
if (!$conv_arr["success"] && (substr($conv, 0, 7) == "http://")) {
$conv = str_replace("http://", "https://", $conv);
$conv_as = fetch_url($conv."?page=".$pageno);
} elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
} elseif (!$conv_arr["success"] && (substr($conv, 0, 8) == "https://")) {
$conv = str_replace("https://", "http://", $conv);
$conv_as = fetch_url($conv."?page=".$pageno);
} else
@ -1040,7 +1057,7 @@ class ostatus {
// 1. Our conversation hasn't the "real" thread starter
// 2. This first post is a post inside our thread
// 3. This first post is a post inside another thread
if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
if (($first_id != $parent["uri"]) && ($parent["uri"] != "")) {
$new_parent = true;
@ -1127,7 +1144,7 @@ class ostatus {
}
// The item we are having on the system is the one that we wanted to store via the item array
if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
if (isset($item["uri"]) && ($item["uri"] == $existing_message["uri"])) {
$item = array();
$item_stored = 0;
}
@ -1147,7 +1164,7 @@ class ostatus {
$details = self::get_actor_details($actor, $uid, $parent["contact-id"]);
// Do we only want to import threads that were started by our contacts?
if ($details["not_following"] AND $new_parent AND get_config('system','ostatus_full_threads')) {
if ($details["not_following"] && $new_parent && get_config('system','ostatus_full_threads')) {
logger("Don't import uri ".$first_id." because user ".$uid." doesn't follow the person ".$actor, LOGGER_DEBUG);
continue;
}
@ -1201,46 +1218,56 @@ class ostatus {
$arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
// Is it a reshared item?
if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
if (isset($single_conv->verb) && ($single_conv->verb == "share") && isset($single_conv->object)) {
if (is_array($single_conv->object))
$single_conv->object = $single_conv->object[0];
logger("Found reshared item ".$single_conv->object->id);
// $single_conv->object->context->conversation;
if (isset($single_conv->object->object->id))
$arr["uri"] = $single_conv->object->object->id;
else
$arr["uri"] = $single_conv->object->id;
if (isset($single_conv->object->object->url))
$plink = self::convert_href($single_conv->object->object->url);
else
$plink = self::convert_href($single_conv->object->url);
if (isset($single_conv->object->object->content))
$arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
else
$arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
$arr["plink"] = $plink;
$arr["created"] = $single_conv->object->published;
$arr["edited"] = $single_conv->object->published;
$arr["author-name"] = $single_conv->object->actor->displayName;
if ($arr["owner-name"] == '') {
$arr["author-name"] = $single_conv->object->actor->contact->displayName;
// Sometimes GNU Social doesn't returns a complete object
if (!isset($single_conv->object->actor->url)) {
$object = self::shared_object($single_conv->object->id, $conversation);
if (is_object($object)) {
$single_conv->object = $object;
}
}
$arr["author-link"] = $single_conv->object->actor->url;
$arr["author-avatar"] = Probe::fixAvatar($single_conv->object->actor->image->url, $arr["author-link"]);
$arr["app"] = $single_conv->object->provider->displayName."#";
//$arr["verb"] = $single_conv->object->verb;
if (isset($single_conv->object->actor->url)) {
logger("Found reshared item ".$single_conv->object->id);
$arr["location"] = $single_conv->object->location->displayName;
$arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
// $single_conv->object->context->conversation;
if (isset($single_conv->object->object->id)) {
$arr["uri"] = $single_conv->object->object->id;
} else {
$arr["uri"] = $single_conv->object->id;
}
if (isset($single_conv->object->object->url)) {
$plink = self::convert_href($single_conv->object->object->url);
} else {
$plink = self::convert_href($single_conv->object->url);
}
if (isset($single_conv->object->object->content)) {
$arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
} else {
$arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
}
$arr["plink"] = $plink;
$arr["created"] = $single_conv->object->published;
$arr["edited"] = $single_conv->object->published;
$arr["author-name"] = $single_conv->object->actor->displayName;
if ($arr["owner-name"] == '') {
$arr["author-name"] = $single_conv->object->actor->contact->displayName;
}
$arr["author-link"] = $single_conv->object->actor->url;
$arr["author-avatar"] = Probe::fixAvatar($single_conv->object->actor->image->url, $arr["author-link"]);
$arr["app"] = $single_conv->object->provider->displayName."#";
//$arr["verb"] = $single_conv->object->verb;
$arr["location"] = $single_conv->object->location->displayName;
$arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
}
}
if ($arr["location"] == "")
@ -1250,27 +1277,20 @@ class ostatus {
unset($arr["coord"]);
// Copy fields from given item array
if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] == $single_conv->id))) {
$copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
"gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
"title", "attach", "app", "type", "location", "contact-id", "uri");
foreach ($copy_fields AS $field)
if (isset($item[$field]))
$arr[$field] = $item[$field];
if (isset($item["uri"]) && (($item["uri"] == $arr["uri"]) || ($item["uri"] == $single_conv->id))) {
logger('Use stored item array for item with URI '.$item["uri"], LOGGER_DEBUG);
$newitem = item_store($item);
$item = array();
$item_stored = $newitem;
} else {
$newitem = item_store($arr);
}
$newitem = item_store($arr);
if (!$newitem) {
logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
continue;
}
if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
$item = array();
$item_stored = $newitem;
}
logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
// Add the conversation entry (but don't fetch the whole conversation)
@ -1287,7 +1307,7 @@ class ostatus {
}
}
if (($item_stored < 0) AND (count($item) > 0)) {
if (($item_stored < 0) && (count($item) > 0)) {
if (get_config('system','ostatus_full_threads')) {
$details = self::get_actor_details($item["owner-link"], $uid, $item["contact-id"]);
@ -1523,7 +1543,7 @@ class ostatus {
break;
}
if (($siteinfo["type"] != "photo") AND isset($siteinfo["image"])) {
if (($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
$imgdata = get_photo_info($siteinfo["image"]);
$attributes = array("rel" => "enclosure",
"href" => $siteinfo["image"],
@ -1768,7 +1788,7 @@ class ostatus {
*/
private function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
}
@ -1834,7 +1854,7 @@ class ostatus {
*/
private function like_entry($doc, $item, $owner, $toplevel) {
if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
}
@ -1979,7 +1999,7 @@ class ostatus {
*/
private function note_entry($doc, $item, $owner, $toplevel) {
if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
}
@ -2060,7 +2080,7 @@ class ostatus {
xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
"href" => App::get_baseurl()."/display/".$item["guid"]));
if ($complete AND ($item["id"] > 0))
if ($complete && ($item["id"] > 0))
xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
xml::add_element($doc, $entry, "activity:verb", $verb);
@ -2082,7 +2102,7 @@ class ostatus {
$mentioned = array();
if (($item['parent'] != $item['id']) OR ($item['parent-uri'] !== $item['uri']) OR (($item['thr-parent'] !== '') AND ($item['thr-parent'] !== $item['uri']))) {
if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
$parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
$parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
@ -2155,7 +2175,7 @@ class ostatus {
$r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
intval($owner["uid"]),
dbesc(normalise_link($mention)));
if ($r[0]["forum"] OR $r[0]["prv"])
if ($r[0]["forum"] || $r[0]["prv"])
xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
"ostatus:object-type" => ACTIVITY_OBJ_GROUP,
"href" => $mention));
@ -2181,7 +2201,7 @@ class ostatus {
self::get_attachment($doc, $entry, $item);
if ($complete AND ($item["id"] > 0)) {
if ($complete && ($item["id"] > 0)) {
$app = $item["app"];
if ($app == "")
$app = "web";

View file

@ -12,7 +12,7 @@ function getGps($exifCoord, $hemi) {
$minutes = count($exifCoord) > 1 ? gps2Num($exifCoord[1]) : 0;
$seconds = count($exifCoord) > 2 ? gps2Num($exifCoord[2]) : 0;
$flip = ($hemi == 'W' or $hemi == 'S') ? -1 : 1;
$flip = ($hemi == 'W' || $hemi == 'S') ? -1 : 1;
return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
}
@ -44,7 +44,7 @@ function photo_albums($uid, $update = false) {
$key = "photo_albums:".$uid.":".local_user().":".remote_user();
$albums = Cache::get($key);
if (is_null($albums) OR $update) {
if (is_null($albums) || $update) {
if (!Config::get('system', 'no_count', false)) {
/// @todo This query needs to be renewed. It is really slow
// At this time we just store the data in the cache

View file

@ -8,7 +8,7 @@ class pidfile {
if (file_exists($this->_file)) {
$pid = trim(@file_get_contents($this->_file));
if (($pid != "") AND posix_kill($pid, 0)) {
if (($pid != "") && posix_kill($pid, 0)) {
$this->_running = true;
}
}

View file

@ -54,7 +54,7 @@ function get_old_attachment_data($body) {
$picturedata = get_photo_info($matches[1]);
if (($picturedata[0] >= 500) AND ($picturedata[0] >= $picturedata[1]))
if (($picturedata[0] >= 500) && ($picturedata[0] >= $picturedata[1]))
$post["image"] = $matches[1];
else
$post["preview"] = $matches[1];
@ -64,8 +64,8 @@ function get_old_attachment_data($body) {
$post["url"] = $matches[1];
$post["title"] = $matches[2];
}
if (($post["url"] == "") AND (in_array($post["type"], array("link", "video")))
AND preg_match("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $attacheddata, $matches)) {
if (($post["url"] == "") && (in_array($post["type"], array("link", "video")))
&& preg_match("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $attacheddata, $matches)) {
$post["url"] = $matches[1];
}
@ -204,7 +204,7 @@ function get_attached_data($body) {
// Workaround:
// Sometimes photo posts to the own album are not detected at the start.
// So we seem to cannot use the cache for these cases. That's strange.
if (($data["type"] != "photo") AND strstr($pictures[0][1], "/photos/"))
if (($data["type"] != "photo") && strstr($pictures[0][1], "/photos/"))
$data = ParseUrl::getSiteinfo($pictures[0][1], true);
if ($data["type"] == "photo") {
@ -256,7 +256,7 @@ function get_attached_data($body) {
$post["type"] = "text";
$post["text"] = trim($body);
}
} elseif (isset($post["url"]) AND ($post["type"] == "video")) {
} elseif (isset($post["url"]) && ($post["type"] == "video")) {
$data = ParseUrl::getSiteinfoCached($post["url"], true);
if (isset($data["images"][0]))
@ -278,7 +278,7 @@ function shortenmsg($msg, $limit, $twitter = false) {
if (iconv_strlen(trim($msg."\n".$line), "UTF-8") <= $limit)
$msg = trim($msg."\n".$line);
// Is the new message empty by now or is it a reshared message?
elseif (($msg == "") OR (($row == 1) AND (substr($msg, 0, 4) == $recycle)))
elseif (($msg == "") || (($row == 1) && (substr($msg, 0, 4) == $recycle)))
$msg = iconv_substr(iconv_substr(trim($msg."\n".$line), 0, $limit, "UTF-8"), 0, -3, "UTF-8").$ellipsis;
else
break;
@ -315,7 +315,7 @@ function plaintext(App $a, $b, $limit = 0, $includedlinks = false, $htmlmode = 2
//$post = get_attached_data($b["body"]);
$post = get_attached_data($body);
if (($b["title"] != "") AND ($post["text"] != ""))
if (($b["title"] != "") && ($post["text"] != ""))
$post["text"] = trim($b["title"]."\n\n".$post["text"]);
elseif ($b["title"] != "")
$post["text"] = trim($b["title"]);
@ -329,7 +329,7 @@ function plaintext(App $a, $b, $limit = 0, $includedlinks = false, $htmlmode = 2
// If we post to a network with no limit we only fetch
// an abstract exactly for this network
if (($limit == 0) AND ($abstract == $default_abstract))
if (($limit == 0) && ($abstract == $default_abstract))
$abstract = "";
} else // Try to guess the correct target network
@ -373,25 +373,25 @@ function plaintext(App $a, $b, $limit = 0, $includedlinks = false, $htmlmode = 2
elseif ($post["type"] == "photo")
$link = $post["image"];
if (($msg == "") AND isset($post["title"]))
if (($msg == "") && isset($post["title"]))
$msg = trim($post["title"]);
if (($msg == "") AND isset($post["description"]))
if (($msg == "") && isset($post["description"]))
$msg = trim($post["description"]);
// If the link is already contained in the post, then it neeedn't to be added again
// But: if the link is beyond the limit, then it has to be added.
if (($link != "") AND strstr($msg, $link)) {
if (($link != "") && strstr($msg, $link)) {
$pos = strpos($msg, $link);
// Will the text be shortened in the link?
// Or is the link the last item in the post?
if (($limit > 0) AND ($pos < $limit) AND (($pos + 23 > $limit) OR ($pos + strlen($link) == strlen($msg))))
if (($limit > 0) && ($pos < $limit) && (($pos + 23 > $limit) || ($pos + strlen($link) == strlen($msg))))
$msg = trim(str_replace($link, "", $msg));
elseif (($limit == 0) OR ($pos < $limit)) {
elseif (($limit == 0) || ($pos < $limit)) {
// The limit has to be increased since it will be shortened - but not now
// Only do it with Twitter (htmlmode = 8)
if (($limit > 0) AND (strlen($link) > 23) AND ($htmlmode == 8))
if (($limit > 0) && (strlen($link) > 23) && ($htmlmode == 8))
$limit = $limit - 23 + strlen($link);
$link = "";
@ -414,7 +414,7 @@ function plaintext(App $a, $b, $limit = 0, $includedlinks = false, $htmlmode = 2
if (iconv_strlen($msg, "UTF-8") > $limit) {
if (($post["type"] == "text") AND isset($post["url"]))
if (($post["type"] == "text") && isset($post["url"]))
$post["url"] = $b["plink"];
elseif (!isset($post["url"])) {
$limit = $limit - 23;

View file

@ -563,7 +563,7 @@ function theme_include($file, $root = '') {
$root = $root . '/';
}
$theme_info = $a->theme_info;
if (is_array($theme_info) AND array_key_exists('extends',$theme_info)) {
if (is_array($theme_info) && array_key_exists('extends',$theme_info)) {
$parent = $theme_info['extends'];
} else {
$parent = 'NOPATH';

View file

@ -2,13 +2,14 @@
use Friendica\App;
use Friendica\Core\Config;
use Friendica\Util\Lock;
if (!file_exists("boot.php") AND (sizeof($_SERVER["argv"]) != 0)) {
if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) {
$directory = dirname($_SERVER["argv"][0]);
if (substr($directory, 0, 1) != "/")
if (substr($directory, 0, 1) != "/") {
$directory = $_SERVER["PWD"]."/".$directory;
}
$directory = realpath($directory."/..");
chdir($directory);
@ -19,16 +20,12 @@ require_once("boot.php");
function poller_run($argv, $argc){
global $a, $db;
if (is_null($a)) {
$a = new App(dirname(__DIR__));
}
$a = new App(dirname(__DIR__));
if (is_null($db)) {
@include(".htconfig.php");
require_once("include/dba.php");
$db = new dba($db_host, $db_user, $db_pass, $db_data);
unset($db_host, $db_user, $db_pass, $db_data);
};
@include(".htconfig.php");
require_once("include/dba.php");
$db = new dba($db_host, $db_user, $db_pass, $db_data);
unset($db_host, $db_user, $db_pass, $db_data);
Config::load();
@ -41,56 +38,86 @@ function poller_run($argv, $argc){
load_hooks();
// At first check the maximum load. We shouldn't continue with a high load
if ($a->maxload_reached()) {
logger('Pre check: maximum load reached, quitting.', LOGGER_DEBUG);
return;
}
// We now start the process. This is done after the load check since this could increase the load.
$a->start_process();
if ($a->min_memory_reached()) {
return;
}
if (poller_max_connections_reached()) {
return;
}
if ($a->maxload_reached()) {
return;
}
if (($argc <= 1) OR ($argv[1] != "no_cron")) {
poller_run_cron();
}
if ($a->max_processes_reached()) {
return;
}
// Checking the number of workers
// At first we check the number of workers and quit if there are too much of them
// This is done at the top to avoid that too much code is executed without a need to do so,
// since the poller mostly quits here.
if (poller_too_much_workers()) {
poller_kill_stale_workers();
logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
return;
}
// Do we have too few memory?
if ($a->min_memory_reached()) {
logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
return;
}
// Possibly there are too much database connections
if (poller_max_connections_reached()) {
logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
return;
}
// Possibly there are too much database processes that block the system
if ($a->max_processes_reached()) {
logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
return;
}
// Now we start additional cron processes if we should do so
if (($argc <= 1) || ($argv[1] != "no_cron")) {
poller_run_cron();
}
$starttime = time();
// We fetch the next queue entry that is about to be executed
while ($r = poller_worker_process()) {
// Check free memory
if ($a->min_memory_reached()) {
return;
// If we got that queue entry we claim it for us
if (!poller_claim_process($r[0])) {
continue;
}
// Count active workers and compare them with a maximum value that depends on the load
if (poller_too_much_workers()) {
return;
// To avoid the quitting of multiple pollers only one poller at a time will execute the check
if (Lock::set('poller_worker', 0)) {
// Count active workers and compare them with a maximum value that depends on the load
if (poller_too_much_workers()) {
logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
return;
}
// Check free memory
if ($a->min_memory_reached()) {
logger('Memory limit reached, quitting.', LOGGER_DEBUG);
return;
}
Lock::remove('poller_worker');
}
// finally the work will be done
if (!poller_execute($r[0])) {
logger('Process execution failed, quitting.', LOGGER_DEBUG);
return;
}
// Quit the poller once every hour
if (time() > ($starttime + 3600))
if (time() > ($starttime + 3600)) {
logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
return;
}
}
logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
}
/**
@ -108,43 +135,22 @@ function poller_execute($queue) {
// Quit when in maintenance
if (Config::get('system', 'maintenance', true)) {
logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
return false;
}
// Constantly check the number of parallel database processes
if ($a->max_processes_reached()) {
logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
return false;
}
// Constantly check the number of available database connections to let the frontend be accessible at any time
if (poller_max_connections_reached()) {
logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
return false;
}
if (!dba::update('workerqueue', array('executed' => datetime_convert(), 'pid' => $mypid),
array('id' => $queue["id"], 'pid' => 0))) {
logger("Couldn't update queue entry ".$queue["id"]." - skip this execution", LOGGER_DEBUG);
dba::commit();
return true;
}
// Assure that there are no tasks executed twice
$id = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
if (!$id) {
logger("Queue item ".$queue["id"]." vanished - skip this execution", LOGGER_DEBUG);
dba::commit();
return true;
} elseif ((strtotime($id[0]["executed"]) <= 0) OR ($id[0]["pid"] == 0)) {
logger("Entry for queue item ".$queue["id"]." wasn't stored - skip this execution", LOGGER_DEBUG);
dba::commit();
return true;
} elseif ($id[0]["pid"] != $mypid) {
logger("Queue item ".$queue["id"]." is to be executed by process ".$id[0]["pid"]." and not by me (".$mypid.") - skip this execution", LOGGER_DEBUG);
dba::commit();
return true;
}
dba::commit();
$argv = json_decode($queue["parameter"]);
// Check for existance and validity of the include file
@ -161,9 +167,7 @@ function poller_execute($queue) {
$funcname = str_replace(".php", "", basename($argv[0]))."_run";
if (function_exists($funcname)) {
poller_exec_function($queue, $funcname, $argv);
dba::delete('workerqueue', array('id' => $queue["id"]));
} else {
logger("Function ".$funcname." does not exist");
@ -238,24 +242,27 @@ function poller_exec_function($queue, $funcname, $argv) {
$o = "\nDatabase Read:\n";
foreach ($a->callstack["database"] AS $func => $time) {
$time = round($time, 3);
if ($time > 0)
if ($time > 0) {
$o .= $func.": ".$time."\n";
}
}
}
if (isset($a->callstack["database_write"])) {
$o .= "\nDatabase Write:\n";
foreach ($a->callstack["database_write"] AS $func => $time) {
$time = round($time, 3);
if ($time > 0)
if ($time > 0) {
$o .= $func.": ".$time."\n";
}
}
}
if (isset($a->callstack["network"])) {
$o .= "\nNetwork:\n";
foreach ($a->callstack["network"] AS $func => $time) {
$time = round($time, 3);
if ($time > 0)
if ($time > 0) {
$o .= $func.": ".$time."\n";
}
}
}
} else {
@ -296,27 +303,30 @@ function poller_max_connections_reached() {
if ($max == 0) {
// the maximum number of possible user connections can be a system variable
$r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
if ($r)
if (dbm::is_result($r)) {
$max = $r[0]["Value"];
}
// Or it can be granted. This overrides the system variable
$r = q("SHOW GRANTS");
if ($r)
if (dbm::is_result($r)) {
foreach ($r AS $grants) {
$grant = array_pop($grants);
if (stristr($grant, "GRANT USAGE ON"))
if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match))
if (stristr($grant, "GRANT USAGE ON")) {
if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
$max = $match[1];
}
}
}
}
}
// If $max is set we will use the processlist to determine the current number of connections
// The processlist only shows entries of the current user
if ($max != 0) {
$r = q("SHOW PROCESSLIST");
if (!dbm::is_result($r))
if (!dbm::is_result($r)) {
return false;
}
$used = count($r);
logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
@ -332,28 +342,28 @@ function poller_max_connections_reached() {
// We will now check for the system values.
// This limit could be reached although the user limits are fine.
$r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
if (!$r)
if (!dbm::is_result($r)) {
return false;
}
$max = intval($r[0]["Value"]);
if ($max == 0)
if ($max == 0) {
return false;
}
$r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
if (!$r)
if (!dbm::is_result($r)) {
return false;
}
$used = intval($r[0]["Value"]);
if ($used == 0)
if ($used == 0) {
return false;
}
logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
$level = $used / $max * 100;
if ($level < $maxlevel)
if ($level < $maxlevel) {
return false;
}
logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
return true;
}
@ -432,10 +442,32 @@ function poller_too_much_workers() {
$slope = $maxworkers / pow($maxsysload, $exponent);
$queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
// Create a list of queue entries grouped by their priority
$listitem = array();
// Adding all processes with no workerqueue entry
$processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS (SELECT id FROM `workerqueue` WHERE `workerqueue`.`pid` = `process`.`pid`)");
if ($process = dba::fetch($processes)) {
$listitem[0] = "0:".$process["running"];
}
dba::close($processes);
// Now adding all processes with workerqueue entries
$entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` GROUP BY `priority`");
while ($entry = dba::fetch($entries)) {
$processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE `priority` = ?", $entry["priority"]);
if ($process = dba::fetch($processes)) {
$listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
}
dba::close($processes);
}
dba::close($entries);
$processlist = ' ('.implode(', ', $listitem).')';
$s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= '%s'", dbesc(NULL_DATE));
$entries = $s[0]["total"];
if (Config::get("system", "worker_fastlane", false) AND ($queues > 0) AND ($entries > 0) AND ($active >= $queues)) {
if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
$s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` <= '%s' ORDER BY `priority` LIMIT 1", dbesc(NULL_DATE));
$top_priority = $s[0]["priority"];
@ -443,37 +475,16 @@ function poller_too_much_workers() {
intval($top_priority), dbesc(NULL_DATE));
$high_running = dbm::is_result($s);
if (!$high_running AND ($top_priority > PRIORITY_UNDEFINED) AND ($top_priority < PRIORITY_NEGLIGIBLE)) {
if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
$queues = $active + 1;
}
}
// Create a list of queue entries grouped by their priority
$running = array(PRIORITY_CRITICAL => 0,
PRIORITY_HIGH => 0,
PRIORITY_MEDIUM => 0,
PRIORITY_LOW => 0,
PRIORITY_NEGLIGIBLE => 0);
$r = q("SELECT COUNT(*) AS `running`, `priority` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` GROUP BY `priority`");
if (dbm::is_result($r))
foreach ($r AS $process)
$running[$process["priority"]] = $process["running"];
$processlist = "";
$r = q("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` GROUP BY `priority`");
if (dbm::is_result($r))
foreach ($r as $entry) {
if ($processlist != "")
$processlist .= ", ";
$processlist .= $entry["priority"].":".$running[$entry["priority"]]."/".$entry["entries"];
}
logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries." (".$processlist.") - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
// Are there fewer workers running as possible? Then fork a new one.
if (!Config::get("system", "worker_dont_fork") AND ($queues > ($active + 1)) AND ($entries > 1)) {
if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
$args = array("include/poller.php", "no_cron");
$a = get_app();
@ -481,7 +492,7 @@ function poller_too_much_workers() {
}
}
return($active >= $queues);
return $active >= $queues;
}
/**
@ -492,7 +503,7 @@ function poller_too_much_workers() {
function poller_active_workers() {
$workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
return($workers[0]["processes"]);
return $workers[0]["processes"];
}
/**
@ -513,36 +524,37 @@ function poller_passing_slow(&$highest_priority) {
INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`");
// No active processes at all? Fine
if (!dbm::is_result($r))
return(false);
if (!dbm::is_result($r)) {
return false;
}
$priorities = array();
foreach ($r AS $line)
foreach ($r AS $line) {
$priorities[] = $line["priority"];
}
// Should not happen
if (count($priorities) == 0)
return(false);
if (count($priorities) == 0) {
return false;
}
$highest_priority = min($priorities);
// The highest process is already the slowest one?
// Then we quit
if ($highest_priority == PRIORITY_NEGLIGIBLE)
return(false);
if ($highest_priority == PRIORITY_NEGLIGIBLE) {
return false;
}
$high = 0;
foreach ($priorities AS $priority)
if ($priority == $highest_priority)
foreach ($priorities AS $priority) {
if ($priority == $highest_priority) {
++$high;
}
}
logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
$passing_slow = (($high/count($priorities)) > (2/3));
if ($passing_slow)
if ($passing_slow) {
logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
return($passing_slow);
}
return $passing_slow;
}
/**
@ -552,12 +564,12 @@ function poller_passing_slow(&$highest_priority) {
*/
function poller_worker_process() {
dba::transaction();
// Check if we should pass some low priority process
$highest_priority = 0;
if (poller_passing_slow($highest_priority)) {
dba::lock('workerqueue');
// Are there waiting processes with a higher priority than the currently highest?
$r = q("SELECT * FROM `workerqueue`
WHERE `executed` <= '%s' AND `priority` < %d
@ -573,15 +585,72 @@ function poller_worker_process() {
ORDER BY `priority`, `created` LIMIT 1",
dbesc(NULL_DATE),
intval($highest_priority));
if (dbm::is_result($r)) {
return $r;
}
} else {
dba::lock('workerqueue');
}
// If there is no result (or we shouldn't pass lower processes) we check without priority limit
if (($highest_priority == 0) OR !dbm::is_result($r)) {
if (!dbm::is_result($r)) {
$r = q("SELECT * FROM `workerqueue` WHERE `executed` <= '%s' ORDER BY `priority`, `created` LIMIT 1", dbesc(NULL_DATE));
}
// We only unlock the tables here, when we got no data
if (!dbm::is_result($r)) {
dba::unlock();
}
return $r;
}
/**
* @brief Assigns a workerqueue entry to the current process
*
* When we are sure that the table locks are working correctly, we can remove the checks from here
*
* @param array $queue Workerqueue entry
*
* @return boolean "true" if the claiming was successful
*/
function poller_claim_process($queue) {
$mypid = getmypid();
$success = dba::update('workerqueue', array('executed' => datetime_convert(), 'pid' => $mypid),
array('id' => $queue["id"], 'pid' => 0));
dba::unlock();
if (!$success) {
logger("Couldn't update queue entry ".$queue["id"]." - skip this execution", LOGGER_DEBUG);
return false;
}
// Assure that there are no tasks executed twice
$id = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
if (!$id) {
logger("Queue item ".$queue["id"]." vanished - skip this execution", LOGGER_DEBUG);
return false;
} elseif ((strtotime($id[0]["executed"]) <= 0) || ($id[0]["pid"] == 0)) {
logger("Entry for queue item ".$queue["id"]." wasn't stored - skip this execution", LOGGER_DEBUG);
return false;
} elseif ($id[0]["pid"] != $mypid) {
logger("Queue item ".$queue["id"]." is to be executed by process ".$id[0]["pid"]." and not by me (".$mypid.") - skip this execution", LOGGER_DEBUG);
return false;
}
return true;
}
/**
* @brief Removes a workerqueue entry from the current process
*/
function poller_unclaim_process() {
$mypid = getmypid();
dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid));
}
/**
* @brief Call the front end worker
*/
@ -678,7 +747,11 @@ function poller_run_cron() {
if (array_search(__file__,get_included_files())===0){
poller_run($_SERVER["argv"],$_SERVER["argc"]);
poller_unclaim_process();
get_app()->end_process();
Lock::remove('poller_worker');
killme();
}

View file

@ -45,7 +45,7 @@ function post_update_1192() {
WHERE `thread`.`gcontact-id` = 0 AND
(`thread`.`uid` IN (SELECT `uid` from `user`) OR `thread`.`uid` = 0)");
if ($r AND ($r[0]["total"] == 0)) {
if ($r && ($r[0]["total"] == 0)) {
set_config("system", "post_update_version", 1192);
return true;
}
@ -171,7 +171,7 @@ function post_update_1198() {
WHERE `thread`.`author-id` = 0 AND `thread`.`owner-id` = 0 AND
(`thread`.`uid` IN (SELECT `uid` from `user`) OR `thread`.`uid` = 0)");
if ($r AND ($r[0]["total"] == 0)) {
if ($r && ($r[0]["total"] == 0)) {
set_config("system", "post_update_version", 1198);
logger("Done", LOGGER_DEBUG);
return true;
@ -247,7 +247,7 @@ function post_update_1206() {
return false;
}
foreach ($r AS $user) {
if (!empty($user["lastitem_date"]) AND ($user["lastitem_date"] > $user["last-item"])) {
if (!empty($user["lastitem_date"]) && ($user["lastitem_date"] > $user["last-item"])) {
q("UPDATE `contact` SET `last-item` = '%s' WHERE `id` = %d",
dbesc($user["lastitem_date"]),
intval($user["id"]));

View file

@ -1,6 +1,12 @@
<?php
require_once('include/diaspora.php');
function profile_change() {
Diaspora::send_profile(local_user());
function profile_update_run(&$argv, &$argc) {
if ($argc != 2) {
return;
}
$uid = intval($argv[1]);
Diaspora::send_profile($uid);
}

View file

@ -17,7 +17,7 @@ function pubsubpublish_run(&$argv, &$argc){
foreach ($r as $rr) {
logger("Publish feed to ".$rr["callback_url"], LOGGER_DEBUG);
proc_run(PRIORITY_HIGH, 'include/pubsubpublish.php', $rr["id"]);
proc_run(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), 'include/pubsubpublish.php', $rr["id"]);
}
}

View file

@ -27,7 +27,7 @@ function queue_run(&$argv, &$argc) {
logger('queue: start');
// Handling the pubsubhubbub requests
proc_run(PRIORITY_HIGH,'include/pubsubpublish.php');
proc_run(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), 'include/pubsubpublish.php');
$r = q("SELECT `queue`.*, `contact`.`name`, `contact`.`uid` FROM `queue`
INNER JOIN `contact` ON `queue`.`cid` = `contact`.`id`
@ -45,14 +45,14 @@ function queue_run(&$argv, &$argc) {
* For the first 12 hours we'll try to deliver every 15 minutes
* After that, we'll only attempt delivery once per hour.
*/
$r = q("SELECT `id` FROM `queue` WHERE ((`created` > UTC_TIMESTAMP() - INTERVAL 12 HOUR && `last` < UTC_TIMESTAMP() - INTERVAL 15 MINUTE) OR (`last` < UTC_TIMESTAMP() - INTERVAL 1 HOUR)) ORDER BY `cid`, `created`");
$r = q("SELECT `id` FROM `queue` WHERE ((`created` > UTC_TIMESTAMP() - INTERVAL 12 HOUR AND `last` < UTC_TIMESTAMP() - INTERVAL 15 MINUTE) OR (`last` < UTC_TIMESTAMP() - INTERVAL 1 HOUR)) ORDER BY `cid`, `created`");
call_hooks('queue_predeliver', $a, $r);
if (dbm::is_result($r)) {
foreach ($r as $q_item) {
logger('Call queue for id '.$q_item['id']);
proc_run(PRIORITY_LOW, "include/queue.php", $q_item['id']);
proc_run(array('priority' => PRIORITY_LOW, 'dont_fork' => true), "include/queue.php", $q_item['id']);
}
}
return;
@ -84,7 +84,7 @@ function queue_run(&$argv, &$argc) {
$dead = Cache::get($cachekey_deadguy.$c[0]['notify']);
if (!is_null($dead) AND $dead) {
if (!is_null($dead) && $dead) {
logger('queue: skipping known dead url: '.$c[0]['notify']);
update_queue_time($q_item['id']);
return;
@ -102,7 +102,7 @@ function queue_run(&$argv, &$argc) {
Cache::set($cachekey_server.$server, $vital, CACHE_QUARTER_HOUR);
}
if (!is_null($vital) AND !$vital) {
if (!is_null($vital) && !$vital) {
logger('queue: skipping dead server: '.$server);
update_queue_time($q_item['id']);
return;

View file

@ -10,7 +10,7 @@ function convertquote($body, $reply)
$quoteline = $arrbody[$i];
while ((strlen($quoteline)>0) and ((substr($quoteline, 0, 1) == '>')
or (substr($quoteline, 0, 1) == ' '))) {
|| (substr($quoteline, 0, 1) == ' '))) {
if (substr($quoteline, 0, 1) == '>')
$quotelevel++;

View file

@ -65,7 +65,7 @@ function ref_session_write($id, $data) {
$memcache = cache::memcache();
$a = get_app();
if (is_object($memcache) AND is_object($a)) {
if (is_object($memcache) && is_object($a)) {
$memcache->set($a->get_hostname().":session:".$id, $data, MEMCACHE_COMPRESSED, $expire);
return true;
}

View file

@ -150,7 +150,7 @@ function poco_load_worker($cid, $uid, $zcid, $url) {
$gender = $entry->gender;
}
if (isset($entry->generation) AND ($entry->generation > 0)) {
if (isset($entry->generation) && ($entry->generation > 0)) {
$generation = ++$entry->generation;
}
@ -160,7 +160,7 @@ function poco_load_worker($cid, $uid, $zcid, $url) {
}
}
if (isset($entry->contactType) AND ($entry->contactType >= 0))
if (isset($entry->contactType) && ($entry->contactType >= 0))
$contact_type = $entry->contactType;
$gcontact = array("url" => $profile_url,
@ -238,7 +238,7 @@ function sanitize_gcontact($gcontact) {
$alternate = poco_alternate_ostatus_url($gcontact['url']);
// The global contacts should contain the original picture, not the cached one
if (($gcontact['generation'] != 1) AND stristr(normalise_link($gcontact['photo']), normalise_link(App::get_baseurl()."/photo/"))) {
if (($gcontact['generation'] != 1) && stristr(normalise_link($gcontact['photo']), normalise_link(App::get_baseurl()."/photo/"))) {
$gcontact['photo'] = "";
}
@ -250,7 +250,7 @@ function sanitize_gcontact($gcontact) {
$gcontact['network'] = $r[0]["network"];
}
if (($gcontact['network'] == "") OR ($gcontact['network'] == NETWORK_OSTATUS)) {
if (($gcontact['network'] == "") || ($gcontact['network'] == NETWORK_OSTATUS)) {
$r = q("SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
dbesc($gcontact['url']), dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
);
@ -268,13 +268,13 @@ function sanitize_gcontact($gcontact) {
);
if (count($x)) {
if (!isset($gcontact['network']) AND ($x[0]["network"] != NETWORK_STATUSNET)) {
if (!isset($gcontact['network']) && ($x[0]["network"] != NETWORK_STATUSNET)) {
$gcontact['network'] = $x[0]["network"];
}
if ($gcontact['updated'] <= NULL_DATE) {
$gcontact['updated'] = $x[0]["updated"];
}
if (!isset($gcontact['server_url']) AND (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
if (!isset($gcontact['server_url']) && (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
$gcontact['server_url'] = $x[0]["server_url"];
}
if (!isset($gcontact['addr'])) {
@ -282,8 +282,8 @@ function sanitize_gcontact($gcontact) {
}
}
if ((!isset($gcontact['network']) OR !isset($gcontact['name']) OR !isset($gcontact['addr']) OR !isset($gcontact['photo']) OR !isset($gcontact['server_url']) OR $alternate)
AND poco_reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)) {
if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']) || $alternate)
&& poco_reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)) {
$data = Probe::uri($gcontact['url']);
if ($data["network"] == NETWORK_PHANTOM) {
@ -296,7 +296,7 @@ function sanitize_gcontact($gcontact) {
$gcontact = array_merge($gcontact, $data);
if ($alternate AND ($gcontact['network'] == NETWORK_OSTATUS)) {
if ($alternate && ($gcontact['network'] == NETWORK_OSTATUS)) {
// Delete the old entry - if it exists
$r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
if ($r) {
@ -306,7 +306,7 @@ function sanitize_gcontact($gcontact) {
}
}
if (!isset($gcontact['name']) OR !isset($gcontact['photo'])) {
if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
throw new Exception('No name and photo for URL '.$gcontact['url']);
}
@ -483,11 +483,11 @@ function poco_last_updated($profile, $force = false) {
$server_url = normalise_link(poco_detect_server($profile));
}
if (($server_url == '') AND ($gcontacts[0]["server_url"] != "")) {
if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
$server_url = $gcontacts[0]["server_url"];
}
if (!$force AND (($server_url == '') OR ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
$server_url = normalise_link(poco_detect_server($profile));
}
@ -521,7 +521,7 @@ function poco_last_updated($profile, $force = false) {
}
// noscrape is really fast so we don't cache the call.
if (($server_url != "") AND ($gcontacts[0]["nick"] != "")) {
if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
// Use noscrape if possible
$server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
@ -529,7 +529,7 @@ function poco_last_updated($profile, $force = false) {
if ($server) {
$noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
if ($noscraperet["success"] && ($noscraperet["body"] != "")) {
$noscrape = json_decode($noscraperet["body"], true);
@ -593,7 +593,7 @@ function poco_last_updated($profile, $force = false) {
}
// If we only can poll the feed, then we only do this once a while
if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
if (!$force && !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
update_gcontact($contact);
@ -604,8 +604,8 @@ function poco_last_updated($profile, $force = false) {
// Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
// Then check the other link and delete this one
if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
(normalise_link($profile) == normalise_link($data["alias"])) AND
if (($data["network"] == NETWORK_OSTATUS) && poco_alternate_ostatus_url($profile) &&
(normalise_link($profile) == normalise_link($data["alias"])) &&
(normalise_link($profile) != normalise_link($data["url"]))) {
// Delete the old entry
@ -629,7 +629,7 @@ function poco_last_updated($profile, $force = false) {
return false;
}
if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
if (($data["poll"] == "") || (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
dbesc(datetime_convert()), dbesc(normalise_link($profile)));
@ -717,24 +717,24 @@ function poco_do_update($created, $updated, $last_failure, $last_contact) {
return false;
// If the last contact was less than a week ago and the last failure is older than a week then don't update
//if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
//if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
// return false;
// If the last contact time was more than a week ago and the contact was created more than a week ago, then only try once a week
if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7)))
return false;
// If the last contact time was more than a month ago and the contact was created more than a month ago, then only try once a month
if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30)))
return false;
return true;
}
function poco_to_boolean($val) {
if (($val == "true") OR ($val == 1))
if (($val == "true") || ($val == 1))
return(true);
if (($val == "false") OR ($val == 0))
if (($val == "false") || ($val == 0))
return(false);
return ($val);
@ -825,7 +825,7 @@ function poco_fetch_nodeinfo($server_url) {
$server['register_policy'] = REGISTER_CLOSED;
if (is_bool($nodeinfo->openRegistrations) AND $nodeinfo->openRegistrations) {
if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
$server['register_policy'] = REGISTER_OPEN;
}
@ -977,7 +977,7 @@ function poco_check_server($server_url, $network = "", $force = false) {
$info = $servers[0]["info"];
$register_policy = $servers[0]["register_policy"];
if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
if (!$force && !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
return ($last_contact >= $last_failure);
}
@ -1009,7 +1009,7 @@ function poco_check_server($server_url, $network = "", $force = false) {
// Quit if there is a timeout.
// But we want to make sure to only quit if we are mostly sure that this server url fits.
if (dbm::is_result($servers) AND ($orig_server_url == $server_url) AND
if (dbm::is_result($servers) && ($orig_server_url == $server_url) &&
($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
dba::p("UPDATE `gserver` SET `last_failure` = ? WHERE `nurl` = ?", datetime_convert(), normalise_link($server_url));
@ -1018,7 +1018,7 @@ function poco_check_server($server_url, $network = "", $force = false) {
// Maybe the page is unencrypted only?
$xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
if (!$serverret["success"] || ($serverret["body"] == "") || (@sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
$server_url = str_replace("https://", "http://", $server_url);
// We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
@ -1034,7 +1034,7 @@ function poco_check_server($server_url, $network = "", $force = false) {
$xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
}
if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
if (!$serverret["success"] || ($serverret["body"] == "") || (sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
// Workaround for bad configured servers (known nginx problem)
if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
$failure = true;
@ -1073,7 +1073,7 @@ function poco_check_server($server_url, $network = "", $force = false) {
// Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
$serverret = z_fetch_url($server_url);
if (!$serverret["success"] OR ($serverret["body"] == "")) {
if (!$serverret["success"] || ($serverret["body"] == "")) {
$failure = true;
} else {
$server = poco_detect_server_type($serverret["body"]);
@ -1106,13 +1106,13 @@ function poco_check_server($server_url, $network = "", $force = false) {
}
}
if (!$failure AND ($poco == "")) {
if (!$failure && ($poco == "")) {
// Test for Statusnet
// Will also return data for Friendica and GNU Social - but it will be overwritten later
// The "not implemented" is a special treatment for really, really old Friendica versions
$serverret = z_fetch_url($server_url."/api/statusnet/version.json");
if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
$platform = "StatusNet";
// Remove junk that some GNU Social servers return
$version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
@ -1122,8 +1122,8 @@ function poco_check_server($server_url, $network = "", $force = false) {
// Test for GNU Social
$serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
$platform = "GNU Social";
// Remove junk that some GNU Social servers return
$version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
@ -1133,7 +1133,7 @@ function poco_check_server($server_url, $network = "", $force = false) {
// Test for Mastodon
$serverret = z_fetch_url($server_url."/api/v1/instance");
if ($serverret["success"] AND ($serverret["body"] != '')) {
if ($serverret["success"] && ($serverret["body"] != '')) {
$data = json_decode($serverret["body"]);
if (isset($data->version)) {
$platform = "Mastodon";
@ -1188,9 +1188,9 @@ function poco_check_server($server_url, $network = "", $force = false) {
$data->site->private = poco_to_boolean($data->site->private);
$data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly) {
if (!$data->site->closed && !$data->site->private and $data->site->inviteonly) {
$register_policy = REGISTER_APPROVE;
} elseif (!$data->site->closed AND !$data->site->private) {
} elseif (!$data->site->closed && !$data->site->private) {
$register_policy = REGISTER_OPEN;
} else {
$register_policy = REGISTER_CLOSED;
@ -1255,7 +1255,7 @@ function poco_check_server($server_url, $network = "", $force = false) {
// Check for noscrape
// Friendica servers could be detected as OStatus servers
if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
if (!$failure && in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
$serverret = z_fetch_url($server_url."/friendica/json");
if (!$serverret["success"]) {
@ -1290,7 +1290,7 @@ function poco_check_server($server_url, $network = "", $force = false) {
}
}
if ($possible_failure AND !$failure) {
if ($possible_failure && !$failure) {
$failure = true;
}
@ -1302,9 +1302,9 @@ function poco_check_server($server_url, $network = "", $force = false) {
$last_failure = $orig_last_failure;
}
if (($last_contact <= $last_failure) AND !$failure) {
if (($last_contact <= $last_failure) && !$failure) {
logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
} elseif (($last_contact >= $last_failure) AND $failure) {
} else if (($last_contact >= $last_failure) && $failure) {
logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
}
@ -1746,7 +1746,7 @@ function poco_discover_single_server($id) {
$success = poco_discover_server(json_decode($retdata["body"]));
}
if (!$success AND (get_config('system','poco_discovery') > 2)) {
if (!$success && (get_config('system','poco_discovery') > 2)) {
logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
poco_discover_server_users($data, $server);
}
@ -1793,7 +1793,7 @@ function poco_discover($complete = false) {
logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
proc_run(PRIORITY_LOW, "include/discover_poco.php", "update_server_directory", intval($server['id']));
if (!$complete AND (--$no_of_queries == 0)) {
if (!$complete && (--$no_of_queries == 0)) {
break;
}
}
@ -1833,7 +1833,7 @@ function poco_discover_server_users($data, $server) {
function poco_discover_server($data, $default_generation = 0) {
if (!isset($data->entry) OR !count($data->entry)) {
if (!isset($data->entry) || !count($data->entry)) {
return false;
}
@ -1897,11 +1897,11 @@ function poco_discover_server($data, $default_generation = 0) {
$gender = $entry->gender;
}
if (isset($entry->generation) AND ($entry->generation > 0)) {
if(isset($entry->generation) && ($entry->generation > 0)) {
$generation = ++$entry->generation;
}
if (isset($entry->contactType) AND ($entry->contactType >= 0)) {
if(isset($entry->contactType) && ($entry->contactType >= 0)) {
$contact_type = $entry->contactType;
}
@ -1951,7 +1951,7 @@ function poco_discover_server($data, $default_generation = 0) {
function clean_contact_url($url) {
$parts = parse_url($url);
if (!isset($parts["scheme"]) OR !isset($parts["host"])) {
if (!isset($parts["scheme"]) || !isset($parts["host"])) {
return $url;
}
@ -1978,7 +1978,7 @@ function clean_contact_url($url) {
* @param arr $contact contact array (called by reference)
*/
function fix_alternate_contact_address(&$contact) {
if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
if (($contact["network"] == NETWORK_OSTATUS) && poco_alternate_ostatus_url($contact["url"])) {
$data = probe_url($contact["url"]);
if ($contact["network"] == NETWORK_OSTATUS) {
logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
@ -2023,7 +2023,8 @@ function get_gcontact_id($contact) {
$contact["url"] = clean_contact_url($contact["url"]);
}
$r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 2",
dba::lock('gcontact');
$r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
dbesc(normalise_link($contact["url"])));
if (dbm::is_result($r)) {
@ -2035,7 +2036,7 @@ function get_gcontact_id($contact) {
$last_failure = strtotime($r[0]["last_failure"]);
$last_contact_str = $r[0]["last_contact"];
$last_contact = strtotime($r[0]["last_contact"]);
$doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
$doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
}
} else {
q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
@ -2064,18 +2065,13 @@ function get_gcontact_id($contact) {
$doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
}
}
dba::unlock();
if ($doprobing) {
logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
proc_run(PRIORITY_LOW, 'include/gprobe.php', bin2hex($contact["url"]));
}
if ((dbm::is_result($r)) AND (count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != "")) {
q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
dbesc(normalise_link($contact["url"])),
intval($gcontact_id));
}
return $gcontact_id;
}
@ -2088,7 +2084,7 @@ function get_gcontact_id($contact) {
function update_gcontact($contact) {
// Check for invalid "contact-type" value
if (isset($contact['contact-type']) AND (intval($contact['contact-type']) < 0)) {
if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
$contact['contact-type'] = 0;
}
@ -2126,8 +2122,8 @@ function update_gcontact($contact) {
}
// assign all unassigned fields from the database entry
foreach ($fields AS $field => $data) {
if (!isset($contact[$field]) OR ($contact[$field] == "")) {
foreach ($fields as $field => $data)
if (!isset($contact[$field]) || ($contact[$field] == "")) {
$contact[$field] = $r[0][$field];
}
}
@ -2170,7 +2166,7 @@ function update_gcontact($contact) {
$contact["server_url"] = normalise_link($contact["server_url"]);
}
if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
if (($contact["addr"] == "") && ($contact["server_url"] != "") && ($contact["nick"] != "")) {
$hostname = str_replace("http://", "", $contact["server_url"]);
$contact["addr"] = $contact["nick"]."@".$hostname;
}
@ -2179,7 +2175,7 @@ function update_gcontact($contact) {
$update = false;
unset($fields["generation"]);
if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
if ((($contact["generation"] > 0) && ($contact["generation"] <= $r[0]["generation"])) || ($r[0]["generation"] == 0)) {
foreach ($fields AS $field => $data) {
if ($contact[$field] != $r[0][$field]) {
logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
@ -2286,7 +2282,7 @@ function update_gcontact_for_user($uid) {
"gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
"birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
"notify" => $r[0]["notify"], "url" => $r[0]["url"],
"hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
"hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
"nick" => $r[0]["nickname"], "addr" => $addr,
"connect" => $addr, "server_url" => App::get_baseurl(),
"generation" => 1, "network" => NETWORK_DFRN);

View file

@ -13,7 +13,7 @@ function spool_post_run($argv, $argc) {
$path = get_spoolpath();
if (($path != '') AND is_writable($path)){
if (($path != '') && is_writable($path)){
if ($dh = opendir($path)) {
while (($file = readdir($dh)) !== false) {
@ -30,7 +30,7 @@ function spool_post_run($argv, $argc) {
}
// We can't read or write the file? So we don't care about it.
if (!is_writable($fullfile) OR !is_readable($fullfile)) {
if (!is_writable($fullfile) || !is_readable($fullfile)) {
continue;
}
@ -42,7 +42,7 @@ function spool_post_run($argv, $argc) {
}
// Skip if it doesn't seem to be an item array
if (!isset($arr['uid']) AND !isset($arr['uri']) AND !isset($arr['network'])) {
if (!isset($arr['uid']) && !isset($arr['uri']) && !isset($arr['network'])) {
continue;
}

View file

@ -31,7 +31,7 @@ function create_tags_from_item($itemid) {
$tags = "";
foreach ($taglist as $tag)
if ((substr(trim($tag), 0, 1) == "#") OR (substr(trim($tag), 0, 1) == "@"))
if ((substr(trim($tag), 0, 1) == "#") || (substr(trim($tag), 0, 1) == "@"))
$tags .= " ".trim($tag);
else
$tags .= " #".trim($tag);
@ -91,7 +91,7 @@ function create_tags_from_item($itemid) {
dbesc($link), dbesc($message["guid"]), dbesc($message["created"]), dbesc($message["received"]), intval($global));
// Search for mentions
if ((substr($tag, 0, 1) == '@') AND (strpos($link, $profile_base_friendica) OR strpos($link, $profile_base_diaspora))) {
if ((substr($tag, 0, 1) == '@') && (strpos($link, $profile_base_friendica) || strpos($link, $profile_base_diaspora))) {
$users = q("SELECT `uid` FROM `contact` WHERE self AND (`url` = '%s' OR `nurl` = '%s')", $link, $link);
foreach ($users AS $user) {
if ($user["uid"] == $message["uid"]) {

View file

@ -293,7 +293,7 @@ function paginate_data(App $a, $count = null) {
$stripped = trim($stripped, '/');
$pagenum = $a->pager['page'];
if (($a->page_offset != '') AND !preg_match('/[?&].offset=/', $stripped)) {
if (($a->page_offset != '') && !preg_match('/[?&].offset=/', $stripped)) {
$stripped .= '&offset=' . urlencode($a->page_offset);
}
@ -1276,8 +1276,8 @@ function redir_private_images($a, &$item)
function put_item_in_cache(&$item, $update = false) {
if (($item["rendered-hash"] != hash("md5", $item["body"])) OR ($item["rendered-hash"] == "") OR
($item["rendered-html"] == "") OR get_config("system", "ignore_cache")) {
if (($item["rendered-hash"] != hash("md5", $item["body"])) || ($item["rendered-hash"] == "") ||
($item["rendered-html"] == "") || get_config("system", "ignore_cache")) {
// The function "redir_private_images" changes the body.
// I'm not sure if we should store it permanently, so we save the old value.
@ -1290,7 +1290,7 @@ function put_item_in_cache(&$item, $update = false) {
$item["rendered-hash"] = hash("md5", $item["body"]);
$item["body"] = $body;
if ($update AND ($item["id"] != 0)) {
if ($update && ($item["id"] != 0)) {
q("UPDATE `item` SET `rendered-html` = '%s', `rendered-hash` = '%s' WHERE `id` = %d",
dbesc($item["rendered-html"]), dbesc($item["rendered-hash"]), intval($item["id"]));
}
@ -1352,7 +1352,7 @@ function prepare_body(&$item, $attach = false, $preview = false) {
$update = (!local_user() and !remote_user() and ($item["uid"] == 0));
// Or update it if the current viewer is the intented viewer
if (($item["uid"] == local_user()) AND ($item["uid"] != 0)) {
if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
$update = true;
}

View file

@ -45,12 +45,12 @@ function add_shadow_thread($itemid) {
$item = $items[0];
// is it already a copy?
if (($itemid == 0) OR ($item['uid'] == 0)) {
if (($itemid == 0) || ($item['uid'] == 0)) {
return;
}
// Is it a visible public post?
if (!$item["visible"] OR $item["deleted"] OR $item["moderated"] OR $item["private"]) {
if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
return;
}
@ -86,8 +86,8 @@ function add_shadow_thread($itemid) {
$item = q("SELECT * FROM `item` WHERE `id` = %d", intval($itemid));
if (count($item) AND ($item[0]["allow_cid"] == '') AND ($item[0]["allow_gid"] == '') AND
($item[0]["deny_cid"] == '') AND ($item[0]["deny_gid"] == '')) {
if (count($item) && ($item[0]["allow_cid"] == '') && ($item[0]["allow_gid"] == '') &&
($item[0]["deny_cid"] == '') && ($item[0]["deny_gid"] == '')) {
$r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = 0 LIMIT 1",
dbesc($item['uri']));

View file

@ -40,16 +40,16 @@ function update_gcontact_run(&$argv, &$argc) {
return;
}
if (($data["name"] == "") AND ($r[0]['name'] != ""))
if (($data["name"] == "") && ($r[0]['name'] != ""))
$data["name"] = $r[0]['name'];
if (($data["nick"] == "") AND ($r[0]['nick'] != ""))
if (($data["nick"] == "") && ($r[0]['nick'] != ""))
$data["nick"] = $r[0]['nick'];
if (($data["addr"] == "") AND ($r[0]['addr'] != ""))
if (($data["addr"] == "") && ($r[0]['addr'] != ""))
$data["addr"] = $r[0]['addr'];
if (($data["photo"] == "") AND ($r[0]['photo'] != ""))
if (($data["photo"] == "") && ($r[0]['photo'] != ""))
$data["photo"] = $r[0]['photo'];

View file

@ -51,7 +51,7 @@ class xml {
}
foreach($array as $key => $value) {
if (!isset($element) AND isset($xml)) {
if (!isset($element) && isset($xml)) {
$element = $xml;
}
@ -67,7 +67,7 @@ class xml {
}
$element_parts = explode(":", $key);
if ((count($element_parts) > 1) AND isset($namespaces[$element_parts[0]])) {
if ((count($element_parts) > 1) && isset($namespaces[$element_parts[0]])) {
$namespace = $namespaces[$element_parts[0]];
} elseif (isset($namespaces[""])) {
$namespace = $namespaces[""];
@ -76,18 +76,18 @@ class xml {
}
// Remove undefined namespaces from the key
if ((count($element_parts) > 1) AND is_null($namespace)) {
if ((count($element_parts) > 1) && is_null($namespace)) {
$key = $element_parts[1];
}
if (substr($key, 0, 11) == "@attributes") {
if (!isset($element) OR !is_array($value)) {
if (!isset($element) || !is_array($value)) {
continue;
}
foreach ($value as $attr_key => $attr_value) {
$element_parts = explode(":", $attr_key);
if ((count($element_parts) > 1) AND isset($namespaces[$element_parts[0]])) {
if ((count($element_parts) > 1) && isset($namespaces[$element_parts[0]])) {
$namespace = $namespaces[$element_parts[0]];
} else {
$namespace = NULL;
@ -323,7 +323,7 @@ class xml {
if ($type == "open") { // The starting of the tag '<tag>'
$parent[$level-1] = &$current;
if (!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
if (!is_array($current) || (!in_array($tag, array_keys($current)))) { // Insert New tag
$current[$tag] = $result;
if ($attributes_data) {
$current[$tag. '_attr'] = $attributes_data;
@ -399,7 +399,7 @@ class xml {
/**
* @brief Delete a node in a XML object
*
*
* @param object $doc XML document
* @param string $node Node name
*/