diff --git a/include/datetime.php b/include/datetime.php index 287e9a2d8..da454a32a 100644 --- a/include/datetime.php +++ b/include/datetime.php @@ -14,13 +14,20 @@ use \Friendica\Core\Config; * @return int */ function timezone_cmp($a, $b) { - if(strstr($a,'/') && strstr($b,'/')) { - if ( t($a) == t($b)) return 0; + if (strstr($a, '/') && strstr($b, '/')) { + if ( t($a) == t($b)) { + return 0; + } return ( t($a) < t($b)) ? -1 : 1; } - if(strstr($a,'/')) return -1; - if(strstr($b,'/')) return 1; - if ( t($a) == t($b)) return 0; + + if (strstr($a, '/')) { + return -1; + } elseif (strstr($b, '/')) { + return 1; + } elseif ( t($a) == t($b)) { + return 0; + } return ( t($a) < t($b)) ? -1 : 1; } @@ -39,23 +46,24 @@ function select_timezone($current = 'America/Los_Angeles') { usort($timezone_identifiers, 'timezone_cmp'); $continent = ''; - foreach($timezone_identifiers as $value) { + foreach ($timezone_identifiers as $value) { $ex = explode("/", $value); - if(count($ex) > 1) { - if($ex[0] != $continent) { - if($continent != '') + if (count($ex) > 1) { + if ($ex[0] != $continent) { + if ($continent != '') { $o .= ''; + } $continent = $ex[0]; $o .= ''; } - if(count($ex) > 2) + if (count($ex) > 2) { $city = substr($value,strpos($value,'/')+1); - else + } else { $city = $ex[1]; - } - else { + } + } else { $city = $ex[0]; - if($continent != t('Miscellaneous')) { + if ($continent != t('Miscellaneous')) { $o .= ''; $continent = t('Miscellaneous'); $o .= ''; @@ -114,48 +122,50 @@ function datetime_convert($from = 'UTC', $to = 'UTC', $s = 'now', $fmt = "Y-m-d // Defaults to UTC if nothing is set, but throws an exception if set to empty string. // Provide some sane defaults regardless. - if($from === '') + if ($from === '') { $from = 'UTC'; - if($to === '') + } + if ($to === '') { $to = 'UTC'; - if( ($s === '') || (! is_string($s)) ) + } + if ( ($s === '') || (! is_string($s)) ) { $s = 'now'; + } - // Slight hackish adjustment so that 'zero' datetime actually returns what is intended - // otherwise we end up with -0001-11-30 ... - // add 32 days so that we at least get year 00, and then hack around the fact that - // months and days always start with 1. + /* + * Slight hackish adjustment so that 'zero' datetime actually returns what is intended + * otherwise we end up with -0001-11-30 ... + * add 32 days so that we at least get year 00, and then hack around the fact that + * months and days always start with 1. + */ - if(substr($s,0,10) <= '0001-01-01') { + if (substr($s,0,10) <= '0001-01-01') { $d = new DateTime($s . ' + 32 days', new DateTimeZone('UTC')); return str_replace('1','0',$d->format($fmt)); } try { $from_obj = new DateTimeZone($from); - } - catch(Exception $e) { + } catch (Exception $e) { $from_obj = new DateTimeZone('UTC'); } try { $d = new DateTime($s, $from_obj); - } - catch(Exception $e) { + } catch (Exception $e) { logger('datetime_convert: exception: ' . $e->getMessage()); $d = new DateTime('now', $from_obj); } try { $to_obj = new DateTimeZone($to); - } - catch(Exception $e) { + } catch (Exception $e) { $to_obj = new DateTimeZone('UTC'); } $d->setTimeZone($to_obj); - return($d->format($fmt)); + return $d->format($fmt); } @@ -169,12 +179,14 @@ function dob($dob) { list($year,$month,$day) = sscanf($dob,'%4d-%2d-%2d'); $f = get_config('system','birthday_input_format'); - if(! $f) + if (! $f) { $f = 'ymd'; - if($dob <= '0001-01-01') + } + if ($dob <= '0001-01-01') { $value = ''; - else + } else { $value = (($year) ? datetime_convert('UTC','UTC',$dob,'Y-m-d') : datetime_convert('UTC','UTC',$dob,'m-d')); + } $age = ((intval($value)) ? age($value, $a->user["timezone"], $a->user["timezone"]) : ""); @@ -189,6 +201,7 @@ function dob($dob) { ) )); + /// @TODO Old-lost code? // if ($dob && $dob > '0001-01-01') // $o = datesel($f,mktime(0,0,0,0,0,1900),mktime(),mktime(0,0,0,$month,$day,$year),'dob'); // else @@ -214,7 +227,7 @@ function dob($dob) { * @return string Parsed HTML output. */ function datesel($format, $min, $max, $default, $id = 'datepicker') { - return datetimesel($format,$min,$max,$default,'',$id,true,false, '',''); + return datetimesel($format, $min, $max, $default, '', $id, true, false, '', ''); } /** @@ -231,8 +244,8 @@ function datesel($format, $min, $max, $default, $id = 'datepicker') { * * @return string Parsed HTML output. */ -function timesel($format, $h, $m, $id='timepicker') { - return datetimesel($format,new DateTime(),new DateTime(),new DateTime("$h:$m"),'',$id,false,true); +function timesel($format, $h, $m, $id = 'timepicker') { + return datetimesel($format, new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true); } /** @@ -267,7 +280,9 @@ function datetimesel($format, $min, $max, $default, $label, $id = 'datetimepicke // First day of the week (0 = Sunday) $firstDay = get_pconfig(local_user(),'system','first_day_of_week'); - if ($firstDay === false) $firstDay=0; + if ($firstDay === false) { + $firstDay=0; + } $lang = substr(get_browser_language(), 0, 2); @@ -279,9 +294,15 @@ function datetimesel($format, $min, $max, $default, $label, $id = 'datetimepicke $o = ''; $dateformat = ''; - if($pickdate) $dateformat .= 'Y-m-d'; - if($pickdate && $picktime) $dateformat .= ' '; - if($picktime) $dateformat .= 'H:i'; + if ($pickdate) { + $dateformat .= 'Y-m-d'; + } + if ($pickdate && $picktime) { + $dateformat .= ' '; + } + if ($picktime) { + $dateformat .= 'H:i'; + } $minjs = $min ? ",minDate: new Date({$min->getTimestamp()}*1000), yearStart: " . $min->format('Y') : ''; $maxjs = $max ? ",maxDate: new Date({$max->getTimestamp()}*1000), yearEnd: " . $max->format('Y') : ''; @@ -290,15 +311,21 @@ function datetimesel($format, $min, $max, $default, $label, $id = 'datetimepicke $defaultdatejs = $default ? ",defaultDate: new Date({$default->getTimestamp()}*1000)" : ''; $pickers = ''; - if(!$pickdate) $pickers .= ',datepicker: false'; - if(!$picktime) $pickers .= ',timepicker: false'; + if (!$pickdate) { + $pickers .= ',datepicker: false'; + } + if (!$picktime) { + $pickers .= ',timepicker: false'; + } $extra_js = ''; $pickers .= ",dayOfWeekStart: ".$firstDay.",lang:'".$lang."'"; - if($minfrom != '') + if ($minfrom != '') { $extra_js .= "\$('#id_$minfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({minDate: currentDateTime})}})"; - if($maxfrom != '') + } + if ($maxfrom != '') { $extra_js .= "\$('#id_$maxfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({maxDate: currentDateTime})}})"; + } $readable_format = $dateformat; $readable_format = str_replace('Y','yyyy',$readable_format); @@ -393,13 +420,16 @@ function relative_date($posted_date, $format = null) { * * @return int Age in years */ -function age($dob,$owner_tz = '',$viewer_tz = '') { - if(! intval($dob)) +function age($dob, $owner_tz = '', $viewer_tz = '') { + if (! intval($dob)) { return 0; - if(! $owner_tz) + } + if (! $owner_tz) { $owner_tz = date_default_timezone_get(); - if(! $viewer_tz) + } + if (! $viewer_tz) { $viewer_tz = date_default_timezone_get(); + } $birthdate = datetime_convert('UTC',$owner_tz,$dob . ' 00:00:00+00:00','Y-m-d'); list($year,$month,$day) = explode("-",$birthdate); @@ -407,8 +437,9 @@ function age($dob,$owner_tz = '',$viewer_tz = '') { $curr_month = datetime_convert('UTC',$viewer_tz,'now','m'); $curr_day = datetime_convert('UTC',$viewer_tz,'now','d'); - if(($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) + if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) { $year_diff--; + } return $year_diff; } @@ -430,11 +461,11 @@ function get_dim($y,$m) { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); - if($m != 2) + if ($m != 2) { return $dim[$m]; - - if(((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0)) + } elseif (((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0)) { return 29; + } return $dim[2]; } @@ -473,8 +504,6 @@ function get_first_dim($y,$m) { * @todo Provide (prev,next) links, define class variations for different size calendars */ function cal($y = 0,$m = 0, $links = false, $class='') { - - // month table - start at 1 to match human usage. $mtab = array(' ', @@ -486,10 +515,12 @@ function cal($y = 0,$m = 0, $links = false, $class='') { $thisyear = datetime_convert('UTC',date_default_timezone_get(),'now','Y'); $thismonth = datetime_convert('UTC',date_default_timezone_get(),'now','m'); - if(! $y) + if (! $y) { $y = $thisyear; - if(! $m) + } + if (! $m) { $m = intval($thismonth); + } $dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); $f = get_first_dim($y,$m); @@ -498,29 +529,33 @@ function cal($y = 0,$m = 0, $links = false, $class='') { $dow = 0; $started = false; - if(($y == $thisyear) && ($m == $thismonth)) + if (($y == $thisyear) && ($m == $thismonth)) { $tddate = intval(datetime_convert('UTC',date_default_timezone_get(),'now','j')); + } $str_month = day_translate($mtab[$m]); $o = ''; $o .= ""; - for($a = 0; $a < 7; $a ++) + for ($a = 0; $a < 7; $a ++) { $o .= ''; + } $o .= ''; - while($d <= $l) { - if(($dow == $f) && (! $started)) + while ($d <= $l) { + if (($dow == $f) && (! $started)) { $started = true; + } $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : ''); $o .= "'; $dow ++; - if(($dow == 7) && ($d <= $l)) { + if (($dow == 7) && ($d <= $l)) { $dow = 0; $o .= ''; } } - if($dow) - for($a = $dow; $a < 7; $a ++) + if ($dow) { + for ($a = $dow; $a < 7; $a ++) { $o .= ''; + } + } $o .= '
$str_month $y
' . mb_substr(day_translate($dn[$a]),0,3,'UTF-8') . '
"; $day = str_replace(' ',' ',sprintf('%2.2d', $d)); - if($started) { - if(is_array($links) && isset($links[$d])) + if ($started) { + if (is_array($links) && isset($links[$d])) { $o .= "$day"; - else + } else { $o .= $day; + } $d ++; } else { @@ -529,14 +564,16 @@ function cal($y = 0,$m = 0, $links = false, $class='') { $o .= '
 
'."\r\n"; diff --git a/include/dba_pdo.php b/include/dba_pdo.php index a44c447af..56692fbb3 100644 --- a/include/dba_pdo.php +++ b/include/dba_pdo.php @@ -34,7 +34,7 @@ $objDDDBLResultHandler->add('PDOStatement', array('HANDLER' => $cloPDOStatementR * */ -if(! class_exists('dba')) { +if (! class_exists('dba')) { class dba { private $debug = 0; @@ -66,9 +66,9 @@ class dba { return; } - if($install) { - if(strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) { - if(! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) { + if ($install) { + if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) { + if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) { $this->error = sprintf( t('Cannot locate DNS info for database server \'%s\''), $server); $this->connected = false; $this->db = null; @@ -81,13 +81,13 @@ class dba { \DDDBL\connect(); $this->db = \DDDBL\getDB(); - if(\DDDBL\isConnected()) { + if (\DDDBL\isConnected()) { $this->connected = true; } - if(! $this->connected) { + if (! $this->connected) { $this->db = null; - if(! $install) + if (! $install) system_unavailable(); } @@ -109,11 +109,11 @@ class dba { $objPreparedQueryPool = new \DDDBL\DataObjectPool('Query-Definition'); # check if query do not exists till now, if so create its definition - if(!$objPreparedQueryPool->exists($strQueryAlias)) + if (!$objPreparedQueryPool->exists($strQueryAlias)) $objPreparedQueryPool->add($strQueryAlias, array('QUERY' => $sql, 'HANDLER' => $strHandler)); - if((! $this->db) || (! $this->connected)) + if ((! $this->db) || (! $this->connected)) return false; $this->error = ''; @@ -124,7 +124,7 @@ class dba { $r = \DDDBL\get($strQueryAlias); # bad workaround to emulate the bizzare behavior of mysql_query - if(in_array($strSQLType, array('INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'SET'))) + if (in_array($strSQLType, array('INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'SET'))) $result = true; $intErrorCode = false; @@ -138,7 +138,7 @@ class dba { $a->save_timestamp($stamp1, "database"); - if(x($a->config,'system') && x($a->config['system'],'db_log')) { + if (x($a->config,'system') && x($a->config['system'],'db_log')) { if (($duration > $a->config["system"]["db_loglimit"])) { $duration = round($duration, 3); $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); @@ -149,20 +149,20 @@ class dba { } } - if($intErrorCode) + if ($intErrorCode) $this->error = $intErrorCode; - if(strlen($this->error)) { + if (strlen($this->error)) { logger('dba: ' . $this->error); } - if($this->debug) { + if ($this->debug) { $mesg = ''; - if($result === false) + if ($result === false) $mesg = 'false'; - elseif($result === true) + elseif ($result === true) $mesg = 'true'; else { # this needs fixing, but is a bug itself @@ -182,13 +182,13 @@ class dba { * These usually indicate SQL syntax errors that need to be resolved. */ - if(isset($result) AND ($result === false)) { + if (isset($result) AND ($result === false)) { logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error); - if(file_exists('dbfail.out')) + if (file_exists('dbfail.out')) file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND); } - if(isset($result) AND (($result === true) || ($result === false))) + if (isset($result) AND (($result === true) || ($result === false))) return $result; if ($onlyquery) { @@ -199,7 +199,7 @@ class dba { //$a->save_timestamp($stamp1, "database"); - if($this->debug) + if ($this->debug) logger('dba: ' . printable(print_r($r, true))); return($r); } @@ -223,7 +223,7 @@ class dba { } public function escape($str) { - if($this->db && $this->connected) { + if ($this->db && $this->connected) { $strQuoted = $this->db->quote($str); # this workaround is needed, because quote creates "'" and the beginning and the end # of the string, which is correct. but until now the queries set this delimiter manually, @@ -238,27 +238,27 @@ class dba { } }} -if(! function_exists('printable')) { +if (! function_exists('printable')) { function printable($s) { $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s); $s = str_replace("\x00",'.',$s); - if(x($_SERVER,'SERVER_NAME')) + if (x($_SERVER,'SERVER_NAME')) $s = escape_tags($s); return $s; }} // Procedural functions -if(! function_exists('dbg')) { +if (! function_exists('dbg')) { function dbg($state) { global $db; - if($db) + if ($db) $db->dbg($state); }} -if(! function_exists('dbesc')) { +if (! function_exists('dbesc')) { function dbesc($str) { global $db; - if($db && $db->connected) + if ($db && $db->connected) return($db->escape($str)); else return(str_replace("'","\\'",$str)); @@ -271,17 +271,17 @@ function dbesc($str) { // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d", // 'user', 1); -if(! function_exists('q')) { +if (! function_exists('q')) { function q($sql) { global $db; $args = func_get_args(); unset($args[0]); - if($db && $db->connected) { + if ($db && $db->connected) { $stmt = @vsprintf($sql,$args); // Disabled warnings //logger("dba: q: $stmt", LOGGER_ALL); - if($stmt === false) + if ($stmt === false) logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG); return $db->q($stmt); } @@ -303,11 +303,11 @@ function q($sql) { * */ -if(! function_exists('dbq')) { +if (! function_exists('dbq')) { function dbq($sql) { global $db; - if($db && $db->connected) + if ($db && $db->connected) $ret = $db->q($sql); else $ret = false; @@ -321,21 +321,21 @@ function dbq($sql) { // cast to int to avoid trouble. -if(! function_exists('dbesc_array_cb')) { +if (! function_exists('dbesc_array_cb')) { function dbesc_array_cb(&$item, $key) { - if(is_string($item)) + if (is_string($item)) $item = dbesc($item); }} -if(! function_exists('dbesc_array')) { +if (! function_exists('dbesc_array')) { function dbesc_array(&$arr) { - if(is_array($arr) && count($arr)) { + if (is_array($arr) && count($arr)) { array_walk($arr,'dbesc_array_cb'); } }} -if(! function_exists('dba_timer')) { +if (! function_exists('dba_timer')) { function dba_timer() { return microtime(true); }} diff --git a/include/dbstructure.php b/include/dbstructure.php index 1355202f9..76f1bb000 100644 --- a/include/dbstructure.php +++ b/include/dbstructure.php @@ -486,7 +486,7 @@ function db_create_table($name, $fields, $verbose, $action, $indexes=null) { $sql_rows = array(); $primary_keys = array(); - foreach($fields AS $fieldname => $field) { + foreach ($fields AS $fieldname => $field) { $sql_rows[] = "`".dbesc($fieldname)."` ".db_field_command($field); if (x($field,'primary') and $field['primary']!=''){ $primary_keys[] = $fieldname; @@ -1692,11 +1692,11 @@ function db_definition() { function dbstructure_run(&$argv, &$argc) { global $a, $db; - if(is_null($a)){ + if (is_null($a)){ $a = new App; } - if(is_null($db)) { + if (is_null($db)) { @include(".htconfig.php"); require_once("include/dba.php"); $db = new dba($db_host, $db_user, $db_pass, $db_data); @@ -1721,7 +1721,7 @@ function dbstructure_run(&$argv, &$argc) { $current = intval(DB_UPDATE_VERSION); // run any left update_nnnn functions in update.php - for($x = $stored; $x < $current; $x ++) { + for ($x = $stored; $x < $current; $x ++) { $r = run_update_function($x); if (!$r) break; } diff --git a/include/dfrn.php b/include/dfrn.php index 7221d52a2..a4651c6c8 100644 --- a/include/dfrn.php +++ b/include/dfrn.php @@ -868,7 +868,7 @@ class dfrn { // The signed text contains the content in Markdown, the sender handle and the signatur for the content // It is needed for relayed comments to Diaspora. - if($item['signed_text']) { + if ($item['signed_text']) { $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']))); xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign); } @@ -1288,7 +1288,7 @@ class dfrn { $href = ""; $width = 0; foreach ($avatar->attributes AS $attributes) { - /// @TODO Rewrite these similar if() to one switch + /// @TODO Rewrite these similar if () to one switch if ($attributes->name == "href") { $href = $attributes->textContent; } @@ -2165,7 +2165,7 @@ class dfrn { $title = ""; foreach ($links AS $link) { foreach ($link->attributes AS $attributes) { - /// @TODO Rewrite these repeated (same) if() statements to a switch() + /// @TODO Rewrite these repeated (same) if () statements to a switch() if ($attributes->name == "href") { $href = $attributes->textContent; } @@ -2415,7 +2415,7 @@ class dfrn { // When activated, forums don't work. // And: Why should we disallow commenting by followers? // the behaviour is now similar to the Diaspora part. - //if($importer["rel"] == CONTACT_IS_FOLLOWER) { + //if ($importer["rel"] == CONTACT_IS_FOLLOWER) { // logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG); // return; //} @@ -2540,7 +2540,7 @@ class dfrn { logger("Item was stored with id ".$posted_id, LOGGER_DEBUG); - if(stristr($item["verb"],ACTIVITY_POKE)) + if (stristr($item["verb"],ACTIVITY_POKE)) self::do_poke($item, $importer, $posted_id); } } @@ -2667,7 +2667,7 @@ class dfrn { create_tags_from_itemuri($uri, $importer["uid"]); create_files_from_itemuri($uri, $importer["uid"]); update_thread_uri($uri, $importer["importer_uid"]); - if($item["last-child"]) { + if ($item["last-child"]) { // ensure that last-child is set in case the comment that had it just got wiped. q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ", dbesc(datetime_convert()), diff --git a/include/diaspora.php b/include/diaspora.php index 07acbe9ea..b8eff62b1 100644 --- a/include/diaspora.php +++ b/include/diaspora.php @@ -45,7 +45,7 @@ class Diaspora { $servers = explode(",", $serverdata); - foreach($servers AS $server) { + foreach ($servers AS $server) { $server = trim($server); $addr = "relay@".str_replace("http://", "", normalise_link($server)); $batch = $server."/receive/public"; @@ -207,7 +207,7 @@ class Diaspora { $children = $basedom->children('https://joindiaspora.com/protocol'); - if($children->header) { + if ($children->header) { $public = true; $author_link = str_replace('acct:','',$children->header->author_id); } else { @@ -240,11 +240,11 @@ class Diaspora { // figure out where in the DOM tree our data is hiding - if($dom->provenance->data) + if ($dom->provenance->data) $base = $dom->provenance; - elseif($dom->env->data) + elseif ($dom->env->data) $base = $dom->env; - elseif($dom->data) + elseif ($dom->data) $base = $dom; if (!$base) { @@ -277,7 +277,7 @@ class Diaspora { $data = base64url_decode($data); - if($public) + if ($public) $inner_decrypted = $data; else { @@ -578,7 +578,7 @@ class Diaspora { logger("Fetching diaspora key for: ".$handle); $r = self::person_by_handle($handle); - if($r) + if ($r) return $r["pubkey"]; return ""; @@ -634,7 +634,7 @@ class Diaspora { */ private static function add_fcontact($arr, $update = false) { - if($update) { + if ($update) { $r = q("UPDATE `fcontact` SET `name` = '%s', `photo` = '%s', @@ -818,7 +818,7 @@ class Diaspora { // perhaps we were already sharing with this person. Now they're sharing with us. // That makes us friends. // Normally this should have handled by getting a request - but this could get lost - if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) { + if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) { q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d", intval(CONTACT_IS_FRIEND), intval($contact["id"]), @@ -828,12 +828,12 @@ class Diaspora { logger("defining user ".$contact["nick"]." as friend"); } - if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"])) + if (($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"])) return false; - if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND) + if ($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND) return true; - if($contact["rel"] == CONTACT_IS_FOLLOWER) - if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment) + if ($contact["rel"] == CONTACT_IS_FOLLOWER) + if (($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment) return true; // Messages for the global users are always accepted @@ -991,7 +991,7 @@ class Diaspora { logger("Fetch post from ".$source_url, LOGGER_DEBUG); $envelope = fetch_url($source_url); - if($envelope) { + if ($envelope) { logger("Envelope was fetched.", LOGGER_DEBUG); $x = self::verify_magic_envelope($envelope); if (!$x) @@ -1007,7 +1007,7 @@ class Diaspora { logger("Fetch post from ".$source_url, LOGGER_DEBUG); $x = fetch_url($source_url); - if(!$x) + if (!$x) return false; } @@ -1064,7 +1064,7 @@ class Diaspora { FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1", intval($uid), dbesc($guid)); - if(!$r) { + if (!$r) { $result = self::store_by_guid($guid, $contact["url"], $uid); if (!$result) { @@ -1325,7 +1325,7 @@ class Diaspora { } // If we are the origin of the parent we store the original data and notify our followers - if($message_id AND $parent_item["origin"]) { + if ($message_id AND $parent_item["origin"]) { // Formerly we stored the signed text, the signature and the author in different fields. // We now store the raw data so that we are more flexible. @@ -1502,7 +1502,7 @@ class Diaspora { intval($importer["uid"]), dbesc($guid) ); - if($c) + if ($c) $conversation = $c[0]; else { $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`) @@ -1515,13 +1515,13 @@ class Diaspora { dbesc($subject), dbesc($participants) ); - if($r) + if ($r) $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1", intval($importer["uid"]), dbesc($guid) ); - if($c) + if ($c) $conversation = $c[0]; } if (!$conversation) { @@ -1529,7 +1529,7 @@ class Diaspora { return; } - foreach($messages as $mesg) + foreach ($messages as $mesg) self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation); return true; @@ -1659,7 +1659,7 @@ class Diaspora { logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG); // If we are the origin of the parent we store the original data and notify our followers - if($message_id AND $parent_item["origin"]) { + if ($message_id AND $parent_item["origin"]) { // Formerly we stored the signed text, the signature and the author in different fields. // We now store the raw data so that we are more flexible. @@ -1834,10 +1834,10 @@ class Diaspora { $handle_parts = explode("@", $author); $nick = $handle_parts[0]; - if($name === "") + if ($name === "") $name = $handle_parts[0]; - if( preg_match("|^https?://|", $image_url) === 0) + if ( preg_match("|^https?://|", $image_url) === 0) $image_url = "http://".$handle_parts[1].$image_url; update_contact_avatar($image_url, $importer["uid"], $contact["id"]); @@ -1852,7 +1852,7 @@ class Diaspora { // this is to prevent multiple birthday notifications in a single year // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year - if(substr($birthday,5) === substr($contact["bd"],5)) + if (substr($birthday,5) === substr($contact["bd"],5)) $birthday = $contact["bd"]; $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s', @@ -1895,7 +1895,7 @@ class Diaspora { $a = get_app(); - if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) { + if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) { q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d", intval(CONTACT_IS_FRIEND), intval($contact["id"]), @@ -1908,7 +1908,7 @@ class Diaspora { intval($importer["uid"]) ); - if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) { + if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) { $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1", intval($importer["uid"]) @@ -1916,7 +1916,7 @@ class Diaspora { // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array - if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) { + if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) { $arr = array(); $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]); @@ -1947,7 +1947,7 @@ class Diaspora { $arr["deny_gid"] = $user[0]["deny_gid"]; $i = item_store($arr); - if($i) + if ($i) proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i); } } @@ -2086,12 +2086,12 @@ class Diaspora { $def_gid = get_default_group($importer['uid'], $ret["network"]); - if(intval($def_gid)) + if (intval($def_gid)) group_add_member($importer["uid"], "", $contact_record["id"], $def_gid); update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true); - if($importer["page-flags"] == PAGE_NORMAL) { + if ($importer["page-flags"] == PAGE_NORMAL) { logger("Sending intra message for author ".$author.".", LOGGER_DEBUG); @@ -2141,7 +2141,7 @@ class Diaspora { ); $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"])); - if($u) { + if ($u) { logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG); $ret = self::send_share($u[0], $contact_record); @@ -2765,7 +2765,7 @@ class Diaspora { $a = get_app(); $enabled = intval(get_config("system", "diaspora_enabled")); - if(!$enabled) + if (!$enabled) return 200; $logid = random_string(4); @@ -3104,14 +3104,14 @@ class Diaspora { $body = html_entity_decode(bb2diaspora($body)); // Adding the title - if(strlen($title)) + if (strlen($title)) $body = "## ".html_entity_decode($title)."\n\n".$body; if ($item["attach"]) { $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER); - if(cnt) { + if (cnt) { $body .= "\n".t("Attachments:")."\n"; - foreach($matches as $mtch) + foreach ($matches as $mtch) $body .= "[".$mtch[3]."](".$mtch[1].")\n"; } } @@ -3604,7 +3604,7 @@ class Diaspora { $kw = str_replace(' ',' ',$kw); $arr = explode(' ',$profile['pub_keywords']); if (count($arr)) { - for($x = 0; $x < 5; $x ++) { + for ($x = 0; $x < 5; $x ++) { if (trim($arr[$x])) $tags .= '#'. trim($arr[$x]) .' '; } @@ -3626,7 +3626,7 @@ class Diaspora { "searchable" => $searchable, "tag_string" => $tags); - foreach($recips as $recip) { + foreach ($recips as $recip) { logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG); self::build_and_transmit($profile, $recip, "profile", $message, false, "", true); } @@ -3649,17 +3649,20 @@ class Diaspora { } $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid'])); - if(!$r) + if (!dbm::is_result($r)) { return false; + } $contact["uprvkey"] = $r[0]['prvkey']; $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id)); - if (!$r) + if (!dbm::is_result($r)) { return false; + } - if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) + if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) { return false; + } $message = self::construct_like($r[0], $contact); $message["author_signature"] = self::signature($contact, $message); diff --git a/include/directory.php b/include/directory.php index 4a221fac0..41a3dd784 100644 --- a/include/directory.php +++ b/include/directory.php @@ -1,4 +1,5 @@ results)) { - foreach($j->results as $jj) { + foreach ($j->results as $jj) { // Check if the contact already exists $exists = q("SELECT `id`, `last_contact`, `last_failure`, `updated` FROM `gcontact` WHERE `nurl` = '%s'", normalise_link($jj->url)); - if ($exists) { + if (dbm::is_result($exists)) { logger("Profile ".$jj->url." already exists (".$search.")", LOGGER_DEBUG); if (($exists[0]["last_contact"] < $exists[0]["last_failure"]) AND @@ -272,12 +272,16 @@ function gs_search_user($search) { if (!$result["success"]) { return false; } + $contacts = json_decode($result["body"]); if ($contacts->status == 'ERROR') { return false; } - foreach($contacts->data AS $user) { + + /// @TODO AS is considered as a notation for constants (as they usually being written all upper-case) + /// @TODO find all those and convert to all lower-case which is a keyword then + foreach ($contacts->data AS $user) { $contact = probe_url($user->site_address."/".$user->name); if ($contact["network"] != NETWORK_PHANTOM) { $contact["about"] = $user->description; diff --git a/include/email.php b/include/email.php index 42f80c242..b8d99433e 100644 --- a/include/email.php +++ b/include/email.php @@ -4,7 +4,7 @@ require_once('include/msgclean.php'); require_once('include/quoteconvert.php'); function email_connect($mailbox,$username,$password) { - if(! function_exists('imap_open')) + if (! function_exists('imap_open')) return false; $mbox = @imap_open($mailbox,$username,$password); @@ -14,23 +14,23 @@ function email_connect($mailbox,$username,$password) { function email_poll($mbox,$email_addr) { - if(! ($mbox && $email_addr)) + if (! ($mbox && $email_addr)) return array(); $search1 = @imap_search($mbox,'FROM "' . $email_addr . '"', SE_UID); - if(! $search1) + if (! $search1) $search1 = array(); $search2 = @imap_search($mbox,'TO "' . $email_addr . '"', SE_UID); - if(! $search2) + if (! $search2) $search2 = array(); $search3 = @imap_search($mbox,'CC "' . $email_addr . '"', SE_UID); - if(! $search3) + if (! $search3) $search3 = array(); $search4 = @imap_search($mbox,'BCC "' . $email_addr . '"', SE_UID); - if(! $search4) + if (! $search4) $search4 = array(); $res = array_unique(array_merge($search1,$search2,$search3,$search4)); @@ -57,8 +57,8 @@ function email_msg_headers($mbox,$uid) { $raw_header = str_replace("\r",'',$raw_header); $ret = array(); $h = explode("\n",$raw_header); - if(count($h)) - foreach($h as $line ) { + if (count($h)) + foreach ($h as $line ) { if (preg_match("/^[a-zA-Z]/", $line)) { $key = substr($line,0,strpos($line,':')); $value = substr($line,strpos($line,':')+1); @@ -79,10 +79,10 @@ function email_get_msg($mbox,$uid, $reply) { $struc = (($mbox && $uid) ? @imap_fetchstructure($mbox,$uid,FT_UID) : null); - if(! $struc) + if (! $struc) return $ret; - if(! $struc->parts) { + if (! $struc->parts) { $ret['body'] = email_get_part($mbox,$uid,$struc,0, 'html'); $html = $ret['body']; @@ -94,7 +94,7 @@ function email_get_msg($mbox,$uid, $reply) { else { $text = ''; $html = ''; - foreach($struc->parts as $ptop => $p) { + foreach ($struc->parts as $ptop => $p) { $x = email_get_part($mbox,$uid,$p,$ptop + 1, 'plain'); if ($x) { $text .= $x; @@ -206,16 +206,16 @@ function email_get_part($mbox,$uid,$p,$partno, $subtype) { function email_header_encode($in_str, $charset) { - $out_str = $in_str; + $out_str = $in_str; $need_to_convert = false; - for($x = 0; $x < strlen($in_str); $x ++) { - if((ord($in_str[$x]) == 0) || ((ord($in_str[$x]) > 128))) { + for ($x = 0; $x < strlen($in_str); $x ++) { + if ((ord($in_str[$x]) == 0) || ((ord($in_str[$x]) > 128))) { $need_to_convert = true; } } - if(! $need_to_convert) + if (! $need_to_convert) return $in_str; if ($out_str && $charset) { diff --git a/include/enotify.php b/include/enotify.php index ebc27309d..f86174bd4 100644 --- a/include/enotify.php +++ b/include/enotify.php @@ -411,10 +411,12 @@ function notification($params) { $hash = random_string(); $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1", dbesc($hash)); - if (dbm::is_result($r)) + if (dbm::is_result($r)) { $dups = true; - } while($dups == true); + } + } while ($dups == true); + /// @TODO One statement is enough $datarray = array(); $datarray['hash'] = $hash; $datarray['name'] = $params['source_name']; diff --git a/include/event.php b/include/event.php index ebd4885c9..75fc3cf73 100644 --- a/include/event.php +++ b/include/event.php @@ -10,7 +10,7 @@ require_once 'include/datetime.php'; function format_event_html($ev, $simple = false) { - if(! ((is_array($ev)) && count($ev))) { + if (! ((is_array($ev)) && count($ev))) return ''; } @@ -98,26 +98,26 @@ function parse_event($h) { logger('parse_event: parse error: ' . $e); } - if(! $dom) + if (! $dom) return $ret; $items = $dom->getElementsByTagName('*'); - foreach($items as $item) { - if(attribute_contains($item->getAttribute('class'), 'vevent')) { + foreach ($items as $item) { + if (attribute_contains($item->getAttribute('class'), 'vevent')) { $level2 = $item->getElementsByTagName('*'); - foreach($level2 as $x) { - if(attribute_contains($x->getAttribute('class'),'dtstart') && $x->getAttribute('title')) { + foreach ($level2 as $x) { + if (attribute_contains($x->getAttribute('class'),'dtstart') && $x->getAttribute('title')) { $ret['start'] = $x->getAttribute('title'); - if(! strpos($ret['start'],'Z')) + if (! strpos($ret['start'],'Z')) $ret['adjust'] = true; } - if(attribute_contains($x->getAttribute('class'),'dtend') && $x->getAttribute('title')) + if (attribute_contains($x->getAttribute('class'),'dtend') && $x->getAttribute('title')) $ret['finish'] = $x->getAttribute('title'); - if(attribute_contains($x->getAttribute('class'),'description')) + if (attribute_contains($x->getAttribute('class'),'description')) $ret['desc'] = $x->textContent; - if(attribute_contains($x->getAttribute('class'),'location')) + if (attribute_contains($x->getAttribute('class'),'location')) $ret['location'] = $x->textContent; } } @@ -125,23 +125,23 @@ function parse_event($h) { // sanitise - if((x($ret,'desc')) && ((strpos($ret['desc'],'<') !== false) || (strpos($ret['desc'],'>') !== false))) { + if ((x($ret,'desc')) && ((strpos($ret['desc'],'<') !== false) || (strpos($ret['desc'],'>') !== false))) { $config = HTMLPurifier_Config::createDefault(); $config->set('Cache.DefinitionImpl', null); $purifier = new HTMLPurifier($config); $ret['desc'] = html2bbcode($purifier->purify($ret['desc'])); } - if((x($ret,'location')) && ((strpos($ret['location'],'<') !== false) || (strpos($ret['location'],'>') !== false))) { + if ((x($ret,'location')) && ((strpos($ret['location'],'<') !== false) || (strpos($ret['location'],'>') !== false))) { $config = HTMLPurifier_Config::createDefault(); $config->set('Cache.DefinitionImpl', null); $purifier = new HTMLPurifier($config); $ret['location'] = html2bbcode($purifier->purify($ret['location'])); } - if(x($ret,'start')) + if (x($ret,'start')) $ret['start'] = datetime_convert('UTC','UTC',$ret['start']); - if(x($ret,'finish')) + if (x($ret,'finish')) $ret['finish'] = datetime_convert('UTC','UTC',$ret['finish']); return $ret; @@ -595,7 +595,7 @@ function event_by_id($owner_uid = 0, $event_params, $sql_extra = '') { */ function events_by_date($owner_uid = 0, $event_params, $sql_extra = '') { // Only allow events if there is a valid owner_id - if($owner_uid == 0) { + if ($owner_uid == 0) { return; } diff --git a/include/expire.php b/include/expire.php index 35b109a50..098125a79 100644 --- a/include/expire.php +++ b/include/expire.php @@ -11,12 +11,13 @@ function expire_run(&$argv, &$argc){ // physically remove anything that has been deleted for more than two months - $r = q("delete from item where deleted = 1 and changed < UTC_TIMESTAMP() - INTERVAL 60 DAY"); + $r = q("DELETE FROM `item` WHERE `deleted` = 1 AND `changed` < UTC_TIMESTAMP() - INTERVAL 60 DAY"); // make this optional as it could have a performance impact on large sites - if(intval(get_config('system','optimize_items'))) - q("optimize table item"); + if (intval(get_config('system','optimize_items'))) { + q("OPTIMIZE TABLE `item`"); + } logger('expire: start');