* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
- *
+ *
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
- *
+ *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
$myurl = Config::get('blackout','url');
if (! is_string($myurl)) { $myurl = "http://www.example.com"; }
$t = get_markup_template( "admin.tpl", "addon/blackout/" );
-
- $o = replace_macros($t, array(
+
+ $o = replace_macros($t, [
'$submit' => t('Save Settings'),
- '$rurl' => array("rurl", "Redirect URL", $myurl, "all your visitors from the web will be redirected to this URL"),
- '$startdate' => array("startdate", "Begin of the Blackout<br />(YYYY-MM-DD hh:mm)", $mystart, "format is <em>YYYY</em> year, <em>MM</em> month, <em>DD</em> day, <em>hh</em> hour and <em>mm</em> minute"),
- '$enddate' => array("enddate", "End of the Blackout<br />(YYYY-MM-DD hh:mm)", $myend, ""),
+ '$rurl' => ["rurl", "Redirect URL", $myurl, "all your visitors from the web will be redirected to this URL"],
+ '$startdate' => ["startdate", "Begin of the Blackout<br />(YYYY-MM-DD hh:mm)", $mystart, "format is <em>YYYY</em> year, <em>MM</em> month, <em>DD</em> day, <em>hh</em> hour and <em>mm</em> minute"],
+ '$enddate' => ["enddate", "End of the Blackout<br />(YYYY-MM-DD hh:mm)", $myend, ""],
- ));
+ ]);
$date1 = DateTime::createFromFormat('Y-m-d G:i', $mystart);
$date2 = DateTime::createFromFormat('Y-m-d G:i', $myend);
if ($date2 < $date1) {
* Description: block people
* Version: 1.0
* Author: Mike Macgirvin <http://macgirvin.com/profile/mike>
- *
+ *
*/
use Friendica\Core\PConfig;
}
if($found) {
$rnd = random_string(8);
- $b['html'] = '<div id="blockem-wrap-' . $rnd . '" class="fakelink" onclick=openClose(\'blockem-' . $rnd . '\'); >' . sprintf( t('Blocked %s - Click to open/close'),$word ) . '</div><div id="blockem-' . $rnd . '" style="display: none; " >' . $b['html'] . '</div>';
+ $b['html'] = '<div id="blockem-wrap-' . $rnd . '" class="fakelink" onclick=openClose(\'blockem-' . $rnd . '\'); >' . sprintf( t('Blocked %s - Click to open/close'),$word ) . '</div><div id="blockem-' . $rnd . '" style="display: none; " >' . $b['html'] . '</div>';
}
}
}
if(array_key_exists('unblock',$_GET) && $_GET['unblock']) {
$arr = explode(',',$words);
- $newarr = array();
+ $newarr = [];
if(count($arr)) {
foreach($arr as $x) {
function buffer_plugin_admin(&$a, &$o){
$t = get_markup_template( "admin.tpl", "addon/buffer/" );
- $o = replace_macros($t, array(
+ $o = replace_macros($t, [
'$submit' => t('Save Settings'),
// name, label, value, help, [extra values]
- '$client_id' => array('client_id', t('Client ID'), Config::get('buffer', 'client_id' ), ''),
- '$client_secret' => array('client_secret', t('Client Secret'), Config::get('buffer', 'client_secret' ), ''),
- ));
+ '$client_id' => ['client_id', t('Client ID'), Config::get('buffer', 'client_id' ), ''],
+ '$client_secret' => ['client_secret', t('Client Secret'), Config::get('buffer', 'client_secret' ), ''],
+ ]);
}
function buffer_plugin_admin_post(&$a){
$client_id = ((x($_POST,'client_id')) ? notags(trim($_POST['client_id'])) : '');
elseif ($profile->service == "google")
$post["text"] .= html_entity_decode(" ", ENT_QUOTES, 'UTF-8'); // Send a special blank to identify the post through the "fromgplus" addon
- $message = array();
+ $message = [];
$message["text"] = $post["text"];
$message["profile_ids[]"] = $profile->id;
$message["shorten"] = false;
public $ok = false;
- private $endpoints = array(
+ private $endpoints = [
'/user' => 'get',
'/profiles' => 'get',
'/info/configuration' => 'get',
- );
+ ];
- public $errors = array(
+ public $errors = [
'invalid-endpoint' => 'The endpoint you supplied does not appear to be valid.',
'403' => 'Permission denied.',
'1042' => 'User did not save successfully.',
'1050' => 'Client could not be found.',
'1051' => 'No authorization to access client.',
- );
+ ];
function __construct($client_id = '', $client_secret = '', $callback_url = '', $access_token = '') {
if ($client_id) $this->set_client_id($client_id);
if (!$ok) return $this->error('invalid-endpoint');
}
- if (!$data || !is_array($data)) $data = array();
+ if (!$data || !is_array($data)) $data = [];
$data['access_token'] = $this->access_token;
$method = $this->endpoints[$done_endpoint]; //get() or post()
}
function error($error) {
- return (object) array('error' => $this->errors[$error]);
+ return (object) ['error' => $this->errors[$error]];
}
function create_access_token_url() {
- $data = array(
+ $data = [
'code' => $this->code,
'grant_type' => 'authorization_code',
'client_id' => $this->client_id,
'client_secret' => $this->client_secret,
'redirect_uri' => $this->callback_url,
- );
+ ];
$obj = $this->post($this->access_token_url, $data);
$this->access_token = $obj->access_token;
function req($url = '', $data = '', $post = true) {
if (!$url) return false;
- if (!$data || !is_array($data)) $data = array();
+ if (!$data || !is_array($data)) $data = [];
- $options = array(CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false);
+ $options = [CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false];
if ($post) {
- $options += array(
+ $options += [
CURLOPT_POST => $post,
CURLOPT_POSTFIELDS => $data
- );
+ ];
} else {
$url .= '?' . http_build_query($data);
}
$a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="'.$a->get_baseurl().'/addon/communityhome/communityhome.css" media="all" />';
if (!Config::get('communityhome','hidelogin')){
- $aside = array(
+ $aside = [
'$tab_1' => t('Login'),
'$tab_2' => t('OpenID'),
'$noOid' => Config::get('system','no_openid'),
- );
+ ];
// login form
$aside['$login_title'] = t('Login');
$aside['$login_form'] = Login::form($a->query_string, $a->config['register_policy'] == REGISTER_CLOSED ? false : true);
} else {
- $aside = array(
+ $aside = [
//'$tab_1' => t('Login'),
//'$tab_2' => t('OpenID'),
//'$noOid' => Config::get('system','no_openid'),
- );
+ ];
}
// last 12 users
if (Config::get('communityhome','showlastusers')){
$aside['$lastusers_title'] = t('Latest users');
- $aside['$lastusers_items'] = array();
+ $aside['$lastusers_items'] = [];
$sql_extra = "";
$publish = (Config::get('system','publish_all') ? '' : " AND `publish` = 1 " );
$order = " ORDER BY `register_date` DESC ";
$photo = 'thumb';
foreach($r as $rr) {
$profile_link = $a->get_baseurl() . '/profile/' . ((strlen($rr['nickname'])) ? $rr['nickname'] : $rr['profile_uid']);
- $entry = replace_macros($tpl,array(
+ $entry = replace_macros($tpl,[
'$id' => $rr['id'],
'$profile_link' => $profile_link,
'$photo' => $a->get_cached_avatar_image($rr[$photo]),
'$alt_text' => $rr['name'],
- ));
+ ]);
$aside['$lastusers_items'][] = $entry;
}
}
LIMIT 0,10");
if($r && count($r)) {
$aside['$activeusers_title'] = t('Most active users');
- $aside['$activeusers_items'] = array();
+ $aside['$activeusers_items'] = [];
$photo = 'thumb';
foreach($r as $rr) {
$profile_link = $a->get_baseurl() . '/profile/' . ((strlen($rr['nickname'])) ? $rr['nickname'] : $rr['profile_uid']);
- $entry = replace_macros($tpl,array(
+ $entry = replace_macros($tpl,[
'$id' => $rr['id'],
'$profile_link' => $profile_link,
'$photo' => $rr[$photo],
'$photo_user' => sprintf("%s (%s posts, %s contacts)",$rr['name'], ($rr['items']?$rr['items']:'0'), ($rr['contacts']?$rr['contacts']:'0'))
- ));
+ ]);
$aside['$activeusers_items'][] = $entry;
}
}
// last 12 photos
if (Config::get('communityhome','showlastphotos')){
$aside['$photos_title'] = t('Latest photos');
- $aside['$photos_items'] = array();
+ $aside['$photos_items'] = [];
$r = q("SELECT `photo`.`id`, `photo`.`resource-id`, `photo`.`scale`, `photo`.`desc`, `user`.`nickname`, `user`.`username` FROM
(SELECT `resource-id`, MAX(`scale`) as maxscale FROM `photo`
WHERE `profile`=0 AND `contact-id`=0 AND `album` NOT IN ('Contact Photos', '%s', 'Profile Photos', '%s')
$photo_page = $a->get_baseurl() . '/photos/' . $rr['nickname'] . '/image/' . $rr['resource-id'];
$photo_url = $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . $rr['scale'] .'.jpg';
- $entry = replace_macros($tpl,array(
+ $entry = replace_macros($tpl,[
'$id' => $rr['id'],
'$profile_link' => $photo_page,
'$photo' => $photo_url,
'$photo_user' => $rr['username'],
'$photo_title' => $rr['desc']
- ));
+ ]);
$aside['$photos_items'][] = $entry;
}
// last 10 liked items
if (Config::get('communityhome','showlastlike')){
$aside['$like_title'] = t('Latest likes');
- $aside['$like_items'] = array();
+ $aside['$like_items'] = [];
$r = q("SELECT `T1`.`created`, `T1`.`liker`, `T1`.`liker-link`, `item`.* FROM
(SELECT `parent-uri`, `created`, `author-name` AS `liker`,`author-link` AS `liker-link`
FROM `item` WHERE `verb`='http://activitystrea.ms/schema/1.0/like' GROUP BY `parent-uri` ORDER BY `created` DESC) AS T1
default:
if ($rr['resource-id']){
$post_type = t('photo');
- $m=array(); preg_match("/\[url=([^]]*)\]/", $rr['body'], $m);
+ $m=[]; preg_match("/\[url=([^]]*)\]/", $rr['body'], $m);
$rr['plink'] = $m[1];
} else {
$post_type = t('status');
}\r
\r
function convert_app_menu($a,&$b) {\r
- $b['app_menu'][] = '<div class="app-title"><a href="convert">Units Conversion</a></div>'; \r
+ $b['app_menu'][] = '<div class="app-title"><a href="convert">Units Conversion</a></div>';\r
}\r
\r
\r
function convert_content($app) {\r
\r
include("UnitConvertor.php");\r
- \r
+\r
class TP_Converter extends UnitConvertor {\r
function TP_Converter($lang = "en")\r
{\r
} else {\r
$dec_point = '.'; $thousand_sep = ",";\r
}\r
- \r
+\r
$this->UnitConvertor($dec_point , $thousand_sep );\r
\r
} // end func UnitConvertor\r
function find_base_unit($from,$to) {\r
while (list($skey,$sval) = each($this->bases)) {\r
if ($skey == $from || $to == $skey || in_array($to,$sval) || in_array($from,$sval)) {\r
- return $skey; \r
+ return $skey;\r
}\r
}\r
- return false; \r
+ return false;\r
}\r
\r
function getTable($value, $from_unit, $to_unit, $precision) {\r
- \r
+\r
if ($base_unit = $this->find_base_unit($from_unit,$to_unit)) {\r
- \r
- // A baseunit was found now lets convert from -> $base_unit \r
- \r
- $cell ['value'] = $this->convert($value, $from_unit, $base_unit, $precision)." ".$base_unit; \r
+\r
+ // A baseunit was found now lets convert from -> $base_unit\r
+\r
+ $cell ['value'] = $this->convert($value, $from_unit, $base_unit, $precision)." ".$base_unit;\r
$cell ['class'] = ($base_unit == $from_unit || $base_unit == $to_unit) ? "framedred": "";\r
$cells[] = $cell;\r
// We now have the base unit and value now lets produce the table;\r
while (list($key,$val) = each($this->bases[$base_unit])) {\r
- $cell ['value'] = $this->convert($value, $from_unit, $val, $precision)." ".$val; \r
+ $cell ['value'] = $this->convert($value, $from_unit, $val, $precision)." ".$val;\r
$cell ['class'] = ($val == $from_unit || $val == $to_unit) ? "framedred": "";\r
$cells[] = $cell;\r
}\r
}\r
$string .= "</tr></table>";\r
return $string;\r
- } \r
- \r
+ }\r
+\r
}\r
}\r
\r
$conv = new TP_Converter('en');\r
\r
\r
-$conversions = array(\r
- 'Temperature'=>array('base' =>'Celsius',\r
- 'conv'=>array(\r
- 'Fahrenheit'=>array('ratio'=>1.8, 'offset'=>32),\r
- 'Kelvin'=>array('ratio'=>1, 'offset'=>273),\r
+$conversions = [\r
+ 'Temperature'=>['base' =>'Celsius',\r
+ 'conv'=>[\r
+ 'Fahrenheit'=>['ratio'=>1.8, 'offset'=>32],\r
+ 'Kelvin'=>['ratio'=>1, 'offset'=>273],\r
'Reaumur'=>0.8\r
- )\r
- ),\r
- 'Weight' => array('base' =>'kg',\r
- 'conv'=>array(\r
+ ]\r
+ ],\r
+ 'Weight' => ['base' =>'kg',\r
+ 'conv'=>[\r
'g'=>1000,\r
'mg'=>1000000,\r
't'=>0.001,\r
'oz'=>35.274,\r
'lb'=>2.2046,\r
'cwt(UK)' => 0.019684,\r
- 'cwt(US)' => 0.022046, \r
+ 'cwt(US)' => 0.022046,\r
'ton (US)' => 0.0011023,\r
'ton (UK)' => 0.0009842\r
- )\r
- ),\r
- 'Distance' => array('base' =>'km',\r
- 'conv'=>array(\r
+ ]\r
+ ],\r
+ 'Distance' => ['base' =>'km',\r
+ 'conv'=>[\r
'm'=>1000,\r
'dm'=>10000,\r
'cm'=>100000,\r
'yd'=>1093.6,\r
'furlong'=>4.970969537898672,\r
'fathom'=>546.8066491688539\r
- )\r
- ),\r
- 'Area' => array('base' =>'km 2',\r
- 'conv'=>array( \r
+ ]\r
+ ],\r
+ 'Area' => ['base' =>'km 2',\r
+ 'conv'=>[\r
'ha'=>100,\r
'acre'=>247.105,\r
'm 2'=>pow(1000,2),\r
'dm 2'=>pow(10000,2),\r
'cm 2'=>pow(100000,2),\r
- 'mm 2'=>pow(1000000,2), \r
+ 'mm 2'=>pow(1000000,2),\r
'mile 2'=>pow(0.62137,2),\r
'naut.miles 2'=>pow(0.53996,2),\r
'in 2'=>pow(39370,2),\r
'ft 2'=>pow(3280.8,2),\r
'yd 2'=>pow(1093.6,2),\r
- )\r
- ),\r
- 'Volume' => array('base' =>'m 3',\r
- 'conv'=>array(\r
+ ]\r
+ ],\r
+ 'Volume' => ['base' =>'m 3',\r
+ 'conv'=>[\r
'in 3'=>61023.6,\r
'ft 3'=>35.315,\r
'cm 3'=>pow(10,6),\r
'fl oz' => 33814.02,\r
'tablespoon' => 67628.04,\r
'teaspoon' => 202884.1,\r
- 'pt (UK)'=>1000/0.56826, \r
+ 'pt (UK)'=>1000/0.56826,\r
'barrel petroleum'=>1000/158.99,\r
- 'Register Tons'=>2.832, \r
+ 'Register Tons'=>2.832,\r
'Ocean Tons'=>1.1327\r
- )\r
- ),\r
- 'Speed' =>array('base' =>'kmph',\r
- 'conv'=>array(\r
+ ]\r
+ ],\r
+ 'Speed' =>['base' =>'kmph',\r
+ 'conv'=>[\r
'mps'=>0.0001726031,\r
'milesph'=>0.62137,\r
'knots'=>0.53996,\r
'mach STP'=>0.0008380431,\r
'c (warp)'=>9.265669e-10\r
- )\r
- )\r
-);\r
+ ]\r
+ ]\r
+];\r
\r
\r
while (list($key,$val) = each($conversions)) {\r
$o .= '</select>';\r
\r
$o .= '<input type="submit" name="Submit" value="Submit" /></form>';\r
- \r
+\r
return $o;\r
}\r
<?php
/**
- * Name: Current Weather
+ * Name: Current Weather
* Description: Shows current weather conditions for user's location on their network page.
* Version: 1.1
* Author: Tony Baldwin <http://friendica.tonybaldwin.info/u/t0ny>
} else {
$desc = (string)$res->weather['value'].', '.(string)$res->clouds['name'];
}
- $r = array(
+ $r = [
'city'=> (string) $res->city['name'][0],
'country' => (string) $res->city->country[0],
'lat' => (string) $res->city->coord['lat'],
'wind' => (string)$res->wind->speed['name'].' ('.(string)$res->wind->speed['value'].$wunit.')',
'update' => (string)$res->lastupdate['value'],
'icon' => (string)$res->weather['icon']
- );
+ ];
PConfig::set(local_user(), 'curweather', 'last', $now->getTimestamp());
Cache::set('curweather'.md5($url), serialize($r), CACHE_HOUR);
return $r;
if ($ok) {
$t = get_markup_template("widget.tpl", "addon/curweather/" );
- $curweather = replace_macros ($t, array(
+ $curweather = replace_macros ($t, [
'$title' => t("Current Weather"),
'$icon' => proxy_url('http://openweathermap.org/img/w/'.$res['icon'].'.png'),
'$city' => $res['city'],
'$lat' => $res['lat'],
'$description' => $res['descripion'],
'$temp' => $res['temperature'],
- '$relhumidity' => array('caption'=>t('Relative Humidity'), 'val'=>$res['humidity']),
- '$pressure' => array('caption'=>t('Pressure'), 'val'=>$res['pressure']),
- '$wind' => array('caption'=>t('Wind'), 'val'=> $res['wind']),
+ '$relhumidity' => ['caption'=>t('Relative Humidity'), 'val'=>$res['humidity']],
+ '$pressure' => ['caption'=>t('Pressure'), 'val'=>$res['pressure']],
+ '$wind' => ['caption'=>t('Wind'), 'val'=> $res['wind']],
'$lastupdate' => t('Last Updated').': '.$res['update'].'UTC',
'$databy' => t('Data by'),
'$showonmap' => t('Show on map')
- ));
+ ]);
} else {
$t = get_markup_template('widget-error.tpl', 'addon/curweather/');
- $curweather = replace_macros( $t, array(
+ $curweather = replace_macros( $t, [
'$problem' => t('There was a problem accessing the weather data. But have a look'),
'$rpt' => $rpt,
'$atOWM' => t('at OpenWeatherMap')
- ));
+ ]);
}
$fk_app->page['aside'] = $curweather.$fk_app->page['aside'];
$curweather_loc = PConfig::get(local_user(), 'curweather', 'curweather_loc');
$curweather_units = PConfig::get(local_user(), 'curweather', 'curweather_units');
$appid = Config::get('curweather','appid');
- if ($appid=="") {
+ if ($appid=="") {
$noappidtext = t('No APPID found, please contact your admin to obtain one.');
} else {
$noappidtext = '';
}
$enable = intval(PConfig::get(local_user(),'curweather','curweather_enable'));
$enable_checked = (($enable) ? ' checked="checked" ' : '');
-
+
// load template and replace the macros
$t = get_markup_template("settings.tpl", "addon/curweather/" );
- $s = replace_macros ($t, array(
- '$submit' => t('Save Settings'),
+ $s = replace_macros ($t, [
+ '$submit' => t('Save Settings'),
'$header' => t('Current Weather').' '.t('Settings'),
'$noappidtext' => $noappidtext,
'$info' => t('Enter either the name of your location or the zip code.'),
- '$curweather_loc' => array( 'curweather_loc', t('Your Location'), $curweather_loc, t('Identifier of your location (name or zip code), e.g. <em>Berlin,DE</em> or <em>14476,DE</em>.') ),
- '$curweather_units' => array( 'curweather_units', t('Units'), $curweather_units, t('select if the temperature should be displayed in °C or °F'), array('metric'=>'°C', 'imperial'=>'°F')),
- '$enabled' => array( 'curweather_enable', t('Show weather data'), $enable, '')
- ));
+ '$curweather_loc' => [ 'curweather_loc', t('Your Location'), $curweather_loc, t('Identifier of your location (name or zip code), e.g. <em>Berlin,DE</em> or <em>14476,DE</em>.') ],
+ '$curweather_units' => [ 'curweather_units', t('Units'), $curweather_units, t('select if the temperature should be displayed in °C or °F'), ['metric'=>'°C', 'imperial'=>'°F']],
+ '$enabled' => [ 'curweather_enable', t('Show weather data'), $enable, '']
+ ]);
return;
}
$appid = Config::get('curweather','appid');
$cachetime = Config::get('curweather','cachetime');
$t = get_markup_template("admin.tpl", "addon/curweather/" );
- $o = replace_macros ($t, array(
+ $o = replace_macros ($t, [
'$submit' => t('Save Settings'),
- '$cachetime' => array('cachetime', t('Caching Interval'), $cachetime, t('For how long should the weather data be cached? Choose according your OpenWeatherMap account type.'), array('0'=>t('no cache'), '300'=>'5 '.t('minutes'), '900'=>'15 '.t('minutes'), '1800'=>'30 '.t('minutes'), '3600'=>'60 '.t('minutes'))),
- '$appid' => array('appid', t('Your APPID'), $appid, t('Your API key provided by OpenWeatherMap'))
- ));
+ '$cachetime' => ['cachetime', t('Caching Interval'), $cachetime, t('For how long should the weather data be cached? Choose according your OpenWeatherMap account type.'), ['0'=>t('no cache'), '300'=>'5 '.t('minutes'), '900'=>'15 '.t('minutes'), '1800'=>'30 '.t('minutes'), '3600'=>'60 '.t('minutes')]],
+ '$appid' => ['appid', t('Your APPID'), $appid, t('Your API key provided by OpenWeatherMap')]
+ ]);
}
define("CALDAV_FRIENDICA_MINE", "friendica-mine");
define("CALDAV_FRIENDICA_CONTACTS", "friendica-contacts");
-$GLOBALS["CALDAV_PRIVATE_SYSTEM_CALENDARS"] = array(CALDAV_FRIENDICA_MINE, CALDAV_FRIENDICA_CONTACTS);
-$GLOBALS["CALDAV_PRIVATE_SYSTEM_BACKENDS"] = array("Sabre_CalDAV_Backend_Friendica");
+$GLOBALS["CALDAV_PRIVATE_SYSTEM_CALENDARS"] = [CALDAV_FRIENDICA_MINE, CALDAV_FRIENDICA_CONTACTS];
+$GLOBALS["CALDAV_PRIVATE_SYSTEM_BACKENDS"] = ["Sabre_CalDAV_Backend_Friendica"];
define("CARDDAV_NAMESPACE_PRIVATE", 1);
define("CARDDAV_FRIENDICA_CONTACT", "friendica");
-$GLOBALS["CARDDAV_PRIVATE_SYSTEM_ADDRESSBOOKS"] = array(CARDDAV_FRIENDICA_CONTACT);
-$GLOBALS["CARDDAV_PRIVATE_SYSTEM_BACKENDS"] = array("Sabre_CardDAV_Backend_Friendica");
+$GLOBALS["CARDDAV_PRIVATE_SYSTEM_ADDRESSBOOKS"] = [CARDDAV_FRIENDICA_CONTACT];
+$GLOBALS["CARDDAV_PRIVATE_SYSTEM_BACKENDS"] = ["Sabre_CardDAV_Backend_Friendica"];
$GLOBALS["CALDAV_ACL_PLUGIN_CLASS"] = "Sabre_DAVACL_Plugin_Friendica";
if (strpos($principalUri, "principals/users/") !== 0) return null;
$username = substr($principalUri, strlen("principals/users/"));
- return array("namespace" => CALDAV_NAMESPACE_PRIVATE, "namespace_id" => dav_compat_username2id($username));
+ return ["namespace" => CALDAV_NAMESPACE_PRIVATE, "namespace_id" => dav_compat_username2id($username)];
}
*/
function wdcal_create_std_calendars_get_statements($user_id, $withcheck = true)
{
- $stms = array();
+ $stms = [];
$a = get_app();
- $uris = array(
+ $uris = [
'private' => t("Private Calendar"),
CALDAV_FRIENDICA_MINE => t("Friendica Events: Mine"),
CALDAV_FRIENDICA_CONTACTS => t("Friendica Events: Contacts"),
- );
+ ];
foreach ($uris as $uri => $name) {
$cals = q("SELECT * FROM %s%scalendars WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CALDAV_NAMESPACE_PRIVATE, IntVal($user_id), dbesc($uri));
*/
function wdcal_create_std_addressbooks_get_statements($user_id, $withcheck = true)
{
- $stms = array();
+ $stms = [];
$a = get_app();
- $uris = array(
+ $uris = [
'private' => t("Private Addresses"),
CARDDAV_FRIENDICA_CONTACT => t("Friendica Contacts"),
- );
+ ];
foreach ($uris as $uri => $name) {
$cals = q("SELECT * FROM %s%saddressbooks WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CALDAV_NAMESPACE_PRIVATE, IntVal($user_id), dbesc($uri));
*/
function dav_get_update_statements($from_version)
{
- $stms = array();
+ $stms = [];
if ($from_version == 1) {
$stms[] = "ALTER TABLE `dav_calendarobjects`
`dav_locks` ,
`dav_notifications` ;";
- $stms = array_merge($stms, dav_get_create_statements(array("dav_calendarobjects")));
+ $stms = array_merge($stms, dav_get_create_statements(["dav_calendarobjects"]));
$user_ids = q("SELECT DISTINCT `uid` FROM %s%scalendars", CALDAV_SQL_DB, CALDAV_SQL_PREFIX);
foreach ($user_ids as $user) $stms = array_merge($stms, wdcal_create_std_calendars_get_statements($user["uid"], false));
}
- if (in_array($from_version, array(1, 2))) {
+ if (in_array($from_version, [1, 2])) {
$stms[] = "CREATE TABLE IF NOT EXISTS `dav_addressbooks` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`namespace` mediumint(9) NOT NULL,
* @param array $except
* @return array
*/
-function dav_get_create_statements($except = array())
+function dav_get_create_statements($except = [])
{
- $arr = array();
+ $arr = [];
if (!in_array("dav_caldav_log", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_caldav_log` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
function dav_create_tables()
{
$stms = dav_get_create_statements();
- $errors = array();
+ $errors = [];
foreach ($stms as $st) { // @TODO Friendica-dependent
dba::e($st);
function dav_upgrade_tables()
{
$ver = dav_check_tables();
- if (!in_array($ver, array(1, 2))) return array("Unknown error");
+ if (!in_array($ver, [1, 2])) return ["Unknown error"];
$stms = dav_get_update_statements($ver);
- $errors = array();
+ $errors = [];
foreach ($stms as $st) { // @TODO Friendica-dependent
dba::e($st);
$summary = (($row["summary"]) ? $row["summary"] : substr(preg_replace("/\[[^\]]*\]/", "", $row["desc"]), 0, 100));
- return array(
+ return [
"jq_id" => $row["id"],
"ev_id" => $row["id"],
"summary" => escape_tags($summary),
"url_detail" => $base_path . "/events/event/" . $row["id"],
"url_edit" => "",
"special_type" => ($row["type"] == "birthday" ? "birthday" : ""),
- );
+ ];
}
if (is_numeric($date_to)) $sql_where .= " AND `start` <= '" . date("Y-m-d H:i:s", $date_to) . "'";
else $sql_where .= " AND `start` <= '" . dbesc($date_to) . "'";
}
- $ret = array();
+ $ret = [];
$r = q("SELECT * FROM `event` WHERE `uid` = %d " . $sql_where . " ORDER BY `start`", IntVal($calendar["namespace_id"]));
public function getCalendarsForUser($principalUri)
{
$n = dav_compat_principal2namespace($principalUri);
- if ($n["namespace"] != $this->getNamespace()) return array();
+ if ($n["namespace"] != $this->getNamespace()) return [];
$cals = q("SELECT * FROM %s%scalendars WHERE `namespace` = %d AND `namespace_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $this->getNamespace(), IntVal($n["namespace_id"]));
- $ret = array();
+ $ret = [];
foreach ($cals as $cal) {
if (!in_array($cal["uri"], $GLOBALS["CALDAV_PRIVATE_SYSTEM_CALENDARS"])) continue;
- $dat = array(
+ $dat = [
"id" => $cal["id"],
"uri" => $cal["uri"],
"principaluri" => $principalUri,
'{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}getctag' => $cal['ctag'] ? $cal['ctag'] : '0',
- '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet(array("VEVENT")),
+ '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet(["VEVENT"]),
"calendar_class" => "Sabre_CalDAV_Calendar_Virtual",
- );
+ ];
foreach ($this->propertyMap as $key=> $field) $dat[$key] = $cal[$field];
$ret[] = $dat;
{
$uid = dav_compat_principal2uid($principalUri);
- $addressBooks = array();
+ $addressBooks = [];
$books = q("SELECT id, ctag FROM %s%saddressbooks WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CARDDAV_NAMESPACE_PRIVATE, IntVal($uid), dbesc(CARDDAV_FRIENDICA_CONTACT));
$ctag = $books[0]["ctag"];
- $addressBooks[] = array(
+ $addressBooks[] = [
'id' => $books[0]["id"],
'uri' => "friendica",
'principaluri' => $principalUri,
'{http://calendarserver.org/ns/}getctag' => $ctag,
'{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data' =>
new Sabre_CardDAV_Property_SupportedAddressData(),
- );
+ ];
return $addressBooks;
{
$name = explode(" ", $contact["name"]);
$first_name = $last_name = "";
- $middle_name = array();
+ $middle_name = [];
$num = count($name);
for ($i = 0; $i < $num && $first_name == ""; $i++) if ($name[$i] != "") {
$first_name = $name[$i];
}
$vcard = vcard_source_compile($vcarddata);
- return array(
+ return [
"id" => $contact["id"],
"carddata" => $vcard,
"uri" => $contact["id"] . ".vcf",
"lastmodified" => wdcal_mySql2PhpTime($vcarddata->last_update),
"etag" => md5($vcard),
"size" => strlen($vcard),
- );
+ ];
}
*/
public function getUsers()
{
- return array($this->currentUser);
+ return [$this->currentUser];
}
/**
{
// This backend only support principals in one collection
- if ($prefixPath !== $this->prefix) return array();
+ if ($prefixPath !== $this->prefix) return [];
- $users = array();
+ $users = [];
$r = q("SELECT `nickname` FROM `user` WHERE `nickname` = '%s'", escape_tags($this->authBackend->getCurrentUser()) );
foreach ($r as $t) {
- $users[] = array(
+ $users[] = [
'uri' => $this->prefix . '/' . strtolower($t['nickname']),
'{DAV:}displayname' => $t['nickname'],
- );
+ ];
}
return $users;
if ($prefixPath !== $this->prefix) return null;
$r = q("SELECT `nickname` FROM `user` WHERE `nickname` = '%s'", escape_tags($userName) );
- if (count($r) == 0) return array();
+ if (count($r) == 0) return [];
- return array(
+ return [
'uri' => $this->prefix . '/' . strtolower($r[0]['nickname']),
'{DAV:}displayname' => $r[0]['nickname'],
- );
+ ];
}
function getGroupMemberSet($principal)
{
- return array();
+ return [];
}
function getGroupMembership($principal)
{
- return array();
+ return [];
}
/** @var Sabre\VObject\Component\VCalendar $vObject */
$vObject = Sabre\VObject\Reader::read($text);
$comp = $vObject->getComponents();
- $imported = array();
+ $imported = [];
foreach ($comp as $c) try {
/** @var Sabre\VObject\Component\VEvent $c */
$uid = $c->__get("UID")->value;
* @param bool $show_nav
* @return string
*/
-function wdcal_printCalendar($calendars, $calendars_selected, $data_feed_url, $view = "week", $theme = 0, $height_diff = 175, $readonly = false, $curr_day = "", $add_params = array(), $show_nav = true)
+function wdcal_printCalendar($calendars, $calendars_selected, $data_feed_url, $view = "week", $theme = 0, $height_diff = 175, $readonly = false, $curr_day = "", $add_params = [], $show_nav = true)
{
$a = get_app();
$localization = wdcal_local::getInstanceByUser($a->user["uid"]);
if (count($calendars_selected) == 0) foreach ($calendars as $c) {
- $prop = $c->getProperties(array("id"));
+ $prop = $c->getProperties(["id"]);
$calendars_selected[] = $prop["id"];
}
- $opts = array(
+ $opts = [
"view" => $view,
"theme" => $theme,
"readonly" => $readonly,
"date_format_dm3" => $localization->dateformat_js_dm3(),
"date_format_full" => $localization->dateformat_datepicker_js(),
"baseurl" => $a->get_baseurl() . "/dav/wdcal/",
- );
+ ];
$x = '
<script>
<div class="calselect"><strong>Available Calendars:</strong>';
foreach ($calendars as $cal) {
- $cal_id = $cal->getProperties(array("id", DAV_DISPLAYNAME));
+ $cal_id = $cal->getProperties(["id", DAV_DISPLAYNAME]);
$x .= '<label style="margin-left: 10px; margin-right: 10px;"><input type="checkbox" name="cals[]" value="' . $cal_id["id"] . '"';
$found = false;
foreach ($calendars_selected as $pre) if ($pre["id"] == $cal_id["id"]) $found = true;
} else {
$server = dav_create_server(true, true, false);
$cals = dav_get_current_user_calendars($server, DAV_ACL_READ);
- $x = wdcal_printCalendar($cals, array(), $a->get_baseurl() . "/dav/wdcal/feed/", "week", 0, 200);
+ $x = wdcal_printCalendar($cals, [], $a->get_baseurl() . "/dav/wdcal/feed/", "week", 0, 200);
}
}
} catch (DAVVersionMismatchException $e) {
*/
function dav_profile_tabs_hook(&$a, &$b)
{
- $b["tabs"][] = array(
+ $b["tabs"][] = [
"label" => t('Calendar'),
"url" => $a->get_baseurl() . "/dav/wdcal/",
"sel" => "",
"title" => t('Extended calendar with CalDAV-support'),
- );
+ ];
}
q("UPDATE %s%snotifications SET `notified` = 1 WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $not["id"]);
$event = q("SELECT * FROM %s%sjqcalendar WHERE `calendarobject_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $not["calendarobject_id"]);
$calendar = q("SELECT * FROM %s%scalendars WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $not["calendar_id"]);
- $users = array();
+ $users = [];
if (count($calendar) != 1 || count($event) == 0) continue;
switch ($calendar[0]["namespace"]) {
case CALDAV_NAMESPACE_PRIVATE:
case "email":
case "display": // @TODO implement "Display"
foreach ($users as $user) {
- $find = array("%to%", "%event%", "%url%");
- $repl = array($user["username"], $event[0]["Summary"], $a->get_baseurl() . "/dav/wdcal/" . $calendar[0]["id"] . "/" . $not["calendarobject_id"] . "/");
+ $find = ["%to%", "%event%", "%url%"];
+ $repl = [$user["username"], $event[0]["Summary"], $a->get_baseurl() . "/dav/wdcal/" . $calendar[0]["id"] . "/" . $not["calendarobject_id"] . "/"];
$text_text = str_replace($find, $repl, "Hi %to%!\n\nThe event \"%event%\" is about to begin:\n%url%");
$text_html = str_replace($find, $repl, "Hi %to%!<br>\n<br>\nThe event \"%event%\" is about to begin:<br>\n<a href='" . "%url%" . "'>%url%</a>");
- $params = array(
+ $params = [
'fromName' => FRIENDICA_PLATFORM,
'fromEmail' => t('noreply') . '@' . $a->get_hostname(),
'replyTo' => t('noreply') . '@' . $a->get_hostname(),
'htmlVersion' => $text_html,
'textVersion' => $text_text,
'additionalMailHeader' => "",
- );
+ ];
Emailer::send($params);
}
break;
return ($this->tls) ? 'https' : 'http';
}
- private function doHttpRequest($url, $data = array(), $headers = array()) {
+ private function doHttpRequest($url, $data = [], $headers = []) {
if (0 === strpos($url, '/')) {
$url = $this->getScheme() . '://' . $this->host . $url;
}
return $this->last_http_result;
}
- private function doHttpDelete($url, $data = array(), $headers = array()) {
+ private function doHttpDelete($url, $data = [], $headers = []) {
$this->http_method = 'DELETE';
$this->doHttpRequest($url, $data, $headers);
$this->http_method = null; // reset for next request
}
private function parseAuthenticityToken($str) {
- $m = array();
+ $m = [];
preg_match('/<meta (?:name="csrf-token" content="(.*?)"|content="(.*?)" name="csrf-token")/', $str, $m);
if (empty($m[1]) && !empty($m[2])) {
$token = $m[2];
public function logIn() {
$this->doHttpRequest('/users/sign_in');
- $params = array(
+ $params = [
'user[username]' => $this->user,
'user[password]' => $this->password,
'authenticity_token' => $this->csrf_token
- );
+ ];
$this->doHttpRequest('/users/sign_in', $params);
$this->doHttpRequest('/stream');
return (200 === $this->last_http_result->info['http_code']) ? true : false;
public function getAspects() {
$this->doHttpRequest('/bookmarklet');
- $m = array();
+ $m = [];
preg_match('/"aspects"\:(\[.+?\])/', $this->last_http_result->response, $m);
return (!empty($m[1])) ? json_decode($m[1]) : false;
}
public function getServices() {
$this->doHttpRequest('/bookmarklet');
- $m = array();
+ $m = [];
preg_match('/"configured_services"\:(\[.+?\])/', $this->last_http_result->response, $m);
return (!empty($m[1])) ? json_decode($m[1]) : false;
}
return $this->readJsonResponse($this->last_http_result->response);
}
- public function postStatusMessage($msg, $aspect_ids = 'all_aspects', $additional_data = array()) {
- $data = array(
+ public function postStatusMessage($msg, $aspect_ids = 'all_aspects', $additional_data = []) {
+ $data = [
'aspect_ids' => $aspect_ids,
- 'status_message' => array(
+ 'status_message' => [
'text' => $msg,
'provider_display_name' => $this->provider
- )
- );
+ ]
+ ];
if (!empty($additional_data)) {
$data += $additional_data;
}
- $headers = array(
+ $headers = [
'Content-Type: application/json',
'Accept: application/json',
'X-CSRF-Token: ' . $this->csrf_token
- );
+ ];
$this->http_method = 'POST';
$this->doHttpRequest('/status_messages', json_encode($data), $headers);
}
public function postPhoto($file) {
- $params = array(
+ $params = [
'photo[pending]' => 'true',
'qqfile' => basename($file)
- );
+ ];
$query_string = '?' . http_build_query($params);
- $headers = array(
+ $headers = [
'Accept: application/json',
'X-Requested-With: XMLHttpRequest',
'X-CSRF-Token: ' . $this->csrf_token,
'X-File-Name: ' . basename($file),
'Content-Type: application/octet-stream',
- );
+ ];
if ($size = @filesize($file)) {
$headers[] = "Content-Length: $size";
}
}
public function deletePost($id) {
- $headers = array('X-CSRF-Token: ' . $this->csrf_token);
- $this->doHttpDelete("/posts/$id", array(), $headers);
+ $headers = ['X-CSRF-Token: ' . $this->csrf_token];
+ $this->doHttpDelete("/posts/$id", [], $headers);
return (204 === $this->last_http_result->info['http_code']) ? true : false;
}
public function deleteComment($id) {
- $headers = array('X-CSRF-Token: ' . $this->csrf_token);
- $this->doHttpDelete("/comments/$id", array(), $headers);
+ $headers = ['X-CSRF-Token: ' . $this->csrf_token];
+ $this->doHttpDelete("/comments/$id", [], $headers);
return (204 === $this->last_http_result->info['http_code']) ? true : false;
}
logger('diaspora_send: all values seem to be okay', LOGGER_DEBUG);
require_once('include/bb2diaspora.php');
- $tag_arr = array();
+ $tag_arr = [];
$tags = '';
$x = preg_match_all('/\#\[(.*?)\](.*?)\[/',$b['tag'],$matches,PREG_SET_ORDER);
if (count($r))
$a->contact = $r[0]["id"];
- $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $body));
+ $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $body]);
require_once('include/queue_fn.php');
add_to_queue($a->contact,NETWORK_DIASPORA2,$s);
notice(t('Diaspora post failed. Queued for retry.').EOL);
if($b['parent'] != $b['id'])
return;
- // dreamwidth post in the LJ user's timezone.
+ // dreamwidth post in the LJ user's timezone.
// Hopefully the person's Friendica account
// will be set to the same thing.
intval($b['uid'])
);
if($x && strlen($x[0]['timezone']))
- $tz = $x[0]['timezone'];
+ $tz = $x[0]['timezone'];
$dw_username = PConfig::get($b['uid'],'dwpost','dw_username');
$dw_password = PConfig::get($b['uid'],'dwpost','dw_password');
logger('dwpost: data: ' . $xml, LOGGER_DATA);
if($dw_blog !== 'test')
- $x = post_url($dw_blog,$xml,array("Content-Type: text/xml"));
+ $x = post_url($dw_blog,$xml,["Content-Type: text/xml"]);
logger('posted to dreamwidth: ' . ($x) ? $x : '', LOGGER_DEBUG);
}
$adult = 0;
$length = (($_GET['length']) ? intval($_GET['length']) : 0);
-$numlines = ((intval($_GET['numlines'])) ? intval($_GET['numlines']) : 0);
+$numlines = ((intval($_GET['numlines'])) ? intval($_GET['numlines']) : 0);
$cat = (($_GET['cat'] == '1') ? 1 : 0);
$equal = (($_GET['equal'] == '1') ? 1 : 0);
$stats = (($_GET['stats'] == '1') ? 1 : 0);
function do_query($table,$length,$numlines,$adult,$cat,$limit,$lang,$pattern,$regex,$equal) {
global $db;
$rnd = mt_rand();
- $r = array();
+ $r = [];
$typesql = (($table) ? " WHERE `category` = '$table' " : " WHERE 1 ");
$lengthsql = (($length) ? " AND LENGTH(`text`) < $length " : "" );
$eqsql = '';
if($equal) {
- $catsavail = array();
- $res = @$db->query("SELECT DISTINCT ( `category` ) FROM `fortune`
+ $catsavail = [];
+ $res = @$db->query("SELECT DISTINCT ( `category` ) FROM `fortune`
$typesql
$adultsql
$lengthsql
$langsql
- $patsql
+ $patsql
$regexsql ");
if($res->num_rows) {
while($x = $res->fetch_array(MYSQL_ASSOC))
$catsavail[] = $x['category'];
-
+
$eqsql = " AND `category` = '"
. $catsavail[mt_rand(0,$res->num_rows - 1)] . "' ";
}
}
- $result = @$db->query("SELECT `text`, `category` FROM `fortune`
+ $result = @$db->query("SELECT `text`, `category` FROM `fortune`
$typesql
$adultsql
$lengthsql
$patsql
$regexsql
$eqsql
- ORDER BY RAND($rnd)
+ ORDER BY RAND($rnd)
LIMIT $limit");
if($result->num_rows) {
function do_stats($table,$length,$numlines,$adult,$cat,$limit,$lang,$pattern,$regex,$equal) {
global $db;
$rnd = mt_rand();
- $r = array();
+ $r = [];
$typesql = (($table) ? " WHERE `category` = '$table' " : " WHERE 1 ");
$lengthsql = (($length) ? " AND LENGTH(`text`) < $length " : "" );
$eqsql = '';
- $result = @$db->query("SELECT `text`, `category` FROM `fortune`
+ $result = @$db->query("SELECT `text`, `category` FROM `fortune`
$typesql
$adultsql
$lengthsql
echo '<br />' . $result->num_rows . ' matching quotations.<br />';
- $res = @$db->query("SELECT DISTINCT ( `category` ) FROM `fortune`
+ $res = @$db->query("SELECT DISTINCT ( `category` ) FROM `fortune`
$typesql
$adultsql
$lengthsql
$langsql
- $patsql
+ $patsql
$regexsql ");
if($res->num_rows) {
echo '<br />Matching Databases:<br />';
while($x = $res->fetch_array(MYSQL_ASSOC))
echo $x['category'].'<br />';
-
+
}
else
echo '<br />No matching databases using those search parameters - please refine your options.<br />';
-
+
}
// So for now, just remove them.
$s = str_replace(
- array("&",
+ ["&",
"<",
">",
'"',
"\007",
"\t",
"\r",
- "\n"),
+ "\n"],
- array("&",
+ ["&",
"<",
">",
""",
"",
" ",
"",
- "<br />"),
+ "<br />"],
$s);
// Replace pseudo diacritics
// These were used to produce accented characters. For instance an accented
$admin = '';
- $o .= replace_macros($tpl, array(
+ $o .= replace_macros($tpl, [
'$search' => $search,
'$globaldir' => $globaldir,
'$desc' => t('Find on this site'),
'$finding' => (strlen($search) ? '<h4>' . t('Finding: ') . "'" . $search . "'" . '</h4>' : ""),
'$sitedir' => t('Site Directory'),
'$submit' => t('Find')
- ));
+ ]);
if($search)
$search = dbesc($search);
if(count($r))
$a->set_pager_total($r[0]['total']);
- $order = " ORDER BY `name` ASC ";
+ $order = " ORDER BY `name` ASC ";
$r = q("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags` FROM `profile` LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid` WHERE `is-default` = 1 $publish AND `user`.`blocked` = 0 AND `page-flags` = 2 $sql_extra $order LIMIT %d , %d ",
$profile_link = $a->get_baseurl() . '/profile/' . ((strlen($rr['nickname'])) ? $rr['nickname'] : $rr['profile_uid']);
-
+
$pdesc = (($rr['pdesc']) ? $rr['pdesc'] . '<br />' : '');
$details = '';
}
if(strlen($rr['dob'])) {
if(($years = age($rr['dob'],$rr['timezone'],'')) != 0)
- $details .= '<br />' . t('Age: ') . $years ;
+ $details .= '<br />' . t('Age: ') . $years ;
}
if(strlen($rr['gender']))
$details .= '<br />' . t('Gender: ') . $rr['gender'];
$homepage = ((x($profile,'homepage') == 1) ? t('Homepage:') : False);
$about = ((x($profile,'about') == 1) ? t('About:') : False);
-
+
# $tpl = file_get_contents( dirname(__file__).'/forumdirectory_item.tpl');
$tpl = get_markup_template( 'forumdirectory_item.tpl', 'addon/forumdirectory/' );
- $entry = replace_macros($tpl,array(
+ $entry = replace_macros($tpl,[
'$id' => $rr['id'],
'$profile_link' => $profile_link,
'$photo' => $a->get_cached_avatar_image($rr[$photo]),
'$homepage' => $homepage,
'$about' => $about,
- ));
+ ]);
- $arr = array('contact' => $rr, 'entry' => $entry);
+ $arr = ['contact' => $rr, 'entry' => $entry];
unset($profile);
unset($location);
function fromgplus_plugin_admin(&$a, &$o){
$t = get_markup_template("admin.tpl", "addon/fromgplus/");
- $o = replace_macros($t, array(
+ $o = replace_macros($t, [
'$submit' => t('Save Settings'),
- '$key' => array('key', t('Key'), trim(Config::get('fromgplus', 'key')), t('')),
- ));
+ '$key' => ['key', t('Key'), trim(Config::get('fromgplus', 'key')), t('')],
+ ]);
}
function fromgplus_plugin_admin_post(&$a){
$bbcode = html_entity_decode($html, ENT_QUOTES, 'UTF-8');
- $bbcode = str_ireplace(array("\n"), array(""), $bbcode);
- $bbcode = str_ireplace(array("<b>", "</b>"), array("[b]", "[/b]"), $bbcode);
- $bbcode = str_ireplace(array("<i>", "</i>"), array("[i]", "[/i]"), $bbcode);
- $bbcode = str_ireplace(array("<s>", "</s>"), array("[s]", "[/s]"), $bbcode);
- $bbcode = str_ireplace(array("<br />"), array("\n"), $bbcode);
- $bbcode = str_ireplace(array("<br/>"), array("\n"), $bbcode);
- $bbcode = str_ireplace(array("<br>"), array("\n"), $bbcode);
+ $bbcode = str_ireplace(["\n"], [""], $bbcode);
+ $bbcode = str_ireplace(["<b>", "</b>"], ["[b]", "[/b]"], $bbcode);
+ $bbcode = str_ireplace(["<i>", "</i>"], ["[i]", "[/i]"], $bbcode);
+ $bbcode = str_ireplace(["<s>", "</s>"], ["[s]", "[/s]"], $bbcode);
+ $bbcode = str_ireplace(["<br />"], ["\n"], $bbcode);
+ $bbcode = str_ireplace(["<br/>"], ["\n"], $bbcode);
+ $bbcode = str_ireplace(["<br>"], ["\n"], $bbcode);
$bbcode = trim(strip_tags($bbcode));
return($bbcode);
$var = parse_url($var, PHP_URL_QUERY);
$var = html_entity_decode($var);
$var = explode('&', $var);
- $arr = array();
+ $arr = [];
foreach($var as $val) {
$x = explode('=', $val);
//$image = str_replace(array($preview, $preview2), array("/", "/"), $image->url);
$image = $image->url;
- $cleaned = array();
+ $cleaned = [];
$queryvar = fromgplus_parse_query($fullImage);
if ($queryvar['url'] != "")
if ($cleaned["full"] != "")
$infoFull = Image::getInfoFromURL($cleaned["full"]);
else
- $infoFull = array("0" => 0, "1" => 0);
+ $infoFull = ["0" => 0, "1" => 0];
if ($cleaned["preview"] != "")
$infoPreview = Image::getInfoFromURL($cleaned["preview"]);
else
- $infoFull = array("0" => 0, "1" => 0);
+ $infoFull = ["0" => 0, "1" => 0];
if (($infoPreview[0] >= $infoFull[0]) && ($infoPreview[1] >= $infoFull[1])) {
$temp = $cleaned["full"];
$text = strip_tags($text);
$text = html_entity_decode($text, ENT_QUOTES);
$text = trim($text);
- $text = str_replace(array("\n", "\r", " ", $trash), array("", "", "", ""), $text);
+ $text = str_replace(["\n", "\r", " ", $trash], ["", "", "", ""], $text);
return($text);
}
$post = "";
$quote = "";
- $pagedata = array();
+ $pagedata = [];
$pagedata["type"] = "";
foreach ($item->object->attachments as $attachment) {
$t = get_markup_template("admin.tpl", "addon/geocoordinates/");
- $o = replace_macros($t, array(
+ $o = replace_macros($t, [
'$submit' => t('Save Settings'),
- '$api_key' => array('api_key', t('API Key'), Config::get('geocoordinates', 'api_key' ), ''),
- '$language' => array('language', t('Language code (IETF format)'), Config::get('geocoordinates', 'language' ), ''),
- ));
+ '$api_key' => ['api_key', t('API Key'), Config::get('geocoordinates', 'api_key' ), ''],
+ '$language' => ['language', t('Language code (IETF format)'), Config::get('geocoordinates', 'language' ), ''],
+ ]);
}
function geocoordinates_plugin_admin_post(&$a)
if ($default_avatar != "gravatar")
$url .= '&d=' .$default_avatar;
- $b['url'] = $url;
+ $b['url'] = $url;
$b['success'] = true;
}
$rating = 'g'; // suitable for display on all websites with any audience type
// Available options for the select boxes
- $default_avatars = array(
+ $default_avatars = [
'mm' => t('generic profile image'),
'identicon' => t('random geometric pattern'),
'monsterid' => t('monster face'),
'wavatar' => t('computer generated face'),
'retro' => t('retro arcade style face'),
- );
- $ratings = array(
+ ];
+ $ratings = [
'g' => 'g',
'pg' => 'pg',
'r' => 'r',
'x' => 'x'
- );
+ ];
// Check if Libravatar is enabled and show warning
$r = q("SELECT * FROM `addon` WHERE `name` = '%s' and `installed` = 1",
// output Gravatar settings
$o .= '<input type="hidden" name="form_security_token" value="' .get_form_security_token("gravatarsave") .'">';
- $o .= replace_macros( $t, array(
+ $o .= replace_macros( $t, [
'$submit' => t('Save Settings'),
- '$default_avatar' => array('avatar', t('Default avatar image'), $default_avatar, t('Select default avatar image if none was found at Gravatar. See README'), $default_avatars),
- '$rating' => array('rating', t('Rating of images'), $rating, t('Select the appropriate avatar rating for your site. See README'), $ratings),
- ));
+ '$default_avatar' => ['avatar', t('Default avatar image'), $default_avatar, t('Select default avatar image if none was found at Gravatar. See README'), $default_avatars],
+ '$rating' => ['rating', t('Rating of images'), $rating, t('Select the appropriate avatar rating for your site. See README'), $ratings],
+ ]);
}
/**
return;
}
- $item = array();
+ $item = [];
if (isset($_REQUEST['type'])) {
$item['type'] = $_REQUEST['type'];
}
- if (!in_array($item['type'], array('status', 'link', 'photo'))) {
+ if (!in_array($item['type'], ['status', 'link', 'photo'])) {
logger('Unknown item type ' . $item['type'], LOGGER_DEBUG);
return;
}
if($b['parent'] != $b['id'])
return;
- // insanejournal post in the LJ user's timezone.
+ // insanejournal post in the LJ user's timezone.
// Hopefully the person's Friendica account
// will be set to the same thing.
intval($b['uid'])
);
if($x && strlen($x[0]['timezone']))
- $tz = $x[0]['timezone'];
+ $tz = $x[0]['timezone'];
$ij_username = PConfig::get($b['uid'],'ijpost','ij_username');
$ij_password = PConfig::get($b['uid'],'ijpost','ij_password');
logger('ijpost: data: ' . $xml, LOGGER_DATA);
if($ij_blog !== 'test')
- $x = post_url($ij_blog,$xml,array("Content-Type: text/xml"));
+ $x = post_url($ij_blog,$xml,["Content-Type: text/xml"]);
logger('posted to insanejournal: ' . ($x) ? $x : '', LOGGER_DEBUG);
}
}
function impressum_plugin_admin (&$a, &$o) {
$t = get_markup_template( "admin.tpl", "addon/impressum/" );
- $o = replace_macros($t, array(
+ $o = replace_macros($t, [
'$submit' => t('Save Settings'),
- '$owner' => array('owner', t('Site Owner'), Config::get('impressum','owner'), t('The page operators name.')),
- '$ownerprofile' => array('ownerprofile', t('Site Owners Profile'), Config::get('impressum','ownerprofile'), t('Profile address of the operator.')),
- '$postal' => array('postal', t('Postal Address'), Config::get('impressum','postal'), t('How to contact the operator via snail mail. You can use BBCode here.')),
- '$notes' => array('notes', t('Notes'), Config::get('impressum','notes'), t('Additional notes that are displayed beneath the contact information. You can use BBCode here.')),
- '$email' => array('email', t('Email Address'), Config::get('impressum','email'), t('How to contact the operator via email. (will be displayed obfuscated)')),
- '$footer_text' => array('footer_text', t('Footer note'), Config::get('impressum','footer_text'), t('Text for the footer. You can use BBCode here.')),
- ));
+ '$owner' => ['owner', t('Site Owner'), Config::get('impressum','owner'), t('The page operators name.')],
+ '$ownerprofile' => ['ownerprofile', t('Site Owners Profile'), Config::get('impressum','ownerprofile'), t('Profile address of the operator.')],
+ '$postal' => ['postal', t('Postal Address'), Config::get('impressum','postal'), t('How to contact the operator via snail mail. You can use BBCode here.')],
+ '$notes' => ['notes', t('Notes'), Config::get('impressum','notes'), t('Additional notes that are displayed beneath the contact information. You can use BBCode here.')],
+ '$email' => ['email', t('Email Address'), Config::get('impressum','email'), t('How to contact the operator via email. (will be displayed obfuscated)')],
+ '$footer_text' => ['footer_text', t('Footer note'), Config::get('impressum','footer_text'), t('Text for the footer. You can use BBCode here.')],
+ ]);
}
$autochans = PConfig::get( local_user(), 'irc','autochans'); /* auto connect chans */
$t = get_markup_template( "settings.tpl", "addon/irc/" );
- $s .= replace_macros($t, array(
+ $s .= replace_macros($t, [
'$header' => t('IRC Settings'),
'$info' => t('Here you can change the system wide settings for the channels to automatically join and access via the side bar. Note the changes you do here, only effect the channel selection if you are logged in.'),
'$submit' => t('Save Settings'),
- '$autochans' => array( 'autochans', t('Channel(s) to auto connect (comma separated)'), $autochans, t('List of channels that shall automatically connected to when the app is launched.')),
- '$sitechats' => array( 'sitechats', t('Popular Channels (comma separated)'), $sitechats, t('List of popular channels, will be displayed at the side and hotlinked for easy joining.') )
- ));
+ '$autochans' => [ 'autochans', t('Channel(s) to auto connect (comma separated)'), $autochans, t('List of channels that shall automatically connected to when the app is launched.')],
+ '$sitechats' => [ 'sitechats', t('Popular Channels (comma separated)'), $sitechats, t('List of popular channels, will be displayed at the side and hotlinked for easy joining.') ]
+ ]);
return;
if($sitechats)
$chats = explode(',',$sitechats);
else
- $chats = array('friendica','chat','chatback','hottub','ircbar','dateroom','debian');
+ $chats = ['friendica','chat','chatback','hottub','ircbar','dateroom','debian'];
$a->page['aside'] .= '<div class="widget"><h3>' . t('Popular Channels') . '</h3><ul>';
EOT;
return $o;
-
+
}
function irc_plugin_admin_post (&$a) {
$sitechats = Config::get('irc','sitechats'); /* popular channels */
$autochans = Config::get('irc','autochans'); /* auto connect chans */
$t = get_markup_template( "admin.tpl", "addon/irc/" );
- $o = replace_macros($t, array(
+ $o = replace_macros($t, [
'$submit' => t('Save Settings'),
- '$autochans' => array( 'autochans', t('Channel(s) to auto connect (comma separated)'), $autochans, t('List of channels that shall automatically connected to when the app is launched.')),
- '$sitechats' => array( 'sitechats', t('Popular Channels (comma separated)'), $sitechats, t('List of popular channels, will be displayed at the side and hotlinked for easy joining.') )
- ));
+ '$autochans' => [ 'autochans', t('Channel(s) to auto connect (comma separated)'), $autochans, t('List of channels that shall automatically connected to when the app is launched.')],
+ '$sitechats' => [ 'sitechats', t('Popular Channels (comma separated)'), $sitechats, t('List of popular channels, will be displayed at the side and hotlinked for easy joining.') ]
+ ]);
}
$encrypted_address_hex = bin2hex($encrypted_address);
- $answer = Array(
+ $answer = [
"status" => "ok",
"encrypted_address" => $encrypted_address_hex
- );
+ ];
$answer_json = json_encode($answer);
echo $answer_json;
}
// get a list of jabber accounts of the contacts
- $contacts = Array();
+ $contacts = [];
$uid = local_user();
$rows = q("SELECT * FROM `pconfig` WHERE `uid`=$uid AND `cat`='jappixmini' AND `k` LIKE 'id:%%'");
foreach ($rows as $row) {
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Max-Age: 31536000');
-
+
exit;
}
// CORS headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
-
+
$method = 'POST';
}
}
// HTTP headers
-$headers = array('User-Agent: Jappix (BOSH PHP Proxy)', 'Connection: keep-alive', 'Content-Type: text/xml; charset=utf-8', 'Content-Length: '.strlen($data));
+$headers = ['User-Agent: Jappix (BOSH PHP Proxy)', 'Connection: keep-alive', 'Content-Type: text/xml; charset=utf-8', 'Content-Length: '.strlen($data)];
// CURL is better if available
if(function_exists('curl_init'))
if($use_curl) {
// Initialize CURL
$connection = curl_init($HOST_BOSH);
-
+
// Set the CURL settings
curl_setopt($connection, CURLOPT_HEADER, 0);
curl_setopt($connection, CURLOPT_POST, 1);
curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
-
+
// Get the CURL output
$output = curl_exec($connection);
}
// Built-in stream functions
else {
// HTTP parameters
- $parameters = array('http' => array(
+ $parameters = ['http' => [
'method' => 'POST',
'content' => $data
- )
- );
+ ]
+ ];
$parameters['http']['header'] = $headers;
if($method == 'POST') {
// XML header
header('Content-Type: text/xml; charset=utf-8');
-
+
if(!$output)
echo('<body xmlns=\'http://jabber.org/protocol/httpbind\' type=\'terminate\'/>');
else
if($method == 'GET') {
// JSON header
header('Content-type: application/json');
-
+
// Encode output to JSON
$json_output = json_encode($output);
-
+
if(($output == false) || ($output == '') || ($json_output == 'null'))
echo($callback.'({"reply":"<body xmlns=\'http:\/\/jabber.org\/protocol\/httpbind\' type=\'terminate\'\/>"});');
else
*
* JavaScript Photo/Image Uploader
*
- * Uses Valum 'qq' Uploader.
+ * Uses Valum 'qq' Uploader.
* Module Author: Chris Case
*
*/
$b['addon_text'] .= '<link href="' . $a->get_baseurl() . '/addon/js_upload/file-uploader/client/fileuploader.css" rel="stylesheet" type="text/css">';
$b['addon_text'] .= '<script src="' . $a->get_baseurl() . '/addon/js_upload/file-uploader/client/fileuploader.js" type="text/javascript"></script>';
-
+
$upload_msg = t('Upload a file');
$drop_msg = t('Drop files here to upload');
$cancel = t('Cancel');
$maximagesize = intval(Config::get('system','maximagesize'));
$b['addon_text'] .= <<< EOT
-
- <div id="file-uploader-demo1">
- <noscript>
+
+ <div id="file-uploader-demo1">
+ <noscript>
<p>Please enable JavaScript to use file uploader.</p>
<!-- or put a simple form for upload here -->
- </noscript>
+ </noscript>
</div>
<script type="text/javascript">
-var uploader = null;
+var uploader = null;
function getSelected(opt) {
var selected = new Array();
var index = 0;
}
}
return selected;
- }
+ }
function createUploader() {
uploader = new qq.FileUploader({
element: document.getElementById('file-uploader-demo1'),
action: '{$b['post_url']}',
- template: '<div class="qq-uploader">' +
+ template: '<div class="qq-uploader">' +
'<div class="qq-upload-drop-area"><span>$drop_msg</span></div>' +
'<div class="qq-upload-button">$upload_msg</div>' +
- '<ul class="qq-upload-list"></ul>' +
+ '<ul class="qq-upload-list"></ul>' +
'</div>',
// template for one item in file list
'<span class="qq-upload-size"></span>' +
'<a class="qq-upload-cancel" href="#">$cancel</a>' +
'<span class="qq-upload-failed-text">$failed</span>' +
- '</li>',
+ '</li>',
debug: true,
sizeLimit: $maximagesize,
});
}
}
- });
+ });
}
// in your app create uploader as soon as the DOM is ready
-// don't wait for the window to load
-window.onload = createUploader;
+// don't wait for the window to load
+window.onload = createUploader;
</script>
-
+
EOT;
// list of valid extensions, ex. array("jpeg", "xml", "bmp")
- $allowedExtensions = array("jpeg","gif","png","jpg");
+ $allowedExtensions = ["jpeg","gif","png","jpg"];
// max file size in bytes
* Save the file in the temp dir.
* @return boolean TRUE on success
*/
- function save() {
+ function save() {
$input = fopen("php://input", "r");
$upload_dir = Config::get('system','tempdir');
fclose($input);
fclose($temp);
-
- if ($realSize != $this->getSize()){
+
+ if ($realSize != $this->getSize()){
return false;
}
return true;
function getSize() {
if (isset($_SERVER["CONTENT_LENGTH"])){
- return (int)$_SERVER["CONTENT_LENGTH"];
+ return (int)$_SERVER["CONTENT_LENGTH"];
} else {
throw new Exception('Getting content length is not supported.');
- }
- }
+ }
+ }
}
/**
* Handle file uploads via regular form post (uses the $_FILES array)
*/
-class qqUploadedFileForm {
+class qqUploadedFileForm {
/**
}
class qqFileUploader {
- private $allowedExtensions = array();
+ private $allowedExtensions = [];
private $sizeLimit = 10485760;
private $file;
- function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760){
+ function __construct(array $allowedExtensions = [], $sizeLimit = 10485760){
$allowedExtensions = array_map("strtolower", $allowedExtensions);
-
- $this->allowedExtensions = $allowedExtensions;
+
+ $this->allowedExtensions = $allowedExtensions;
$this->sizeLimit = $sizeLimit;
-
+
if (isset($_GET['qqfile'])) {
$this->file = new qqUploadedFileXhr();
} elseif (isset($_FILES['qqfile'])) {
$this->file = new qqUploadedFileForm();
} else {
- $this->file = false;
+ $this->file = false;
}
}
-
-
+
+
private function toBytes($str){
$val = trim($str);
$last = strtolower($str[strlen($str)-1]);
switch($last) {
case 'g': $val *= 1024;
case 'm': $val *= 1024;
- case 'k': $val *= 1024;
+ case 'k': $val *= 1024;
}
return $val;
}
-
+
/**
* Returns array('success'=>true) or array('error'=>'error message')
*/
function handleUpload(){
-
+
if (!$this->file){
- return array('error' => t('No files were uploaded.'));
+ return ['error' => t('No files were uploaded.')];
}
-
+
$size = $this->file->getSize();
-
+
if ($size == 0) {
- return array('error' => t('Uploaded file is empty'));
+ return ['error' => t('Uploaded file is empty')];
}
-
+
// if ($size > $this->sizeLimit) {
// return array('error' => t('Uploaded file is too large'));
// }
-
+
$maximagesize = Config::get('system','maximagesize');
if(($maximagesize) && ($size > $maximagesize)) {
- return array('error' => t('Image exceeds size limit of ') . $maximagesize );
+ return ['error' => t('Image exceeds size limit of ') . $maximagesize ];
}
if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){
$these = implode(', ', $this->allowedExtensions);
- return array('error' => t('File has an invalid extension, it should be one of ') . $these . '.');
+ return ['error' => t('File has an invalid extension, it should be one of ') . $these . '.'];
}
-
+
if ($this->file->save()){
- return array(
+ return [
'success'=>true,
- 'path' => $this->file->getPath(),
+ 'path' => $this->file->getPath(),
'filename' => $filename . '.' . $ext
- );
+ ];
} else {
- return array(
+ return [
'error'=> t('Upload was cancelled, or server error encountered'),
- 'path' => $this->file->getPath(),
+ 'path' => $this->file->getPath(),
'filename' => $filename . '.' . $ext
- );
+ ];
}
-
- }
+
+ }
}
function krynn_install() {
/**
- *
+ *
* Our demo plugin will attach in three places.
* The first is just prior to storing a local post.
*
/**
*
- * Then we'll attach into the plugin settings page, and also the
+ * Then we'll attach into the plugin settings page, and also the
* settings post hook so that we can create and update
* user preferences.
*
*
*/
- $krynn = array('Ansalon','Abanasinia','Solace','Haven','Gateway','Qualinost','Ankatavaka','Pax Tharkas','Ergoth','Newsea','Straights of Schallsea','Plains of Dust','Tarsis','Barren Hills','Que Shu','Citadel of Light','Solinari','Hedge Maze','Tower of High Sorcery','Inn of the Last Home','Last Heroes Tomb','Academy of Sorcery','Gods Row','Temple of Majere','Temple of Kiri-Jolith','Temple of Mishakal','Temple of Zeboim','The Trough','Sad Town','Xak Tsaroth','Zhaman','Skullcap','Saifhum','Karthay','Mithas','Kothas','Silver Dragon Mountain','Silvanesti');
+ $krynn = ['Ansalon','Abanasinia','Solace','Haven','Gateway','Qualinost','Ankatavaka','Pax Tharkas','Ergoth','Newsea','Straights of Schallsea','Plains of Dust','Tarsis','Barren Hills','Que Shu','Citadel of Light','Solinari','Hedge Maze','Tower of High Sorcery','Inn of the Last Home','Last Heroes Tomb','Academy of Sorcery','Gods Row','Temple of Majere','Temple of Kiri-Jolith','Temple of Mishakal','Temple of Zeboim','The Trough','Sad Town','Xak Tsaroth','Zhaman','Skullcap','Saifhum','Karthay','Mithas','Kothas','Silver Dragon Mountain','Silvanesti'];
$planet = array_rand($krynn,1);
$item['location'] = $krynn[$planet];
/**
*
- * Called from the Plugin Setting form.
+ * Called from the Plugin Setting form.
* Add our own settings info to the page.
*
*/
}
$t = get_markup_template("settings.tpl", "addon/langfilter/");
- $s .= replace_macros($t, array(
+ $s .= replace_macros($t, [
'$title' => t("Language Filter"),
'$intro' => t('This addon tries to identify the language of a postings. If it does not match any language spoken by you (see below) the posting will be collapsed. Remember detecting the language is not perfect, especially with short postings.'),
- '$enabled' => array('langfilter_enable', t('Use the language filter'), $enable_checked, ''),
- '$languages' => array('langfilter_languages', t('I speak'), $languages, t('List of abbreviations (iso2 codes) for languages you speak, comma separated. For example "de,it".')),
- '$minconfidence' => array('langfilter_minconfidence', t('Minimum confidence in language detection'), $minconfidence, t('Minimum confidence in language detection being correct, from 0 to 100. Posts will not be filtered when the confidence of language detection is below this percent value.')),
- '$minlength' => array('langfilter_minlength', t('Minimum length of message body'), $minlength, t('Minimum length of message body for language filter to be used. Posts shorter than this number of characters will not be filtered.')),
+ '$enabled' => ['langfilter_enable', t('Use the language filter'), $enable_checked, ''],
+ '$languages' => ['langfilter_languages', t('I speak'), $languages, t('List of abbreviations (iso2 codes) for languages you speak, comma separated. For example "de,it".')],
+ '$minconfidence' => ['langfilter_minconfidence', t('Minimum confidence in language detection'), $minconfidence, t('Minimum confidence in language detection being correct, from 0 to 100. Posts will not be filtered when the confidence of language detection is below this percent value.')],
+ '$minlength' => ['langfilter_minlength', t('Minimum length of message body'), $minlength, t('Minimum length of message body for language filter to be used. Posts shorter than this number of characters will not be filtered.')],
'$submit' => t('Save Settings'),
- ));
+ ]);
return;
}
$results = get_existing_account($username);
if (empty($results)) {
if (strlen($email) > 0 && strlen($name) > 0) {
- $arr = array('username' => $name, 'nickname' => $username, 'email' => $email, 'password' => $password, 'verified' => 1);
+ $arr = ['username' => $name, 'nickname' => $username, 'email' => $email, 'password' => $password, 'verified' => 1];
try {
User::create($arr);
}
function leistungsschutzrecht_cuttext($text) {
- $text = str_replace(array("\r", "\n"), array(" ", " "), $text);
+ $text = str_replace(["\r", "\n"], [" ", " "], $text);
do {
$oldtext = $text;
$sitelist = fetch_url($url);
$siteurls = explode(',', $sitelist);
- $whitelist = array('tagesschau.de', 'heute.de', 'wdr.de');
+ $whitelist = ['tagesschau.de', 'heute.de', 'wdr.de'];
- $sites = array();
+ $sites = [];
foreach ($siteurls AS $site) {
if (!in_array($site, $whitelist)) {
$sites[$site] = $site;
if($ltree_url && $ltree_api_token && $ltree_blog && $ltree_source) {
require_once('include/bb2diaspora.php');
- $tag_arr = array();
+ $tag_arr = [];
$tags = '';
$x = preg_match_all('/\#\[(.*?)\](.*?)\[/',$b['tag'],$matches,PREG_SET_ORDER);
$body = "## ".html_entity_decode($title)."\n\n".$body;
- $params = array(
+ $params = [
'text' => $body,
'source' => $ltree_source
// 'token' => $ltree_api_token
- );
+ ];
$result = post_url($ltree_blog,$params);
logger('libertree: ' . $result);
$default_avatar = 'identicon'; // pseudo-random geometric pattern based on email hash
// Available options for the select boxes
- $default_avatars = array(
+ $default_avatars = [
'mm' => t('generic profile image'),
'identicon' => t('random geometric pattern'),
'monsterid' => t('monster face'),
'wavatar' => t('computer generated face'),
'retro' => t('retro arcade style face'),
- );
+ ];
// Show warning if PHP version is too old
if (! version_compare(PHP_VERSION, '5.3.0', '>=')) {
// output Libravatar settings
$o .= '<input type="hidden" name="form_security_token" value="' .get_form_security_token("libravatarsave") .'">';
- $o .= replace_macros( $t, array(
+ $o .= replace_macros( $t, [
'$submit' => t('Save Settings'),
- '$default_avatar' => array('avatar', t('Default avatar image'), $default_avatar, t('Select default avatar image if none was found. See README'), $default_avatars),
- ));
+ '$default_avatar' => ['avatar', t('Default avatar image'), $default_avatar, t('Select default avatar image if none was found. See README'), $default_avatars],
+ ]);
}
/**
if($b['parent'] != $b['id'])
return;
- // LiveJournal post in the LJ user's timezone.
+ // LiveJournal post in the LJ user's timezone.
// Hopefully the person's Friendica account
// will be set to the same thing.
intval($b['uid'])
);
if($x && strlen($x[0]['timezone']))
- $tz = $x[0]['timezone'];
+ $tz = $x[0]['timezone'];
$lj_username = xmlify(PConfig::get($b['uid'],'ljpost','lj_username'));
$lj_password = xmlify(PConfig::get($b['uid'],'ljpost','lj_password'));
logger('ljpost: data: ' . $xml, LOGGER_DATA);
if($lj_blog !== 'test')
- $x = post_url($lj_blog,$xml,array("Content-Type: text/xml"));
+ $x = post_url($lj_blog,$xml,["Content-Type: text/xml"]);
logger('posted to livejournal: ' . ($x) ? $x : '', LOGGER_DEBUG);
}
function mailstream_plugin_admin(&$a,&$o) {
$frommail = Config::get('mailstream', 'frommail');
$template = get_markup_template('admin.tpl', 'addon/mailstream/');
- $config = array('frommail',
+ $config = ['frommail',
t('From Address'),
$frommail,
- t('Email address that stream items will appear to be from.'));
- $o .= replace_macros($template, array(
+ t('Email address that stream items will appear to be from.')];
+ $o .= replace_macros($template, [
'$frommail' => $config,
- '$submit' => t('Save Settings')));
+ '$submit' => t('Save Settings')]);
}
function mailstream_plugin_admin_post ($a) {
if (!PConfig::get($item['uid'], 'mailstream', 'attachimg')) {
return;
}
- $attachments = array();
+ $attachments = [];
$baseurl = $a->get_baseurl();
preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
foreach (array_merge($matches1[3], $matches2[1]) as $url) {
$redirects;
$cookiejar = tempnam(get_temppath(), 'cookiejar-mailstream-');
- $attachments[$url] = array(
+ $attachments[$url] = [
'data' => fetch_url($url, true, $redirects, 0, Null, $cookiejar),
'guid' => hash("crc32", $url),
'filename' => basename($url),
- 'type' => $a->get_curl_content_type());
+ 'type' => $a->get_curl_content_type()];
if (strlen($attachments[$url]['data'])) {
$item['body'] = str_replace($url, 'cid:' . $attachments[$url]['guid'], $item['body']);
continue;
}
require_once(dirname(__file__).'/phpmailer/class.phpmailer.php');
require_once('include/bbcode.php');
- $attachments = array();
+ $attachments = [];
mailstream_do_images($a, $item, $attachments);
$frommail = Config::get('mailstream', 'frommail');
if ($frommail == "") {
$template = get_markup_template('mail.tpl', 'addon/mailstream/');
$item['body'] = bbcode($item['body']);
$item['url'] = $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item['id'];
- $mail->Body = replace_macros($template, array(
+ $mail->Body = replace_macros($template, [
'$upstream' => t('Upstream'),
'$local' => t('Local'),
- '$item' => $item));
+ '$item' => $item]);
mailstream_html_wrap($mail->Body);
if (!$mail->Send()) {
throw new Exception($mail->ErrorInfo);
$nolikes = PConfig::get(local_user(), 'mailstream', 'nolikes');
$attachimg= PConfig::get(local_user(), 'mailstream', 'attachimg');
$template = get_markup_template('settings.tpl', 'addon/mailstream/');
- $s .= replace_macros($template, array(
- '$enabled' => array(
+ $s .= replace_macros($template, [
+ '$enabled' => [
'mailstream_enabled',
t('Enabled'),
- $enabled),
- '$address' => array(
+ $enabled],
+ '$address' => [
'mailstream_address',
t('Email Address'),
$address,
- t("Leave blank to use your account email address")),
- '$nolikes' => array(
+ t("Leave blank to use your account email address")],
+ '$nolikes' => [
'mailstream_nolikes',
t('Exclude Likes'),
$nolikes,
- t("Check this to omit mailing \"Like\" notifications")),
- '$attachimg' => array(
+ t("Check this to omit mailing \"Like\" notifications")],
+ '$attachimg' => [
'mailstream_attachimg',
t('Attach Images'),
$attachimg,
- t("Download images in posts and attach them to the email. Useful for reading email while offline.")),
+ t("Download images in posts and attach them to the email. Useful for reading email while offline.")],
'$title' => t('Mail Stream Settings'),
- '$submit' => t('Save Settings')));
+ '$submit' => t('Save Settings')]);
}
function mailstream_plugin_settings_post($a,$post) {
function mathjax_install() {
register_hook('page_header', 'addon/mathjax/mathjax.php', 'mathjax_page_header');
- register_hook('plugin_settings', 'addon/mathjax/mathjax.php', 'mathjax_settings');
+ register_hook('plugin_settings', 'addon/mathjax/mathjax.php', 'mathjax_settings');
register_hook('plugin_settings_post', 'addon/mathjax/mathjax.php', 'mathjax_settings_post');
logger('installed js_math plugin');
}
function mathjax_uninstall() {
unregister_hook('page_header', 'addon/mathjax/mathjax.php', 'mathjax_page_header');
- unregister_hook('plugin_settings', 'addon/mathjax/mathjax.php', 'mathjax_settings');
+ unregister_hook('plugin_settings', 'addon/mathjax/mathjax.php', 'mathjax_settings');
unregister_hook('plugin_settings_post', 'addon/mathjax/mathjax.php', 'mathjax_settings_post');
}
function mathjax_settings_post ($a, $post) {
$b .= '<script type="text/javascript" src="'.$url.'"></script>';
} else {
$use = PConfig::get(local_user(),'mathjax','use');
- if ($use) {
+ if ($use) {
$b .= '<script type="text/javascript" src="'.$url.'"></script>';
}
}
Config::set('mathjax','baseurl','http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML');
}
- $o = replace_macros( $t, array(
+ $o = replace_macros( $t, [
'$submit' => t('Save Settings'),
- '$baseurl' => array('baseurl', t('MathJax Base URL'), Config::get('mathjax','baseurl' ), t('The URL for the javascript file that should be included to use MathJax. Can be either the MathJax CDN or another installation of MathJax.')),
- ));
+ '$baseurl' => ['baseurl', t('MathJax Base URL'), Config::get('mathjax','baseurl' ), t('The URL for the javascript file that should be included to use MathJax. Can be either the MathJax CDN or another installation of MathJax.')],
+ ]);
}
}
function morepokes_poke_verbs($a,&$b) {
- $b['bitchslap'] = array('bitchslapped', t('bitchslap'), t('bitchslapped'));
- $b['shag'] = array('shag', t('shag'), t('shagged'));
- $b['somethingobscenelybiological'] = array('something obscenely biological', t('do something obscenely biological to'), t('did something obscenely biological to'));
- $b['newpokefeature'] = array('pointed out the poke feature to', t('point out the poke feature to'), t('pointed out the poke feature to'));
- $b['declareundyinglove'] = array('declared undying love for', t('declare undying love for'), t('declared undying love for'));
- $b['patent'] = array('patented', t('patent'), t('patented'));
- $b['strokebeard'] = array('stroked their beard at', t('stroke beard'), t('stroked their beard at'));
- $b['bemoan'] = array('bemoaned the declining standards of modern secondary and tertiary education to', t('bemoan the declining standards of modern secondary and tertiary education to'), t('bemoans the declining standards of modern secondary and tertiary education to'));
- $b['hugs'] = array('hugged', t('hug'), t('hugged'));
- $b['kiss'] = array('kissed', t('kiss'), t('kissed'));
- $b['raiseeyebrows'] = array('raised their eyebrows at', t('raise eyebrows at'), t('raised their eyebrows at'));
- $b['insult'] = array('insulted', t('insult'), t('insulted'));
- $b['praise'] = array('praised', t('praise'), t('praised'));
- $b['bedubiousof'] = array('was dubious of', t('be dubious of'), t('was dubious of'));
- $b['eat'] = array('ate', t('eat'), t('ate'));
- $b['giggleandfawn'] = array('giggled and fawned at', t('giggle and fawn at'), t('giggled and fawned at'));
- $b['doubt'] = array('doubted', t('doubt'), t('doubted'));
- $b['glare'] = array('glared at', t('glare'), t('glared at'));
+ $b['bitchslap'] = ['bitchslapped', t('bitchslap'), t('bitchslapped')];
+ $b['shag'] = ['shag', t('shag'), t('shagged')];
+ $b['somethingobscenelybiological'] = ['something obscenely biological', t('do something obscenely biological to'), t('did something obscenely biological to')];
+ $b['newpokefeature'] = ['pointed out the poke feature to', t('point out the poke feature to'), t('pointed out the poke feature to')];
+ $b['declareundyinglove'] = ['declared undying love for', t('declare undying love for'), t('declared undying love for')];
+ $b['patent'] = ['patented', t('patent'), t('patented')];
+ $b['strokebeard'] = ['stroked their beard at', t('stroke beard'), t('stroked their beard at')];
+ $b['bemoan'] = ['bemoaned the declining standards of modern secondary and tertiary education to', t('bemoan the declining standards of modern secondary and tertiary education to'), t('bemoans the declining standards of modern secondary and tertiary education to')];
+ $b['hugs'] = ['hugged', t('hug'), t('hugged')];
+ $b['kiss'] = ['kissed', t('kiss'), t('kissed')];
+ $b['raiseeyebrows'] = ['raised their eyebrows at', t('raise eyebrows at'), t('raised their eyebrows at')];
+ $b['insult'] = ['insulted', t('insult'), t('insulted')];
+ $b['praise'] = ['praised', t('praise'), t('praised')];
+ $b['bedubiousof'] = ['was dubious of', t('be dubious of'), t('was dubious of')];
+ $b['eat'] = ['ate', t('eat'), t('ate')];
+ $b['giggleandfawn'] = ['giggled and fawned at', t('giggle and fawn at'), t('giggled and fawned at')];
+ $b['doubt'] = ['doubted', t('doubt'), t('doubted')];
+ $b['glare'] = ['glared at', t('glare'), t('glared at')];
;}
function newmemberwidget_plugin_admin(&$a, &$o){
$t = get_markup_template('admin.tpl','addon/newmemberwidget');
- $o = replace_macros($t, array(
+ $o = replace_macros($t, [
'$submit' => t('Save Settings'),
- '$freetext' => array( "freetext", t("Message"), Config::get( "newmemberwidget", "freetext" ), t("Your message for new members. You can use bbcode here.")),
- '$linkglobalsupport' => array( "linkglobalsupport", t('Add a link to global support forum'), Config::get( 'newmemberwidget', 'linkglobalsupport'), t('Should a link to the global support forum be displayed?')." (<a href='https://forum.friendi.ca/profile/helpers'>@helpers</a>)"),
- '$linklocalsupport' => array( "linklocalsupport", t('Add a link to the local support forum'), Config::get( 'newmemberwidget', 'linklocalsupport'), t('If you have a local support forum and want to have a link displayed in the widget, check this box.')),
- '$localsupportname' => array( "localsupportname", t('Name of the local support group'), Config::get( 'newmemberwidget', 'localsupport'), t('If you checked the above, specify the <em>nickname</em> of the local support group here (i.e. helpers)')),
- ));
+ '$freetext' => [ "freetext", t("Message"), Config::get( "newmemberwidget", "freetext" ), t("Your message for new members. You can use bbcode here.")],
+ '$linkglobalsupport' => [ "linkglobalsupport", t('Add a link to global support forum'), Config::get( 'newmemberwidget', 'linkglobalsupport'), t('Should a link to the global support forum be displayed?')." (<a href='https://forum.friendi.ca/profile/helpers'>@helpers</a>)"],
+ '$linklocalsupport' => [ "linklocalsupport", t('Add a link to the local support forum'), Config::get( 'newmemberwidget', 'linklocalsupport'), t('If you have a local support forum and want to have a link displayed in the widget, check this box.')],
+ '$localsupportname' => [ "localsupportname", t('Name of the local support group'), Config::get( 'newmemberwidget', 'localsupport'), t('If you checked the above, specify the <em>nickname</em> of the local support group here (i.e. helpers)')],
+ ]);
}
$sender_name = sprintf(t('%s Administrator'), $sitename);
else
$sender_name = sprintf(t('%1$s, %2$s Administrator'), $a->config['admin_name'], $sitename);
-
+
if (! x($a->config['sender_email']))
$sender_email = 'noreply@' . $a->get_hostname();
else
$subject = $_REQUEST['subject'];
- $textversion = strip_tags(html_entity_decode(bbcode(stripslashes(str_replace(array("\\r", "\\n"),array( "", "\n"), $text))),ENT_QUOTES,'UTF-8'));
+ $textversion = strip_tags(html_entity_decode(bbcode(stripslashes(str_replace(["\\r", "\\n"],[ "", "\n"], $text))),ENT_QUOTES,'UTF-8'));
+
+ $htmlversion = bbcode(stripslashes(str_replace(["\\r","\\n"], ["","<br />\n"],$text)));
- $htmlversion = bbcode(stripslashes(str_replace(array("\\r","\\n"), array("","<br />\n"),$text)));
-
// if this is a test, send it only to the admin(s)
// admin_email might be a comma separated list, but we need "a@b','c@d','e@f
if ( intval($_REQUEST['test'])) {
$email = $a->config['admin_email'];
- $email = "'" . str_replace(array(" ",","), array("","','"), $email) . "'";
+ $email = "'" . str_replace([" ",","], ["","','"], $email) . "'";
}
$sql_extra = ((intval($_REQUEST['test'])) ? sprintf(" AND `email` in ( %s )", $email) : '');
foreach($recips as $recip) {
- Emailer::send(array(
+ Emailer::send([
'fromName' => $sender_name,
'fromEmail' => $sender_email,
'replyTo' => $sender_email,
'messageSubject' => $subject,
'htmlVersion' => $htmlversion,
'textVersion' => $textversion
- ));
+ ]);
}
notice( t('Emails sent'));
$title = t('Send email to all members of this Friendica instance.');
- $o = replace_macros(get_markup_template('notifyall_form.tpl','addon/notifyall/'),array(
+ $o = replace_macros(get_markup_template('notifyall_form.tpl','addon/notifyall/'),[
'$title' => $title,
'$text' => htmlspecialchars($_REQUEST['text']),
- '$subject' => array('subject',t('Message subject'),$_REQUEST['subject'],''),
- '$test' => array('test',t('Test mode (only send to administrator)'), 0,''),
+ '$subject' => ['subject',t('Message subject'),$_REQUEST['subject'],''],
+ '$test' => ['test',t('Test mode (only send to administrator)'), 0,''],
'$submit' => t('Submit')
- ));
+ ]);
return $o;
* Description: Collapse posts with inappropriate content
* Version: 1.0
* Author: Mike Macgirvin <http://macgirvin.com/profile/mike>
- *
+ *
*/
use Friendica\Core\PConfig;
}
-// This function isn't perfect and isn't trying to preserve the html structure - it's just a
-// quick and dirty filter to pull out embedded photo blobs because 'nsfw' seems to come up
+// This function isn't perfect and isn't trying to preserve the html structure - it's just a
+// quick and dirty filter to pull out embedded photo blobs because 'nsfw' seems to come up
// inside them quite often. We don't need anything fancy, just pull out the data blob so we can
-// check against the rest of the body.
-
+// check against the rest of the body.
+
function nsfw_extract_photos($body) {
$new_body = '';
-
+
$img_start = strpos($body,'src="data:');
$img_end = (($img_start !== false) ? strpos(substr($body,$img_start),'>') : false);
while($img_end !== false) {
$img_end += $img_start;
$new_body = $new_body . substr($body,0,$img_start);
-
+
$cnt ++;
$body = substr($body,0,$img_end);
$arr = explode(',',$words);
}
else {
- $arr = array('nsfw');
+ $arr = ['nsfw'];
}
$found = false;
}
}
}
- }
- }
+ }
+ }
}
if($found) {
$rnd = random_string(8);
- $b['html'] = '<div id="nsfw-wrap-' . $rnd . '" class="fakelink" onclick=openClose(\'nsfw-' . $rnd . '\'); >' . sprintf( t('%s - Click to open/close'),$word ) . '</div><div id="nsfw-' . $rnd . '" style="display: none; " >' . $b['html'] . '</div>';
+ $b['html'] = '<div id="nsfw-wrap-' . $rnd . '" class="fakelink" onclick=openClose(\'nsfw-' . $rnd . '\'); >' . sprintf( t('%s - Click to open/close'),$word ) . '</div><div id="nsfw-' . $rnd . '" style="display: none; " >' . $b['html'] . '</div>';
}
}
* Author: Klaus Weidenbach
*
*/
-
+
use Friendica\Core\Cache;
use Friendica\Core\Config;
*
* If an item has coordinates add link to a tile map server, e.g. openstreetmap.org.
* If an item has a location open it with the help of OSM's Nominatim reverse geocode search.
- *
+ *
* @param mixed $a
* @param array& $item
*/
$j = json_decode($x['body'],true);
if($j && is_array($j) && $j[0]['lat'] && $j[0]['lon']) {
- $arr = array('lat' => $j[0]['lat'],'lon' => $j[0]['lon'],'location' => $b['location'], 'html' => '');
+ $arr = ['lat' => $j[0]['lat'],'lon' => $j[0]['lon'],'location' => $b['location'], 'html' => ''];
openstreetmap_generate_map($a,$arr);
$b['html'] = $arr['html'];
}
$marker = 0;
}
- $o = replace_macros($t, array(
+ $o = replace_macros($t, [
'$submit' => t('Submit'),
- '$tmsserver' => array('tmsserver', t('Tile Server URL'), $tmsserver, t('A list of <a href="http://wiki.openstreetmap.org/wiki/TMS" target="_blank">public tile servers</a>')),
- '$nomserver' => array('nomserver', t('Nominatim (reverse geocoding) Server URL'), $nomserver, t('A list of <a href="http://wiki.openstreetmap.org/wiki/Nominatim" target="_blank">Nominatim servers</a>')),
- '$zoom' => array('zoom', t('Default zoom'), $zoom, t('The default zoom level. (1:world, 18:highest, also depends on tile server)')),
- '$marker' => array('marker', t('Include marker on map'), $marker, t('Include a marker on the map.')),
- ));
+ '$tmsserver' => ['tmsserver', t('Tile Server URL'), $tmsserver, t('A list of <a href="http://wiki.openstreetmap.org/wiki/TMS" target="_blank">public tile servers</a>')],
+ '$nomserver' => ['nomserver', t('Nominatim (reverse geocoding) Server URL'), $nomserver, t('A list of <a href="http://wiki.openstreetmap.org/wiki/Nominatim" target="_blank">Nominatim servers</a>')],
+ '$zoom' => ['zoom', t('Default zoom'), $zoom, t('The default zoom level. (1:world, 18:highest, also depends on tile server)')],
+ '$marker' => ['marker', t('Include marker on map'), $marker, t('Include a marker on the map.')],
+ ]);
}
function openstreetmap_plugin_admin_post(&$a)
}
function piwik_plugin_admin (&$a, &$o) {
$t = get_markup_template( "admin.tpl", "addon/piwik/" );
- $o = replace_macros( $t, array(
+ $o = replace_macros( $t, [
'$submit' => t('Save Settings'),
- '$piwikbaseurl' => array('baseurl', t('Piwik Base URL'), Config::get('piwik','baseurl' ), t('Absolute path to your Piwik installation. (without protocol (http/s), with trailing slash)')),
- '$siteid' => array('siteid', t('Site ID'), Config::get('piwik','siteid' ), ''),
- '$optout' => array('optout', t('Show opt-out cookie link?'), Config::get('piwik','optout' ), ''),
- '$async' => array('async', t('Asynchronous tracking'), Config::get('piwik','async' ), ''),
- ));
+ '$piwikbaseurl' => ['baseurl', t('Piwik Base URL'), Config::get('piwik','baseurl' ), t('Absolute path to your Piwik installation. (without protocol (http/s), with trailing slash)')],
+ '$siteid' => ['siteid', t('Site ID'), Config::get('piwik','siteid' ), ''],
+ '$optout' => ['optout', t('Show opt-out cookie link?'), Config::get('piwik','optout' ), ''],
+ '$async' => ['async', t('Asynchronous tracking'), Config::get('piwik','async' ), ''],
+ ]);
}
function piwik_plugin_admin_post (&$a) {
$url = ((x($_POST, 'baseurl')) ? notags(trim($_POST['baseurl'])) : '');
function planets_install() {
/**
- *
+ *
* Our demo plugin will attach in three places.
* The first is just prior to storing a local post.
*
/**
*
- * Then we'll attach into the plugin settings page, and also the
+ * Then we'll attach into the plugin settings page, and also the
* settings post hook so that we can create and update
* user preferences.
*
*
*/
- $planets = array('Alderaan','Tatooine','Dagobah','Polis Massa','Coruscant','Hoth','Endor','Kamino','Rattatak','Mustafar','Iego','Geonosis','Felucia','Dantooine','Ansion','Artaru','Bespin','Boz Pity','Cato Neimoidia','Christophsis','Kashyyyk','Kessel','Malastare','Mygeeto','Nar Shaddaa','Ord Mantell','Saleucami','Subterrel','Death Star','Teth','Tund','Utapau','Yavin');
+ $planets = ['Alderaan','Tatooine','Dagobah','Polis Massa','Coruscant','Hoth','Endor','Kamino','Rattatak','Mustafar','Iego','Geonosis','Felucia','Dantooine','Ansion','Artaru','Bespin','Boz Pity','Cato Neimoidia','Christophsis','Kashyyyk','Kessel','Malastare','Mygeeto','Nar Shaddaa','Ord Mantell','Saleucami','Subterrel','Death Star','Teth','Tund','Utapau','Yavin'];
$planet = array_rand($planets,1);
$item['location'] = $planets[$planet];
/**
*
- * Called from the Plugin Setting form.
+ * Called from the Plugin Setting form.
* Add our own settings info to the page.
*
*/
if(count($r)) {
foreach($r as $rr) {
- notification(array(
+ notification([
'uid' => $rr['uid'],
'type' => NOTIFY_SYSTEM,
'system_type' => 'public_server_expire',
'source_name' => t('Administrator'),
'source_link' => $a->get_baseurl(),
'source_photo' => $a->get_baseurl() . '/images/person-80.jpg',
- ));
+ ]);
q("update user set expire_notification_sent = '%s' where uid = %d",
dbesc(datetime_convert()),
function public_server_plugin_admin ( &$a, &$o) {
$token = get_form_security_token("publicserver");
$t = get_markup_template( "admin.tpl", "addon/public_server");
- $o = replace_macros($t, array(
+ $o = replace_macros($t, [
'$submit' => t('Save Settings'),
'$form_security_token' => $token,
'$infotext' => t('Set any of these options to 0 to deactivate it.'),
- '$expiredays' => Array( "expiredays","Expire Days", intval(Config::get('public_server', 'expiredays')), "When an account is created on the site, it is given a hard "),
- '$expireposts' => Array( "expireposts", "Expire Posts", intval(Config::get('public_server','expireposts')), "Set the default days for posts to expire here"),
- '$nologin' => Array( "nologin", "No Login", intval(Config::get('public_server','nologin')), "Remove users who have never logged in after nologin days "),
- '$flagusers' => Array( "flagusers", "Flag users", intval(Config::get('public_server','flagusers')), "Remove users who last logged in over flagusers days ago"),
- '$flagposts' => Array( "flagposts", "Flag posts", intval(Config::get('public_server','flagposts')), "For users who last logged in over flagposts days ago set post expiry days to flagpostsexpire "),
- '$flagpostsexpire' => Array( "flagpostsexpire", "Flag posts expire", intval(Config::get('public_server','flagpostsexpire'))),
- ));
+ '$expiredays' => [ "expiredays","Expire Days", intval(Config::get('public_server', 'expiredays')), "When an account is created on the site, it is given a hard "],
+ '$expireposts' => [ "expireposts", "Expire Posts", intval(Config::get('public_server','expireposts')), "Set the default days for posts to expire here"],
+ '$nologin' => [ "nologin", "No Login", intval(Config::get('public_server','nologin')), "Remove users who have never logged in after nologin days "],
+ '$flagusers' => [ "flagusers", "Flag users", intval(Config::get('public_server','flagusers')), "Remove users who last logged in over flagusers days ago"],
+ '$flagposts' => [ "flagposts", "Flag posts", intval(Config::get('public_server','flagposts')), "For users who last logged in over flagposts days ago set post expiry days to flagpostsexpire "],
+ '$flagpostsexpire' => [ "flagpostsexpire", "Flag posts expire", intval(Config::get('public_server','flagpostsexpire'))],
+ ]);
}
$url = "https://".$host."/api/client/register";
- $params = array();
+ $params = [];
$application_name = Config::get('pumpio', 'application_name');
// Filtering the hostname if someone is entering it with "http"
$host = $_POST['pumpio_host'];
$host = trim($host);
- $host = str_replace(array("https://", "http://"), array("", ""), $host);
+ $host = str_replace(["https://", "http://"], ["", ""], $host);
PConfig::set(local_user(),'pumpio','post',intval($_POST['pumpio']));
PConfig::set(local_user(),'pumpio','import',$_POST['pumpio_import']);
$content = bbcode($b['body'], false, false, 4);
- $params = array();
+ $params = [];
$params["verb"] = "post";
if (!$iscomment) {
- $params["object"] = array(
+ $params["object"] = [
'objectType' => "note",
- 'content' => $content);
+ 'content' => $content];
if ($title != "")
$params["object"]["displayName"] = $title;
$params["bcc"] = $receiver["bcc"];
} else {
- $inReplyTo = array("id" => $orig_post["uri"],
- "objectType" => "note");
+ $inReplyTo = ["id" => $orig_post["uri"],
+ "objectType" => "note"];
if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
$inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
- $params["object"] = array(
+ $params["object"] = [
'objectType' => "comment",
'content' => $content,
- 'inReplyTo' => $inReplyTo);
+ 'inReplyTo' => $inReplyTo];
if ($title != "")
$params["object"]["displayName"] = $title;
$url = 'https://'.$host.'/api/user/'.$user.'/feed';
if (pumpio_reachable($url))
- $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
+ $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
else
$success = false;
if (count($r))
$a->contact = $r[0]["id"];
- $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params));
+ $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $params]);
require_once('include/queue_fn.php');
add_to_queue($a->contact,NETWORK_PUMPIO,$s);
notice(t('Pump.io post failed. Queued for retry.').EOL);
$objectType = "image";
$params["verb"] = $action;
- $params["object"] = array('id' => $uri,
+ $params["object"] = ['id' => $uri,
"objectType" => $objectType,
- "content" => $content);
+ "content" => $content];
$client = new oauth_client_class;
$client->oauth_version = '1.0a';
$url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
if (pumpio_reachable($url))
- $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
+ $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
else
$success = false;
if (count($r))
$a->contact = $r[0]["id"];
- $s = serialize(array('url' => $url, 'item' => $orig_post["id"], 'post' => $params));
+ $s = serialize(['url' => $url, 'item' => $orig_post["id"], 'post' => $params]);
require_once('include/queue_fn.php');
add_to_queue($a->contact,NETWORK_PUMPIO,$s);
notice(t('Pump.io like failed. Queued for retry.').EOL);
$username = $user.'@'.$host;
if (pumpio_reachable($url))
- $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
+ $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
else
$success = false;
if ($first_time)
continue;
- $receiptians = array();
+ $receiptians = [];
if (@is_array($post->cc))
$receiptians = array_merge($receiptians, $post->cc);
return;
}
- $likedata = array();
+ $likedata = [];
$likedata['parent'] = $orig_post['id'];
$likedata['verb'] = ACTIVITY_LIKE;
$likedata['gravity'] = 3;
function pumpio_get_contact($uid, $contact, $no_insert = false) {
- GContact::update(array("url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
+ GContact::update(["url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
"photo" => $contact->image->url, "name" => $contact->displayName, "hide" => true,
"nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
- "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)));
+ "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)]);
$cid = Contact::getIdForURL($contact->url, $uid);
if ($no_insert)
if (!strstr("post|share|update", $post->verb))
return false;
- $receiptians = array();
+ $receiptians = [];
if (@is_array($post->cc))
$receiptians = array_merge($receiptians, $post->cc);
if ($receiver->id == "http://activityschema.org/collection/public")
$public = true;
- $postarray = array();
+ $postarray = [];
$postarray['network'] = NETWORK_PUMPIO;
$postarray['gravity'] = 0;
$postarray['uid'] = $uid;
$conv_parent = $conv['parent'];
- notification(array(
+ notification([
'type' => NOTIFY_COMMENT,
'notify_flags' => $user[0]['notify-flags'],
'language' => $user[0]['language'],
'verb' => ACTIVITY_POST,
'otype' => 'item',
'parent' => $conv_parent,
- ));
+ ]);
// only send one notification
break;
$url .= '?since='.urlencode($last_id);
if (pumpio_reachable($url))
- $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
+ $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user);
else
$success = false;
$url = 'https://'.$hostname.'/api/user/'.$username.'/following';
if (pumpio_reachable($url))
- $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
+ $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
else
$success = false;
$url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
if (pumpio_reachable($url))
- $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
+ $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users);
else
$success = false;
}
$client->client_secret = $consumer_secret;
if (pumpio_reachable($z['url']))
- $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
+ $success = $client->CallAPI($z['url'], 'POST', $z['post'], ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user);
else
$success = false;
function pumpio_getreceiver(&$a, $b) {
- $receiver = array();
+ $receiver = [];
if (!$b["private"]) {
$public = PConfig::get($b['uid'], "pumpio", "public");
if ($public)
- $receiver["to"][] = Array(
+ $receiver["to"][] = [
"objectType" => "collection",
- "id" => "http://activityschema.org/collection/public");
+ "id" => "http://activityschema.org/collection/public"];
} else {
$cids = explode("><", $b["allow_cid"]);
$gids = explode("><", $b["allow_gid"]);
);
if (count($r)) {
- $receiver["bcc"][] = Array(
+ $receiver["bcc"][] = [
"displayName" => $r[0]["name"],
"objectType" => "person",
"preferredUsername" => $r[0]["nick"],
- "url" => $r[0]["url"]);
+ "url" => $r[0]["url"]];
}
}
foreach ($gids AS $gid) {
);
foreach ($r AS $row)
- $receiver["bcc"][] = Array(
+ $receiver["bcc"][] = [
"displayName" => $row["name"],
"objectType" => "person",
"preferredUsername" => $row["nick"],
- "url" => $row["url"]);
+ "url" => $row["url"]];
}
}
);
if (count($r)) {
- $receiver["to"][] = Array(
+ $receiver["to"][] = [
"displayName" => $r[0]["name"],
"objectType" => "person",
"preferredUsername" => $r[0]["nick"],
- "url" => $r[0]["url"]);
+ "url" => $r[0]["url"]];
}
}
}
logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
if (pumpio_reachable($url))
- $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $item);
+ $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item);
else
$success = false;
function pumpio_reachable($url) {
- $data = z_fetch_url($url, false, $redirects, array('timeout'=>10));
+ $data = z_fetch_url($url, false, $redirects, ['timeout'=>10]);
return(intval($data['return_code']) != 0);
}
* Description: Sample Friendica plugin/addon. Set a random place when posting.
* Version: 1.0
* Author: Mike Macgirvin <http://macgirvin.com/profile/mike>
- *
- *
- *
+ *
+ *
+ *
*
* Addons are registered with the system through the admin
* panel.
* When registration is detected, the system calls the plugin
* name_install() function, located in 'addon/name/name.php',
* where 'name' is the name of the addon.
- * If the addon is removed from the configuration list, the
+ * If the addon is removed from the configuration list, the
* system will call the name_uninstall() function.
*
*/
function randplace_install() {
/**
- *
+ *
* Our demo plugin will attach in three places.
* The first is just prior to storing a local post.
*
/**
*
- * Then we'll attach into the plugin settings page, and also the
+ * Then we'll attach into the plugin settings page, and also the
* settings post hook so that we can create and update
* user preferences.
*
*
*/
- $cities = array();
+ $cities = [];
$zones = timezone_identifiers_list();
foreach($zones as $zone) {
if((strpos($zone,'/')) && (! stristr($zone,'US/')) && (! stristr($zone,'Etc/')))
/**
*
- * Called from the Plugin Setting form.
+ * Called from the Plugin Setting form.
* Add our own settings info to the page.
*
*/
* Description: Allow the recipients of private posts to see who else can see the post by clicking the lock icon
* Version: 1.0
* Author: Zach <https://f.shmuz.in/profile/techcity>
- *
+ *
*/
use Friendica\Core\Config;
/* Get the current state of our config variable */
$remote_perms = PConfig::get(local_user(),'remote_perms','show');
-
+
/* Add some HTML to the existing form */
// $t = file_get_contents("addon/remote_permissions/settings.tpl" );
$t = get_markup_template("settings.tpl", "addon/remote_permissions/" );
- $o .= replace_macros($t, array(
+ $o .= replace_macros($t, [
'$remote_perms_title' => t('Remote Permissions Settings'),
'$remote_perms_label' => t('Allow recipients of your private posts to see the other recipients of the posts'),
'$checked' => (($remote_perms == 1) ? 'checked="checked"' : ''),
'$submit' => t('Save Settings')
- ));
+ ]);
}
$r = q("SELECT nick, url FROM contact WHERE id = %d LIMIT 1",
intval($item_copy['contact-id'])
);
- if(! $r)
+ if(! $r)
return;
// Find out if the contact lives here
if(($item_copy['private'] == 1) && (! strlen($item_copy['allow_cid'])) && (! strlen($item_copy['allow_gid']))
&& (! strlen($item_copy['deny_cid'])) && (! strlen($item_copy['deny_gid']))) {
- $allow_names = array();
+ $allow_names = [];
// Check for the original post here -- that's the only way
// to definitely get all of the recipients
$deny_groups = expand_acl($item['deny_gid']);
$o = t('Visible to:') . '<br />';
- $allow = array();
- $deny = array();
+ $allow = [];
+ $deny = [];
if(count($allowed_groups)) {
$r = q("SELECT DISTINCT `contact-id` FROM group_member WHERE gid IN ( %s )",
dbesc(implode(', ', $allowed_groups))
);
- foreach($r as $rr)
+ foreach($r as $rr)
$allow[] = $rr['contact-id'];
}
$allow = array_unique($allow + $allowed_users);
$r = q("SELECT DISTINCT `contact-id` FROM group_member WHERE gid IN ( %s )",
dbesc(implode(', ', $deny_groups))
);
- foreach($r as $rr)
+ foreach($r as $rr)
$deny[] = $rr['contact-id'];
}
$deny = $deny + $deny_users;
if(! $r)
return;
- $allow = array();
+ $allow = [];
foreach($r as $rr)
$allow[] = $rr['uid'];
function remote_permissions_plugin_admin(&$a, &$o){
$t = get_markup_template( "admin.tpl", "addon/remote_permissions/" );
- $o = replace_macros($t, array(
+ $o = replace_macros($t, [
'$submit' => t('Save Settings'),
- '$global' => array('remotepermschoice', t('Global'), 1, t('The posts of every user on this server show the post recipients'), Config::get('remote_perms', 'global') == 1),
- '$individual' => array('remotepermschoice', t('Individual'), 2, t('Each user chooses whether his/her posts show the post recipients'), Config::get('remote_perms', 'global') == 0)
- ));
+ '$global' => ['remotepermschoice', t('Global'), 1, t('The posts of every user on this server show the post recipients'), Config::get('remote_perms', 'global') == 1],
+ '$individual' => ['remotepermschoice', t('Individual'), 2, t('Each user chooses whether his/her posts show the post recipients'), Config::get('remote_perms', 'global') == 0]
+ ]);
}
function remote_permissions_plugin_admin_post(&$a){
$duration = microtime(true)-$a->performance["start"];
- $ignored_modules = array("fbrowser");
+ $ignored_modules = ["fbrowser"];
$ignored = in_array($a->module, $ignored_modules);
if (is_site_admin() && ($_GET["mode"] != "minimal") && !$a->is_mobile && !$a->is_tablet && !$ignored) {
$t = get_markup_template('admin.tpl', 'addon/securemail/');
- $s .= replace_macros($t, array(
+ $s .= replace_macros($t, [
'$title' => t('"Secure Mail" Settings'),
'$submit' => t('Save Settings'),
'$test' => t('Save and send test'), //NOTE: update also in 'post'
- '$enable' => array('securemail-enable', t('Enable Secure Mail'), $enable, ''),
- '$publickey' => array('securemail-pkey', t('Public key'), $publickey, t('Your public PGP key, ascii armored format'), 'rows="10"')
- ));
+ '$enable' => ['securemail-enable', t('Enable Secure Mail'), $enable, ''],
+ '$publickey' => ['securemail-pkey', t('Public key'), $publickey, t('Your public PGP key, ascii armored format'), 'rows="10"']
+ ]);
}
/**
$subject = 'Friendica - Secure Mail - Test';
$message = 'This is a test message from your Friendica Secure Mail addon.';
- $params = array(
+ $params = [
'uid' => local_user(),
'fromName' => $sitename,
'fromEmail' => $sender_email,
'messageSubject' => $subject,
'htmlVersion' => "<p>{$message}</p>",
'textVersion' => $message,
- );
+ ];
// enable addon for test
PConfig::set(local_user(), 'securemail', 'enable', 1);
$key = OpenPGP_Message::parse($public_key);
- $data = new OpenPGP_LiteralDataPacket($b['textVersion'], array(
+ $data = new OpenPGP_LiteralDataPacket($b['textVersion'], [
'format' => 'u',
'filename' => 'encrypted.gpg'
- ));
- $encrypted = OpenPGP_Crypt_Symmetric::encrypt($key, new OpenPGP_Message(array($data)));
+ ]);
+ $encrypted = OpenPGP_Crypt_Symmetric::encrypt($key, new OpenPGP_Message([$data]));
$armored_encrypted = wordwrap(
OpenPGP::enarmor($encrypted->to_bytes(), 'PGP MESSAGE'),
64,
@$doc->loadHTML($doctype."<html><body>".$text."</body></html>");
$text = $doc->saveHTML();
- $text = str_replace(array("<html><body>", "</body></html>", $doctype), array("", "", ""), $text);
+ $text = str_replace(["<html><body>", "</body></html>", $doctype], ["", "", ""], $text);
return($text);
}
function smileybutton_install() {
- //Register hooks
+ //Register hooks
register_hook('jot_tool', 'addon/smileybutton/smileybutton.php', 'show_button');
-
+
logger("installed smileybutton");
}
function smileybutton_uninstall() {
//Delet registered hooks
- unregister_hook('jot_tool', 'addon/smileybutton/smileybutton.php', 'show_button');
+ unregister_hook('jot_tool', 'addon/smileybutton/smileybutton.php', 'show_button');
logger("removed smileybutton");
}
*
*/
- $texts = array(
- '<3',
- '</3',
- ':-)',
- ';-)',
- ':-(',
- ':-P',
- ':-X',
- ':-D',
- ':-O',
- '\\\\o/',
- 'O_o',
- ":\'(",
- ":-!",
- ":-/",
- ":-[",
+ $texts = [
+ '<3',
+ '</3',
+ ':-)',
+ ';-)',
+ ':-(',
+ ':-P',
+ ':-X',
+ ':-D',
+ ':-O',
+ '\\\\o/',
+ 'O_o',
+ ":\'(",
+ ":-!",
+ ":-/",
+ ":-[",
"8-)",
- ':beer',
- ':coffee',
+ ':beer',
+ ':coffee',
':facepalm',
':like',
':dislike',
'~friendica',
'red#'
- );
+ ];
- $icons = array(
+ $icons = [
'<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
'<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
'<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
'<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
'<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
'<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
- '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',
+ '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',
'<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
'<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O_o" />',
'<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
'<img class="smiley" src="' . $a->get_baseurl() . '/images/dislike.gif" alt=":dislike" />',
'<img class="smiley" src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" />',
'<img class="smiley" src="' . $a->get_baseurl() . '/images/rhash-16.png" alt="red" />'
- );
-
+ ];
+
// Call hooks to get aditional smileies from other addons
- $params = array('texts' => $texts, 'icons' => $icons, 'string' => ""); //changed
+ $params = ['texts' => $texts, 'icons' => $icons, 'string' => ""]; //changed
call_hooks('smilie', $params);
//Generate html for smiley list
//Add css to header
$css_file = 'addon/smileybutton/view/'.current_theme().'.css';
- if (! file_exists($css_file))
+ if (! file_exists($css_file))
$css_file = 'addon/smileybutton/view/default.css';
$css_url = $a->get_baseurl().'/'.$css_file;
$a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="'.$css_url.'" media="all" />'."\r\n";
-
+
//Get the correct image for the theme
$image = 'addon/smileybutton/view/'.current_theme().'.png';
- if (! file_exists($image))
+ if (! file_exists($image))
$image = 'addon/smileybutton/view/default.png';
$image_url = $a->get_baseurl().'/'.$image;
*/
function http($url, $method, $postfields = NULL)
{
- $this->http_info = array();
+ $this->http_info = [];
$ci = curl_init();
/* Curl settings */
$prx = Config::get('system', 'proxy');
curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
- curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
+ curl_setopt($ci, CURLOPT_HTTPHEADER, ['Expect:']);
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
- curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
+ curl_setopt($ci, CURLOPT_HEADERFUNCTION, [$this, 'getHeader']);
curl_setopt($ci, CURLOPT_HEADER, FALSE);
switch ($method) {
$mirrorenabled = PConfig::get(local_user(), 'statusnet', 'mirror_posts');
$mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
$import = PConfig::get(local_user(), 'statusnet', 'import');
- $importselected = array("", "", "");
+ $importselected = ["", "", ""];
$importselected[$import] = ' selected="selected"';
//$importenabled = PConfig::get(local_user(),'statusnet','import');
//$importchecked = (($importenabled) ? ' checked="checked" ' : '');
$img_str = fetch_url($image);
$tempfile = tempnam(get_temppath(), "cache");
file_put_contents($tempfile, $img_str);
- $postdata = array("status" => $msg, "media[]" => $tempfile);
+ $postdata = ["status" => $msg, "media[]" => $tempfile];
} else {
- $postdata = array("status" => $msg);
+ $postdata = ["status" => $msg];
}
// and now dent it :-)
function statusnet_plugin_admin_post(App $a)
{
- $sites = array();
+ $sites = [];
foreach ($_POST['sitename'] as $id => $sitename) {
$sitename = trim($sitename);
$key != "" &&
!x($_POST['delete'][$id])) {
- $sites[] = Array(
+ $sites[] = [
'sitename' => $sitename,
'apiurl' => $apiurl,
'consumersecret' => $secret,
'consumerkey' => $key,
//'applicationname' => $applicationname
- );
+ ];
}
}
function statusnet_plugin_admin(App $a, &$o)
{
$sites = Config::get('statusnet', 'sites');
- $sitesform = array();
+ $sitesform = [];
if (is_array($sites)) {
foreach ($sites as $id => $s) {
- $sitesform[] = Array(
- 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
- 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], t("Base API Path \x28remember the trailing /\x29")),
- 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
- 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
+ $sitesform[] = [
+ 'sitename' => ["sitename[$id]", "Site name", $s['sitename'], ""],
+ 'apiurl' => ["apiurl[$id]", "Api url", $s['apiurl'], t("Base API Path \x28remember the trailing /\x29")],
+ 'secret' => ["secret[$id]", "Secret", $s['consumersecret'], ""],
+ 'key' => ["key[$id]", "Key", $s['consumerkey'], ""],
//'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
- 'delete' => Array("delete[$id]", "Delete", False, "Check to delete this preset"),
- );
+ 'delete' => ["delete[$id]", "Delete", False, "Check to delete this preset"],
+ ];
}
}
/* empty form to add new site */
$id++;
- $sitesform[] = Array(
- 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
- 'apiurl' => Array("apiurl[$id]", "Api url", "", t("Base API Path \x28remember the trailing /\x29")),
- 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
- 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
+ $sitesform[] = [
+ 'sitename' => ["sitename[$id]", t("Site name"), "", ""],
+ 'apiurl' => ["apiurl[$id]", "Api url", "", t("Base API Path \x28remember the trailing /\x29")],
+ 'secret' => ["secret[$id]", t("Consumer Secret"), "", ""],
+ 'key' => ["key[$id]", t("Consumer Key"), "", ""],
//'applicationname' => Array("applicationname[$id]", t("Application name"), "", ""),
- );
+ ];
$t = get_markup_template("admin.tpl", "addon/statusnet/");
- $o = replace_macros($t, array(
+ $o = replace_macros($t, [
'$submit' => t('Save Settings'),
'$sites' => $sitesform,
- ));
+ ]);
}
function statusnet_prepare_body(App $a, &$b)
$connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
- $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
+ $parameters = ["exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false];
$first_time = ($lastid == "");
return -1;
}
- GContact::update(array("url" => $contact->statusnet_profile_url,
+ GContact::update(["url" => $contact->statusnet_profile_url,
"network" => NETWORK_STATUSNET, "photo" => $contact->profile_image_url,
"name" => $contact->name, "nick" => $contact->screen_name,
"location" => $contact->location, "about" => $contact->description,
- "addr" => statusnet_address($contact), "generation" => 3));
+ "addr" => statusnet_address($contact), "generation" => 3]);
$r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' AND `network` = '%s'LIMIT 1", intval($uid), dbesc(normalise_link($contact->statusnet_profile_url)), dbesc(NETWORK_STATUSNET));
return;
}
- $parameters = array();
+ $parameters = [];
if ($screen_name != "") {
$parameters["screen_name"] = $screen_name;
$api = PConfig::get($uid, 'statusnet', 'baseapi');
$hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
- $postarray = array();
+ $postarray = [];
$postarray['network'] = NETWORK_STATUSNET;
$postarray['gravity'] = 0;
$postarray['uid'] = $uid;
);
if (count($r)) {
- return array();
+ return [];
}
$contactid = 0;
$postarray['owner-link'] = $r[0]["url"];
$postarray['owner-avatar'] = $r[0]["photo"];
} else {
- return array();
+ return [];
}
}
// Don't create accounts of people who just comment something
if (($contactid == 0) && !$only_existing_contact) {
$contactid = $self['id'];
} elseif ($contactid <= 0) {
- return array();
+ return [];
}
$postarray['contact-id'] = $contactid;
$conv_parent = $conv['parent'];
- notification(array(
+ notification([
'type' => NOTIFY_COMMENT,
'notify_flags' => $user[0]['notify-flags'],
'language' => $user[0]['language'],
'verb' => ACTIVITY_POST,
'otype' => 'item',
'parent' => $conv_parent,
- ));
+ ]);
// only send one notification
break;
function statusnet_fetchhometimeline(App $a, $uid, $mode = 1)
{
- $conversations = array();
+ $conversations = [];
$ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
$csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
return;
}
- $parameters = array("exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true);
+ $parameters = ["exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true];
//$parameters["count"] = 200;
if ($mode == 1) {
if (($item != 0) && !function_exists("check_item_notification")) {
require_once 'include/enotify.php';
- notification(array(
+ notification([
'type' => NOTIFY_TAGSELF,
'notify_flags' => $u[0]['notify-flags'],
'language' => $u[0]['language'],
'verb' => ACTIVITY_TAG,
'otype' => 'item',
'parent' => $parent_id,
- ));
+ ]);
}
}
}
}
if ($no_tags) {
- return array("body" => $body, "tags" => "");
+ return ["body" => $body, "tags" => ""];
}
$str_tags = '';
}
}
- return array("body" => $body, "tags" => $str_tags);
+ return ["body" => $body, "tags" => $str_tags];
}
function statusnet_fetch_own_contact(App $a, $uid)
if(count($r)) {
foreach($r as $rr) {
- notification(array(
+ notification([
'uid' => $rr['uid'],
'type' => NOTIFY_SYSTEM,
'system_type' => 'testdrive_expire',
'source_name' => t('Administrator'),
'source_link' => $a->get_baseurl(),
'source_photo' => $a->get_baseurl() . '/images/person-80.jpg',
- ));
+ ]);
q("update user set expire_notification_sent = '%s' where uid = %d",
dbesc(datetime_convert()),
}
function tictac_app_menu($a,&$b) {
- $b['app_menu'][] = '<div class="app-title"><a href="tictac">' . t('Three Dimensional Tic-Tac-Toe') . '</a></div>';
+ $b['app_menu'][] = '<div class="app-title"><a href="tictac">' . t('Three Dimensional Tic-Tac-Toe') . '</a></div>';
}
$dimen = $a->argv[3];
$yours = $a->argv[4];
$mine = $a->argv[5];
-
+
$yours .= $_POST['move'];
}
elseif($a->argc > 1) {
$o .= '<a href="tictac/1">' . t('New game with handicap') . '</a><br />';
$o .= '<p>' . t('Three dimensional tic-tac-toe is just like the traditional game except that it is played on multiple levels simultaneously. ');
$o .= t('In this case there are three levels. You win by getting three in a row on any level, as well as up, down, and diagonally across the different levels.');
- $o .= '</p><p>';
+ $o .= '</p><p>';
$o .= t('The handicap game disables the center position on the middle level because the player claiming this square often has an unfair advantage.');
$o .= '</p>';
private $handicap = 0;
private $yours;
private $mine;
- private $winning_play;
+ private $winning_play;
private $you;
private $me;
private $debug = 1;
- private $crosses = array('011','101','110','112','121','211');
+ private $crosses = ['011','101','110','112','121','211'];
/*
'001','010','011','012','021',
'201','210','211','212','221');
*/
- private $corners = array(
+ private $corners = [
'000','002','020','022',
- '200','202','220','222');
-
- private $planes = array(
- array('000','001','002','010','011','012','020','021','022'), // horiz 1
- array('100','101','102','110','111','112','120','121','122'), // 2
- array('200','201','202','210','211','212','220','221','222'), // 3
- array('000','010','020','100','110','120','200','210','220'), // vert left
- array('000','001','002','100','101','102','200','201','202'), // vert top
- array('002','012','022','102','112','122','202','212','222'), // vert right
- array('020','021','022','120','121','122','220','221','222'), // vert bot
- array('010','011','012','110','111','112','210','211','212'), // left vertx
- array('001','011','021','101','111','221','201','211','221'), // top vertx
- array('000','001','002','110','111','112','220','221','222'), // diag top
- array('020','021','022','110','111','112','200','201','202'), // diag bot
- array('000','010','020','101','111','121','202','212','222'), // diag left
- array('002','012','022','101','111','121','200','210','220'), // diag right
- array('002','011','020','102','111','120','202','211','220'), // diag x
- array('000','011','022','100','111','122','200','211','222') // diag x
-
- );
-
-
- private $winner = array(
- array('000','001','002'), // board 0 winners - left corner across
- array('000','010','020'), // down
- array('000','011','022'), // diag
- array('001','011','021'), // middle-top down
- array('010','011','012'), // middle-left across
- array('002','011','020'), // right-top diag
- array('002','012','022'), // right-top down
- array('020','021','022'), // bottom-left across
- array('100','101','102'), // board 1 winners
- array('100','110','120'),
- array('100','111','122'),
- array('101','111','121'),
- array('110','111','112'),
- array('102','111','120'),
- array('102','112','122'),
- array('120','121','122'),
- array('200','201','202'), // board 2 winners
- array('200','210','220'),
- array('200','211','222'),
- array('201','211','221'),
- array('210','211','212'),
- array('202','211','220'),
- array('202','212','222'),
- array('220','221','222'),
- array('000','100','200'), // top-left corner 3d
- array('000','101','202'),
- array('000','110','220'),
- array('000','111','222'),
- array('001','101','201'), // top-middle 3d
- array('001','111','221'),
- array('002','102','202'), // top-right corner 3d
- array('002','101','200'),
- array('002','112','222'),
- array('002','111','220'),
- array('010','110','210'), // left-middle 3d
- array('010','111','212'),
- array('011','111','211'), // middle-middle 3d
- array('012','112','212'), // right-middle 3d
- array('012','111','210'),
- array('020','120','220'), // bottom-left corner 3d
- array('020','110','200'),
- array('020','121','222'),
- array('020','111','202'),
- array('021','121','221'), // bottom-middle 3d
- array('021','111','201'),
- array('022','122','222'), // bottom-right corner 3d
- array('022','121','220'),
- array('022','112','202'),
- array('022','111','200')
-
- );
+ '200','202','220','222'];
+
+ private $planes = [
+ ['000','001','002','010','011','012','020','021','022'], // horiz 1
+ ['100','101','102','110','111','112','120','121','122'], // 2
+ ['200','201','202','210','211','212','220','221','222'], // 3
+ ['000','010','020','100','110','120','200','210','220'], // vert left
+ ['000','001','002','100','101','102','200','201','202'], // vert top
+ ['002','012','022','102','112','122','202','212','222'], // vert right
+ ['020','021','022','120','121','122','220','221','222'], // vert bot
+ ['010','011','012','110','111','112','210','211','212'], // left vertx
+ ['001','011','021','101','111','221','201','211','221'], // top vertx
+ ['000','001','002','110','111','112','220','221','222'], // diag top
+ ['020','021','022','110','111','112','200','201','202'], // diag bot
+ ['000','010','020','101','111','121','202','212','222'], // diag left
+ ['002','012','022','101','111','121','200','210','220'], // diag right
+ ['002','011','020','102','111','120','202','211','220'], // diag x
+ ['000','011','022','100','111','122','200','211','222'] // diag x
+
+ ];
+
+
+ private $winner = [
+ ['000','001','002'], // board 0 winners - left corner across
+ ['000','010','020'], // down
+ ['000','011','022'], // diag
+ ['001','011','021'], // middle-top down
+ ['010','011','012'], // middle-left across
+ ['002','011','020'], // right-top diag
+ ['002','012','022'], // right-top down
+ ['020','021','022'], // bottom-left across
+ ['100','101','102'], // board 1 winners
+ ['100','110','120'],
+ ['100','111','122'],
+ ['101','111','121'],
+ ['110','111','112'],
+ ['102','111','120'],
+ ['102','112','122'],
+ ['120','121','122'],
+ ['200','201','202'], // board 2 winners
+ ['200','210','220'],
+ ['200','211','222'],
+ ['201','211','221'],
+ ['210','211','212'],
+ ['202','211','220'],
+ ['202','212','222'],
+ ['220','221','222'],
+ ['000','100','200'], // top-left corner 3d
+ ['000','101','202'],
+ ['000','110','220'],
+ ['000','111','222'],
+ ['001','101','201'], // top-middle 3d
+ ['001','111','221'],
+ ['002','102','202'], // top-right corner 3d
+ ['002','101','200'],
+ ['002','112','222'],
+ ['002','111','220'],
+ ['010','110','210'], // left-middle 3d
+ ['010','111','212'],
+ ['011','111','211'], // middle-middle 3d
+ ['012','112','212'], // right-middle 3d
+ ['012','111','210'],
+ ['020','120','220'], // bottom-left corner 3d
+ ['020','110','200'],
+ ['020','121','222'],
+ ['020','111','202'],
+ ['021','121','221'], // bottom-middle 3d
+ ['021','111','201'],
+ ['022','122','222'], // bottom-right corner 3d
+ ['022','121','220'],
+ ['022','112','202'],
+ ['022','111','200']
+
+ ];
function __construct($dimen,$handicap,$mefirst,$yours,$mine) {
$this->dimen = 3;
$this->mine .= $move;
$this->me = $this->parse_moves('me');
}
- else {
+ else {
$move = $this->offensive_move();
if(strlen($move)) {
$this->mine .= $move;
$str = $this->mine;
if($player == 'you')
$str = $this->yours;
- $ret = array();
+ $ret = [];
while(strlen($str)) {
$ret[] = substr($str,0,3);
$str = substr($str,3);
if($this->handicap) {
$p = $this->uncontested_plane();
foreach($this->corners as $c)
- if((in_array($c,$p))
+ if((in_array($c,$p))
&& (! $this->is_yours($c)) && (! $this->is_mine($c)))
return($c);
}
if(in_array($this->me[0],$this->corners)) {
$p = $this->my_best_plane();
foreach($this->winner as $w) {
- if((in_array($w[0],$this->you))
+ if((in_array($w[0],$this->you))
|| (in_array($w[1],$this->you))
|| (in_array($w[2],$this->you)))
- continue;
- if(in_array($w[0],$this->corners)
+ continue;
+ if(in_array($w[0],$this->corners)
&& in_array($w[2],$this->corners)
&& in_array($w[0],$p) && in_array($w[2],$p)) {
if($this->me[0] == $w[0])
else {
$r = $this->get_corners($this->me);
if(count($r) > 1) {
- $w1 = array(); $w2 = array();
+ $w1 = []; $w2 = [];
foreach($this->winner as $w) {
if(in_array('111',$w))
continue;
if(count($w1) && count($w2)) {
foreach($w1 as $a) {
foreach($w2 as $b) {
- if((in_array($a[0],$this->you))
+ if((in_array($a[0],$this->you))
|| (in_array($a[1],$this->you))
|| (in_array($a[2],$this->you))
|| (in_array($b[0],$this->you))
|| (in_array($b[1],$this->you))
|| (in_array($b[2],$this->you)))
- continue;
+ continue;
if(($a[0] == $b[0]) && ! $this->is_mine($a[0])) {
return $a[0];
}
// && in_array($this->you[0],$this->corners)
// && $this->is_neighbor($this->me[0],$this->you[0])) {
- // Yuck. You foiled my plan. Since you obviously aren't playing to win,
- // I'll try again. You may keep me busy for a few rounds, but I'm
+ // Yuck. You foiled my plan. Since you obviously aren't playing to win,
+ // I'll try again. You may keep me busy for a few rounds, but I'm
// gonna' get you eventually.
// $p = $this->uncontested_plane();
// find all the winners containing my points.
- $mywinners = array();
+ $mywinners = [];
foreach($this->winner as $w)
foreach($this->me as $m)
if((in_array($m,$w)) && (! in_array($w,$mywinners)))
$mywinners[] = $w;
// find all the rules where my points are in the center.
- $trythese = array();
+ $trythese = [];
if(count($mywinners)) {
foreach($mywinners as $w) {
foreach($this->me as $m) {
}
}
- $myplanes = array();
+ $myplanes = [];
for($p = 0; $p < count($this->planes); $p ++) {
if($this->handicap && in_array('111',$this->planes[$p]))
continue;
foreach($this->me as $m)
- if((in_array($m,$this->planes[$p]))
+ if((in_array($m,$this->planes[$p]))
&& (! in_array($this->planes[$p],$myplanes)))
$myplanes[] = $this->planes[$p];
}
shuffle($myplanes);
// find all winners which share an endpoint, and which are uncontested
- $candidates = array();
+ $candidates = [];
if(count($trythese) && count($myplanes)) {
foreach($trythese as $t) {
foreach($this->winner as $w) {
// Find out if we are about to force a win.
// Looking for two winning vectors with a common endpoint
- // and where we own the middle of both - we are now going to
+ // and where we own the middle of both - we are now going to
// grab the endpoint. The game isn't yet over but we've already won.
if(count($candidates)) {
}
// find opponents planes
- $yourplanes = array();
+ $yourplanes = [];
for($p = 0; $p < count($this->planes); $p ++) {
if($this->handicap && in_array('111',$this->planes[$p]))
continue;
// We now have a list of winning strategy vectors for our second point
// Pick one that will force you into defensive mode.
// Pick a point close to you so we don't risk giving you two
- // in a row when you block us. That would force *us* into
+ // in a row when you block us. That would force *us* into
// defensive mode.
// We want: or: not:
// X|O| X| | X| |
if(count($this->you) == 1) {
foreach($this->winner as $w) {
- if(in_array($this->me[0], $w) && in_array($c[1],$w)
- && $this->uncontested_winner($w)
+ if(in_array($this->me[0], $w) && in_array($c[1],$w)
+ && $this->uncontested_winner($w)
&& $this->is_neighbor($this->you[0],$c[1])) {
return($c[1]);
- }
+ }
}
}
- }
+ }
- // You're somewhere else entirely or have made more than one move
+ // You're somewhere else entirely or have made more than one move
// - any strategy vector which puts you on the defense will have to do
foreach($candidates as $c) {
foreach($this->winner as $w) {
- if(in_array($this->me[0], $w) && in_array($c[1],$w)
+ if(in_array($this->me[0], $w) && in_array($c[1],$w)
&& $this->uncontested_winner($w)) {
return($c[1]);
- }
+ }
}
}
}
- // worst case scenario, no strategy we can play,
+ // worst case scenario, no strategy we can play,
// just find an empty space and take it
for($x = 0; $x < $this->dimen; $x ++)
for($y = 0; $y < $this->dimen; $y ++)
for($z = 0; $z < $this->dimen; $z ++)
- if((! $this->marked_yours($x,$y,$z))
+ if((! $this->marked_yours($x,$y,$z))
&& (! $this->marked_mine($x,$y,$z))) {
if($this->handicap && $x == 1 && $y == 1 && $z == 1)
continue;
return(sprintf("%d%d%d",$x,$y,$z));
}
-
+
return '';
}
}
function get_corners($a) {
- $total = array();
+ $total = [];
if(count($a))
foreach($a as $b)
if(in_array($b,$this->corners))
function my_best_plane() {
- $second_choice = array();
+ $second_choice = [];
shuffle($this->planes);
for($p = 0; $p < count($this->planes); $p ++ ) {
$contested = 0;
continue;
foreach($this->you as $m) {
if(in_array($m,$this->planes[$p]))
- $contested ++;
+ $contested ++;
}
if(! $contested)
return($this->planes[$p]);
if($this->handicap && in_array('111',$pl[$p]))
continue;
foreach($this->you as $m) {
- if(in_array($m,$pl[$p]))
- $freeplane = false;
+ if(in_array($m,$pl[$p]))
+ $freeplane = false;
}
if(! $freeplane) {
$freeplane = true;
if($freeplane)
return($pl[$p]);
}
- return array();
+ return [];
}
function fullboard() {
$bordertop = (($y != 0) ? " border-top: 2px solid #000;" : "");
$borderleft = (($z != 0) ? " border-left: 2px solid #000;" : "");
if($this->handicap && $x == 1 && $y == 1 && $z == 1)
- $o .= "<td style=\"width: 25px; height: 25px; $bordertop $borderleft\" align=\"center\"> </td>";
+ $o .= "<td style=\"width: 25px; height: 25px; $bordertop $borderleft\" align=\"center\"> </td>";
elseif($this->marked_yours($x,$y,$z))
$o .= "<td style=\"width: 25px; height: 25px; $bordertop $borderleft $winner\" align=\"center\">X</td>";
elseif($this->marked_mine($x,$y,$z))
function tumblr_plugin_admin(&$a, &$o){
$t = get_markup_template( "admin.tpl", "addon/tumblr/" );
- $o = replace_macros($t, array(
+ $o = replace_macros($t, [
'$submit' => t('Save Settings'),
// name, label, value, help, [extra values]
- '$consumer_key' => array('consumer_key', t('Consumer Key'), Config::get('tumblr', 'consumer_key' ), ''),
- '$consumer_secret' => array('consumer_secret', t('Consumer Secret'), Config::get('tumblr', 'consumer_secret' ), ''),
- ));
+ '$consumer_key' => ['consumer_key', t('Consumer Key'), Config::get('tumblr', 'consumer_key' ), ''],
+ '$consumer_secret' => ['consumer_secret', t('Consumer Secret'), Config::get('tumblr', 'consumer_secret' ), ''],
+ ]);
}
function tumblr_plugin_admin_post(&$a){
$userinfo = $tum_oauth->get('user/info');
- $blogs = array();
+ $blogs = [];
$s .= '<label id="tumblr-page-label" for="tumblr-page">' . t('Post to page:') . '</label>';
$s .= '<select name="tumblr_page" id="tumblr-page">';
foreach($userinfo->response->user->blogs as $blog) {
- $blogurl = substr(str_replace(array("http://", "https://"), array("", ""), $blog->url), 0, -1);
+ $blogurl = substr(str_replace(["http://", "https://"], ["", ""], $blog->url), 0, -1);
if ($page == $blogurl)
$s .= "<option value='".$blogurl."' selected>".$blogurl."</option>";
else
require_once('include/bbcode.php');
- $tag_arr = array();
+ $tag_arr = [];
$tags = '';
$x = preg_match_all('/\#\[(.*?)\](.*?)\[/',$b['tag'],$matches,PREG_SET_ORDER);
$siteinfo = get_attached_data($b["body"]);
- $params = array(
+ $params = [
'state' => 'published',
'tags' => $tags,
'tweet' => 'off',
- 'format' => 'html');
+ 'format' => 'html'];
if (!isset($siteinfo["type"]))
$siteinfo["type"] = "";
$cb->setConsumerKey($ckey, $csecret);
$cb->setToken($otoken, $osecret);
- $parameters = array();
+ $parameters = [];
$parameters["screen_name"] = $nickname;
$user = $cb->friendships_create($parameters);
</div>';
$s .= '<div class="clear"></div>';
- $s .= replace_macros($field_checkbox, array(
- '$field' => array('twitter-enable', t('Allow posting to Twitter'), $enabled, t('If enabled all your <strong>public</strong> postings can be posted to the associated Twitter account. You can choose to do so by default (here) or for every posting separately in the posting options when writing the entry.'))
- ));
+ $s .= replace_macros($field_checkbox, [
+ '$field' => ['twitter-enable', t('Allow posting to Twitter'), $enabled, t('If enabled all your <strong>public</strong> postings can be posted to the associated Twitter account. You can choose to do so by default (here) or for every posting separately in the posting options when writing the entry.')]
+ ]);
if ($a->user['hidewall']) {
$s .= '<p>' . t('<strong>Note</strong>: Due to your privacy settings (<em>Hide your profile details from unknown viewers?</em>) the link potentially included in public postings relayed to Twitter will lead the visitor to a blank page informing the visitor that the access to your profile has been restricted.') . '</p>';
}
- $s .= replace_macros($field_checkbox, array(
- '$field' => array('twitter-default', t('Send public postings to Twitter by default'), $defenabled, '')
- ));
- $s .= replace_macros($field_checkbox, array(
- '$field' => array('twitter-mirror', t('Mirror all posts from twitter that are no replies'), $mirrorenabled, '')
- ));
- $s .= replace_macros($field_checkbox, array(
- '$field' => array('twitter-import', t('Import the remote timeline'), $importenabled, '')
- ));
- $s .= replace_macros($field_checkbox, array(
- '$field' => array('twitter-create_user', t('Automatically create contacts'), $create_userenabled, '')
- ));
+ $s .= replace_macros($field_checkbox, [
+ '$field' => ['twitter-default', t('Send public postings to Twitter by default'), $defenabled, '']
+ ]);
+ $s .= replace_macros($field_checkbox, [
+ '$field' => ['twitter-mirror', t('Mirror all posts from twitter that are no replies'), $mirrorenabled, '']
+ ]);
+ $s .= replace_macros($field_checkbox, [
+ '$field' => ['twitter-import', t('Import the remote timeline'), $importenabled, '']
+ ]);
+ $s .= replace_macros($field_checkbox, [
+ '$field' => ['twitter-create_user', t('Automatically create contacts'), $create_userenabled, '']
+ ]);
$s .= '<div class="clear"></div>';
$s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
$cb->setConsumerKey($ckey, $csecret);
$cb->setToken($otoken, $osecret);
- $post = array('id' => $pid);
+ $post = ['id' => $pid];
logger("twitter_action '" . $action . "' ID: " . $pid . " data: " . print_r($post, true), LOGGER_DATA);
$cb->setConsumerKey($ckey, $csecret);
$cb->setToken($otoken, $osecret);
- $post = array('status' => $msg, 'media[]' => $tempfile);
+ $post = ['status' => $msg, 'media[]' => $tempfile];
if ($iscomment) {
$post["in_reply_to_status_id"] = substr($orig_post["uri"], 9);
}
// -----------------
$url = 'statuses/update';
- $post = array('status' => $msg, 'weighted_character_count' => 'true');
+ $post = ['status' => $msg, 'weighted_character_count' => 'true'];
if ($iscomment) {
$post["in_reply_to_status_id"] = substr($orig_post["uri"], 9);
$a->contact = $r[0]["id"];
}
- $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $post));
+ $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $post]);
require_once 'include/queue_fn.php';
add_to_queue($a->contact, NETWORK_TWITTER, $s);
notice(t('Twitter post failed. Queued for retry.') . EOL);
{
$t = get_markup_template("admin.tpl", "addon/twitter/");
- $o = replace_macros($t, array(
+ $o = replace_macros($t, [
'$submit' => t('Save Settings'),
// name, label, value, help, [extra values]
- '$consumerkey' => array('consumerkey', t('Consumer key'), Config::get('twitter', 'consumerkey'), ''),
- '$consumersecret' => array('consumersecret', t('Consumer secret'), Config::get('twitter', 'consumersecret'), ''),
- ));
+ '$consumerkey' => ['consumerkey', t('Consumer key'), Config::get('twitter', 'consumerkey'), ''],
+ '$consumersecret' => ['consumersecret', t('Consumer secret'), Config::get('twitter', 'consumersecret'), ''],
+ ]);
}
function twitter_cron(App $a, $b)
}
if (method_exists('dba', 'delete')) {
- $r = dba::select('item', array('id'), array('deleted' => true, 'network' => NETWORK_TWITTER));
+ $r = dba::select('item', ['id'], ['deleted' => true, 'network' => NETWORK_TWITTER]);
while ($row = dba::fetch($r)) {
- dba::delete('item', array('id' => $row['id']));
+ dba::delete('item', ['id' => $row['id']]);
}
dba::close($r);
} else {
if (is_object($post->retweeted_status)) {
// We don't support nested shares, so we mustn't show quotes as shares on retweets
- $item = twitter_createpost($a, $uid, $post->retweeted_status, array('id' => 0), false, false, true);
+ $item = twitter_createpost($a, $uid, $post->retweeted_status, ['id' => 0], false, false, true);
$datarray['body'] = "\n" . share_header($item['author-name'], $item['author-link'], $item['author-avatar'], "", $item['created'], $item['plink']);
$datarray['body'] .= $item['body'] . '[/share]';
} else {
- $item = twitter_createpost($a, $uid, $post, array('id' => 0), false, false, false);
+ $item = twitter_createpost($a, $uid, $post, ['id' => 0], false, false, false);
$datarray['body'] = $item['body'];
}
require_once 'library/twitteroauth.php';
$connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
- $parameters = array("exclude_replies" => true, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended");
+ $parameters = ["exclude_replies" => true, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"];
$first_time = ($lastid == "");
$avatar = twitter_fix_avatar($contact->profile_image_url_https);
- GContact::update(array("url" => "https://twitter.com/" . $contact->screen_name,
+ GContact::update(["url" => "https://twitter.com/" . $contact->screen_name,
"network" => NETWORK_TWITTER, "photo" => $avatar, "hide" => true,
"name" => $contact->name, "nick" => $contact->screen_name,
"location" => $contact->location, "about" => $contact->description,
- "addr" => $contact->screen_name . "@twitter.com", "generation" => 2));
+ "addr" => $contact->screen_name . "@twitter.com", "generation" => 2]);
$r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
intval($uid), dbesc("twitter::" . $contact->id_str));
return;
}
- $parameters = array();
+ $parameters = [];
if ($screen_name != "") {
$parameters["screen_name"] = $screen_name;
}
if ($no_tags) {
- return array("body" => $body, "tags" => "", "plain" => $plain);
+ return ["body" => $body, "tags" => "", "plain" => $plain];
}
- $tags_arr = array();
+ $tags_arr = [];
foreach ($item->entities->hashtags AS $hashtag) {
$url = "#[url=" . $a->get_baseurl() . "/search?tag=" . rawurlencode($hashtag->text) . "]" . $hashtag->text . "[/url]";
$tags = implode($tags_arr, ",");
}
- return array("body" => $body, "tags" => $tags, "plain" => $plain);
+ return ["body" => $body, "tags" => $tags, "plain" => $plain];
}
/**
}
// This is a pure media post, first search for all media urls
- $media = array();
+ $media = [];
foreach ($post->extended_entities->media AS $medium) {
switch ($medium->type) {
case 'photo':
function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_existing_contact, $noquote)
{
- $postarray = array();
+ $postarray = [];
$postarray['network'] = NETWORK_TWITTER;
$postarray['gravity'] = 0;
$postarray['uid'] = $uid;
if (count($r)) {
logger("Item with extid " . $postarray['uri'] . " found.", LOGGER_DEBUG);
- return array();
+ return [];
}
$contactid = 0;
$postarray['owner-avatar'] = $r[0]["photo"];
} else {
logger("No self contact for user " . $uid, LOGGER_DEBUG);
- return array();
+ return [];
}
}
// Don't create accounts of people who just comment something
$contactid = $self['id'];
} elseif ($contactid <= 0) {
logger("Contact ID is zero or less than zero.", LOGGER_DEBUG);
- return array();
+ return [];
}
$postarray['contact-id'] = $contactid;
$conv_parent = $conv['parent'];
- notification(array(
+ notification([
'type' => NOTIFY_COMMENT,
'notify_flags' => $user[0]['notify-flags'],
'language' => $user[0]['language'],
'verb' => ACTIVITY_POST,
'otype' => 'item',
'parent' => $conv_parent,
- ));
+ ]);
// only send one notification
break;
{
logger("twitter_fetchparentposts: Fetching for user " . $uid . " and post " . $post->id_str, LOGGER_DEBUG);
- $posts = array();
+ $posts = [];
while ($post->in_reply_to_status_id_str != "") {
- $parameters = array("trim_user" => false, "tweet_mode" => "extended", "id" => $post->in_reply_to_status_id_str);
+ $parameters = ["trim_user" => false, "tweet_mode" => "extended", "id" => $post->in_reply_to_status_id_str];
$post = $connection->get('statuses/show', $parameters);
return;
}
- $parameters = array("exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended");
+ $parameters = ["exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"];
//$parameters["count"] = 200;
// Fetching timeline
$lastid = PConfig::get($uid, 'twitter', 'lasthometimelineid');
if (($item != 0) && !function_exists("check_item_notification")) {
require_once 'include/enotify.php';
- notification(array(
+ notification([
'type' => NOTIFY_TAGSELF,
'notify_flags' => $u[0]['notify-flags'],
'language' => $u[0]['language'],
'verb' => ACTIVITY_TAG,
'otype' => 'item',
'parent' => $parent_id
- ));
+ ]);
}
}
}
* Description: Add "View Source" link to item context
* Version: 1.0
* Author: Mike Macgirvin <http://macgirvin.com/profile/mike>
- *
+ *
*/
function viewsrc_install() {
} else
$item_id = $b['item']['id'];
- $b['menu'] = array_merge( array( t('View Source') => $a->get_baseurl() . '/viewsrc/'. $item_id), $b['menu']);
+ $b['menu'] = array_merge( [ t('View Source') => $a->get_baseurl() . '/viewsrc/'. $item_id], $b['menu']);
//if((! local_user()) || (local_user() != $b['item']['uid']))
// return;
function webrtc_plugin_admin (&$a, &$o) {
$t = get_markup_template( "admin.tpl", "addon/webrtc/" );
- $o = replace_macros( $t, array(
+ $o = replace_macros( $t, [
'$submit' => t('Save Settings'),
- '$webrtcurl' => array('webrtcurl', t('WebRTC Base URL'), Config::get('webrtc','webrtcurl' ), t('Page your users will create a WebRTC chat room on. For example you could use https://live.mayfirst.org .')),
- ));
+ '$webrtcurl' => ['webrtcurl', t('WebRTC Base URL'), Config::get('webrtc','webrtcurl' ), t('Page your users will create a WebRTC chat room on. For example you could use https://live.mayfirst.org .')],
+ ]);
}
function webrtc_plugin_admin_post (&$a) {
$url = ((x($_POST, 'webrtcurl')) ? notags(trim($_POST['webrtcurl'])) : '');
}
function friendheader_widget_args(){
- return Array();
+ return [];
}
function friendheader_widget_size(){
- return Array('780px','140px');
+ return ['780px','140px'];
}
function friendheader_widget_content(&$a, $conf){
- $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.* FROM `profile`
+ $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.* FROM `profile`
LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
WHERE `user`.`uid` = %s AND `profile`.`is-default` = 1 LIMIT 1",
intval($conf['uid'])
.allcontact-link { float: right; margin: 0px; }
.contact-block-content { clear:both; }
.contact-block-div { display: block !important; float: left!important; width: 50px!important; height: 50px!important; margin: 2px!important;}
-
+
</style>";
$o .= _abs_url(contact_block());
$o .= "<a href='".$a->get_baseurl().'/profile/'.$a->profile['nickname']."' target=new>". t('Get added to this list!') ."</a>";
-
+
return $o;
}
}
function friends_widget_args(){
- return Array();
+ return [];
}
function friends_widget_size(){
- return Array('100%','200px');
+ return ['100%','200px'];
}
function friends_widget_content(&$a, $conf){
- $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.* FROM `profile`
+ $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.* FROM `profile`
LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
WHERE `user`.`uid` = %s AND `profile`.`is-default` = 1 LIMIT 1",
intval($conf['uid'])
.allcontact-link { float: right; margin: 0px; }
.contact-block-content { clear:both; }
.contact-block-div { display: block !important; float: left!important; width: 50px!important; height: 50px!important; margin: 2px!important;}
-
+
</style>";
$o .= _abs_url(contact_block());
$o .= "<a href='".$a->get_baseurl().'/profile/'.$a->profile['nickname']."'>". t('Connect on Friendica!') ."</a>";
}
function like_widget_args(){
- return Array("KEY");
+ return ["KEY"];
}
function like_widget_size(){
- return Array('60px','20px');
+ return ['60px','20px'];
}
function like_widget_content(&$a, $conf){
$args = explode(",",$_GET['a']);
-
-
+
+
$baseq="SELECT COUNT(`item`.`id`) as `c`, `p`.`id`
- FROM `item`,
- (SELECT `i`.`id` FROM `item` as `i` WHERE
+ FROM `item`,
+ (SELECT `i`.`id` FROM `item` as `i` WHERE
`i`.`visible` = 1 AND `i`.`deleted` = 0
- AND (( `i`.`wall` = 1 AND `i`.`allow_cid` = ''
- AND `i`.`allow_gid` = ''
- AND `i`.`deny_cid` = ''
- AND `i`.`deny_gid` = '' )
+ AND (( `i`.`wall` = 1 AND `i`.`allow_cid` = ''
+ AND `i`.`allow_gid` = ''
+ AND `i`.`deny_cid` = ''
+ AND `i`.`deny_gid` = '' )
OR `i`.`uid` = %d )
AND `i`.`body` LIKE '%%%s%%' LIMIT 1) as `p`
WHERE `item`.`parent` = `p`.`id` ";
-
+
// count likes
$r = q( $baseq . "AND `item`.`verb` = 'http://activitystrea.ms/schema/1.0/like'",
intval($conf['uid']),
);
$likes = $r[0]['c'];
$iid = $r[0]['id'];
-
+
// count dislikes
$r = q( $baseq . "AND `item`.`verb` = 'http://purl.org/macgirvin/dfrn/1.0/dislike'",
intval($conf['uid']),
dbesc($args[0])
);
$dislikes = $r[0]['c'];
-
-
+
+
require_once("include/conversation.php");
-
+
$o = "";
-
+
# $t = file_get_contents( dirname(__file__). "/widget_like.tpl" );
$t = get_markup_template("widget_like.tpl", "addon/widgets/");
- $o .= replace_macros($t, array(
+ $o .= replace_macros($t, [
'$like' => $likes,
'$strlike' => sprintf( tt("%d person likes this", "%d people like this", $likes), $likes),
-
+
'$dislike' => $dislikes,
'$strdislike'=> sprintf( tt("%d person doesn't like this", "%d people don't like this", $dislikes), $dislikes),
-
+
'$baseurl' => $a->get_baseurl(),
- ));
-
+ ]);
+
return $o;
}
use Friendica\Core\PConfig;
function widgets_install() {
- register_hook('plugin_settings', 'addon/widgets/widgets.php', 'widgets_settings');
+ register_hook('plugin_settings', 'addon/widgets/widgets.php', 'widgets_settings');
register_hook('plugin_settings_post', 'addon/widgets/widgets.php', 'widgets_settings_post');
logger("installed widgets");
}
function widgets_uninstall() {
- unregister_hook('plugin_settings', 'addon/widgets/widgets.php', 'widgets_settings');
+ unregister_hook('plugin_settings', 'addon/widgets/widgets.php', 'widgets_settings');
unregister_hook('plugin_settings_post', 'addon/widgets/widgets.php', 'widgets_settings_post');
}
return;
if (isset($_POST['widgets-submit'])){
PConfig::delete(local_user(), 'widgets', 'key');
-
+
}
}
function widgets_settings(&$a,&$o) {
if(! local_user())
- return;
-
-
+ return;
+
+
$key = PConfig::get(local_user(), 'widgets', 'key' );
if ($key=='') { $key = mt_rand(); PConfig::set(local_user(), 'widgets', 'key', $key); }
- $widgets = array();
+ $widgets = [];
$d = dir(dirname(__file__));
while(false !== ($f = $d->read())) {
if(substr($f,0,7)=="widget_") {
$w=$m[1];
if ($w!=""){
require_once($f);
- $widgets[] = array($w, call_user_func($w."_widget_name"));
+ $widgets[] = [$w, call_user_func($w."_widget_name")];
}
}
}
-
-
+
+
# $t = file_get_contents( dirname(__file__). "/settings.tpl" );
$t = get_markup_template("settings.tpl", "addon/widgets/");
- $o .= replace_macros($t, array(
+ $o .= replace_macros($t, [
'$submit' => t('Generate new key'),
'$baseurl' => $a->get_baseurl(),
'$title' => "Widgets",
'$key' => $key,
'$widgets_h' => t('Widgets available'),
'$widgets' => $widgets,
- ));
-
+ ]);
+
}
function widgets_module() {
function _randomAlphaNum($length){
return substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',$length)),0,$length);
-}
+}
function widgets_content(&$a) {
if (!count($r)){
if($a->argv[2]=="cb"){header('HTTP/1.0 400 Bad Request'); killme();}
return;
- }
- $conf = array();
+ }
+ $conf = [];
$conf['uid'] = $r[0]['uid'];
foreach($r as $e) { $conf[$e['k']]=$e['v']; }
-
- $o = "";
+
+ $o = "";
$widgetfile =dirname(__file__)."/widget_".$a->argv[1].".php";
if (file_exists($widgetfile)){
} else {
if($a->argv[2]=="cb"){header('HTTP/1.0 400 Bad Request'); killme();}
return;
- }
-
+ }
+
if ($a->argv[2]=="cb"){
/*header('Access-Control-Allow-Origin: *');*/
$o .= call_user_func($a->argv[1].'_widget_content',$a, $conf);
-
+
} else {
-
+
if (isset($_GET['p']) && local_user()==$conf['uid'] ) {
$o .= "<style>.f9k_widget { float: left;border:1px solid black; }</style>";
$o .= "<h1>Preview Widget</h1>";
} else {
header("content-type: application/x-javascript");
}
-
-
-
+
+
+
$widget_size = call_user_func($a->argv[1].'_widget_size');
-
+
$script = file_get_contents(dirname(__file__)."/widgets.js");
- $o .= replace_macros($script, array(
+ $o .= replace_macros($script, [
'$entrypoint' => $a->get_baseurl()."/widgets/".$a->argv[1]."/cb/",
'$key' => $conf['key'],
'$widget_id' => 'f9a_'.$a->argv[1]."_"._randomAlphaNum(6),
'$width' => $widget_size[0],
'$height' => $widget_size[1],
'$type' => $a->argv[1],
- ));
+ ]);
+
-
if (isset($_GET['p'])) {
$wargs = call_user_func($a->argv[1].'_widget_args');
$jsargs = implode("</em>,<em>", $wargs);
if ($jsargs!='') $jsargs = "&a=<em>".$jsargs."</em>";
-
+
$o .= "</script>
<br style='clear:left'/><br/>
<h4>Copy and paste this code</h4>
<code>"
-
+
.htmlspecialchars('<script src="'.$a->get_baseurl().'/widgets/'.$a->argv[1].'?k='.$conf['key'])
.$jsargs
.htmlspecialchars('"></script>')
."</code>";
-
+
return $o;
- }
-
- }
-
+ }
+
+ }
+
echo $o;
killme();
}
-
+
?>
"</wp:Tile> " .
"</wp:Notification>";
- $result = send_push($device_url, array(
+ $result = send_push($device_url, [
'X-WindowsPhone-Target: token',
'X-NotificationClass: ' . $priority,
- ), $msg);
+ ], $msg);
return $result;
}
"</wp:Toast>" .
"</wp:Notification>";
- $result = send_push($device_url, array(
+ $result = send_push($device_url, [
'X-WindowsPhone-Target: toast',
'X-NotificationClass: ' . $priority,
- ), $msg);
+ ], $msg);
return $result;
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers + array(
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $headers + [
'Content-Type: text/xml',
'charset=utf-8',
'Accept: application/*',
- )
+ ]
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $msg);
case "update_settings":
$ret = windowsphonepush_updatesettings($a);
header("Content-Type: application/json; charset=utf-8");
- echo json_encode(array('status' => $ret));
+ echo json_encode(['status' => $ret]);
killme();
break;
case "update_counterunseen":
$ret = windowsphonepush_updatecounterunseen();
header("Content-Type: application/json; charset=utf-8");
- echo json_encode(array('status' => $ret));
+ echo json_encode(['status' => $ret]);
killme();
break;
default:
}
header("Content-Type: application/json");
- echo json_encode(array('uid' => local_user(),
+ echo json_encode(['uid' => local_user(),
'enable' => $enable,
'device_url' => $device_url,
'senditemtext' => $senditemtext,
'lastpushid' => $lastpushid,
'counterunseen' => $counterunseen,
- 'addonversion' => $addonversion));
+ 'addonversion' => $addonversion]);
}
/* update_settings is used to transfer the device_url from WP device to the Friendica server
// Is it a link to an aricle, a video or a photo?
if (isset($siteinfo["type"])) {
- if (in_array($siteinfo["type"], array("link", "audio", "video", "photo"))) {
+ if (in_array($siteinfo["type"], ["link", "audio", "video", "photo"])) {
$postentry = true;
}
}
{
$t = get_markup_template("admin.tpl", "addon/xmpp/");
- $o = replace_macros($t, array(
+ $o = replace_macros($t, [
'$submit' => t('Save Settings'),
- '$bosh_proxy' => array('bosh_proxy', t('Jabber BOSH host'), Config::get('xmpp', 'bosh_proxy'), ''),
- '$central_userbase' => array('central_userbase', t('Use central userbase'), Config::get('xmpp', 'central_userbase'), t('If enabled, users will automatically login to an ejabberd server that has to be installed on this machine with synchronized credentials via the "auth_ejabberd.php" script.')),
- ));
+ '$bosh_proxy' => ['bosh_proxy', t('Jabber BOSH host'), Config::get('xmpp', 'bosh_proxy'), ''],
+ '$central_userbase' => ['central_userbase', t('Use central userbase'), Config::get('xmpp', 'central_userbase'), t('If enabled, users will automatically login to an ejabberd server that has to be installed on this machine with synchronized credentials via the "auth_ejabberd.php" script.')],
+ ]);
}
function xmpp_plugin_admin_post()
return;
}
- if (in_array($a->query_string, array("admin/federation/"))) {
+ if (in_array($a->query_string, ["admin/federation/"])) {
return;
}
return;
}
- if (in_array($a->argv[0], array("manage", "logout"))) {
+ if (in_array($a->argv[0], ["manage", "logout"])) {
$additional_commands = "converse.user.logout();\n";
} else {
$additional_commands = "";