require_once 'include/pgettext.php';
require_once 'include/nav.php';
require_once 'include/identity.php';
-require_once 'update.php';
define('FRIENDICA_PLATFORM', 'Friendica');
define('FRIENDICA_CODENAME', 'Asparagus');
}
}
+/**
+ * Return the provided variable value if it exists and is truthy or the provided
+ * default value instead.
+ *
+ * Works with initialized variables and potentially uninitialized array keys
+ *
+ * Usages:
+ * - defaults($var, $default)
+ * - defaults($array, 'key', $default)
+ *
+ * @brief Returns a defaut value if the provided variable or array key is falsy
+ * @see x()
+ * @return mixed
+ */
+function defaults() {
+ $args = func_get_args();
+
+ if (count($args) < 2) {
+ throw new BadFunctionCallException('defaults() requires at least 2 parameters');
+ }
+ if (count($args) > 3) {
+ throw new BadFunctionCallException('defaults() cannot use more than 3 parameters');
+ }
+ if (count($args) === 3 && !is_array($args[0])) {
+ throw new BadFunctionCallException('defaults($arr, $key, $def) requires an array as first parameter');
+ }
+ if (count($args) === 3 && is_null($args[1])) {
+ throw new BadFunctionCallException('defaults($arr, $key, $def) $key is null');
+ }
+
+ $default = array_pop($args);
+
+ if (call_user_func_array('x', $args)) {
+ if (count($args) === 1) {
+ $return = $args[0];
+ } else {
+ $return = $args[0][$args[1]];
+ }
+ } else {
+ $return = $default;
+ }
+
+ return $return;
+}
+
/**
* @brief Returns the baseurl.
*
function check_db($via_worker)
{
$build = Config::get('system', 'build');
- if (!x($build)) {
+
+ if (empty($build)) {
Config::set('system', 'build', DB_UPDATE_VERSION);
$build = DB_UPDATE_VERSION;
}
+
+ // We don't support upgrading from very old versions anymore
+ if ($build < NEW_UPDATE_ROUTINE_VERSION) {
+ die('You try to update from a version prior to database version 1170. The direct upgrade path is not supported. Please update to version 3.5.4 before updating to this version.');
+ }
+
if ($build != DB_UPDATE_VERSION) {
// When we cannot execute the database update via the worker, we will do it directly
if (!Worker::add(PRIORITY_CRITICAL, 'DBUpdate') && $via_worker) {
// and www.example.com vs example.com.
// We will only change the url to an ip address if there is no existing setting
- if (!x($url)) {
+ if (empty($url)) {
$url = Config::set('system', 'url', System::baseUrl());
}
if ((!link_compare($url, System::baseUrl())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $a->get_hostname))) {
function update_db(App $a)
{
$build = Config::get('system', 'build');
- if (!x($build)) {
- $build = Config::set('system', 'build', DB_UPDATE_VERSION);
+
+ if (empty($build)) {
+ Config::set('system', 'build', DB_UPDATE_VERSION);
+ $build = DB_UPDATE_VERSION;
}
if ($build != DB_UPDATE_VERSION) {
+ require_once 'update.php';
+
$stored = intval($build);
$current = intval(DB_UPDATE_VERSION);
if ($stored < $current) {
Config::load('database');
- // We're reporting a different version than what is currently installed.
- // Run any existing update scripts to bring the database up to current.
- // make sure that boot.php and update.php are the same release, we might be
- // updating right this very second and the correct version of the update.php
- // file may not be here yet. This can happen on a very busy site.
-
- if (DB_UPDATE_VERSION == UPDATE_VERSION) {
- // Compare the current structure with the defined structure
-
- $t = Config::get('database', 'dbupdate_' . DB_UPDATE_VERSION);
- if (!is_null($t)) {
- return;
- }
-
- Config::set('database', 'dbupdate_' . DB_UPDATE_VERSION, time());
-
- // run old update routine (wich could modify the schema and
- // conflits with new routine)
- for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
- $r = run_update_function($x);
- if (!$r) {
- break;
- }
- }
- if ($stored < NEW_UPDATE_ROUTINE_VERSION) {
- $stored = NEW_UPDATE_ROUTINE_VERSION;
- }
+ // Compare the current structure with the defined structure
+ $t = Config::get('database', 'dbupdate_' . DB_UPDATE_VERSION);
+ if (!is_null($t)) {
+ return;
+ }
- // run new update routine
- // it update the structure in one call
- $retval = DBStructure::update(false, true);
- if ($retval) {
- DBStructure::updateFail(
- DB_UPDATE_VERSION,
- $retval
- );
- return;
- } else {
- Config::set('database', 'dbupdate_' . DB_UPDATE_VERSION, 'success');
- }
+ Config::set('database', 'dbupdate_' . DB_UPDATE_VERSION, time());
+
+ // run update routine
+ // it update the structure in one call
+ $retval = DBStructure::update(false, true);
+ if ($retval) {
+ DBStructure::updateFail(
+ DB_UPDATE_VERSION,
+ $retval
+ );
+ return;
+ } else {
+ Config::set('database', 'dbupdate_' . DB_UPDATE_VERSION, 'success');
+ }
- // run any left update_nnnn functions in update.php
- for ($x = $stored; $x < $current; $x ++) {
- $r = run_update_function($x);
- if (!$r) {
- break;
- }
+ // run any left update_nnnn functions in update.php
+ for ($x = $stored + 1; $x <= $current; $x++) {
+ $r = run_update_function($x);
+ if (!$r) {
+ break;
}
}
}
if (local_user()) {
return false;
}
- if ((x($_SESSION, 'authenticated')) && (x($_SESSION, 'visitor_id'))) {
+ if (x($_SESSION, 'authenticated') && x($_SESSION, 'visitor_id')) {
return intval($_SESSION['visitor_id']);
}
return false;
function get_max_import_size()
{
$a = get_app();
- return ((x($a->config, 'max_import_size')) ? $a->config['max_import_size'] : 0 );
+ return (x($a->config, 'max_import_size') ? $a->config['max_import_size'] : 0);
}
function infinite_scroll_data($module)
{
if (PConfig::get(local_user(), 'system', 'infinite_scroll')
- && ($module == "network") && ($_GET["mode"] != "minimal")
+ && $module == 'network'
+ && defaults($_GET, 'mode', '') != 'minimal'
) {
// get the page number
- if (is_string($_GET["page"])) {
- $pageno = $_GET["page"];
- } else {
- $pageno = 1;
- }
+ $pageno = defaults($_GET, 'page', 1);
$reload_uri = "";
}
}
- if (($a->page_offset != "") && ! strstr($reload_uri, "&offset=")) {
+ $a = get_app();
+ if ($a->page_offset != "" && !strstr($reload_uri, "&offset=")) {
$reload_uri .= "&offset=" . urlencode($a->page_offset);
}
-Where to get started to help improve Friendica?
-===============================================
+# Where to get started to help improve Friendica
+
+<!-- markdownlint-disable MD010 MD013 -->
* [Home](help)
We are looking for helpers in all areas, whether you write text or code, whether you spread the word to convince people or design new icons.
Whether you feel like an expert or like a newbie - join us with your ideas!
-Contact us
----
+## Contact us
The discussion of Friendica development takes place in the following Friendica forums:
* The main [forum for Friendica development](https://forum.friendi.ca/profile/developers)
* The [forum for Friendica theme development](https://friendica.eu/profile/ftdevs)
-Help other users
----
+## Help other users
Remember the questions you had when you first tried Friendica?
A good place to start can be to help new people find their way around Friendica in the [general support forum](https://forum.friendi.ca/prufile/helpers).
Welcome them, answer their questions, point them to documentation or ping other helpers directly if you can't help but think you know who can.
-Translation
----
+## Translation
The documentation contains help on how to translate Friendica [at Transifex](/help/translations) where the UI is translated.
If you don't want to translate the UI, or it is already done to your satisfaction, you might want to work on the translation of the /help files?
-Design
----
+## Design
Are you good at designing things?
If you have seen Friendica you probably have ideas to improve it, haven't you?
* If you would like to work with us on enhancing the user interface, please join the [UX Watchdogs forum](https://fc.oscp.info/profile/ux-watchdogs)
* Make plans for a better Friendica interface design and share them with us.
* Tell us if you are able to realize your ideas or what kind of help you need.
-We can't promise we have the right skills in the group but we'll try.
+ We can't promise we have the right skills in the group but we'll try.
* Choose a thing to start with, e.g. work on the icon set of your favorite theme
-Programming
----
+## Programming
### Composer
For the sake of consistency between contribution and general code readability, Friendica follows the widespread [PSR-2 coding standards](http://www.php-fig.org/psr/psr-2/) to the exception of a few rules.
Here's a few primers if you are new to Friendica or to the PSR-2 coding standards:
- * Indentation is tabs, period (not PSR-2).
- * By default, strings are enclosed in single quotes, but feel free to use double quotes if it makes more sense (SQL queries, adding tabs and line feeds).
- * Operators are wrapped by spaces, e.g. `$var === true`, `$var = 1 + 2` and `'string' . $concat . 'enation'`
- * Braces are mandatory in conditions
- * Boolean operators are `&&` and `||` for PHP conditions, `AND` and `OR` for SQL queries
- * No closing PHP tag
- * No trailing spaces
+
+* Indentation is tabs, period (not PSR-2).
+* By default, strings are enclosed in single quotes, but feel free to use double quotes if it makes more sense (SQL queries, adding tabs and line feeds).
+* Operators are wrapped by spaces, e.g. `$var === true`, `$var = 1 + 2` and `'string' . $concat . 'enation'`
+* Braces are mandatory in conditions
+* Boolean operators are `&&` and `||` for PHP conditions, `AND` and `OR` for SQL queries
+* No closing PHP tag
+* No trailing spaces
Don't worry, you don't have to know by heart the PSR-2 coding standards to start contributing to Friendica.
There are a few tools you can use to check or fix your files before you commit.
The configuration file for Doxygen is located in the `util` directory of the project sources.
Run
- $> doxygen util/Doxyfile
+ $> doxygen util/Doxyfile
to generate the files which will be located in the `doc/html` subdirectory in the Friendica directory.
You can browse these files with any browser.
Have a look at our [issue tracker](https://github.com/friendica/friendica) on github!
- * Try to reproduce a bug that needs more inquiries and write down what you find out.
- * If a bug looks fixed, ask the bug reporters for feedback to find out if the bug can be closed.
- * Fix a bug if you can. Please make the pull request against the *develop* branch of the repository.
- * There is a *Junior Job* label for issues we think might be a good point to start with.
- But you don't have to limit yourself to those issues.
+* Try to reproduce a bug that needs more inquiries and write down what you find out.
+* If a bug looks fixed, ask the bug reporters for feedback to find out if the bug can be closed.
+* Fix a bug if you can. Please make the pull request against the *develop* branch of the repository.
+* There is a *Junior Job* label for issues we think might be a good point to start with.
+ But you don't have to limit yourself to those issues.
### Web interface
If you want to get involved here:
* Look at the first steps that were made (e.g. the clean theme).
-Ask us to find out whom to talk to about their experiences.
+ Ask us to find out whom to talk to about their experiences.
* Talk to design people if you know any.
* Let us know about your plans [in the dev forum](https://forum.friendi.ca/profile/developers) or the [theme developer forum](https://friendica.eu/profile/ftdevs).
-Do not worry about cross-posting.
+ Do not worry about cross-posting.
### Client software
---
+### account/update_profile (POST; AUTH)
+
+#### Parameters
+
+* name (optional): full name of the user
+* description (optional): a description of the user
+
+#### Unsupported parameters
+
+* url
+* location
+* profile_link_color
+* include_entities
+* skip_status
+
+---
+
### friendships/incoming (*; AUTH)
#### Unsupported parameters
* friendships/lookup
* account/settings
* account/update_delivery_device
-* account/update_profile
* blocks/ids
* users/show
* users/search
<?php
/**
- * @file include/api.php
* Friendica implementation of statusnet/twitter API
*
+ * @file include/api.php
* @todo Automatically detect if incoming data is HTML or BBCode
*/
use Friendica\App;
$called_api = null;
/**
- * @brief Auth API user
- *
* It is not sufficient to use local_user() to check whether someone is allowed to use the API,
* because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
* into a page, and visitors will post something without noticing it).
+ *
+ * @brief Auth API user
*/
function api_user()
{
}
/**
- * @brief Get source name from API client
- *
* Clients can send 'source' parameter to be show in post metadata
* as "sent via <source>".
* Some clients doesn't send a source param, we support ones we know
* (only Twidere, atm)
*
+ * @brief Get source name from API client
+ *
* @return string
* Client source name, default to "api" if unset/unknown
*/
}
/**
- * @brief Register API endpoint
+ * Register a function to be the endpoint for defined API path.
*
- * Register a function to be the endpont for defined API path.
+ * @brief Register API endpoint
*
* @param string $path API URL path, relative to System::baseUrl()
* @param string $func Function name to call on path request
}
/**
- * @brief Login API user
- *
* Log in user via OAuth1 or Simple HTTP Auth.
* Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
*
+ * @brief Login API user
+ *
* @param object $a App
* @hook 'authenticate'
* array $addon_auth
}
if (!x($_SERVER, 'PHP_AUTH_USER')) {
- logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
+ logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
header('WWW-Authenticate: Basic realm="Friendica"');
throw new UnauthorizedException("This API requires login");
}
*/
call_hooks('authenticate', $addon_auth);
- if (($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
+ if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
$record = $addon_auth['user_record'];
} else {
$user_id = User::authenticate(trim($user), trim($password));
}
}
- if ((! $record) || (! count($record))) {
+ if (!$record || !count($record)) {
logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
header('WWW-Authenticate: Basic realm="Friendica"');
//header('HTTP/1.0 401 Unauthorized');
}
/**
- * @brief Check HTTP method of called API
- *
* API endpoints can define which HTTP method to accept when called.
* This function check the current HTTP method agains endpoint
* registered method.
*
+ * @brief Check HTTP method of called API
+ *
* @param string $method Required methods, uppercase, separated by comma
* @return bool
*/
}
/**
- * @brief Main API entry point
- *
* Authenticate user, call registered API function, set HTTP headers
*
+ * @brief Main API entry point
+ *
* @param object $a App
* @return string API call result
*/
break;
case "json":
header("Content-Type: application/json");
- foreach ($r as $rr)
+ foreach ($r as $rr) {
$json = json_encode($rr);
- if (x($_GET, 'callback')) {
- $json = $_GET['callback'] . "(" . $json . ")";
- }
- return $json;
+ }
+ if (x($_GET, 'callback')) {
+ $json = $_GET['callback'] . "(" . $json . ")";
+ }
+ return $json;
break;
case "rss":
header("Content-Type: application/rss+xml");
*
* @param string $type Return type (xml, json, rss, as)
* @param object $e HTTPException Error object
- * @return strin error message formatted as $type
+ * @return string error message formatted as $type
*/
function api_error($type, $e)
{
$pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
+ if (!empty($profile[0]['about'])) {
+ $description = $profile[0]['about'];
+ } else {
+ $description = $uinfo[0]["about"];
+ }
+
+ if (!empty($usr[0]['default-location'])) {
+ $location = $usr[0]['default-location'];
+ } elseif (!empty($uinfo[0]["location"])) {
+ $location = $uinfo[0]["location"];
+ } else {
+ $location = $network_name;
+ }
+
$ret = array(
'id' => intval($pcontact_id),
'id_str' => (string) intval($pcontact_id),
'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
- 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
- 'description' => (($profile) ? $profile[0]['pdesc'] : null),
+ 'location' => $location,
+ 'description' => $description,
'profile_image_url' => $uinfo[0]['micro'],
'profile_image_url_https' => $uinfo[0]['micro'],
'url' => $uinfo[0]['url'],
* @param string $type Return type (atom, rss, xml, json)
* @param array $data JSON style array
*
- * @return (string|object) XML data or JSON data
+ * @return (string|object|array) XML data or JSON data
*/
function api_format_data($root_element, $type, $data)
{
- $a = get_app();
-
switch ($type) {
case "atom":
case "rss":
/**
* Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
* returns a 401 status code and an error message if not.
- * http://developer.twitter.com/doc/get/account/verify_credentials
+ * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
+ *
+ * @param string $type Return type (atom, rss, xml, json)
*/
function api_account_verify_credentials($type)
{
return api_format_data("user", $type, array('user' => $user_info));
}
-/// @TODO move to top of file or somwhere better
+/// @TODO move to top of file or somewhere better
api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
/**
* Get data from $_POST or $_GET
+ *
+ * @param string $k
*/
function requestdata($k)
{
return null;
}
-/*Waitman Gobble Mod*/
+/**
+ * Waitman Gobble Mod
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ */
function api_statuses_mediap($type)
{
$a = get_app();
/// @TODO move this to top of file or somewhere better!
api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
+/**
+ * Updates the user’s current status.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
+ */
function api_statuses_update($type)
{
return api_status_show($type);
}
-/// @TODO move to top of file or somwhere better
+/// @TODO move to top of file or somewhere better
api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
+/**
+ * Uploads an image to Friendica.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array
+ * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
+ */
function api_media_upload($type)
{
$a = get_app();
return array("media" => $returndata);
}
-/// @TODO move to top of file or somwhere better
+/// @TODO move to top of file or somewhere better
api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
+/**
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ */
function api_status_show($type)
{
$a = get_app();
/**
* Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
* The author's most recent status will be returned inline.
- * http://developer.twitter.com/doc/get/users/show
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
*/
function api_users_show($type)
{
api_register_func('api/users/show', 'api_users_show');
api_register_func('api/externalprofile/show', 'api_users_show');
+/**
+ * Search a public user account.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
+ */
function api_users_search($type)
{
$a = get_app();
if (DBM::is_result($r)) {
$k = 0;
foreach ($r as $user) {
- $user_info = api_get_user($a, $user["id"], "json");
+ $user_info = api_get_user($a, $user["id"]);
if ($type == "xml") {
$userlist[$k++.":user"] = $user_info;
api_register_func('api/search', 'api_search', true);
/**
+ * Returns the most recent statuses posted by the user and the users they follow.
+ *
+ * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
*
- * http://developer.twitter.com/doc/get/statuses/home_timeline
+ * @param string $type Return type (atom, rss, xml, json)
*
- * TODO: Optional parameters
- * TODO: Add reply info
+ * @todo Optional parameters
+ * @todo Add reply info
*/
function api_statuses_home_timeline($type)
{
api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
+/**
+ * Returns the most recent statuses from public users.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ */
function api_statuses_public_timeline($type)
{
$a = get_app();
$sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
}
- $r = dba::p("SELECT " . item_fieldlists() . "
+ $r = dba::p(
+ "SELECT " . item_fieldlists() . "
FROM `thread`
STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
" . item_joins() . "
$sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
}
- $r = dba::p("SELECT " . item_fieldlists() . "
+ $r = dba::p(
+ "SELECT " . item_fieldlists() . "
FROM `item`
" . item_joins() . "
STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
/**
+ * Returns the most recent statuses posted by users this node knows about.
+ *
* @brief Returns the list of public federated posts this node knows about
*
* @param string $type Return format: json, xml, atom, rss
$sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
}
- $r = dba::p("SELECT " . item_fieldlists() . "
+ $r = dba::p(
+ "SELECT " . item_fieldlists() . "
FROM `thread`
STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
" . item_joins() . "
api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
/**
- * @TODO nothing to say?
+ * Returns a single status.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
*/
function api_statuses_show($type)
{
api_register_func('api/statuses/show', 'api_statuses_show', true);
/**
- * @TODO nothing to say?
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @todo nothing to say?
*/
function api_conversation_show($type)
{
AND `item`.`uid` = %d AND `item`.`verb` = '%s'
AND `item`.`id`>%d $sql_extra
ORDER BY `item`.`id` DESC LIMIT %d ,%d",
- intval($id), intval(api_user()),
+ intval($id),
+ intval(api_user()),
dbesc(ACTIVITY_POST),
intval($since_id),
- intval($start), intval($count)
+ intval($start),
+ intval($count)
);
if (!DBM::is_result($r)) {
api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
/**
- * @TODO nothing to say?
+ * Repeats a status.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
*/
function api_statuses_repeat($type)
{
api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
/**
- * @TODO nothing to say?
+ * Destroys a specific status.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
*/
function api_statuses_destroy($type)
{
api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
/**
- * @TODO Nothing more than an URL to say?
- * http://developer.twitter.com/doc/get/statuses/mentions
+ * Returns the most recent mentions.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @see http://developer.twitter.com/doc/get/statuses/mentions
*/
function api_statuses_mentions($type)
{
api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
/**
+ * Returns the most recent statuses posted by the user.
+ *
* @brief Returns a user's public timeline
*
* @param string $type Either "json" or "xml"
* @return string|array
* @throws ForbiddenException
+ * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
*/
function api_statuses_user_timeline($type)
{
return api_format_data("statuses", $type, $data);
}
-/// @TODO move to top of file or somwhere better
-api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
+/// @TODO move to top of file or somewhere better
+api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
/**
- * Star/unstar an item
+ * Star/unstar an item.
* param: id : id of the item
*
- * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
*/
function api_favorites_create_destroy($type)
{
throw new BadRequestException("Invalid action ".$action);
}
- $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
+ $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
return api_format_data("status", $type, $data);
}
-/// @TODO move to top of file or somwhere better
+/// @TODO move to top of file or somewhere better
api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
+/**
+ * Returns the most recent favorite statuses.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return string|array
+ */
function api_favorites($type)
{
global $called_api;
return api_format_data("statuses", $type, $data);
}
-/// @TODO move to top of file or somwhere better
+/// @TODO move to top of file or somewhere better
api_register_func('api/favorites', 'api_favorites', true);
+/**
+ *
+ * @param array $item
+ * @param array $recipient
+ * @param array $sender
+ *
+ * @return array
+ */
function api_format_messages($item, $recipient, $sender)
{
// standard meta information
return $ret;
}
+/**
+ *
+ * @param array $item
+ *
+ * @return array
+ */
function api_convert_item($item)
{
$body = $item['body'];
);
}
+/**
+ *
+ * @param string $body
+ *
+ * @return array|false
+ */
function api_get_attachments(&$body)
{
$text = $body;
return $attachments;
}
+/**
+ *
+ * @param string $text
+ * @param string $bbcode
+ *
+ * @return array
+ * @todo Links at the first character of the post
+ */
function api_get_entitities(&$text, $bbcode)
{
- /*
- To-Do:
- * Links at the first character of the post
- */
-
$a = get_app();
$include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
foreach ($ordered_urls as $url) {
if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
&& !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
- )
+ ) {
$display_url = $url["title"];
- else {
+ } else {
$display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
$display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
- if (strlen($display_url) > 26)
+ if (strlen($display_url) > 26) {
$display_url = substr($display_url, 0, 25)."…";
+ }
}
//$start = strpos($text, $url, $offset);
foreach ($images[1] as $image) {
//$start = strpos($text, $url, $offset);
$start = iconv_strpos($text, $image, 0, "UTF-8");
- if (!($start === false))
+ if (!($start === false)) {
$ordered_images[$start] = $image;
+ }
}
//$entities["media"] = array();
$offset = 0;
$display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
$display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
- if (strlen($display_url) > 26)
+ if (strlen($display_url) > 26) {
$display_url = substr($display_url, 0, 25)."…";
+ }
$start = iconv_strpos($text, $url, $offset, "UTF-8");
if (!($start === false)) {
return $entities;
}
+
+/**
+ *
+ * @param array $item
+ * @param string $text
+ *
+ * @return string
+ */
function api_format_items_embeded_images(&$item, $text)
{
$text = preg_replace_callback(
*
* @param string $txt text
* @return array
- * name => 'name'
+ * 'name' => 'name',
* 'url => 'url'
*/
function api_contactlink_to_array($txt)
* @brief return likes, dislikes and attend status for item
*
* @param array $item array
+ * @param string $type Return type (atom, rss, xml, json)
+ *
* @return array
- * likes => int count
+ * likes => int count,
* dislikes => int count
*/
function api_format_items_activities(&$item, $type = "json")
$xml_activities["friendica:".$k] = $v;
// add user data into xml output
$k_user = 0;
- foreach ($v as $user)
+ foreach ($v as $user) {
$xml_activities["friendica:".$k][$k_user++.":user"] = $user;
+ }
}
$activities = $xml_activities;
}
/**
* @brief format items to be returned by api
*
- * @param array $r array of items
- * @param array $user_info
- * @param bool $filter_user filter items by $user_info
+ * @param array $r array of items
+ * @param array $user_info
+ * @param bool $filter_user filter items by $user_info
+ * @param string $type Return type (atom, rss, xml, json)
*/
function api_format_items($r, $user_info, $filter_user = false, $type = "json")
{
if ($item["coord"] != "") {
$coords = explode(' ', $item["coord"]);
if (count($coords) == 2) {
- if ($type == "json")
+ if ($type == "json") {
$status["geo"] = array('type' => 'Point',
'coordinates' => array((float) $coords[0],
(float) $coords[1]));
- else // Not sure if this is the official format - if someone founds a documentation we can check
+ } else {// Not sure if this is the official format - if someone founds a documentation we can check
$status["georss:point"] = $item["coord"];
+ }
}
}
$ret[] = $status;
return $ret;
}
+/**
+ * Returns the remaining number of API requests available to the user before the API limit is reached.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ */
function api_account_rate_limit_status($type)
{
if ($type == "xml") {
return api_format_data('hash', $type, array('hash' => $hash));
}
-/// @TODO move to top of file or somwhere better
+/// @TODO move to top of file or somewhere better
api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
+/**
+ * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ */
function api_help_test($type)
{
if ($type == 'xml') {
return api_format_data('ok', $type, array("ok" => $ok));
}
-/// @TODO move to top of file or somwhere better
+/// @TODO move to top of file or somewhere better
api_register_func('api/help/test', 'api_help_test', false);
+/**
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ */
function api_lists($type)
{
$ret = array();
return api_format_data('lists', $type, array("lists_list" => $ret));
}
-/// @TODO move to top of file or somwhere better
+/// @TODO move to top of file or somewhere better
api_register_func('api/lists', 'api_lists', true);
+/**
+ * Returns all lists the user subscribes to.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
+ */
function api_lists_list($type)
{
$ret = array();
return api_format_data('lists', $type, array("lists_list" => $ret));
}
-/// @TODO move to top of file or somwhere better
+/// @TODO move to top of file or somewhere better
api_register_func('api/lists/list', 'api_lists_list', true);
/**
- * @brief Returns either the friends of the follower list
- *
- * Note: Considers friends and followers lists to be private and won't return
+ * Considers friends and followers lists to be private and won't return
* anything if any user_id parameter is passed.
*
+ * @brief Returns either the friends of the follower list
+ *
* @param string $qtype Either "friends" or "followers"
* @return boolean|array
* @throws ForbiddenException
return false;
}
+ $sql_extra = '';
if ($qtype == 'friends') {
$sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
- }
- if ($qtype == 'followers') {
+ } elseif ($qtype == 'followers') {
$sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
}
/**
+ * Returns the user's friends.
+ *
* @brief Returns the list of friends of the provided user
*
* @deprecated By Twitter API in favor of friends/list
}
/**
- * @brief Returns the list of friends of the provided user
+ * Returns the user's followers.
+ *
+ * @brief Returns the list of followers of the provided user
*
* @deprecated By Twitter API in favor of friends/list
*
/// @TODO move to top of file or somewhere better
api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
+/**
+ * Returns the instance's configuration information.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ */
function api_statusnet_config($type)
{
$a = get_app();
$private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
$textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
if ($a->config['api_import_size']) {
- $texlimit = string($a->config['api_import_size']);
+ $textlimit = (string) $a->config['api_import_size'];
}
$ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
$sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
api_register_func('api/statusnet/config', 'api_statusnet_config', false);
+/**
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ */
function api_statusnet_version($type)
{
// liar
api_register_func('api/statusnet/version', 'api_statusnet_version', false);
/**
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ * @param string $qtype
+ *
* @todo use api_format_data() to return data
*/
-function api_ff_ids($type,$qtype)
+function api_ff_ids($type, $qtype)
{
$a = get_app();
$user_info = api_get_user($a);
- if ($qtype == 'friends') {
- $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
- }
- if ($qtype == 'followers') {
- $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
- }
-
- if (!$user_info["self"]) {
- $sql_extra = " AND false ";
- }
-
$stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
$r = q(
return api_format_data("ids", $type, array('id' => $ids));
}
+/**
+ * Returns the ID of every user the user is following.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
+ */
function api_friends_ids($type)
{
return api_ff_ids($type, 'friends');
}
+/**
+ * Returns the ID of every user following the user.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
+ */
function api_followers_ids($type)
{
return api_ff_ids($type, 'followers');
api_register_func('api/friends/ids', 'api_friends_ids', true);
api_register_func('api/followers/ids', 'api_followers_ids', true);
+/**
+ * Sends a new direct message.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
+ */
function api_direct_messages_new($type)
{
$a = get_app();
- if (api_user() === false) throw new ForbiddenException();
+ if (api_user() === false) {
+ throw new ForbiddenException();
+ }
- if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) return;
+ if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
+ return;
+ }
$sender = api_get_user($a);
}
return api_format_data("direct-messages", $type, $data);
-
}
/// @TODO move to top of file or somewhere better
api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
/**
+ * Destroys a direct message.
+ *
* @brief delete a direct_message from mail table through api
*
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string
+ * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
*/
function api_direct_messages_destroy($type)
{
}
}
/// @todo return JSON data like Twitter API not yet implemented
-
}
/// @TODO move to top of file or somewhere better
api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
+/**
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ * @param string $box
+ * @param string $verbose
+ *
+ * @return array|string
+ */
function api_direct_messages_box($type, $box, $verbose)
{
$a = get_app();
return api_format_data("direct-messages", $type, $data);
}
+/**
+ * Returns the most recent direct messages sent by the user.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
+ */
function api_direct_messages_sentbox($type)
{
$verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
return api_direct_messages_box($type, "sentbox", $verbose);
}
+/**
+ * Returns the most recent direct messages sent to the user.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
+ */
function api_direct_messages_inbox($type)
{
$verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
return api_direct_messages_box($type, "inbox", $verbose);
}
+/**
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ */
function api_direct_messages_all($type)
{
$verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
return api_direct_messages_box($type, "all", $verbose);
}
+/**
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ */
function api_direct_messages_conversation($type)
{
$verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
+/**
+ * Returns an OAuth Request Token.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ * @see https://oauth.net/core/1.0/#auth_step1
+ */
function api_oauth_request_token($type)
{
$oauth1 = new FKOAuth1();
killme();
}
+/**
+ * Returns an OAuth Access Token.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ * @see https://oauth.net/core/1.0/#auth_step3
+ */
function api_oauth_access_token($type)
{
$oauth1 = new FKOAuth1();
intval(api_user()),
dbesc($album)
);
- if (!DBM::is_result($r))
+ if (!DBM::is_result($r)) {
throw new BadRequestException("album not available");
+ }
// function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
// to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
* @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
*
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string
+ * @return string|array
*/
function api_fr_photo_detail($type)
{
/**
+ * Updates the user’s profile image.
+ *
* @brief updates the profile image for the user (either a specified profile or the default profile)
*
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
+ *
* @return string
+ * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
*/
function api_account_update_profile_image($type)
{
api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
+/**
+ * Update user profile
+ *
+ * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
+ *
+ * @return array|string
+ */
+function api_account_update_profile($type)
+{
+ $local_user = api_user();
+ $api_user = api_get_user(get_app());
+
+ if (!empty($_POST['name'])) {
+ dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
+ dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
+ dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
+ dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
+ }
+ if (isset($_POST['description'])) {
+ dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
+ dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
+ dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
+ }
+
+ Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
+ // Update global directory in background
+ if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
+ Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
+ }
+
+ return api_account_verify_credentials($type);
+}
+
+/// @TODO move to top of file or somewhere better
+api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
+
+/**
+ *
+ * @param string $acl_string
+ */
function check_acl_input($acl_string)
{
if ($acl_string == null || $acl_string == " ") {
return $contact_not_found;
}
+/**
+ *
+ * @param string $mediatype
+ * @param array $media
+ * @param string $type
+ * @param string $album
+ * @param string $allow_cid
+ * @param string $deny_cid
+ * @param string $allow_gid
+ * @param string $deny_gid
+ * @param string $desc
+ * @param integer $profile
+ * @param boolean $visibility
+ * @param string $photo_id
+ */
function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $profile = 0, $visibility = false, $photo_id = null)
{
$visitor = 0;
}
logger(
"File upload src: " . $src . " - filename: " . $filename .
- " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG
+ " - size: " . $filesize . " - type: " . $filetype,
+ LOGGER_DEBUG
);
// check if there was a php upload error
}
// check against max upload size within Friendica instance
$maximagesize = Config::get('system', 'maximagesize');
- if (($maximagesize) && ($filesize > $maximagesize)) {
+ if ($maximagesize && ($filesize > $maximagesize)) {
$formattedBytes = formatBytes($maximagesize);
throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
}
}
}
+/**
+ *
+ * @param string $hash
+ * @param string $allow_cid
+ * @param string $deny_cid
+ * @param string $allow_gid
+ * @param string $deny_gid
+ * @param string $filetype
+ * @param boolean $visibility
+ */
function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
{
// get data about the api authenticated user
item_store($arr);
}
+/**
+ *
+ * @param string $type
+ * @param int $scale
+ * @param string $photo_id
+ *
+ * @return array
+ */
function prepare_photo_data($type, $scale, $photo_id)
{
$scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
*/
function api_friendica_remoteauth()
{
- $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
- $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
+ $url = (x($_GET, 'url') ? $_GET['url'] : '');
+ $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
if ($url === '' || $c_url === '') {
throw new BadRequestException("Wrong parameters.");
// traditional DFRN
- $r = q(
- "SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
- dbesc($c_url),
- intval(api_user())
- );
+ $r = dba::select('contact', [], ['uid' => api_user(), 'nurl' => $c_url], ['limit' => 1]);
- if ((! DBM::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
+ if (!DBM::is_result($r) || ($r['network'] !== NETWORK_DFRN)) {
throw new BadRequestException("Unknown contact");
}
- $cid = $r[0]['id'];
+ $cid = $r['id'];
- $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
+ $dfrn_id = $orig_id = (($r['issued-id']) ? $r['issued-id'] : $r['dfrn-id']);
- if ($r[0]['duplex'] && $r[0]['issued-id']) {
- $orig_id = $r[0]['issued-id'];
+ if ($r['duplex'] && $r['issued-id']) {
+ $orig_id = $r['issued-id'];
$dfrn_id = '1:' . $orig_id;
}
- if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
- $orig_id = $r[0]['dfrn-id'];
+ if ($r['duplex'] && $r['dfrn-id']) {
+ $orig_id = $r['dfrn-id'];
$dfrn_id = '0:' . $orig_id;
}
intval(time() + 45)
);
- logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
- $dest = (($url) ? '&destination_url=' . $url : '');
+ logger($r['name'] . ' ' . $sec, LOGGER_DEBUG);
+ $dest = ($url ? '&destination_url=' . $url : '');
goaway(
- $r[0]['poll'] . '?dfrn_id=' . $dfrn_id
+ $r['poll'] . '?dfrn_id=' . $dfrn_id
. '&dfrn_version=' . DFRN_PROTOCOL_VERSION
. '&type=profile&sec=' . $sec . $dest . $quiet
);
* @brief Return the item shared, if the item contains only the [share] tag
*
* @param array $item Sharer item
- * @return array Shared item or false if not a reshare
+ * @return array|false Shared item or false if not a reshare
*/
function api_share_as_retweet(&$item)
{
$posted = "";
preg_match("/posted='(.*?)'/ism", $attributes, $matches);
- if ($matches[1] != "")
+ if ($matches[1] != "") {
$posted = $matches[1];
+ }
preg_match('/posted="(.*?)"/ism', $attributes, $matches);
if ($matches[1] != "") {
$reshared_item["edited"] = $posted;
return $reshared_item;
-
}
+/**
+ *
+ * @param string $profile
+ *
+ * @return string|false
+ * @todo remove trailing junk from profile url
+ * @todo pump.io check has to check the website
+ */
function api_get_nick($profile)
{
- /* To-Do:
- - remove trailing junk from profile url
- - pump.io check has to check the website
- */
-
$nick = "";
$r = q(
return false;
}
+/**
+ *
+ * @param array $item
+ *
+ * @return array
+ */
function api_in_reply_to($item)
{
$in_reply_to = array();
$in_reply_to['screen_name'] = null;
if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
- $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
+ $r = q(
+ "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
intval($item['uid']),
- dbesc($item['thr-parent']));
+ dbesc($item['thr-parent'])
+ );
if (DBM::is_result($r)) {
$in_reply_to['status_id'] = intval($r[0]['id']);
$in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
- $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
+ $r = q(
+ "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
WHERE `item`.`id` = %d LIMIT 1",
intval($in_reply_to['status_id'])
return $in_reply_to;
}
+/**
+ *
+ * @param string $Text
+ *
+ * @return string
+ */
function api_clean_plain_items($Text)
{
$include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
{
$data = get_attachment_data($body);
- if (!$data)
+ if (!$data) {
return $body;
-
+ }
$body = "";
- if (isset($data["text"]))
+ if (isset($data["text"])) {
$body = $data["text"];
-
- if (($body == "") && (isset($data["title"])))
+ }
+ if (($body == "") && isset($data["title"])) {
$body = $data["title"];
-
- if (isset($data["url"]))
+ }
+ if (isset($data["url"])) {
$body .= "\n".$data["url"];
-
+ }
$body .= $data["after"];
return $body;
}
+/**
+ *
+ * @param array $contacts
+ *
+ * @return array
+ */
function api_best_nickname(&$contacts)
{
$best_contact = array();
- if (count($contact) == 0)
+ if (count($contact) == 0) {
return;
+ }
- foreach ($contacts as $contact)
+ foreach ($contacts as $contact) {
if ($contact["network"] == "") {
$contact["network"] = "dfrn";
$best_contact = array($contact);
}
+ }
- if (sizeof($best_contact) == 0)
- foreach ($contacts as $contact)
- if ($contact["network"] == "dfrn")
+ if (sizeof($best_contact) == 0) {
+ foreach ($contacts as $contact) {
+ if ($contact["network"] == "dfrn") {
$best_contact = array($contact);
+ }
+ }
+ }
- if (sizeof($best_contact) == 0)
- foreach ($contacts as $contact)
- if ($contact["network"] == "dspr")
+ if (sizeof($best_contact) == 0) {
+ foreach ($contacts as $contact) {
+ if ($contact["network"] == "dspr") {
$best_contact = array($contact);
+ }
+ }
+ }
- if (sizeof($best_contact) == 0)
- foreach ($contacts as $contact)
- if ($contact["network"] == "stat")
+ if (sizeof($best_contact) == 0) {
+ foreach ($contacts as $contact) {
+ if ($contact["network"] == "stat") {
$best_contact = array($contact);
+ }
+ }
+ }
- if (sizeof($best_contact) == 0)
- foreach ($contacts as $contact)
- if ($contact["network"] == "pump")
+ if (sizeof($best_contact) == 0) {
+ foreach ($contacts as $contact) {
+ if ($contact["network"] == "pump") {
$best_contact = array($contact);
+ }
+ }
+ }
- if (sizeof($best_contact) == 0)
- foreach ($contacts as $contact)
- if ($contact["network"] == "twit")
+ if (sizeof($best_contact) == 0) {
+ foreach ($contacts as $contact) {
+ if ($contact["network"] == "twit") {
$best_contact = array($contact);
+ }
+ }
+ }
if (sizeof($best_contact) == 1) {
$contacts = $best_contact;
}
}
-// return all or a specified group of the user with the containing contacts
+/**
+ * Return all or a specified group of the user with the containing contacts.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ */
function api_friendica_group_show($type)
{
$a = get_app();
- if (api_user() === false) throw new ForbiddenException();
+ if (api_user() === false) {
+ throw new ForbiddenException();
+ }
// params
$user_info = api_get_user($a);
intval($gid)
);
// error message if specified gid is not in database
- if (!DBM::is_result($r))
+ if (!DBM::is_result($r)) {
throw new BadRequestException("gid not available");
+ }
} else {
$r = q(
"SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
-// delete the specified group of the user
+/**
+ * Delete the specified group of the user.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ */
function api_friendica_group_delete($type)
{
$a = get_app();
api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
-// create the specified group with the posted array of contacts
+/**
+ * Create the specified group with the posted array of contacts.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ */
function api_friendica_group_create($type)
{
$a = get_app();
- if (api_user() === false) throw new ForbiddenException();
+ if (api_user() === false) {
+ throw new ForbiddenException();
+ }
// params
$user_info = api_get_user($a);
$users = $json['user'];
// error if no name specified
- if ($name == "")
+ if ($name == "") {
throw new BadRequestException('group name not specified');
+ }
// get data of the specified group name
$rname = q(
dbesc($name)
);
// error message if specified group name already exists
- if (DBM::is_result($rname))
+ if (DBM::is_result($rname)) {
throw new BadRequestException('group name already exists');
+ }
// check if specified group name is a deleted group
$rname = q(
dbesc($name)
);
// error message if specified group name already exists
- if (DBM::is_result($rname))
+ if (DBM::is_result($rname)) {
$reactivate_group = true;
+ }
// create group
$ret = Group::create($uid, $name);
intval($cid),
intval($uid)
);
- if (count($contact))
+ if (count($contact)) {
$result = Group::addMember($gid, $cid);
- else {
+ } else {
$erroraddinguser = true;
$errorusers[] = $cid;
}
api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
-// update the specified group with the posted array of contacts
+/**
+ * Update the specified group with the posted array of contacts.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ */
function api_friendica_group_update($type)
{
$a = get_app();
- if (api_user() === false) throw new ForbiddenException();
+ if (api_user() === false) {
+ throw new ForbiddenException();
+ }
// params
$user_info = api_get_user($a);
$users = $json['user'];
// error if no name specified
- if ($name == "")
+ if ($name == "") {
throw new BadRequestException('group name not specified');
+ }
// error if no gid specified
- if ($gid == "")
+ if ($gid == "") {
throw new BadRequestException('gid not specified');
+ }
// remove members
$members = Contact::getByGroupId($gid);
api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
+/**
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ */
function api_friendica_activity($type)
{
$a = get_app();
- if (api_user() === false) throw new ForbiddenException();
+ if (api_user() === false) {
+ throw new ForbiddenException();
+ }
$verb = strtolower($a->argv[3]);
$verb = preg_replace("|\..*$|", "", $verb);
}
}
-/// @TODO move to top of file or somwhere better
+/// @TODO move to top of file or somewhere better
api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
{
$a = get_app();
- if (api_user() === false) throw new ForbiddenException();
- if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
+ if (api_user() === false) {
+ throw new ForbiddenException();
+ }
+ if ($a->argc!==3) {
+ throw new BadRequestException("Invalid argument count");
+ }
$nm = new NotificationsManager();
$notes = $nm->getAll(array(), "+seen -date", 50);
if ($type == "xml") {
$xmlnotes = array();
- foreach ($notes as $note)
+ foreach ($notes as $note) {
$xmlnotes[] = array("@attributes" => $note);
+ }
$notes = $xmlnotes;
}
}
/**
- * @brief Set notification as seen and returns associated item (if possible)
- *
* POST request with 'id' param as notification id
*
+ * @brief Set notification as seen and returns associated item (if possible)
+ *
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string
*/
{
$a = get_app();
- if (api_user() === false) throw new ForbiddenException();
- if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
+ if (api_user() === false) {
+ throw new ForbiddenException();
+ }
+ if ($a->argc!==4) {
+ throw new BadRequestException("Invalid argument count");
+ }
$id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
$nm = new NotificationsManager();
$note = $nm->getByID($id);
- if (is_null($note)) throw new BadRequestException("Invalid argument");
+ if (is_null($note)) {
+ throw new BadRequestException("Invalid argument");
+ }
$nm->setSeen($note);
if ($note['otype']=='item') {
return api_format_data('result', $type, array('result' => "success"));
}
-/// @TODO move to top of file or somwhere better
+/// @TODO move to top of file or somewhere better
api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
}
}
-/// @TODO move to top of file or somwhere better
+/// @TODO move to top of file or somewhere better
api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
/**
* @brief search for direct_messages containing a searchstring through api
*
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string (success: success=true if found and search_result contains found messages
+ * @return string (success: success=true if found and search_result contains found messages,
* success=false if nothing was found, search_result='nothing found',
* error: result=error with error message)
*/
return api_format_data("direct_message_search", $type, array('$result' => $success));
}
-/// @TODO move to top of file or somwhere better
+/// @TODO move to top of file or somewhere better
api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
/**
return api_format_data("terms", $type, array('terms' => $result));
}
-/// @TODO move to top of file or somwhere better
+/// @TODO move to top of file or somewhere better
api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
/*
@TODO Maybe open to implement?
To.Do:
- [pagename] => api/1.1/statuses/lookup.json
- [id] => 605138389168451584
- [include_cards] => true
- [cards_platform] => Android-12
- [include_entities] => true
- [include_my_retweet] => 1
- [include_rts] => 1
- [include_reply_count] => true
- [include_descendent_reply_count] => true
+ [pagename] => api/1.1/statuses/lookup.json
+ [id] => 605138389168451584
+ [include_cards] => true
+ [cards_platform] => Android-12
+ [include_entities] => true
+ [include_my_retweet] => 1
+ [include_rts] => 1
+ [include_reply_count] => true
+ [include_descendent_reply_count] => true
(?)
use League\HTMLToMarkdown\HtmlConverter;
-require_once 'include/oembed.php';
require_once 'include/event.php';
require_once 'library/markdown.php';
require_once 'include/html2bbcode.php';
use Friendica\App;
use Friendica\Content\Smilies;
+use Friendica\Content\OEmbed;
use Friendica\Core\Cache;
use Friendica\Core\System;
use Friendica\Core\Config;
use Friendica\Model\Contact;
use Friendica\Util\Map;
-require_once 'include/oembed.php';
require_once 'include/event.php';
require_once 'mod/proxy.php';
require_once 'include/plaintext.php';
$url = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"),
array("https://www.youtube.com/", "https://player.vimeo.com/"), $url);
- $o = oembed_fetch_url($url);
+ $o = OEmbed::fetchURL($url);
if (!is_object($o)) {
return $match[0];
return $match[0];
}
- $html = oembed_format_object($o);
+ $html = OEmbed::formatObject($o);
return $html;
}
return $newbody;
}
-function bb_ShareAttributes($share, $simplehtml) {
+function bb_ShareAttributes($share, $simplehtml)
+{
$attributes = $share[2];
$author = "";
preg_match("/author='(.*?)'/ism", $attributes, $matches);
- if ($matches[1] != "")
- $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
+ if (x($matches, 1)) {
+ $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
+ }
preg_match('/author="(.*?)"/ism', $attributes, $matches);
- if ($matches[1] != "")
+ if (x($matches, 1)) {
$author = $matches[1];
+ }
$profile = "";
preg_match("/profile='(.*?)'/ism", $attributes, $matches);
- if ($matches[1] != "")
+ if (x($matches, 1)) {
$profile = $matches[1];
+ }
preg_match('/profile="(.*?)"/ism', $attributes, $matches);
- if ($matches[1] != "")
+ if (x($matches, 1)) {
$profile = $matches[1];
+ }
$avatar = "";
preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
- if ($matches[1] != "")
+ if (x($matches, 1)) {
$avatar = $matches[1];
+ }
preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
- if ($matches[1] != "")
+ if (x($matches, 1)) {
$avatar = $matches[1];
+ }
$link = "";
preg_match("/link='(.*?)'/ism", $attributes, $matches);
- if ($matches[1] != "")
+ if (x($matches, 1)) {
$link = $matches[1];
+ }
preg_match('/link="(.*?)"/ism', $attributes, $matches);
- if ($matches[1] != "")
+ if (x($matches, 1)) {
$link = $matches[1];
+ }
$posted = "";
- $itemcache = get_itemcachepath();
-
preg_match("/posted='(.*?)'/ism", $attributes, $matches);
- if ($matches[1] != "")
+ if (x($matches, 1)) {
$posted = $matches[1];
+ }
preg_match('/posted="(.*?)"/ism', $attributes, $matches);
- if ($matches[1] != "")
+ if (x($matches, 1)) {
$posted = $matches[1];
-
- // relative dates only make sense when they aren't cached
- if ($itemcache == "")
- $reldate = (($posted) ? " " . relative_date($posted) : '');
+ }
// We only call this so that a previously unknown contact can be added.
// This is important for the function "get_contact_details_by_url".
$data = Contact::getDetailsByURL($profile);
- if (isset($data["name"]) && ($data["name"] != "") && isset($data["addr"]) && ($data["addr"] != ""))
- $userid_compact = $data["name"]." (".$data["addr"].")";
- else
- $userid_compact = GetProfileUsername($profile,$author, true);
+ if (x($data, "name") && x($data, "addr")) {
+ $userid_compact = $data["name"] . " (" . $data["addr"] . ")";
+ } else {
+ $userid_compact = GetProfileUsername($profile, $author, true);
+ }
- if (isset($data["addr"]) && ($data["addr"] != ""))
+ if (x($data, "addr")) {
$userid = $data["addr"];
- else
- $userid = GetProfileUsername($profile,$author, false);
+ } else {
+ $userid = GetProfileUsername($profile, $author, false);
+ }
- if (isset($data["name"]) && ($data["name"] != ""))
+ if (x($data, "name")) {
$author = $data["name"];
+ }
- if (isset($data["micro"]) && ($data["micro"] != ""))
+ if (x($data, "micro")) {
$avatar = $data["micro"];
+ }
$preshare = trim($share[1]);
- if ($preshare != "")
+ if ($preshare != "") {
$preshare .= "<br /><br />";
+ }
switch ($simplehtml) {
case 1:
- $text = $preshare.html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8').' <a href="'.$profile.'">'.$userid."</a>: <br />»".$share[3]."«";
+ $text = $preshare . html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8') . ' <a href="' . $profile . '">' . $userid . "</a>: <br />»" . $share[3] . "«";
break;
case 2:
- $text = $preshare.html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8').' '.$userid_compact.": <br />".$share[3];
+ $text = $preshare . html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8') . ' ' . $userid_compact . ": <br />" . $share[3];
break;
case 3: // Diaspora
- $headline .= '<b>'.html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8').$userid.':</b><br />';
+ $headline .= '<b>' . html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8') . $userid . ':</b><br />';
$text = trim($share[1]);
- if ($text != "")
+ if ($text != "") {
$text .= "<hr />";
+ }
if (substr(normalise_link($link), 0, 19) != "http://twitter.com/") {
- $text .= $headline.'<blockquote>'.trim($share[3])."</blockquote><br />";
+ $text .= $headline . '<blockquote>' . trim($share[3]) . "</blockquote><br />";
- if ($link != "")
- $text .= '<br /><a href="'.$link.'">[l]</a>';
- } else
- $text .= '<br /><a href="'.$link.'">'.$link.'</a>';
+ if ($link != "") {
+ $text .= '<br /><a href="' . $link . '">[l]</a>';
+ }
+ } else {
+ $text .= '<br /><a href="' . $link . '">' . $link . '</a>';
+ }
break;
case 4:
- $headline .= '<br /><b>'.html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8');
- $headline .= sprintf(t('<a href="%1$s" target="_blank">%2$s</a> %3$s'), $link, $userid, $posted);
+ $headline .= '<br /><b>' . html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8');
+ $headline .= t('<a href="%1$s" target="_blank">%2$s</a> %3$s', $link, $userid, $posted);
$headline .= ":</b><br />";
$text = trim($share[1]);
- if ($text != "")
+ if ($text != "") {
$text .= "<hr />";
+ }
- $text .= $headline.'<blockquote class="shared_content">'.trim($share[3])."</blockquote><br />";
+ $text .= $headline . '<blockquote class="shared_content">' . trim($share[3]) . "</blockquote><br />";
break;
case 5:
- $text = $preshare.html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8').' '.$userid_compact.": <br />".$share[3];
+ $text = $preshare . html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8') . ' ' . $userid_compact . ": <br />" . $share[3];
break;
case 6: // app.net
- $text = $preshare.">> @".$userid_compact.": <br />".$share[3];
+ $text = $preshare . ">> @" . $userid_compact . ": <br />" . $share[3];
break;
case 7: // statusnet/GNU Social
- $text = $preshare.html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')." @".$userid_compact.": ".$share[3];
+ $text = $preshare . html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8') . " @" . $userid_compact . ": " . $share[3];
break;
case 8: // twitter
- $text = $preshare."RT @".$userid_compact.": ".$share[3];
+ $text = $preshare . "RT @" . $userid_compact . ": " . $share[3];
break;
case 9: // Google+/Facebook
- $text = $preshare.html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8').' '.$userid_compact.": <br />".$share[3];
+ $text = $preshare . html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8') . ' ' . $userid_compact . ": <br />" . $share[3];
- if ($link != "")
- $text .= "<br /><br />".$link;
+ if ($link != "") {
+ $text .= "<br /><br />" . $link;
+ }
break;
default:
- $text = trim($share[1])."\n";
+ $text = trim($share[1]) . "\n";
$avatar = proxy_url($avatar, false, PROXY_SIZE_THUMB);
$tpl = get_markup_template('shared_content.tpl');
- $text .= replace_macros($tpl,
- array(
- '$profile' => $profile,
- '$avatar' => $avatar,
- '$author' => $author,
- '$link' => $link,
- '$posted' => $posted,
- '$reldate' => $reldate,
- '$content' => trim($share[3])
- )
- );
+ $text .= replace_macros($tpl, array(
+ '$profile' => $profile,
+ '$avatar' => $avatar,
+ '$author' => $author,
+ '$link' => $link,
+ '$posted' => $posted,
+ '$content' => trim($share[3])
+ )
+ );
break;
}
// $Text = preg_replace("/\[youtube\](.*?)\[\/youtube\]/", '<object width="425" height="350" type="application/x-shockwave-flash" data="http://www.youtube.com/v/$1" ><param name="movie" value="http://www.youtube.com/v/$1"></param><!--[if IE]><embed src="http://www.youtube.com/v/$1" type="application/x-shockwave-flash" width="425" height="350" /><![endif]--></object>', $Text);
// oembed tag
- $Text = oembed_bbcode2html($Text);
+ $Text = OEmbed::BBCode2HTML($Text);
// Avoid triple linefeeds through oembed
$Text = str_replace("<br style='clear:left'></span><br /><br />", "<br style='clear:left'></span><br />", $Text);
$profile_owner = $a->profile['profile_uid'];
if (!$update) {
- $tab = notags(trim($_GET['tab']));
- $tab = ( $tab ? $tab : 'posts' );
+ $tab = 'posts';
+ if (x($_GET, 'tab')) {
+ $tab = notags(trim($_GET['tab']));
+ }
if ($tab === 'posts') {
/*
* This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
$threadsid++;
- $comment = '';
$owner_url = '';
$owner_name = '';
$sparkle = '';
- if ($mode === 'search' || $mode === 'community') {
- if (((activity_match($item['verb'], ACTIVITY_LIKE)) || (activity_match($item['verb'], ACTIVITY_DISLIKE)))
- && ($item['id'] != $item['parent']))
- continue;
- $nickname = $item['nickname'];
- } else {
- $nickname = $a->user['nickname'];
- }
-
// prevent private email from leaking.
if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
continue;
'like' => '',
'dislike' => '',
'comment' => '',
- //'conv' => (($preview) ? '' : array('href'=> 'display/' . $nickname . '/' . $item['id'], 'title'=> t('View in context'))),
'conv' => (($preview) ? '' : array('href'=> 'display/'.$item['guid'], 'title'=> t('View in context'))),
'previewing' => $previewing,
'wait' => t('Please wait'),
return $o;
}
-function status_editor(App $a, $x, $notes_cid = 0, $popup = false) {
+function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
+{
$o = '';
- $geotag = (x($x, 'allow_location') ? replace_macros(get_markup_template('jot_geotag.tpl'), array()) : '');
+ $geotag = x($x, 'allow_location') ? replace_macros(get_markup_template('jot_geotag.tpl'), array()) : '';
$tpl = get_markup_template('jot-header.tpl');
$a->page['htmlhead'] .= replace_macros($tpl, array(
- '$newpost' => 'true',
- '$baseurl' => System::baseUrl(true),
- '$geotag' => $geotag,
- '$nickname' => $x['nickname'],
- '$ispublic' => t('Visible to <strong>everybody</strong>'),
- '$linkurl' => t('Please enter a link URL:'),
- '$vidurl' => t("Please enter a video link/URL:"),
- '$audurl' => t("Please enter an audio link/URL:"),
- '$term' => t('Tag term:'),
- '$fileas' => t('Save to Folder:'),
+ '$newpost' => 'true',
+ '$baseurl' => System::baseUrl(true),
+ '$geotag' => $geotag,
+ '$nickname' => $x['nickname'],
+ '$ispublic' => t('Visible to <strong>everybody</strong>'),
+ '$linkurl' => t('Please enter a link URL:'),
+ '$vidurl' => t("Please enter a video link/URL:"),
+ '$audurl' => t("Please enter an audio link/URL:"),
+ '$term' => t('Tag term:'),
+ '$fileas' => t('Save to Folder:'),
'$whereareu' => t('Where are you right now?'),
- '$delitems' => t('Delete item(s)?')
+ '$delitems' => t('Delete item(s)?')
));
$tpl = get_markup_template('jot-end.tpl');
$a->page['end'] .= replace_macros($tpl, array(
- '$newpost' => 'true',
- '$baseurl' => System::baseUrl(true),
- '$geotag' => $geotag,
- '$nickname' => $x['nickname'],
- '$ispublic' => t('Visible to <strong>everybody</strong>'),
- '$linkurl' => t('Please enter a link URL:'),
- '$vidurl' => t("Please enter a video link/URL:"),
- '$audurl' => t("Please enter an audio link/URL:"),
- '$term' => t('Tag term:'),
- '$fileas' => t('Save to Folder:'),
+ '$newpost' => 'true',
+ '$baseurl' => System::baseUrl(true),
+ '$geotag' => $geotag,
+ '$nickname' => $x['nickname'],
+ '$ispublic' => t('Visible to <strong>everybody</strong>'),
+ '$linkurl' => t('Please enter a link URL:'),
+ '$vidurl' => t("Please enter a video link/URL:"),
+ '$audurl' => t("Please enter an audio link/URL:"),
+ '$term' => t('Tag term:'),
+ '$fileas' => t('Save to Folder:'),
'$whereareu' => t('Where are you right now?')
));
$tpl = get_markup_template("jot.tpl");
$o .= replace_macros($tpl,array(
- '$return_path' => $query_str,
- '$action' => 'item',
- '$share' => (x($x,'button') ? $x['button'] : t('Share')),
- '$upload' => t('Upload photo'),
- '$shortupload' => t('upload photo'),
- '$attach' => t('Attach file'),
- '$shortattach' => t('attach file'),
- '$weblink' => t('Insert web link'),
+ '$return_path' => $query_str,
+ '$action' => 'item',
+ '$share' => defaults($x, 'button', t('Share')),
+ '$upload' => t('Upload photo'),
+ '$shortupload' => t('upload photo'),
+ '$attach' => t('Attach file'),
+ '$shortattach' => t('attach file'),
+ '$weblink' => t('Insert web link'),
'$shortweblink' => t('web link'),
- '$video' => t('Insert video link'),
- '$shortvideo' => t('video link'),
- '$audio' => t('Insert audio link'),
- '$shortaudio' => t('audio link'),
- '$setloc' => t('Set your location'),
- '$shortsetloc' => t('set location'),
- '$noloc' => t('Clear browser location'),
- '$shortnoloc' => t('clear location'),
- '$title' => $x['title'],
+ '$video' => t('Insert video link'),
+ '$shortvideo' => t('video link'),
+ '$audio' => t('Insert audio link'),
+ '$shortaudio' => t('audio link'),
+ '$setloc' => t('Set your location'),
+ '$shortsetloc' => t('set location'),
+ '$noloc' => t('Clear browser location'),
+ '$shortnoloc' => t('clear location'),
+ '$title' => defaults($x, 'title', ''),
'$placeholdertitle' => t('Set title'),
- '$category' => $x['category'],
- '$placeholdercategory' => (Feature::isEnabled(local_user(), 'categories') ? t('Categories (comma-separated list)') : ''),
- '$wait' => t('Please wait'),
- '$permset' => t('Permission settings'),
+ '$category' => defaults($x, 'category', ''),
+ '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? t('Categories (comma-separated list)') : '',
+ '$wait' => t('Please wait'),
+ '$permset' => t('Permission settings'),
'$shortpermset' => t('permissions'),
- '$ptyp' => (($notes_cid) ? 'note' : 'wall'),
- '$content' => $x['content'],
- '$post_id' => $x['post_id'],
- '$baseurl' => System::baseUrl(true),
- '$defloc' => $x['default_location'],
- '$visitor' => $x['visitor'],
- '$pvisit' => (($notes_cid) ? 'none' : $x['visitor']),
- '$public' => t('Public post'),
- '$jotnets' => $jotnets,
- '$lockstate' => $x['lockstate'],
- '$bang' => $x['bang'],
- '$profile_uid' => $x['profile_uid'],
- '$preview' => ((Feature::isEnabled($x['profile_uid'],'preview')) ? t('Preview') : ''),
- '$jotplugins' => $jotplugins,
- '$notes_cid' => $notes_cid,
- '$sourceapp' => t($a->sourcename),
- '$cancel' => t('Cancel'),
- '$rand_num' => random_digits(12),
+ '$ptyp' => $notes_cid ? 'note' : 'wall',
+ '$content' => defaults($x, 'content', ''),
+ '$post_id' => defaults($x, 'post_id', ''),
+ '$baseurl' => System::baseUrl(true),
+ '$defloc' => $x['default_location'],
+ '$visitor' => $x['visitor'],
+ '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
+ '$public' => t('Public post'),
+ '$lockstate' => $x['lockstate'],
+ '$bang' => $x['bang'],
+ '$profile_uid' => $x['profile_uid'],
+ '$preview' => Feature::isEnabled($x['profile_uid'], 'preview') ? t('Preview') : '',
+ '$jotplugins' => $jotplugins,
+ '$notes_cid' => $notes_cid,
+ '$sourceapp' => t($a->sourcename),
+ '$cancel' => t('Cancel'),
+ '$rand_num' => random_digits(12),
// ACL permissions box
- '$acl' => $x['acl'],
- '$acl_data' => $x['acl_data'],
- '$group_perms' => t('Post to Groups'),
+ '$acl' => $x['acl'],
+ '$acl_data' => $x['acl_data'],
+ '$group_perms' => t('Post to Groups'),
'$contact_perms' => t('Post to Contacts'),
- '$private' => t('Private post'),
- '$is_private' => $private_post,
- '$public_link' => $public_post_link,
+ '$private' => t('Private post'),
+ '$is_private' => $private_post,
+ '$public_link' => $public_post_link,
//jot nav tab (used in some themes)
'$message' => t('Message'),
if ($popup == true) {
- $o = '<div id="jot-popup" style="display: none;">'.$o.'</div>';
+ $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
}
return $o;
$ret = array();
foreach ($response_verbs as $v) {
$ret[$v] = array();
- $ret[$v]['count'] = ((x($conv_responses[$v], $item['uri'])) ? $conv_responses[$v][$item['uri']] : '');
- $ret[$v]['list'] = ((x($conv_responses[$v], $item['uri'])) ? $conv_responses[$v][$item['uri'] . '-l'] : '');
- $ret[$v]['self'] = ((x($conv_responses[$v], $item['uri'])) ? $conv_responses[$v][$item['uri'] . '-self'] : '0');
+ $ret[$v]['count'] = defaults($conv_responses[$v], $item['uri'], '');
+ $ret[$v]['list'] = defaults($conv_responses[$v], $item['uri'] . '-l', '');
+ $ret[$v]['self'] = defaults($conv_responses[$v], $item['uri'] . '-self', '0');
if (count($ret[$v]['list']) > MAX_LIKERS) {
$ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS);
array_push($ret[$v]['list_part'], '<a href="#" data-toggle="modal" data-target="#' . $v . 'Modal-'
+++ /dev/null
-<?php
-
-use Friendica\Core\Config;
-
-require_once 'library/ASNValue.class.php';
-require_once 'library/asn1.php';
-
-// supported algorithms are 'sha256', 'sha1'
-
-function rsa_sign($data, $key, $alg = 'sha256') {
- openssl_sign($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
- return $sig;
-}
-
-function rsa_verify($data, $sig, $key, $alg = 'sha256') {
- return openssl_verify($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
-}
-
-function DerToPem($Der, $Private = false) {
- //Encode:
- $Der = base64_encode($Der);
- //Split lines:
- $lines = str_split($Der, 65);
- $body = implode("\n", $lines);
- //Get title:
- $title = $Private ? 'RSA PRIVATE KEY' : 'PUBLIC KEY';
- //Add wrapping:
- $result = "-----BEGIN {$title}-----\n";
- $result .= $body . "\n";
- $result .= "-----END {$title}-----\n";
-
- return $result;
-}
-
-function DerToRsa($Der) {
- //Encode:
- $Der = base64_encode($Der);
- //Split lines:
- $lines = str_split($Der, 64);
- $body = implode("\n", $lines);
- //Get title:
- $title = 'RSA PUBLIC KEY';
- //Add wrapping:
- $result = "-----BEGIN {$title}-----\n";
- $result .= $body . "\n";
- $result .= "-----END {$title}-----\n";
-
- return $result;
-}
-
-function pkcs8_encode($Modulus, $PublicExponent) {
- //Encode key sequence
- $modulus = new ASNValue(ASNValue::TAG_INTEGER);
- $modulus->SetIntBuffer($Modulus);
- $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
- $publicExponent->SetIntBuffer($PublicExponent);
- $keySequenceItems = array($modulus, $publicExponent);
- $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
- $keySequence->SetSequence($keySequenceItems);
- //Encode bit string
- $bitStringValue = $keySequence->Encode();
- $bitStringValue = chr(0x00) . $bitStringValue; //Add unused bits byte
- $bitString = new ASNValue(ASNValue::TAG_BITSTRING);
- $bitString->Value = $bitStringValue;
- //Encode body
- $bodyValue = "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00" . $bitString->Encode();
- $body = new ASNValue(ASNValue::TAG_SEQUENCE);
- $body->Value = $bodyValue;
- //Get DER encoded public key:
- $PublicDER = $body->Encode();
- return $PublicDER;
-}
-
-function pkcs1_encode($Modulus, $PublicExponent) {
- //Encode key sequence
- $modulus = new ASNValue(ASNValue::TAG_INTEGER);
- $modulus->SetIntBuffer($Modulus);
- $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
- $publicExponent->SetIntBuffer($PublicExponent);
- $keySequenceItems = array($modulus, $publicExponent);
- $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
- $keySequence->SetSequence($keySequenceItems);
- //Encode bit string
- $bitStringValue = $keySequence->Encode();
- return $bitStringValue;
-}
-
-function metopem($m, $e) {
- $der = pkcs8_encode($m, $e);
- $key = DerToPem($der, false);
- return $key;
-}
-
-function pubrsatome($key, &$m, &$e)
-{
- require_once 'library/asn1.php';
-
- $lines = explode("\n", $key);
- unset($lines[0]);
- unset($lines[count($lines)]);
- $x = base64_decode(implode('', $lines));
-
- $r = ASN_BASE::parseASNString($x);
-
- $m = base64url_decode($r[0]->asnData[0]->asnData);
- $e = base64url_decode($r[0]->asnData[1]->asnData);
-}
-
-
-function rsatopem($key) {
- pubrsatome($key, $m, $e);
- return metopem($m, $e);
-}
-
-function pemtorsa($key) {
- pemtome($key, $m, $e);
- return metorsa($m, $e);
-}
-
-function pemtome($key, &$m, &$e)
-{
- $lines = explode("\n", $key);
- unset($lines[0]);
- unset($lines[count($lines)]);
- $x = base64_decode(implode('', $lines));
-
- $r = ASN_BASE::parseASNString($x);
-
- $m = base64url_decode($r[0]->asnData[1]->asnData[0]->asnData[0]->asnData);
- $e = base64url_decode($r[0]->asnData[1]->asnData[0]->asnData[1]->asnData);
-}
-
-function metorsa($m, $e) {
- $der = pkcs1_encode($m, $e);
- $key = DerToRsa($der);
- return $key;
-}
-
-function salmon_key($pubkey) {
- pemtome($pubkey, $m, $e);
- return 'RSA' . '.' . base64url_encode($m, true) . '.' . base64url_encode($e, true) ;
-}
-
-function new_keypair($bits) {
- $openssl_options = array(
- 'digest_alg' => 'sha1',
- 'private_key_bits' => $bits,
- 'encrypt_key' => false
- );
-
- $conf = Config::get('system', 'openssl_conf_file');
- if ($conf) {
- $openssl_options['config'] = $conf;
- }
- $result = openssl_pkey_new($openssl_options);
-
- if (empty($result)) {
- logger('new_keypair: failed');
- return false;
- }
-
- // Get private key
- $response = array('prvkey' => '', 'pubkey' => '');
-
- openssl_pkey_export($result, $response['prvkey']);
-
- // Get public key
- $pkey = openssl_pkey_get_details($result);
- $response['pubkey'] = $pkey["key"];
-
- return $response;
-}
require_once 'include/bbcode.php';
require_once 'include/datetime.php';
-require_once "include/conversation.php";
+require_once 'include/conversation.php';
function format_event_html($ev, $simple = false) {
if (! ((is_array($ev)) && count($ev))) {
/**
* @brief Convert an array with event data to bbcode.
- *
+ *
* @param array $ev Array which conains the event data.
* @return string The event as a bbcode formatted string.
*/
/**
* @brief Extract bbcode formatted event data from a string
* and convert it to html.
- *
+ *
* @params: string $s The string which should be parsed for event data.
* @return string The html output.
*/
/**
* @brief Extract bbcode formatted event data from a string.
- *
+ *
* @params: string $s The string which should be parsed for event data.
* @return array The array with the event information.
*/
/**
* @brief Delete an event from the event table.
- *
+ *
* Note: This function does only delete the event from the event table not its
* related entry in the item table.
- *
+ *
* @param int $event_id Event ID.
* @return void
*/
/**
* @brief Store the event.
- *
+ *
* Store the event in the event table and create an event item in the item table.
- *
+ *
* @param array $arr Array with event data.
* @return int The event id.
*/
/**
* @brief Create an array with translation strings used for events.
- *
+ *
* @return array Array with translations strings.
*/
function get_event_strings() {
* string 'adjust_start' =>
*
* @param string $sql_extra Additional sql conditions (e.g. permission request).
- *
+ *
* @return array Query results.
*/
function events_by_date($owner_uid = 0, $event_params, $sql_extra = '') {
// Show edit and drop actions only if the user is the owner of the event and the event
// is a real event (no bithdays).
+ $edit = null;
+ $copy = null;
+ $drop = null;
if (local_user() && local_user() == $rr['uid'] && $rr['type'] == 'event') {
$edit = ((! $rr['cid']) ? array(System::baseUrl() . '/events/event/' . $rr['id'], t('Edit event'), '', '') : null);
$copy = ((! $rr['cid']) ? array(System::baseUrl() . '/events/copy/' . $rr['id'], t('Duplicate event'), '', '') : null);
/**
* @brief Get all events for a user ID.
- *
+ *
* The query for events is done permission sensitive.
* If the user is the owner of the calendar he/she
* will get all of his/her available events.
/**
* @brief Format an item array with event data to HTML.
- *
+ *
* @param arr $item Array with item and event data.
* @return string HTML output.
*/
/**
* @brief Format a string with map bbcode to an array with location data.
- *
+ *
* Note: The string must only contain location data. A string with no bbcode will be
* handled as location name.
- *
+ *
* @param string $s The string with the bbcode formatted location data.
- *
+ *
* @return array The array with the location data.
* 'name' => The name of the location,<br>
* 'address' => The address of the location,<br>
<?php
+
/**
* @file include/identity.php
*/
-
use Friendica\App;
use Friendica\Content\Feature;
use Friendica\Content\ForumManager;
* @param string $nickname string
* @param int $profile int
* @param array $profiledata array
+ * @param boolean $show_connect Show connect link
*/
-function profile_load(App $a, $nickname, $profile = 0, $profiledata = array())
+function profile_load(App $a, $nickname, $profile = 0, $profiledata = array(), $show_connect = true)
{
$user = q(
"SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
dbesc($nickname)
);
- if (!$user && count($user) && !count($profiledata)) {
+ if (!$user && !count($user) && !count($profiledata)) {
logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
notice(t('Requested account is not available.') . EOL);
$a->error = 404;
return;
}
+ if (!x($a->page, 'aside')) {
+ $a->page['aside'] = '';
+ }
+
+ if ($profiledata) {
+ $a->page['aside'] .= profile_sidebar($profiledata, true, $show_connect);
+
+ if (!DBM::is_result($user)) {
+ return;
+ }
+ }
+
$pdata = get_profiledata_by_nick($nickname, $user[0]['uid'], $profile);
if (empty($pdata) && empty($profiledata)) {
"SELECT `pub_keywords` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
intval($pdata['profile_uid'])
);
- if ($x && count($x))
+ if ($x && count($x)) {
$pdata['pub_keywords'] = $x[0]['pub_keywords'];
+ }
}
$a->profile = $pdata;
$a->profile['mobile-theme'] = PConfig::get($a->profile['profile_uid'], 'system', 'mobile_theme');
$a->profile['network'] = NETWORK_DFRN;
- $a->page['title'] = $a->profile['name'] . " @ " . $a->config['sitename'];
+ $a->page['title'] = $a->profile['name'] . ' @ ' . $a->config['sitename'];
- if (!$profiledata && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
+ if (!$profiledata && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
$_SESSION['theme'] = $a->profile['theme'];
}
$a->set_template_engine(); // reset the template engine to the default in case the user's theme doesn't specify one
- $theme_info_file = "view/theme/" . current_theme() . "/theme.php";
+ $theme_info_file = 'view/theme/' . current_theme() . '/theme.php';
if (file_exists($theme_info_file)) {
require_once $theme_info_file;
}
- if (! (x($a->page, 'aside'))) {
+ if (!x($a->page, 'aside')) {
$a->page['aside'] = '';
}
if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
$a->page['aside'] .= replace_macros(
- get_markup_template('profile_edlink.tpl'),
- array(
+ get_markup_template('profile_edlink.tpl'), array(
'$editprofile' => t('Edit profile'),
'$profid' => $a->profile['id']
)
);
}
- $block = (((Config::get('system', 'block_public')) && (! local_user()) && (! remote_user())) ? true : false);
+ $block = ((Config::get('system', 'block_public') && !local_user() && !remote_user()) ? true : false);
/**
* @todo
* By now, the contact block isn't shown, when a different profile is given
* But: When this profile was on the same server, then we could display the contacts
*/
- if ($profiledata) {
- $a->page['aside'] .= profile_sidebar($profiledata, true);
- } else {
- $a->page['aside'] .= profile_sidebar($a->profile, $block);
+ if (!$profiledata) {
+ $a->page['aside'] .= profile_sidebar($a->profile, $block, $show_connect);
}
- /*if (! $block)
- $a->page['aside'] .= contact_block();*/
-
return;
}
-
/**
* @brief Get all profil data of a local user
*
* Passing a non-zero profile ID can also allow a preview of a selected profile
* by the owner
*
+ * Includes all available profile data
+ *
* @param string $nickname nick
* @param int $uid uid
* @param int $profile ID of the profile
* @returns array
- * Includes all available profile data
*/
function get_profiledata_by_nick($nickname, $uid = 0, $profile = 0)
{
return $r;
}
-
/**
* @brief Formats a profile for display in the sidebar.
*
*
* @param array $profile
* @param int $block
+ * @param boolean $show_connect Show connect link
*
* @return HTML string stuitable for sidebar inclusion
*
* @hooks 'profile_sidebar'
* array $arr
*/
-function profile_sidebar($profile, $block = 0)
+function profile_sidebar($profile, $block = 0, $show_connect = true)
{
$a = get_app();
$o = '';
$location = false;
$address = false;
- // $pdesc = true;
// This function can also use contact information in $profile
$is_contact = x($profile, 'cid');
- if ((! is_array($profile)) && (! count($profile))) {
+ if (!is_array($profile) && !count($profile)) {
return $o;
}
- $profile['picdate'] = urlencode($profile['picdate']);
+ $profile['picdate'] = urlencode(defaults($profile, 'picdate', ''));
- if (($profile['network'] != "") && ($profile['network'] != NETWORK_DFRN)) {
+ if (($profile['network'] != '') && ($profile['network'] != NETWORK_DFRN)) {
$profile['network_name'] = format_network_name($profile['network'], $profile['url']);
} else {
- $profile['network_name'] = "";
+ $profile['network_name'] = '';
}
call_hooks('profile_sidebar_enter', $profile);
// don't show connect link to yourself
- $connect = (($profile['uid'] != local_user()) ? t('Connect') : false);
+ $connect = $profile['uid'] != local_user() ? t('Connect') : false;
// don't show connect link to authenticated visitors either
if (remote_user() && count($_SESSION['remote'])) {
}
}
+ if (!$show_connect) {
+ $connect = false;
+ }
+
// Is the local user already connected to that user?
if ($connect && local_user()) {
- if (isset($profile["url"])) {
- $profile_url = normalise_link($profile["url"]);
+ if (isset($profile['url'])) {
+ $profile_url = normalise_link($profile['url']);
} else {
- $profile_url = normalise_link(System::baseUrl()."/profile/".$profile["nickname"]);
+ $profile_url = normalise_link(System::baseUrl() . '/profile/' . $profile['nickname']);
}
if (dba::exists('contact', array('pending' => false, 'uid' => local_user(), 'nurl' => $profile_url))) {
}
}
- if ($connect && ($profile['network'] != NETWORK_DFRN) && !isset($profile['remoteconnect']))
+ if ($connect && ($profile['network'] != NETWORK_DFRN) && !isset($profile['remoteconnect'])) {
$connect = false;
+ }
$remoteconnect = null;
- if (isset($profile['remoteconnect']))
+ if (isset($profile['remoteconnect'])) {
$remoteconnect = $profile['remoteconnect'];
+ }
- if ($connect && ($profile['network'] == NETWORK_DFRN) && !isset($remoteconnect))
- $subscribe_feed = t("Atom feed");
- else
+ if ($connect && ($profile['network'] == NETWORK_DFRN) && !isset($remoteconnect)) {
+ $subscribe_feed = t('Atom feed');
+ } else {
$subscribe_feed = false;
+ }
- if (remote_user() || (get_my_url() && $profile['unkmail'] && ($profile['uid'] != local_user()))) {
+ if (remote_user() || (get_my_url() && x($profile, 'unkmail') && ($profile['uid'] != local_user()))) {
$wallmessage = t('Message');
- $wallmessage_link = "wallmessage/".$profile["nickname"];
+ $wallmessage_link = 'wallmessage/' . $profile['nickname'];
if (remote_user()) {
$r = q(
);
}
if ($r) {
- $remote_url = $r[0]["url"];
- $message_path = preg_replace("=(.*)/profile/(.*)=ism", "$1/message/new/", $remote_url);
- $wallmessage_link = $message_path.base64_encode($profile["addr"]);
+ $remote_url = $r[0]['url'];
+ $message_path = preg_replace('=(.*)/profile/(.*)=ism', '$1/message/new/', $remote_url);
+ $wallmessage_link = $message_path . base64_encode($profile['addr']);
}
} else {
$wallmessage = false;
// show edit profile to yourself
if (!$is_contact && $profile['uid'] == local_user() && Feature::isEnabled(local_user(), 'multi_profiles')) {
- $profile['edit'] = array(System::baseUrl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles'));
+ $profile['edit'] = array(System::baseUrl() . '/profiles', t('Profiles'), '', t('Manage/edit profiles'));
$r = q(
"SELECT * FROM `profile` WHERE `uid` = %d",
local_user()
'alt' => t('Profile Image'),
'profile_name' => $rr['profile-name'],
'isdefault' => $rr['is-default'],
- 'visibile_to_everybody' => t('visible to everybody'),
+ 'visibile_to_everybody' => t('visible to everybody'),
'edit_visibility' => t('Edit visibility'),
);
}
}
}
if (!$is_contact && $profile['uid'] == local_user() && !Feature::isEnabled(local_user(), 'multi_profiles')) {
- $profile['edit'] = array(System::baseUrl(). '/profiles/'.$profile['id'], t('Edit profile'),"", t('Edit profile'));
+ $profile['edit'] = array(System::baseUrl() . '/profiles/' . $profile['id'], t('Edit profile'), '', t('Edit profile'));
$profile['menu'] = array(
'chg_photo' => t('Change profile photo'),
'cr_new' => null,
// Fetch the account type
$account_type = Contact::getAccountType($profile);
- if ((x($profile, 'address') == 1)
- || (x($profile, 'location') == 1)
- || (x($profile, 'locality') == 1)
- || (x($profile, 'region') == 1)
- || (x($profile, 'postal-code') == 1)
- || (x($profile, 'country-name') == 1)
+ if (x($profile, 'address')
+ || x($profile, 'location')
+ || x($profile, 'locality')
+ || x($profile, 'region')
+ || x($profile, 'postal-code')
+ || x($profile, 'country-name')
) {
$location = t('Location:');
}
- $gender = ((x($profile, 'gender') == 1) ? t('Gender:') : false);
-
-
- $marital = ((x($profile, 'marital') == 1) ? t('Status:') : false);
-
- $homepage = ((x($profile, 'homepage') == 1) ? t('Homepage:') : false);
+ $gender = x($profile, 'gender') ? t('Gender:') : false;
+ $marital = x($profile, 'marital') ? t('Status:') : false;
+ $homepage = x($profile, 'homepage') ? t('Homepage:') : false;
+ $about = x($profile, 'about') ? t('About:') : false;
+ $xmpp = x($profile, 'xmpp') ? t('XMPP:') : false;
- $about = ((x($profile, 'about') == 1) ? t('About:') : false);
-
- $xmpp = ((x($profile, 'xmpp') == 1) ? t('XMPP:') : false);
-
- if (($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
+ if ((x($profile, 'hidewall') || $block) && !local_user() && !remote_user()) {
$location = $pdesc = $gender = $marital = $homepage = $about = false;
}
$firstname = $split_name['first'];
$lastname = $split_name['last'];
- if ($profile['guid'] != "") {
+ if (x($profile, 'guid')) {
$diaspora = array(
'guid' => $profile['guid'],
'podloc' => System::baseUrl(),
$diaspora = false;
}
+ $contact_block = '';
+ $updated = '';
+ $contacts = 0;
if (!$block) {
$contact_block = contact_block();
intval($a->profile['uid'])
);
if (DBM::is_result($r)) {
- $updated = date("c", strtotime($r[0]['updated']));
+ $updated = date('c', strtotime($r[0]['updated']));
}
$r = q(
$p[$k] = $v;
}
- if (isset($p["about"])) {
- $p["about"] = bbcode($p["about"]);
+ if (isset($p['about'])) {
+ $p['about'] = bbcode($p['about']);
}
- if (isset($p["address"])) {
- $p["address"] = bbcode($p["address"]);
+ if (isset($p['address'])) {
+ $p['address'] = bbcode($p['address']);
} else {
- $p["address"] = bbcode($p["location"]);
+ $p['address'] = bbcode($p['location']);
}
- if (isset($p["photo"])) {
- $p["photo"] = proxy_url($p["photo"], false, PROXY_SIZE_SMALL);
+ if (isset($p['photo'])) {
+ $p['photo'] = proxy_url($p['photo'], false, PROXY_SIZE_SMALL);
}
$tpl = get_markup_template('profile_vcard.tpl');
- $o .= replace_macros(
- $tpl,
- array(
+ $o .= replace_macros($tpl, array(
'$profile' => $p,
'$xmpp' => $xmpp,
- '$connect' => $connect,
- '$remoteconnect' => $remoteconnect,
+ '$connect' => $connect,
+ '$remoteconnect' => $remoteconnect,
'$subscribe_feed' => $subscribe_feed,
'$wallmessage' => $wallmessage,
'$wallmessage_link' => $wallmessage_link,
'$account_type' => $account_type,
'$location' => $location,
- '$gender' => $gender,
- // '$pdesc' => $pdesc,
- '$marital' => $marital,
+ '$gender' => $gender,
+ '$marital' => $marital,
'$homepage' => $homepage,
'$about' => $about,
- '$network' => t('Network:'),
+ '$network' => t('Network:'),
'$contacts' => $contacts,
'$updated' => $updated,
'$diaspora' => $diaspora,
'$contact_block' => $contact_block,
- )
- );
+ ));
$arr = array('profile' => &$profile, 'entry' => &$o);
return $o;
}
-
function get_birthdays()
{
$a = get_app();
$o = '';
- if (! local_user() || $a->is_mobile || $a->is_tablet) {
+ if (!local_user() || $a->is_mobile || $a->is_tablet) {
return $o;
}
/*
* $mobile_detect = new Mobile_Detect();
* $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
- * if ($is_mobile)
- * return $o;
+ * if ($is_mobile)
+ * return $o;
*/
$bd_format = t('g A l F d'); // 8 AM Friday January 18
$bd_short = t('F d');
- $cachekey = "get_birthdays:".local_user();
+ $cachekey = 'get_birthdays:' . local_user();
$r = Cache::get($cachekey);
if (is_null($r)) {
$s = dba::p(
$classtoday = $istoday ? ' birthday-today ' : '';
if ($total) {
foreach ($r as &$rr) {
- if (! strlen($rr['name'])) {
+ if (!strlen($rr['name'])) {
continue;
}
$sparkle = '';
$url = $rr['url'];
if ($rr['network'] === NETWORK_DFRN) {
- $sparkle = " sparkle";
- $url = System::baseUrl() . '/redir/' . $rr['cid'];
+ $sparkle = ' sparkle';
+ $url = System::baseUrl() . '/redir/' . $rr['cid'];
}
$rr['link'] = $url;
$rr['title'] = $rr['name'];
- $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . t('[today]') : '');
+ $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . t('[today]') : '');
$rr['startime'] = null;
$rr['today'] = $today;
}
}
}
- $tpl = get_markup_template("birthdays_reminder.tpl");
- return replace_macros(
- $tpl,
- array(
+ $tpl = get_markup_template('birthdays_reminder.tpl');
+ return replace_macros($tpl, array(
'$baseurl' => System::baseUrl(),
'$classtoday' => $classtoday,
'$count' => $total,
'$event_reminders' => t('Birthday Reminders'),
'$event_title' => t('Birthdays this week:'),
'$events' => $r,
- '$lbr' => '{', // raw brackets mess up if/endif macro processing
+ '$lbr' => '{', // raw brackets mess up if/endif macro processing
'$rbr' => '}'
- )
- );
+ ));
}
-
function get_events()
{
require_once 'include/bbcode.php';
$a = get_app();
- if (! local_user() || $a->is_mobile || $a->is_tablet) {
+ if (!local_user() || $a->is_mobile || $a->is_tablet) {
return $o;
}
/*
- * $mobile_detect = new Mobile_Detect();
- * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
- * if ($is_mobile)
- * return $o;
+ * $mobile_detect = new Mobile_Detect();
+ * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
+ * if ($is_mobile)
+ * return $o;
*/
$bd_format = t('g A l F d'); // 8 AM Friday January 18
- $bd_short = t('F d');
+ $classtoday = '';
$s = dba::p(
"SELECT `event`.* FROM `event`
$r = array();
if (DBM::is_result($s)) {
- $now = strtotime('now');
$istoday = false;
while ($rr = dba::fetch($s)) {
}
$description = substr(strip_tags(bbcode($rr['desc'])), 0, 32) . '... ';
- if (! $description) {
+ if (!$description) {
$description = t('[No description]');
}
$today = ((substr($strt, 0, 10) === datetime_convert('UTC', $a->timezone, 'now', 'Y-m-d')) ? true : false);
$rr['title'] = $title;
- $rr['description'] = $desciption;
- $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ? ' ' . t('[today]') : '');
+ $rr['description'] = $description;
+ $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ? ' ' . t('[today]') : '');
$rr['startime'] = $strt;
$rr['today'] = $today;
dba::close($s);
$classtoday = (($istoday) ? 'event-today' : '');
}
- $tpl = get_markup_template("events_reminder.tpl");
- return replace_macros(
- $tpl,
- array(
+ $tpl = get_markup_template('events_reminder.tpl');
+ return replace_macros($tpl, array(
'$baseurl' => System::baseUrl(),
'$classtoday' => $classtoday,
'$count' => count($r),
'$event_reminders' => t('Event Reminders'),
'$event_title' => t('Events this week:'),
'$events' => $r,
- )
- );
+ ));
}
function advanced_profile(App $a)
$uid = $a->profile['uid'];
$o .= replace_macros(
- get_markup_template('section_title.tpl'),
- array(
- '$title' => t('Profile')
+ get_markup_template('section_title.tpl'), array(
+ '$title' => t('Profile')
)
);
$profile = array();
- $profile['fullname'] = array( t('Full Name:'), $a->profile['name'] ) ;
+ $profile['fullname'] = array(t('Full Name:'), $a->profile['name']);
if ($a->profile['gender']) {
- $profile['gender'] = array( t('Gender:'), $a->profile['gender'] );
+ $profile['gender'] = array(t('Gender:'), $a->profile['gender']);
}
if (($a->profile['dob']) && ($a->profile['dob'] > '0001-01-01')) {
$year_bd_format = t('j F, Y');
$short_bd_format = t('j F');
+ $val = intval($a->profile['dob']) ?
+ day_translate(datetime_convert('UTC', 'UTC', $a->profile['dob'] . ' 00:00 +00:00', $year_bd_format))
+ : day_translate(datetime_convert('UTC', 'UTC', '2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format));
- $val = ((intval($a->profile['dob']))
- ? day_translate(datetime_convert('UTC', 'UTC', $a->profile['dob'] . ' 00:00 +00:00', $year_bd_format))
- : day_translate(datetime_convert('UTC', 'UTC', '2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)));
-
- $profile['birthday'] = array( t('Birthday:'), $val);
+ $profile['birthday'] = array(t('Birthday:'), $val);
}
+
if (!empty($a->profile['dob'])
&& $a->profile['dob'] > '0001-01-01'
&& $age = age($a->profile['dob'], $a->profile['timezone'], '')
) {
- $profile['age'] = array( t('Age:'), $age );
+ $profile['age'] = array(t('Age:'), $age);
}
if ($a->profile['marital']) {
- $profile['marital'] = array( t('Status:'), $a->profile['marital']);
+ $profile['marital'] = array(t('Status:'), $a->profile['marital']);
}
/// @TODO Maybe use x() here, plus below?
}
if ($a->profile['sexual']) {
- $profile['sexual'] = array( t('Sexual Preference:'), $a->profile['sexual'] );
+ $profile['sexual'] = array(t('Sexual Preference:'), $a->profile['sexual']);
}
if ($a->profile['homepage']) {
- $profile['homepage'] = array( t('Homepage:'), linkify($a->profile['homepage']) );
+ $profile['homepage'] = array(t('Homepage:'), linkify($a->profile['homepage']));
}
if ($a->profile['hometown']) {
- $profile['hometown'] = array( t('Hometown:'), linkify($a->profile['hometown']) );
+ $profile['hometown'] = array(t('Hometown:'), linkify($a->profile['hometown']));
}
if ($a->profile['pub_keywords']) {
- $profile['pub_keywords'] = array( t('Tags:'), $a->profile['pub_keywords']);
+ $profile['pub_keywords'] = array(t('Tags:'), $a->profile['pub_keywords']);
}
if ($a->profile['politic']) {
- $profile['politic'] = array( t('Political Views:'), $a->profile['politic']);
+ $profile['politic'] = array(t('Political Views:'), $a->profile['politic']);
}
if ($a->profile['religion']) {
- $profile['religion'] = array( t('Religion:'), $a->profile['religion']);
+ $profile['religion'] = array(t('Religion:'), $a->profile['religion']);
}
if ($txt = prepare_text($a->profile['about'])) {
- $profile['about'] = array( t('About:'), $txt );
+ $profile['about'] = array(t('About:'), $txt);
}
if ($txt = prepare_text($a->profile['interest'])) {
- $profile['interest'] = array( t('Hobbies/Interests:'), $txt);
+ $profile['interest'] = array(t('Hobbies/Interests:'), $txt);
}
if ($txt = prepare_text($a->profile['likes'])) {
- $profile['likes'] = array( t('Likes:'), $txt);
+ $profile['likes'] = array(t('Likes:'), $txt);
}
if ($txt = prepare_text($a->profile['dislikes'])) {
- $profile['dislikes'] = array( t('Dislikes:'), $txt);
+ $profile['dislikes'] = array(t('Dislikes:'), $txt);
}
if ($txt = prepare_text($a->profile['contact'])) {
- $profile['contact'] = array( t('Contact information and Social Networks:'), $txt);
+ $profile['contact'] = array(t('Contact information and Social Networks:'), $txt);
}
if ($txt = prepare_text($a->profile['music'])) {
- $profile['music'] = array( t('Musical interests:'), $txt);
+ $profile['music'] = array(t('Musical interests:'), $txt);
}
if ($txt = prepare_text($a->profile['book'])) {
- $profile['book'] = array( t('Books, literature:'), $txt);
+ $profile['book'] = array(t('Books, literature:'), $txt);
}
if ($txt = prepare_text($a->profile['tv'])) {
- $profile['tv'] = array( t('Television:'), $txt);
+ $profile['tv'] = array(t('Television:'), $txt);
}
if ($txt = prepare_text($a->profile['film'])) {
- $profile['film'] = array( t('Film/dance/culture/entertainment:'), $txt);
+ $profile['film'] = array(t('Film/dance/culture/entertainment:'), $txt);
}
if ($txt = prepare_text($a->profile['romance'])) {
- $profile['romance'] = array( t('Love/Romance:'), $txt);
+ $profile['romance'] = array(t('Love/Romance:'), $txt);
}
if ($txt = prepare_text($a->profile['work'])) {
- $profile['work'] = array( t('Work/employment:'), $txt);
+ $profile['work'] = array(t('Work/employment:'), $txt);
}
if ($txt = prepare_text($a->profile['education'])) {
- $profile['education'] = array( t('School/education:'), $txt );
+ $profile['education'] = array(t('School/education:'), $txt);
}
//show subcribed forum if it is enabled in the usersettings
if (Feature::isEnabled($uid, 'forumlist_profile')) {
- $profile['forumlist'] = array( t('Forums:'), ForumManager::profileAdvanced($uid));
+ $profile['forumlist'] = array(t('Forums:'), ForumManager::profileAdvanced($uid));
}
if ($a->profile['uid'] == local_user()) {
- $profile['edit'] = array(System::baseUrl(). '/profiles/'.$a->profile['id'], t('Edit profile'),"", t('Edit profile'));
+ $profile['edit'] = array(System::baseUrl() . '/profiles/' . $a->profile['id'], t('Edit profile'), '', t('Edit profile'));
}
- return replace_macros(
- $tpl,
- array(
+ return replace_macros($tpl, array(
'$title' => t('Profile'),
'$basic' => t('Basic'),
'$advanced' => t('Advanced'),
'$profile' => $profile
- )
- );
+ ));
}
return '';
function profile_tabs($a, $is_owner = false, $nickname = null)
{
- //echo "<pre>"; var_dump($a->user); killme();
-
if (is_null($nickname)) {
- $nickname = $a->user['nickname'];
+ $nickname = $a->user['nickname'];
}
+ $tab = false;
if (x($_GET, 'tab')) {
$tab = notags(trim($_GET['tab']));
}
$tabs = array(
array(
- 'label'=>t('Status'),
- 'url' => $url,
- 'sel' => ((!isset($tab) && $a->argv[0]=='profile') ? 'active' : ''),
+ 'label' => t('Status'),
+ 'url' => $url,
+ 'sel' => !$tab && $a->argv[0] == 'profile' ? 'active' : '',
'title' => t('Status Messages and Posts'),
- 'id' => 'status-tab',
+ 'id' => 'status-tab',
'accesskey' => 'm',
),
array(
'label' => t('Profile'),
- 'url' => $url.'/?tab=profile',
- 'sel' => ((isset($tab) && $tab=='profile') ? 'active' : ''),
+ 'url' => $url . '/?tab=profile',
+ 'sel' => $tab == 'profile' ? 'active' : '',
'title' => t('Profile Details'),
- 'id' => 'profile-tab',
+ 'id' => 'profile-tab',
'accesskey' => 'r',
),
array(
'label' => t('Photos'),
- 'url' => System::baseUrl() . '/photos/' . $nickname,
- 'sel' => ((!isset($tab) && $a->argv[0]=='photos') ? 'active' : ''),
+ 'url' => System::baseUrl() . '/photos/' . $nickname,
+ 'sel' => !$tab && $a->argv[0] == 'photos' ? 'active' : '',
'title' => t('Photo Albums'),
- 'id' => 'photo-tab',
+ 'id' => 'photo-tab',
'accesskey' => 'h',
),
array(
'label' => t('Videos'),
- 'url' => System::baseUrl() . '/videos/' . $nickname,
- 'sel' => ((!isset($tab) && $a->argv[0]=='videos') ? 'active' : ''),
+ 'url' => System::baseUrl() . '/videos/' . $nickname,
+ 'sel' => !$tab && $a->argv[0] == 'videos' ? 'active' : '',
'title' => t('Videos'),
- 'id' => 'video-tab',
+ 'id' => 'video-tab',
'accesskey' => 'v',
),
);
// the calendar link for the full featured events calendar
if ($is_owner && $a->theme_events_in_profile) {
- $tabs[] = array(
- 'label' => t('Events'),
- 'url' => System::baseUrl() . '/events',
- 'sel' =>((!isset($tab) && $a->argv[0]=='events') ? 'active' : ''),
- 'title' => t('Events and Calendar'),
- 'id' => 'events-tab',
- 'accesskey' => 'e',
- );
+ $tabs[] = array(
+ 'label' => t('Events'),
+ 'url' => System::baseUrl() . '/events',
+ 'sel' => !$tab && $a->argv[0] == 'events' ? 'active' : '',
+ 'title' => t('Events and Calendar'),
+ 'id' => 'events-tab',
+ 'accesskey' => 'e',
+ );
// if the user is not the owner of the calendar we only show a calendar
// with the public events of the calendar owner
- } elseif (! $is_owner) {
+ } elseif (!$is_owner) {
$tabs[] = array(
- 'label' => t('Events'),
- 'url' => System::baseUrl() . '/cal/' . $nickname,
- 'sel' =>((!isset($tab) && $a->argv[0]=='cal') ? 'active' : ''),
- 'title' => t('Events and Calendar'),
- 'id' => 'events-tab',
- 'accesskey' => 'e',
- );
+ 'label' => t('Events'),
+ 'url' => System::baseUrl() . '/cal/' . $nickname,
+ 'sel' => !$tab && $a->argv[0] == 'cal' ? 'active' : '',
+ 'title' => t('Events and Calendar'),
+ 'id' => 'events-tab',
+ 'accesskey' => 'e',
+ );
}
if ($is_owner) {
$tabs[] = array(
'label' => t('Personal Notes'),
- 'url' => System::baseUrl() . '/notes',
- 'sel' =>((!isset($tab) && $a->argv[0]=='notes') ? 'active' : ''),
+ 'url' => System::baseUrl() . '/notes',
+ 'sel' => !$tab && $a->argv[0] == 'notes' ? 'active' : '',
'title' => t('Only You Can See This'),
- 'id' => 'notes-tab',
+ 'id' => 'notes-tab',
'accesskey' => 't',
);
}
- if ((! $is_owner) && ((count($a->profile)) || (! $a->profile['hide-friends']))) {
+ if ((!$is_owner) && ((count($a->profile)) || (!$a->profile['hide-friends']))) {
$tabs[] = array(
'label' => t('Contacts'),
- 'url' => System::baseUrl() . '/viewcontacts/' . $nickname,
- 'sel' => ((!isset($tab) && $a->argv[0]=='viewcontacts') ? 'active' : ''),
+ 'url' => System::baseUrl() . '/viewcontacts/' . $nickname,
+ 'sel' => !$tab && $a->argv[0] == 'viewcontacts' ? 'active' : '',
'title' => t('Contacts'),
- 'id' => 'viewcontacts-tab',
+ 'id' => 'viewcontacts-tab',
'accesskey' => 'k',
);
}
- $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
+ $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $tab, 'tabs' => $tabs);
call_hooks('profile_tabs', $arr);
$tpl = get_markup_template('common_tabs.tpl');
// The check fetches the cached value from gprobe to reduce the load for this system
$urlparts = parse_url($tmp_str);
- $result = Cache::get("gprobe:" . $urlparts["host"]);
- if ((!is_null($result)) && (in_array($result["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
- logger("DDoS attempt detected for " . $urlparts["host"] . " by " . $_SERVER["REMOTE_ADDR"] . ". server data: " . print_r($_SERVER, true), LOGGER_DEBUG);
+ $result = Cache::get('gprobe:' . $urlparts['host']);
+ if ((!is_null($result)) && (in_array($result['network'], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
+ logger('DDoS attempt detected for ' . $urlparts['host'] . ' by ' . $_SERVER['REMOTE_ADDR'] . '. server data: ' . print_r($_SERVER, true), LOGGER_DEBUG);
return;
}
function zrl($s, $force = false)
{
- if (! strlen($s)) {
+ if (!strlen($s)) {
return $s;
}
- if ((! strpos($s, '/profile/')) && (! $force)) {
+ if ((!strpos($s, '/profile/')) && (!$force)) {
return $s;
}
if ($force && substr($s, -1, 1) !== '/') {
}
$achar = strpos($s, '?') ? '&' : '?';
$mine = get_my_url();
- if ($mine && ! link_compare($mine, $s)) {
+ if ($mine && !link_compare($mine, $s)) {
return $s . $achar . 'zrl=' . urlencode($mine);
}
return $s;
function get_theme_uid()
{
$uid = ((!empty($_REQUEST['puid'])) ? intval($_REQUEST['puid']) : 0);
- if ((local_user()) && ((PConfig::get(local_user(), 'system', 'always_my_theme')) || (! $uid))) {
+ if ((local_user()) && ((PConfig::get(local_user(), 'system', 'always_my_theme')) || (!$uid))) {
return local_user();
}
use Friendica\Protocol\Feed;
require_once 'include/bbcode.php';
-require_once 'include/oembed.php';
-require_once 'include/crypto.php';
require_once 'include/tags.php';
require_once 'include/files.php';
require_once 'include/text.php';
* @return array Item array with removed conversation data
*/
function store_conversation($arr) {
- if (in_array($arr['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)) && !empty($arr['uri'])) {
+ if (in_array(defaults($arr, 'network', NETWORK_PHANTOM), array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)) && !empty($arr['uri'])) {
$conversation = array('item-uri' => $arr['uri'], 'received' => DBM::date());
if (isset($arr['parent-uri']) && ($arr['parent-uri'] != $arr['uri'])) {
}
/// @TODO add type-hint array
-function item_store($arr, $force_parent = false, $notify = false, $dontcache = false) {
-
+function item_store($arr, $force_parent = false, $notify = false, $dontcache = false)
+{
$a = get_app();
// If it is a posting where users should get notifications, then define it as wall posting
$arr['guid'] = uri_to_guid($arr['uri'], $a->get_hostname());
}
}
+ } else {
+ $arr['network'] = trim(defaults($arr, 'network', NETWORK_PHANTOM));
}
if ($notify) {
* We have to check several networks since Friendica posts could be repeated
* via OStatus (maybe Diasporsa as well)
*/
- if (in_array(trim($arr['network']), array(NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""))) {
+ if (in_array($arr['network'], array(NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""))) {
$r = q("SELECT `id`, `network` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` IN ('%s', '%s', '%s') LIMIT 1",
dbesc(trim($arr['uri'])),
intval($uid),
$arr['attach'] = ((x($arr, 'attach')) ? notags(trim($arr['attach'])) : '');
$arr['app'] = ((x($arr, 'app')) ? notags(trim($arr['app'])) : '');
$arr['origin'] = ((x($arr, 'origin')) ? intval($arr['origin']) : 0 );
- $arr['network'] = ((x($arr, 'network')) ? trim($arr['network']) : '');
$arr['postopts'] = ((x($arr, 'postopts')) ? trim($arr['postopts']) : '');
$arr['resource-id'] = ((x($arr, 'resource-id')) ? trim($arr['resource-id']) : '');
$arr['event-id'] = ((x($arr, 'event-id')) ? intval($arr['event-id']) : 0 );
$arr['plink'] = System::baseUrl() . '/display/' . urlencode($arr['guid']);
}
- if ($arr['network'] == "") {
+ if ($arr['network'] == NETWORK_PHANTOM) {
$r = q("SELECT `network` FROM `contact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
dbesc(normalise_link($arr['author-link'])),
intval($arr['uid'])
);
- if (!DBM::is_result($r))
+ if (!DBM::is_result($r)) {
$r = q("SELECT `network` FROM `gcontact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' LIMIT 1",
dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
dbesc(normalise_link($arr['author-link']))
);
+ }
if (!DBM::is_result($r)) {
$r = q("SELECT `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
logger("Contact-id was missing for post ".$arr["guid"]." from user id ".$uid." - now set to ".$arr["contact-id"], LOGGER_DEBUG);
}
- if ($arr["gcontact-id"] == 0) {
+ if (!x($arr, "gcontact-id")) {
/*
* The gcontact should mostly behave like the contact. But is is supposed to be global for the system.
* This means that wall posts, repeated posts, etc. should have the gcontact id of the owner.
function do_like($item_id, $verb) {
$a = get_app();
- if (! local_user() && ! remote_user()) {
+ if (!local_user() && !remote_user()) {
return false;
}
dbesc($item_id)
);
- if (! $item_id || ! DBM::is_result($items)) {
+ if (!$item_id || !DBM::is_result($items)) {
logger('like: unknown item ' . $item_id);
return false;
}
$item = $items[0];
+ $uid = $item['uid'];
- if (! can_write_wall($a, $item['uid'])) {
- logger('like: unable to write on wall ' . $item['uid']);
+ if (($uid == 0) && local_user()) {
+ $uid = local_user();
+ }
+
+ if (!can_write_wall($a, $uid)) {
+ logger('like: unable to write on wall ' . $uid);
return false;
}
// Retrieves the local post owner
$owners = q("SELECT `contact`.* FROM `contact`
- WHERE `contact`.`self` = 1
+ WHERE `contact`.`self`
AND `contact`.`uid` = %d",
- intval($item['uid'])
+ intval($uid)
);
if (DBM::is_result($owners)) {
$owner_self_contact = $owners[0];
} else {
- logger('like: unknown owner ' . $item['uid']);
+ logger('like: unknown owner ' . $uid);
return false;
}
}
// Contact-id is the uid-dependant author contact
- if (local_user() == $item['uid']) {
+ if (local_user() == $uid) {
$item_contact_id = $owner_self_contact['id'];
$item_contact = $owner_self_contact;
} else {
- $item_contact_id = Contact::getIdForURL($author_contact['url'], $item['uid']);
+ $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid);
$contacts = q("SELECT * FROM `contact` WHERE `id` = %d",
intval($item_contact_id)
// @todo: Explain this block
if (! $item['visible']) {
- q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d AND `uid` = %d",
- intval($item['id']),
- intval($item['uid'])
+ q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d",
+ intval($item['id'])
);
}
+++ /dev/null
-<?php
-
-/**
- * @file include/oembed.php
- */
-
-use Friendica\App;
-use Friendica\Core\Cache;
-use Friendica\Core\System;
-use Friendica\ParseUrl;
-use Friendica\Core\Config;
-use Friendica\Database\DBM;
-
-function oembed_replacecb($matches){
- $embedurl=$matches[1];
- $j = oembed_fetch_url($embedurl);
- $s = oembed_format_object($j);
-
- return $s;
-}
-
-/**
- * @brief Get data from an URL to embed its content.
- *
- * @param string $embedurl The URL from which the data should be fetched.
- * @param bool $no_rich_type If set to true rich type content won't be fetched.
- *
- * @return bool|object Returns object with embed content or false if no embedable
- * content exists
- */
-function oembed_fetch_url($embedurl, $no_rich_type = false) {
- $embedurl = trim($embedurl, "'");
- $embedurl = trim($embedurl, '"');
-
- $a = get_app();
-
- $condition = array('url' => normalise_link($embedurl));
- $r = dba::select('oembed', array('content'), $condition, array('limit' => 1));
-
- if (DBM::is_result($r)) {
- $txt = $r["content"];
- } else {
- $txt = Cache::get($a->videowidth . $embedurl);
- }
- // These media files should now be caught in bbcode.php
- // left here as a fallback in case this is called from another source
-
- $noexts = array("mp3", "mp4", "ogg", "ogv", "oga", "ogm", "webm");
- $ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);
-
-
- if (is_null($txt)) {
- $txt = "";
-
- if (!in_array($ext, $noexts)){
- // try oembed autodiscovery
- $redirects = 0;
- $html_text = fetch_url($embedurl, false, $redirects, 15, "text/*");
- if ($html_text) {
- $dom = @DOMDocument::loadHTML($html_text);
- if ($dom) {
- $xpath = new DOMXPath($dom);
- $attr = "oembed";
- $xattr = oe_build_xpath("class","oembed");
- $entries = $xpath->query("//link[@type='application/json+oembed']");
- foreach ($entries as $e) {
- $href = $e->getAttributeNode("href")->nodeValue;
- $txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
- break;
- }
- $entries = $xpath->query("//link[@type='text/json+oembed']");
- foreach ($entries as $e) {
- $href = $e->getAttributeNode("href")->nodeValue;
- $txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
- break;
- }
- }
- }
- }
-
- $txt = trim($txt);
-
- if ($txt[0] != "{") {
- $txt = '{"type":"error"}';
- } else { //save in cache
- $j = json_decode($txt);
- if ($j->type != "error") {
- dba::insert('oembed', array('url' => normalise_link($embedurl),
- 'content' => $txt, 'created' => datetime_convert()), true);
- }
-
- Cache::set($a->videowidth.$embedurl, $txt, CACHE_DAY);
- }
- }
-
- $j = json_decode($txt);
-
- if (!is_object($j)) {
- return false;
- }
-
- // Always embed the SSL version
- if (isset($j->html)) {
- $j->html = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"),
- array("https://www.youtube.com/", "https://player.vimeo.com/"), $j->html);
- }
-
- $j->embedurl = $embedurl;
-
- // If fetching information doesn't work, then improve via internal functions
- if (($j->type == "error") || ($no_rich_type && ($j->type == "rich"))) {
- $data = ParseUrl::getSiteinfoCached($embedurl, true, false);
- $j->type = $data["type"];
-
- if ($j->type == "photo") {
- $j->url = $data["url"];
- //$j->width = $data["images"][0]["width"];
- //$j->height = $data["images"][0]["height"];
- }
-
- if (isset($data["title"])) {
- $j->title = $data["title"];
- }
-
- if (isset($data["text"])) {
- $j->description = $data["text"];
- }
-
- if (is_array($data["images"])) {
- $j->thumbnail_url = $data["images"][0]["src"];
- $j->thumbnail_width = $data["images"][0]["width"];
- $j->thumbnail_height = $data["images"][0]["height"];
- }
- }
-
- call_hooks('oembed_fetch_url', $embedurl, $j);
-
- return $j;
-}
-
-function oembed_format_object($j){
- require_once("mod/proxy.php");
-
- $embedurl = $j->embedurl;
- $jhtml = oembed_iframe($j->embedurl,(isset($j->width) ? $j->width : null), (isset($j->height) ? $j->height : null) );
- $ret="<span class='oembed ".$j->type."'>";
- switch ($j->type) {
- case "video":
- if (isset($j->thumbnail_url)) {
- $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width:200;
- $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->thumbnail_height:180;
- // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
- $tr = (($th) ? $tw/$th : 1);
-
- $th=120; $tw = $th*$tr;
- $tpl=get_markup_template('oembed_video.tpl');
- $ret.=replace_macros($tpl, array(
- '$baseurl' => System::baseUrl(),
- '$embedurl' => $embedurl,
- '$escapedhtml' => base64_encode($jhtml),
- '$tw' => $tw,
- '$th' => $th,
- '$turl' => $j->thumbnail_url,
- ));
-
- } else {
- $ret=$jhtml;
- }
- //$ret.="<br>";
- break;
- case "photo":
- $ret.= "<img width='".$j->width."' src='".proxy_url($j->url)."'>";
- break;
- case "link":
- break;
- case "rich":
- // not so safe..
- if (!Config::get("system","no_oembed_rich_content")) {
- $ret.= proxy_parse_html($jhtml);
- }
- break;
- }
-
- // add link to source if not present in "rich" type
- if ($j->type!='rich' || !strpos($j->html,$embedurl) ){
- $ret .= "<h4>";
- if (isset($j->title)) {
- if (isset($j->provider_name)) {
- $ret .= $j->provider_name.": ";
- }
-
- $embedlink = (isset($j->title))?$j->title:$embedurl;
- $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
- if (isset($j->author_name)) {
- $ret.=" (".$j->author_name.")";
- }
- } elseif (isset($j->provider_name) || isset($j->author_name)) {
- $embedlink = "";
- if (isset($j->provider_name)) {
- $embedlink .= $j->provider_name;
- }
-
- if (isset($j->author_name)) {
- if ($embedlink != "") {
- $embedlink .= ": ";
- }
-
- $embedlink .= $j->author_name;
- }
- if (trim($embedlink) == "") {
- $embedlink = $embedurl;
- }
-
- $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
- }
- //if (isset($j->author_name)) $ret.=" by ".$j->author_name;
- //if (isset($j->provider_name)) $ret.=" on ".$j->provider_name;
- $ret .= "</h4>";
- } else {
- // add <a> for html2bbcode conversion
- $ret .= "<a href='$embedurl' rel='oembed'>$embedurl</a>";
- }
- $ret.="</span>";
- $ret = str_replace("\n","",$ret);
- return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
-}
-
-/**
- * @brief Generates the iframe HTML for an oembed attachment.
- *
- * Width and height are given by the remote, and are regularly too small for
- * the generated iframe.
- *
- * The width is entirely discarded for the actual width of the post, while fixed
- * height is used as a starting point before the inevitable resizing.
- *
- * Since the iframe is automatically resized on load, there are no need for ugly
- * and impractical scrollbars.
- *
- * @param string $src Original remote URL to embed
- * @param string $width
- * @param string $height
- * @return string formatted HTML
- *
- * @see oembed_format_object()
- */
-function oembed_iframe($src, $width, $height) {
- $a = get_app();
-
- if (!$height || strstr($height,'%')) {
- $height = '200';
- }
- $width = '100%';
-
- $s = System::baseUrl() . '/oembed/' . base64url_encode($src);
- return '<iframe onload="resizeIframe(this);" class="embed_rich" height="' . $height . '" width="' . $width . '" src="' . $s . '" allowfullscreen scrolling="no" frameborder="no">' . t('Embedded content') . '</iframe>';
-}
-
-
-
-function oembed_bbcode2html($text){
- $stopoembed = Config::get("system","no_oembed");
- if ($stopoembed == true){
- return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>". t('Embedding disabled') ." : $1</i><!-- /oembed $1 -->" ,$text);
- }
- return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", 'oembed_replacecb' ,$text);
-}
-
-
-function oe_build_xpath($attr, $value){
- // http://westhoffswelt.de/blog/0036_xpath_to_select_html_by_class.html
- return "contains( normalize-space( @$attr ), ' $value ' ) or substring( normalize-space( @$attr ), 1, string-length( '$value' ) + 1 ) = '$value ' or substring( normalize-space( @$attr ), string-length( @$attr ) - string-length( '$value' ) ) = ' $value' or @$attr = '$value'";
-}
-
-function oe_get_inner_html($node) {
- $innerHTML= '';
- $children = $node->childNodes;
- foreach ($children as $child) {
- $innerHTML .= $child->ownerDocument->saveXML($child);
- }
- return $innerHTML;
-}
-
-/**
- * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
- * and replace it with [embed]url[/embed]
- */
-function oembed_html2bbcode($text) {
- // start parser only if 'oembed' is in text
- if (strpos($text, "oembed")) {
-
- // convert non ascii chars to html entities
- $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
-
- // If it doesn't parse at all, just return the text.
- $dom = @DOMDocument::loadHTML($html_text);
- if (! $dom) {
- return $text;
- }
- $xpath = new DOMXPath($dom);
- $attr = "oembed";
-
- $xattr = oe_build_xpath("class","oembed");
- $entries = $xpath->query("//span[$xattr]");
-
- $xattr = "@rel='oembed'";//oe_build_xpath("rel","oembed");
- foreach ($entries as $e) {
- $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
- if (!is_null($href)) {
- $e->parentNode->replaceChild(new DOMText("[embed]".$href."[/embed]"), $e);
- }
- }
- return oe_get_inner_html( $dom->getElementsByTagName("body")->item(0) );
- } else {
- return $text;
- }
-}
<?php
+
/**
* @file include/tags.php
*/
use Friendica\Database\DBM;
use Friendica\Model\Contact;
-function create_tags_from_item($itemid) {
+function create_tags_from_item($itemid)
+{
$profile_base = System::baseUrl();
$profile_data = parse_url($profile_base);
- $profile_base_friendica = $profile_data['host'].$profile_data['path']."/profile/";
- $profile_base_diaspora = $profile_data['host'].$profile_data['path']."/u/";
+ $profile_path = defaults($profile_data, 'path', '');
+ $profile_base_friendica = $profile_data['host'] . $profile_path . '/profile/';
+ $profile_base_diaspora = $profile_data['host'] . $profile_path . '/u/';
$messages = q("SELECT `guid`, `uid`, `id`, `edited`, `deleted`, `created`, `received`, `title`, `body`, `tag`, `parent` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
intval(TERM_HASHTAG),
intval(TERM_MENTION));
- if ($message["deleted"])
+ if ($message['deleted']) {
return;
+ }
- $taglist = explode(",", $message["tag"]);
+ $taglist = explode(',', $message['tag']);
- $tags = "";
- foreach ($taglist as $tag)
- if ((substr(trim($tag), 0, 1) == "#") || (substr(trim($tag), 0, 1) == "@"))
- $tags .= " ".trim($tag);
- else
- $tags .= " #".trim($tag);
+ $tags = '';
+ foreach ($taglist as $tag) {
+ if ((substr(trim($tag), 0, 1) == '#') || (substr(trim($tag), 0, 1) == '@')) {
+ $tags .= ' ' . trim($tag);
+ } else {
+ $tags .= ' #' . trim($tag);
+ }
+ }
- $data = " ".$message["title"]." ".$message["body"]." ".$tags." ";
+ $data = ' ' . $message['title'] . ' ' . $message['body'] . ' ' . $tags . ' ';
// ignore anything in a code block
- $data = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$data);
+ $data = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $data);
$tags = array();
- $pattern = "/\W\#([^\[].*?)[\s'\".,:;\?!\[\]\/]/ism";
- if (preg_match_all($pattern, $data, $matches))
- foreach ($matches[1] as $match)
- $tags["#".strtolower($match)] = "";
+ $pattern = '/\W\#([^\[].*?)[\s\'".,:;\?!\[\]\/]/ism';
+ if (preg_match_all($pattern, $data, $matches)) {
+ foreach ($matches[1] as $match) {
+ $tags['#' . strtolower($match)] = '';
+ }
+ }
- $pattern = "/\W([\#@])\[url\=(.*?)\](.*?)\[\/url\]/ism";
+ $pattern = '/\W([\#@])\[url\=(.*?)\](.*?)\[\/url\]/ism';
if (preg_match_all($pattern, $data, $matches, PREG_SET_ORDER)) {
- foreach ($matches as $match)
- $tags[$match[1].strtolower(trim($match[3], ',.:;[]/\"?!'))] = $match[2];
+ foreach ($matches as $match) {
+ $tags[$match[1] . strtolower(trim($match[3], ',.:;[]/\"?!'))] = $match[2];
+ }
}
- foreach ($tags as $tag=>$link) {
-
- if (substr(trim($tag), 0, 1) == "#") {
+ foreach ($tags as $tag => $link) {
+ if (substr(trim($tag), 0, 1) == '#') {
// try to ignore #039 or #1 or anything like that
- if (ctype_digit(substr(trim($tag),1)))
+ if (ctype_digit(substr(trim($tag), 1)))
continue;
// try to ignore html hex escapes, e.g. #x2317
- if ((substr(trim($tag),1,1) == 'x' || substr(trim($tag),1,1) == 'X') && ctype_digit(substr(trim($tag),2)))
+ if ((substr(trim($tag), 1, 1) == 'x' || substr(trim($tag), 1, 1) == 'X') && ctype_digit(substr(trim($tag), 2)))
continue;
$type = TERM_HASHTAG;
$term = substr($tag, 1);
- } elseif (substr(trim($tag), 0, 1) == "@") {
+ } elseif (substr(trim($tag), 0, 1) == '@') {
$type = TERM_MENTION;
$term = substr($tag, 1);
} else { // This shouldn't happen
$term = $tag;
}
- if ($message["uid"] == 0) {
+ if ($message['uid'] == 0) {
$global = true;
q("UPDATE `term` SET `global` = 1 WHERE `otype` = %d AND `guid` = '%s'",
- intval(TERM_OBJ_POST), dbesc($message["guid"]));
+ intval(TERM_OBJ_POST), dbesc($message['guid']));
} else {
$isglobal = q("SELECT `global` FROM `term` WHERE `uid` = 0 AND `otype` = %d AND `guid` = '%s'",
- intval(TERM_OBJ_POST), dbesc($message["guid"]));
+ intval(TERM_OBJ_POST), dbesc($message['guid']));
$global = (count($isglobal) > 0);
}
$r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `guid`, `created`, `received`, `global`)
VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s', %d)",
- intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval($type), dbesc($term),
- dbesc($link), dbesc($message["guid"]), dbesc($message["created"]), dbesc($message["received"]), intval($global));
+ intval($message['uid']), intval($itemid), intval(TERM_OBJ_POST), intval($type), dbesc($term),
+ dbesc($link), dbesc($message['guid']), dbesc($message['created']), dbesc($message['received']), intval($global));
// Search for mentions
if ((substr($tag, 0, 1) == '@') && (strpos($link, $profile_base_friendica) || strpos($link, $profile_base_diaspora))) {
$users = q("SELECT `uid` FROM `contact` WHERE self AND (`url` = '%s' OR `nurl` = '%s')", $link, $link);
foreach ($users AS $user) {
- if ($user["uid"] == $message["uid"]) {
+ if ($user['uid'] == $message['uid']) {
q("UPDATE `item` SET `mention` = 1 WHERE `id` = %d", intval($itemid));
- q("UPDATE `thread` SET `mention` = 1 WHERE `iid` = %d", intval($message["parent"]));
+ q("UPDATE `thread` SET `mention` = 1 WHERE `iid` = %d", intval($message['parent']));
}
}
}
}
}
-function create_tags_from_itemuri($itemuri, $uid) {
+function create_tags_from_itemuri($itemuri, $uid)
+{
$messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid));
if (count($messages)) {
foreach ($messages as $message) {
- create_tags_from_item($message["id"]);
+ create_tags_from_item($message['id']);
}
}
}
-function update_items() {
-
+function update_items()
+{
$messages = dba::p("SELECT `oid`,`item`.`guid`, `item`.`created`, `item`.`received` FROM `term` INNER JOIN `item` ON `item`.`id`=`term`.`oid` WHERE `term`.`otype` = 1 AND `term`.`guid` = ''");
- logger("fetched messages: ".dba::num_rows($messages));
+ logger('fetched messages: ' . dba::num_rows($messages));
while ($message = dba::fetch($messages)) {
-
- if ($message["uid"] == 0) {
+ if ($message['uid'] == 0) {
$global = true;
q("UPDATE `term` SET `global` = 1 WHERE `otype` = %d AND `guid` = '%s'",
- intval(TERM_OBJ_POST), dbesc($message["guid"]));
+ intval(TERM_OBJ_POST), dbesc($message['guid']));
} else {
$isglobal = q("SELECT `global` FROM `term` WHERE `uid` = 0 AND `otype` = %d AND `guid` = '%s'",
- intval(TERM_OBJ_POST), dbesc($message["guid"]));
+ intval(TERM_OBJ_POST), dbesc($message['guid']));
$global = (count($isglobal) > 0);
}
q("UPDATE `term` SET `guid` = '%s', `created` = '%s', `received` = '%s', `global` = %d WHERE `otype` = %d AND `oid` = %d",
- dbesc($message["guid"]), dbesc($message["created"]), dbesc($message["received"]),
- intval($global), intval(TERM_OBJ_POST), intval($message["oid"]));
+ dbesc($message['guid']), dbesc($message['created']), dbesc($message['received']),
+ intval($global), intval(TERM_OBJ_POST), intval($message['oid']));
}
dba::close($messages);
$messages = dba::p("SELECT `guid` FROM `item` WHERE `uid` = 0");
- logger("fetched messages: ".dba::num_rows($messages));
+ logger('fetched messages: ' . dba::num_rows($messages));
while ($message = dba::fetch(messages)) {
- q("UPDATE `item` SET `global` = 1 WHERE `guid` = '%s'", dbesc($message["guid"]));
+ q("UPDATE `item` SET `global` = 1 WHERE `guid` = '%s'", dbesc($message['guid']));
}
dba::close($messages);
*
* @return arr Alphabetical sorted array of used tags of an user.
*/
-function tagadelic($uid, $count = 0, $owner_id = 0, $flags = '', $type = TERM_HASHTAG) {
- require_once('include/security.php');
+function tagadelic($uid, $count = 0, $owner_id = 0, $flags = '', $type = TERM_HASHTAG)
+{
+ require_once 'include/security.php';
$item_condition = item_condition();
$sql_options = item_permissions_sql($uid);
- $limit = $count ? sprintf("LIMIT %d", intval($count)) : "";
+ $limit = $count ? sprintf('LIMIT %d', intval($count)) : '';
if ($flags) {
if ($flags === 'wall') {
- $sql_options .= " AND `item`.`wall` ";
+ $sql_options .= ' AND `item`.`wall` ';
}
}
if ($owner_id) {
- $sql_options .= " AND `item`.`owner-id` = ".intval($owner_id)." ";
+ $sql_options .= ' AND `item`.`owner-id` = ' . intval($owner_id) . ' ';
}
// Fetch tags
$type,
TERM_OBJ_POST
);
- if(!DBM::is_result($r)) {
+ if (!DBM::is_result($r)) {
return array();
}
*
* @return string HTML formatted output.
*/
-function wtagblock($uid, $count = 0,$owner_id = 0, $flags = '', $type = TERM_HASHTAG) {
+function wtagblock($uid, $count = 0, $owner_id = 0, $flags = '', $type = TERM_HASHTAG)
+{
$o = '';
$r = tagadelic($uid, $count, $owner_id, $flags, $type);
if (count($r)) {
$contact = dba::select(
- "contact",
- array("url"),
- array("id" => $uid),
- array("limit" => 1)
+ 'contact',
+ array('url'),
+ array('id' => $uid),
+ array('limit' => 1)
);
$url = System::removedBaseUrl($contact['url']);
foreach ($r as $rr) {
$tag['level'] = $rr[2];
- $tag['url'] = $url."?tag=".urlencode($rr[0]);
+ $tag['url'] = $url . '?tag=' . urlencode($rr[0]);
$tag['name'] = $rr[0];
$tags[] = $tag;
}
- $tpl = get_markup_template("tagblock_widget.tpl");
+ $tpl = get_markup_template('tagblock_widget.tpl');
$o = replace_macros($tpl, array(
'$title' => t('Tags'),
- '$tags' => $tags
+ '$tags' => $tags
));
-
}
return $o;
}
* @param array $arr Array of tags/terms with tag/term name and total count of use.
* @return array Alphabetical sorted array of used tags/terms of an user.
*/
-function tag_calc($arr) {
+function tag_calc($arr)
+{
$tags = array();
$min = 1e9;
$max = -1e9;
*
* @return int
*/
-function tags_sort($a, $b) {
+function tags_sort($a, $b)
+{
if (strtolower($a[0]) == strtolower($b[0])) {
return 0;
}
* @param int $limit Max number of displayed tags.
* @return string HTML formattat output.
*/
-function tagcloud_wall_widget($limit = 50) {
+function tagcloud_wall_widget($limit = 50)
+{
$a = get_app();
- if(!$a->profile['profile_uid'] || !$a->profile['url']) {
- return "";
+ if (!$a->profile['profile_uid'] || !$a->profile['url']) {
+ return '';
}
- if(Feature::isEnabled($a->profile['profile_uid'], 'tagadelic')) {
+ if (Feature::isEnabled($a->profile['profile_uid'], 'tagadelic')) {
$owner_id = Contact::getIdForURL($a->profile['url']);
- if(!$owner_id) {
- return "";
+ if (!$owner_id) {
+ return '';
}
return wtagblock($a->profile['profile_uid'], $limit, $owner_id, 'wall');
}
- return "";
+ return '';
}
function micropro($contact, $redirect = false, $class = '', $textmode = false) {
// Use the contact URL if no address is available
- if ($contact["addr"] == "") {
+ if (!x($contact, "addr")) {
$contact["addr"] = $contact["url"];
}
}
return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),array(
- '$click' => (($contact['click']) ? $contact['click'] : ''),
+ '$click' => defaults($contact, 'click', ''),
'$class' => $class,
'$url' => $url,
'$photo' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
}
}
-function put_item_in_cache(&$item, $update = false) {
-
- if (($item["rendered-hash"] != hash("md5", $item["body"])) || ($item["rendered-hash"] == "") ||
- ($item["rendered-html"] == "") || Config::get("system", "ignore_cache")) {
+function put_item_in_cache(&$item, $update = false)
+{
+ $rendered_hash = defaults($item, 'rendered-hash', '');
+ if ($rendered_hash == ''
+ || $item["rendered-html"] == ""
+ || $rendered_hash != hash("md5", $item["body"])
+ || Config::get("system", "ignore_cache")
+ ) {
// The function "redir_private_images" changes the body.
// I'm not sure if we should store it permanently, so we save the old value.
$body = $item["body"];
}
function formatBytes($bytes, $precision = 2) {
- $units = array('B', 'KB', 'MB', 'GB', 'TB');
+ $units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
session_start();
$a->save_timestamp($stamp1, "parser");
} else {
+ $_SESSION = [];
Worker::executeIfIdle();
}
// header('Link: <' . System::baseUrl() . '/amcd>; rel="acct-mgmt";');
-if (x($_COOKIE["Friendica"]) || (x($_SESSION, 'authenticated')) || (x($_POST, 'auth-params')) || ($a->module === 'login')) {
+if (x($_COOKIE, "Friendica") || (x($_SESSION, 'authenticated')) || (x($_POST, 'auth-params')) || ($a->module === 'login')) {
require "include/auth.php";
}
// off one % two of them are needed in the query
// Add more platforms if you like, when one returns 0 known nodes it is not
// displayed on the stats page.
- $platforms = array('Friendi%%a', 'Diaspora', '%%red%%', 'Hubzilla', 'BlaBlaNet', 'GNU Social', 'StatusNet', 'Mastodon', 'Pleroma');
+ $platforms = array('Friendi%%a', 'Diaspora', '%%red%%', 'Hubzilla', 'BlaBlaNet', 'GNU Social', 'StatusNet', 'Mastodon', 'Pleroma', 'socialhome');
$colors = array(
'Friendi%%a' => '#ffc018', // orange from the logo
'Diaspora' => '#a1a1a1', // logo is black and white, makes a gray
'GNU Social' => '#a22430', // dark red from the logo
'StatusNet' => '#789240', // the green from the logo (red and blue have already others
'Mastodon' => '#1a9df9', // blue from the Mastodon logo
- 'Pleroma' => '#E46F0F' // Orange from the text that is used on Pleroma instances
+ 'Pleroma' => '#E46F0F', // Orange from the text that is used on Pleroma instances
+ 'socialhome' => '#52056b' // lilac from the Django Image used at the Socialhome homepage
);
$counts = array();
$total = 0;
require_once 'include/contact_selectors.php';
require_once 'mod/proxy.php';
+require_once 'include/follow.php';
function contacts_init(App $a) {
if (! local_user()) {
require_once 'include/contact_widgets.php';
- if ($_GET['nets'] == "all") {
- $_GET['nets'] = "";
+ $nets = defaults($_GET, 'nets', '');
+ if ($nets == "all") {
+ $nets = "";
}
if (! x($a->page,'aside')) {
'$account_type' => Contact::getAccountType($a->data['contact'])
));
- $finpeople_widget = '';
+ $findpeople_widget = '';
$follow_widget = '';
$networks_widget = '';
} else {
$vcard_widget = '';
- $networks_widget .= networks_widget('contacts',$_GET['nets']);
+ $networks_widget = networks_widget('contacts', $nets);
if (isset($_GET['add'])) {
$follow_widget = follow_widget($_GET['add']);
} else {
$follow_widget = follow_widget();
}
- $findpeople_widget .= findpeople_widget();
+ $findpeople_widget = findpeople_widget();
}
- $groups_widget .= Group::sidebarWidget('contacts','group','full',0,$contact_id);
+ $groups_widget = Group::sidebarWidget('contacts','group','full',0,$contact_id);
$a->page['aside'] .= replace_macros(get_markup_template("contacts-widget-sidebar.tpl"),array(
'$vcard_widget' => $vcard_widget,
require_once 'include/contact_selectors.php';
- $tpl = get_markup_template("contact_edit.tpl");
-
switch($contact['rel']) {
case CONTACT_IS_FRIEND:
$dir_icon = 'images/lrarrow.gif';
$lost_contact = (($contact['archive'] && $contact['term-date'] > NULL_DATE && $contact['term-date'] < datetime_convert('','','now')) ? t('Communications lost with this contact!') : '');
+ $fetch_further_information = null;
if ($contact['network'] == NETWORK_FEED) {
$fetch_further_information = array('fetch_further_information',
t('Fetch further information for feeds'),
'3' => t('Fetch keywords'),
'2' => t('Fetch information and keywords')));
}
- if (in_array($contact['network'], array(NETWORK_FEED, NETWORK_MAIL)))
+
+ $poll_interval = null;
+ if (in_array($contact['network'], array(NETWORK_FEED, NETWORK_MAIL))) {
$poll_interval = contact_poll_interval($contact['priority'],(! $poll_enabled));
+ }
- if ($contact['network'] == NETWORK_DFRN)
+ $profile_select = null;
+ if ($contact['network'] == NETWORK_DFRN) {
$profile_select = contact_profile_assign($contact['profile-id'],(($contact['network'] !== NETWORK_DFRN) ? true : false));
+ }
+ $follow = '';
+ $follow_text = '';
if (in_array($contact['network'], array(NETWORK_DIASPORA, NETWORK_OSTATUS))) {
if ($contact['rel'] == CONTACT_IS_FOLLOWER) {
$follow = System::baseUrl(true)."/follow?url=".urlencode($contact["url"]);
// Load contactact related actions like hide, suggest, delete and others
$contact_actions = contact_actions($contact);
-
+ $tpl = get_markup_template("contact_edit.tpl");
$o .= replace_macros($tpl, array(
//'$header' => t('Contact Editor'),
'$header' => t("Contact"),
'$lbl_info2' => t('Their personal note'),
'$reason' => trim(notags($contact['reason'])),
'$infedit' => t('Edit contact notes'),
- '$common_text' => $common_text,
'$common_link' => 'common/loc/' . local_user() . '/' . $contact['id'],
- '$all_friends' => $all_friends,
'$relation_text' => $relation_text,
'$visit' => sprintf( t('Visit %s\'s profile [%s]'),$contact['name'],$contact['url']),
'$blockunblock' => t('Block/Unblock contact'),
'$photo' => $contact['photo'],
'$name' => htmlentities($contact['name']),
'$dir_icon' => $dir_icon,
- '$alt_text' => $alt_text,
'$sparkle' => $sparkle,
'$url' => $url,
'$profileurllabel' => t('Profile URL'),
}
- $blocked = false;
- $hidden = false;
- $ignored = false;
- $all = false;
+ $blocked = false;
+ $hidden = false;
+ $ignored = false;
+ $archived = false;
+ $all = false;
if(($a->argc == 2) && ($a->argv[1] === 'all')) {
$sql_extra = '';
$all = true;
- }
- elseif(($a->argc == 2) && ($a->argv[1] === 'blocked')) {
+ } elseif(($a->argc == 2) && ($a->argv[1] === 'blocked')) {
$sql_extra = " AND `blocked` = 1 ";
$blocked = true;
- }
- elseif(($a->argc == 2) && ($a->argv[1] === 'hidden')) {
+ } elseif(($a->argc == 2) && ($a->argv[1] === 'hidden')) {
$sql_extra = " AND `hidden` = 1 ";
$hidden = true;
- }
- elseif(($a->argc == 2) && ($a->argv[1] === 'ignored')) {
+ } elseif(($a->argc == 2) && ($a->argv[1] === 'ignored')) {
$sql_extra = " AND `readonly` = 1 ";
$ignored = true;
- }
- elseif(($a->argc == 2) && ($a->argv[1] === 'archived')) {
+ } elseif(($a->argc == 2) && ($a->argv[1] === 'archived')) {
$sql_extra = " AND `archive` = 1 ";
$archived = true;
- }
- else
+ } else {
$sql_extra = " AND `blocked` = 0 ";
+ }
- $search = ((x($_GET,'search')) ? notags(trim($_GET['search'])) : '');
- $nets = ((x($_GET,'nets')) ? notags(trim($_GET['nets'])) : '');
+ $search = x($_GET, 'search') ? notags(trim($_GET['search'])) : '';
+ $nets = x($_GET, 'nets') ? notags(trim($_GET['nets'])) : '';
$tabs = array(
array(
$tab_tpl = get_markup_template('common_tabs.tpl');
$t = replace_macros($tab_tpl, array('$tabs'=>$tabs));
-
-
$searching = false;
- if($search) {
+ $search_hdr = null;
+ if ($search) {
$search_hdr = $search;
$search_txt = dbesc(protect_sprintf(preg_quote($search)));
$searching = true;
}
$sql_extra .= (($searching) ? " AND (name REGEXP '$search_txt' OR url REGEXP '$search_txt' OR nick REGEXP '$search_txt') " : "");
- if($nets)
+ if ($nets) {
$sql_extra .= sprintf(" AND network = '%s' ", dbesc($nets));
+ }
$sql_extra2 = ((($sort_type > 0) && ($sort_type <= CONTACT_IS_FRIEND)) ? sprintf(" AND `rel` = %d ",intval($sort_type)) : '');
-
$r = q("SELECT COUNT(*) AS `total` FROM `contact`
WHERE `uid` = %d AND `self` = 0 AND `pending` = 0 $sql_extra $sql_extra2 ",
- intval($_SESSION['uid']));
+ intval($_SESSION['uid'])
+ );
if (DBM::is_result($r)) {
$a->set_pager_total($r[0]['total']);
$total = $r[0]['total'];
'$total' => $total,
'$search' => $search_hdr,
'$desc' => t('Search your contacts'),
- '$finding' => (($searching) ? sprintf(t('Results for: %s'),$search) : ""),
+ '$finding' => $searching ? t('Results for: %s', $search) : "",
'$submit' => t('Find'),
'$cmd' => $a->cmd,
'$contacts' => $contacts,
),
'$h_batch_actions' => t('Batch Actions'),
'$paginate' => paginate($a),
-
));
return $o;
$contact = $r[0];
$a->page['aside'] = "";
profile_load($a, "", 0, Contact::getDetailsByURL($contact["url"]));
- } else
- $profile = "";
+ }
$tab_str = contacts_tab($a, $contact_id, 1);
- $o .= $tab_str;
+ $o = $tab_str;
$o .= Contact::getPostsFromUrl($contact["url"]);
<?php
+
/**
* @file mod/crepair.php
*/
require_once 'include/contact_selectors.php';
require_once 'mod/contacts.php';
-function crepair_init(App $a) {
- if (! local_user()) {
+function crepair_init(App $a)
+{
+ if (!local_user()) {
return;
}
$contact_id = 0;
- if(($a->argc == 2) && intval($a->argv[1])) {
+ if (($a->argc == 2) && intval($a->argv[1])) {
$contact_id = intval($a->argv[1]);
$r = q("SELECT * FROM `contact` WHERE `uid` = %d and `id` = %d LIMIT 1",
intval(local_user()),
intval($contact_id)
);
- if (! DBM::is_result($r)) {
+ if (!DBM::is_result($r)) {
$contact_id = 0;
}
}
- if(! x($a->page,'aside'))
+ if (!x($a->page, 'aside')) {
$a->page['aside'] = '';
+ }
- if($contact_id) {
+ if ($contact_id) {
$a->data['contact'] = $r[0];
$contact = $r[0];
profile_load($a, "", 0, Contact::getDetailsByURL($contact["url"]));
}
}
-function crepair_post(App $a) {
- if (! local_user()) {
+function crepair_post(App $a)
+{
+ if (!local_user()) {
return;
}
$cid = (($a->argc > 1) ? intval($a->argv[1]) : 0);
- if($cid) {
+ if ($cid) {
$r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
intval($cid),
intval(local_user())
);
}
- if (! DBM::is_result($r)) {
+ if (!DBM::is_result($r)) {
return;
}
$contact = $r[0];
- $name = ((x($_POST,'name')) ? $_POST['name'] : $contact['name']);
- $nick = ((x($_POST,'nick')) ? $_POST['nick'] : '');
- $url = ((x($_POST,'url')) ? $_POST['url'] : '');
- $request = ((x($_POST,'request')) ? $_POST['request'] : '');
- $confirm = ((x($_POST,'confirm')) ? $_POST['confirm'] : '');
- $notify = ((x($_POST,'notify')) ? $_POST['notify'] : '');
- $poll = ((x($_POST,'poll')) ? $_POST['poll'] : '');
- $attag = ((x($_POST,'attag')) ? $_POST['attag'] : '');
- $photo = ((x($_POST,'photo')) ? $_POST['photo'] : '');
- $remote_self = ((x($_POST,'remote_self')) ? $_POST['remote_self'] : false);
- $nurl = normalise_link($url);
+ $name = defaults($_POST, 'name' , $contact['name']);
+ $nick = defaults($_POST, 'nick' , '');
+ $url = defaults($_POST, 'url' , '');
+ $request = defaults($_POST, 'request' , '');
+ $confirm = defaults($_POST, 'confirm' , '');
+ $notify = defaults($_POST, 'notify' , '');
+ $poll = defaults($_POST, 'poll' , '');
+ $attag = defaults($_POST, 'attag' , '');
+ $photo = defaults($_POST, 'photo' , '');
+ $remote_self = defaults($_POST, 'remote_self', false);
+ $nurl = normalise_link($url);
$r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `nurl` = '%s', `request` = '%s', `confirm` = '%s', `notify` = '%s', `poll` = '%s', `attag` = '%s' , `remote_self` = %d
WHERE `id` = %d AND `uid` = %d",
return;
}
-
-
-function crepair_content(App $a) {
-
- if (! local_user()) {
- notice( t('Permission denied.') . EOL);
+function crepair_content(App $a)
+{
+ if (!local_user()) {
+ notice(t('Permission denied.') . EOL);
return;
}
$cid = (($a->argc > 1) ? intval($a->argv[1]) : 0);
- if($cid) {
+ if ($cid) {
$r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
intval($cid),
intval(local_user())
);
}
- if (! DBM::is_result($r)) {
- notice( t('Contact not found.') . EOL);
+ if (!DBM::is_result($r)) {
+ notice(t('Contact not found.') . EOL);
return;
}
$returnaddr = "contacts/$cid";
- $allow_remote_self = Config::get('system','allow_users_remote_self');
+ $allow_remote_self = Config::get('system', 'allow_users_remote_self');
// Disable remote self for everything except feeds.
// There is an issue when you repeat an item from maybe twitter and you got comments from friendica and twitter
// Problem is, you couldn't reply to both networks.
- if (!in_array($contact['network'], array(NETWORK_FEED, NETWORK_DFRN, NETWORK_DIASPORA)))
+ if (!in_array($contact['network'], array(NETWORK_FEED, NETWORK_DFRN, NETWORK_DIASPORA))) {
$allow_remote_self = false;
+ }
- if ($contact['network'] == NETWORK_FEED)
- $remote_self_options = array('0'=>t('No mirroring'), '1'=>t('Mirror as forwarded posting'), '2'=>t('Mirror as my own posting'));
- else
- $remote_self_options = array('0'=>t('No mirroring'), '2'=>t('Mirror as my own posting'));
+ if ($contact['network'] == NETWORK_FEED) {
+ $remote_self_options = array('0' => t('No mirroring'), '1' => t('Mirror as forwarded posting'), '2' => t('Mirror as my own posting'));
+ } else {
+ $remote_self_options = array('0' => t('No mirroring'), '2' => t('Mirror as my own posting'));
+ }
- $update_profile = in_array($contact['network'], array(NETWORK_DFRN, NETWORK_DSPR, NETWORK_OSTATUS));
+ $update_profile = in_array($contact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS));
$tab_str = contacts_tab($a, $contact['id'], 5);
-
$tpl = get_markup_template('crepair.tpl');
- $o .= replace_macros($tpl, array(
- //'$title' => t('Repair Contact Settings'),
- '$tab_str' => $tab_str,
- '$warning' => $warning,
- '$info' => $info,
- '$returnaddr' => $returnaddr,
- '$return' => t('Return to contact editor'),
- '$update_profile' => update_profile,
- '$udprofilenow' => t('Refetch contact data'),
- '$contact_id' => $contact['id'],
- '$lbl_submit' => t('Submit'),
-
+ $o = replace_macros($tpl, array(
+ '$tab_str' => $tab_str,
+ '$warning' => $warning,
+ '$info' => $info,
+ '$returnaddr' => $returnaddr,
+ '$return' => t('Return to contact editor'),
+ '$update_profile' => $update_profile,
+ '$udprofilenow' => t('Refetch contact data'),
+ '$contact_id' => $contact['id'],
+ '$lbl_submit' => t('Submit'),
'$label_remote_self' => t('Remote Self'),
'$allow_remote_self' => $allow_remote_self,
'$remote_self' => array('remote_self',
- t('Mirror postings from this contact'),
- $contact['remote_self'],
- t('Mark this contact as remote_self, this will cause friendica to repost new entries from this contact.'),
- $remote_self_options
- ),
+ t('Mirror postings from this contact'),
+ $contact['remote_self'],
+ t('Mark this contact as remote_self, this will cause friendica to repost new entries from this contact.'),
+ $remote_self_options
+ ),
'$name' => array('name', t('Name') , htmlentities($contact['name'])),
'$nick' => array('nick', t('Account Nickname'), htmlentities($contact['nick'])),
));
return $o;
-
}
use Friendica\Model\User;
use Friendica\Network\Probe;
use Friendica\Protocol\Diaspora;
+use Friendica\Util\Crypto;
require_once 'include/enotify.php';
* worried about key leakage than anybody cracking it.
*
*/
- require_once 'include/crypto.php';
-
- $res = new_keypair(4096);
+ $res = Crypto::newKeypair(4096);
$private_key = $res['prvkey'];
<?php
+
/**
* @file mod/dfrn_poll.php
*/
require_once 'include/items.php';
require_once 'include/auth.php';
-function dfrn_poll_init(App $a) {
- $dfrn_id = ((x($_GET,'dfrn_id')) ? $_GET['dfrn_id'] : '');
- $type = ((x($_GET,'type')) ? $_GET['type'] : 'data');
- $last_update = ((x($_GET,'last_update')) ? $_GET['last_update'] : '');
- $destination_url = ((x($_GET,'destination_url')) ? $_GET['destination_url'] : '');
- $challenge = ((x($_GET,'challenge')) ? $_GET['challenge'] : '');
- $sec = ((x($_GET,'sec')) ? $_GET['sec'] : '');
- $dfrn_version = ((x($_GET,'dfrn_version')) ? (float) $_GET['dfrn_version'] : 2.0);
- $perm = ((x($_GET,'perm')) ? $_GET['perm'] : 'r');
- $quiet = ((x($_GET,'quiet')) ? true : false);
+function dfrn_poll_init(App $a)
+{
+ $dfrn_id = x($_GET,'dfrn_id') ? $_GET['dfrn_id'] : '';
+ $type = x($_GET,'type') ? $_GET['type'] : 'data';
+ $last_update = x($_GET,'last_update') ? $_GET['last_update'] : '';
+ $destination_url = x($_GET,'destination_url') ? $_GET['destination_url'] : '';
+ $challenge = x($_GET,'challenge') ? $_GET['challenge'] : '';
+ $sec = x($_GET,'sec') ? $_GET['sec'] : '';
+ $dfrn_version = x($_GET,'dfrn_version') ? (float) $_GET['dfrn_version'] : 2.0;
+ $perm = x($_GET,'perm') ? $_GET['perm'] : 'r';
+ $quiet = x($_GET,'quiet') ? true : false;
// Possibly it is an OStatus compatible server that requests a user feed
if (($a->argc > 1) && ($dfrn_id == '') && !strstr($_SERVER["HTTP_USER_AGENT"], 'Friendica')) {
$nickname = $a->argv[1];
header("Content-type: application/atom+xml");
- echo OStatus::feed($a, $nickname, $last_update, 10);
+ echo OStatus::feed($nickname, $last_update, 10);
killme();
}
- $direction = (-1);
-
+ $direction = -1;
- if(strpos($dfrn_id,':') == 1) {
- $direction = intval(substr($dfrn_id,0,1));
- $dfrn_id = substr($dfrn_id,2);
+ if (strpos($dfrn_id, ':') == 1) {
+ $direction = intval(substr($dfrn_id, 0, 1));
+ $dfrn_id = substr($dfrn_id, 2);
}
$hidewall = false;
- if(($dfrn_id === '') && (! x($_POST,'dfrn_id'))) {
- if((Config::get('system','block_public')) && (! local_user()) && (! remote_user())) {
+ if (($dfrn_id === '') && (!x($_POST, 'dfrn_id'))) {
+ if (Config::get('system', 'block_public') && !local_user() && !remote_user()) {
http_status_exit(403);
}
$user = '';
- if($a->argc > 1) {
+ if ($a->argc > 1) {
$r = q("SELECT `hidewall`,`nickname` FROM `user` WHERE `user`.`nickname` = '%s' LIMIT 1",
dbesc($a->argv[1])
);
- if (!$r)
+ if (!$r) {
http_status_exit(404);
+ }
$hidewall = ($r[0]['hidewall'] && !local_user());
logger('dfrn_poll: public feed request from ' . $_SERVER['REMOTE_ADDR'] . ' for ' . $user);
header("Content-type: application/atom+xml");
- echo DFRN::feed('', $user,$last_update, 0, $hidewall);
+ echo DFRN::feed('', $user, $last_update, 0, $hidewall);
killme();
}
- if(($type === 'profile') && (! strlen($sec))) {
-
+ if (($type === 'profile') && (!strlen($sec))) {
$sql_extra = '';
- switch($direction) {
- case (-1):
- $sql_extra = sprintf(" AND ( `dfrn-id` = '%s' OR `issued-id` = '%s' ) ", dbesc($dfrn_id),dbesc($dfrn_id));
+ switch ($direction) {
+ case -1:
+ $sql_extra = sprintf(" AND ( `dfrn-id` = '%s' OR `issued-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
$my_id = $dfrn_id;
break;
case 0:
);
if (DBM::is_result($r)) {
-
$s = fetch_url($r[0]['poll'] . '?dfrn_id=' . $my_id . '&type=profile-check');
logger("dfrn_poll: old profile returns " . $s, LOGGER_DATA);
- if(strlen($s)) {
-
+ if (strlen($s)) {
$xml = parse_xml_string($s);
- if((int) $xml->status == 1) {
+ if ((int) $xml->status === 1) {
$_SESSION['authenticated'] = 1;
- if(! x($_SESSION,'remote'))
+ if (!x($_SESSION, 'remote')) {
$_SESSION['remote'] = array();
+ }
- $_SESSION['remote'][] = array('cid' => $r[0]['id'],'uid' => $r[0]['uid'],'url' => $r[0]['url']);
+ $_SESSION['remote'][] = array('cid' => $r[0]['id'], 'uid' => $r[0]['uid'], 'url' => $r[0]['url']);
$_SESSION['visitor_id'] = $r[0]['id'];
$_SESSION['visitor_home'] = $r[0]['url'];
$_SESSION['visitor_handle'] = $r[0]['addr'];
$_SESSION['visitor_visiting'] = $r[0]['uid'];
- if(!$quiet)
- info( sprintf(t('%1$s welcomes %2$s'), $r[0]['username'] , $r[0]['name']) . EOL);
+ if (!$quiet) {
+ info(sprintf(t('%1$s welcomes %2$s'), $r[0]['username'], $r[0]['name']) . EOL);
+ }
+
// Visitors get 1 day session.
$session_id = session_id();
$expire = time() + 86400;
goaway((strlen($destination_url)) ? $destination_url : System::baseUrl() . '/profile/' . $profile);
}
goaway(System::baseUrl());
-
}
- if($type === 'profile-check' && $dfrn_version < 2.2 ) {
-
- if((strlen($challenge)) && (strlen($sec))) {
-
+ if ($type === 'profile-check' && $dfrn_version < 2.2) {
+ if ((strlen($challenge)) && (strlen($sec))) {
q("DELETE FROM `profile_check` WHERE `expire` < " . intval(time()));
$r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1",
dbesc($sec)
);
- if (! DBM::is_result($r)) {
+ if (!DBM::is_result($r)) {
xml_status(3, 'No ticket');
// NOTREACHED
}
+
$orig_id = $r[0]['dfrn_id'];
- if(strpos($orig_id, ':'))
- $orig_id = substr($orig_id,2);
+ if (strpos($orig_id, ':')) {
+ $orig_id = substr($orig_id, 2);
+ }
$c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
intval($r[0]['cid'])
);
- if (! DBM::is_result($c)) {
+ if (!DBM::is_result($c)) {
xml_status(3, 'No profile');
}
+
$contact = $c[0];
$sent_dfrn_id = hex2bin($dfrn_id);
- $challenge = hex2bin($challenge);
+ $challenge = hex2bin($challenge);
$final_dfrn_id = '';
- if(($contact['duplex']) && strlen($contact['prvkey'])) {
- openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
- openssl_private_decrypt($challenge,$decoded_challenge,$contact['prvkey']);
- }
- else {
- openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
- openssl_public_decrypt($challenge,$decoded_challenge,$contact['pubkey']);
+ if (($contact['duplex']) && strlen($contact['prvkey'])) {
+ openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
+ openssl_private_decrypt($challenge, $decoded_challenge, $contact['prvkey']);
+ } else {
+ openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
+ openssl_public_decrypt($challenge, $decoded_challenge, $contact['pubkey']);
}
$final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
- if(strpos($final_dfrn_id,':') == 1)
- $final_dfrn_id = substr($final_dfrn_id,2);
+ if (strpos($final_dfrn_id, ':') == 1) {
+ $final_dfrn_id = substr($final_dfrn_id, 2);
+ }
- if($final_dfrn_id != $orig_id) {
+ if ($final_dfrn_id != $orig_id) {
logger('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, LOGGER_DEBUG);
// did not decode properly - cannot trust this site
xml_status(3, 'Bad decryption');
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><dfrn_poll><status>0</status><challenge>$decoded_challenge</challenge><sec>$sec</sec></dfrn_poll>";
killme();
// NOTREACHED
- }
- else {
- // old protocol
-
- switch($direction) {
+ } else {
+ // old protocol
+ switch ($direction) {
case 1:
$dfrn_id = '0:' . $dfrn_id;
break;
break;
}
-
q("DELETE FROM `profile_check` WHERE `expire` < " . intval(time()));
$r = q("SELECT * FROM `profile_check` WHERE `dfrn_id` = '%s' ORDER BY `expire` DESC",
dbesc($dfrn_id));
return; // NOTREACHED
}
}
-
}
-
-
-function dfrn_poll_post(App $a) {
-
- $dfrn_id = ((x($_POST,'dfrn_id')) ? $_POST['dfrn_id'] : '');
- $challenge = ((x($_POST,'challenge')) ? $_POST['challenge'] : '');
- $url = ((x($_POST,'url')) ? $_POST['url'] : '');
- $sec = ((x($_POST,'sec')) ? $_POST['sec'] : '');
- $ptype = ((x($_POST,'type')) ? $_POST['type'] : '');
- $dfrn_version = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version'] : 2.0);
- $perm = ((x($_POST,'perm')) ? $_POST['perm'] : 'r');
-
- if($ptype === 'profile-check') {
-
- if((strlen($challenge)) && (strlen($sec))) {
-
+function dfrn_poll_post(App $a)
+{
+ $dfrn_id = x($_POST,'dfrn_id') ? $_POST['dfrn_id'] : '';
+ $challenge = x($_POST,'challenge') ? $_POST['challenge'] : '';
+ $url = x($_POST,'url') ? $_POST['url'] : '';
+ $sec = x($_POST,'sec') ? $_POST['sec'] : '';
+ $ptype = x($_POST,'type') ? $_POST['type'] : '';
+ $dfrn_version = x($_POST,'dfrn_version') ? (float) $_POST['dfrn_version'] : 2.0;
+ $perm = x($_POST,'perm') ? $_POST['perm'] : 'r';
+
+ if ($ptype === 'profile-check') {
+ if (strlen($challenge) && strlen($sec)) {
logger('dfrn_poll: POST: profile-check');
q("DELETE FROM `profile_check` WHERE `expire` < " . intval(time()));
$r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1",
dbesc($sec)
);
- if (! DBM::is_result($r)) {
+ if (!DBM::is_result($r)) {
xml_status(3, 'No ticket');
// NOTREACHED
}
+
$orig_id = $r[0]['dfrn_id'];
- if(strpos($orig_id, ':'))
- $orig_id = substr($orig_id,2);
+ if (strpos($orig_id, ':')) {
+ $orig_id = substr($orig_id, 2);
+ }
$c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
intval($r[0]['cid'])
);
- if (! DBM::is_result($c)) {
+ if (!DBM::is_result($c)) {
xml_status(3, 'No profile');
}
+
$contact = $c[0];
$sent_dfrn_id = hex2bin($dfrn_id);
- $challenge = hex2bin($challenge);
+ $challenge = hex2bin($challenge);
$final_dfrn_id = '';
- if(($contact['duplex']) && strlen($contact['prvkey'])) {
- openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
- openssl_private_decrypt($challenge,$decoded_challenge,$contact['prvkey']);
- }
- else {
- openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
- openssl_public_decrypt($challenge,$decoded_challenge,$contact['pubkey']);
+ if ($contact['duplex'] && strlen($contact['prvkey'])) {
+ openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
+ openssl_private_decrypt($challenge, $decoded_challenge, $contact['prvkey']);
+ } else {
+ openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
+ openssl_public_decrypt($challenge, $decoded_challenge, $contact['pubkey']);
}
$final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
- if(strpos($final_dfrn_id,':') == 1)
- $final_dfrn_id = substr($final_dfrn_id,2);
+ if (strpos($final_dfrn_id, ':') == 1) {
+ $final_dfrn_id = substr($final_dfrn_id, 2);
+ }
- if($final_dfrn_id != $orig_id) {
+ if ($final_dfrn_id != $orig_id) {
logger('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, LOGGER_DEBUG);
// did not decode properly - cannot trust this site
xml_status(3, 'Bad decryption');
killme();
// NOTREACHED
}
-
}
- $direction = (-1);
- if(strpos($dfrn_id,':') == 1) {
- $direction = intval(substr($dfrn_id,0,1));
- $dfrn_id = substr($dfrn_id,2);
+ $direction = -1;
+ if (strpos($dfrn_id, ':') == 1) {
+ $direction = intval(substr($dfrn_id, 0, 1));
+ $dfrn_id = substr($dfrn_id, 2);
}
-
$r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
dbesc($dfrn_id),
dbesc($challenge)
);
- if (! DBM::is_result($r)) {
+ if (!DBM::is_result($r)) {
killme();
}
$sql_extra = '';
- switch($direction) {
- case (-1):
+ switch ($direction) {
+ case -1:
$sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
$my_id = $dfrn_id;
break;
break; // NOTREACHED
}
-
$r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 $sql_extra LIMIT 1");
-
-
- if (! DBM::is_result($r)) {
+ if (!DBM::is_result($r)) {
killme();
}
$owner_uid = $r[0]['uid'];
$contact_id = $r[0]['id'];
-
- if($type === 'reputation' && strlen($url)) {
+ if ($type === 'reputation' && strlen($url)) {
$r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
dbesc($url),
intval($owner_uid)
$reputation = $r[0]['rating'];
$text = $r[0]['reason'];
- if($r[0]['id'] == $contact_id) { // inquiring about own reputation not allowed
+ if ($r[0]['id'] == $contact_id) { // inquiring about own reputation not allowed
$reputation = 0;
$text = '';
}
";
killme();
// NOTREACHED
- }
- else {
-
+ } else {
// Update the writable flag if it changed
- logger('dfrn_poll: post request feed: ' . print_r($_POST,true),LOGGER_DATA);
- if($dfrn_version >= 2.21) {
- if($perm === 'rw')
+ logger('dfrn_poll: post request feed: ' . print_r($_POST, true), LOGGER_DATA);
+ if ($dfrn_version >= 2.21) {
+ if ($perm === 'rw') {
$writable = 1;
- else
+ } else {
$writable = 0;
+ }
- if($writable != $contact['writable']) {
+ if ($writable != $contact['writable']) {
q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d",
intval($writable),
intval($contact_id)
$o = DFRN::feed($dfrn_id, $a->argv[1], $last_update, $direction);
echo $o;
killme();
-
}
}
-function dfrn_poll_content(App $a) {
-
- $dfrn_id = ((x($_GET,'dfrn_id')) ? $_GET['dfrn_id'] : '');
- $type = ((x($_GET,'type')) ? $_GET['type'] : 'data');
- $last_update = ((x($_GET,'last_update')) ? $_GET['last_update'] : '');
- $destination_url = ((x($_GET,'destination_url')) ? $_GET['destination_url'] : '');
- $sec = ((x($_GET,'sec')) ? $_GET['sec'] : '');
- $dfrn_version = ((x($_GET,'dfrn_version')) ? (float) $_GET['dfrn_version'] : 2.0);
- $perm = ((x($_GET,'perm')) ? $_GET['perm'] : 'r');
- $quiet = ((x($_GET,'quiet')) ? true : false);
-
- $direction = (-1);
- if(strpos($dfrn_id,':') == 1) {
- $direction = intval(substr($dfrn_id,0,1));
- $dfrn_id = substr($dfrn_id,2);
+function dfrn_poll_content(App $a)
+{
+ $dfrn_id = x($_GET,'dfrn_id') ? $_GET['dfrn_id'] : '';
+ $type = x($_GET,'type') ? $_GET['type'] : 'data';
+ $last_update = x($_GET,'last_update') ? $_GET['last_update'] : '';
+ $destination_url = x($_GET,'destination_url') ? $_GET['destination_url'] : '';
+ $sec = x($_GET,'sec') ? $_GET['sec'] : '';
+ $dfrn_version = x($_GET,'dfrn_version') ? (float) $_GET['dfrn_version'] : 2.0;
+ $perm = x($_GET,'perm') ? $_GET['perm'] : 'r';
+ $quiet = x($_GET,'quiet') ? true : false;
+
+ $direction = -1;
+ if (strpos($dfrn_id, ':') == 1) {
+ $direction = intval(substr($dfrn_id, 0, 1));
+ $dfrn_id = substr($dfrn_id, 2);
}
-
- if($dfrn_id != '') {
+ if ($dfrn_id != '') {
// initial communication from external contact
$hash = random_string();
$r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
- if($type !== 'profile') {
+ if ($type !== 'profile') {
$r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` , `type`, `last_update` )
VALUES( '%s', '%s', '%s', '%s', '%s' ) ",
dbesc($hash),
dbesc($last_update)
);
}
+
$sql_extra = '';
- switch($direction) {
- case (-1):
- if($type === 'profile')
- $sql_extra = sprintf(" AND ( `dfrn-id` = '%s' OR `issued-id` = '%s' ) ", dbesc($dfrn_id),dbesc($dfrn_id));
- else
+ switch ($direction) {
+ case -1:
+ if ($type === 'profile') {
+ $sql_extra = sprintf(" AND ( `dfrn-id` = '%s' OR `issued-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
+ } else {
$sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
+ }
+
$my_id = $dfrn_id;
break;
case 0:
AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
dbesc($nickname)
);
-
if (DBM::is_result($r)) {
-
$challenge = '';
$encrypted_id = '';
- $id_str = $my_id . '.' . mt_rand(1000,9999);
-
- if(($r[0]['duplex'] && strlen($r[0]['pubkey'])) || (! strlen($r[0]['prvkey']))) {
- openssl_public_encrypt($hash,$challenge,$r[0]['pubkey']);
- openssl_public_encrypt($id_str,$encrypted_id,$r[0]['pubkey']);
- }
- else {
- openssl_private_encrypt($hash,$challenge,$r[0]['prvkey']);
- openssl_private_encrypt($id_str,$encrypted_id,$r[0]['prvkey']);
+ $id_str = $my_id . '.' . mt_rand(1000, 9999);
+
+ if (($r[0]['duplex'] && strlen($r[0]['pubkey'])) || !strlen($r[0]['prvkey'])) {
+ openssl_public_encrypt($hash, $challenge, $r[0]['pubkey']);
+ openssl_public_encrypt($id_str, $encrypted_id, $r[0]['pubkey']);
+ } else {
+ openssl_private_encrypt($hash, $challenge, $r[0]['prvkey']);
+ openssl_private_encrypt($id_str, $encrypted_id, $r[0]['prvkey']);
}
$challenge = bin2hex($challenge);
$encrypted_id = bin2hex($encrypted_id);
- }
- else {
+ } else {
$status = 1;
$challenge = '';
$encrypted_id = '';
}
- if(($type === 'profile') && (strlen($sec))) {
-
+ if (($type === 'profile') && (strlen($sec))) {
// URL reply
-
- if($dfrn_version < 2.2) {
+ if ($dfrn_version < 2.2) {
$s = fetch_url($r[0]['poll']
. '?dfrn_id=' . $encrypted_id
. '&type=profile-check'
. '&challenge=' . $challenge
. '&sec=' . $sec
);
- }
- else {
+ } else {
$s = post_url($r[0]['poll'], array(
'dfrn_id' => $encrypted_id,
'type' => 'profile-check',
$profile = ((DBM::is_result($r) && $r[0]['nickname']) ? $r[0]['nickname'] : $nickname);
- switch($destination_url) {
+ switch ($destination_url) {
case 'profile':
$dest = System::baseUrl() . '/profile/' . $profile . '?f=&tab=profile';
break;
logger("dfrn_poll: sec profile: " . $s, LOGGER_DATA);
- if(strlen($s) && strstr($s,'<?xml')) {
-
+ if (strlen($s) && strstr($s, '<?xml')) {
$xml = parse_xml_string($s);
- logger('dfrn_poll: profile: parsed xml: ' . print_r($xml,true), LOGGER_DATA);
+ logger('dfrn_poll: profile: parsed xml: ' . print_r($xml, true), LOGGER_DATA);
logger('dfrn_poll: secure profile: challenge: ' . $xml->challenge . ' expecting ' . $hash);
logger('dfrn_poll: secure profile: sec: ' . $xml->sec . ' expecting ' . $sec);
-
- if(((int) $xml->status == 0) && ($xml->challenge == $hash) && ($xml->sec == $sec)) {
+ if (((int) $xml->status == 0) && ($xml->challenge == $hash) && ($xml->sec == $sec)) {
$_SESSION['authenticated'] = 1;
- if(! x($_SESSION,'remote'))
+ if (!x($_SESSION, 'remote')) {
$_SESSION['remote'] = array();
- $_SESSION['remote'][] = array('cid' => $r[0]['id'],'uid' => $r[0]['uid'],'url' => $r[0]['url']);
+ }
+
+ $_SESSION['remote'][] = array('cid' => $r[0]['id'], 'uid' => $r[0]['uid'], 'url' => $r[0]['url']);
$_SESSION['visitor_id'] = $r[0]['id'];
$_SESSION['visitor_home'] = $r[0]['url'];
$_SESSION['visitor_visiting'] = $r[0]['uid'];
- if(!$quiet)
- info( sprintf(t('%1$s welcomes %2$s'), $r[0]['username'] , $r[0]['name']) . EOL);
+ if (!$quiet) {
+ info(sprintf(t('%1$s welcomes %2$s'), $r[0]['username'], $r[0]['name']) . EOL);
+ }
+
// Visitors get 1 day session.
$session_id = session_id();
$expire = time() + 86400;
}
goaway($dest);
// NOTREACHED
-
- }
- else {
+ } else {
// XML reply
header("Content-type: text/xml");
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
. "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
. "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
. "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
- . '</dfrn_poll>' . "\r\n" ;
+ . '</dfrn_poll>' . "\r\n";
killme();
// NOTREACHED
}
if ($update) {
$item_id = $_REQUEST['item_id'];
- $item = dba::select('item', ['uid'], ['id' => $item_id], ['limit' => 1]);
+ $item = dba::select('item', ['uid', 'parent'], ['id' => $item_id], ['limit' => 1]);
$a->profile = array('uid' => intval($item['uid']), 'profile_uid' => intval($item['uid']));
+ $item_parent = $item['parent'];
} else {
$item_id = (($a->argc > 2) ? $a->argv[2] : 0);
$contact_id = 0;
- if (is_array($_SESSION['remote'])) {
+ if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
foreach ($_SESSION['remote'] as $v) {
if ($v['uid'] == $a->profile['uid']) {
$contact_id = $v['cid'];
}
$is_owner = (local_user() && (in_array($a->profile['profile_uid'], [local_user(), 0])) ? true : false);
- if ($a->profile['hidewall'] && !$is_owner && !$remote_contact) {
+ if (x($a->profile, 'hidewall') && !$is_owner && !$remote_contact) {
notice(t('Access to this profile has been restricted.') . EOL);
return;
}
return;
}
- if ($a->argc == 1) {
+ if ($a->argc > 1) {
// If it's a json request abort here because we don't
// need the widget data
if ($a->argv[1] === 'json') {
));
$o = '';
+ $tabs = '';
// tabs
if ($a->theme_events_in_profile) {
$tabs = profile_tabs($a, true);
$start = sprintf('%d-%d-%d %d:%d:%d', $y, $m, 1, 0, 0, 0);
$finish = sprintf('%d-%d-%d %d:%d:%d', $y, $m, $dim, 23, 59, 59);
-
- if ($a->argv[1] === 'json') {
- if (x($_GET, 'start')) {$start = $_GET['start'];}
- if (x($_GET, 'end')) {$finish = $_GET['end'];}
+ if ($a->argc > 1 && $a->argv[1] === 'json') {
+ if (x($_GET, 'start')) {
+ $start = $_GET['start'];
+ }
+ if (x($_GET, 'end')) {
+ $finish = $_GET['end'];
+ }
}
$start = datetime_convert('UTC', 'UTC', $start);
$events = process_events($r);
}
- if ($a->argv[1] === 'json'){
+ if ($a->argc > 1 && $a->argv[1] === 'json'){
echo json_encode($events);
killme();
}
use Friendica\Protocol\Diaspora;
use Friendica\Util\XML;
-require_once "include/crypto.php";
-
function fetch_init(App $a)
{
function follow_post(App $a) {
- if (! local_user()) {
- notice( t('Permission denied.') . EOL);
+ if (!local_user()) {
+ notice(t('Permission denied.') . EOL);
goaway($_SESSION['return_url']);
// NOTREACHED
}
goaway(System::baseUrl().'/contacts/'.$result['cid']);
}
- info( t('Contact added').EOL);
+ info(t('Contact added').EOL);
if (strstr($return_url,'contacts')) {
goaway(System::baseUrl().'/contacts/'.$contact_id);
function follow_content(App $a) {
- if (! local_user()) {
- notice( t('Permission denied.') . EOL);
+ if (!local_user()) {
+ notice(t('Permission denied.') . EOL);
goaway($_SESSION['return_url']);
// NOTREACHED
}
$ret = Probe::uri($url);
if (($ret["network"] == NETWORK_DIASPORA) && !Config::get('system','diaspora_enabled')) {
- notice( t("Diaspora support isn't enabled. Contact can't be added.") . EOL);
+ notice(t("Diaspora support isn't enabled. Contact can't be added.") . EOL);
$submit = "";
//goaway($_SESSION['return_url']);
// NOTREACHED
}
if (($ret["network"] == NETWORK_OSTATUS) && Config::get('system','ostatus_disabled')) {
- notice( t("OStatus support is disabled. Contact can't be added.") . EOL);
+ notice(t("OStatus support is disabled. Contact can't be added.") . EOL);
$submit = "";
//goaway($_SESSION['return_url']);
// NOTREACHED
}
if ($ret["network"] == NETWORK_PHANTOM) {
- notice( t("The network type couldn't be detected. Contact can't be added.") . EOL);
+ notice(t("The network type couldn't be detected. Contact can't be added.") . EOL);
$submit = "";
//goaway($_SESSION['return_url']);
// NOTREACHED
$r = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1", intval($uid));
if (!$r) {
- notice( t('Permission denied.') . EOL);
+ notice(t('Permission denied.') . EOL);
goaway($_SESSION['return_url']);
// NOTREACHED
}
));
$a->page['aside'] = "";
- profile_load($a, "", 0, Contact::getDetailsByURL($ret["url"]));
+
+ profile_load($a, "", 0, Contact::getDetailsByURL($ret["url"]), false);
if ($gcontact_id <> 0) {
$o .= replace_macros(get_markup_template('section_title.tpl'),
use Friendica\Core\Worker;
use Friendica\Database\DBM;
+require_once 'include/follow.php';
+
function fsuggest_post(App $a) {
if (! local_user()) {
<?php
-
+/**
+ * @file mod/hostxrd.php
+ */
use Friendica\App;
use Friendica\Core\Config;
use Friendica\Core\System;
+use Friendica\Protocol\Salmon;
+use Friendica\Util\Crypto;
-require_once('include/crypto.php');
-
-function hostxrd_init(App $a) {
+function hostxrd_init(App $a)
+{
header('Access-Control-Allow-Origin: *');
header("Content-type: text/xml");
- $pubkey = Config::get('system','site_pubkey');
+ $pubkey = Config::get('system', 'site_pubkey');
- if(! $pubkey) {
- $res = new_keypair(1024);
+ if (! $pubkey) {
+ $res = Crypto::newKeypair(1024);
Config::set('system','site_prvkey', $res['prvkey']);
Config::set('system','site_pubkey', $res['pubkey']);
'$zhost' => $a->get_hostname(),
'$zroot' => System::baseUrl(),
'$domain' => System::baseUrl(),
- '$bigkey' => salmon_key(Config::get('system','site_pubkey')),
- ));
- exit();
+ '$bigkey' => Salmon::salmonKey(Config::get('system', 'site_pubkey')))
+ );
+ exit();
}
* Author: Rabuzarus <https://github.com/rabuzarus>
* License: GNU AFFERO GENERAL PUBLIC LICENSE (Version 3)
*/
-
use Friendica\App;
use Friendica\Core\Config;
use Friendica\Model\Contact;
use Friendica\Model\GContact;
-function hovercard_init(App $a) {
+function hovercard_init(App $a)
+{
// Just for testing purposes
- $_GET["mode"] = "minimal";
+ $_GET['mode'] = 'minimal';
}
-function hovercard_content() {
- $profileurl = (x($_REQUEST,'profileurl') ? $_REQUEST['profileurl'] : "");
- $datatype = (x($_REQUEST,'datatype') ?$_REQUEST['datatype'] : "json");
+function hovercard_content()
+{
+ $profileurl = defaults($_REQUEST, 'profileurl', '');
+ $datatype = defaults($_REQUEST, 'datatype' , 'json');
// Get out if the system doesn't have public access allowed
- if(intval(Config::get('system','block_public')))
+ if (intval(Config::get('system', 'block_public'))) {
http_status_exit(401);
+ }
// Return the raw content of the template. We use this to make templates usable for js functions.
// Look at hovercard.js (function getHoverCardTemplate()).
- // This part should be moved in it's own module. Maybe we could make more templates accessabel.
- // (We need to discuss possible security lacks before doing this)
- if ($datatype == "tpl") {
- $templatecontent = get_template_content("hovercard.tpl");
+ // This part should be moved in its own module. Maybe we could make more templates accessible.
+ // (We need to discuss possible security leaks before doing this)
+ if ($datatype == 'tpl') {
+ $templatecontent = get_template_content('hovercard.tpl');
echo $templatecontent;
killme();
}
- // If a contact is connected the url is internally changed to "redir/CID". We need the pure url to search for
+ // If a contact is connected the url is internally changed to 'redir/CID'. We need the pure url to search for
// the contact. So we strip out the contact id from the internal url and look in the contact table for
// the real url (nurl)
- if (local_user() && strpos($profileurl, "redir/") === 0) {
+ $cid = 0;
+ if (local_user() && strpos($profileurl, 'redir/') === 0) {
$cid = intval(substr($profileurl, 6));
- $r = dba::select('contact', array('nurl', 'self'), array('id' => $cid), array('limit' => 1));
- $profileurl = ($r["nurl"] ? $r["nurl"] : "");
- $self = ($r["self"] ? $r["self"] : "");
+ $r = dba::select('contact', array('nurl'), array('id' => $cid), array('limit' => 1));
+ $profileurl = defaults($r, 'nurl', '');
}
+ $contact = [];
// if it's the url containing https it should be converted to http
$nurl = normalise_link(GContact::cleanContactUrl($profileurl));
- if($nurl) {
+ if ($nurl) {
// Search for contact data
$contact = Contact::getDetailsByURL($nurl);
}
- if(!is_array($contact))
+ if (!count($contact)) {
return;
+ }
// Get the photo_menu - the menu if possible contact actions
- if(local_user())
+ if (local_user()) {
$actions = Contact::photoMenu($contact);
-
+ }
// Move the contact data to the profile array so we can deliver it to
- //
$profile = array(
- 'name' => $contact["name"],
- 'nick' => $contact["nick"],
- 'addr' => (($contact["addr"] != "") ? $contact["addr"] : $contact["url"]),
- 'thumb' => proxy_url($contact["thumb"], false, PROXY_SIZE_THUMB),
- 'url' => ($cid ? ("redir/".$cid) : zrl($contact["url"])),
- 'nurl' => $contact["nurl"], // We additionally store the nurl as identifier
-// 'alias' => $contact["alias"],
- 'location' => $contact["location"],
- 'gender' => $contact["gender"],
- 'about' => $contact["about"],
- 'network' => format_network_name($contact["network"], $contact["url"]),
- 'tags' => $contact["keywords"],
-// 'nsfw' => intval($contact["nsfw"]),
-// 'server_url' => $contact["server_url"],
- 'bd' => (($contact["birthday"] <= '0001-01-01') ? "" : $contact["birthday"]),
-// 'generation' => $contact["generation"],
+ 'name' => $contact['name'],
+ 'nick' => $contact['nick'],
+ 'addr' => defaults($contact, 'addr', $contact['url']),
+ 'thumb' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
+ 'url' => $cid ? ('redir/' . $cid) : zrl($contact['url']),
+ 'nurl' => $contact['nurl'], // We additionally store the nurl as identifier
+ 'location' => $contact['location'],
+ 'gender' => $contact['gender'],
+ 'about' => $contact['about'],
+ 'network' => format_network_name($contact['network'], $contact['url']),
+ 'tags' => $contact['keywords'],
+ 'bd' => $contact['birthday'] <= '0001-01-01' ? '' : $contact['birthday'],
'account_type' => Contact::getAccountType($contact),
- 'actions' => $actions,
+ 'actions' => $actions,
);
- if($datatype == "html") {
- $t = get_markup_template("hovercard.tpl");
-
- $o = replace_macros($t, array(
+ if ($datatype == 'html') {
+ $tpl = get_markup_template('hovercard.tpl');
+ $o = replace_macros($tpl, array(
'$profile' => $profile,
));
return $o;
-
} else {
json_return_and_die($profile);
}
*
* @return string|bool Output the raw content if existent, otherwise false
*/
-function get_template_content($template, $root = "") {
-
+function get_template_content($template, $root = '')
+{
// We load the whole template system to get the filename.
// Maybe we can do it a little bit smarter if I get time.
$t = get_markup_template($template, $root);
$filename = $t->filename;
// Get the content of the template file
- if(file_exists($filename)) {
+ if (file_exists($filename)) {
$content = file_get_contents($filename);
return $content;
use Friendica\Protocol\Email;
use Friendica\Util\Emailer;
-require_once 'include/crypto.php';
require_once 'include/enotify.php';
require_once 'include/tags.php';
require_once 'include/files.php';
use Friendica\App;
use Friendica\Core\System;
-require_once('include/security.php');
-require_once('include/bbcode.php');
-require_once('include/items.php');
-require_once('include/like.php');
+require_once 'include/security.php';
+require_once 'include/bbcode.php';
+require_once 'include/items.php';
+require_once 'include/like.php';
function like_content(App $a) {
- if(! local_user() && ! remote_user()) {
+ if (!local_user() && !remote_user()) {
return false;
}
$verb = notags(trim($_GET['verb']));
- if(! $verb)
+ if (!$verb) {
$verb = 'like';
+ }
$item_id = (($a->argc > 1) ? notags(trim($a->argv[1])) : 0);
$r = do_like($item_id, $verb);
- if (!$r) return;
+ if (!$r) {
+ return;
+ }
// See if we've been passed a return path to redirect to
$return_path = ((x($_REQUEST,'return')) ? $_REQUEST['return'] : '');
like_content_return(System::baseUrl(), $return_path);
killme(); // NOTREACHED
-// return; // NOTREACHED
}
// then redirect back to the calling page. If not, just quietly end
function like_content_return($baseurl, $return_path) {
-
- if($return_path) {
+ if ($return_path) {
$rand = '_=' . time();
- if(strpos($return_path, '?')) $rand = "&$rand";
- else $rand = "?$rand";
+ if (strpos($return_path, '?')) {
+ $rand = "&$rand";
+ } else {
+ $rand = "?$rand";
+ }
goaway($baseurl . "/" . $return_path . $rand);
}
killme();
}
-
require_once 'include/message.php';
require_once 'include/conversation.php';
-function message_init(App $a) {
-
+function message_init(App $a)
+{
$tabs = '';
- if ($a->argc >1 && is_numeric($a->argv[1])) {
- $tabs = render_messages(get_messages(local_user(),0,5), 'mail_list.tpl');
+ if ($a->argc > 1 && is_numeric($a->argv[1])) {
+ $tabs = render_messages(get_messages(local_user(), 0, 5), 'mail_list.tpl');
}
$new = array(
'label' => t('New Message'),
'url' => 'message/new',
- 'sel'=> ($a->argv[1] == 'new'),
+ 'sel' => $a->argc > 1 && $a->argv[1] == 'new',
'accesskey' => 'm',
);
$tpl = get_markup_template('message_side.tpl');
$a->page['aside'] = replace_macros($tpl, array(
- '$tabs'=>$tabs,
- '$new'=>$new,
+ '$tabs' => $tabs,
+ '$new' => $new,
));
$base = System::baseUrl();
$head_tpl = get_markup_template('message-head.tpl');
- $a->page['htmlhead'] .= replace_macros($head_tpl,array(
+ $a->page['htmlhead'] .= replace_macros($head_tpl, array(
'$baseurl' => System::baseUrl(true),
'$base' => $base
));
$end_tpl = get_markup_template('message-end.tpl');
- $a->page['end'] .= replace_macros($end_tpl,array(
+ $a->page['end'] .= replace_macros($end_tpl, array(
'$baseurl' => System::baseUrl(true),
'$base' => $base
));
-
}
-function message_post(App $a) {
-
- if (! local_user()) {
- notice( t('Permission denied.') . EOL);
+function message_post(App $a)
+{
+ if (!local_user()) {
+ notice(t('Permission denied.') . EOL);
return;
}
- $replyto = ((x($_REQUEST,'replyto')) ? notags(trim($_REQUEST['replyto'])) : '');
- $subject = ((x($_REQUEST,'subject')) ? notags(trim($_REQUEST['subject'])) : '');
- $body = ((x($_REQUEST,'body')) ? escape_tags(trim($_REQUEST['body'])) : '');
- $recipient = ((x($_REQUEST,'messageto')) ? intval($_REQUEST['messageto']) : 0 );
+ $replyto = x($_REQUEST, 'replyto') ? notags(trim($_REQUEST['replyto'])) : '';
+ $subject = x($_REQUEST, 'subject') ? notags(trim($_REQUEST['subject'])) : '';
+ $body = x($_REQUEST, 'body') ? escape_tags(trim($_REQUEST['body'])) : '';
+ $recipient = x($_REQUEST, 'messageto') ? intval($_REQUEST['messageto']) : 0;
$ret = send_message($recipient, $body, $subject, $replyto);
$norecip = false;
- switch($ret){
+ switch ($ret) {
case -1:
- notice( t('No recipient selected.') . EOL );
+ notice(t('No recipient selected.') . EOL);
$norecip = true;
break;
case -2:
- notice( t('Unable to locate contact information.') . EOL );
+ notice(t('Unable to locate contact information.') . EOL);
break;
case -3:
- notice( t('Message could not be sent.') . EOL );
+ notice(t('Message could not be sent.') . EOL);
break;
case -4:
- notice( t('Message collection failure.') . EOL );
+ notice(t('Message collection failure.') . EOL);
break;
default:
- info( t('Message sent.') . EOL );
+ info(t('Message sent.') . EOL);
}
// fake it to go back to the input form if no recipient listed
-
if ($norecip) {
$a->argc = 2;
$a->argv[1] = 'new';
- } else
+ } else {
goaway($_SESSION['return_url']);
-
+ }
}
-function message_content(App $a) {
-
+function message_content(App $a)
+{
$o = '';
nav_set_selected('messages');
- if (! local_user()) {
- notice( t('Permission denied.') . EOL);
+ if (!local_user()) {
+ notice(t('Permission denied.') . EOL);
return;
}
- $myprofile = System::baseUrl().'/profile/' . $a->user['nickname'];
+ $myprofile = System::baseUrl() . '/profile/' . $a->user['nickname'];
$tpl = get_markup_template('mail_head.tpl');
$header = replace_macros($tpl, array(
'$messages' => t('Messages'),
- '$tab_content' => $tab_content
));
-
if (($a->argc == 3) && ($a->argv[1] === 'drop' || $a->argv[1] === 'dropconv')) {
- if (! intval($a->argv[2]))
+ if (!intval($a->argv[2])) {
return;
+ }
// Check if we should do HTML-based delete confirmation
if ($_REQUEST['confirm']) {
// so add any arguments as hidden inputs
$query = explode_querystring($a->query_string);
$inputs = array();
- foreach($query['args'] as $arg) {
+ foreach ($query['args'] as $arg) {
if (strpos($arg, 'confirm=') === false) {
$arg_parts = explode('=', $arg);
$inputs[] = array('name' => $arg_parts[0], 'value' => $arg_parts[1]);
intval(local_user())
);
if ($r) {
- info( t('Message deleted.') . EOL );
+ info(t('Message deleted.') . EOL);
}
//goaway(System::baseUrl(true) . '/message' );
goaway($_SESSION['return_url']);
// Actually if we do this, we can never receive another reply to that conversation,
// as we will never again have the info we need to re-create it.
// We'll just have to orphan it.
-
//if ($convid) {
// q("delete from conv where id = %d limit 1",
// intval($convid)
// );
//}
- if ($r)
- info( t('Conversation removed.') . EOL );
+ if ($r) {
+ info(t('Conversation removed.') . EOL);
+ }
}
//goaway(System::baseUrl(true) . '/message' );
goaway($_SESSION['return_url']);
}
-
}
if (($a->argc > 1) && ($a->argv[1] === 'new')) {
-
$o .= $header;
$tpl = get_markup_template('msg-header.tpl');
'$linkurl' => t('Please enter a link URL:')
));
- $preselect = (isset($a->argv[2])?array($a->argv[2]):false);
-
+ $preselect = isset($a->argv[2]) ? array($a->argv[2]) : false;
$prename = $preurl = $preid = '';
$preurl = $r[0]['url'];
$preid = $r[0]['id'];
$preselect = array($preid);
- } else
+ } else {
$preselect = false;
+ }
}
- $prefill = (($preselect) ? $prename : '');
+ $prefill = $preselect ? $prename : '';
// the ugly select box
-
- $select = contact_select('messageto','message-to-select', $preselect, 4, true, false, false, 10);
+ $select = contact_select('messageto', 'message-to-select', $preselect, 4, true, false, false, 10);
$tpl = get_markup_template('prv_message.tpl');
- $o .= replace_macros($tpl,array(
+ $o .= replace_macros($tpl, array(
'$header' => t('Send Private Message'),
'$to' => t('To:'),
'$showinputs' => 'true',
'$autocomp' => $autocomp,
'$preid' => $preid,
'$subject' => t('Subject:'),
- '$subjtxt' => ((x($_REQUEST,'subject')) ? strip_tags($_REQUEST['subject']) : ''),
- '$text' => ((x($_REQUEST,'body')) ? escape_tags(htmlspecialchars($_REQUEST['body'])) : ''),
+ '$subjtxt' => x($_REQUEST, 'subject') ? strip_tags($_REQUEST['subject']) : '',
+ '$text' => x($_REQUEST, 'body') ? escape_tags(htmlspecialchars($_REQUEST['body'])) : '',
'$readonly' => '',
'$yourmessage' => t('Your message:'),
'$select' => $select,
$r = get_messages(local_user(), $a->pager['start'], $a->pager['itemspage']);
- if (! DBM::is_result($r)) {
- info( t('No messages.') . EOL);
+ if (!DBM::is_result($r)) {
+ info(t('No messages.') . EOL);
return $o;
}
intval(local_user())
);
}
- if (! count($messages)) {
- notice( t('Message not available.') . EOL );
+ if (!count($messages)) {
+ notice(t('Message not available.') . EOL);
return $o;
}
$seen = 0;
$unknown = false;
- foreach($messages as $message) {
+ foreach ($messages as $message) {
if ($message['unknown'])
$unknown = true;
if ($message['from-url'] == $myprofile) {
$from_url = $myprofile;
$sparkle = '';
} elseif ($message['contact-id'] != 0) {
- $from_url = 'redir/'.$message['contact-id'];
+ $from_url = 'redir/' . $message['contact-id'];
$sparkle = ' sparkle';
} else {
- $from_url = $message['from-url']."?zrl=".urlencode($myprofile);
+ $from_url = $message['from-url'] . "?zrl=" . urlencode($myprofile);
$sparkle = ' sparkle';
}
-
$extracted = item_extract_images($message['body']);
- if ($extracted['images'])
+ if ($extracted['images']) {
$message['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $message['contact-id']);
+ }
$from_name_e = $message['from-name'];
$subject_e = $message['title'];
$to_name_e = $message['name'];
$contact = Contact::getDetailsByURL($message['from-url']);
- if (isset($contact["thumb"]))
+ if (isset($contact["thumb"])) {
$from_photo = $contact["thumb"];
- else
+ } else {
$from_photo = $message['from-photo'];
+ }
$mails[] = array(
'id' => $message['id'],
'body' => $body_e,
'delete' => t('Delete message'),
'to_name' => $to_name_e,
- 'date' => datetime_convert('UTC',date_default_timezone_get(),$message['created'],'D, d M Y - g:i A'),
- 'ago' => relative_date($message['created']),
+ 'date' => datetime_convert('UTC', date_default_timezone_get(), $message['created'], 'D, d M Y - g:i A'),
+ 'ago' => relative_date($message['created']),
);
$seen = $message['seen'];
}
-
$select = $message['name'] . '<input type="hidden" name="messageto" value="' . $contact_id . '" />';
$parent = '<input type="hidden" name="replyto" value="' . $message['parent-uri'] . '" />';
$tpl = get_markup_template('mail_display.tpl');
-
- $subjtxt_e = $message['title'];
-
$o = replace_macros($tpl, array(
'$thread_id' => $a->argv[1],
'$thread_subject' => $message['title'],
'$thread_seen' => $seen,
- '$delete' => t('Delete conversation'),
+ '$delete' => t('Delete conversation'),
'$canreply' => (($unknown) ? false : '1'),
'$unknown_text' => t("No secure communications available. You <strong>may</strong> be able to respond from the sender's profile page."),
'$mails' => $mails,
'$to' => t('To:'),
'$showinputs' => '',
'$subject' => t('Subject:'),
- '$subjtxt' => $subjtxt_e,
+ '$subjtxt' => $message['title'],
'$readonly' => ' readonly="readonly" style="background: #BBBBBB;" ',
'$yourmessage' => t('Your message:'),
'$text' => '',
'$insert' => t('Insert web link'),
'$submit' => t('Submit'),
'$wait' => t('Please wait')
-
));
return $o;
}
}
-function get_messages($user, $lstart, $lend) {
+function get_messages($user, $lstart, $lend)
+{
//TODO: rewritte with a sub-query to get the first message of each private thread with certainty
return q("SELECT max(`mail`.`created`) AS `mailcreated`, min(`mail`.`seen`) AS `mailseen`,
ANY_VALUE(`mail`.`id`) AS `id`, ANY_VALUE(`mail`.`uid`) AS `uid`, ANY_VALUE(`mail`.`guid`) AS `guid`,
);
}
-function render_messages(array $msg, $t) {
-
+function render_messages(array $msg, $t)
+{
$a = get_app();
$tpl = get_markup_template($t);
$rslt = '';
- $myprofile = System::baseUrl().'/profile/' . $a->user['nickname'];
-
- foreach($msg as $rr) {
+ $myprofile = System::baseUrl() . '/profile/' . $a->user['nickname'];
- if ($rr['unknown'])
- $participants = sprintf( t("Unknown sender - %s"),$rr['from-name']);
- elseif (link_compare($rr['from-url'], $myprofile))
- $participants = sprintf( t("You and %s"), $rr['name']);
- else
- $participants = sprintf(t("%s and You"), $rr['from-name']);
+ foreach ($msg as $rr) {
+ if ($rr['unknown']) {
+ $participants = t("Unknown sender - %s", $rr['from-name']);
+ } elseif (link_compare($rr['from-url'], $myprofile)) {
+ $participants = t("You and %s", $rr['name']);
+ } else {
+ $participants = t("%s and You", $rr['from-name']);
+ }
$subject_e = (($rr['mailseen']) ? $rr['title'] : '<strong>' . $rr['title'] . '</strong>');
$body_e = $rr['body'];
$to_name_e = $rr['name'];
$contact = Contact::getDetailsByURL($rr['url']);
- if (isset($contact["thumb"]))
+ if (isset($contact["thumb"])) {
$from_photo = $contact["thumb"];
- else
+ } else {
$from_photo = (($rr['thumb']) ? $rr['thumb'] : $rr['from-photo']);
+ }
$rslt .= replace_macros($tpl, array(
'$id' => $rr['id'],
'$delete' => t('Delete conversation'),
'$body' => $body_e,
'$to_name' => $to_name_e,
- '$date' => datetime_convert('UTC',date_default_timezone_get(),$rr['mailcreated'], t('D, d M Y - g:i A')),
- '$ago' => relative_date($rr['mailcreated']),
+ '$date' => datetime_convert('UTC', date_default_timezone_get(), $rr['mailcreated'], t('D, d M Y - g:i A')),
+ '$ago' => relative_date($rr['mailcreated']),
'$seen' => $rr['mailseen'],
- '$count' => sprintf( tt('%d message', '%d messages', $rr['count']), $rr['count']),
+ '$count' => tt('%d message', '%d messages', $rr['count']),
));
}
// Set this so that the conversation function can find out contact info for our wall-wall items
$a->page_contact = $a->contact;
- $o .= conversation($a, $items, $mode, $update);
+ $o = conversation($a, $items, $mode, $update);
if (!$update) {
if (PConfig::get(local_user(), 'system', 'infinite_scroll')) {
if ($group) {
if (($t = Contact::getOStatusCountByGroupId($group)) && !PConfig::get(local_user(), 'system', 'nowarn_insecure')) {
- notice(sprintf(tt("Warning: This group contains %s member from a network that doesn't allow non public messages.",
+ notice(tt("Warning: This group contains %s member from a network that doesn't allow non public messages.",
"Warning: This group contains %s members from a network that doesn't allow non public messages.",
- $t), $t).EOL);
+ $t) . EOL);
notice(t("Messages in this group won't be send to these receivers.").EOL);
}
}
}
$o = replace_macros(get_markup_template("section_title.tpl"),array(
- '$title' => sprintf(t('Group: %s'), $r['name'])
+ '$title' => t('Group: %s', $r['name'])
)) . $o;
} elseif ($cid) {
$sql_order = "";
$order_mode = "received";
- if (strlen($file)) {
- $sql_post_table .= sprintf("INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
- dbesc(protect_sprintf($file)), intval(TERM_OBJ_POST), intval(TERM_FILE), intval(local_user()));
- $sql_order = "`item`.`id`";
- $order_mode = "id";
- }
-
if ($conv) {
$sql_extra3 .= " AND $sql_table.`mention`";
}
$sql_order = "$sql_table.$ordering";
}
- if (($_GET["offset"] != "")) {
+ if (x($_GET, 'offset')) {
$sql_extra3 .= sprintf(" AND $sql_order <= '%s'", dbesc($_GET["offset"]));
}
$parents_str = '';
$date_offset = "";
+ $items = array();
if (DBM::is_result($r)) {
foreach ($r as $rr) {
- if (!in_array($rr['item_id'],$parents_arr)) {
+ if (!in_array($rr['item_id'], $parents_arr)) {
$parents_arr[] = $rr['item_id'];
}
}
$max_comments = 100;
}
- $items = array();
-
foreach ($parents_arr AS $parents) {
- $thread_items = dba::p(item_query()." AND `item`.`uid` = ?
+ $thread_items = dba::p(item_query() . " AND `item`.`uid` = ?
AND `item`.`parent` = ?
- ORDER BY `item`.`commented` DESC LIMIT ".intval($max_comments + 1),
+ ORDER BY `item`.`commented` DESC LIMIT " . intval($max_comments + 1),
local_user(),
$parents
);
$items = array_merge($items, dba::inArray($thread_items));
}
}
- $items = conv_sort($items,$ordering);
- } else {
- $items = array();
+ $items = conv_sort($items, $ordering);
}
- if ($_GET["offset"] == "") {
+ if (x($_GET, 'offset')) {
+ $date_offset = $_GET["offset"];
+ } elseif(count($items)) {
$date_offset = $items[0][$order_mode];
} else {
- $date_offset = $_GET["offset"];
+ $date_offset = '';
}
$a->page_offset = $date_offset;
$contact_details = Contact::getDetailsByURL($rr['url'], local_user(), $rr);
$contacts[] = array(
- 'img_hover' => sprintf(t('Visit %s\'s profile [%s]'), $contact_details['name'], $rr['url']),
+ 'img_hover' => t('Visit %s\'s profile [%s]', $contact_details['name'], $rr['url']),
'edit_hover' => t('Edit contact'),
'photo_menu' => Contact::photoMenu($rr),
'id' => $rr['id'],
- 'alt_text' => $alt_text,
- 'dir_icon' => $dir_icon,
'thumb' => proxy_url($contact_details['thumb'], false, PROXY_SIZE_THUMB),
'name' => $contact_details['name'],
'username' => $contact_details['name'],
'details' => $contact_details['location'],
'tags' => $contact_details['keywords'],
'about' => $contact_details['about'],
- 'sparkle' => $sparkle,
'itemurl' => (($contact_details['addr'] != "") ? $contact_details['addr'] : $rr['url']),
'url' => $rr['url'],
- 'network' => network_to_name($rr['network'], $url),
+ 'network' => network_to_name($rr['network'], $rr['url']),
);
}
}
$tpl = get_markup_template("nogroup-template.tpl");
- $o .= replace_macros(
+ $o = replace_macros(
$tpl,
array(
'$header' => t('Contacts who are not members of a group'),
+++ /dev/null
-<?php
-
-use Friendica\App;
-
-require_once("include/oembed.php");
-
-function oembed_content(App $a) {
- // logger('mod_oembed ' . $a->query_string, LOGGER_ALL);
-
- if ($a->argv[1]=='b2h'){
- $url = array( "", trim(hex2bin($_REQUEST['url'])));
- echo oembed_replacecb($url);
- killme();
- }
-
- if ($a->argv[1]=='h2b'){
- $text = trim(hex2bin($_REQUEST['text']));
- echo oembed_html2bbcode($text);
- killme();
- }
-
- if ($a->argc == 2){
- echo "<html><body>";
- $url = base64url_decode($a->argv[1]);
- $j = oembed_fetch_url($url);
-
- // workaround for media.ccc.de (and any other endpoint that return size 0)
- if (substr($j->html, 0, 7) == "<iframe" && strstr($j->html, 'width="0"')) {
- $j->html = '<style>html,body{margin:0;padding:0;} iframe{width:100%;height:100%;}</style>'. $j->html;
- $j->html = str_replace('width="0"', '', $j->html);
- $j->html = str_replace('height="0"', '', $j->html);
- }
- echo $j->html;
-// logger('mod-oembed ' . $j->html, LOGGER_ALL);
- echo "</body></html>";
- }
- killme();
-}
<?php
+
/**
* @file mod/photo.php
*/
require_once 'include/security.php';
-function photo_init(App $a) {
+function photo_init(App $a)
+{
global $_SERVER;
$prvcachecontrol = false;
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
header('HTTP/1.1 304 Not Modified');
header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
- header('Etag: '.$_SERVER['HTTP_IF_NONE_MATCH']);
- header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
+ header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
+ header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
header("Cache-Control: max-age=31536000");
if (function_exists('header_remove')) {
header_remove('Last-Modified');
}
$default = 'images/person-175.jpg';
+ $public = true;
if (isset($type)) {
-
- /**
- * Profile photos
- */
-
+ // Profile photos
switch ($type) {
-
case 'profile':
case 'custom':
$resolution = 4;
$uid = str_replace(array('.jpg', '.png', '.gif'), array('', '', ''), $person);
foreach (Image::supportedTypes() AS $m => $e) {
- $uid = str_replace('.'.$e, '', $uid);
+ $uid = str_replace('.' . $e, '', $uid);
}
$r = q("SELECT * FROM `photo` WHERE `scale` = %d AND `uid` = %d AND `profile` = 1 LIMIT 1",
$mimetype = 'image/jpeg';
}
} else {
-
- /**
- * Other photos
- */
-
+ // Other photos
$resolution = 0;
$photo = str_replace(array('.jpg', '.png', '.gif'), array('', '', ''), $photo);
foreach (Image::supportedTypes() AS $m => $e) {
- $photo = str_replace('.'.$e, '', $photo);
+ $photo = str_replace('.' . $e, '', $photo);
}
if (substr($photo, -2, 1) == '-') {
intval($resolution)
);
if (DBM::is_result($r)) {
-
$sql_extra = permissions_sql($r[0]['uid']);
// Now we'll see if we can access the photo
-
$r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` <= %d $sql_extra ORDER BY scale DESC LIMIT 1",
dbesc($photo),
intval($resolution)
);
-
- $public = (DBM::is_result($r)) && ($r[0]['allow_cid'] == '') && ($r[0]['allow_gid'] == '') && ($r[0]['deny_cid'] == '') && ($r[0]['deny_gid'] == '');
-
if (DBM::is_result($r)) {
$resolution = $r[0]['scale'];
$data = $r[0]['data'];
$mimetype = $r[0]['type'];
+ $public = $r[0]['allow_cid'] == '' && $r[0]['allow_gid'] == '' && $r[0]['deny_cid'] == '' && $r[0]['deny_gid'] == '';
} else {
// The picure exists. We already checked with the first query.
// obviously, this is not an authorized viev!
if (empty($data)) {
if (isset($resolution)) {
switch ($resolution) {
-
case 4:
$data = file_get_contents('images/person-175.jpg');
$mimetype = 'image/jpeg';
}
// Resize only if its not a GIF and it is supported by the library
- if (($mimetype != "image/gif") && in_array($mimetype, Image::supportedTypes())) {
+ if ($mimetype != "image/gif" && in_array($mimetype, Image::supportedTypes())) {
$Image = new Image($data, $mimetype);
if ($Image->isValid()) {
if (isset($customres) && $customres > 0 && $customres < 500) {
header_remove('pragma');
}
- header("Content-type: ".$mimetype);
+ header("Content-type: " . $mimetype);
if ($prvcachecontrol) {
-
// it is a private photo that they have no permission to view.
// tell the browser not to cache it, in case they authenticate
// and subsequently have permission to see it
-
header("Cache-Control: no-store, no-cache, must-revalidate");
-
} else {
header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
- header('Etag: "'.md5($data).'"');
- header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
+ header('Etag: "' . md5($data) . '"');
+ header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
header("Cache-Control: max-age=31536000");
}
echo $data;
// If the photo is public and there is an existing photo directory store the photo there
- if ($public and ($file != "")) {
+ if ($public and $file != '') {
// If the photo path isn't there, try to create it
$basepath = $a->get_basepath();
- if (!is_dir($basepath."/photo")) {
+ if (!is_dir($basepath . "/photo")) {
if (is_writable($basepath)) {
- mkdir($basepath."/photo");
+ mkdir($basepath . "/photo");
}
}
- if (is_dir($basepath."/photo")) {
- file_put_contents($basepath."/photo/".$file, $data);
+ if (is_dir($basepath . "/photo")) {
+ file_put_contents($basepath . "/photo/" . $file, $data);
}
}
auto_redir($a, $a->argv[1]);
}
- if ((Config::get('system', 'block_public')) && (! local_user()) && (! remote_user())) {
+ if (Config::get('system', 'block_public') && !local_user() && !remote_user()) {
return;
}
dbesc($nick)
);
- if (! DBM::is_result($user)) {
+ if (!DBM::is_result($user)) {
return;
}
$tpl = get_markup_template("vcard-widget.tpl");
- $vcard_widget .= replace_macros($tpl, array(
+ $vcard_widget = replace_macros($tpl, array(
'$name' => $profile['name'],
'$photo' => $profile['photo'],
- '$addr' => (($profile['addr'] != "") ? $profile['addr'] : ""),
+ '$addr' => defaults($profile, 'addr', ''),
'$account_type' => $account_type,
- '$pdesc' => (($profile['pdesc'] != "") ? $profile['pdesc'] : ""),
+ '$pdesc' => defaults($profile, 'pdesc', ''),
));
$albums = photo_albums($a->data['user']['uid']);
- $albums_visible = ((intval($a->data['user']['hidewall']) && (! local_user()) && (! remote_user())) ? false : true);
+ $albums_visible = ((intval($a->data['user']['hidewall']) && !local_user() && !remote_user()) ? false : true);
// add various encodings to the array so we can just loop through and pick them out in a template
$ret = array('success' => false);
$ret['albums'] = array();
foreach ($albums as $k => $album) {
//hide profile photos to others
- if ((! $is_owner) && (! remote_user()) && ($album['album'] == t('Profile Photos')))
+ if (!$is_owner && !remote_user() && ($album['album'] == t('Profile Photos')))
continue;
$entry = array(
'text' => $album['album'],
}
}
- $albums = $ret;
-
if (local_user() && $a->data['user']['uid'] == local_user()) {
$can_post = true;
}
- if ($albums['success']) {
+ if ($ret['success']) {
$photo_albums_widget = replace_macros(get_markup_template('photo_albums.tpl'), array(
'$nick' => $a->data['user']['nickname'],
'$title' => t('Photo Albums'),
'$recent' => t('Recent Photos'),
- '$albums' => $albums['albums'],
+ '$albums' => $ret['albums'],
'$baseurl' => System::baseUrl(),
'$upload' => array(t('Upload New Photos'), 'photos/' . $a->data['user']['nickname'] . '/upload'),
'$can_post' => $can_post
}
- if (! x($a->page, 'aside')) {
+ if (!x($a->page, 'aside')) {
$a->page['aside'] = '';
}
$a->page['aside'] .= $vcard_widget;
$a->page['aside'] .= $photo_albums_widget;
-
$tpl = get_markup_template("photos_head.tpl");
$a->page['htmlhead'] .= replace_macros($tpl,array(
'$ispublic' => t('everybody')
));
-
}
return;
}
-
-
-function photos_post(App $a) {
-
+function photos_post(App $a)
+{
logger('mod-photos: photos_post: begin' , LOGGER_DEBUG);
-
-
- logger('mod_photos: REQUEST ' . print_r($_REQUEST,true), LOGGER_DATA);
- logger('mod_photos: FILES ' . print_r($_FILES,true), LOGGER_DATA);
+ logger('mod_photos: REQUEST ' . print_r($_REQUEST, true), LOGGER_DATA);
+ logger('mod_photos: FILES ' . print_r($_FILES, true), LOGGER_DATA);
$phototypes = Image::supportedTypes();
$visitor = 0;
$page_owner_uid = $a->data['user']['uid'];
- $community_page = (($a->data['user']['page-flags'] == PAGE_COMMUNITY) ? true : false);
+ $community_page = $a->data['user']['page-flags'] == PAGE_COMMUNITY;
- if ((local_user()) && (local_user() == $page_owner_uid)) {
+ if (local_user() && (local_user() == $page_owner_uid)) {
$can_post = true;
} else {
if ($community_page && remote_user()) {
$contact_id = 0;
- if (is_array($_SESSION['remote'])) {
+ if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
foreach ($_SESSION['remote'] as $v) {
if ($v['uid'] == $page_owner_uid) {
$contact_id = $v['cid'];
}
}
if ($contact_id) {
-
$r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
intval($contact_id),
intval($page_owner_uid)
}
}
- if (! $can_post) {
+ if (!$can_post) {
notice( t('Permission denied.') . EOL );
killme();
}
intval($page_owner_uid)
);
- if (! DBM::is_result($r)) {
+ if (!DBM::is_result($r)) {
notice( t('Contact information unavailable') . EOL);
logger('photos_post: unable to locate contact record for page owner. uid=' . $page_owner_uid);
killme();
$owner_record = $r[0];
-
- if (($a->argc > 3) && ($a->argv[2] === 'album')) {
+ if ($a->argc > 3 && $a->argv[2] === 'album') {
$album = hex2bin($a->argv[3]);
if ($album === t('Profile Photos') || $album === 'Contact Photos' || $album === t('Contact Photos')) {
goaway($_SESSION['photo_return']);
}
- /*
- * RENAME photo album
- */
-
+ // RENAME photo album
$newalbum = notags(trim($_POST['albumname']));
if ($newalbum != $album) {
q("UPDATE `photo` SET `album` = '%s' WHERE `album` = '%s' AND `uid` = %d",
// Update the photo albums cache
photo_albums($page_owner_uid, true);
- $newurl = str_replace(bin2hex($album),bin2hex($newalbum),$_SESSION['photo_return']);
+ $newurl = str_replace(bin2hex($album), bin2hex($newalbum), $_SESSION['photo_return']);
goaway($newurl);
return; // NOTREACHED
}
*/
if ($_POST['dropalbum'] == t('Delete Album')) {
-
// Check if we should do HTML-based delete confirmation
- if ($_REQUEST['confirm']) {
+ if (x($_REQUEST, 'confirm')) {
$drop_url = $a->query_string;
$extra_inputs = array(
array('name' => 'albumname', 'value' => $_POST['albumname']),
$str_res = implode(',', $res);
// remove the associated photos
-
q("DELETE FROM `photo` WHERE `resource-id` IN ( $str_res ) AND `uid` = %d",
intval($page_owner_uid)
);
// find and delete the corresponding item with all the comments and likes/dislikes
-
- $r = q("SELECT `parent-uri` FROM `item` WHERE `resource-id` IN ( $str_res ) AND `uid` = %d",
+ $r = q("SELECT `id`, `parent-uri`, `visible` FROM `item` WHERE `resource-id` IN ( $str_res ) AND `uid` = %d",
intval($page_owner_uid)
);
if (DBM::is_result($r)) {
$drop_id = intval($rr['id']);
// send the notification upstream/downstream as the case may be
-
if ($rr['visible']) {
Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
}
// Check if the user has responded to a delete confirmation query for a single photo
- if (($a->argc > 2) && $_REQUEST['canceled']) {
+ if ($a->argc > 2 && x($_REQUEST, 'canceled')) {
goaway($_SESSION['photo_return']);
}
- if (($a->argc > 2) && (x($_POST,'delete')) && ($_POST['delete'] == t('Delete Photo'))) {
+ if ($a->argc > 2 && defaults($_POST, 'delete', '') === t('Delete Photo')) {
// same as above but remove single photo
// Check if we should do HTML-based delete confirmation
- if ($_REQUEST['confirm']) {
+ if (x($_REQUEST, 'confirm')) {
$drop_url = $a->query_string;
$a->page['content'] = replace_macros(get_markup_template('confirm.tpl'), array(
'$method' => 'post',
intval($page_owner_uid),
dbesc($r[0]['resource-id'])
);
- $i = q("SELECT * FROM `item` WHERE `resource-id` = '%s' AND `uid` = %d LIMIT 1",
+ $i = q("SELECT `id`, `uri`, `visible` FROM `item` WHERE `resource-id` = '%s' AND `uid` = %d LIMIT 1",
dbesc($r[0]['resource-id']),
intval($page_owner_uid)
);
return; // NOTREACHED
}
- if (($a->argc > 2) && ((x($_POST,'desc') !== false) || (x($_POST,'newtag') !== false)) || (x($_POST,'albname') !== false)) {
-
- $desc = ((x($_POST,'desc')) ? notags(trim($_POST['desc'])) : '');
- $rawtags = ((x($_POST,'newtag')) ? notags(trim($_POST['newtag'])) : '');
- $item_id = ((x($_POST,'item_id')) ? intval($_POST['item_id']) : 0);
- $albname = ((x($_POST,'albname')) ? notags(trim($_POST['albname'])) : '');
- $origaname = ((x($_POST,'origaname')) ? notags(trim($_POST['origaname'])) : '');
+ if ($a->argc > 2 && (x($_POST, 'desc') !== false || x($_POST, 'newtag') !== false || x($_POST, 'albname') !== false)) {
+ $desc = x($_POST, 'desc') ? notags(trim($_POST['desc'])) : '';
+ $rawtags = x($_POST, 'newtag') ? notags(trim($_POST['newtag'])) : '';
+ $item_id = x($_POST, 'item_id') ? intval($_POST['item_id']) : 0;
+ $albname = x($_POST, 'albname') ? notags(trim($_POST['albname'])) : '';
+ $origaname = x($_POST, 'origaname') ? notags(trim($_POST['origaname'])) : '';
$str_group_allow = perms2str($_POST['group_allow']);
$str_contact_allow = perms2str($_POST['contact_allow']);
$str_group_deny = perms2str($_POST['group_deny']);
$resource_id = $a->argv[2];
- if (! strlen($albname)) {
+ if (!strlen($albname)) {
$albname = datetime_convert('UTC',date_default_timezone_get(),'now', 'Y');
}
-
- if ((x($_POST,'rotate') !== false) &&
- ( (intval($_POST['rotate']) == 1) || (intval($_POST['rotate']) == 2) )) {
+ if (x($_POST,'rotate') !== false &&
+ (intval($_POST['rotate']) == 1 || intval($_POST['rotate']) == 2)) {
logger('rotate');
$r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d AND `scale` = 0 LIMIT 1",
$visibility = 1;
}
- if (! $item_id) {
-
+ if (!$item_id) {
// Create item container
-
$title = '';
$uri = item_new_uri($a->get_hostname(),$page_owner_uid);
. '[/url]';
$item_id = item_store($arr);
-
}
if ($item_id) {
}
if (strlen($rawtags)) {
-
$str_tags = '';
$inform = '';
// if the new tag doesn't have a namespace specifier (@foo or #foo) give it a hashtag
-
- $x = substr($rawtags,0,1);
+ $x = substr($rawtags, 0, 1);
if ($x !== '@' && $x !== '#') {
$rawtags = '#' . $rawtags;
}
if (count($tags)) {
foreach ($tags as $tag) {
- if (isset($profile)) {
- unset($profile);
- }
if (strpos($tag, '@') === 0) {
+ $profile = '';
$name = substr($tag,1);
if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
$newname = $name;
intval($page_owner_uid)
);
- if (! DBM::is_result($r)) {
+ if (!DBM::is_result($r)) {
//select someone by attag or nick and the name passed in
$r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
dbesc($name),
if (count($taginfo)) {
foreach ($taginfo as $tagged) {
-
- $uri = item_new_uri($a->get_hostname(),$page_owner_uid);
+ $uri = item_new_uri($a->get_hostname(), $page_owner_uid);
$arr = array();
$arr['guid'] = get_guid(32);
}
- /**
- * default post action - upload a photo
- */
-
+ // default post action - upload a photo
call_hooks('photo_post_init', $_POST);
- /**
- * Determine the album to use
- */
-
- $album = notags(trim($_REQUEST['album']));
- $newalbum = notags(trim($_REQUEST['newalbum']));
+ // Determine the album to use
+ $album = x($_REQUEST, 'album') ? notags(trim($_REQUEST['album'])) : '';
+ $newalbum = x($_REQUEST, 'newalbum') ? notags(trim($_REQUEST['newalbum'])) : '';
logger('mod/photos.php: photos_post(): album= ' . $album . ' newalbum= ' . $newalbum , LOGGER_DEBUG);
- if (! strlen($album)) {
+ if (!strlen($album)) {
if (strlen($newalbum)) {
$album = $newalbum;
} else {
dbesc($album),
intval($page_owner_uid)
);
- if ((! DBM::is_result($r)) || ($album == t('Profile Photos'))) {
+ if (!DBM::is_result($r) || ($album == t('Profile Photos'))) {
$visible = 1;
} else {
$visible = 0;
}
- if (intval($_REQUEST['not_visible']) || $_REQUEST['not_visible'] === 'true') {
+ if (x($_REQUEST, 'not_visible') && $_REQUEST['not_visible'] !== 'false') {
$visible = 0;
}
- $str_group_allow = perms2str(((is_array($_REQUEST['group_allow'])) ? $_REQUEST['group_allow'] : explode(',', $_REQUEST['group_allow'])));
- $str_contact_allow = perms2str(((is_array($_REQUEST['contact_allow'])) ? $_REQUEST['contact_allow'] : explode(',', $_REQUEST['contact_allow'])));
- $str_group_deny = perms2str(((is_array($_REQUEST['group_deny'])) ? $_REQUEST['group_deny'] : explode(',', $_REQUEST['group_deny'])));
- $str_contact_deny = perms2str(((is_array($_REQUEST['contact_deny'])) ? $_REQUEST['contact_deny'] : explode(',', $_REQUEST['contact_deny'])));
+ $group_allow = defaults($_REQUEST, 'group_allow' , []);
+ $contact_allow = defaults($_REQUEST, 'contact_allow', []);
+ $group_deny = defaults($_REQUEST, 'group_deny' , []);
+ $contact_deny = defaults($_REQUEST, 'contact_deny' , []);
+
+ $str_group_allow = perms2str(is_array($group_allow) ? $group_allow : explode(',', $group_allow));
+ $str_contact_allow = perms2str(is_array($contact_allow) ? $contact_allow : explode(',', $contact_allow));
+ $str_group_deny = perms2str(is_array($group_deny) ? $group_deny : explode(',', $group_deny));
+ $str_contact_deny = perms2str(is_array($contact_deny) ? $contact_deny : explode(',', $contact_deny));
$ret = array('src' => '', 'filename' => '', 'filesize' => 0, 'type' => '');
- call_hooks('photo_post_file',$ret);
+ call_hooks('photo_post_file', $ret);
- if (x($ret,'src') && x($ret,'filesize')) {
+ if (x($ret, 'src') && x($ret, 'filesize')) {
$src = $ret['src'];
$filename = $ret['filename'];
$filesize = $ret['filesize'];
$type = $ret['type'];
+ $error = UPLOAD_ERR_OK;
} else {
- $src = $_FILES['userfile']['tmp_name'];
- $filename = basename($_FILES['userfile']['name']);
- $filesize = intval($_FILES['userfile']['size']);
- $type = $_FILES['userfile']['type'];
+ $src = $_FILES['userfile']['tmp_name'];
+ $filename = basename($_FILES['userfile']['name']);
+ $filesize = intval($_FILES['userfile']['size']);
+ $type = $_FILES['userfile']['type'];
+ $error = $_FILES['userfile']['error'];
+ }
+
+ if ($error !== UPLOAD_ERR_OK) {
+ switch ($error) {
+ case UPLOAD_ERR_INI_SIZE:
+ notice(t('Image exceeds size limit of %s', ini_get('upload_max_filesize')) . EOL);
+ break;
+ case UPLOAD_ERR_FORM_SIZE:
+ notice(t('Image exceeds size limit of %s', formatBytes(defaults($_REQUEST, 'MAX_FILE_SIZE', 0))) . EOL);
+ break;
+ case UPLOAD_ERR_PARTIAL:
+ notice(t('Image upload didn\'t complete, please try again') . EOL);
+ break;
+ case UPLOAD_ERR_NO_FILE:
+ notice(t('Image file is missing') . EOL);
+ break;
+ case UPLOAD_ERR_NO_TMP_DIR:
+ case UPLOAD_ERR_CANT_WRITE:
+ case UPLOAD_ERR_EXTENSION:
+ notice(t('Server can\'t accept new file upload at this time, please contact your administrator') . EOL);
+ break;
+ }
+ @unlink($src);
+ $foo = 0;
+ call_hooks('photo_post_end', $foo);
+ return;
}
+
if ($type == "") {
$type = Image::guessType($filename);
}
logger('photos: upload: received file: ' . $filename . ' as ' . $src . ' ('. $type . ') ' . $filesize . ' bytes', LOGGER_DEBUG);
- $maximagesize = Config::get('system','maximagesize');
+ $maximagesize = Config::get('system', 'maximagesize');
- if (($maximagesize) && ($filesize > $maximagesize)) {
- notice( sprintf(t('Image exceeds size limit of %s'), formatBytes($maximagesize)) . EOL);
+ if ($maximagesize && ($filesize > $maximagesize)) {
+ notice(t('Image exceeds size limit of %s', formatBytes($maximagesize)) . EOL);
@unlink($src);
$foo = 0;
- call_hooks('photo_post_end',$foo);
+ call_hooks('photo_post_end', $foo);
return;
}
- if (! $filesize) {
- notice( t('Image file is empty.') . EOL);
+ if (!$filesize) {
+ notice(t('Image file is empty.') . EOL);
@unlink($src);
$foo = 0;
- call_hooks('photo_post_end',$foo);
+ call_hooks('photo_post_end', $foo);
return;
}
$Image = new Image($imagedata, $type);
- if (! $Image->isValid()) {
+ if (!$Image->isValid()) {
logger('mod/photos.php: photos_post(): unable to process image' , LOGGER_DEBUG);
- notice( t('Unable to process image.') . EOL );
+ notice(t('Unable to process image.') . EOL);
@unlink($src);
$foo = 0;
call_hooks('photo_post_end',$foo);
@unlink($src);
$max_length = Config::get('system', 'max_image_length');
- if (! $max_length) {
+ if (!$max_length) {
$max_length = MAX_IMAGE_LENGTH;
}
if ($max_length > 0) {
$r = Photo::store($Image, $page_owner_uid, $visitor, $photo_hash, $filename, $album, 0 , 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
- if (! $r) {
+ if (!$r) {
logger('mod/photos.php: photos_post(): image store failed' , LOGGER_DEBUG);
- notice( t('Image upload failed.') . EOL );
+ notice(t('Image upload failed.') . EOL);
killme();
}
$smallest = 2;
}
- $basename = basename($filename);
$uri = item_new_uri($a->get_hostname(), $page_owner_uid);
// Create item container
-
$lat = $lon = null;
-
- /// @TODO merge these 2 if() into one?
- if ($exif && $exif['GPS']) {
- if (Feature::isEnabled($channel_id,'photo_location')) {
- $lat = getGps($exif['GPS']['GPSLatitude'], $exif['GPS']['GPSLatitudeRef']);
- $lon = getGps($exif['GPS']['GPSLongitude'], $exif['GPS']['GPSLongitudeRef']);
- }
+ if ($exif && $exif['GPS'] && Feature::isEnabled($channel_id, 'photo_location')) {
+ $lat = getGps($exif['GPS']['GPSLatitude'], $exif['GPS']['GPSLatitudeRef']);
+ $lon = getGps($exif['GPS']['GPSLongitude'], $exif['GPS']['GPSLongitudeRef']);
}
$arr = array();
-
if ($lat && $lon) {
$arr['coord'] = $lat . ' ' . $lon;
}
call_hooks('photo_post_end',intval($item_id));
- /*
- * addon uploaders should call "killme()" [e.g. exit] within the photo_post_end hook
- * if they do not wish to be redirected
- */
+ // addon uploaders should call "killme()" [e.g. exit] within the photo_post_end hook
+ // if they do not wish to be redirected
goaway($_SESSION['photo_return']);
// NOTREACHED
}
-function photos_content(App $a) {
-
+function photos_content(App $a)
+{
// URLs:
// photos/name
// photos/name/upload
// photos/name/image/xxxxx
// photos/name/image/xxxxx/edit
-
- if ((Config::get('system', 'block_public')) && (! local_user()) && (! remote_user())) {
+ if (Config::get('system', 'block_public') && !local_user() && !remote_user()) {
notice( t('Public access denied.') . EOL);
return;
}
require_once 'include/security.php';
require_once 'include/conversation.php';
- if (! x($a->data,'user')) {
+ if (!x($a->data,'user')) {
notice( t('No photos selected') . EOL );
return;
}
$_SESSION['photo_return'] = $a->cmd;
- //
// Parse arguments
- //
-
+ $datum = null;
if ($a->argc > 3) {
$datatype = $a->argv[2];
$datum = $a->argv[3];
$cmd = 'view';
}
- //
// Setup permissions structures
- //
-
$can_post = false;
$visitor = 0;
$contact = null;
$community_page = (($a->data['user']['page-flags'] == PAGE_COMMUNITY) ? true : false);
- if ((local_user()) && (local_user() == $owner_uid)) {
+ if (local_user() && (local_user() == $owner_uid)) {
$can_post = true;
} else {
if ($community_page && remote_user()) {
}
}
- // perhaps they're visiting - but not a community page, so they wouldn't have write access
+ $groups = [];
- if (remote_user() && (! $visitor)) {
+ // perhaps they're visiting - but not a community page, so they wouldn't have write access
+ if (remote_user() && !$visitor) {
$contact_id = 0;
if (is_array($_SESSION['remote'])) {
foreach ($_SESSION['remote'] as $v) {
}
}
- /// @TODO merge these 2 if() into one?
- if (! $remote_contact) {
- if (local_user()) {
- $contact_id = $_SESSION['cid'];
- $contact = $a->contact;
- }
+ if (!$remote_contact && local_user()) {
+ $contact_id = $_SESSION['cid'];
+ $contact = $a->contact;
}
- if ($a->data['user']['hidewall'] && (local_user() != $owner_uid) && (! $remote_contact)) {
+ if ($a->data['user']['hidewall'] && (local_user() != $owner_uid) && !$remote_contact) {
notice( t('Access to this item is restricted.') . EOL);
return;
}
- $sql_extra = permissions_sql($owner_uid,$remote_contact,$groups);
+ $sql_extra = permissions_sql($owner_uid, $remote_contact, $groups);
$o = "";
$is_owner = (local_user() && (local_user() == $owner_uid));
$o .= profile_tabs($a, $is_owner, $a->data['user']['nickname']);
- /**
- * Display upload form
- */
-
+ // Display upload form
if ($datatype === 'upload') {
- if (! ($can_post)) {
+ if (!$can_post) {
notice(t('Permission denied.'));
return;
}
-
- $selname = (($datum) ? hex2bin($datum) : '');
-
+ $selname = $datum ? hex2bin($datum) : '';
$albumselect = '';
-
- $albumselect .= '<option value="" ' . ((! $selname) ? ' selected="selected" ' : '') . '> </option>';
+ $albumselect .= '<option value="" ' . (!$selname ? ' selected="selected" ' : '') . '> </option>';
if (count($a->data['albums'])) {
foreach ($a->data['albums'] as $album) {
if (($album['album'] === '') || ($album['album'] === 'Contact Photos') || ($album['album'] === t('Contact Photos'))) {
$usage_message = '';
- // Private/public post links for the non-JS ACL form
- $private_post = 1;
- if ($_REQUEST['public']) {
- $private_post = 0;
- }
-
- $query_str = $a->query_string;
- if (strpos($query_str, 'public=1') !== false) {
- $query_str = str_replace(array('?public=1', '&public=1'), array('', ''), $query_str);
- }
-
- /*
- * I think $a->query_string may never have ? in it, but I could be wrong
- * It looks like it's from the index.php?q=[etc] rewrite that the web
- * server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
- */
- if (strpos($query_str, '?') === false) {
- $public_post_link = '?public=1';
- } else {
- $public_post_link = '&public=1';
- }
-
$tpl = get_markup_template('photos_upload.tpl');
- $albumselect_e = $albumselect;
- $aclselect_e = (($visitor) ? '' : populate_acl($a->user));
+ $aclselect_e = ($visitor ? '' : populate_acl($a->user));
$o .= replace_macros($tpl,array(
'$pagename' => t('Upload Photos'),
'$newalbum' => t('New album name: '),
'$existalbumtext' => t('or existing album name: '),
'$nosharetext' => t('Do not show a status post for this upload'),
- '$albumselect' => $albumselect_e,
+ '$albumselect' => $albumselect,
'$permissions' => t('Permissions'),
'$aclselect' => $aclselect_e,
'$alt_uploader' => $ret['addon_text'],
- '$default_upload_box' => (($ret['default_upload']) ? $default_upload_box : ''),
- '$default_upload_submit' => (($ret['default_upload']) ? $default_upload_submit : ''),
+ '$default_upload_box' => ($ret['default_upload'] ? $default_upload_box : ''),
+ '$default_upload_submit' => ($ret['default_upload'] ? $default_upload_submit : ''),
'$uploadurl' => $ret['post_url'],
// ACL permissions box
'$acl_data' => construct_acl_data($a, $a->user), // For non-Javascript ACL selector
'$group_perms' => t('Show to Groups'),
'$contact_perms' => t('Show to Contacts'),
- '$private' => t('Private Photo'),
- '$public' => t('Public Photo'),
- '$is_private' => $private_post,
- '$return_path' => $query_str,
- '$public_link' => $public_post_link,
-
+ '$return_path' => $a->query_string,
));
return $o;
}
- /*
- * Display a single photo album
- */
-
+ // Display a single photo album
if ($datatype === 'album') {
-
$album = hex2bin($datum);
$r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s'
}
/// @TODO I have seen this many times, maybe generalize it script-wide and encapsulate it?
- if ($_GET['order'] === 'posted') {
+ $order_field = defaults($_GET, 'order', '');
+ if ($order_field === 'posted') {
$order = 'ASC';
} else {
$order = 'DESC';
}
}
- if ($_GET['order'] === 'posted') {
+ if ($order_field === 'posted') {
$order = array(t('Show Newest First'), 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album));
} else {
$order = array(t('Show Oldest First'), 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '?f=&order=posted');
$photos = array();
- if (DBM::is_result($r))
- $twist = 'rotright';
+ if (DBM::is_result($r)) {
+ // "Twist" is only used for the duepunto theme with style "slackr"
+ $twist = false;
foreach ($r as $rr) {
- if ($twist == 'rotright') {
- $twist = 'rotleft';
- } else {
- $twist = 'rotright';
- }
+ $twist = !$twist;
$ext = $phototypes[$rr['type']];
$photos[] = array(
'id' => $rr['id'],
- 'twist' => ' ' . $twist . rand(2,4),
+ 'twist' => ' ' . ($twist ? 'rotleft' : 'rotright') . rand(2,4),
'link' => 'photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id']
- . (($_GET['order'] === 'posted') ? '?f=&order=posted' : ''),
+ . ($order_field === 'posted' ? '?f=&order=posted' : ''),
'title' => t('View Photo'),
'src' => 'photo/' . $rr['resource-id'] . '-' . $rr['scale'] . '.' .$ext,
'alt' => $imgalt_e,
'desc'=> $desc_e,
'ext' => $ext,
- 'hash'=> $rr['resource_id'],
+ 'hash'=> $rr['resource-id'],
);
+ }
}
$tpl = get_markup_template('photo_album.tpl');
}
- /*
- * Display one photo
- */
+ // Display one photo
if ($datatype === 'image') {
-
- //$o = '';
// fetch image, item containing image, then comments
-
$ph = q("SELECT * FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'
$sql_extra ORDER BY `scale` ASC ",
intval($owner_uid),
dbesc($datum)
);
- if (! DBM::is_result($ph)) {
+ if (!DBM::is_result($ph)) {
$ph = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'
LIMIT 1",
intval($owner_uid),
// The query leads to a really intense used index.
// By now we hide it if someone wants to.
if (!Config::get('system', 'no_count', false)) {
- if ($_GET['order'] === 'posted')
+ $order_field = defaults($_GET, 'order', '');
+ if ($order_field === 'posted') {
$order = 'ASC';
- else
+ } else {
$order = 'DESC';
+ }
$prvnxt = q("SELECT `resource-id` FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `scale` = 0
$sql_extra ORDER BY `created` $order ",
break;
}
}
- $edit_suffix = ((($cmd === 'edit') && ($can_post)) ? '/edit' : '');
- $prevlink = 'photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . $edit_suffix . (($_GET['order'] === 'posted') ? '?f=&order=posted' : '');
- $nextlink = 'photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . $edit_suffix . (($_GET['order'] === 'posted') ? '?f=&order=posted' : '');
+ $edit_suffix = ((($cmd === 'edit') && $can_post) ? '/edit' : '');
+ $prevlink = 'photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . $edit_suffix . ($order_field === 'posted' ? '?f=&order=posted' : '');
+ $nextlink = 'photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . $edit_suffix . ($order_field === 'posted' ? '?f=&order=posted' : '');
}
}
);
$map = null;
+ $link_item = [];
if (DBM::is_result($linked_items)) {
$link_item = $linked_items[0];
);
- if ((local_user()) && (local_user() == $link_item['uid'])) {
+ if (local_user() && (local_user() == $link_item['uid'])) {
q("UPDATE `item` SET `unseen` = 0 WHERE `parent` = %d and `uid` = %d",
intval($link_item['parent']),
intval(local_user())
$edit = Null;
- if (($cmd === 'edit') && ($can_post)) {
+ if ($cmd === 'edit' && $can_post) {
$edit_tpl = get_markup_template('photo_edit.tpl');
- // Private/public post links for the non-JS ACL form
- $private_post = 1;
- if ($_REQUEST['public']) {
- $private_post = 0;
- }
-
- $query_str = $a->query_string;
- if (strpos($query_str, 'public=1') !== false) {
- $query_str = str_replace(array('?public=1', '&public=1'), array('', ''), $query_str);
- }
-
- /*
- * I think $a->query_string may never have ? in it, but I could be wrong
- * It looks like it's from the index.php?q=[etc] rewrite that the web
- * server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
- */
- if (strpos($query_str, '?') === false) {
- $public_post_link = '?public=1';
- } else {
- $public_post_link = '&public=1';
- }
-
$album_e = $ph[0]['album'];
$caption_e = $ph[0]['desc'];
$aclselect_e = populate_acl($ph[0]);
'$permissions' => t('Permissions'),
'$aclselect' => $aclselect_e,
- '$item_id' => ((count($linked_items)) ? $link_item['id'] : 0),
+ '$item_id' => defaults($link_item, 'id', 0),
'$submit' => t('Submit'),
'$delete' => t('Delete Photo'),
'$acl_data' => construct_acl_data($a, $ph[0]), // For non-Javascript ACL selector
'$group_perms' => t('Show to Groups'),
'$contact_perms' => t('Show to Contacts'),
- '$private' => t('Private photo'),
- '$public' => t('Public photo'),
- '$is_private' => $private_post,
- '$return_path' => $query_str,
- '$public_link' => $public_post_link,
+ '$return_path' => $a->query_string,
));
}
- if (count($linked_items)) {
+ $like = '';
+ $dislike = '';
+ $likebuttons = '';
+ $comments = '';
+ $paginate = '';
+ $responses = '';
+ if (count($linked_items)) {
$cmnt_tpl = get_markup_template('comment_item.tpl');
$tpl = get_markup_template('photo_item.tpl');
$return_url = $a->cmd;
- $like_tpl = get_markup_template('like_noshare.tpl');
-
- $likebuttons = '';
-
if ($can_post || can_write_wall($a, $owner_uid)) {
+ $like_tpl = get_markup_template('like_noshare.tpl');
$likebuttons = replace_macros($like_tpl, array(
'$id' => $link_item['id'],
'$likethis' => t("I like this \x28toggle\x29"),
));
}
- $comments = '';
- if (! DBM::is_result($r)) {
+ if (!DBM::is_result($r)) {
if (($can_post || can_write_wall($a, $owner_uid)) && $link_item['last-child']) {
$comments .= replace_macros($cmnt_tpl, array(
'$return_path' => '',
}
}
- $alike = array();
- $dlike = array();
-
- $like = '';
- $dislike = '';
-
$conv_responses = array(
'like' => array('title' => t('Likes','title')),'dislike' => array('title' => t('Dislikes','title')),
'attendyes' => array('title' => t('Attending','title')), 'attendno' => array('title' => t('Not attending','title')), 'attendmaybe' => array('title' => t('Might attend','title'))
// display comments
if (DBM::is_result($r)) {
-
foreach ($r as $item) {
builtin_activity_puller($item, $conv_responses);
}
- $like = ((x($conv_responses['like'], $link_item['uri'])) ? format_like($conv_responses['like'][$link_item['uri']], $conv_responses['like'][$link_item['uri'] . '-l'], 'like',$link_item['id']) : '');
- $dislike = ((x($conv_responses['dislike'], $link_item['uri'])) ? format_like($conv_responses['dislike'][$link_item['uri']], $conv_responses['dislike'][$link_item['uri'] . '-l'], 'dislike',$link_item['id']) : '');
+ if (x($conv_responses['like'], $link_item['uri'])) {
+ $like = format_like($conv_responses['like'][$link_item['uri']], $conv_responses['like'][$link_item['uri'] . '-l'], 'like', $link_item['id']);
+ }
+ if (x($conv_responses['dislike'], $link_item['uri'])) {
+ $dislike = format_like($conv_responses['dislike'][$link_item['uri']], $conv_responses['dislike'][$link_item['uri'] . '-l'], 'dislike', $link_item['id']);
+ }
if (($can_post || can_write_wall($a, $owner_uid)) && $link_item['last-child']) {
$comments .= replace_macros($cmnt_tpl,array(
));
}
-
foreach ($r as $item) {
$comment = '';
$template = $tpl;
$sparkle = '';
- if (((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE))) && ($item['id'] != $item['parent']))
+ if ((activity_match($item['verb'], ACTIVITY_LIKE) || activity_match($item['verb'], ACTIVITY_DISLIKE)) && ($item['id'] != $item['parent'])) {
continue;
+ }
$redirect_url = 'redir/' . $item['cid'];
-
if (local_user() && ($item['contact-uid'] == local_user())
- && ($item['network'] == NETWORK_DFRN) && (! $item['self'] )) {
+ && ($item['network'] == NETWORK_DFRN) && !$item['self']) {
$profile_url = $redirect_url;
$sparkle = ' sparkle';
} else {
$diff_author = (($item['url'] !== $item['author-link']) ? true : false);
- $profile_name = (((strlen($item['author-name'])) && $diff_author) ? $item['author-name'] : $item['name']);
- $profile_avatar = (((strlen($item['author-avatar'])) && $diff_author) ? $item['author-avatar'] : $item['thumb']);
+ $profile_name = ((strlen($item['author-name']) && $diff_author) ? $item['author-name'] : $item['name']);
+ $profile_avatar = ((strlen($item['author-avatar']) && $diff_author) ? $item['author-avatar'] : $item['thumb']);
$profile_link = $profile_url;
}
}
}
+ $response_verbs = array('like');
+ if (Feature::isEnabled($owner_uid, 'dislike')) {
+ $response_verbs[] = 'dislike';
+ }
+ $responses = get_responses($conv_responses, $response_verbs, '', $link_item);
$paginate = paginate($a);
}
-
- $response_verbs = array('like');
- if (Feature::isEnabled($owner_uid, 'dislike')) {
- $response_verbs[] = 'dislike';
- }
- $responses = get_responses($conv_responses,$response_verbs, '', $link_item);
-
$photo_tpl = get_markup_template('photo_view.tpl');
-
- $album_e = array($album_link, $ph[0]['album']);
- $tags_e = $tags;
- $like_e = $like;
- $dislike_e = $dislike;
-
$o .= replace_macros($photo_tpl, array(
'$id' => $ph[0]['id'],
- '$album' => $album_e,
+ '$album' => [$album_link, $ph[0]['album']],
'$tools' => $tools,
'$lock' => $lock,
'$photo' => $photo,
'$prevlink' => $prevlink,
'$nextlink' => $nextlink,
'$desc' => $ph[0]['desc'],
- '$tags' => $tags_e,
+ '$tags' => $tags,
'$edit' => $edit,
'$map' => $map,
'$map_text' => t('Map'),
'$likebuttons' => $likebuttons,
- '$like' => $like_e,
- '$dislike' => $dikslike_e,
+ '$like' => $like,
+ '$dislike' => $dislike,
'responses' => $responses,
'$comments' => $comments,
'$paginate' => $paginate,
$photos = array();
if (DBM::is_result($r)) {
- $twist = 'rotright';
+ // "Twist" is only used for the duepunto theme with style "slackr"
+ $twist = false;
foreach ($r as $rr) {
//hide profile photos to others
- if ((! $is_owner) && (! remote_user()) && ($rr['album'] == t('Profile Photos')))
- continue;
+ if (!$is_owner && !remote_user() && ($rr['album'] == t('Profile Photos')))
+ continue;
- if ($twist == 'rotright')
- $twist = 'rotleft';
- else
- $twist = 'rotright';
+ $twist = !$twist;
$ext = $phototypes[$rr['type']];
$photos[] = array(
'id' => $rr['id'],
- 'twist' => ' ' . $twist . rand(2,4),
+ 'twist' => ' ' . ($twist ? 'rotleft' : 'rotright') . rand(2,4),
'link' => 'photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'],
'title' => t('View Photo'),
'src' => 'photo/' . $rr['resource-id'] . '-' . ((($rr['scale']) == 6) ? 4 : $rr['scale']) . '.' . $ext,
if (intval(Feature::isEnabled(local_user(), 'forumlist_widget'))) {
$forum_counts = ForumManager::countUnseenItems();
- if (DBM::is_result($forums_counts)) {
- foreach ($forums_counts as $forum_count) {
+ if (DBM::is_result($forum_counts)) {
+ foreach ($forum_counts as $forum_count) {
if ($forum_count['count'] > 0) {
$forums_unseen[] = $forum_count;
}
$notification["href"] = System::baseUrl() . "/notify/view/" . $notification["id"];
- if ($notification["visible"] && !$notification["spam"]
- && !$notification["deleted"] && !is_array($result[$notification["parent"]])
+ if ($notification["visible"]
+ && !$notification["spam"]
+ && !$notification["deleted"]
+ && !(x($result, $notification["parent"]) && is_array($result[$notification["parent"]]))
) {
// Should we condense the notifications or show them all?
if (PConfig::get(local_user(), 'system', 'detailed_notif')) {
use Friendica\Core\System;
use Friendica\Database\DBM;
-require_once('include/contact_widgets.php');
-require_once('include/redir.php');
+require_once 'include/contact_widgets.php';
+require_once 'include/redir.php';
-function profile_init(App $a) {
-
- if(! x($a->page,'aside'))
+function profile_init(App $a)
+{
+ if (!x($a->page, 'aside')) {
$a->page['aside'] = '';
+ }
- if($a->argc > 1)
+ if ($a->argc > 1) {
$which = htmlspecialchars($a->argv[1]);
- else {
- $r = q("select nickname from user where blocked = 0 and account_expired = 0 and account_removed = 0 and verified = 1 order by rand() limit 1");
+ } else {
+ $r = q("SELECT `nickname` FROM `user` WHERE `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 ORDER BY RAND() LIMIT 1");
if (DBM::is_result($r)) {
goaway(System::baseUrl() . '/profile/' . $r[0]['nickname']);
- }
- else {
+ } else {
logger('profile error: mod_profile ' . $a->query_string, LOGGER_DEBUG);
- notice( t('Requested profile is not available.') . EOL );
+ notice(t('Requested profile is not available.') . EOL);
$a->error = 404;
return;
}
}
$profile = 0;
- if((local_user()) && ($a->argc > 2) && ($a->argv[2] === 'view')) {
+ if (local_user() && $a->argc > 2 && $a->argv[2] === 'view') {
$which = $a->user['nickname'];
$profile = htmlspecialchars($a->argv[1]);
- }
- else {
+ } else {
auto_redir($a, $which);
}
- profile_load($a,$which,$profile);
+ profile_load($a, $which, $profile);
- $blocked = (((Config::get('system','block_public')) && (! local_user()) && (! remote_user())) ? true : false);
- $userblock = (($a->profile['hidewall'] && (! local_user()) && (! remote_user())) ? true : false);
+ $blocked = !local_user() && !remote_user() && Config::get('system', 'block_public');
+ $userblock = !local_user() && !remote_user() && $a->profile['hidewall'];
- if((x($a->profile,'page-flags')) && ($a->profile['page-flags'] == PAGE_COMMUNITY)) {
+ if (x($a->profile, 'page-flags') && $a->profile['page-flags'] == PAGE_COMMUNITY) {
$a->page['htmlhead'] .= '<meta name="friendica.community" content="true" />';
}
- if (x($a->profile,'openidserver')) {
+
+ if (x($a->profile, 'openidserver')) {
$a->page['htmlhead'] .= '<link rel="openid.server" href="' . $a->profile['openidserver'] . '" />' . "\r\n";
}
- if (x($a->profile,'openid')) {
- $delegate = ((strstr($a->profile['openid'],'://')) ? $a->profile['openid'] : 'https://' . $a->profile['openid']);
+
+ if (x($a->profile, 'openid')) {
+ $delegate = strstr($a->profile['openid'], '://') ? $a->profile['openid'] : 'https://' . $a->profile['openid'];
$a->page['htmlhead'] .= '<link rel="openid.delegate" href="' . $delegate . '" />' . "\r\n";
}
+
// site block
- if ((! $blocked) && (! $userblock)) {
- $keywords = ((x($a->profile,'pub_keywords')) ? $a->profile['pub_keywords'] : '');
- $keywords = str_replace(array('#',',',' ',',,'),array('',' ',',',','),$keywords);
- if(strlen($keywords))
- $a->page['htmlhead'] .= '<meta name="keywords" content="' . $keywords . '" />' . "\r\n" ;
+ if (!$blocked && !$userblock) {
+ $keywords = str_replace(array('#', ',', ' ', ',,'), array('', ' ', ',', ','), defaults($a->profile, 'pub_keywords', ''));
+ if (strlen($keywords)) {
+ $a->page['htmlhead'] .= '<meta name="keywords" content="' . $keywords . '" />' . "\r\n";
+ }
}
- $a->page['htmlhead'] .= '<meta name="dfrn-global-visibility" content="' . (($a->profile['net-publish']) ? 'true' : 'false') . '" />' . "\r\n" ;
- $a->page['htmlhead'] .= '<link rel="alternate" type="application/atom+xml" href="' . System::baseUrl() . '/dfrn_poll/' . $which .'" />' . "\r\n" ;
- $uri = urlencode('acct:' . $a->profile['nickname'] . '@' . $a->get_hostname() . (($a->path) ? '/' . $a->path : ''));
+ $a->page['htmlhead'] .= '<meta name="dfrn-global-visibility" content="' . ($a->profile['net-publish'] ? 'true' : 'false') . '" />' . "\r\n";
+ $a->page['htmlhead'] .= '<link rel="alternate" type="application/atom+xml" href="' . System::baseUrl() . '/feed/' . $which . '/" title="' . t('%s\'s posts', $a->profile['username']) . '"/>' . "\r\n";
+ $a->page['htmlhead'] .= '<link rel="alternate" type="application/atom+xml" href="' . System::baseUrl() . '/feed/' . $which . '/comments" title="' . t('%s\'s comments', $a->profile['username']) . '"/>' . "\r\n";
+ $a->page['htmlhead'] .= '<link rel="alternate" type="application/atom+xml" href="' . System::baseUrl() . '/feed/' . $which . '/activity" title="' . t('%s\'s timeline', $a->profile['username']) . '"/>' . "\r\n";
+ $uri = urlencode('acct:' . $a->profile['nickname'] . '@' . $a->get_hostname() . ($a->path ? '/' . $a->path : ''));
$a->page['htmlhead'] .= '<link rel="lrdd" type="application/xrd+xml" href="' . System::baseUrl() . '/xrd/?uri=' . $uri . '" />' . "\r\n";
header('Link: <' . System::baseUrl() . '/xrd/?uri=' . $uri . '>; rel="lrdd"; type="application/xrd+xml"', false);
$dfrn_pages = array('request', 'confirm', 'notify', 'poll');
foreach ($dfrn_pages as $dfrn) {
- $a->page['htmlhead'] .= "<link rel=\"dfrn-{$dfrn}\" href=\"".System::baseUrl()."/dfrn_{$dfrn}/{$which}\" />\r\n";
+ $a->page['htmlhead'] .= "<link rel=\"dfrn-{$dfrn}\" href=\"" . System::baseUrl() . "/dfrn_{$dfrn}/{$which}\" />\r\n";
}
- $a->page['htmlhead'] .= "<link rel=\"dfrn-poco\" href=\"".System::baseUrl()."/poco/{$which}\" />\r\n";
-
+ $a->page['htmlhead'] .= '<link rel="dfrn-poco" href="' . System::baseUrl() . "/poco/{$which}\" />\r\n";
}
-
-function profile_content(App $a, $update = 0) {
-
+function profile_content(App $a, $update = 0)
+{
$category = $datequery = $datequery2 = '';
if ($a->argc > 2) {
}
}
- if (! x($category)) {
- $category = ((x($_GET,'category')) ? $_GET['category'] : '');
+ if (!x($category)) {
+ $category = defaults($_GET, 'category', '');
}
- $hashtags = (x($_GET, 'tag') ? $_GET['tag'] : '');
+ $hashtags = defaults($_GET, 'tag', '');
- if (Config::get('system','block_public') && (! local_user()) && (! remote_user())) {
+ if (Config::get('system', 'block_public') && !local_user() && !remote_user()) {
return login();
}
- require_once("include/bbcode.php");
- require_once('include/security.php');
- require_once('include/conversation.php');
- require_once('include/acl_selectors.php');
- require_once('include/items.php');
+ require_once 'include/bbcode.php';
+ require_once 'include/security.php';
+ require_once 'include/conversation.php';
+ require_once 'include/acl_selectors.php';
+ require_once 'include/items.php';
$groups = array();
$contact_id = 0;
- if (is_array($_SESSION['remote'])) {
+ if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
foreach ($_SESSION['remote'] as $v) {
if ($v['uid'] == $a->profile['profile_uid']) {
$contact_id = $v['cid'];
}
}
- if (! $remote_contact) {
+ if (!$remote_contact) {
if (local_user()) {
$contact_id = $_SESSION['cid'];
$contact = $a->contact;
}
}
- $is_owner = ((local_user()) && (local_user() == $a->profile['profile_uid']) ? true : false);
+ $is_owner = local_user() == $a->profile['profile_uid'];
$last_updated_key = "profile:" . $a->profile['profile_uid'] . ":" . local_user() . ":" . remote_user();
- if ($a->profile['hidewall'] && (! $is_owner) && (! $remote_contact)) {
- notice( t('Access to this profile has been restricted.') . EOL);
+ if (x($a->profile, 'hidewall') && !$is_owner && !$remote_contact) {
+ notice(t('Access to this profile has been restricted.') . EOL);
return;
}
- if (! $update) {
- if (x($_GET,'tab')) {
+ if (!$update) {
+ $tab = false;
+ if (x($_GET, 'tab')) {
$tab = notags(trim($_GET['tab']));
}
- $o.=profile_tabs($a, $is_owner, $a->profile['nickname']);
+ $o .= profile_tabs($a, $is_owner, $a->profile['nickname']);
if ($tab === 'profile') {
$o .= advanced_profile($a);
- call_hooks('profile_advanced',$o);
+ call_hooks('profile_advanced', $o);
return $o;
}
$o .= common_friends_visitor_widget($a->profile['profile_uid']);
- if (x($_SESSION,'new_member') && $_SESSION['new_member'] && $is_owner) {
+ if (x($_SESSION, 'new_member') && $is_owner) {
$o .= '<a href="newmember" id="newmember-tips" style="font-size: 1.2em;"><b>' . t('Tips for New Members') . '</b></a>' . EOL;
}
- $commpage = (($a->profile['page-flags'] == PAGE_COMMUNITY) ? true : false);
- $commvisitor = (($commpage && $remote_contact == true) ? true : false);
+ $commpage = $a->profile['page-flags'] == PAGE_COMMUNITY;
+ $commvisitor = $commpage && $remote_contact;
- $a->page['aside'] .= posted_date_widget(System::baseUrl(true) . '/profile/' . $a->profile['nickname'],$a->profile['profile_uid'],true);
- $a->page['aside'] .= categories_widget(System::baseUrl(true) . '/profile/' . $a->profile['nickname'],(x($category) ? xmlify($category) : ''));
+ $a->page['aside'] .= posted_date_widget(System::baseUrl(true) . '/profile/' . $a->profile['nickname'], $a->profile['profile_uid'], true);
+ $a->page['aside'] .= categories_widget(System::baseUrl(true) . '/profile/' . $a->profile['nickname'], (x($category) ? xmlify($category) : ''));
$a->page['aside'] .= tagcloud_wall_widget();
- if (can_write_wall($a,$a->profile['profile_uid'])) {
-
+ if (can_write_wall($a, $a->profile['profile_uid'])) {
$x = array(
'is_owner' => $is_owner,
- 'allow_location' => ((($is_owner || $commvisitor) && $a->profile['allow_location']) ? true : false),
- 'default_location' => (($is_owner) ? $a->user['default-location'] : ''),
+ 'allow_location' => ($is_owner || $commvisitor) && $a->profile['allow_location'],
+ 'default_location' => $is_owner ? $a->user['default-location'] : '',
'nickname' => $a->profile['nickname'],
- 'lockstate' => (((is_array($a->user) && ((strlen($a->user['allow_cid'])) ||
- (strlen($a->user['allow_gid'])) || (strlen($a->user['deny_cid'])) ||
- (strlen($a->user['deny_gid']))))) ? 'lock' : 'unlock'),
- 'acl' => (($is_owner) ? populate_acl($a->user, true) : ''),
+ 'lockstate' => is_array($a->user)
+ && (strlen($a->user['allow_cid'])
+ || strlen($a->user['allow_gid'])
+ || strlen($a->user['deny_cid'])
+ || strlen($a->user['deny_gid'])
+ ) ? 'lock' : 'unlock',
+ 'acl' => $is_owner ? populate_acl($a->user, true) : '',
'bang' => '',
- 'visitor' => (($is_owner || $commvisitor) ? 'block' : 'none'),
+ 'visitor' => $is_owner || $commvisitor ? 'block' : 'none',
'profile_uid' => $a->profile['profile_uid'],
- 'acl_data' => ( $is_owner ? construct_acl_data($a, $a->user) : '' ), // For non-Javascript ACL selector
+ 'acl_data' => $is_owner ? construct_acl_data($a, $a->user) : '', // For non-Javascript ACL selector
);
- $o .= status_editor($a,$x);
+ $o .= status_editor($a, $x);
}
}
- /**
- * Get permissions SQL - if $remote_contact is true, our remote user has been pre-verified and we already have fetched his/her groups
- */
- $sql_extra = item_permissions_sql($a->profile['profile_uid'],$remote_contact,$groups);
-
+ // Get permissions SQL - if $remote_contact is true, our remote user has been pre-verified and we already have fetched his/her groups
+ $sql_extra = item_permissions_sql($a->profile['profile_uid'], $remote_contact, $groups);
+ $sql_extra2 = '';
if ($update) {
$last_updated = (x($_SESSION['last_updated'], $last_updated_key) ? $_SESSION['last_updated'][$last_updated_key] : 0);
FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
WHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND
- (`item`.`deleted` = 0 OR item.verb = '" . ACTIVITY_LIKE ."'
+ (`item`.`deleted` = 0 OR item.verb = '" . ACTIVITY_LIKE . "'
OR item.verb = '" . ACTIVITY_DISLIKE . "' OR item.verb = '" . ACTIVITY_ATTEND . "'
OR item.verb = '" . ACTIVITY_ATTENDNO . "' OR item.verb = '" . ACTIVITY_ATTENDMAYBE . "')
AND `item`.`moderated` = 0
if (!DBM::is_result($r)) {
return '';
}
-
} else {
$sql_post_table = "";
if (x($category)) {
$sql_post_table = sprintf("INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($a->profile['profile_uid']));
- //$sql_extra .= protect_sprintf(file_tag_file_query('item',$category,'category'));
}
if (x($hashtags)) {
}
if ($datequery) {
- $sql_extra2 .= protect_sprintf(sprintf(" AND `thread`.`created` <= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$datequery))));
+ $sql_extra2 .= protect_sprintf(sprintf(" AND `thread`.`created` <= '%s' ", dbesc(datetime_convert(date_default_timezone_get(), '', $datequery))));
}
if ($datequery2) {
- $sql_extra2 .= protect_sprintf(sprintf(" AND `thread`.`created` >= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$datequery2))));
+ $sql_extra2 .= protect_sprintf(sprintf(" AND `thread`.`created` >= '%s' ", dbesc(datetime_convert(date_default_timezone_get(), '', $datequery2))));
}
// Belongs the profile page to a forum?
$r = q("SELECT `uid` FROM `user` WHERE `uid` = %d AND `page-flags` IN (%d, %d)",
intval($a->profile['profile_uid']),
intval(PAGE_COMMUNITY),
- intval(PAGE_PRVGROUP));
+ intval(PAGE_PRVGROUP)
+ );
if (!DBM::is_result($r)) {
$sql_extra3 = sprintf(" AND `thread`.`contact-id` = %d ", intval(intval($a->profile['contact_id'])));
// check if we serve a mobile device and get the user settings
// accordingly
if ($a->is_mobile) {
- $itemspage_network = PConfig::get(local_user(),'system','itemspage_mobile_network');
- $itemspage_network = ((intval($itemspage_network)) ? $itemspage_network : 10);
+ $itemspage_network = PConfig::get(local_user(), 'system', 'itemspage_mobile_network', 10);
} else {
- $itemspage_network = PConfig::get(local_user(),'system','itemspage_network');
- $itemspage_network = ((intval($itemspage_network)) ? $itemspage_network : 20);
+ $itemspage_network = PConfig::get(local_user(), 'system', 'itemspage_network', 20);
}
+
// now that we have the user settings, see if the theme forces
// a maximum item number which is lower then the user choice
- if(($a->force_max_items > 0) && ($a->force_max_items < $itemspage_network))
+ if (($a->force_max_items > 0) && ($a->force_max_items < $itemspage_network)) {
$itemspage_network = $a->force_max_items;
+ }
$a->set_pager_itemspage($itemspage_network);
- $pager_sql = sprintf(" LIMIT %d, %d ",intval($a->pager['start']), intval($a->pager['itemspage']));
+ $pager_sql = sprintf(" LIMIT %d, %d ", intval($a->pager['start']), intval($a->pager['itemspage']));
$r = q("SELECT `thread`.`iid` AS `item_id`, `thread`.`network` AS `item_network`
FROM `thread`
ORDER BY `thread`.`created` DESC $pager_sql",
intval($a->profile['profile_uid'])
);
-
}
$parents_arr = array();
$_SESSION['last_updated'][$last_updated_key] = time();
if (DBM::is_result($r)) {
- foreach($r as $rr)
+ foreach ($r as $rr) {
$parents_arr[] = $rr['item_id'];
+ }
+
$parents_str = implode(', ', $parents_arr);
- $items = q(item_query()." AND `item`.`uid` = %d
+ $items = q(item_query() . " AND `item`.`uid` = %d
AND `item`.`parent` IN (%s)
$sql_extra ",
intval($a->profile['profile_uid']),
dbesc($parents_str)
);
- $items = conv_sort($items,'created');
+ $items = conv_sort($items, 'created');
} else {
$items = array();
}
- if($is_owner && (! $update) && (! Config::get('theme','hide_eventlist'))) {
+ if ($is_owner && !$update && !Config::get('theme', 'hide_eventlist')) {
$o .= get_birthdays();
$o .= get_events();
}
use Friendica\Database\DBM;
use Friendica\Protocol\Diaspora;
-require_once 'include/crypto.php';
-
/**
* @param object $a App
* @return void
use Friendica\Database\DBM;
use Friendica\Protocol\OStatus;
use Friendica\Protocol\Salmon;
+use Friendica\Util\Crypto;
-require_once 'include/crypto.php';
require_once 'include/items.php';
require_once 'include/follow.php';
logger('mod-salmon: key details: ' . print_r($key_info,true), LOGGER_DEBUG);
- $pubkey = metopem($m,$e);
+ $pubkey = Crypto::meToPem($m, $e);
// We should have everything we need now. Let's see if it verifies.
// Try GNU Social format
- $verify = rsa_verify($signed_data, $signature, $pubkey);
+ $verify = Crypto::rsaVerify($signed_data, $signature, $pubkey);
$mode = 1;
if (! $verify) {
logger('mod-salmon: message did not verify using protocol. Trying compliant format.');
- $verify = rsa_verify($compliant_format, $signature, $pubkey);
+ $verify = Crypto::rsaVerify($compliant_format, $signature, $pubkey);
$mode = 2;
}
if (! $verify) {
logger('mod-salmon: message did not verify using padding. Trying old statusnet format.');
- $verify = rsa_verify($stnet_signed_data, $signature, $pubkey);
+ $verify = Crypto::rsaVerify($stnet_signed_data, $signature, $pubkey);
$mode = 3;
}
use Friendica\Database\DBM;
use Friendica\Model\Contact;
-require_once('include/items.php');
-require_once('include/acl_selectors.php');
-require_once('include/bbcode.php');
-require_once('include/security.php');
-require_once('include/redir.php');
+require_once 'include/items.php';
+require_once 'include/acl_selectors.php';
+require_once 'include/bbcode.php';
+require_once 'include/security.php';
+require_once 'include/redir.php';
function videos_init(App $a) {
$tpl = get_markup_template("vcard-widget.tpl");
- $vcard_widget .= replace_macros($tpl, array(
+ $vcard_widget = replace_macros($tpl, array(
'$name' => $profile['name'],
'$photo' => $profile['photo'],
- '$addr' => (($profile['addr'] != "") ? $profile['addr'] : ""),
+ '$addr' => defaults($profile, 'addr', ''),
'$account_type' => $account_type,
- '$pdesc' => (($profile['pdesc'] != "") ? $profile['pdesc'] : ""),
+ '$pdesc' => defaults($profile, 'pdesc', ''),
));
}
}
- // perhaps they're visiting - but not a community page, so they wouldn't have write access
+ $groups = [];
+ // perhaps they're visiting - but not a community page, so they wouldn't have write access
if(remote_user() && (! $visitor)) {
$contact_id = 0;
if(is_array($_SESSION['remote'])) {
return;
}
- $sql_extra = permissions_sql($owner_uid,$remote_contact,$groups);
+ $sql_extra = permissions_sql($owner_uid, $remote_contact, $groups);
$o = "";
<?php
-
+/**
+ * @file mod/xrd.php
+ */
use Friendica\App;
use Friendica\Core\System;
use Friendica\Database\DBM;
+use Friendica\Protocol\Salmon;
-require_once('include/crypto.php');
-
-function xrd_init(App $a) {
+function xrd_init(App $a)
+{
if ($a->argv[0] == 'xrd') {
$uri = urldecode(notags(trim($_GET['uri'])));
if ($_SERVER['HTTP_ACCEPT'] == 'application/jrd+json') {
}
}
-function xrd_json($a, $uri, $alias, $profile_url, $r) {
- $salmon_key = salmon_key($r['spubkey']);
+function xrd_json($a, $uri, $alias, $profile_url, $r)
+{
+ $salmon_key = Salmon::salmonKey($r['spubkey']);
header('Access-Control-Allow-Origin: *');
header("Content-type: application/json; charset=utf-8");
killme();
}
-function xrd_xml($a, $uri, $alias, $profile_url, $r) {
- $salmon_key = salmon_key($r['spubkey']);
+function xrd_xml($a, $uri, $alias, $profile_url, $r)
+{
+ $salmon_key = Salmon::salmonKey($r['spubkey']);
header('Access-Control-Allow-Origin: *');
header("Content-type: text/xml");
'$salmon' => System::baseUrl() . '/salmon/' . $r['nickname'],
'$salmen' => System::baseUrl() . '/salmon/' . $r['nickname'] . '/mention',
'$subscribe' => System::baseUrl() . '/follow?url={uri}',
- '$modexp' => 'data:application/magic-public-key,' . $salmon_key,
- ));
+ '$modexp' => 'data:application/magic-public-key,' . $salmon_key)
+ );
$arr = array('user' => $r, 'xml' => $o);
call_hooks('personal_xrd', $arr);
public $query_string;
public $config;
public $page;
+ public $page_offset;
public $profile;
public $profile_uid;
public $user;
--- /dev/null
+<?php\r
+\r
+/**\r
+ * @file src/Content/OEmbed.php\r
+ */\r
+\r
+namespace Friendica\Content;\r
+\r
+use Friendica\Core\Cache;\r
+use Friendica\Core\System;\r
+use Friendica\ParseUrl;\r
+use Friendica\Core\Config;\r
+use Friendica\Database\DBM;\r
+use dba;\r
+use DOMDocument;\r
+use DOMXPath;\r
+use DOMNode;\r
+\r
+require_once 'include/dba.php';\r
+require_once 'mod/proxy.php';\r
+\r
+/**\r
+ * Handles all OEmbed content fetching and replacement\r
+ *\r
+ * OEmbed is a standard used to allow an embedded representation of a URL on\r
+ * third party sites\r
+ *\r
+ * @see https://oembed.com\r
+ *\r
+ * @author Hypolite Petovan <mrpetovan@gmail.com>\r
+ */\r
+class OEmbed\r
+{\r
+ public static function replaceCallback($matches)\r
+ {\r
+ $embedurl = $matches[1];\r
+ $j = self::fetchURL($embedurl);\r
+ $s = self::formatObject($j);\r
+\r
+ return $s;\r
+ }\r
+\r
+ /**\r
+ * @brief Get data from an URL to embed its content.\r
+ *\r
+ * @param string $embedurl The URL from which the data should be fetched.\r
+ * @param bool $no_rich_type If set to true rich type content won't be fetched.\r
+ *\r
+ * @return bool|object Returns object with embed content or false if no embedable\r
+ * content exists\r
+ */\r
+ public static function fetchURL($embedurl, $no_rich_type = false)\r
+ {\r
+ $embedurl = trim($embedurl, "'");\r
+ $embedurl = trim($embedurl, '"');\r
+\r
+ $a = get_app();\r
+\r
+ $condition = array('url' => normalise_link($embedurl));\r
+ $r = dba::select('oembed', array('content'), $condition, array('limit' => 1));\r
+\r
+ if (DBM::is_result($r)) {\r
+ $txt = $r["content"];\r
+ } else {\r
+ $txt = Cache::get($a->videowidth . $embedurl);\r
+ }\r
+ // These media files should now be caught in bbcode.php\r
+ // left here as a fallback in case this is called from another source\r
+\r
+ $noexts = array("mp3", "mp4", "ogg", "ogv", "oga", "ogm", "webm");\r
+ $ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);\r
+\r
+\r
+ if (is_null($txt)) {\r
+ $txt = "";\r
+\r
+ if (!in_array($ext, $noexts)) {\r
+ // try oembed autodiscovery\r
+ $redirects = 0;\r
+ $html_text = fetch_url($embedurl, false, $redirects, 15, "text/*");\r
+ if ($html_text) {\r
+ $dom = @DOMDocument::loadHTML($html_text);\r
+ if ($dom) {\r
+ $xpath = new DOMXPath($dom);\r
+ $entries = $xpath->query("//link[@type='application/json+oembed']");\r
+ foreach ($entries as $e) {\r
+ $href = $e->getAttributeNode("href")->nodeValue;\r
+ $txt = fetch_url($href . '&maxwidth=' . $a->videowidth);\r
+ break;\r
+ }\r
+ $entries = $xpath->query("//link[@type='text/json+oembed']");\r
+ foreach ($entries as $e) {\r
+ $href = $e->getAttributeNode("href")->nodeValue;\r
+ $txt = fetch_url($href . '&maxwidth=' . $a->videowidth);\r
+ break;\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ $txt = trim($txt);\r
+\r
+ if (!$txt || $txt[0] != "{") {\r
+ $txt = '{"type":"error"}';\r
+ } else { //save in cache\r
+ $j = json_decode($txt);\r
+ if ($j->type != "error") {\r
+ dba::insert('oembed', array('url' => normalise_link($embedurl),\r
+ 'content' => $txt, 'created' => datetime_convert()), true);\r
+ }\r
+\r
+ Cache::set($a->videowidth . $embedurl, $txt, CACHE_DAY);\r
+ }\r
+ }\r
+\r
+ $j = json_decode($txt);\r
+\r
+ if (!is_object($j)) {\r
+ return false;\r
+ }\r
+\r
+ // Always embed the SSL version\r
+ if (isset($j->html)) {\r
+ $j->html = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"), array("https://www.youtube.com/", "https://player.vimeo.com/"), $j->html);\r
+ }\r
+\r
+ $j->embedurl = $embedurl;\r
+\r
+ // If fetching information doesn't work, then improve via internal functions\r
+ if (($j->type == "error") || ($no_rich_type && ($j->type == "rich"))) {\r
+ $data = ParseUrl::getSiteinfoCached($embedurl, true, false);\r
+ $j->type = $data["type"];\r
+\r
+ if ($j->type == "photo") {\r
+ $j->url = $data["url"];\r
+ //$j->width = $data["images"][0]["width"];\r
+ //$j->height = $data["images"][0]["height"];\r
+ }\r
+\r
+ if (isset($data["title"])) {\r
+ $j->title = $data["title"];\r
+ }\r
+\r
+ if (isset($data["text"])) {\r
+ $j->description = $data["text"];\r
+ }\r
+\r
+ if (is_array($data["images"])) {\r
+ $j->thumbnail_url = $data["images"][0]["src"];\r
+ $j->thumbnail_width = $data["images"][0]["width"];\r
+ $j->thumbnail_height = $data["images"][0]["height"];\r
+ }\r
+ }\r
+\r
+ call_hooks('oembed_fetch_url', $embedurl, $j);\r
+\r
+ return $j;\r
+ }\r
+\r
+ public static function formatObject($j)\r
+ {\r
+ $embedurl = $j->embedurl;\r
+ $jhtml = self::iframe($j->embedurl, (isset($j->width) ? $j->width : null), (isset($j->height) ? $j->height : null));\r
+ $ret = "<span class='oembed " . $j->type . "'>";\r
+ switch ($j->type) {\r
+ case "video":\r
+ if (isset($j->thumbnail_url)) {\r
+ $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width : 200;\r
+ $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->thumbnail_height : 180;\r
+ // make sure we don't attempt divide by zero, fallback is a 1:1 ratio\r
+ $tr = (($th) ? $tw / $th : 1);\r
+\r
+ $th = 120;\r
+ $tw = $th * $tr;\r
+ $tpl = get_markup_template('oembed_video.tpl');\r
+ $ret.=replace_macros($tpl, array(\r
+ '$baseurl' => System::baseUrl(),\r
+ '$embedurl' => $embedurl,\r
+ '$escapedhtml' => base64_encode($jhtml),\r
+ '$tw' => $tw,\r
+ '$th' => $th,\r
+ '$turl' => $j->thumbnail_url,\r
+ ));\r
+ } else {\r
+ $ret = $jhtml;\r
+ }\r
+ //$ret.="<br>";\r
+ break;\r
+ case "photo":\r
+ $ret.= "<img width='" . $j->width . "' src='" . proxy_url($j->url) . "'>";\r
+ break;\r
+ case "link":\r
+ break;\r
+ case "rich":\r
+ // not so safe..\r
+ if (!Config::get("system", "no_oembed_rich_content")) {\r
+ $ret.= proxy_parse_html($jhtml);\r
+ }\r
+ break;\r
+ }\r
+\r
+ // add link to source if not present in "rich" type\r
+ if ($j->type != 'rich' || !strpos($j->html, $embedurl)) {\r
+ $ret .= "<h4>";\r
+ if (isset($j->title)) {\r
+ if (isset($j->provider_name)) {\r
+ $ret .= $j->provider_name . ": ";\r
+ }\r
+\r
+ $embedlink = (isset($j->title)) ? $j->title : $embedurl;\r
+ $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";\r
+ if (isset($j->author_name)) {\r
+ $ret.=" (" . $j->author_name . ")";\r
+ }\r
+ } elseif (isset($j->provider_name) || isset($j->author_name)) {\r
+ $embedlink = "";\r
+ if (isset($j->provider_name)) {\r
+ $embedlink .= $j->provider_name;\r
+ }\r
+\r
+ if (isset($j->author_name)) {\r
+ if ($embedlink != "") {\r
+ $embedlink .= ": ";\r
+ }\r
+\r
+ $embedlink .= $j->author_name;\r
+ }\r
+ if (trim($embedlink) == "") {\r
+ $embedlink = $embedurl;\r
+ }\r
+\r
+ $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";\r
+ }\r
+ //if (isset($j->author_name)) $ret.=" by ".$j->author_name;\r
+ //if (isset($j->provider_name)) $ret.=" on ".$j->provider_name;\r
+ $ret .= "</h4>";\r
+ } else {\r
+ // add <a> for html2bbcode conversion\r
+ $ret .= "<a href='$embedurl' rel='oembed'>$embedurl</a>";\r
+ }\r
+ $ret.="</span>";\r
+ $ret = str_replace("\n", "", $ret);\r
+ return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));\r
+ }\r
+\r
+ public static function BBCode2HTML($text)\r
+ {\r
+ $stopoembed = Config::get("system", "no_oembed");\r
+ if ($stopoembed == true) {\r
+ return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>" . t('Embedding disabled') . " : $1</i><!-- /oembed $1 -->", $text);\r
+ }\r
+ return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text);\r
+ }\r
+\r
+ /**\r
+ * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>\r
+ * and replace it with [embed]url[/embed]\r
+ */\r
+ public static function HTML2BBCode($text)\r
+ {\r
+ // start parser only if 'oembed' is in text\r
+ if (strpos($text, "oembed")) {\r
+\r
+ // convert non ascii chars to html entities\r
+ $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));\r
+\r
+ // If it doesn't parse at all, just return the text.\r
+ $dom = @DOMDocument::loadHTML($html_text);\r
+ if (!$dom) {\r
+ return $text;\r
+ }\r
+ $xpath = new DOMXPath($dom);\r
+\r
+ $xattr = self::buildXPath("class", "oembed");\r
+ $entries = $xpath->query("//span[$xattr]");\r
+\r
+ $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed");\r
+ foreach ($entries as $e) {\r
+ $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;\r
+ if (!is_null($href)) {\r
+ $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e);\r
+ }\r
+ }\r
+ return self::getInnerHTML($dom->getElementsByTagName("body")->item(0));\r
+ } else {\r
+ return $text;\r
+ }\r
+ }\r
+\r
+ /**\r
+ * @brief Generates the iframe HTML for an oembed attachment.\r
+ *\r
+ * Width and height are given by the remote, and are regularly too small for\r
+ * the generated iframe.\r
+ *\r
+ * The width is entirely discarded for the actual width of the post, while fixed\r
+ * height is used as a starting point before the inevitable resizing.\r
+ *\r
+ * Since the iframe is automatically resized on load, there are no need for ugly\r
+ * and impractical scrollbars.\r
+ *\r
+ * @param string $src Original remote URL to embed\r
+ * @param string $width\r
+ * @param string $height\r
+ * @return string formatted HTML\r
+ *\r
+ * @see oembed_format_object()\r
+ */\r
+ private static function iframe($src, $width, $height)\r
+ {\r
+ $a = get_app();\r
+\r
+ if (!$height || strstr($height, '%')) {\r
+ $height = '200';\r
+ }\r
+ $width = '100%';\r
+\r
+ $s = System::baseUrl() . '/oembed/' . base64url_encode($src);\r
+ return '<iframe onload="resizeIframe(this);" class="embed_rich" height="' . $height . '" width="' . $width . '" src="' . $s . '" allowfullscreen scrolling="no" frameborder="no">' . t('Embedded content') . '</iframe>';\r
+ }\r
+\r
+ /**\r
+ * Generates an XPath query to select elements whose provided attribute contains\r
+ * the provided value in a space-separated list.\r
+ *\r
+ * @brief Generates attribute search XPath string\r
+ *\r
+ * @param string $attr Name of the attribute to seach\r
+ * @param string $value Value to search in a space-separated list\r
+ * @return string\r
+ */\r
+ private static function buildXPath($attr, $value)\r
+ {\r
+ // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath\r
+ return "contains(normalize-space(@$attr), ' $value ') or substring(normalize-space(@$attr), 1, string-length('$value') + 1) = '$value ' or substring(normalize-space(@$attr), string-length(@$attr) - string-length('$value')) = ' $value' or @$attr = '$value'";\r
+ }\r
+\r
+ /**\r
+ * Returns the inner XML string of a provided DOMNode\r
+ *\r
+ * @brief Returns the inner XML string of a provided DOMNode\r
+ *\r
+ * @param DOMNode $node\r
+ * @return string\r
+ */\r
+ private static function getInnerHTML(DOMNode $node)\r
+ {\r
+ $innerHTML = '';\r
+ $children = $node->childNodes;\r
+ foreach ($children as $child) {\r
+ $innerHTML .= $child->ownerDocument->saveXML($child);\r
+ }\r
+ return $innerHTML;\r
+ }\r
+}\r
$exponent = 3;
$slope = $maxworkers / pow($maxsysload, $exponent);
$queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
+ $processlist = '';
if (Config::get('system', 'worker_debug')) {
// Create a list of queue entries grouped by their priority
if (!DBM::is_result($contact)) {
// The link could be provided as http although we stored it as https
$ssl_url = str_replace('http://', 'https://', $url);
- $r = dba::select('contact', array('id', 'avatar-date'), array('`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid), array('limit' => 1));
+ $r = dba::select('contact', array('id', 'avatar', 'avatar-date'), array('`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid), array('limit' => 1));
$contact = dba::fetch($r);
dba::close($r);
}
$update_contact = ($contact['avatar-date'] < datetime_convert('', '', 'now -7 days'));
// We force the update if the avatar is empty
- if ($contact['avatar'] == '') {
+ if (!x($contact, 'avatar')) {
$update_contact = true;
}
use Friendica\Model\Group;
use Friendica\Model\Photo;
use Friendica\Object\Image;
+use Friendica\Util\Crypto;
use dba;
use Exception;
require_once 'boot.php';
-require_once 'include/crypto.php';
require_once 'include/dba.php';
require_once 'include/enotify.php';
require_once 'include/network.php';
$return['password'] = $new_password;
- $keys = new_keypair(4096);
+ $keys = Crypto::newKeypair(4096);
if ($keys === false) {
throw new Exception(t('SERIOUS ERROR: Generation of security keys failed.'));
}
$pubkey = $keys['pubkey'];
// Create another keypair for signing/verifying salmon protocol messages.
- $sres = new_keypair(512);
+ $sres = Crypto::newKeypair(512);
$sprvkey = $sres['prvkey'];
$spubkey = $sres['pubkey'];
--- /dev/null
+<?php\r
+\r
+namespace Friendica\Module;\r
+\r
+use Friendica\BaseModule;\r
+use Friendica\Protocol\OStatus;\r
+\r
+/**\r
+ * Provides public Atom feeds\r
+ *\r
+ * Currently supported:\r
+ * - /feed/[nickname]/ => posts\r
+ * - /feed/[nickname]/posts => posts\r
+ * - /feed/[nickname]/comments => comments\r
+ * - /feed/[nickname]/replies => comments\r
+ * - /feed/[nickname]/activity => activity\r
+ *\r
+ * The nocache GET parameter is provided mainly for debug purposes, requires auth\r
+ *\r
+ * @brief Provides public Atom feeds\r
+ *\r
+ * @author Hypolite Petovan <mrpetovan@gmail.com>\r
+ */\r
+class Feed extends BaseModule\r
+{\r
+ public static function content()\r
+ {\r
+ $a = self::getApp();\r
+\r
+ $last_update = x($_GET, 'last_update') ? $_GET['last_update'] : '';\r
+ $nocache = x($_GET, 'nocache') && local_user();\r
+\r
+ if ($a->argc < 2) {\r
+ http_status_exit(400);\r
+ }\r
+\r
+ $type = null;\r
+ if ($a->argc > 2) {\r
+ $type = $a->argv[2];\r
+ }\r
+\r
+ switch ($type) {\r
+ case 'posts':\r
+ case 'comments':\r
+ case 'activity':\r
+ break;\r
+ case 'replies':\r
+ $type = 'comments';\r
+ break;\r
+ default:\r
+ $type = 'posts';\r
+ }\r
+\r
+ $nickname = $a->argv[1];\r
+ header("Content-type: application/atom+xml");\r
+ echo OStatus::feed($nickname, $last_update, 10, $type, $nocache);\r
+ killme();\r
+ }\r
+}\r
--- /dev/null
+<?php\r
+\r
+namespace Friendica\Module;\r
+\r
+use Friendica\BaseModule;\r
+use Friendica\Content;\r
+\r
+/**\r
+ * Oembed module\r
+ *\r
+ * Displays stored embed content based on a base64 hash of a remote URL\r
+ *\r
+ * Example: /oembed/aHR0cHM6Ly9...\r
+ *\r
+ * @author Hypolite Petovan <mrpetovan@gmail.com>\r
+ */\r
+class Oembed extends BaseModule\r
+{\r
+ public static function content()\r
+ {\r
+ $a = self::getApp();\r
+\r
+ // Unused form: /oembed/b2h?url=...\r
+ if ($a->argv[1] == 'b2h') {\r
+ $url = array("", trim(hex2bin($_REQUEST['url'])));\r
+ echo Content\OEmbed::replaceCallback($url);\r
+ killme();\r
+ }\r
+\r
+ // Unused form: /oembed/h2b?text=...\r
+ if ($a->argv[1] == 'h2b') {\r
+ $text = trim(hex2bin($_REQUEST['text']));\r
+ echo Content\OEmbed::HTML2BBCode($text);\r
+ killme();\r
+ }\r
+\r
+ if ($a->argc == 2) {\r
+ echo '<html><body>';\r
+ $url = base64url_decode($a->argv[1]);\r
+ $j = Content\OEmbed::fetchURL($url);\r
+\r
+ // workaround for media.ccc.de (and any other endpoint that return size 0)\r
+ if (substr($j->html, 0, 7) == "<iframe" && strstr($j->html, 'width="0"')) {\r
+ $j->html = '<style>html,body{margin:0;padding:0;} iframe{width:100%;height:100%;}</style>' . $j->html;\r
+ $j->html = str_replace('width="0"', '', $j->html);\r
+ $j->html = str_replace('height="0"', '', $j->html);\r
+ }\r
+ echo $j->html;\r
+ echo '</body></html>';\r
+ }\r
+ killme();\r
+ }\r
+}\r
use Friendica\Model\Profile;
use Friendica\Protocol\Email;
use Friendica\Protocol\Feed;
+use Friendica\Util\Crypto;
use Friendica\Util\XML;
use dba;
require_once 'include/dba.php';
require_once 'include/network.php';
-require_once "include/crypto.php";
/**
* @brief This class contain functions for probing URL
$data["url"] = $uri;
}
- if ($data["photo"] != "") {
+ if (x($data, "photo")) {
$data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
} else {
$data["photo"] = System::baseUrl().'/images/person-175.jpg';
$data["name"] = $data["nick"];
}
- if ($data["name"] == "") {
+ if (!x($data, "name")) {
$data["name"] = $data["url"];
}
}
//if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
if (strstr($data["pubkey"], 'RSA ')) {
- $data["pubkey"] = rsatopem($data["pubkey"]);
+ $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
}
}
}
if ($search->length > 0) {
$data["pubkey"] = $search->item(0)->nodeValue;
if (strstr($data["pubkey"], 'RSA ')) {
- $data["pubkey"] = rsatopem($data["pubkey"]);
+ $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
}
}
//if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
if (strstr($data["pubkey"], 'RSA ')) {
- $data["pubkey"] = rsatopem($data["pubkey"]);
+ $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
}
}
}
if (sizeof($key) >= 3) {
$m = base64url_decode($key[1]);
$e = base64url_decode($key[2]);
- $data["pubkey"] = metopem($m, $e);
+ $data["pubkey"] = Crypto::meToPem($m, $e);
}
}
}
<?php
+
/**
* @file src/Object/Post.php
*/
+
namespace Friendica\Object;
use Friendica\BaseObject;
$this->data = $data;
$this->setTemplate('wall');
- $this->toplevel = ($this->getId() == $this->getDataValue('parent'));
+ $this->toplevel = $this->getId() == $this->getDataValue('parent');
- if (is_array($_SESSION['remote'])) {
+ if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
foreach ($_SESSION['remote'] as $visitor) {
if ($visitor['cid'] == $this->getDataValue('contact-id')) {
$this->visiting = true;
}
}
- $this->writable = ($this->getDataValue('writable') || $this->getDataValue('self'));
-
- $ssl_state = ((local_user()) ? true : false);
+ $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
$this->redirect_url = 'redir/' . $this->getDataValue('cid');
if (!$this->isToplevel()) {
// Prepare the children
if (count($data['children'])) {
foreach ($data['children'] as $item) {
- /*
- * Only add will be displayed
- */
+ // Only add will be displayed
if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
continue;
- } elseif (! visible_activity($item)) {
+ } elseif (!visible_activity($item)) {
continue;
}
|| strlen($item['deny_cid']) || strlen($item['deny_gid']))))
? t('Private Message')
: false);
- $shareable = ((in_array($conv->getProfileOwner(), [0, local_user()]) && ($item['private'] != 1)) ? true : false);
+ $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
if (local_user() && link_compare($a->contact['url'], $item['author-link'])) {
if ($item["event-id"] != 0) {
- $edpost = array("events/event/".$item['event-id'], t("Edit"));
+ $edpost = array("events/event/" . $item['event-id'], t("Edit"));
} else {
- $edpost = array("editpost/".$item['id'], t("Edit"));
+ $edpost = array("editpost/" . $item['id'], t("Edit"));
}
} else {
$edpost = false;
$filer = (($conv->getProfileOwner() == local_user()) ? t("save to folder") : false);
- $diff_author = ((link_compare($item['url'], $item['author-link'])) ? false : true);
- $profile_name = htmlentities(((strlen($item['author-name'])) && $diff_author) ? $item['author-name'] : $item['name']);
- if ($item['author-link'] && (! $item['author-name'])) {
+ $diff_author = !link_compare($item['url'], $item['author-link']);
+ $profile_name = htmlentities(((strlen($item['author-name'])) && $diff_author) ? $item['author-name'] : $item['name']);
+ if ($item['author-link'] && (!$item['author-name'])) {
$profile_name = $item['author-link'];
}
call_hooks('render_location', $locate);
$location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
- $tags=array();
- $hashtags = array();
- $mentions = array();
-
- /*foreach(explode(',',$item['tag']) as $tag){
- $tag = trim($tag);
- if ($tag!="") {
- $t = bbcode($tag);
- $tags[] = $t;
- if($t[0] == '#')
- $hashtags[] = $t;
- elseif($t[0] == '@')
- $mentions[] = $t;
- }
- }*/
-
// process action responses - e.g. like/dislike/attend/agree/whatever
$response_verbs = array('like', 'dislike');
+ $isevent = false;
+ $attend = [];
if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
$response_verbs[] = 'attendyes';
$response_verbs[] = 'attendno';
$response_verbs[] = 'attendmaybe';
if ($conv->isWritable()) {
$isevent = true;
- $attend = array( t('I will attend'), t('I will not attend'), t('I might attend'));
+ $attend = array(t('I will attend'), t('I will not attend'), t('I might attend'));
}
}
$responses = get_responses($conv_responses, $response_verbs, $this, $item);
foreach ($response_verbs as $value => $verbs) {
- $responses[$verbs]['output'] = ((x($conv_responses[$verbs], $item['uri'])) ? format_like($conv_responses[$verbs][$item['uri']], $conv_responses[$verbs][$item['uri'] . '-l'], $verbs, $item['uri']) : '');
+ $responses[$verbs]['output'] = x($conv_responses[$verbs], $item['uri']) ? format_like($conv_responses[$verbs][$item['uri']], $conv_responses[$verbs][$item['uri'] . '-l'], $verbs, $item['uri']) : '';
}
/*
$osparkle = ' sparkle';
}
+ $tagger = '';
+
if ($this->isToplevel()) {
if ($conv->getProfileOwner() == local_user()) {
$isstarred = (($item['starred']) ? "starred" : "unstarred");
'do' => t("add star"),
'undo' => t("remove star"),
'toggle' => t("toggle star status"),
- 'classdo' => (($item['starred']) ? "hidden" : ""),
- 'classundo' => (($item['starred']) ? "" : "hidden"),
- 'starred' => t('starred'),
+ 'classdo' => $item['starred'] ? "hidden" : "",
+ 'classundo' => $item['starred'] ? "" : "hidden",
+ 'starred' => t('starred'),
);
$r = dba::select('thread', array('ignored'), array('uid' => $item['uid'], 'iid' => $item['id']), array('limit' => 1));
if (DBM::is_result($r)) {
'do' => t("ignore thread"),
'undo' => t("unignore thread"),
'toggle' => t("toggle ignore status"),
- 'classdo' => (($r['ignored']) ? "hidden" : ""),
- 'classundo' => (($r['ignored']) ? "" : "hidden"),
- 'ignored' => t('ignored'),
+ 'classdo' => $r['ignored'] ? "hidden" : "",
+ 'classundo' => $r['ignored'] ? "" : "hidden",
+ 'ignored' => t('ignored'),
);
}
- $tagger = '';
if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
$tagger = array(
'add' => t("add tag"),
if ($conv->isWritable()) {
$buttons = array(
- 'like' => array( t("I like this \x28toggle\x29"), t("like")),
- 'dislike' => ((Feature::isEnabled($conv->getProfileOwner(), 'dislike')) ? array( t("I don't like this \x28toggle\x29"), t("dislike")) : ''),
+ 'like' => array(t("I like this \x28toggle\x29"), t("like")),
+ 'dislike' => Feature::isEnabled($conv->getProfileOwner(), 'dislike') ? array(t("I don't like this \x28toggle\x29"), t("dislike")) : '',
);
if ($shareable) {
- $buttons['share'] = array( t('Share this'), t('share'));
+ $buttons['share'] = array(t('Share this'), t('share'));
}
}
$owner_name_e = $this->getOwnerName();
// Disable features that aren't available in several networks
-
/// @todo Add NETWORK_DIASPORA when it will pass this information
if (!in_array($item["item_network"], array(NETWORK_DFRN)) && isset($buttons["dislike"])) {
- unset($buttons["dislike"], $isevent);
+ unset($buttons["dislike"]);
+ $isevent = false;
$tagger = '';
}
'guid' => urlencode($item['guid']),
'isevent' => $isevent,
'attend' => $attend,
- 'linktitle' => sprintf(t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
- 'olinktitle' => sprintf(t('View %s\'s profile @ %s'), htmlentities($this->getOwnerName()), ((strlen($item['owner-link'])) ? $item['owner-link'] : $item['url'])),
+ 'linktitle' => t('View %s\'s profile @ %s', $profile_name, defaults($item, 'author-link', $item['url'])),
+ 'olinktitle' => t('View %s\'s profile @ %s', htmlentities($this->getOwnerName()), defaults($item, 'owner-link', $item['url'])),
'to' => t('to'),
'via' => t('via'),
'wall' => t('Wall-to-Wall'),
'sparkle' => $sparkle,
'title' => $title_e,
'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
- 'ago' => (($item['app']) ? sprintf(t('%s from %s'), relative_date($item['created']), $item['app']) : relative_date($item['created'])),
+ 'ago' => $item['app'] ? t('%s from %s', relative_date($item['created']), $item['app']) : relative_date($item['created']),
'app' => $item['app'],
'created' => relative_date($item['created']),
'lock' => $lock,
'owner_photo' => $a->remove_baseurl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
'owner_name' => htmlentities($owner_name_e),
'plink' => get_plink($item),
- 'edpost' => ((Feature::isEnabled($conv->getProfileOwner(), 'edit_posts')) ? $edpost : ''),
+ 'edpost' => Feature::isEnabled($conv->getProfileOwner(), 'edit_posts') ? $edpost : '',
'isstarred' => $isstarred,
- 'star' => ((Feature::isEnabled($conv->getProfileOwner(), 'star_posts')) ? $star : ''),
- 'ignore' => ((Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts')) ? $ignore : ''),
+ 'star' => Feature::isEnabled($conv->getProfileOwner(), 'star_posts') ? $star : '',
+ 'ignore' => Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts') ? $ignore : '',
'tagger' => $tagger,
- 'filer' => ((Feature::isEnabled($conv->getProfileOwner(), 'filing')) ? $filer : ''),
+ 'filer' => Feature::isEnabled($conv->getProfileOwner(), 'filing') ? $filer : '',
'drop' => $drop,
'vote' => $buttons,
'like' => $responses['like']['output'],
'responses' => $responses,
'switchcomment' => t('Comment'),
'comment' => $comment,
- 'previewing' => ($conv->isPreview() ? ' preview ' : ''),
+ 'previewing' => $conv->isPreview() ? ' preview ' : '',
'wait' => t('Please wait'),
'thread_level' => $thread_level,
'edited' => $edited,
// Collapse
if (($nb_children > 2) || ($thread_level > 1)) {
$result['children'][0]['comment_firstcollapsed'] = true;
- $result['children'][0]['num_comments'] = sprintf(tt('%d comment', '%d comments', $total_children), $total_children);
+ $result['children'][0]['num_comments'] = tt('%d comment', '%d comments', $total_children);
$result['children'][0]['hidden_comments_num'] = $total_children;
$result['children'][0]['hidden_comments_text'] = tt('comment', 'comments', $total_children);
$result['children'][0]['hide_text'] = t('show more');
logger('[ERROR] Post::addChild : Item has no ID!!', LOGGER_DEBUG);
return false;
} elseif ($this->getChild($item->getId())) {
- logger('[WARN] Post::addChild : Item already exists ('. $item->getId() .').', LOGGER_DEBUG);
+ logger('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', LOGGER_DEBUG);
return false;
}
/*
return true;
}
}
- logger('[WARN] Item::removeChild : Item is not a child ('. $id .').', LOGGER_DEBUG);
+ logger('[WARN] Item::removeChild : Item is not a child (' . $id . ').', LOGGER_DEBUG);
return false;
}
private function setTemplate($name)
{
if (!x($this->available_templates, $name)) {
- logger('[ERROR] Item::setTemplate : Template not available ("'. $name .'").', LOGGER_DEBUG);
+ logger('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', LOGGER_DEBUG);
return false;
}
if ($conv) {
// This will allow us to comment on wall-to-wall items owned by our friends
// and community forums even if somebody else wrote the post.
-
// bug #517 - this fixes for conversation owner
if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
return true;
$comment_box = '';
$conv = $this->getThread();
- $template = get_markup_template($this->getCommentBoxTemplate());
$ww = '';
if (($conv->getMode() === 'network') && $this->isWallToWall()) {
$ww = 'ww';
}
if ($conv->isWritable() && $this->isWritable()) {
- $qc = $qcomment = null;
+ $qc = $qcomment = null;
/*
* Hmmm, code depending on the presence of a particular plugin?
$qcomment = (($qc) ? explode("\n", $qc) : null);
}
- $comment_box = replace_macros(
- $template,
- array(
+ $template = get_markup_template($this->getCommentBoxTemplate());
+ $comment_box = replace_macros($template, array(
'$return_path' => $a->query_string,
'$threaded' => $this->isThreaded(),
- // '$jsreload' => (($conv->getMode() === 'display') ? $_SESSION['return_url'] : ''),
'$jsreload' => '',
- '$type' => (($conv->getMode() === 'profile') ? 'wall-comment' : 'net-comment'),
+ '$type' => $conv->getMode() === 'profile' ? 'wall-comment' : 'net-comment',
'$id' => $this->getId(),
'$parent' => $this->getId(),
'$qcomment' => $qcomment,
- '$profile_uid' => $conv->getProfileOwner(),
+ '$profile_uid' => $conv->getProfileOwner(),
'$mylink' => $a->remove_baseurl($a->contact['url']),
'$mytitle' => t('This is you'),
'$myphoto' => $a->remove_baseurl($a->contact['thumb']),
'$preview' => ((Feature::isEnabled($conv->getProfileOwner(), 'preview')) ? t('Preview') : ''),
'$indent' => $indent,
'$sourceapp' => t($a->sourcename),
- '$ww' => (($conv->getMode() === 'network') ? $ww : ''),
- '$rand_num' => random_digits(12))
- );
+ '$ww' => $conv->getMode() === 'network' ? $ww : '',
+ '$rand_num' => random_digits(12)
+ ));
}
return $comment_box;
$alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
$owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
- if ((! $owner_linkmatch) && (! $alias_linkmatch) && (! $owner_namematch)) {
+ if ((!$owner_linkmatch) && (!$alias_linkmatch) && (!$owner_namematch)) {
// The author url doesn't match the owner (typically the contact)
// and also doesn't match the contact alias.
// The name match is a hack to catch several weird cases where URLs are
// all over the park. It can be tricked, but this prevents you from
// seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
// well that it's the same Bob Smith.
-
// But it could be somebody else with the same name. It just isn't highly likely.
$this->owner_name = $this->getDataValue('owner-name');
$this->wall_to_wall = true;
// If it is our contact, use a friendly redirect link
- if ((link_compare($this->getDataValue('owner-link'), $this->getDataValue('url')))
- && ($this->getDataValue('network') === NETWORK_DFRN)
+ if ($this->getDataValue('network') === NETWORK_DFRN
+ && link_compare($this->getDataValue('owner-link'), $this->getDataValue('url'))
) {
$this->owner_url = $this->getRedirectUrl();
} else {
*/
namespace Friendica;
-use Friendica\Core\Config;
+use Friendica\Content\OEmbed;
use Friendica\Object\Image;
use Friendica\Util\XML;
require_once 'include/dba.php';
require_once "include/network.php";
-require_once "include/oembed.php";
/**
* @brief Class with methods for extracting certain content from an url
$body = $data["body"];
if ($do_oembed) {
- $oembed_data = oembed_fetch_url($url);
+ $oembed_data = OEmbed::fetchURL($url);
if (!in_array($oembed_data->type, array("error", "rich", ""))) {
$siteinfo["type"] = $oembed_data->type;
*/
namespace Friendica\Protocol;
+use Friendica\Content\OEmbed;
use Friendica\Core\Config;
use Friendica\Core\System;
use Friendica\Core\Worker;
require_once "include/files.php";
require_once "include/event.php";
require_once "include/text.php";
-require_once "include/oembed.php";
require_once "include/html2bbcode.php";
require_once "include/bbcode.php";
/* get site pubkey. this could be a new installation with no site keys*/
$pubkey = Config::get('system', 'site_pubkey');
if (! $pubkey) {
- $res = new_keypair(1024);
+ $res = Crypto::newKeypair(1024);
Config::set('system', 'site_prvkey', $res['prvkey']);
Config::set('system', 'site_pubkey', $res['pubkey']);
}
$item['body'] = html2bb_video($item['body']);
- $item['body'] = oembed_html2bbcode($item['body']);
+ $item['body'] = OEmbed::HTML2BBCode($item['body']);
$config = \HTMLPurifier_Config::createDefault();
$config->set('Cache.DefinitionImpl', null);
use Friendica\Model\Profile;
use Friendica\Model\User;
use Friendica\Network\Probe;
+use Friendica\Util\Crypto;
use Friendica\Util\XML;
use dba;
$key = self::key($handle);
- $verify = rsa_verify($signable_data, $sig, $key);
+ $verify = Crypto::rsaVerify($signable_data, $sig, $key);
if (!$verify) {
logger('Message did not verify. Discarding.');
return false;
$author_addr = base64_decode($key_id);
$key = self::key($author_addr);
- $verify = rsa_verify($signed_data, $signature, $key);
+ $verify = Crypto::rsaVerify($signed_data, $signature, $key);
if (!$verify) {
logger('Message did not verify. Discarding.');
http_status_exit(400);
http_status_exit(400);
}
- $verify = rsa_verify($signed_data, $signature, $key);
+ $verify = Crypto::rsaVerify($signed_data, $signature, $key);
if (!$verify) {
logger('Message did not verify. Discarding.');
$key = self::key($msg["author"]);
- if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
+ if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
logger("No valid parent author signature for parent author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$parent_author_signature, LOGGER_DEBUG);
return false;
}
$key = self::key($fields->author);
- if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
+ if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
return false;
} else {
// Check signature
$signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
$key = self::key($old_handle);
- if (!rsa_verify($signed_text, $signature, $key, "sha256")) {
+ if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
logger('No valid signature for migration.');
return false;
}
self::fetchGuid($datarray);
$message_id = item_store($datarray);
+ self::sendParticipation($contact, $datarray);
+
if ($message_id) {
logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
return true;
self::fetchGuid($datarray);
$message_id = item_store($datarray);
+ self::sendParticipation($contact, $datarray);
+
if ($message_id) {
logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
return true;
$user['uprvkey'] = $user['prvkey'];
}
- $signature = rsa_sign($signable_data, $user["uprvkey"]);
+ $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
$sig = base64url_encode($signature);
$xmldata = array("me:env" => array("me:data" => $data,
$signed_text = implode(";", $sigmsg);
- return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
+ return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
}
/**
return $return_code;
}
+ /**
+ * @brief sends a participation (Used to get all further updates)
+ *
+ * @param array $contact Target of the communication
+ * @param array $item Item array
+ *
+ * @return int The result of the transmission
+ */
+ private static function sendParticipation($contact, $item)
+ {
+ // Don't send notifications for private postings
+ if ($item['private']) {
+ return;
+ }
+
+ $cachekey = "diaspora:sendParticipation:".$item['guid'];
+
+ $result = Cache::get($cachekey);
+ if (!is_null($result)) {
+ return;
+ }
+
+ // Fetch some user id to have a valid handle to transmit the participation.
+ // In fact it doesn't matter which user sends this - but it is needed by the protocol.
+ // If the item belongs to a user, we take this user id.
+ if ($item['uid'] == 0) {
+ $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
+ $first_user = dba::select('user', ['uid'], $condition, ['limit' => 1]);
+ $owner = User::getOwnerDataById($first_user['uid']);
+ } else {
+ $owner = User::getOwnerDataById($item['uid']);
+ }
+
+ $author = self::myHandle($owner);
+
+ $message = array("author" => $author,
+ "guid" => get_guid(32),
+ "parent_type" => "Post",
+ "parent_guid" => $item["guid"]);
+
+ logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
+
+ // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
+ Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
+
+ return self::buildAndTransmit($owner, $contact, "participation", $message);
+ }
+
/**
* @brief sends an account migration
*
$profile = self::createProfileData($uid);
$signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
- $signature = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
+ $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
$message = array("author" => $old_handle,
"profile" => $profile,
/**
* @brief Adds the header elements to the XML document
*
- * @param object $doc XML document
- * @param array $owner Contact data of the poster
+ * @param object $doc XML document
+ * @param array $owner Contact data of the poster
+ * @param string $filter The related feed filter (activity, posts or comments)
*
* @return object header root element
*/
- private static function addHeader($doc, $owner)
+ private static function addHeader($doc, $owner, $filter)
{
$a = get_app();
$root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
$root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
- $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
+ switch ($filter) {
+ case 'activity': $title = t('%s\'s timeline', $owner['name']); break;
+ case 'posts' : $title = t('%s\'s posts' , $owner['name']); break;
+ case 'comments': $title = t('%s\'s comments', $owner['name']); break;
+ }
+
+ $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION);
XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
- XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
- XML::addElement($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
+ XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
+ XML::addElement($doc, $root, "title", $title);
XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
XML::addElement($doc, $root, "logo", $owner["photo"]);
XML::addElement($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
self::hublinks($doc, $root, $owner["nick"]);
- $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "salmon");
+ $attributes = array("href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon");
XML::addElement($doc, $root, "link", "", $attributes);
- $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
+ $attributes = array("href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
XML::addElement($doc, $root, "link", "", $attributes);
- $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
+ $attributes = array("href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
XML::addElement($doc, $root, "link", "", $attributes);
- $attributes = array("href" => System::baseUrl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
- "rel" => "self", "type" => "application/atom+xml");
+ $attributes = array("href" => System::baseUrl() . "/api/statuses/user_timeline/" . $owner["nick"] . ".atom",
+ "rel" => "self", "type" => "application/atom+xml");
XML::addElement($doc, $root, "link", "", $attributes);
return $root;
}
/**
+ * Creates the XML feed for a given nickname
+ *
+ * Supported filters:
+ * - activity (default): all the public posts
+ * - posts: all the public top-level posts
+ * - comments: all the public replies
+ *
+ * Updates the provided last_update parameter if the result comes from the
+ * cache or it is empty
+ *
* @brief Creates the XML feed for a given nickname
*
- * @param object $a The application class
* @param string $owner_nick Nickname of the feed owner
* @param string $last_update Date of the last update
* @param integer $max_items Number of maximum items to fetch
+ * @param string $filter Feed items filter (activity, posts or comments)
+ * @param boolean $nocache Wether to bypass caching
*
* @return string XML feed
*/
- public static function feed(App $a, $owner_nick, &$last_update, $max_items = 300)
+ public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
{
$stamp = microtime(true);
- $cachekey = "ostatus:feed:".$owner_nick.":".$last_update;
+ $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
$previous_created = $last_update;
$result = Cache::get($cachekey);
- if (!is_null($result)) {
- logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created.' (cached)', LOGGER_DEBUG);
+ if (!$nocache && !is_null($result)) {
+ logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', LOGGER_DEBUG);
$last_update = $result['last_update'];
return $result['feed'];
}
- $r = q(
+ $owner = dba::fetch_first(
"SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
- WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
- dbesc($owner_nick)
+ WHERE `contact`.`self` AND `user`.`nickname` = ? LIMIT 1",
+ $owner_nick
);
- if (!DBM::is_result($r)) {
+ if (!DBM::is_result($owner)) {
return;
}
- $owner = $r[0];
-
if (!strlen($last_update)) {
$last_update = 'now -30 days';
}
$check_date = datetime_convert('UTC', 'UTC', $last_update, 'Y-m-d H:i:s');
$authorid = Contact::getIdForURL($owner["url"], 0);
+ $sql_extra = '';
+ if ($filter === 'posts') {
+ $sql_extra .= ' AND `item`.`id` = `item`.`parent` ';
+ }
+
+ if ($filter === 'comments') {
+ $sql_extra .= sprintf(" AND `item`.`object-type` = '%s' ", dbesc(ACTIVITY_OBJ_COMMENT));
+ }
+
$items = q(
"SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
- WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
- `item`.`author-id` = %d AND `item`.`created` > '%s' AND
- NOT `item`.`deleted` AND NOT `item`.`private` AND
- `thread`.`network` IN ('%s', '%s')
+ WHERE `item`.`uid` = %d
+ AND `item`.`contact-id` = %d
+ AND `item`.`author-id` = %d
+ AND `item`.`created` > '%s'
+ AND NOT `item`.`deleted`
+ AND NOT `item`.`private`
+ AND `thread`.`network` IN ('%s', '%s')
+ $sql_extra
ORDER BY `item`.`created` DESC LIMIT %d",
- intval($owner["uid"]), intval($owner["id"]),
- intval($authorid), dbesc($check_date),
- dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN), intval($max_items)
+ intval($owner["uid"]),
+ intval($owner["id"]),
+ intval($authorid),
+ dbesc($check_date),
+ dbesc(NETWORK_OSTATUS),
+ dbesc(NETWORK_DFRN),
+ intval($max_items)
);
$doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;
- $root = self::addHeader($doc, $owner);
+ $root = self::addHeader($doc, $owner, $filter);
foreach ($items as $item) {
if (Config::get('system', 'ostatus_debug')) {
$msg = array('feed' => $feeddata, 'last_update' => $last_update);
Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
- logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created, LOGGER_DEBUG);
+ logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, LOGGER_DEBUG);
return $feeddata;
}
namespace Friendica\Protocol;
use Friendica\Network\Probe;
+use Friendica\Util\Crypto;
use Friendica\Util\XML;
-require_once 'include/crypto.php';
-
/**
* @brief Salmon Protocol class
* The Salmon Protocol is a message exchange protocol running over HTTP designed to decentralize commentary
$data_type = 'application/atom+xml';
$encoding = 'base64url';
$algorithm = 'RSA-SHA256';
- $keyhash = base64url_encode(hash('sha256', salmon_key($owner['spubkey'])), true);
+ $keyhash = base64url_encode(hash('sha256', self::salmonKey($owner['spubkey'])), true);
$precomputed = '.' . base64url_encode($data_type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($algorithm);
// GNU Social format
- $signature = base64url_encode(rsa_sign($data . $precomputed, $owner['sprvkey']));
+ $signature = base64url_encode(Crypto::rsaSign($data . $precomputed, $owner['sprvkey']));
// Compliant format
- $signature2 = base64url_encode(rsa_sign(str_replace('=', '', $data . $precomputed), $owner['sprvkey']));
+ $signature2 = base64url_encode(Crypto::rsaSign(str_replace('=', '', $data . $precomputed), $owner['sprvkey']));
// Old Status.net format
- $signature3 = base64url_encode(rsa_sign($data, $owner['sprvkey']));
+ $signature3 = base64url_encode(Crypto::rsaSign($data, $owner['sprvkey']));
// At first try the non compliant method that works for GNU Social
$xmldata = array("me:env" => array("me:data" => $data,
return (($return_code >= 200) && ($return_code < 300)) ? 0 : 1;
}
+
+ /**
+ * @param string $pubkey public key
+ * @return string
+ */
+ public static function salmonKey($pubkey)
+ {
+ Crypto::pemToMe($pubkey, $m, $e);
+ return 'RSA' . '.' . base64url_encode($m, true) . '.' . base64url_encode($e, true);
+ }
}
--- /dev/null
+<?php
+/**
+ * @file src/Util/Crypto.php
+ */
+namespace Friendica\Util;
+
+use Friendica\Core\Config;
+use ASN_BASE;
+use ASNValue;
+
+require_once 'library/ASNValue.class.php';
+require_once 'library/asn1.php';
+
+/**
+ * @brief Crypto class
+ */
+class Crypto
+{
+ // supported algorithms are 'sha256', 'sha1'
+ /**
+ * @param string $data data
+ * @param string $key key
+ * @param string $alg algorithm
+ * @return string
+ */
+ public static function rsaSign($data, $key, $alg = 'sha256')
+ {
+ openssl_sign($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
+ return $sig;
+ }
+
+ /**
+ * @param string $data data
+ * @param string $sig signature
+ * @param string $key key
+ * @param string $alg algorithm
+ * @return boolean
+ */
+ public static function rsaVerify($data, $sig, $key, $alg = 'sha256')
+ {
+ return openssl_verify($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
+ }
+
+ /**
+ * @param string $Der der formatted string
+ * @param string $Private key type optional, default false
+ * @return string
+ */
+ private static function DerToPem($Der, $Private = false)
+ {
+ //Encode:
+ $Der = base64_encode($Der);
+ //Split lines:
+ $lines = str_split($Der, 65);
+ $body = implode("\n", $lines);
+ //Get title:
+ $title = $Private ? 'RSA PRIVATE KEY' : 'PUBLIC KEY';
+ //Add wrapping:
+ $result = "-----BEGIN {$title}-----\n";
+ $result .= $body . "\n";
+ $result .= "-----END {$title}-----\n";
+
+ return $result;
+ }
+
+ /**
+ * @param string $Der der formatted string
+ * @return string
+ */
+ private static function DerToRsa($Der)
+ {
+ //Encode:
+ $Der = base64_encode($Der);
+ //Split lines:
+ $lines = str_split($Der, 64);
+ $body = implode("\n", $lines);
+ //Get title:
+ $title = 'RSA PUBLIC KEY';
+ //Add wrapping:
+ $result = "-----BEGIN {$title}-----\n";
+ $result .= $body . "\n";
+ $result .= "-----END {$title}-----\n";
+
+ return $result;
+ }
+
+ /**
+ * @param string $Modulus modulo
+ * @param string $PublicExponent exponent
+ * @return string
+ */
+ private static function pkcs8Encode($Modulus, $PublicExponent)
+ {
+ //Encode key sequence
+ $modulus = new ASNValue(ASNValue::TAG_INTEGER);
+ $modulus->SetIntBuffer($Modulus);
+ $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
+ $publicExponent->SetIntBuffer($PublicExponent);
+ $keySequenceItems = array($modulus, $publicExponent);
+ $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
+ $keySequence->SetSequence($keySequenceItems);
+ //Encode bit string
+ $bitStringValue = $keySequence->Encode();
+ $bitStringValue = chr(0x00) . $bitStringValue; //Add unused bits byte
+ $bitString = new ASNValue(ASNValue::TAG_BITSTRING);
+ $bitString->Value = $bitStringValue;
+ //Encode body
+ $bodyValue = "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00" . $bitString->Encode();
+ $body = new ASNValue(ASNValue::TAG_SEQUENCE);
+ $body->Value = $bodyValue;
+ //Get DER encoded public key:
+ $PublicDER = $body->Encode();
+ return $PublicDER;
+ }
+
+ /**
+ * @param string $Modulus modulo
+ * @param string $PublicExponent exponent
+ * @return string
+ */
+ private static function pkcs1Encode($Modulus, $PublicExponent)
+ {
+ //Encode key sequence
+ $modulus = new ASNValue(ASNValue::TAG_INTEGER);
+ $modulus->SetIntBuffer($Modulus);
+ $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
+ $publicExponent->SetIntBuffer($PublicExponent);
+ $keySequenceItems = array($modulus, $publicExponent);
+ $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
+ $keySequence->SetSequence($keySequenceItems);
+ //Encode bit string
+ $bitStringValue = $keySequence->Encode();
+ return $bitStringValue;
+ }
+
+ /**
+ * @param string $m modulo
+ * @param string $e exponent
+ * @return string
+ */
+ public static function meToPem($m, $e)
+ {
+ $der = self::pkcs8Encode($m, $e);
+ $key = self::DerToPem($der, false);
+ return $key;
+ }
+
+ /**
+ * @param string $key key
+ * @param string $m modulo reference
+ * @param object $e exponent reference
+ * @return void
+ */
+ private static function pubRsaToMe($key, &$m, &$e)
+ {
+ $lines = explode("\n", $key);
+ unset($lines[0]);
+ unset($lines[count($lines)]);
+ $x = base64_decode(implode('', $lines));
+
+ $r = ASN_BASE::parseASNString($x);
+
+ $m = base64url_decode($r[0]->asnData[0]->asnData);
+ $e = base64url_decode($r[0]->asnData[1]->asnData);
+ }
+
+ /**
+ * @param string $key key
+ * @return string
+ */
+ public static function rsaToPem($key)
+ {
+ self::pubRsaToMe($key, $m, $e);
+ return self::meToPem($m, $e);
+ }
+
+ /**
+ * @param string $key key
+ * @return string
+ */
+ private static function pemToRsa($key)
+ {
+ self::pemToMe($key, $m, $e);
+ return self::meToRsa($m, $e);
+ }
+
+ /**
+ * @param string $key key
+ * @param string $m modulo reference
+ * @param string $e exponent reference
+ * @return void
+ */
+ public static function pemToMe($key, &$m, &$e)
+ {
+ $lines = explode("\n", $key);
+ unset($lines[0]);
+ unset($lines[count($lines)]);
+ $x = base64_decode(implode('', $lines));
+
+ $r = ASN_BASE::parseASNString($x);
+
+ $m = base64url_decode($r[0]->asnData[1]->asnData[0]->asnData[0]->asnData);
+ $e = base64url_decode($r[0]->asnData[1]->asnData[0]->asnData[1]->asnData);
+ }
+
+ /**
+ * @param string $m modulo
+ * @param string $e exponent
+ * @return string
+ */
+ private static function meToRsa($m, $e)
+ {
+ $der = self::pkcs1Encode($m, $e);
+ $key = self::DerToRsa($der);
+ return $key;
+ }
+
+ /**
+ * @param integer $bits number of bits
+ * @return mixed
+ */
+ public static function newKeypair($bits)
+ {
+ $openssl_options = array(
+ 'digest_alg' => 'sha1',
+ 'private_key_bits' => $bits,
+ 'encrypt_key' => false
+ );
+
+ $conf = Config::get('system', 'openssl_conf_file');
+ if ($conf) {
+ $openssl_options['config'] = $conf;
+ }
+ $result = openssl_pkey_new($openssl_options);
+
+ if (empty($result)) {
+ logger('new_keypair: failed');
+ return false;
+ }
+
+ // Get private key
+ $response = array('prvkey' => '', 'pubkey' => '');
+
+ openssl_pkey_export($result, $response['prvkey']);
+
+ // Get public key
+ $pkey = openssl_pkey_get_details($result);
+ $response['pubkey'] = $pkey["key"];
+
+ return $response;
+ }
+}
$lockpath = Config::get('jabber', 'lockpath');
if (is_null($lockpath)) {
+ $this->writeLog(LOG_INFO, 'No lockpath defined.');
return;
}
// Now it is safe to create the pid file
PidFile::create($file);
+ if (!file_exists($file)) {
+ $this->writeLog(LOG_WARNING, 'Logfile ' . $file . " couldn't be created.");
+ }
}
/**
}
}
if ($relay_to_owner) {
- logger('notifier: followup '.$target_item["guid"], LOGGER_DEBUG);
// local followup to remote post
$followup = true;
$public_message = false; // not public
$recipients = array($parent['contact-id']);
$recipients_followup = array($parent['contact-id']);
+ logger('notifier: followup '.$target_item["guid"].' to '.$conversant_str, LOGGER_DEBUG);
+
//if (!$target_item['private'] && $target_item['wall'] &&
if (!$target_item['private'] &&
(strlen($target_item['allow_cid'].$target_item['allow_gid'].
logger("Generate feed of user ".$rr['nickname']." to ".$rr['callback_url']." - last updated ".$rr['last_update'], LOGGER_DEBUG);
$last_update = $rr['last_update'];
- $params = OStatus::feed($a, $rr['nickname'], $last_update);
+ $params = OStatus::feed($rr['nickname'], $last_update);
if (!$params) {
return;
<?php
-define('UPDATE_VERSION' , 1238);
-
use Friendica\Core\Config;
use Friendica\Core\PConfig;
use Friendica\Core\Worker;
*
* update.php - automatic system update
*
- * Automatically update database schemas and any other development changes such that
- * copying the latest files from the source code repository will always perform a clean
- * and painless upgrade.
- *
- * Each function in this file is named update_nnnn() where nnnn is an increasing number
- * which began counting at 1000.
+ * This function is responsible for doing post update changes to the data
+ * (not the structure) in the database.
*
- * At the top of the file "boot.php" is a define for DB_UPDATE_VERSION. Any time there is a change
- * to the database schema or one which requires an upgrade path from the existing application,
- * the DB_UPDATE_VERSION and the UPDATE_VERSION at the top of this file are incremented.
+ * Database structure changes are done in src/Database/DBStructure.php
*
- * The current DB_UPDATE_VERSION is stored in the config area of the database. If the application starts up
- * and DB_UPDATE_VERSION is greater than the last stored build number, we will process every update function
- * in order from the currently stored value to the new DB_UPDATE_VERSION. This is expected to bring the system
- * up to current without requiring re-installation or manual intervention.
+ * If there is a need for a post process to a structure change, update this file
+ * by adding a new function at the end with the number of the new DB_UPDATE_VERSION.
*
- * Once the upgrade functions have completed, the current DB_UPDATE_VERSION is stored as the current value.
- * The DB_UPDATE_VERSION will always be one greater than the last numbered script in this file.
+ * The numbered script in this file has to be exactly like the DB_UPDATE_VERSION
*
- * If you change the database schema, the following are required:
- * 1. Update the file src/Database/DBStructure.php to match the new schema.
- * 2. If there is a need for a post procession, update this file by adding a new function at the end with the number of the current DB_UPDATE_VERSION.
- * This function should perform some post procession steps but no database updates.
- * 3. Increment the DB_UPDATE_VERSION in boot.php *AND* the UPDATE_VERSION in this file to match it
- * 4. TEST the upgrade prior to checkin and filing a pull request.
+ * Example:
+ * You are currently on version 4711 and you are preparing changes that demand an update script.
*
- * IMPORTANT!
- * NEVER do a database change anymore in the update functions! Only do this in the file src/Database/DBStructure.php!
+ * 1. Create a function "update_4712()" here in the update.php
+ * 2. Apply the needed structural changes in src/Database/DBStructure.php
+ * 3. Set DB_UPDATE_VERSION in boot.php to 4712.
*/
+function update_1178() {
+ require_once 'mod/profiles.php';
+ $profiles = q("SELECT `uid`, `about`, `locality`, `pub_keywords`, `gender` FROM `profile` WHERE `is-default`");
-function update_1000() {
-
- q("ALTER TABLE `item` DROP `like`, DROP `dislike` ");
-
- q("ALTER TABLE `item` ADD `verb` CHAR( 255 ) NOT NULL AFTER `body` ,
- ADD `object-type` CHAR( 255 ) NOT NULL AFTER `verb` ,
- ADD `object` TEXT NOT NULL AFTER `object-type` ");
-
- q("ALTER TABLE `intro` ADD `duplex` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `knowyou` ");
- q("ALTER TABLE `contact` ADD `duplex` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `rel` ");
- q("ALTER TABLE `contact` CHANGE `issued-pubkey` `issued-pubkey` TEXTCHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL");
- q("ALTER TABLE `contact` ADD `term-date` DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00' AFTER `avatar-date`");
-}
-
-function update_1001() {
- q("ALTER TABLE `item` ADD `wall` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `type` ");
- q("ALTER TABLE `item` ADD INDEX ( `wall` )");
-}
-
-function update_1002() {
- q("ALTER TABLE `item` ADD `gravity` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `wall` ");
-}
-
-function update_1003() {
- q("ALTER TABLE `contact` DROP `issued-pubkey` , DROP `ret-id` , DROP `ret-pubkey` ");
- q("ALTER TABLE `contact` ADD `usehub` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `ret-aes`");
- q("ALTER TABLE `contact` ADD `hub-verify` CHAR( 255 ) NOT NULL AFTER `usehub`");
- q("ALTER TABLE `contact` ADD INDEX ( `uid` ) , ADD INDEX ( `self` ), ADD INDEX ( `issued-id` ), ADD INDEX ( `dfrn-id` )");
- q("ALTER TABLE `contact` ADD INDEX ( `blocked` ), ADD INDEX ( `readonly` )");
-}
-
-function update_1004() {
- q("ALTER TABLE `contact` ADD `subhub` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `usehub`");
-}
-
-function update_1005() {
-
- q("ALTER TABLE `user` ADD `spubkey` TEXT NOT NULL AFTER `prvkey` ,
- ADD `sprvkey` TEXT NOT NULL AFTER `spubkey`");
-
-}
-
-function update_1006() {
-
- // create 's' keys for everybody that does not have one
-
- $r = q("SELECT * FROM `user` WHERE `spubkey` = '' ");
- if (DBM::is_result($r)) {
- foreach ($r as $rr) {
- $sres=openssl_pkey_new(array('encrypt_key' => false ));
- $sprvkey = '';
- openssl_pkey_export($sres, $sprvkey);
- $spkey = openssl_pkey_get_details($sres);
- $spubkey = $spkey["key"];
- $r = q("UPDATE `user` SET `spubkey` = '%s', `sprvkey` = '%s'
- WHERE `uid` = %d",
- dbesc($spubkey),
- dbesc($sprvkey),
- intval($rr['uid'])
- );
- }
- }
-}
-
-function update_1007() {
- q("ALTER TABLE `user` ADD `page-flags` INT NOT NULL DEFAULT '0' AFTER `notify-flags`");
- q("ALTER TABLE `user` ADD INDEX ( `nickname` )");
-}
-
-function update_1008() {
- q("ALTER TABLE `profile` ADD `with` TEXT NOT NULL AFTER `marital` ");
-}
-
-function update_1009() {
- q("ALTER TABLE `user` ADD `allow_location` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `default-location` ");
-}
-
-function update_1010() {
- q("ALTER TABLE `contact` ADD `lrdd` CHAR( 255 ) NOT NULL AFTER `url` ");
-}
-
-function update_1011() {
- q("ALTER TABLE `contact` ADD `nick` CHAR( 255 ) NOT NULL AFTER `name` ");
- $r = q("SELECT * FROM `contact` WHERE 1");
- if (DBM::is_result($r)) {
- foreach ($r as $rr) {
- q("UPDATE `contact` SET `nick` = '%s' WHERE `id` = %d",
- dbesc(basename($rr['url'])),
- intval($rr['id'])
- );
- }
- }
-}
-
-function update_1012() {
- q("ALTER TABLE `item` ADD `inform` MEDIUMTEXT NOT NULL AFTER `tag` ");
-}
-
-function update_1013() {
- q("ALTER TABLE `item` ADD `target-type` CHAR( 255 ) NOT NULL
- AFTER `object` , ADD `target` TEXT NOT NULL AFTER `target-type`");
-}
-
-function update_1014()
-{
- q("ALTER TABLE `contact` ADD `micro` TEXT NOT NULL AFTER `thumb` ");
- $r = q("SELECT * FROM `photo` WHERE `scale` = 4");
- if (DBM::is_result($r)) {
- foreach ($r as $rr) {
- $Image = new Image($rr['data']);
- if ($Image->isValid()) {
- $Image->scaleDown(48);
- Photo::store($Image, $rr['uid'],$rr['contact-id'],$rr['resource-id'],$rr['filename'],$rr['album'],6,(($rr['profile']) ? 1 : 0));
- }
- }
- }
- $r = q("SELECT * FROM `contact` WHERE 1");
- if (DBM::is_result($r)) {
- foreach ($r as $rr) {
- if(stristr($rr['thumb'],'avatar'))
- q("UPDATE `contact` SET `micro` = '%s' WHERE `id` = %d",
- dbesc(str_replace('avatar','micro',$rr['thumb'])),
- intval($rr['id']));
- else
- q("UPDATE `contact` SET `micro` = '%s' WHERE `id` = %d",
- dbesc(str_replace('5.jpg','6.jpg',$rr['thumb'])),
- intval($rr['id']));
- }
- }
-}
-
-function update_1015() {
- q("ALTER TABLE `item` CHANGE `body` `body` mediumtext NOT NULL");
-}
-
-function update_1016() {
- q("ALTER TABLE `user` ADD `openid` CHAR( 255 ) NOT NULL AFTER `email` ");
-}
-
-function update_1017() {
-
- q(" CREATE TABLE IF NOT EXISTS `clients` (
-`client_id` VARCHAR( 20 ) NOT NULL ,
-`pw` VARCHAR( 20 ) NOT NULL ,
-`redirect_uri` VARCHAR( 200 ) NOT NULL ,
-PRIMARY KEY ( `client_id` )
-) ENGINE = MYISAM DEFAULT CHARSET=utf8 ");
-
- q(" CREATE TABLE IF NOT EXISTS `tokens` (
-`id` VARCHAR( 40 ) NOT NULL ,
-`client_id` VARCHAR( 20 ) NOT NULL ,
-`expires` INT NOT NULL ,
-`scope` VARCHAR( 200 ) NOT NULL ,
-PRIMARY KEY ( `id` )
-) ENGINE = MYISAM DEFAULT CHARSET=utf8 ");
-
- q("CREATE TABLE IF NOT EXISTS `auth_codes` (
-`id` VARCHAR( 40 ) NOT NULL ,
-`client_id` VARCHAR( 20 ) NOT NULL ,
-`redirect_uri` VARCHAR( 200 ) NOT NULL ,
-`expires` INT NOT NULL ,
-`scope` VARCHAR( 250 ) NOT NULL ,
-PRIMARY KEY ( `id` )
-) ENGINE = MYISAM DEFAULT CHARSET=utf8 ");
-
-}
-
-function update_1018() {
- q("CREATE TABLE IF NOT EXISTS `queue` (
-`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
-`cid` INT NOT NULL ,
-`created` DATETIME NOT NULL ,
-`last` DATETIME NOT NULL ,
-`content` MEDIUMTEXT NOT NULL
-) ENGINE = MYISAM DEFAULT CHARSET=utf8 ");
-}
-
-function update_1019() {
- q("ALTER TABLE `mail` DROP `delivered`");
- q("ALTER TABLE `profile` ADD `showwith` TINYINT(1) NOT NULL DEFAULT '0' AFTER `marital` ");
-}
-
-function update_1020() {
- q("ALTER TABLE `profile` DROP `showwith`");
- q("ALTER TABLE `item` ADD `thr-parent` CHAR( 255 ) NOT NULL AFTER `parent-uri` ");
-}
-
-function update_1021() {
- q("ALTER TABLE `profile_check` ADD `sec` CHAR( 255 ) NOT NULL AFTER `dfrn_id` ");
- q("ALTER TABLE `profile_check` ADD `cid` INT(10) unsigned NOT NULL DEFAULT '0' AFTER `uid`");
- q("ALTER TABLE `item` ADD `private` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `deny_gid` ");
-}
-
-function update_1022() {
- q("CREATE TABLE `pconfig` (
- `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `uid` INT NOT NULL DEFAULT '0',
- `cat` CHAR( 255 ) NOT NULL ,
- `k` CHAR( 255 ) NOT NULL ,
- `v` MEDIUMTEXT NOT NULL
- ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci ");
-}
-
-function update_1023() {
- q("ALTER TABLE `user` ADD `register_date` DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00' AFTER `timezone` ,
- ADD `login_date` DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00' AFTER `register_date` ");
-}
-
-function update_1024() {
- q("ALTER TABLE `profile` ADD `keywords` TEXT NOT NULL AFTER `religion` ");
-}
-
-function update_1025() {
- q("ALTER TABLE `user` ADD `maxreq` int(11) NOT NULL DEFAULT '10' AFTER `pwdreset` ");
-}
-
-function update_1026() {
- q("CREATE TABLE IF NOT EXISTS `hook` (
- `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `hook` CHAR( 255 ) NOT NULL ,
- `file` CHAR( 255 ) NOT NULL ,
- `function` CHAR( 255 ) NOT NULL
- ) ENGINE = MYISAM DEFAULT CHARSET=utf8 ");
-}
-
-
-function update_1027() {
- q("CREATE TABLE IF NOT EXISTS `addon` (
- `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `name` CHAR( 255 ) NOT NULL ,
- `version` CHAR( 255 ) NOT NULL ,
- `installed` TINYINT( 1 ) NOT NULL DEFAULT '0'
- ) ENGINE = MYISAM DEFAULT CHARSET=utf8 ");
-}
-
-function update_1028() {
- q("ALTER TABLE `user` ADD `openidserver` text NOT NULL AFTER `deny_gid` ");
-}
-
-function update_1029() {
- q("ALTER TABLE `contact` ADD `info` MEDIUMTEXT NOT NULL AFTER `reason` ");
-}
-
-function update_1030() {
- q("ALTER TABLE `contact` ADD `bdyear` CHAR( 4 ) NOT NULL COMMENT 'birthday notify flag' AFTER `profile-id` ");
-
- q("CREATE TABLE IF NOT EXISTS `event` (
- `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `uid` INT NOT NULL ,
- `cid` INT NOT NULL ,
- `created` DATETIME NOT NULL ,
- `edited` DATETIME NOT NULL ,
- `start` DATETIME NOT NULL ,
- `finish` DATETIME NOT NULL ,
- `desc` TEXT NOT NULL ,
- `location` TEXT NOT NULL ,
- `type` CHAR( 255 ) NOT NULL ,
- `adjust` TINYINT( 1 ) NOT NULL DEFAULT '1',
- `allow_cid` MEDIUMTEXT NOT NULL ,
- `allow_gid` MEDIUMTEXT NOT NULL ,
- `deny_cid` MEDIUMTEXT NOT NULL ,
- `deny_gid` MEDIUMTEXT NOT NULL
- ) ENGINE = MYISAM DEFAULT CHARSET=utf8 ");
-
-
-}
-
-function update_1031() {
- // Repair any bad links that slipped into the item table
- $r = q("SELECT `id`, `object` FROM `item` WHERE `object` != '' ");
- if (DBM::is_result($r)) {
- foreach ($r as $rr) {
- if (strstr($rr['object'],'type="http')) {
- q("UPDATE `item` SET `object` = '%s' WHERE `id` = %d",
- dbesc(str_replace('type="http','href="http',$rr['object'])),
- intval($rr['id'])
- );
- }
- }
- }
-}
-
-function update_1032() {
- q("ALTER TABLE `profile` ADD `pdesc` CHAR( 255 ) NOT NULL AFTER `name` ");
-}
-
-function update_1033() {
- q("CREATE TABLE IF NOT EXISTS `cache` (
- `k` CHAR( 255 ) NOT NULL PRIMARY KEY ,
- `v` TEXT NOT NULL,
- `updated` DATETIME NOT NULL
- ) DEFAULT CHARSET=utf8 ");
-}
-
-
-function update_1034() {
-
- /*
- * If you have any of these parent-less posts they can cause problems, and
- * we need to delete them. You can't see them anyway.
- * Legitimate items will usually get re-created on the next
- * pull from the hub.
- * But don't get rid of a post that may have just come in
- * and may not yet have the parent id set.
- */
- q("DELETE FROM `item` WHERE `parent` = 0 AND `created` < UTC_TIMESTAMP() - INTERVAL 2 MINUTE");
-
-}
-
-
-function update_1035() {
-
- q("ALTER TABLE `contact` ADD `success_update` DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00' AFTER `last-update` ");
-
-}
-
-function update_1036() {
-
- $r = dbq("SELECT * FROM `contact` WHERE `network` = 'dfrn' AND `photo` LIKE '%include/photo%' ");
- if (DBM::is_result($r)) {
- foreach ($r as $rr) {
- q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `id` = %d",
- dbesc(str_replace('include/photo','photo',$rr['photo'])),
- dbesc(str_replace('include/photo','photo',$rr['thumb'])),
- dbesc(str_replace('include/photo','photo',$rr['micro'])),
- intval($rr['id']));
- }
- }
-}
-
-function update_1037() {
-
- q("ALTER TABLE `contact` CHANGE `lrdd` `alias` CHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ");
-
-}
-
-function update_1038() {
- q("ALTER TABLE `item` ADD `plink` CHAR( 255 ) NOT NULL AFTER `target` ");
-}
-
-function update_1039() {
- q("ALTER TABLE `addon` ADD `timestamp` BIGINT NOT NULL DEFAULT '0'");
-}
-
-
-function update_1040() {
-
- q("CREATE TABLE IF NOT EXISTS `fcontact` (
- `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `url` CHAR( 255 ) NOT NULL ,
- `name` CHAR( 255 ) NOT NULL ,
- `photo` CHAR( 255 ) NOT NULL
- ) ENGINE = MYISAM DEFAULT CHARSET=utf8 ");
-
- q("CREATE TABLE IF NOT EXISTS `ffinder` (
- `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `uid` INT UNSIGNED NOT NULL ,
- `cid` INT UNSIGNED NOT NULL ,
- `fid` INT UNSIGNED NOT NULL
- ) ENGINE = MYISAM DEFAULT CHARSET=utf8 ");
-
-}
-
-function update_1041() {
- q("ALTER TABLE `profile` CHANGE `keywords` `prv_keywords` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ");
- q("ALTER TABLE `profile` ADD `pub_keywords` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL AFTER `religion` ");
-}
-
-function update_1042() {
- q("ALTER TABLE `user` ADD `expire` INT UNSIGNED NOT NULL DEFAULT '0' AFTER `maxreq` ");
-}
-
-
-function update_1043() {
- q("ALTER TABLE `user` ADD `blockwall` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `blocked` ");
-}
-
-function update_1044() {
- q("ALTER TABLE `profile` ADD FULLTEXT ( `pub_keywords` ) ");
- q("ALTER TABLE `profile` ADD FULLTEXT ( `prv_keywords` ) ");
-}
-
-function update_1045() {
- q("ALTER TABLE `user` ADD `language` CHAR( 16 ) NOT NULL DEFAULT 'en' AFTER `timezone` ");
-}
-
-function update_1046() {
- q("ALTER TABLE `item` ADD `attach` MEDIUMTEXT NOT NULL AFTER `tag` ");
-}
-
-function update_1047() {
- q("ALTER TABLE `contact` ADD `writable` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `readonly` ");
-}
-
-function update_1048() {
- q("UPDATE `contact` SET `writable` = 1 WHERE `network` = 'stat' AND `notify` != '' ");
-}
-
-function update_1049() {
- q("CREATE TABLE `mailacct` (
- `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `uid` INT NOT NULL,
- `server` CHAR( 255 ) NOT NULL ,
- `user` CHAR( 255 ) NOT NULL ,
- `pass` CHAR( 255 ) NOT NULL ,
- `reply_to` CHAR( 255 ) NOT NULL ,
- `last_check` DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00'
- ) ENGINE = MYISAM ");
-}
-
-function update_1050() {
- q("CREATE TABLE `attach` (
- `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `uid` INT NOT NULL ,
- `filetype` CHAR( 64 ) NOT NULL ,
- `filesize` INT NOT NULL ,
- `data` LONGBLOB NOT NULL ,
- `created` DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00',
- `edited` DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00',
- `allow_cid` MEDIUMTEXT NOT NULL ,
- `allow_gid` MEDIUMTEXT NOT NULL ,
- `deny_cid` MEDIUMTEXT NOT NULL ,
- `deny_gid` MEDIUMTEXT NOT NULL
- ) ENGINE = MYISAM ");
-
-}
-
-function update_1051() {
- q("ALTER TABLE `mailacct` ADD `port` INT NOT NULL AFTER `server` ,
- ADD `ssltype` CHAR( 16 ) NOT NULL AFTER `port` ,
- ADD `mailbox` CHAR( 255 ) NOT NULL AFTER `ssltype` ");
-
- q("ALTER TABLE `contact` ADD `addr` CHAR( 255 ) NOT NULL AFTER `url` ");
-}
-
-function update_1052() {
- q("ALTER TABLE `mailacct` CHANGE `pass` `pass` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL");
- q("ALTER TABLE `mailacct` ADD `pubmail` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `reply_to` ");
- q("ALTER TABLE `item` ADD `pubmail` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `private` ");
-}
-
-
-function update_1053() {
- q("ALTER TABLE `item` ADD `extid` CHAR( 255 ) NOT NULL AFTER `parent-uri` , ADD INDEX ( `extid` ) ");
-}
-
-function update_1054() {
- q("ALTER TABLE `register` ADD `language` CHAR( 16 ) NOT NULL AFTER `password` ");
-}
-
-function update_1055() {
- q("ALTER TABLE `profile` ADD `hidewall` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `hide-friends` ");
-}
-
-function update_1056() {
- q("ALTER TABLE `attach` ADD `hash` CHAR( 64 ) NOT NULL AFTER `uid` ");
-}
-
-function update_1057() {
- q("ALTER TABLE `attach` ADD `filename` CHAR( 255 ) NOT NULL AFTER `hash` ");
-}
-
-function update_1058() {
- q("ALTER TABLE `item` ADD `event-id` INT NOT NULL AFTER `resource-id` ");
-}
-
-function update_1059() {
- q("ALTER TABLE `queue` ADD `network` CHAR( 32 ) NOT NULL AFTER `cid` ");
-}
-
-function update_1060() {
- q("ALTER TABLE `event` ADD `uri` CHAR( 255 ) NOT NULL AFTER `cid` ");
-}
-
-function update_1061() {
- q("ALTER TABLE `event` ADD `nofinish` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `type` ");
-}
-
-function update_1062() {
- q("ALTER TABLE `user` ADD `prvnets` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `page-flags` ");
-}
-function update_1063() {
- q("ALTER TABLE `addon` ADD `plugin_admin` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `timestamp` ");
-}
-
-function update_1064() {
- q("ALTER TABLE `item` ADD `app` CHAR( 255 ) NOT NULL AFTER `body` ");
-}
-
-function update_1065() {
- q("ALTER TABLE `intro` ADD `fid` INT NOT NULL DEFAULT '0' AFTER `uid`");
-}
-
-function update_1066() {
- $r = q("ALTER TABLE `item` ADD `received` DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00' AFTER `edited` ");
- if($r)
- q("ALTER TABLE `item` ADD INDEX ( `received` ) ");
-
- $r = q("UPDATE `item` SET `received` = `edited` WHERE 1");
-}
-
-function update_1067() {
- q("ALTER TABLE `ffinder` ADD `type` CHAR( 16 ) NOT NULL AFTER `id` ,
- ADD `note` TEXT NOT NULL AFTER `type` ");
-}
-
-function update_1068() {
- // 1067 was short-sighted. Undo it.
- q("ALTER TABLE `ffinder` DROP `type` , DROP `note` ");
-
- // and do this instead.
-
- q("CREATE TABLE IF NOT EXISTS `fsuggest` (
- `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `uid` INT NOT NULL ,
- `cid` INT NOT NULL ,
- `name` CHAR( 255 ) NOT NULL ,
- `url` CHAR( 255 ) NOT NULL ,
- `photo` CHAR( 255 ) NOT NULL ,
- `note` TEXT NOT NULL ,
- `created` DATETIME NOT NULL
- ) ENGINE = MYISAM DEFAULT CHARSET=utf8");
-
-}
-
-function update_1069() {
- q("ALTER TABLE `fsuggest` ADD `request` CHAR( 255 ) NOT NULL AFTER `url` ");
- q("ALTER TABLE `fcontact` ADD `request` CHAR( 255 ) NOT NULL AFTER `photo` ");
-}
-
-// mail body needs to accomodate private photos
-
-function update_1070() {
- q("ALTER TABLE `mail` CHANGE `body` `body` MEDIUMTEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ");
-}
-
-function update_1071() {
- q("ALTER TABLE `photo` ADD INDEX ( `uid` ) ");
- q("ALTER TABLE `photo` ADD INDEX ( `resource-id` ) ");
- q("ALTER TABLE `photo` ADD INDEX ( `album` ) ");
- q("ALTER TABLE `photo` ADD INDEX ( `scale` ) ");
- q("ALTER TABLE `photo` ADD INDEX ( `profile` ) ");
-
-}
-
-function update_1072() {
- q("ALTER TABLE `item` ADD `starred` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `visible` ");
- q("ALTER TABLE `item` ADD INDEX ( `starred` ) ");
-}
-
-function update_1073() {
- q("ALTER TABLE `contact` ADD `remote_self` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `self` ");
-}
-
-function update_1074() {
- q("ALTER TABLE `user` ADD `hidewall` TINYINT( 1) NOT NULL DEFAULT '0' AFTER `blockwall` ");
- $r = q("SELECT `uid` FROM `profile` WHERE `is-default` = 1 AND `hidewall` = 1");
- if (DBM::is_result($r)) {
- foreach($r as $rr)
- q("UPDATE `user` SET `hidewall` = 1 WHERE `uid` = %d",
- intval($rr['uid'])
- );
- }
- q("ALTER TABLE `profile` DROP `hidewall`");
-}
+ foreach ($profiles AS $profile) {
+ if ($profile["about"].$profile["locality"].$profile["pub_keywords"].$profile["gender"] == "")
+ continue;
-function update_1075() {
- q("ALTER TABLE `user` ADD `guid` CHAR( 16 ) NOT NULL AFTER `uid` ");
- $r = q("SELECT `uid` FROM `user` WHERE 1");
- if (DBM::is_result($r)) {
- foreach ($r as $rr) {
- $found = true;
- do {
- $guid = random_string(16);
- $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
- dbesc($guid)
- );
- if(! count($x))
- $found = false;
- } while ($found == true );
+ $profile["pub_keywords"] = profile_clean_keywords($profile["pub_keywords"]);
- q("UPDATE `user` SET `guid` = '%s' WHERE `uid` = %d",
- dbesc($guid),
- intval($rr['uid'])
+ $r = q("UPDATE `contact` SET `about` = '%s', `location` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `self` AND `uid` = %d",
+ dbesc($profile["about"]),
+ dbesc($profile["locality"]),
+ dbesc($profile["pub_keywords"]),
+ dbesc($profile["gender"]),
+ intval($profile["uid"])
);
- }
}
}
-function update_1076() {
- q("CREATE TABLE `guid` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `guid` CHAR( 16 ) NOT NULL , INDEX ( `guid` ) ) ENGINE = MYISAM ");
-
-}
-
-// There was a typo in 1076 so we'll try again in 1077 to make sure
-// We'll also make it big enough to allow for future growth, I seriously
-// doubt Diaspora will be able to leave guids at 16 bytes,
-// and we can also use the same structure for our own larger guids
-
-function update_1077() {
- q("CREATE TABLE IF NOT EXISTS `guid` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `guid` CHAR( 16 ) NOT NULL , INDEX ( `guid` ) ) ENGINE = MYISAM ");
-
- q("ALTER TABLE `guid` CHANGE `guid` `guid` CHAR( 64 ) NOT NULL");
-}
-
-function update_1078() {
- q("ALTER TABLE `item` ADD `guid` CHAR( 64 ) NOT NULL AFTER `id` , ADD INDEX ( `guid` ) ");
-}
-
-function update_1079() {
- q("CREATE TABLE IF NOT EXISTS `sign` (
- `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `iid` INT UNSIGNED NOT NULL ,
- `signed_text` MEDIUMTEXT NOT NULL ,
- `signature` TEXT NOT NULL ,
- `signer` CHAR( 255 ) NOT NULL ,
- INDEX ( `iid` )
- ) ENGINE = MYISAM ");
-
- q("ALTER TABLE `fcontact` ADD `nick` CHAR( 255 ) NOT NULL ,
- ADD `addr` CHAR( 255 ) NOT NULL ,
- ADD `notify` CHAR( 255 ) NOT NULL ,
- ADD `poll` CHAR( 255 ) NOT NULL ,
- ADD `confirm` CHAR( 255 ) NOT NULL ,
- ADD `priority` TINYINT( 1 ) NOT NULL ,
- ADD `network` CHAR( 32 ) NOT NULL ,
- ADD `alias` CHAR( 255 ) NOT NULL ,
- ADD `pubkey` TEXT NOT NULL ,
- ADD INDEX ( `addr` ) ,
- ADD INDEX ( `network` ) ");
-
-}
-
-function update_1080() {
- q("ALTER TABLE `fcontact` ADD `updated` DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00'");
-}
-
-function update_1081() {
- // there was a typo in update 1081 so it was corrected and moved up to 1082
-}
-
-function update_1082() {
- q("ALTER TABLE `photo` ADD `guid` CHAR( 64 ) NOT NULL AFTER `contact-id`,
- ADD INDEX ( `guid` ) ");
- // make certain the following code is only executed once
- $r = q("select `id` from `photo` where `guid` != '' limit 1");
- if (DBM::is_result($r))
- return;
- $r = q("SELECT distinct(`resource-id`) FROM `photo` WHERE 1 group by `id`");
- if (DBM::is_result($r)) {
- foreach ($r as $rr) {
- $guid = get_guid();
- q("update `photo` set `guid` = '%s' where `resource-id` = '%s'",
- dbesc($guid),
- dbesc($rr['resource-id'])
- );
- }
- }
-}
-
-function update_1083() {
- q("CREATE TABLE IF NOT EXISTS `deliverq` (
- `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `cmd` CHAR( 32 ) NOT NULL ,
- `item` INT NOT NULL ,
- `contact` INT NOT NULL
- ) ENGINE = MYISAM ");
-
-}
-
-function update_1084() {
- q("ALTER TABLE `contact` ADD `attag` CHAR( 255 ) NOT NULL AFTER `nick` ");
-}
-
-function update_1085() {
- q("CREATE TABLE IF NOT EXISTS `search` (
- `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `uid` INT NOT NULL ,
- `term` CHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
- INDEX ( `uid` ),
- INDEX ( `term` )
- ) ENGINE = MYISAM ");
-}
-
-function update_1086() {
- q("ALTER TABLE `item` ADD `bookmark` tinyint(1) NOT NULL DEFAULT '0' AFTER `starred` ");
-}
-
-function update_1087() {
- q("ALTER TABLE `item` ADD `commented` datetime NOT NULL DEFAULT '0001-01-01 00:00:00' AFTER `edited` ");
-
- $r = q("SELECT `id` FROM `item` WHERE `parent` = `id` ");
- if (DBM::is_result($r)) {
- foreach ($r as $rr) {
- $x = q("SELECT max(`created`) AS `cdate` FROM `item` WHERE `parent` = %d LIMIT 1",
- intval($rr['id'])
- );
- if(count($x))
- q("UPDATE `item` SET `commented` = '%s' WHERE `id` = %d",
- dbesc($x[0]['cdate']),
- intval($rr['id'])
- );
- }
- }
-}
-
-function update_1088() {
- q("ALTER TABLE `user` ADD `account_expired` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `expire` ,
- ADD `account_expires_on` DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00' AFTER `account_expired` ,
- ADD `expire_notification_sent` DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00' AFTER `account_expires_on` ");
-}
-
-function update_1089() {
- q("ALTER TABLE `user` ADD `blocktags` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `hidewall` ");
-}
-
-function update_1090() {
- q("ALTER TABLE `contact` ADD `batch` char(255) NOT NULL AFTER `prvkey` ");
-
- q("UPDATE `contact` SET `batch` = concat(substring_index(`url`,'/',3),'/receive/public') WHERE `network` = 'dspr' ");
-
-}
-
-function update_1091() {
-
- // catch a few stragglers that may have crept in before we added this on remote connects
- q("UPDATE `contact` SET `batch` = concat(substring_index(`url`,'/',3),'/receive/public') WHERE `network` = 'dspr' AND `batch` = '' ");
- q("ALTER TABLE `queue` ADD `batch` TINYINT( 1 ) NOT NULL DEFAULT '0' ");
- q("ALTER TABLE `fcontact` ADD `batch` char(255) NOT NULL AFTER `addr` ");
-
-}
-
-function update_1092() {
- q("ALTER TABLE `user` ADD INDEX ( `login_date` ) ");
- q("ALTER TABLE `user` ADD INDEX ( `account_expired` ) ");
-}
-
-function update_1093() {
- q("CREATE TABLE IF NOT EXISTS `fserver` (
- `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `server` CHAR( 255 ) NOT NULL ,
- `posturl` CHAR( 255 ) NOT NULL ,
- `key` TEXT NOT NULL,
- INDEX ( `server` )
- ) ENGINE = MYISAM ");
-
- q("ALTER TABLE `group` ADD `visible` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `uid` ");
-
-}
-
-function update_1094() {
- q("ALTER TABLE `item` ADD `postopts` TEXT NOT NULL AFTER `target` ");
-}
-
-function update_1095() {
- q("ALTER TABLE `contact` ADD `bd` DATE NOT NULL AFTER `bdyear` ");
-}
-
-function update_1096() {
- q("ALTER TABLE `item` ADD `origin` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `deleted` , ADD INDEX ( `origin` ) ");
-}
-
-function update_1097() {
- q("ALTER TABLE `queue`
- ADD INDEX (`cid`),
- ADD INDEX (`created`),
- ADD INDEX (`last`),
- ADD INDEX (`network`),
- ADD INDEX (`batch`)
- ");
-}
-
-function update_1098() {
- q("ALTER TABLE `contact`
- ADD INDEX (`network`),
- ADD INDEX (`name`),
- ADD INDEX (`nick`),
- ADD INDEX (`attag`),
- ADD INDEX (`url`),
- ADD INDEX (`addr`),
- ADD INDEX (`batch`)
- ");
-}
-
-function update_1099() {
- q("CREATE TABLE IF NOT EXISTS `gcontact` (
- `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `name` CHAR( 255 ) NOT NULL ,
- `url` CHAR( 255 ) NOT NULL ,
- `nurl` CHAR( 255 ) NOT NULL ,
- `photo` CHAR( 255 ) NOT NULL
- ) ENGINE = MYISAM ");
-
- q("CREATE TABLE IF NOT EXISTS `glink` (
- `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `cid` INT NOT NULL ,
- `uid` INT NOT NULL ,
- `gcid` INT NOT NULL,
- `updated` DATETIME NOT NULL
- ) ENGINE = MYISAM ");
-
- q("ALTER TABLE `gcontact` ADD INDEX (`nurl`) ");
- q("ALTER TABLE `glink` ADD INDEX (`cid`), ADD INDEX (`uid`), ADD INDEX (`gcid`), ADD INDEX (`updated`) ");
-
- q("ALTER TABLE `contact` ADD `poco` TEXT NOT NULL AFTER `confirm` ");
-
-}
-
-function update_1100() {
- q("ALTER TABLE `contact` ADD `nurl` CHAR( 255 ) NOT NULL AFTER `url` ");
- q("alter table contact add index (`nurl`) ");
-
- require_once('include/text.php');
-
- $r = q("select id, url from contact where url != '' and nurl = '' ");
- if (DBM::is_result($r)) {
- foreach ($r as $rr) {
- q("update contact set nurl = '%s' where id = %d",
- dbesc(normalise_link($rr['url'])),
- intval($rr['id'])
- );
- }
- }
-}
-
-
-function update_1101() {
- q("CREATE TABLE IF NOT EXISTS `gcign` (
- `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `uid` INT NOT NULL ,
- `gcid` INT NOT NULL
- ) ENGINE = MYISAM ");
-
- q("ALTER TABLE `gcign` ADD INDEX (`uid`), ADD INDEX (`gcid`) ");
-}
-
-function update_1102() {
- q("ALTER TABLE `clients` ADD `name` TEXT NULL DEFAULT NULL AFTER `redirect_uri` ");
- q("ALTER TABLE `clients` ADD `icon` TEXT NULL DEFAULT NULL AFTER `name` ");
- q("ALTER TABLE `clients` ADD `uid` INT NOT NULL DEFAULT 0 AFTER `icon` ");
-
- q("ALTER TABLE `tokens` ADD `secret` TEXT NOT NULL AFTER `id` ");
- q("ALTER TABLE `tokens` ADD `uid` INT NOT NULL AFTER `scope` ");
-}
-
-
-function update_1103() {
-// q("ALTER TABLE `item` ADD INDEX ( `wall` ) ");
- q("ALTER TABLE `item` ADD FULLTEXT ( `tag` ) ");
- q("ALTER TABLE `contact` ADD INDEX ( `pending` ) ");
- q("ALTER TABLE `user` ADD INDEX ( `hidewall` ) ");
- q("ALTER TABLE `user` ADD INDEX ( `blockwall` ) ");
- q("ALTER TABLE `user` ADD INDEX ( `blocked` ) ");
- q("ALTER TABLE `user` ADD INDEX ( `verified` ) ");
-
-}
-
-function update_1104() {
- q("ALTER TABLE `item` ADD `forum_mode` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `origin` , ADD INDEX ( `forum_mode` ) ");
-
-}
-
-function update_1105() {
- q("ALTER TABLE `mail` ADD `convid` INT NOT NULL AFTER `contact-id` ");
- q("ALTER TABLE `mail` ADD `guid` CHAR( 64 ) NOT NULL AFTER `uid` ");
-
- q("CREATE TABLE IF NOT EXISTS `conv` (
- `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `guid` CHAR( 64 ) NOT NULL ,
- `recips` MEDIUMTEXT NOT NULL ,
- `uid` INT NOT NULL
- ) ENGINE = MYISAM ");
-}
-
-
-function update_1106() {
- q("ALTER TABLE `item` ADD INDEX ( `author-link` ) ");
-
-}
-
-function update_1107() {
- q("ALTER TABLE `item` ADD INDEX ( `bookmark` ) ");
-
-}
-
-function update_1108() {
- q("ALTER TABLE `contact` ADD `hidden` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `writable` ,
-ADD INDEX ( `hidden` ) ");
-
-}
-
-function update_1109() {
- q("ALTER TABLE `conv` ADD `creator` CHAR( 255 ) NOT NULL ,
- ADD `created` DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00',
- ADD `updated` DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00',
- ADD `subject` MEDIUMTEXT NOT NULL,
- ADD INDEX ( `created` ), ADD INDEX ( `updated` ) ");
-}
-
-function update_1110() {
- q("ALTER TABLE `mail` ADD `reply` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `seen`,
- ADD INDEX ( `reply` ), ADD INDEX ( `uid` ), ADD INDEX ( `guid` ), ADD INDEX ( `seen` ),
- ADD INDEX ( `uri` ), ADD INDEX ( `parent-uri`), ADD INDEX ( `created` ), ADD INDEX ( `convid` ) ");
-
-}
-
-function update_1111() {
- q("ALTER TABLE `gcontact` ADD `connect` CHAR( 255 ) NOT NULL ");
-}
-
-
-function update_1112() {
-
- q("CREATE TABLE IF NOT EXISTS `notify` (
-`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
-`type` INT( 11 ) NOT NULL ,
-`name` CHAR( 255 ) NOT NULL ,
-`url` CHAR( 255 ) NOT NULL ,
-`photo` CHAR( 255 ) NOT NULL ,
-`date` DATETIME NOT NULL ,
-`msg` MEDIUMTEXT NOT NULL ,
-`uid` INT NOT NULL ,
-`link` CHAR( 255 ) NOT NULL ,
-`seen` TINYINT( 1 ) NOT NULL DEFAULT '0'
-) ENGINE = MYISAM ");
-
- q("ALTER TABLE `notify` ADD INDEX ( `type` ), ADD INDEX ( `uid`), ADD INDEX (`seen`), ADD INDEX (`date`) ");
-
-}
-
-function update_1113() {
- q("ALTER TABLE `notify` ADD `verb` CHAR( 255 ) NOT NULL ,
-ADD `otype` CHAR( 16 ) NOT NULL");
-}
-
-function update_1114() {
- q("CREATE TABLE IF NOT EXISTS `item_id` (
-`iid` INT NOT NULL ,
-`uid` INT NOT NULL ,
-`face` CHAR( 255 ) NOT NULL ,
-`dspr` CHAR( 255 ) NOT NULL ,
-`twit` CHAR( 255 ) NOT NULL ,
-`stat` CHAR( 255 ) NOT NULL ,
-PRIMARY KEY ( `iid` ),
-INDEX ( `uid` ),
-INDEX ( `face` ),
-INDEX ( `dspr` ),
-INDEX ( `twit` ),
-INDEX ( `stat` )
-) ENGINE = MYISAM ");
-
-}
-
-function update_1115() {
- q("ALTER TABLE `item` ADD `moderated`
- TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `pubmail`,
- ADD INDEX (`moderated`) ");
-}
-
-function update_1116() {
- //typo! corrected update was rolled forward
-}
-
-function update_1117() {
-q("create table if not exists `manage` (
-`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
-`uid` INT NOT NULL ,
-`mid` INT NOT NULL,
-INDEX ( `uid` ),
-INDEX ( `mid` )
-) ENGINE = MYISAM ");
-
-}
-
-function update_1118() {
- // rolled forward
-}
-
-function update_1119() {
-q("ALTER TABLE `contact` ADD `closeness` TINYINT( 2 ) NOT NULL DEFAULT '99' AFTER `reason` , ADD INDEX (`closeness`) ");
-q("update contact set closeness = 0 where self = 1");
-q("ALTER TABLE `item` ADD `spam` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `visible` , ADD INDEX (`spam`) ");
-}
-
-
-function update_1120() {
-
- // item table update from 1119 did not get into database.sql file.
- // might be missing on new installs. We'll check.
-
- $r = q("describe item");
- if (DBM::is_result($r)) {
- foreach($r as $rr)
- if($rr['Field'] == 'spam')
- return;
- }
- q("ALTER TABLE `item` ADD `spam` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `visible` , ADD INDEX (`spam`) ");
-
-}
-
-function update_1121() {
- q("CREATE TABLE IF NOT EXISTS `poll_result` (
- `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `poll_id` INT NOT NULL ,
- `choice` INT NOT NULL ,
- INDEX ( `poll_id` ),
- INDEX ( `choice` )
- ) ENGINE = MYISAM ");
-
- q("CREATE TABLE IF NOT EXISTS `poll` (
- `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `uid` INT NOT NULL ,
- `q0` MEDIUMTEXT NOT NULL ,
- `q1` MEDIUMTEXT NOT NULL ,
- `q2` MEDIUMTEXT NOT NULL ,
- `q3` MEDIUMTEXT NOT NULL ,
- `q4` MEDIUMTEXT NOT NULL ,
- `q5` MEDIUMTEXT NOT NULL ,
- `q6` MEDIUMTEXT NOT NULL ,
- `q7` MEDIUMTEXT NOT NULL ,
- `q8` MEDIUMTEXT NOT NULL ,
- `q9` MEDIUMTEXT NOT NULL ,
- INDEX ( `uid` )
- ) ENGINE = MYISAM ");
-
-}
-
-function update_1122() {
-q("ALTER TABLE `notify` ADD `hash` CHAR( 64 ) NOT NULL AFTER `id` ,
-ADD INDEX ( `hash` ) ");
-}
-
-function update_1123() {
-Config::set('system','allowed_themes','dispy,quattro,testbubble,vier,darkbubble,darkzero,duepuntozero,greenzero,purplezero,quattro-green,slackr');
-}
-
-function update_1124() {
-q("alter table item add index (`author-name`) ");
-}
-
-function update_1125() {
- q("CREATE TABLE IF NOT EXISTS `notify-threads` (
- `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `notify-id` INT NOT NULL,
- `master-parent-item` INT( 10 ) unsigned NOT NULL DEFAULT '0',
- `parent-item` INT( 10 ) unsigned NOT NULL DEFAULT '0',
- `receiver-uid` INT NOT NULL,
- INDEX ( `master-parent-item` ),
- INDEX ( `receiver-uid` )
- ) ENGINE = MyISAM DEFAULT CHARSET=utf8");
-}
-
-function update_1126() {
- q("ALTER TABLE `mailacct` ADD `action` INT NOT NULL AFTER `pass`,
- ADD `movetofolder` CHAR(255) NOT NULL AFTER `action`");
-}
-
-function update_1127() {
- q("CREATE TABLE IF NOT EXISTS `spam` (
- `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `uid` INT NOT NULL,
- `spam` INT NOT NULL DEFAULT '0',
- `ham` INT NOT NULL DEFAULT '0',
- `term` CHAR(255) NOT NULL,
- INDEX ( `uid` ),
- INDEX ( `spam` ),
- INDEX ( `ham` ),
- INDEX ( `term` )
- ) ENGINE = MyISAM DEFAULT CHARSET=utf8");
-}
-
-
-function update_1128() {
- q("alter table spam add `date` DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00' AFTER `term` ");
-}
-
-function update_1129() {
- q("ALTER TABLE `notify` ADD `parent` INT NOT NULL AFTER `link` , ADD INDEX ( `parent` ), ADD INDEX ( `link` ), ADD INDEX ( `otype` ) ");
-}
-
-function update_1130() {
- q("ALTER TABLE `item` ADD `file` MEDIUMTEXT NOT NULL AFTER `inform`, ADD FULLTEXT KEY (`file`) ");
-}
-
-function update_1131() {
- q("ALTER TABLE `contact` ADD `forum` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `writable` , ADD INDEX ( `forum` ) ");
-}
-
-
-function update_1132() {
- q("CREATE TABLE IF NOT EXISTS `userd` (
-`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
-`username` CHAR( 255 ) NOT NULL,
-INDEX ( `username` )
-) ENGINE = MYISAM ");
-
-}
-
-function update_1133() {
-q("ALTER TABLE `user` ADD `unkmail` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `blocktags` , ADD INDEX ( `unkmail` ) ");
-q("ALTER TABLE `user` ADD `cntunkmail` INT NOT NULL DEFAULT '10' AFTER `unkmail` , ADD INDEX ( `cntunkmail` ) ");
-q("ALTER TABLE `mail` ADD `unknown` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `replied` , ADD INDEX ( `unknown` ) ");
-}
-
-function update_1134() {
- // faulty update merged forward
- // had a hardwired tablename of 'friendica' which isn't the right name on most systems
-}
-
-function update_1135() {
- //there can't be indexes with more than 1000 bytes in mysql,
- //so change charset to be smaller
- q("ALTER TABLE `config` CHANGE `cat` `cat` CHAR( 255 ) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL ,
-CHANGE `k` `k` CHAR( 255 ) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL");
-
- //same thing for pconfig
- q("ALTER TABLE `pconfig` CHANGE `cat` `cat` CHAR( 255 ) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL ,
- CHANGE `k` `k` CHAR( 255 ) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL");
- // faulty update merged forward. Bad update in 1134 caused duplicate k,cat pairs
- // these have to be cleared before the unique keys can be added.
-}
-
-function update_1136() {
-
- $arr = array();
-
- // order in reverse so that we save the newest entry
-
- $r = q("select * from config where 1 order by id desc");
- if (DBM::is_result($r)) {
- foreach ($r as $rr) {
- $found = false;
- foreach($arr as $x) {
- if($x['cat'] == $rr['cat'] && $x['k'] == $rr['k']) {
- $found = true;
- q("delete from config where id = %d",
- intval($rr['id'])
- );
- }
- }
- if(! $found) {
- $arr[] = $rr;
- }
- }
- }
-
- $arr = array();
- $r = q("select * from pconfig where 1 order by id desc");
- if (DBM::is_result($r)) {
- foreach ($r as $rr) {
- $found = false;
- foreach($arr as $x) {
- if($x['uid'] == $rr['uid'] && $x['cat'] == $rr['cat'] && $x['k'] == $rr['k']) {
- $found = true;
- q("delete from pconfig where id = %d",
- intval($rr['id'])
- );
- }
- }
- if(! $found) {
- $arr[] = $rr;
- }
- }
- }
- q("ALTER TABLE `config` ADD UNIQUE `access` ( `cat` , `k` ) ");
- q("ALTER TABLE `pconfig` ADD UNIQUE `access` ( `uid` , `cat` , `k` )");
-
-}
-
-
-function update_1137() {
- q("alter table item_id DROP `face` , DROP `dspr` , DROP `twit` , DROP `stat` ");
- q("ALTER TABLE `item_id` ADD `sid` CHAR( 255 ) NOT NULL AFTER `uid` , ADD `service` CHAR( 255 ) NOT NULL AFTER `sid` , add index (`sid`), add index ( `service`) ");
-}
-
-function update_1138() {
- q("alter table contact add archive tinyint(1) not null default '0' after hidden, add index (archive)");
-}
-
-function update_1139() {
- $r = q("alter table user add account_removed tinyint(1) not null default '0' after expire, add index(account_removed) ");
- if(! $r)
- return UPDATE_FAILED ;
- return UPDATE_SUCCESS ;
-}
-
-function update_1140() {
- $r = q("alter table addon add hidden tinyint(1) not null default '0' after installed, add index(hidden) ");
- if(! $r)
- return UPDATE_FAILED ;
- return UPDATE_SUCCESS ;
-}
-
-function update_1141() {
- $r = q("alter table glink add zcid int(11) not null after gcid, add index(zcid) ");
- if(! $r)
- return UPDATE_FAILED ;
- return UPDATE_SUCCESS ;
-}
-
-
-function update_1142() {
- $r = q("alter table user add service_class char(32) not null after expire_notification_sent, add index(service_class) ");
- if(! $r)
- return UPDATE_FAILED ;
- return UPDATE_SUCCESS ;
-}
-
-function update_1143() {
- $r = q("alter table user add def_gid int(11) not null default '0' after service_class");
- if(! $r)
- return UPDATE_FAILED ;
- return UPDATE_SUCCESS ;
-}
-
-function update_1144() {
- $r = q("alter table contact add prv tinyint(1) not null default '0' after forum");
- if(! $r)
- return UPDATE_FAILED ;
- return UPDATE_SUCCESS ;
-}
-
-function update_1145() {
- $r = q("alter table profile add howlong datetime not null default '0001-01-01 00:00:00' after `with`");
- if(! $r)
- return UPDATE_FAILED ;
- return UPDATE_SUCCESS ;
-}
-
-function update_1146() {
- $r = q("alter table profile add hometown char(255) not null after `country-name`, add index ( `hometown` ) ");
- if(! $r)
- return UPDATE_FAILED ;
- return UPDATE_SUCCESS ;
-}
-
-function update_1147() {
- $r1 = q("ALTER TABLE `sign` ALTER `iid` SET DEFAULT '0'");
- $r2 = q("ALTER TABLE `sign` ADD `retract_iid` INT(10) UNSIGNED NOT NULL DEFAULT '0' AFTER `iid`");
- $r3 = q("ALTER TABLE `sign` ADD INDEX ( `retract_iid` )");
- if((! $r1) || (! $r2) || (! $r3))
- return UPDATE_FAILED ;
- return UPDATE_SUCCESS ;
-}
-
-function update_1148() {
- $r = q("ALTER TABLE photo ADD type CHAR(128) NOT NULL DEFAULT 'image/jpeg' AFTER filename");
- if (!$r)
- return UPDATE_FAILED;
- return UPDATE_SUCCESS;
-}
-
-
-function update_1149() {
- $r1 = q("ALTER TABLE profile ADD likes text NOT NULL after prv_keywords");
- $r2 = q("ALTER TABLE profile ADD dislikes text NOT NULL after likes");
- if (! ($r1 && $r2))
- return UPDATE_FAILED;
- return UPDATE_SUCCESS;
-}
-
-
-function update_1150() {
- $r = q("ALTER TABLE event ADD summary text NOT NULL after finish, add index ( uid ), add index ( cid ), add index ( uri ), add index ( `start` ), add index ( finish ), add index ( `type` ), add index ( adjust ) ");
- if(! $r)
- return UPDATE_FAILED;
- return UPDATE_SUCCESS;
-}
-
-
-function update_1151() {
- $r = q("CREATE TABLE IF NOT EXISTS locks (
- id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- name CHAR( 128 ) NOT NULL ,
- locked TINYINT( 1 ) NOT NULL DEFAULT '0'
- ) ENGINE = MYISAM DEFAULT CHARSET=utf8 ");
- if (!$r)
- return UPDATE_FAILED;
- return UPDATE_SUCCESS;
-}
-
-function update_1152() {
- $r = q("CREATE TABLE IF NOT EXISTS `term` (
- `tid` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `oid` INT UNSIGNED NOT NULL ,
- `otype` TINYINT( 3 ) UNSIGNED NOT NULL ,
- `type` TINYINT( 3 ) UNSIGNED NOT NULL ,
- `term` CHAR( 255 ) NOT NULL ,
- `url` CHAR( 255 ) NOT NULL,
- KEY `oid` ( `oid` ),
- KEY `otype` ( `otype` ),
- KEY `type` ( `type` ),
- KEY `term` ( `term` )
- ) ENGINE = MYISAM DEFAULT CHARSET=utf8 ");
- if (!$r)
- return UPDATE_FAILED;
- return UPDATE_SUCCESS;
-}
-
-function update_1153() {
- $r = q("ALTER TABLE `hook` ADD `priority` INT(11) UNSIGNED NOT NULL DEFAULT '0'");
-
- if(!$r) return UPDATE_FAILED;
- return UPDATE_SUCCESS;
-}
-
-function update_1154() {
- $r = q("ALTER TABLE `event` ADD `ignore` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '0' AFTER `adjust` , ADD INDEX ( `ignore` )");
-
- if(!$r) return UPDATE_FAILED;
- return UPDATE_SUCCESS;
-}
-
-function update_1155() {
- $r1 = q("ALTER TABLE `item_id` DROP PRIMARY KEY");
- $r2 = q("ALTER TABLE `item_id` ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST");
- $r3 = q("ALTER TABLE `item_id` ADD INDEX ( `iid` ) ");
-
- if($r1 && $r2 && $r3)
- return UPDATE_SUCCESS;
-
- return UPDATE_FAILED;
-}
-
-function update_1156() {
- $r = q("ALTER TABLE `photo` ADD `datasize` INT UNSIGNED NOT NULL DEFAULT '0' AFTER `width` ,
-ADD INDEX ( `datasize` ) ");
-
- if(!$r) return UPDATE_FAILED;
- return UPDATE_SUCCESS;
-}
-
-function update_1157() {
- $r = q("CREATE TABLE IF NOT EXISTS `dsprphotoq` (
- `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
- `uid` int(11) NOT NULL,
- `msg` mediumtext NOT NULL,
- `attempt` tinyint(4) NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=MyISAM DEFAULT CHARSET=utf8"
- );
-
- if($r)
- return UPDATE_SUCCESS;
-}
-
-function update_1158() {
- Config::set('system', 'maintenance', 1);
-
- // Wait for 15 seconds for current requests to
- // clear before locking up the database
- sleep(15);
-
- $r = q("CREATE INDEX event_id ON item(`event-id`)");
- Config::set('system', 'maintenance', 0);
-
- if($r)
- return UPDATE_SUCCESS;
-
- return UPDATE_FAILED;
-}
-
-function update_1159() {
- $r = q("ALTER TABLE `term` ADD `aid` int(10) unsigned NOT NULL DEFAULT '0',
- ADD `uid` int(10) unsigned NOT NULL DEFAULT '0',
- ADD INDEX (`uid`),
- ADD INDEX (`aid`)");
-
- if(!$r)
- return UPDATE_FAILED;
-
- return UPDATE_SUCCESS;
-}
-
-function update_1160() {
- Config::set('system', 'maintenance', 1);
-
- // Wait for 15 seconds for current requests to
- // clear before locking up the database
- sleep(15);
-
- $r = q("ALTER TABLE `item` ADD `mention` TINYINT(1) NOT NULL DEFAULT '0', ADD INDEX (`mention`)");
- Config::set('system', 'maintenance', 0);
-
- if(!$r)
- return UPDATE_FAILED;
-
- return UPDATE_SUCCESS;
-}
-
-function update_1161() {
- $r = q("ALTER TABLE `pconfig` ADD INDEX (`cat`)");
-
- if(!$r)
- return UPDATE_FAILED;
-
- return UPDATE_SUCCESS;
-}
-
-function update_1162() {
- require_once('include/tags.php');
- update_items();
-
- return UPDATE_SUCCESS;
-}
-
-function update_1163() {
- Config::set('system', 'maintenance', 1);
-
- $r = q("ALTER TABLE `item` ADD `network` char(32) NOT NULL");
-
- Config::set('system', 'maintenance', 0);
- if(!$r)
- return UPDATE_FAILED;
-
- return UPDATE_SUCCESS;
-}
-function update_1164() {
- Config::set('system', 'maintenance', 1);
-
- $r = q("UPDATE `item` SET `network`='%s' WHERE `contact-id` IN (SELECT `id` FROM`contact` WHERE `network` = '' AND `contact`.`uid` = `item`.`uid`)",
- NETWORK_DFRN);
-
- $r = q("UPDATE `item` SET `network`='%s' WHERE `contact-id` IN (SELECT `id` FROM`contact` WHERE `network` = '%s' AND `contact`.`uid` = `item`.`uid`)",
- NETWORK_DFRN, NETWORK_DFRN);
-
- $r = q("UPDATE `item` SET `network`='%s' WHERE `contact-id` IN (SELECT `id` FROM`contact` WHERE `network` = '%s' AND `contact`.`uid` = `item`.`uid`)",
- NETWORK_OSTATUS, NETWORK_OSTATUS);
-
- $r = q("UPDATE `item` SET `network`='%s' WHERE `contact-id` IN (SELECT `id` FROM`contact` WHERE `network` = '%s' AND `contact`.`uid` = `item`.`uid`)",
- NETWORK_FEED, NETWORK_FEED);
-
- $r = q("UPDATE `item` SET `network`='%s' WHERE `contact-id` IN (SELECT `id` FROM`contact` WHERE `network` = '%s' AND `contact`.`uid` = `item`.`uid`)",
- NETWORK_DIASPORA, NETWORK_DIASPORA);
-
- $r = q("UPDATE `item` SET `network`='%s' WHERE `contact-id` IN (SELECT `id` FROM`contact` WHERE `network` = '%s' AND `contact`.`uid` = `item`.`uid`)",
- NETWORK_MAIL, NETWORK_MAIL);
-
- $r = q("UPDATE `item` SET `network`='%s' WHERE `contact-id` IN (SELECT `id` FROM`contact` WHERE `network` = '%s' AND `contact`.`uid` = `item`.`uid`)",
- NETWORK_FACEBOOK, NETWORK_FACEBOOK);
-
- $r = q("UPDATE `item` SET `network`='%s' WHERE `contact-id` IN (SELECT `id` FROM`contact` WHERE `network` = '%s' AND `contact`.`uid` = `item`.`uid`)",
- NETWORK_LINKEDIN, NETWORK_LINKEDIN);
-
- $r = q("UPDATE `item` SET `network`='%s' WHERE `contact-id` IN (SELECT `id` FROM`contact` WHERE `network` = '%s' AND `contact`.`uid` = `item`.`uid`)",
- NETWORK_XMPP, NETWORK_XMPP);
-
- $r = q("UPDATE `item` SET `network`='%s' WHERE `contact-id` IN (SELECT `id` FROM`contact` WHERE `network` = '%s' AND `contact`.`uid` = `item`.`uid`)",
- NETWORK_MYSPACE, NETWORK_MYSPACE);
-
- $r = q("UPDATE `item` SET `network`='%s' WHERE `contact-id` IN (SELECT `id` FROM`contact` WHERE `network` = '%s' AND `contact`.`uid` = `item`.`uid`)",
- NETWORK_GPLUS, NETWORK_GPLUS);
-
- $r = q("UPDATE `item` SET `network`='%s' WHERE `contact-id` IN (SELECT `id` FROM`contact` WHERE `network` = '%s' AND `contact`.`uid` = `item`.`uid`)",
- NETWORK_PUMPIO, NETWORK_PUMPIO);
-
- $r = q("UPDATE `item` SET `network`='%s' WHERE `contact-id` IN (SELECT `id` FROM`contact` WHERE `network` = '%s' AND `contact`.`uid` = `item`.`uid`)",
- NETWORK_TWITTER, NETWORK_TWITTER);
-
- Config::set('system', 'maintenance', 0);
-
- return UPDATE_SUCCESS;
-}
-
-function update_1165() {
- $r = q("CREATE TABLE IF NOT EXISTS `push_subscriber` (
- `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
- `uid` INT NOT NULL,
- `callback_url` CHAR( 255 ) NOT NULL,
- `topic` CHAR( 255 ) NOT NULL,
- `nickname` CHAR( 255 ) NOT NULL,
- `push` INT NOT NULL,
- `last_update` DATETIME NOT NULL,
- `secret` CHAR( 255 ) NOT NULL
- ) ENGINE = MYISAM DEFAULT CHARSET=utf8 ");
- if (!$r)
- return UPDATE_FAILED;
-
- return UPDATE_SUCCESS;
-}
-
-function update_1166() {
- $r = q("CREATE TABLE IF NOT EXISTS `unique_contacts` (
- `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
- `url` CHAR(255) NOT NULL,
- `nick` CHAR(255) NOT NULL,
- `name` CHAR(255) NOT NULL,
- `avatar` CHAR(255) NOT NULL,
- INDEX (`url`)
- ) ENGINE = MYISAM DEFAULT CHARSET=utf8 ");
- if (!$r)
- return UPDATE_FAILED;
-
- return UPDATE_SUCCESS;
-}
-
-function update_1167() {
- $r = q("ALTER TABLE `contact` ADD `notify_new_posts` TINYINT(1) NOT NULL DEFAULT '0'");
- if (!$r)
- return UPDATE_FAILED;
-
- return UPDATE_SUCCESS;
-}
-
-function update_1168() {
- $r = q("ALTER TABLE `contact` ADD `fetch_further_information` TINYINT(1) NOT NULL DEFAULT '0'");
- if (!$r)
- return UPDATE_FAILED;
-
- return UPDATE_SUCCESS;
-}
-
-function update_1169() {
- $r = q("CREATE TABLE IF NOT EXISTS `thread` (
- `iid` int(10) unsigned NOT NULL DEFAULT '0',
- `uid` int(10) unsigned NOT NULL DEFAULT '0',
- `contact-id` int(11) unsigned NOT NULL DEFAULT '0',
- `created` datetime NOT NULL DEFAULT '0001-01-01 00:00:00',
- `edited` datetime NOT NULL DEFAULT '0001-01-01 00:00:00',
- `commented` datetime NOT NULL DEFAULT '0001-01-01 00:00:00',
- `received` datetime NOT NULL DEFAULT '0001-01-01 00:00:00',
- `changed` datetime NOT NULL DEFAULT '0001-01-01 00:00:00',
- `wall` tinyint(1) NOT NULL DEFAULT '0',
- `private` tinyint(1) NOT NULL DEFAULT '0',
- `pubmail` tinyint(1) NOT NULL DEFAULT '0',
- `moderated` tinyint(1) NOT NULL DEFAULT '0',
- `visible` tinyint(1) NOT NULL DEFAULT '0',
- `spam` tinyint(1) NOT NULL DEFAULT '0',
- `starred` tinyint(1) NOT NULL DEFAULT '0',
- `bookmark` tinyint(1) NOT NULL DEFAULT '0',
- `unseen` tinyint(1) NOT NULL DEFAULT '1',
- `deleted` tinyint(1) NOT NULL DEFAULT '0',
- `origin` tinyint(1) NOT NULL DEFAULT '0',
- `forum_mode` tinyint(1) NOT NULL DEFAULT '0',
- `mention` tinyint(1) NOT NULL DEFAULT '0',
- `network` char(32) NOT NULL,
- PRIMARY KEY (`iid`),
- KEY `created` (`created`),
- KEY `commented` (`commented`),
- KEY `uid_network_commented` (`uid`,`network`,`commented`),
- KEY `uid_network_created` (`uid`,`network`,`created`),
- KEY `uid_contactid_commented` (`uid`,`contact-id`,`commented`),
- KEY `uid_contactid_created` (`uid`,`contact-id`,`created`),
- KEY `wall_private_received` (`wall`,`private`,`received`),
- KEY `uid_created` (`uid`,`created`),
- KEY `uid_commented` (`uid`,`commented`)
- ) ENGINE=MyISAM DEFAULT CHARSET=utf8;");
- if (!$r)
- return UPDATE_FAILED;
-
- Worker::add(PRIORITY_LOW, "ThreadUpdate");
-
- return UPDATE_SUCCESS;
-}
-
-/*
-==========
-ATTENTION!
-==========
-
-All following update functions are ONLY for jobs that need to run AFTER the database changes are applied.
-
-Database changes are ONLY applied in the file src/Database/DBStructure.php.
-*/
-
-function update_1177() {
- require_once("mod/profiles.php");
-
- $profiles = q("SELECT `uid`, `about`, `locality`, `pub_keywords`, `gender` FROM `profile` WHERE `is-default`");
-
- foreach ($profiles AS $profile) {
- if ($profile["about"].$profile["locality"].$profile["pub_keywords"].$profile["gender"] == "")
- continue;
-
- $profile["pub_keywords"] = profile_clean_keywords($profile["pub_keywords"]);
-
- $r = q("UPDATE `contact` SET `about` = '%s', `location` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `self` AND `uid` = %d",
- dbesc($profile["about"]),
- dbesc($profile["locality"]),
- dbesc($profile["pub_keywords"]),
- dbesc($profile["gender"]),
- intval($profile["uid"])
- );
- }
-}
-
-function update_1178() {
+function update_1179() {
if (Config::get('system','no_community_page'))
Config::set('system','community_page_style', CP_NO_COMMUNITY_PAGE);
return UPDATE_SUCCESS;
}
-function update_1180() {
+function update_1181() {
// Fill the new fields in the term table.
Worker::add(PRIORITY_LOW, "TagUpdate");
return UPDATE_SUCCESS;
}
-function update_1188() {
+function update_1189() {
if (strlen(Config::get('system','directory_submit_url')) &&
!strlen(Config::get('system','directory'))) {
return UPDATE_SUCCESS;
}
-function update_1190() {
+function update_1191() {
- require_once('include/plugin.php');
+ require_once 'include/plugin.php';
Config::set('system', 'maintenance', 1);
}
-function update_1202() {
+function update_1203() {
$r = q("UPDATE `user` SET `account-type` = %d WHERE `page-flags` IN (%d, %d)",
dbesc(ACCOUNT_TYPE_COMMUNITY), dbesc(PAGE_COMMUNITY), dbesc(PAGE_PRVGROUP));
}
<img src="{{$avatar}}" height="32" width="32">
</a>
{{/if}}
- {{*<span><a href="{{$profile}}" target="_blank" class="shared-wall-item-name">{{$author}}</a> wrote the following <a href="{{$link}}" target="_blank">post</a>{{$reldate}}:</span>*}}
<div><a href="{{$profile}}" target="_blank" class="shared-wall-item-name"><span class="shared-author">{{$author}}</span></a></div>
<div class="shared-wall-item-ago"><small><a href="{{$link}}" target="_blank"><span class="shared-time">{{$posted}}</a></a></small></div>
</div>
$schemecssfile = false;
$scheme_modified = 0;
-if (! $a->install) {
+if ($a->module !== 'install') {
// Get the UID of the profile owner.
$uid = get_theme_uid();
if ($uid) {
// Setting $schema to '' wasn't working for some reason, so we'll check it's
// not --- like the mobile theme does instead.
// Allow layouts to over-ride the schema.
-if ($_REQUEST['schema']) {
+if (x($_REQUEST, 'schema')) {
$schema = $_REQUEST['schema'];
}
// Calculate some colors in dependance of existing colors.
// Some colors are calculated to don't have too many selection
// fields in the theme settings.
-if (! $menu_background_hover_color) {
+if (!isset($menu_background_hover_color)) {
$mbhc = new Color($nav_bg);
$mcolor = $mbhc->getHex();
$menu_background_hover_color = '#' . $mbhc->lighten(5);
}
}
-if (! $nav_icon_hover_color) {
+if (!isset($nav_icon_hover_color)) {
$nihc = new Color($nav_bg);
if ($nihc->isLight()) {
$nav_icon_hover_color = '#' . $nihc->lighten(10);
}
}
-if (! $link_hover_color) {
+if (!isset($link_hover_color)) {
$lhc = new Color($link_color);
$lcolor = $lhc->getHex();
}
// Convert $bg_image_options into css.
+if (!isset($bg_image_option)) {
+ $bg_image_option = null;
+}
switch ($bg_image_option) {
case "stretch":
$background_size_img = "100%";
</form>
</div>
{{* This form is inserted as experiment to move the search-save button to the second navbar with js *}}
+ {{if $savedsearch}}
<form id="search-save-form" action="{{$action_url}}" method="get" >
<input type="hidden" name="search" value="{{$s}}" />
<button class="btn btn-primary btn-sm btn-main pull-right" type="submit" name="save" id="search-save" value="{{$save_label}}"><i class="fa fa-floppy-o fa-2x" aria-hidden="true"></i></button>
</form>
+ {{/if}}
</div>
<?php
+
/*
* Name: frio
* Description: Bootstrap V3 theme. The theme is currently under construction, so it is far from finished. For further information have a look at the <a href="https://github.com/friendica/friendica/tree/develop/view/theme/frio/README.md">ReadMe</a>.
global $frio;
-function frio_init(App $a) {
-
+function frio_init(App $a)
+{
// disable the events module link in the profile tab
$a->theme_events_in_profile = false;
// if the device is a mobile device set js is_mobile
// variable so the js scripts can use this information
- if($a->is_mobile || $a->is_tablet) {
+ if ($a->is_mobile || $a->is_tablet) {
$a->page["htmlhead"] .= <<< EOT
<script type="text/javascript">
var is_mobile = 1;
</script>
EOT;
-}
+ }
- if ($style == "")
+ if ($style == "") {
$style = Config::get('frio', 'style');
+ }
}
-function frio_install() {
+function frio_install()
+{
register_hook('prepare_body_final', 'view/theme/frio/theme.php', 'frio_item_photo_links');
register_hook('item_photo_menu', 'view/theme/frio/theme.php', 'frio_item_photo_menu');
register_hook('contact_photo_menu', 'view/theme/frio/theme.php', 'frio_contact_photo_menu');
logger("installed theme frio");
}
-function frio_uninstall() {
+function frio_uninstall()
+{
unregister_hook('prepare_body_final', 'view/theme/frio/theme.php', 'frio_item_photo_links');
unregister_hook('item_photo_menu', 'view/theme/frio/theme.php', 'frio_item_photo_menu');
unregister_hook('contact_photo_menu', 'view/theme/frio/theme.php', 'frio_contact_photo_menu');
logger("uninstalled theme frio");
}
+
/**
* @brief Replace friendica photo links hook
*
$occurence = 1;
$p = bb_find_open_close($body_info['html'], "<a", ">");
- while($p !== false && ($occurence++ < 500)) {
+ while ($p !== false && ($occurence++ < 500)) {
$link = substr($body_info['html'], $p['start'], $p['end'] - $p['start']);
$matches = array();
preg_match("/\/photos\/[\w]+\/image\/([\w]+)/", $link, $matches);
- if($matches) {
+ if ($matches) {
// Replace the link for the photo's page with a direct link to the photo itself
$newlink = str_replace($matches[0], "/photo/{$matches[1]}", $link);
// Add a "quiet" parameter to any redir links to prevent the "XX welcomes YY" info boxes
$newlink = preg_replace("/href=\"([^\"]+)\/redir\/([^\"]+)&url=([^\"]+)\"/", 'href="$1/redir/$2&quiet=1&url=$3"', $newlink);
- // Having any arguments to the link for Colorbox causes it to fetch base64 code instead of the image
+ // Having any arguments to the link for Colorbox causes it to fetch base64 code instead of the image
$newlink = preg_replace("/\/[?&]zrl=([^&\"]+)/", '', $newlink);
$body_info['html'] = str_replace($link, $newlink, $body_info['html']);
* @param App $a Unused but required by the hook definition
* @param array $arr Contains item data and the original photo_menu
*/
-function frio_item_photo_menu(App $a, &$arr) {
-
- foreach($arr["menu"] as $k =>$v) {
- if(strpos($v,'poke/?f=&c=') === 0 || strpos($v,'message/new/') === 0) {
+function frio_item_photo_menu(App $a, &$arr)
+{
+ foreach ($arr["menu"] as $k => $v) {
+ if (strpos($v, 'poke/?f=&c=') === 0 || strpos($v, 'message/new/') === 0) {
$v = "javascript:addToModal('" . $v . "'); return false;";
$arr["menu"][$k] = $v;
}
}
- $args = array('item' => $item, 'menu' => $menu);
}
/**
* @param App $a The app data
* @param array $args Contains contact data and the original photo_menu
*/
-function frio_contact_photo_menu(App $a, &$args){
-
- $pokelink = "";
- $pmlink = "";
- $cid = "";
-
+function frio_contact_photo_menu(App $a, &$args)
+{
$cid = $args["contact"]["id"];
$pokelink = $args["menu"]["poke"][1];
$pmlink = $args["menu"]["pm"][1];
// The value for opening in a new tab is e.g. when
// $args["menu"]["status"][2] is true. If the value of the [2] key is true
// and if it's a friendica contact we set it to false
- foreach($args["menu"] as $k =>$v) {
- if($k === "status" || $k === "profile" || $k === "photos") {
+ foreach ($args["menu"] as $k => $v) {
+ if ($k === "status" || $k === "profile" || $k === "photos") {
$v[2] = (($args["contact"]["network"] === "dfrn") ? false : true);
$args["menu"][$k][2] = $v[2];
}
// Add to pm and poke links a new key with the value 'modal'.
// Later we can make conditions in the corresponing templates (e.g.
// contact_template.tpl)
- if(strpos($pokelink,'poke/?f=&c='. $cid) !== false)
+ if (strpos($pokelink, 'poke/?f=&c=' . $cid) !== false) {
$args["menu"]["poke"][3] = "modal";
+ }
- if(strpos($pmlink,'message/new/' . $cid) !== false)
+ if (strpos($pmlink, 'message/new/' . $cid) !== false) {
$args["menu"]["pm"][3] = "modal";
-
- $args = array('contact' => $contact, 'menu' => &$menu);
+ }
}
/**
* @param App $a The App class
* @param array $nav The original nav menu
*/
-function frio_remote_nav($a,&$nav) {
+function frio_remote_nav($a, &$nav)
+{
// get the homelink from $_XSESSION
$homelink = get_my_url();
- if(! $homelink)
- $homelink = ((x($_SESSION,'visitor_home')) ? $_SESSION['visitor_home'] : '');
+ if (!$homelink) {
+ $homelink = defaults($_SESSION, 'visitor_home', '');
+ }
// split up the url in it's parts (protocol,domain/directory, /profile/, nickname
// I'm not familiar with regex, so someone might find a better solutionen
// And construct a webbie (e.g. mickey@friendica.domain.com for the search in gcontact
// We use the webbie for search in gcontact because we don't know if gcontact table stores
// the right value if its http or https protocol
- if(count($url_parts)) {
+ if (count($url_parts)) {
$server_url = $url_parts[1] . $url_parts[2];
$webbie = $url_parts[4] . '@' . $url_parts[2];
}
$r[0]['photo'] = (DBM::is_result($r) ? $a->remove_baseurl($r[0]['micro']) : "images/person-48.jpg");
$r[0]['name'] = $a->user['username'];
-
} elseif (!local_user() && remote_user()) {
$r = q("SELECT `name`, `nick`, `micro` AS `photo` FROM `contact` WHERE `id` = %d", intval(remote_user()));
$nav['remote'] = t("Guest");
-
} elseif (get_my_url()) {
$r = q("SELECT `name`, `nick`, `photo` FROM `gcontact`
WHERE `addr` = '%s' AND `network` = 'dfrn'",
}
if (DBM::is_result($r)) {
- $nav['userinfo'] = array(
- 'icon' => (DBM::is_result($r) ? $r[0]['photo'] : "images/person-48.jpg"),
- 'name' => $r[0]['name'],
- );
- }
+ $nav['userinfo'] = array(
+ 'icon' => (DBM::is_result($r) ? $r[0]['photo'] : "images/person-48.jpg"),
+ 'name' => $r[0]['name'],
+ );
+ }
if (!local_user() && !empty($server_url)) {
$nav['logout'] = Array($server_url . '/logout', t('Logout'), "", t('End this session'));
// user menu
$nav['usermenu'][] = Array($server_url . '/profile/' . $a->user['nickname'], t('Status'), "", t('Your posts and conversations'));
- $nav['usermenu'][] = Array($server_url . '/profile/' . $a->user['nickname']. '?tab=profile', t('Profile'), "", t('Your profile page'));
+ $nav['usermenu'][] = Array($server_url . '/profile/' . $a->user['nickname'] . '?tab=profile', t('Profile'), "", t('Your profile page'));
$nav['usermenu'][] = Array($server_url . '/photos/' . $a->user['nickname'], t('Photos'), "", t('Your photos'));
$nav['usermenu'][] = Array($server_url . '/videos/' . $a->user['nickname'], t('Videos'), "", t('Your videos'));
$nav['usermenu'][] = Array($server_url . '/events/', t('Events'), "", t('Your events'));
$nav['network'] = array($server_url . '/network', t('Network'), "", t('Conversations from your friends'));
$nav['events'] = Array($server_url . '/events', t('Events'), "", t('Events and Calendar'));
$nav['messages'] = array($server_url . '/message', t('Messages'), "", t('Private mail'));
- $nav['settings'] = array($server_url . '/settings', t('Settings'),"", t('Account settings'));
- $nav['contacts'] = array($server_url . '/contacts', t('Contacts'),"", t('Manage/edit friends and contacts'));
+ $nav['settings'] = array($server_url . '/settings', t('Settings'), "", t('Account settings'));
+ $nav['contacts'] = array($server_url . '/contacts', t('Contacts'), "", t('Manage/edit friends and contacts'));
$nav['sitename'] = $a->config['sitename'];
}
}
+
/**
* @brief: Search for contacts
*
* @param App $a The app data @TODO Unused
* @param array $results The array with the originals from acl_lookup()
*/
-function frio_acl_lookup(App $a, &$results) {
- require_once("mod/contacts.php");
+function frio_acl_lookup(App $a, &$results)
+{
+ require_once 'mod/contacts.php';
- $nets = ((x($_GET,"nets")) ? notags(trim($_GET["nets"])) : "");
+ $nets = x($_GET, "nets") ? notags(trim($_GET["nets"])) : "";
// we introduce a new search type, r should do the same query like it's
// done in /mod/contacts for connections
$search_txt = dbesc(protect_sprintf(preg_quote($search)));
$searching = true;
}
- $sql_extra .= (($searching) ? " AND (`attag` LIKE '%%".dbesc($search_txt)."%%' OR `name` LIKE '%%".dbesc($search_txt)."%%' OR `nick` LIKE '%%".dbesc($search_txt)."%%') " : "");
+ $sql_extra = '';
+ if ($searching) {
+ $sql_extra .= " AND (`attag` LIKE '%%" . dbesc($search_txt) . "%%' OR `name` LIKE '%%" . dbesc($search_txt) . "%%' OR `nick` LIKE '%%" . dbesc($search_txt) . "%%') ";
+ }
if ($nets) {
$sql_extra .= sprintf(" AND network = '%s' ", dbesc($nets));
}
- $sql_extra2 = ((($sort_type > 0) && ($sort_type <= CONTACT_IS_FRIEND)) ? sprintf(" AND `rel` = %d ",intval($sort_type)) : '');
-
-
$r = q("SELECT COUNT(*) AS `total` FROM `contact`
- WHERE `uid` = %d AND NOT `self` AND NOT `pending` $sql_extra $sql_extra2 ",
+ WHERE `uid` = %d AND NOT `self` AND NOT `pending` $sql_extra ",
intval($_SESSION['uid']));
if (DBM::is_result($r)) {
$total = $r[0]["total"];
$sql_extra3 = unavailable_networks();
- $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `self` AND NOT `pending` $sql_extra $sql_extra2 $sql_extra3 ORDER BY `name` ASC LIMIT 100 ",
+ $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `self` AND NOT `pending` $sql_extra $sql_extra3 ORDER BY `name` ASC LIMIT 100 ",
intval($_SESSION['uid'])
);
/**
* @brief Manipulate the data of the item
- *
+ *
* At the moment we use this function to add some own stuff to the item menu
- *
+ *
* @param App $a App $a The app data
* @param array $arr Array with the item and the item actions<br>
* 'item' => Array with item data<br>
* 'output' => Array with item actions<br>
*/
-function frio_display_item(App $a,&$arr) {
-
+function frio_display_item(App $a, &$arr)
+{
// Add subthread to the item menu
$subthread = array();
- if ((local_user()) && local_user() == $arr['item']['uid'] && $arr['item']['parent'] == $arr['item']['id'] && (! $arr['item']['self'])) {
+ if (local_user() == $arr['item']['uid'] && $arr['item']['parent'] == $arr['item']['id'] && !$arr['item']['self']) {
$subthread = array(
'menu' => 'follow_thread',
'title' => t('Follow Thread'),