1
0
Fork 0

Merge branch 'develop' of https://github.com/friendica/friendica into develop

This commit is contained in:
hauke 2014-12-27 12:50:24 +01:00
commit 395be3dcde
705 changed files with 144082 additions and 143308 deletions

View file

@ -12,7 +12,7 @@ Deny from all
# Protect repository directory from browsing
RewriteRule "(^|/)\.git" - [F]
# Rewrite current-style URLs of the form 'index.php?q=x'.
# Rewrite current-style URLs of the form 'index.php?pagename=x'.
# Also place auth information into REMOTE_USER for sites running
# in CGI mode.
@ -28,7 +28,7 @@ Deny from all
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [E=REMOTE_USER:%{HTTP:Authorization},L,QSA]
RewriteRule ^(.*)$ index.php?pagename=$1 [E=REMOTE_USER:%{HTTP:Authorization},L,QSA]
</IfModule>

126
CHANGELOG Normal file
View file

@ -0,0 +1,126 @@
Version 3.3.2
Set default value for all not-null fields (fixes SQL warinigs) (annando)
Fix item filters in network page (issue #1222) (fabrixxm)
Remove reference to an ex Friendica hub from documentation (beardyunixer, tobiasd)
API throttling (annando)
Use a san-serif font in breathe style of vier theme (silke)
Prevent BBCode parsing problems with URLs (annando)
Add back tags to posts to Diaspora (annando)
Better display of pictures in posts (annando)
Fix out of control gprobe process (annando)
Version 3.3.1
JSONP support for API (fabrixxm)
Fixed small bug in direct messages API (fabrixxm)
More filter for direct messages API (fabrixxm)
New hooks "getsiteinfo", "page_info_data" (annando)
Better loop post prevention (annando)
Via API, replace data: uri images in plain text version with link to post. (issue #1134) (fabrixxm)
Set default location to empty for new users. Suppress warning on user creation (issue #1193) (fabrixxm)
Correctly build urls with queries (issue #1190) (fabrixxm)
Optionally use keywords in feed as post tags with "remote self" (annando)
A blacklist of keywords to not use can be defined (annando)
"remote self" works also with Friendica and Diaspora contacts (annando)
Show exact post time after 12 hours (FX7)
Optionally redirect from non-SSL to SSL (annando)
Translation updates
Added CHANGELOG
Version 3.3
API
added support in the API to allow image uploads from Twidere
support for the diaspora app in Firefox
Themes
Stopped support of unmaintained themes. They will continue to work if enabled but are no longer displayed in the list of themes.
Merged all "zero" themes into a theme with variations.
new default avatar by Andi Stadler
Usability
network page as default page after login
sections on users' settings page are now collapsable
automatic updating the network stream was improved
Interaction
ignoring of threads
for selected contects one can now get notifications when they post something, useful e.g. for forums
After a new friendica contact is added, the user is directed to the contact page of the new contact. (Instead of the remote profile)
many improvement on all connectors, new app.net connector
the algorithm for shortening postings when posting to limited platforms was improved
improvements for the remote_self functionality for RSS/Atom feeds were done
System stuff
no more apc support due problems with PHP 5.5
privacy image cache moved from an addon into the core
updated the following libraries: smarty 3.1.19, fullcalendar 1.6.4, jquery 1.11, jgrowl 1.3.0
added modernizer 2.8.3, better browser support
updates to the DB structure for better performance
preperations to use PDO in a later release
new notification system
web interface translations updated, addon translations now also possible separately from the main UI and done for CS, IT, RO, DE
vagrant support added for developers
some bugs were fixed for the profile import function
BBCode handling and reformatting to e.g. markdown was improved
Internal PusH server for communication with OStatus contacts
Addons
translation now done at transifex as well
"newmemberwidget" adds widget with help links + welcome message to sidebar of network tab for new members
new statistics addon to take part in the Diaspora* survey
new bidirectional connector for app.net
new relay connector for Diaspora*
new connector for the buffer service
improvements for the connectors with Twitter, StatusNet/GNU Social, pump.io, google+ and facebook
improvements to the cal and jappix-mini addons
Change in the structure of the git repo
The "master" branch will now contain stable stuff and hotfixes.
The new "develop" branch will contain the latest changes.
Version 3.2
LICENSE change from Friendica uses now the AGPL
Language updates: PT_BR, RU, NB_NO, DE, PL, CS, ZH-CN, IT, CA, FR, NL
new languages: BG
added a README.translate and updates to the translation utils
addons are now translated separately
Theme updates: vier, smoothly, diabook, decaf-mobile, dispy, frost, frost-mobile, quattro
Bug fixes: #516, #517, #525, #476, #540, #546, #712, #728
sample nginx and lighttpd config
new default templating engine: smarty3
new share element
maintenance mode for longer running upgrade tasks
small fixed
edit profile photo link
better caching of pictures
threadening for outgoing emails
mail import
oembed thumbnails
SN subscriptions & more SN like behaviour if snautofollow addon is used
collect content of SN discussion threads
communication with Diaspora*
usage of the API
search improvements
MIME types for attachments
support Open Graph and Dublin Core when showing single items
better use of APC if present
use https versions of videos from youtube and vimeo to make firefox happy
fixes to the documentation
if a home.html is there, home.css is used as well
update included TinyMCE to version 3.5.8, fancybox
made more options available in the admin panel that were hidden before
show the admin information about when accounts expire in the admin panel
improving the install.php script
addons now can be members only
item object now contains the "edited" information left for the theme designers to show this info in a pretty way
improvments to the user-import from exported account files
It's now possible to authenticate an ejabberd server against friendica.
bugtracker moved to github
improvements to MySQL queries
Version 3.1
See http://friendica.com/node/58

218
Vagrantfile vendored
View file

@ -1,78 +1,21 @@
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Config Github Settings
github_username = "fideloper"
github_repo = "Vaprobash"
github_branch = "1.0.0"
github_url = "https://raw.githubusercontent.com/#{github_username}/#{github_repo}/#{github_branch}"
# Server Configuration
hostname = "vaprobash.dev"
# Set a local private network IP address.
# See http://en.wikipedia.org/wiki/Private_network for explanation
# You can use the following IP ranges:
# 10.0.0.1 - 10.255.255.254
# 172.16.0.1 - 172.31.255.254
# 192.168.0.1 - 192.168.255.254
server_ip = "192.168.22.10"
server_memory = "384" # MB
server_swap = "768" # Options: false | int (MB) - Guideline: Between one or two times the server_memory
server_timezone = "UTC"
# Database Configuration
mysql_root_password = "root" # We'll assume user "root"
mysql_version = "5.5" # Options: 5.5 | 5.6
mysql_enable_remote = "false" # remote access enabled when true
pgsql_root_password = "root" # We'll assume user "root"
# Languages and Packages6
ruby_version = "latest" # Choose what ruby version should be installed (will also be the default version)
ruby_gems = [ # List any Ruby Gems that you want to install
#"jekyll",
#"sass",
#"compass",
]
# To install HHVM instead of PHP, set this to "true"
hhvm = "false"
# PHP Options
composer_packages = [ # List any global Composer packages that you want to install
#"phpunit/phpunit:4.0.*",
#"codeception/codeception=*",
#"phpspec/phpspec:2.0.*@dev",
#"squizlabs/php_codesniffer:1.5.*",
]
# Default web server document root
# Symfony's public directory is assumed "web"
# Laravel's public directory is assumed "public"
public_folder = "/vagrant"
laravel_root_folder = "/vagrant/laravel" # Where to install Laravel. Will `composer install` if a composer.json file exists
laravel_version = "latest-stable" # If you need a specific version of Laravel, set it here
symfony_root_folder = "/vagrant/symfony" # Where to install Symfony.
nodejs_version = "latest" # By default "latest" will equal the latest stable version
nodejs_packages = [ # List any global NodeJS packages that you want to install
#"grunt-cli",
#"gulp",
#"bower",
#"yo",
]
Vagrant.configure("2") do |config|
# Set server to Ubuntu 14.04
config.vm.box = "ubuntu/trusty64"
# Set server to Ubuntu 12.04
config.vm.box = "precise64"
config.vm.box_url = "http://files.vagrantup.com/precise64.box"
# Create a hostname, don't forget to put it to the `hosts` file
# This will point to the server's default virtual host
# TO DO: Make this work with virtualhost along-side xip.io URL
config.vm.hostname = hostname
config.vm.hostname = "friendica.dev"
# Create a static IP
config.vm.network :private_network, ip: server_ip
@ -103,161 +46,14 @@ Vagrant.configure("2") do |config|
end
# If using Vagrant-Cachier
# http://fgrehm.viewdocs.io/vagrant-cachier
if Vagrant.has_plugin?("vagrant-cachier")
# Configure cached packages to be shared between instances of the same base box.
# Usage docs: http://fgrehm.viewdocs.io/vagrant-cachier/usage
config.cache.scope = :box
config.cache.synced_folder_opts = {
type: :nfs,
mount_options: ['rw', 'vers=3', 'tcp', 'nolock']
}
end
####
# Base Items
##########
# Provision Base Packages
config.vm.provision "shell", path: "#{github_url}/scripts/base.sh", args: [github_url, server_swap]
# Provision PHP
config.vm.provision "shell", path: "#{github_url}/scripts/php.sh", args: [server_timezone, hhvm]
# Enable MSSQL for PHP
# config.vm.provision "shell", path: "#{github_url}/scripts/mssql.sh"
# Provision Vim
# config.vm.provision "shell", path: "#{github_url}/scripts/vim.sh", args: github_url
####
# Web Servers
##########
# Provision Apache Base
config.vm.provision "shell", path: "#{github_url}/scripts/apache.sh", args: [server_ip, public_folder, hostname, github_url]
# Provision Nginx Base
# config.vm.provision "shell", path: "#{github_url}/scripts/nginx.sh", args: [server_ip, public_folder, hostname, github_url]
####
# Databases
##########
# Provision MySQL
config.vm.provision "shell", path: "#{github_url}/scripts/mysql.sh", args: [mysql_root_password, mysql_version, mysql_enable_remote]
# Provision PostgreSQL
# config.vm.provision "shell", path: "#{github_url}/scripts/pgsql.sh", args: pgsql_root_password
# Provision SQLite
# config.vm.provision "shell", path: "#{github_url}/scripts/sqlite.sh"
# Provision RethinkDB
# config.vm.provision "shell", path: "#{github_url}/scripts/rethinkdb.sh", args: pgsql_root_password
# Provision Couchbase
# config.vm.provision "shell", path: "#{github_url}/scripts/couchbase.sh"
# Provision CouchDB
# config.vm.provision "shell", path: "#{github_url}/scripts/couchdb.sh"
# Provision MongoDB
# config.vm.provision "shell", path: "#{github_url}/scripts/mongodb.sh"
# Provision MariaDB
# config.vm.provision "shell", path: "#{github_url}/scripts/mariadb.sh", args: [mysql_root_password, mysql_enable_remote]
####
# Search Servers
##########
# Install Elasticsearch
# config.vm.provision "shell", path: "#{github_url}/scripts/elasticsearch.sh"
# Install SphinxSearch
# config.vm.provision "shell", path: "#{github_url}/scripts/sphinxsearch.sh"
####
# Search Server Administration (web-based)
##########
# Install ElasticHQ
# Admin for: Elasticsearch
# Works on: Apache2, Nginx
# config.vm.provision "shell", path: "#{github_url}/scripts/elastichq.sh"
####
# In-Memory Stores
##########
# Install Memcached
# config.vm.provision "shell", path: "#{github_url}/scripts/memcached.sh"
# Provision Redis (without journaling and persistence)
# config.vm.provision "shell", path: "#{github_url}/scripts/redis.sh"
# Provision Redis (with journaling and persistence)
# config.vm.provision "shell", path: "#{github_url}/scripts/redis.sh", args: "persistent"
# NOTE: It is safe to run this to add persistence even if originally provisioned without persistence
####
# Utility (queue)
##########
# Install Beanstalkd
# config.vm.provision "shell", path: "#{github_url}/scripts/beanstalkd.sh"
# Install Heroku Toolbelt
# config.vm.provision "shell", path: "https://toolbelt.heroku.com/install-ubuntu.sh"
# Install Supervisord
# config.vm.provision "shell", path: "#{github_url}/scripts/supervisord.sh"
####
# Additional Languages
##########
# Install Nodejs
# config.vm.provision "shell", path: "#{github_url}/scripts/nodejs.sh", privileged: false, args: nodejs_packages.unshift(nodejs_version, github_url)
# Install Ruby Version Manager (RVM)
# config.vm.provision "shell", path: "#{github_url}/scripts/rvm.sh", privileged: false, args: ruby_gems.unshift(ruby_version)
####
# Frameworks and Tooling
##########
# Provision Composer
# config.vm.provision "shell", path: "#{github_url}/scripts/composer.sh", privileged: false, args: composer_packages.join(" ")
# Provision Laravel
# config.vm.provision "shell", path: "#{github_url}/scripts/laravel.sh", privileged: false, args: [server_ip, laravel_root_folder, public_folder, laravel_version]
# Provision Symfony
# config.vm.provision "shell", path: "#{github_url}/scripts/symfony.sh", privileged: false, args: [server_ip, symfony_root_folder, public_folder]
# Install Screen
# config.vm.provision "shell", path: "#{github_url}/scripts/screen.sh"
# Install config Mailcatcher
# config.vm.provision "shell", path: "#{github_url}/scripts/mailcatcher.sh"
# Install git-ftp
# config.vm.provision "shell", path: "#{github_url}/scripts/git-ftp.sh", privileged: false
####
# Local Scripts
# Any local scripts you may want to run post-provisioning.
# Add these to the same directory as the Vagrantfile.
##########
config.vm.provision "shell", path: "./util/vagrant_provision.sh"
config.vm.synced_folder "./", "/vagrant/", :owner=> 'www-data', :group=>'vagrant', :mount_options => ['dmode=775', 'fmode=775']
config.vm.provision "shell", path: "./util/vagrant_provision.sh"
end

141
boot.php
View file

@ -11,10 +11,14 @@ require_once('include/cache.php');
require_once('library/Mobile_Detect/Mobile_Detect.php');
require_once('include/features.php');
require_once('update.php');
require_once('include/dbstructure.php');
define ( 'FRIENDICA_PLATFORM', 'Friendica');
define ( 'FRIENDICA_VERSION', '3.2.1753' );
define ( 'FRIENDICA_CODENAME', 'Ginger');
define ( 'FRIENDICA_VERSION', '3.3.2' );
define ( 'DFRN_PROTOCOL_VERSION', '2.23' );
define ( 'DB_UPDATE_VERSION', 1173 );
define ( 'DB_UPDATE_VERSION', 1175 );
define ( 'EOL', "<br />\r\n" );
define ( 'ATOM_TIME', 'Y-m-d\TH:i:s\Z' );
@ -505,17 +509,30 @@ if(! class_exists('App')) {
$argc --;
}
set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
#set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
$this->query_string = substr($_SERVER['QUERY_STRING'],9);
// removing trailing / - maybe a nginx problem
if (substr($this->query_string, 0, 1) == "/")
$this->query_string = substr($this->query_string, 1);
} elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
$this->query_string = substr($_SERVER['QUERY_STRING'],2);
// removing trailing / - maybe a nginx problem
if (substr($this->query_string, 0, 1) == "/")
$this->query_string = substr($this->query_string, 1);
}
if(x($_GET,'q'))
if (x($_GET,'pagename'))
$this->cmd = trim($_GET['pagename'],'/\\');
elseif (x($_GET,'q'))
$this->cmd = trim($_GET['q'],'/\\');
// fix query_string
$this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
// unix style "homedir"
if(substr($this->cmd,0,1) === '~')
@ -526,6 +543,7 @@ if(! class_exists('App')) {
if(substr($this->cmd,0,2) === 'u/')
$this->cmd = 'profile/' . substr($this->cmd,2);
/**
*
* Break the URL path into C style argc/argv style arguments for our
@ -598,6 +616,10 @@ if(! class_exists('App')) {
return($basepath);
}
function get_scheme() {
return($this->scheme);
}
function get_baseurl($ssl = false) {
$scheme = $this->scheme;
@ -617,6 +639,9 @@ if(! class_exists('App')) {
}
}
if (get_config('config','hostname') != "")
$this->hostname = get_config('config','hostname');
$this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
return $this->baseurl;
}
@ -638,12 +663,19 @@ if(! class_exists('App')) {
if (file_exists(".htpreconfig.php"))
@include(".htpreconfig.php");
if (get_config('config','hostname') != "")
$this->hostname = get_config('config','hostname');
if (!isset($this->hostname) OR ($this->hostname == ""))
$this->hostname = $hostname;
}
}
function get_hostname() {
if (get_config('config','hostname') != "")
$this->hostname = get_config('config','hostname');
return $this->hostname;
}
@ -865,6 +897,10 @@ if(! class_exists('App')) {
$this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
}
function get_useragent() {
return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
}
}
}
@ -992,7 +1028,6 @@ if(! function_exists('check_url')) {
if(! function_exists('update_db')) {
function update_db(&$a) {
$build = get_config('system','build');
if(! x($build))
$build = set_config('system','build',DB_UPDATE_VERSION);
@ -1000,53 +1035,61 @@ if(! function_exists('update_db')) {
if($build != DB_UPDATE_VERSION) {
$stored = intval($build);
$current = intval(DB_UPDATE_VERSION);
if(($stored < $current) && file_exists('update.php')) {
if($stored < $current) {
load_config('database');
// We're reporting a different version than what is currently installed.
// Run any existing update scripts to bring the database up to current.
require_once('update.php');
// 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 = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
if($t !== false)
break;
return;
set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
require_once("include/dbstructure.php");
// 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;
// run new update routine
// it update the structure in one call
$retval = update_structure(false, true);
if($retval) {
//send the administrator an e-mail
$email_tpl = get_intltext_template("update_fail_eml.tpl");
$email_msg = replace_macros($email_tpl, array(
'$sitename' => $a->config['sitename'],
'$siteurl' => $a->get_baseurl(),
'$update' => DB_UPDATE_VERSION,
'$error' => sprintf(t('Update %s failed. See error logs.'), DB_UPDATE_VERSION)
));
$subject=sprintf(t('Update Error at %s'), $a->get_baseurl());
require_once('include/email.php');
$subject = email_header_encode($subject,'UTF-8');
mail($a->config['admin_email'], $subject, $email_msg,
'From: ' . 'Administrator' . '@' . $_SERVER['SERVER_NAME']."\n"
.'Content-type: text/plain; charset=UTF-8'."\n"
.'Content-transfer-encoding: 8bit');
//try the logger
logger("CRITICAL: Database structure update failed: ".$retval);
break;
} else
update_fail(
DB_UPDATE_VERSION,
$retval
);
return;
} else {
set_config('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;
}
}
}
}
return;
}
}
if(!function_exists('run_update_function')){
function run_update_function($x) {
if(function_exists('update_' . $x)) {
// There could be a lot of processes running or about to run.
@ -1059,46 +1102,32 @@ if(! function_exists('update_db')) {
$t = get_config('database','update_' . $x);
if($t !== false)
break;
return false;
set_config('database','update_' . $x, time());
// call the specific update
$func = 'update_' . $x;
$retval = $func();
if($retval) {
//send the administrator an e-mail
$email_tpl = get_intltext_template("update_fail_eml.tpl");
$email_msg = replace_macros($email_tpl, array(
'$sitename' => $a->config['sitename'],
'$siteurl' => $a->get_baseurl(),
'$update' => $x,
'$error' => sprintf( t('Update %s failed. See error logs.'), $x)
));
$subject=sprintf(t('Update Error at %s'), $a->get_baseurl());
require_once('include/email.php');
$subject = email_header_encode($subject,'UTF-8');
mail($a->config['admin_email'], $subject, $email_msg,
'From: ' . 'Administrator' . '@' . $_SERVER['SERVER_NAME'] . "\n"
. 'Content-type: text/plain; charset=UTF-8' . "\n"
. 'Content-transfer-encoding: 8bit' );
//try the logger
logger('CRITICAL: Update Failed: '. $x);
break;
update_fail(
$x,
sprintf(t('Update %s failed. See error logs.'), $x)
);
return false;
} else {
set_config('database','update_' . $x, 'success');
set_config('system','build', $x + 1);
return true;
}
} else {
set_config('database','update_' . $x, 'success');
set_config('system','build', $x + 1);
return true;
}
}
}
}
}
return;
return true;
}
}

View file

@ -1,42 +0,0 @@
Friendica 3.2
------------
* LICENSE change from Friendica uses now the AGPL
* Language updates: PT_BR, RU, NB_NO, DE, PL, CS, ZH-CN, IT, CA, FR, NL
* new languages: BG
* added a README.translate and updates to the translation utils
* addons are now translated separately
* Theme updates: vier, smoothly, diabook, decaf-mobile, dispy, frost, frost-mobile, quattro
* Bug fixes: #516, #517, #525, #476, #540, #546, #712, #728
* sample nginx and lighttpd config
* new default templating engine: smarty3
* new share element
* maintenance mode for longer running upgrade tasks
* small fixed
* edit profile photo link
* better caching of pictures
* threadening for outgoing emails
* mail import
* oembed thumbnails
* SN subscriptions & more SN like behaviour if snautofollow addon is used
* collect content of SN discussion threads
* communication with Diaspora*
* usage of the API
* search improvements
* MIME types for attachments
* support Open Graph and Dublin Core when showing single items
* better use of APC if present
* use https versions of videos from youtube and vimeo to make firefox happy
* fixes to the documentation
* if a home.html is there, home.css is used as well
* update included TinyMCE to version 3.5.8, fancybox
* made more options available in the admin panel that were hidden before
* show the admin information about when accounts expire in the admin panel
* improving the install.php script
* addons now can be members only
* item object now contains the "edited" information left for the theme designers to show this info in a pretty way
* improvments to the user-import from exported account files
* It's now possible to authenticate an ejabberd server against friendica.
* bugtracker moved to github
* improvements to MySQL queries

View file

@ -12,6 +12,7 @@ User
* **[What happens when an account is removed? Is it truly deleted?](help/FAQ#removed)**
* **[Can I subscribe to a hashtag?](help/FAQ#hashtag)**
* **[How to create a RSS feed of the stream?](help/FAQ#rss)**
* **[Are there any clients for friendica I can use?](help/FAQ#clients)**
* **[Where I can find help?](help/FAQ#help)**
Admins
@ -39,7 +40,6 @@ Sometimes you get a browser warning about a missing certificate. These warnings
If you dont have a SSL cert yet, there are three ways to get one: buy one, get a free one (eg. via StartSSL) or create your own (not recommended). [You can find more information about setting up SSL and why it's a bad idea to use self-signed SSL here.](help/SSL)
Be aware that a browser warning about security issues is something that can make new users feel insecure about the whole friendica project.
Because of this, Friendica Red will only accept SSL certs signed by a recognized CA and doesn't connect to servers without these kind of SSL. Despite of the negative aspects of SSL, this is a necessary solution until there is an established alternative for this technique.
Also you can have problems with the connection to diaspora because some pods require a SSL-certificated connection.
@ -130,14 +130,33 @@ RSS feed of the conversations at your site
https://helpers.pyxis.uberspace.de/dfrn_poll/helpers/converse
<a name="clients"></a>
**Are there any clients for friendica I can use?**
Friendica is using a [Twitter/StatusNet compatible API](help/api), which means you can use any Twitter/StatusNet/GNU Social client for your plattform as long as you can change the API path in its settings. Here is a list of known working clients
* Android
* Friendica Client for Android
* AndStatus
* Twidere
* Mustard and Mustard-Mod
* Linux
* Hotot
* Choqok
* MacOS X
* Hotot
* Windows
* Hotot
Depending on the features of the client you might encounter some glitches in usability, like being limited in the length of your postings to 140 characters and having no access to the [permission settings](help/Groups-and-Privacy).
<a name="help"></a>
**Where I can find help?**
If you have problems with your Friendica page, you can ask the community at the [Friendica Support Group](https://helpers.pyxis.uberspace.de/profile/helpers). If you can't use your default profile you can either use a test account [test server](http://friendica.com/node/31) respectively an account at a public site [list](http://dir.friendica.com/siteinfo) or you can use the Librelist mailing list. If you want to use the mailing list, please just send a mail to friendica AT librelist DOT com.
If you are using Friendica Red, you will also find help at this forum: [Friendica Red Development](https://myfriendica.net/profile/friendicared).
If you are a theme developer, you will find help at this forum: [Friendica Theme Developers](https://friendica.eu/profile/ftdevs).
Admin
@ -147,13 +166,13 @@ Admin
**Can I configure multiple domains with the same code instance?**
You can do that. What you can't do is point two different domains at the same database. As long as .htconfig.php exists to keep it from trying to do an install, you can keep the real config in include/$hostname/.htconfig.php All of the cache and lock stuff can be configured per instance.
This function is not supported anymore starting from Friendica 3.3
<a name="sources"></a>
**Where can I find the source code of friendica, addons and themes?**
You can find the main respository [here](https://github.com/friendica/friendica). There you will always find the current stable version of friendica. The source files of Friendica Red are [here](https://github.com/friendica/red).
You can find the main respository [here](https://github.com/friendica/friendica). There you will always find the current stable version of friendica.
Addons are listed at [this page](https://github.com/friendica/friendica-addons).

View file

@ -33,6 +33,8 @@ Friendica Documentation and Resources
* [Message Flow](help/Message-Flow)
* [Using SSL with Friendica](help/SSL)
* [Developers](help/Developers)
* [Twitter/StatusNet API Functions](help/api)
* [Translation of Friendica](help/translations)
**External Resources**

View file

@ -70,19 +70,6 @@ This plugin reduces the database load massively. Downside: You can't see the tot
Go to the admin settings of "altpager" and set it to "global".
###Privacy Image Cache
**Description**
This plugin pre-fetches external content and stores it in the cache. Besides speeding up the page rendering it is also good for the privacy of your users, since embedded pictures are loaded from your site and not from a foreign site (that could spy on the IP addresses).
Additionally it helps with content from external sites that have slow performance or aren not online all the time.
**Administration**
Please create a folder named "privacy_image_cache" and "photo" in your web root. If these folders exists then the cached files will be stored there. This has the great advantage that your web server will fetch the files directly from there.
###rendertime
This plugin doesn't speed up your system. It helps analyzing your bottlenecks.

View file

@ -47,7 +47,7 @@ you might have trouble getting everything to work.]
`mkdir view/smarty3`
`chown 777 view/smarty3`
`chmod 777 view/smarty3`
- For installing addons

View file

@ -5,9 +5,7 @@ Making Friends
Friendship in Friendica can take on a great many different meanings. But let's keep it simple, you want to be friends with somebody. How do you do it?
The easiest thing to do is to join the <a href="http://kakste.com/profile/newhere">New Here</a> group. This group is especially for people new to the Friendica network. Simply connect to the group, post to the wall, and make new friends. You don't even have to like us - comment on a few of our posts, and other people will start to add you too.
The next thing you can do is look at the Directory. The directory is split up into two parts. If you click the directory button, you will be presented with a list of all members (who chose to be listed) on your server. You'll also see a link to the Global Directory. If you click through to the global directory, you will be presented with a list of everybody who chose to be listed across all instances of Friendica. You will also see a "Show Community Forums" link, which will direct you to Groups, Forums and Fanpages. You connect to people, groups and forums in the same way, except groups and forums will automatically accept your introduction request, whereas a human will approve you manually.
The first thing you can do is look at the Directory. The directory is split up into two parts. If you click the directory button, you will be presented with a list of all members (who chose to be listed) on your server. You'll also see a link to the Global Directory. If you click through to the global directory, you will be presented with a list of everybody who chose to be listed across all instances of Friendica. You will also see a "Show Community Forums" link, which will direct you to Groups, Forums and Fanpages. You connect to people, groups and forums in the same way, except groups and forums will automatically accept your introduction request, whereas a human will approve you manually.
To connect with other Friendica users:

View file

@ -7,12 +7,8 @@ Here are some more things to help get you started:
**Groups**
- <a href="https://kakste.com/profile/newhere">New Here</a> - a group for people new to Friendica
- <a href="http://helpers.pyxis.uberspace.de/profile/helpers">Friendica Support</a> - problems? This is the place to ask.
- <a href="https://kakste.com/profile/public_stream">Public Stream</a> - a place to talk about anything to anyone.
- <a href="https://letstalk.pyxis.uberspace.de/profile/letstalk">Let's Talk</a> a group for finding people and groups who share similar interests.
- <a href="http://newzot.hydra.uberspace.de/profile/newzot">Local Friendica</a> a page for local Friendica groups</a>

362
doc/api.md Normal file
View file

@ -0,0 +1,362 @@
The friendica API aims to be compatible to the [StatusNet API](http://status.net/wiki/Twitter-compatible_API) which aims to be compatible to the [Twitter API 1.0](https://dev.twitter.com/docs/api/1).
Please refer to the linked documentation for further information.
## Implemented API calls
### General
#### Unsupported parameters
* cursor: Not implemented in StatusNet
* trim_user: Not implemented in StatusNet
* contributor_details: Not implemented in StatusNet
* place_id: Not implemented in StatusNet
* display_coordinates: Not implemented in StatusNet
* include_rts: To-Do
* include_my_retweet: Retweets in friendica are implemented in a different way
#### Different behaviour
* screen_name: The nick name in friendica is only unique in each network but not for all networks. The users are searched in the following priority: Friendica, StatusNet/GNU Social, Diaspora, pump.io, Twitter. If no contact was found by this way, then the first contact is taken.
* include_entities: Default is "false". If set to "true" then the plain text is formatted so that links are having descriptions.
#### Return values
* cid: Contact id of the user (important for "contact_allow" and "contact_deny")
* network: network of the user
### account/verify_credentials
#### Parameters
* skip_status: Don't show the "status" field. (Default: false)
* include_entities: "true" shows entities for pictures and links (Default: false)
### statuses/update, statuses/update_with_media
#### Parameters
* title: Title of the status
* status: Status in text format
* htmlstatus: Status in HTML format
* in_reply_to_status_id
* lat: latitude
* long: longitude
* media: image data
* source: Application name
* group_allow
* contact_allow
* group_deny
* contact_deny
* network
* include_entities: "true" shows entities for pictures and links (Default: false)
#### Unsupported parameters
* trim_user
* place_id
* display_coordinates
### users/search
#### Parameters
* q: name of the user
#### Unsupported parameters
* page
* count
* include_entities
### users/show
#### Parameters
* user_id: id of the user
* screen_name: screen name (for technical reasons, this value is not unique!)
* include_entities: "true" shows entities for pictures and links (Default: false)
### statuses/home_timeline
#### Parameters
* count: Items per page (default: 20)
* page: page number
* since_id: minimal id
* max_id: maximum id
* exclude_replies: don't show replies (default: false)
* conversation_id: Shows all statuses of a given conversation.
* include_entities: "true" shows entities for pictures and links (Default: false)
#### Unsupported parameters
* include_rts
* trim_user
* contributor_details
### statuses/friends_timeline
#### Parameters
* count: Items per page (default: 20)
* page: page number
* since_id: minimal id
* max_id: maximum id
* exclude_replies: don't show replies (default: false)
* conversation_id: Shows all statuses of a given conversation.
* include_entities: "true" shows entities for pictures and links (Default: false)
#### Unsupported parameters
* include_rts
* trim_user
* contributor_details
### statuses/public_timeline
#### Parameters
* count: Items per page (default: 20)
* page: page number
* since_id: minimal id
* max_id: maximum id
* exclude_replies: don't show replies (default: false)
* conversation_id: Shows all statuses of a given conversation.
* include_entities: "true" shows entities for pictures and links (Default: false)
#### Unsupported parameters
* trim_user
### statuses/show
#### Parameters
* id: message number
* conversation: if set to "1" show all messages of the conversation with the given id
* include_entities: "true" shows entities for pictures and links (Default: false)
#### Unsupported parameters
* include_my_retweet
* trim_user
### statuses/retweet
#### Parameters
* id: message number
* include_entities: "true" shows entities for pictures and links (Default: false)
#### Unsupported parameters
* trim_user
### statuses/destroy
#### Parameters
* id: message number
* include_entities: "true" shows entities for pictures and links (Default: false)
#### Unsupported parameters
* trim_user
### statuses/mentions
#### Parameters
* count: Items per page (default: 20)
* page: page number
* since_id: minimal id
* max_id: maximum id
* include_entities: "true" shows entities for pictures and links (Default: false)
#### Unsupported parameters
* include_rts
* trim_user
* contributor_details
### statuses/replies
#### Parameters
* count: Items per page (default: 20)
* page: page number
* since_id: minimal id
* max_id: maximum id
* include_entities: "true" shows entities for pictures and links (Default: false)
#### Unsupported parameters
* include_rts
* trim_user
* contributor_details
### statuses/user_timeline
#### Parameters
* user_id: id of the user
* screen_name: screen name (for technical reasons, this value is not unique!)
* count: Items per page (default: 20)
* page: page number
* since_id: minimal id
* max_id: maximum id
* exclude_replies: don't show replies (default: false)
* conversation_id: Shows all statuses of a given conversation.
* include_entities: "true" shows entities for pictures and links (Default: false)
#### Unsupported parameters
* include_rts
* trim_user
* contributor_details
### conversation/show
Unofficial Twitter command. It shows all direct answers (excluding the original post) to a given id.
#### Parameters
* id: id of the post
* count: Items per page (default: 20)
* page: page number
* since_id: minimal id
* max_id: maximum id
* include_entities: "true" shows entities for pictures and links (Default: false)
#### Unsupported parameters
* include_rts
* trim_user
* contributor_details
### favorites
#### Parameters
* count: Items per page (default: 20)
* page: page number
* since_id: minimal id
* max_id: maximum id
* include_entities: "true" shows entities for pictures and links (Default: false)
#### Unsupported parameters
* user_id
* screen_name
Favorites aren't displayed to other users, so "user_id" and "screen_name". So setting this value will result in an empty array.
### account/rate_limit_status
### help/test
### statuses/friends
* include_entities: "true" shows entities for pictures and links (Default: false)
#### Unsupported parameters
* user_id
* screen_name
* cursor
Friendica doesn't allow showing friends of other users.
### statuses/followers
* include_entities: "true" shows entities for pictures and links (Default: false)
#### Unsupported parameters
* user_id
* screen_name
* cursor
Friendica doesn't allow showing followers of other users.
### statusnet/config
### statusnet/version
### friends/ids
#### Parameters
* stringify_ids: Should the id numbers be sent as text (true) or number (false)? (default: false)
#### Unsupported parameters
* user_id
* screen_name
* cursor
Friendica doesn't allow showing friends of other users.
### followers/ids
#### Parameters
* stringify_ids: Should the id numbers be sent as text (true) or number (false)? (default: false)
#### Unsupported parameters
* user_id
* screen_name
* cursor
Friendica doesn't allow showing followers of other users.
### direct_messages/new
#### Parameters
* user_id: id of the user
* screen_name: screen name (for technical reasons, this value is not unique!)
* text: The message
* replyto: ID of the replied direct message
* title: Title of the direct message
### direct_messages/conversation
Shows all direct messages of a conversation
#### Parameters
* count: Items per page (default: 20)
* page: page number
* since_id: minimal id
* max_id: maximum id
* getText: Defines the format of the status field. Can be "html" or "plain"
* uri: URI of the conversation
### direct_messages/all
#### Parameters
* count: Items per page (default: 20)
* page: page number
* since_id: minimal id
* max_id: maximum id
* getText: Defines the format of the status field. Can be "html" or "plain"
### direct_messages/sent
#### Parameters
* count: Items per page (default: 20)
* page: page number
* since_id: minimal id
* max_id: maximum id
* getText: Defines the format of the status field. Can be "html" or "plain"
* include_entities: "true" shows entities for pictures and links (Default: false)
### direct_messages
#### Parameters
* count: Items per page (default: 20)
* page: page number
* since_id: minimal id
* max_id: maximum id
* getText: Defines the format of the status field. Can be "html" or "plain"
* include_entities: "true" shows entities for pictures and links (Default: false)
#### Unsupported parameters
* skip_status
### oauth/request_token
#### Parameters
* oauth_callback
#### Unsupported parameters
* x_auth_access_type
### oauth/access_token
#### Parameters
* oauth_verifier
#### Unsupported parameters
* x_auth_password
* x_auth_username
* x_auth_mode
## Not Implemented API calls
The following list is extracted from the [API source file](https://github.com/friendica/friendica/blob/master/include/api.php) (at the very bottom):
* favorites/create
* favorites/destroy
* statuses/retweets_of_me
* friendships/create
* friendships/destroy
* friendships/exists
* friendships/show
* account/update_location
* account/update_profile_background_image
* account/update_profile_image
* blocks/create
* blocks/destroy
The following are things from the Twitter API also not implemented in StatusNet:
* statuses/retweeted_to_me
* statuses/retweeted_by_me
* direct_messages/destroy
* account/end_session
* account/update_delivery_device
* notifications/follow
* notifications/leave
* blocks/exists
* blocks/blocking
* lists
## Usage Examples
### BASH / cURL
Betamax has documentated some example API usage from a [bash script](https://en.wikipedia.org/wiki/Bash_(Unix_shell) employing [curl](https://en.wikipedia.org/wiki/CURL) (see [his posting](https://betamax65.de/display/betamax65/43539)).
/usr/bin/curl -u USER:PASS https://YOUR.FRIENDICA.TLD/api/statuses/update.xml -d source="some source id" -d status="the status you want to post"
### Python
The [RSStoFriedika](https://github.com/pafcu/RSStoFriendika) code can be used as an example of how to use the API with python. The lines for posting are located at [line 21](https://github.com/pafcu/RSStoFriendika/blob/master/RSStoFriendika.py#L21) and following.
def tweet(server, message, group_allow=None):
url = server + '/api/statuses/update'
urllib2.urlopen(url, urllib.urlencode({'status': message,'group_allow[]':group_allow}, doseq=True))
There is also a [module for python 3](https://bitbucket.org/tobiasd/python-friendica) for using the API.

View file

@ -33,6 +33,8 @@ Friendica - Dokumentation und Ressourcen
* [Nachrichtenfluss](help/Message-Flow)
* [Betreibe deine Seite mit einem SSL-Zertifikat](help/SSL)
* [Entwickler](help/Developers)
* [Twitter/StatusNet API Functions](help/api) (EN)
* [Translation of Friendica](help/translations) (EN)
**Externe Ressourcen**

View file

@ -65,18 +65,6 @@ Dieses Plugin reduziert die Ladezeit der Datenbank massiv. Nachteil: Du kannst n
Gehe auf admin/plugins/altpager und wähle "global".
###Privacy Image Cache
**Beschreibung**
Dieses Plugin lädt externe Inhalte vor und speichert sie im Cache. Neben der Beschleunigung der Seite dient es so außerdem dazu, die Privatssphäre der Nutzer zu schützen, da eingebettete Inhalte so von deiner Seite aus geladen werden und nicht von externen Quellen (die deine IP-Adresse ermitteln könnten).
Ebenso hilft es bei Inhalten, die nur langsam laden oder nicht immer online sind.
**Einrichtung**
Bitte erstelle einen Ordner namens "privacy_image_cache" und "photo" in deinem Stammverzeichnis. Wenn diese Ordner existieren, dann werden die zwischengespeicherten Inhalte dort abgelegt. Dies hat den großen Vorteil, dass der Server die Dateien direkt von dort bezieht.
###rendertime
**Beschreibung**

View file

@ -5,9 +5,7 @@ Freunde finden
Freundschaft kann in Friendica viele verschiedene Bedeutungen annehmen. Aber lasst es uns einfach halten, du willst einfach mit jemandem befreundet sein. Wie machst du das?
Der einfachste Weg, um das zu machen, ist es, der Gruppe <a href="http://kakste.com/profile/newhere">Neu hier</a> beizutreten. Diese Gruppe ist speziell für Leute, die neu im Friendica-Netzwerk sind. Verbinde dich einfach mit der Gruppe, schreibe auf die "Wall" und lerne neue Leute kennen. Du musst uns nicht einmal direkt "liken" - kommentiere einige Beiträge und andere Leute werden anfangen, dich hinzuzufügen.
Als Nächstes kannst du dir das Verzeichnis anschauen. Das Verzeichnis ist in zwei Teile aufgeteilt. Wenn du auf den "Verzeichnis"-Button klickst, wirst du zunächst alle Mitglieder deines Servers sehen, die sich dazu entschlossen haben, angezeigt zu werden. Außerdem siehst du dort einen Link zum globalen Verzeichnis. Wenn du dich durch das globale Verzeichnis klickst, siehst du alle Nutzer weltweit auf allen Servern, die sich entschlossen haben, im Verzeichnis zu erscheinen. Du wirst außerdem den Link "Show Community Forums" sehen, welcher dich zu Gruppen, Foren und Fan-Seiten führt. Du verbindest dich mit Personen, Gruppen und Foren auf die gleiche Art, wobei Gruppen und Foren deine Anfrage automatisch annehmen, wohingegen ein Mensch dich erst manuell bestätigen muss.
Schau dir das Verzeichnis an. Das Verzeichnis ist in zwei Teile aufgeteilt. Wenn du auf den "Verzeichnis"-Button klickst, wirst du zunächst alle Mitglieder deines Servers sehen, die sich dazu entschlossen haben, angezeigt zu werden. Außerdem siehst du dort einen Link zum globalen Verzeichnis. Wenn du dich durch das globale Verzeichnis klickst, siehst du alle Nutzer weltweit auf allen Servern, die sich entschlossen haben, im Verzeichnis zu erscheinen. Du wirst außerdem den Link "Show Community Forums" sehen, welcher dich zu Gruppen, Foren und Fan-Seiten führt. Du verbindest dich mit Personen, Gruppen und Foren auf die gleiche Art, wobei Gruppen und Foren deine Anfrage automatisch annehmen, wohingegen ein Mensch dich erst manuell bestätigen muss.
*Mit anderen Friendica-Nutzern verbinden*

View file

@ -8,12 +8,8 @@ Hier sind noch einige weitere Dinge, die dir den Start vereinfachen können.
**Gruppen**
- <a href="https://kakste.com/profile/newhere">Neu hier?</a> - eine Gruppe für Leute, die neu bei Friendica sind
- <a href="http://helpers.pyxis.uberspace.de/profile/helpers">Friendica Support</a> - Probleme? Dann ist das der Platz, um zu fragen!
- <a href="https://kakste.com/profile/public_stream">Öffentlicher Stream</a> - ein Platz, um über alles mit jedem zu reden.
- <a href="https://letstalk.pyxis.uberspace.de/profile/letstalk">Let's Talk</a> eine Gruppe, um Leute und Gruppen mit gleichen Interessen zu finden
- <a href="http://newzot.hydra.uberspace.de/profile/newzot">Local Friendica</a> eine Seite für lokale Friendica-Gruppen</a>

View file

@ -8,12 +8,8 @@ Hier sind noch einige weitere Dinge, die dir den Start vereinfachen können.
**Gruppen**
- <a href="https://kakste.com/profile/newhere">Neu hier?</a> - eine Gruppe für Leute, die neu bei Friendica sind
- <a href="http://helpers.pyxis.uberspace.de/profile/helpers">Friendica Support</a> - Probleme? Dann ist das der Platz, um zu fragen!
- <a href="https://kakste.com/profile/public_stream">Öffentlicher Stream</a> - ein Platz, um über alles mit jedem zu reden.
- <a href="https://letstalk.pyxis.uberspace.de/profile/letstalk">Let's Talk</a> eine Gruppe, um Leute und Gruppen mit gleichen Interessen zu finden
- <a href="http://newzot.hydra.uberspace.de/profile/newzot">Local Friendica</a> eine Seite für lokale Friendica-Gruppen</a>

48
doc/readme.md Normal file
View file

@ -0,0 +1,48 @@
Friendica Documentation and Resources
=====================================
**Contents**
* General functions - first steps
* [Account Basics](help/Account-Basics)
* [New User Quick Start](help/Quick-Start-guide)
* [Creating posts](help/Text_editor)
* [BBCode tag reference](help/BBCode)
* [Comment, sort and delete posts](help/Text_comment)
* [Profiles](help/Profiles)
* You and other user
* [Connectors](help/Connectors)
* [Making Friends](help/Making-Friends)
* [Groups and Privacy](help/Groups-and-Privacy)
* [Tags and Mentions](help/Tags-and-Mentions)
* [Community Forums](help/Forums)
* [Chats](help/Chats)
* Further information
* [Improve Performance](help/Improve-Performance)
* [Move Account](help/Move-Account)
* [Remove Account](help/Remove-Account)
* [Bugs and Issues](help/Bugs-and-Issues)
* [Frequently asked questions (FAQ)](help/FAQ)
**Technical Documentation**
* [Install](help/Install)
* [Settings](help/Settings)
* [Plugins](help/Plugins)
* [Installing Connectors (Facebook/Twitter/StatusNet)](help/Installing-Connectors)
* [Message Flow](help/Message-Flow)
* [Using SSL with Friendica](help/SSL)
* [Developers](help/Developers)
* [Twitter/StatusNet API Functions](help/api)
* [Translation of Friendica](help/translations)
**External Resources**
* [Main Website](http://friendica.com)
* [Mailing List Archive](http://librelist.com/browser/friendica/)
**About**
* [Site/Version Info](friendica)

95
doc/translations.md Normal file
View file

@ -0,0 +1,95 @@
Friendica translations
======================
Translation Process
-------------------
The strings used in the UI of Friendica is translated at [Transifex] [1] and then
included in the git repository at github. If you want to help with translation
for any language, be it correcting terms or translating friendica to a
currently not supported language, please register an account at transifex.com
and contact the friendica translation team there.
Translating friendica is simple. Just use the online tool at transifex. If you
don't want to deal with git & co. that is fine, we check the status of the
translations regularly and import them into the source tree at github so that
others can use them.
We do not include every translation from transifex in the source tree to avoid
a scattered and disturbed overall experience. As an uneducated guess we have a
lower limit of 50% translated strings before we include the language (for the
core message.po file, addont translation will be included once all strings of
an addon are translated. This limit is judging only by the amount of translated
strings under the assumption that the most prominent strings for the UI will be
translated first by a translation team. If you feel your translation useable
before this limit, please contact us and we will probably include your teams
work in the source tree.
If you want to get your work into the source tree yourself, feel free to do so
and contact us with and question that arises. The process is simple and
friendica ships with all the tools necessary.
The location of the translated files in the source tree is
/view/LNG-CODE/
where LNG-CODE is the language code used, e.g. de for German or fr for French.
For the email templates (the *.tpl files) just place them into the directory
and you are done. The translated strings come as a "message.po" file from
transifex which needs to be translated into the PHP file friendica uses. To do
so, place the file in the directory mentioned above and use the "po2php"
utility from the util directory of your friendica installation.
Assuming you want to convert the German localization which is placed in
view/de/message.po you would do the following.
1. Navigate at the command prompt to the base directory of your
friendica installation
2. Execute the po2php script, which will place the translation
in the strings.php file that is used by friendica.
$> php util/po2php.php view/de/message.po
The output of the script will be placed at view/de/strings.php where
froemdoca os expecting it, so you can test your translation mmediately.
3. Visit your friendica page to check if it still works in the language you
just translated. If not try to find the error, most likely PHP will give
you a hint in the log/warnings.about the error.
For debugging you can also try to "run" the file with PHP. This should
not give any output if the file is ok but might give a hint for
searching the bug in the file.
$> php view/de/strings.php
4. commit the two files with a meaningful commit message to your git
repository, push it to your fork of the friendica repository at github and
issue a pull request for that commit.
Utilities
---------
Additional to the po2php script there are some more utilities for translation
in the "util" directory of the friendica source tree. If you only want to
translate friendica into another language you wont need any of these tools most
likely but it gives you an idea how the translation process of friendica
works.
For further information see the utils/README file.
Known Problems
--------------
Friendica uses the language setting of the visitors browser to determain the
language for the UI. Most of the time this works, but there are some known
quirks.
One is that some browsers, like Safari, do the setting to "de-de" but friendica
only has a "de" localisation. A workaround would be to add a symbolic link
from
$friendica/view/de-de
pointing to
$friendica/view/de
[1]: https://www.transifex.com/projects/p/friendica/

View file

@ -59,7 +59,7 @@ $a->config['system']['directory_search_url'] = 'http://dir.friendica.com/directo
// PuSH - aka pubsubhubbub URL. This makes delivery of public posts as fast as private posts
$a->config['system']['huburl'] = 'http://pubsubhubbub.appspot.com';
$a->config['system']['huburl'] = '[internal]';
// Server-to-server private message encryption (RINO) is allowed by default.
// Encryption will only be provided if this setting is true and the

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.3 KiB

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 3 KiB

View file

@ -2,7 +2,7 @@
require_once('include/email.php');
class EmailNotification {
class Emailer {
/**
* Send a multipart/alternative message with Text and HTML versions
*
@ -13,12 +13,12 @@ class EmailNotification {
* @param messageSubject subject of the message
* @param htmlVersion html version of the message
* @param textVersion text only version of the message
* @param additionalMailHeader additions to the smtp mail header
*/
static public function sendTextHtmlEmail($fromName,$fromEmail,$replyTo,$toEmail,$messageSubject,$htmlVersion,$textVersion) {
$fromName = email_header_encode($fromName,'UTF-8');
$messageSubject = email_header_encode($messageSubject,'UTF-8');
static public function send($params) {
$fromName = email_header_encode(html_entity_decode($params['fromName'],ENT_QUOTES,'UTF-8'),'UTF-8');
$messageSubject = email_header_encode(html_entity_decode($params['messageSubject'],ENT_QUOTES,'UTF-8'),'UTF-8');
// generate a mime boundary
$mimeBoundary =rand(0,9)."-"
@ -28,14 +28,15 @@ class EmailNotification {
// generate a multipart/alternative message header
$messageHeader =
"From: {$fromName} <{$fromEmail}>\n" .
"Reply-To: {$replyTo}\n" .
$params['additionalMailHeader'] .
"From: $fromName <{$params['fromEmail']}>\n" .
"Reply-To: $fromName <{$params['replyTo']}>\n" .
"MIME-Version: 1.0\n" .
"Content-Type: multipart/alternative; boundary=\"{$mimeBoundary}\"";
// assemble the final multipart message body with the text and html types included
$textBody = chunk_split(base64_encode($textVersion));
$htmlBody = chunk_split(base64_encode($htmlVersion));
$textBody = chunk_split(base64_encode($params['textVersion']));
$htmlBody = chunk_split(base64_encode($params['htmlVersion']));
$multipartMessageBody =
"--" . $mimeBoundary . "\n" . // plain text section
"Content-Type: text/plain; charset=UTF-8\n" .
@ -49,12 +50,14 @@ class EmailNotification {
// send the message
$res = mail(
$toEmail, // send to address
$params['toEmail'], // send to address
$messageSubject, // subject
$multipartMessageBody, // message body
$messageHeader // message headers
);
logger("sendTextHtmlEmail: END");
logger("header " . 'To: ' . $params['toEmail'] . "\n" . $messageHeader, LOGGER_DEBUG);
logger("return value " . (($res)?"true":"false"), LOGGER_DEBUG);
return $res;
}
}
?>

View file

@ -26,6 +26,19 @@
return false;
}
function api_source() {
if (requestdata('source'))
return (requestdata('source'));
// Support for known clients that doesn't send a source name
if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
return ("Twidere");
logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
return ("api");
}
function api_date($str){
//Wed May 23 06:01:13 +0000 2007
return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
@ -122,7 +135,6 @@
// preset
$type="json";
foreach ($API as $p=>$info){
if (strpos($a->query_string, $p)===0){
$called_api= explode("/",$p);
@ -154,7 +166,10 @@
case "json":
header ("Content-Type: application/json");
foreach($r as $rr)
return json_encode($rr);
$json = json_encode($rr);
if ($_GET['callback'])
$json = $_GET['callback']."(".$json.")";
return $json;
break;
case "rss":
header ("Content-Type: application/rss+xml");
@ -666,6 +681,7 @@
logger('api_statuses_update: no user');
return false;
}
$user_info = api_get_user($a);
// convert $_POST array items to the form we use for web posts.
@ -710,8 +726,64 @@
if($parent)
$_REQUEST['type'] = 'net-comment';
else {
// logger("api_statuses_update: upload ".print_r($_FILES, true)." ".print_r($_POST, true)." ".print_r($_GET, true), LOGGER_DEBUG);
//die("blubb");
// Check for throttling (maximum posts per day, week and month)
$throttle_day = get_config('system','throttle_limit_day');
if ($throttle_day > 0) {
$datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
$r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
AND `created` > '%s' AND `id` = `parent`",
intval(api_user()), dbesc($datefrom));
if ($r)
$posts_day = $r[0]["posts_day"];
else
$posts_day = 0;
if ($posts_day > $throttle_day) {
logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
}
}
$throttle_week = get_config('system','throttle_limit_week');
if ($throttle_week > 0) {
$datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
$r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
AND `created` > '%s' AND `id` = `parent`",
intval(api_user()), dbesc($datefrom));
if ($r)
$posts_week = $r[0]["posts_week"];
else
$posts_week = 0;
if ($posts_week > $throttle_week) {
logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
}
}
$throttle_month = get_config('system','throttle_limit_month');
if ($throttle_month > 0) {
$datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
$r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
AND `created` > '%s' AND `id` = `parent`",
intval(api_user()), dbesc($datefrom));
if ($r)
$posts_month = $r[0]["posts_month"];
else
$posts_month = 0;
if ($posts_month > $throttle_month) {
logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
}
}
$_REQUEST['type'] = 'wall';
if(x($_FILES,'media')) {
// upload the image if we have one
@ -727,6 +799,9 @@
$_REQUEST['api_source'] = true;
if (!x($_REQUEST, "source"))
$_REQUEST["source"] = api_source();
// call out normal post function
require_once('mod/item.php');
@ -936,6 +1011,35 @@
}
api_register_func('api/users/show','api_users_show');
function api_users_search(&$a, $type) {
$page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
$userlist = array();
if (isset($_GET["q"])) {
$r = q("SELECT id FROM unique_contacts WHERE name='%s'", dbesc($_GET["q"]));
if (!count($r))
$r = q("SELECT id FROM unique_contacts WHERE nick='%s'", dbesc($_GET["q"]));
if (count($r)) {
foreach ($r AS $user) {
$user_info = api_get_user($a, $user["id"]);
//echo print_r($user_info, true)."\n";
$userdata = api_apply_template("user", $type, array('user' => $user_info));
$userlist[] = $userdata["user"];
}
$userlist = array("users" => $userlist);
} else
die(api_error($a, $type, t("User not found.")));
} else
die(api_error($a, $type, t("User not found.")));
return ($userlist);
}
api_register_func('api/users/search','api_users_search');
/**
*
* http://developer.twitter.com/doc/get/statuses/home_timeline
@ -1272,6 +1376,9 @@
$_REQUEST['type'] = 'wall';
$_REQUEST['api_source'] = true;
if (!x($_REQUEST, "source"))
$_REQUEST["source"] = api_source();
require_once('mod/item.php');
item_post($a);
}
@ -1359,7 +1466,7 @@
AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
AND `contact`.`id` = `item`.`contact-id`
AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention`)
AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
$sql_extra
AND `item`.`id`>%d
ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
@ -1790,6 +1897,16 @@
return($entities);
}
function api_format_items_embeded_images($item, $text){
$a = get_app();
$text = preg_replace_callback(
"|data:image/([^;]+)[^=]+=*|m",
function($match) use ($a, $item) {
return $a->get_baseurl()."/display/".$item['guid'];
},
$text);
return $text;
}
function api_format_items($r,$user_info, $filter_user = false) {
@ -1849,6 +1966,9 @@
$html = bbcode(api_clean_plain_items($item['body']), false, false, 2, true);
$statusbody = trim(html2plain($html, 0));
// handle data: images
$statusbody = api_format_items_embeded_images($item,$statusbody);
$statustitle = trim($item['title']);
if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
@ -1859,6 +1979,9 @@
if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
$statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
$statushtml = trim(bbcode($item['body'], false, false));
$status = array(
'text' => $statustext,
'truncated' => False,
@ -1876,7 +1999,7 @@
//'attachments' => array(),
'user' => $status_user ,
//'entities' => NULL,
'statusnet_html' => trim(bbcode($item['body'], false, false)),
'statusnet_html' => $statushtml,
'statusnet_conversation_id' => $item['parent'],
);
@ -2198,13 +2321,6 @@
function api_direct_messages_box(&$a, $type, $box) {
if (api_user()===false) return false;
unset($_REQUEST["user_id"]);
unset($_GET["user_id"]);
unset($_REQUEST["screen_name"]);
unset($_GET["screen_name"]);
$user_info = api_get_user($a);
// params
$count = (x($_GET,'count')?$_GET['count']:20);
@ -2214,11 +2330,25 @@
$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
$max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
$start = $page*$count;
$user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
$screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
// caller user info
unset($_REQUEST["user_id"]);
unset($_GET["user_id"]);
unset($_REQUEST["screen_name"]);
unset($_GET["screen_name"]);
$user_info = api_get_user($a);
//$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
$profile_url = $user_info["url"];
// pagination
$start = $page*$count;
// filters
if ($box=="sentbox") {
$sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
}
@ -2235,24 +2365,31 @@
if ($max_id > 0)
$sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
if ($user_id !="") {
$sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
}
elseif($screen_name !=""){
$sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
}
$r = q("SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND $sql_extra AND `mail`.`id` > %d ORDER BY `mail`.`id` DESC LIMIT %d,%d",
intval(api_user()),
intval($since_id),
intval($start), intval($count)
);
$ret = Array();
foreach($r as $item) {
if ($box == "inbox" || $item['from-url'] != $profile_url){
$recipient = $user_info;
$sender = api_get_user($a,normalise_link($item['contact-url']));
}
elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
$recipient = api_get_user($a,normalise_link($item['contact-url']));
$sender = $user_info;
}
$ret[]=api_format_messages($item, $recipient, $sender);
}
@ -2350,9 +2487,6 @@
function api_share_as_retweet($a, $uid, &$item) {
$body = trim($item["body"]);

View file

@ -56,6 +56,8 @@ function diaspora2bb($s) {
function bb2diaspora($Text,$preserve_nl = false, $fordiaspora = true) {
$OriginalText = $Text;
// Since Diaspora is creating a summary for links, this function removes them before posting
if ($fordiaspora)
$Text = bb_remove_share_information($Text);
@ -73,12 +75,24 @@ function bb2diaspora($Text,$preserve_nl = false, $fordiaspora = true) {
$Text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $Text);
// Convert it to HTML - don't try oembed
if ($fordiaspora)
if ($fordiaspora) {
$Text = bbcode($Text, $preserve_nl, false, 3);
else {
// Add all tags that maybe were removed
if (preg_match_all("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",$OriginalText, $tags)) {
$tagline = "";
foreach($tags[2] as $tag)
if (!strpos($Text, "#".$tag))
$tagline .= "#".$tag." ";
$Text = $Text."<br />".$tagline;
}
} else {
$Text = bbcode($Text, $preserve_nl, false, 4);
// Libertree doesn't convert a harizontal rule if there isn't a linefeed
$Text = str_replace("<hr />", "<br /><hr />", $Text);
$Text = str_replace(array("<hr />", "<hr>"), array("<br /><hr />", "<br><hr>"), $Text);
}
// Now convert HTML to Markdown

View file

@ -3,10 +3,10 @@ require_once("include/oembed.php");
require_once('include/event.php');
function bb_attachment($Text, $plaintext = false, $tryoembed = true) {
$Text = preg_replace_callback("/\[attachment(.*?)\](.*?)\[\/attachment\]/ism",
$Text = preg_replace_callback("/(.*?)\[attachment(.*?)\](.*?)\[\/attachment\]/ism",
function ($match) use ($plaintext){
$attributes = $match[1];
$attributes = $match[2];
$type = "";
preg_match("/type='(.*?)'/ism", $attributes, $matches);
@ -65,8 +65,13 @@ function bb_attachment($Text, $plaintext = false, $tryoembed = true) {
$preview = $matches[1];
}
if (((strpos($match[1], "[img=") !== false) OR (strpos($match[1], "[img]") !== false)) AND ($image != "")) {
$preview = $image;
$image = "";
}
if ($plaintext)
$text = sprintf('<a href="%s" target="_blank">%s</a>', $url, $title);
$text = sprintf('<a href="%s" target="_blank">%s</a><br>', $url, $title);
else {
$text = sprintf('<span class="type-%s">', $type);
@ -83,44 +88,15 @@ function bb_attachment($Text, $plaintext = false, $tryoembed = true) {
$text .= $oembed;
$text .= sprintf('<blockquote>%s</blockquote></span>', trim($match[2]));
$text .= sprintf('<blockquote>%s</blockquote></span>', trim($match[3]));
}
return($text);
return($match[1].$text);
},$Text);
return($Text);
}
/* function bb_rearrange_link($shared) {
if ($shared[1] != "type-link")
return($shared[0]);
$newshare = trim($shared[2]);
$newshare = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $newshare);
if (!strpos($shared[0], "[bookmark"))
$newshare = preg_replace("/\[url\=(.*?)\](.*?)\[\/url\]/ism", '[bookmark=$1]$2[/bookmark]', $newshare, 1);
preg_match("/\[img\](.*?)\[\/img\]/ism", $newshare, $matches);
if ($matches) {
$newshare = str_replace($matches[0], '', $newshare);
$newshare = "[img]".$matches[1]."[/img]\n".$newshare;
}
$search = array("\n\n", "\n ", " \n");
$replace = array("\n", "\n", "\n");
do {
$oldtext = $newshare;
$newshare = str_replace($search, $replace, $newshare);
} while ($oldtext != $newshare);
$newshare = "[class=type-link]".$newshare."[/class]";
return($newshare);
} */
function bb_rearrange_share($shared) {
if (!in_array(strtolower($shared[2]), array("type-link", "type-audio", "type-video")))
return($shared[0]);
@ -211,7 +187,8 @@ function bb_cleanup_share($shared, $plaintext, $nolink) {
if (isset($bookmark[1][0]))
$link = $bookmark[1][0];
if (($title != "") AND (strpos($shared[1],$title) !== false))
if (($title != "") AND ((strpos($shared[1],$title) !== false) OR
(similar_text($shared[1],$title) / strlen($title)) > 0.9))
$title = "";
// if (strpos($shared[1],$link) !== false)
@ -534,10 +511,14 @@ function bb_ShareAttributes($share, $simplehtml) {
if ($text != "")
$text .= "<hr />";
if (substr(normalise_link($link), 0, 19) != "http://twitter.com/") {
$text .= $headline.'<blockquote class="shared_content">'.trim($share[3])."</blockquote><br />";
if ($link != "")
$text .= '<br /><a href="'.$link.'">[l]</a>';
} else
$text .= '<br /><a href="'.$link.'">'.$link.'</a>';
break;
case 4:
$headline = '<div class="shared_header">';
@ -674,10 +655,12 @@ function bb_RemovePictureLinks($match) {
$text = Cache::get($match[1]);
if(is_null($text)){
$a = get_app();
$ch = @curl_init($match[1]);
@curl_setopt($ch, CURLOPT_NOBODY, true);
@curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
@curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION.")");
@curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
@curl_exec($ch);
$curl_info = @curl_getinfo($ch);
@ -722,10 +705,12 @@ function bb_CleanPictureLinksSub($match) {
$text = Cache::get($match[1]);
if(is_null($text)){
$a = get_app();
$ch = @curl_init($match[1]);
@curl_setopt($ch, CURLOPT_NOBODY, true);
@curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
@curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION.")");
@curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
@curl_exec($ch);
$curl_info = @curl_getinfo($ch);
@ -817,13 +802,6 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true, $simplehtml = fal
// Rearrange shares to attachments
$Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism", "bb_rearrange_share",$Text);
// Handle attached links or videos
$Text = bb_attachment($Text, ($simplehtml != 4) AND ($simplehtml != 0), $tryoembed);
// Rearrange shared links
// if (get_config("system", "rearrange_shared_links") AND (!$simplehtml OR $tryoembed))
// $Text = preg_replace_callback("(\[class=(.*?)\](.*?)\[\/class\])ism","bb_rearrange_link",$Text);
// when the content is meant exporting to other systems then remove the avatar picture since this doesn't really look good on these systems
if (!$tryoembed)
$Text = preg_replace("/\[share(.*?)avatar\s?=\s?'.*?'\s?(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","\n[share$1$2]$3[/share]",$Text);
@ -840,21 +818,22 @@ function bbcode($Text,$preserve_nl = false, $tryoembed = true, $simplehtml = fal
// removing multiplicated newlines
if (get_config("system", "remove_multiplicated_lines")) {
$search = array("\n\n\n", "\n ", " \n", "[/quote]\n\n", "\n[/quote]", "[/li]\n", "\n[li]", "\n[ul]", "[/ul]\n", "\n\n[share ");
$replace = array("\n\n", "\n", "\n", "[/quote]\n", "[/quote]", "[/li]", "[li]", "[ul]", "[/ul]", "\n[share ");
$search = array("\n\n\n", "\n ", " \n", "[/quote]\n\n", "\n[/quote]", "[/li]\n", "\n[li]", "\n[ul]", "[/ul]\n", "\n\n[share ", "[/attachment]\n");
$replace = array("\n\n", "\n", "\n", "[/quote]\n", "[/quote]", "[/li]", "[li]", "[ul]", "[/ul]", "\n[share ", "[/attachment]");
do {
$oldtext = $Text;
$Text = str_replace($search, $replace, $Text);
} while ($oldtext != $Text);
}
// Handle attached links or videos
$Text = bb_attachment($Text, ($simplehtml != 4) AND ($simplehtml != 0), $tryoembed);
$Text = str_replace(array("\r","\n"), array('<br />','<br />'), $Text);
if($preserve_nl)
$Text = str_replace(array("\n","\r"), array('',''),$Text);
// Set up the parameters for a URL search string
$URLSearchString = "^\[\]";
// Set up the parameters for a MAIL search string

View file

@ -282,6 +282,11 @@ function relative_date($posted_date,$format = null) {
return t('less than a second ago');
}
$time_append = '';
if ($etime >= 86400) {
$time_append = ' ('.$localtime.')';
}
$a = array( 12 * 30 * 24 * 60 * 60 => array( t('year'), t('years')),
30 * 24 * 60 * 60 => array( t('month'), t('months')),
7 * 24 * 60 * 60 => array( t('week'), t('weeks')),
@ -298,7 +303,7 @@ function relative_date($posted_date,$format = null) {
// translators - e.g. 22 hours ago, 1 minute ago
if(! $format)
$format = t('%1$d %2$s ago');
return sprintf( $format,$r, (($r == 1) ? $str[0] : $str[1]));
return sprintf( $format,$r, (($r == 1) ? $str[0] : $str[1])).$time_append;
}
}
}}

View file

@ -1,10 +1,15 @@
<?php
# if PDO is avaible for mysql, use the new database abstraction
# TODO: PDO is disabled for release 3.3. We need to investigate why
# the update from 3.2 fails with pdo
/*
if(class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
require_once("library/dddbl2/dddbl.php");
require_once("include/dba_pdo.php");
}
*/
require_once('include/datetime.php');

File diff suppressed because it is too large Load diff

View file

@ -2028,6 +2028,7 @@ function diaspora_retraction($importer,$xml) {
dbesc(datetime_convert()),
intval($r[0]['id'])
);
delete_thread($r[0]['id']);
}
}
}
@ -2100,6 +2101,7 @@ function diaspora_signed_retraction($importer,$xml,$msg) {
dbesc(datetime_convert()),
intval($r[0]['id'])
);
delete_thread($r[0]['id']);
// Now check if the retraction needs to be relayed by us
//

View file

@ -249,6 +249,12 @@ function email_header_encode($in_str, $charset) {
return $out_str;
}
/**
* email_send is used by NETWORK_EMAIL and NETWORK_EMAIL2 code
* (not to notify the user, but to send items to email contacts
*
* TODO: this could be changed to use the Emailer class
*/
function email_send($addr, $subject, $headers, $item) {
//$headers .= 'MIME-Version: 1.0' . "\n";
//$headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";

View file

@ -1,10 +1,12 @@
<?php
require_once('include/Emailer.php');
require_once('include/email.php');
require_once('include/bbcode.php');
require_once('include/html2bbcode.php');
function notification($params) {
logger('notification: entry', LOGGER_DEBUG);
#logger('notification()', LOGGER_DEBUG);
$a = get_app();
@ -19,6 +21,7 @@ function notification($params) {
$thanks = t('Thank You,');
$sitename = $a->config['sitename'];
$site_admin = sprintf( t('%s Administrator'), $sitename);
$nickname = "";
$sender_name = $product;
$hostname = $a->get_hostname();
@ -26,15 +29,26 @@ function notification($params) {
$hostname = substr($hostname,0,strpos($hostname,':'));
$sender_email = t('noreply') . '@' . $hostname;
$additional_mail_header = "";
$user = q("SELECT `nickname` FROM `user` WHERE `uid` = %d", intval($params['uid']));
if ($user)
$nickname = $user[0]["nickname"];
// with $params['show_in_notification_page'] == false, the notification isn't inserted into
// the database, and an email is sent if applicable.
// default, if not specified: true
$show_in_notification_page = ((x($params,'show_in_notification_page')) ? $params['show_in_notification_page']:True);
$additional_mail_header = "";
$additional_mail_header .= "Precedence: list\n";
$additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
$additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
$additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
$additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
$additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
$additional_mail_header .= "List-Archive: <".$a->get_baseurl()."/notifications/system>\n";
if(array_key_exists('item',$params)) {
$title = $params['item']['title'];
$body = $params['item']['body'];
@ -223,6 +237,30 @@ function notification($params) {
$tsitelink = sprintf( $sitelink, $siteurl );
$hsitelink = sprintf( $sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
$itemlink = $params['link'];
switch ($params['verb']) {
case ACTIVITY_FRIEND:
// someone started to share with user (mostly OStatus)
$subject = sprintf( t('[Friendica:Notify] A new person is sharing with you'));
$preamble = sprintf( t('%1$s is sharing with you at %2$s'), $params['source_name'], $sitename);
$epreamble = sprintf( t('%1$s is sharing with you at %2$s'),
'[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
$sitename);
break;
case ACTIVITY_FOLLOW:
// someone started to follow the user (mostly OStatus)
$subject = sprintf( t('[Friendica:Notify] You have a new follower'));
$preamble = sprintf( t('You have a new follower at %2$s : %1$s'), $params['source_name'], $sitename);
$epreamble = sprintf( t('You have a new follower at %2$s : %1$s'),
'[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
$sitename);
break;
default:
// ACTIVITY_REQ_FRIEND is default activity for notifications
break;
}
}
if($params['type'] == NOTIFY_SUGGEST) {
@ -244,11 +282,75 @@ function notification($params) {
}
if($params['type'] == NOTIFY_CONFIRM) {
if ($params['verb'] == ACTIVITY_FRIEND ){ // mutual connection
$subject = sprintf( t('[Friendica:Notify] Connection accepted'));
$preamble = sprintf( t('\'%1$s\' has acepted your connection request at %2$s'), $params['source_name'], $sitename);
$epreamble = sprintf( t('%2$s has accepted your [url=%1$s]connection request[/url].'),
$itemlink,
'[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]');
$body = t('You are now mutual friends and may exchange status updates, photos, and email
without restriction.');
$sitelink = t('Please visit %s if you wish to make any changes to this relationship.');
$tsitelink = sprintf( $sitelink, $siteurl );
$hsitelink = sprintf( $sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
$itemlink = $params['link'];
} else { // ACTIVITY_FOLLOW
$subject = sprintf( t('[Friendica:Notify] Connection accepted'));
$preamble = sprintf( t('\'%1$s\' has acepted your connection request at %2$s'), $params['source_name'], $sitename);
$epreamble = sprintf( t('%2$s has accepted your [url=%1$s]connection request[/url].'),
$itemlink,
'[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]');
$body = sprintf(t('\'%1$s\' has chosen to accept you a "fan", which restricts some forms of communication - such as private messaging and some profile interactions. If this is a celebrity or community page, these settings were applied automatically.'), $params['source_name']);
$body .= "\n\n";
$body .= sprintf(t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future. '), $params['source_name']);
$sitelink = t('Please visit %s if you wish to make any changes to this relationship.');
$tsitelink = sprintf( $sitelink, $siteurl );
$hsitelink = sprintf( $sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
$itemlink = $params['link'];
}
}
if($params['type'] == NOTIFY_SYSTEM) {
switch($params['event']) {
case "SYSTEM_REGISTER_REQUEST":
$subject = sprintf( t('[Friendica System:Notify] registration request'));
$preamble = sprintf( t('You\'ve received a registration request from \'%1$s\' at %2$s'), $params['source_name'], $sitename);
$epreamble = sprintf( t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.'),
$itemlink,
'[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]');
$body = sprintf( t('Full Name: %1$s\nSite Location: %2$s\nLogin Name: %3$s (%4$s)'),
$params['source_name'], $siteurl, $params['source_mail'], $params['source_nick']);
$sitelink = t('Please visit %s to approve or reject the request.');
$tsitelink = sprintf( $sitelink, $params['link'] );
$hsitelink = sprintf( $sitelink, '<a href="' . $params['link'] . '">' . $sitename . '</a><br><br>');
$itemlink = $params['link'];
break;
case "SYSTEM_DB_UPDATE_FAIL":
break;
}
}
if ($params['type'] == "SYSTEM_EMAIL"){
// not part of the notifications.
// it just send a mail to the user.
// It will be used by the system to send emails to users (like
// password reset, invitations and so) using one look (but without
// add a notification to the user, with could be inexistent)
$subject = $params['subject'];
$preamble = $params['preamble'];
$body = $params['body'];
$sitelink = "";
$tsitelink = "";
$hsitelink = "";
$itemlink = "";
$show_in_notification_page = false;
}
$subject .= " (".$nickname."@".$hostname.")";
$h = array(
'params' => $params,
@ -274,8 +376,9 @@ function notification($params) {
$itemlink = $h['itemlink'];
require_once('include/html2bbcode.php');
if ($show_in_notification_page) {
logger("adding notification entry", LOGGER_DEBUG);
do {
$dups = false;
$hash = random_string();
@ -304,7 +407,7 @@ function notification($params) {
if($datarray['abort']) {
pop_lang();
return;
return False;
}
// create notification entry in DB
@ -332,7 +435,7 @@ function notification($params) {
$notify_id = $r[0]['id'];
else {
pop_lang();
return;
return False;
}
// we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
@ -356,17 +459,11 @@ function notification($params) {
if($notify_id != $p[0]['id']) {
pop_lang();
return;
return False;
}
}
$itemlink = $a->get_baseurl() . '/notify/view/' . $notify_id;
$msg = replace_macros($epreamble,array('$itemlink' => $itemlink));
$r = q("update notify set msg = '%s' where id = %d and uid = %d",
@ -375,13 +472,14 @@ function notification($params) {
intval($params['uid'])
);
}
// send email notification if notification preferences permit
if((intval($params['notify_flags']) & intval($params['type']))
|| $params['type'] == NOTIFY_SYSTEM
|| $params['type'] == "SYSTEM_EMAIL") {
require_once('include/bbcode.php');
if((intval($params['notify_flags']) & intval($params['type'])) || $params['type'] == NOTIFY_SYSTEM) {
logger('notification: sending notification email');
logger('sending notification email');
if (isset($params['parent']) AND (intval($params['parent']) != 0)) {
$id_for_parent = $params['parent']."@".$hostname;
@ -410,16 +508,18 @@ function notification($params) {
} else {
// If not, just "follow" the thread.
$additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
logger("include/enotify: There's already a notification for this parent:\n" . print_r($r, true), LOGGER_DEBUG);
logger("There's already a notification for this parent:\n" . print_r($r, true), LOGGER_DEBUG);
}
}
$textversion = strip_tags(html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",
$body))),ENT_QUOTES,'UTF-8'));
// textversion keeps linebreaks
$textversion = strip_tags(str_replace("<br>","\n",html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",
$body))),ENT_QUOTES,'UTF-8')));
$htmlversion = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"),
"<br />\n",$body))),ENT_QUOTES,'UTF-8');
$datarray = array();
$datarray['banner'] = $banner;
$datarray['product'] = $product;
@ -448,14 +548,15 @@ function notification($params) {
call_hooks('enotify_mail', $datarray);
// check whether sending post content in email notifications is allowed
$content_allowed = !get_config('system','enotify_no_content');
// always true for "SYSTEM_EMAIL"
$content_allowed = ((!get_config('system','enotify_no_content')) || ($params['type'] == "SYSTEM_EMAIL"));
// load the template for private message notifications
$tpl = get_markup_template('email_notify_html.tpl');
$email_html_body = replace_macros($tpl,array(
'$banner' => $datarray['banner'],
'$product' => $datarray['product'],
'$preamble' => $datarray['preamble'],
'$preamble' => str_replace("\n","<br>\n",$datarray['preamble']),
'$sitename' => $datarray['sitename'],
'$siteurl' => $datarray['siteurl'],
'$source_name' => $datarray['source_name'],
@ -494,9 +595,9 @@ function notification($params) {
// logger('text: ' . $email_text_body);
// use the EmailNotification library to send the message
// use the Emailer class to send the message
enotify::send(array(
return Emailer::send(array(
'fromName' => $sender_name,
'fromEmail' => $sender_email,
'replyTo' => $sender_email,
@ -508,67 +609,8 @@ function notification($params) {
));
}
pop_lang();
return False;
}
require_once('include/email.php');
class enotify {
/**
* Send a multipart/alternative message with Text and HTML versions
*
* @param fromName name of the sender
* @param fromEmail email fo the sender
* @param replyTo replyTo address to direct responses
* @param toEmail destination email address
* @param messageSubject subject of the message
* @param htmlVersion html version of the message
* @param textVersion text only version of the message
* @param additionalMailHeader additions to the smtp mail header
*/
static public function send($params) {
$fromName = email_header_encode(html_entity_decode($params['fromName'],ENT_QUOTES,'UTF-8'),'UTF-8');
$messageSubject = email_header_encode(html_entity_decode($params['messageSubject'],ENT_QUOTES,'UTF-8'),'UTF-8');
// generate a mime boundary
$mimeBoundary =rand(0,9)."-"
.rand(10000000000,9999999999)."-"
.rand(10000000000,9999999999)."=:"
.rand(10000,99999);
// generate a multipart/alternative message header
$messageHeader =
$params['additionalMailHeader'] .
"From: $fromName <{$params['fromEmail']}>\n" .
"Reply-To: $fromName <{$params['replyTo']}>\n" .
"MIME-Version: 1.0\n" .
"Content-Type: multipart/alternative; boundary=\"{$mimeBoundary}\"";
// assemble the final multipart message body with the text and html types included
$textBody = chunk_split(base64_encode($params['textVersion']));
$htmlBody = chunk_split(base64_encode($params['htmlVersion']));
$multipartMessageBody =
"--" . $mimeBoundary . "\n" . // plain text section
"Content-Type: text/plain; charset=UTF-8\n" .
"Content-Transfer-Encoding: base64\n\n" .
$textBody . "\n" .
"--" . $mimeBoundary . "\n" . // text/html section
"Content-Type: text/html; charset=UTF-8\n" .
"Content-Transfer-Encoding: base64\n\n" .
$htmlBody . "\n" .
"--" . $mimeBoundary . "--\n"; // message ending
// send the message
$res = mail(
$params['toEmail'], // send to address
$messageSubject, // subject
$multipartMessageBody, // message body
$messageHeader // message headers
);
logger("notification: enotify::send header " . 'To: ' . $params['toEmail'] . "\n" . $messageHeader, LOGGER_DEBUG);
logger("notification: enotify::send returns " . $res, LOGGER_DEBUG);
}
}
?>

View file

@ -37,6 +37,8 @@ function gprobe_run(&$argv, &$argc){
dbesc(normalise_link($url))
);
logger("gprobe start for ".normalise_link($url), LOGGER_DEBUG);
if(! count($r)) {
$arr = probe_url($url);
@ -56,6 +58,7 @@ function gprobe_run(&$argv, &$argc){
if(count($r))
poco_load(0,0,$r[0]['id'], str_replace('/profile/','/poco/',$r[0]['url']));
logger("gprobe end for ".normalise_link($url), LOGGER_DEBUG);
return;
}

View file

@ -872,9 +872,18 @@ function get_atom_elements($feed, $item, $contact = array()) {
}
if (isset($contact["network"]) AND ($contact["network"] == NETWORK_FEED) AND $contact['fetch_further_information']) {
$res["body"] = $res["title"].add_page_info($res['plink']);
$preview = "";
// Handle enclosures and treat them as preview picture
if (isset($attach))
foreach ($attach AS $attachment)
if ($attachment->type == "image/jpeg")
$preview = $attachment->link;
$res["body"] = $res["title"].add_page_info($res['plink'], false, $preview, ($contact['fetch_further_information'] == 2), $contact['ffi_keyword_blacklist']);
$res["title"] = "";
$res["object-type"] = ACTIVITY_OBJ_BOOKMARK;
unset($res["attach"]);
} elseif (isset($contact["network"]) AND ($contact["network"] == NETWORK_OSTATUS))
$res["body"] = add_page_info_to_body($res["body"]);
elseif (isset($contact["network"]) AND ($contact["network"] == NETWORK_FEED) AND strstr($res['plink'], ".app.net/")) {
@ -888,12 +897,8 @@ function get_atom_elements($feed, $item, $contact = array()) {
return $res;
}
function add_page_info($url, $no_photos = false, $photo = "") {
require_once("mod/parse_url.php");
$data = parseurl_getsiteinfo($url, true);
logger('add_page_info: fetch page info for '.$url.' '.print_r($data, true), LOGGER_DEBUG);
function add_page_info_data($data) {
call_hooks('page_info_data', $data);
// It maybe is a rich content, but if it does have everything that a link has,
// then treat it that way
@ -907,8 +912,14 @@ function add_page_info($url, $no_photos = false, $photo = "") {
if ($no_photos AND ($data["type"] == "photo"))
return("");
// If the link contains BBCode stuff, make a short link out of this to avoid parsing problems
if (strpos($data["url"], '[') OR strpos($data["url"], ']')) {
require_once("include/network.php");
$data["url"] = short_link($data["url"]);
}
if (($data["type"] != "photo") AND is_string($data["title"]))
$text .= "[bookmark=".$url."]".trim($data["title"])."[/bookmark]";
$text .= "[bookmark=".$data["url"]."]".trim($data["title"])."[/bookmark]";
if (($data["type"] != "video") AND ($photo != ""))
$text .= '[img]'.$photo.'[/img]';
@ -920,7 +931,51 @@ function add_page_info($url, $no_photos = false, $photo = "") {
if (($data["type"] != "photo") AND is_string($data["text"]))
$text .= "[quote]".$data["text"]."[/quote]";
return("\n[class=type-".$data["type"]."]".$text."[/class]");
$hashtags = "";
if (isset($data["keywords"]) AND count($data["keywords"])) {
$a = get_app();
$hashtags = "\n";
foreach ($data["keywords"] AS $keyword) {
$hashtag = str_replace(array(" ", "+", "/", ".", "#", "'"),
array("","", "", "", "", ""), $keyword);
$hashtags .= "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag)."]".$hashtag."[/url] ";
}
}
return("\n[class=type-".$data["type"]."]".$text."[/class]".$hashtags);
}
function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
require_once("mod/parse_url.php");
$data = Cache::get("parse_url:".$url);
if (is_null($data)){
$data = parseurl_getsiteinfo($url, true);
Cache::set("parse_url:".$url,serialize($data));
} else
$data = unserialize($data);
if ($photo != "")
$data["images"][0]["src"] = $photo;
logger('add_page_info: fetch page info for '.$url.' '.print_r($data, true), LOGGER_DEBUG);
if (!$keywords AND isset($data["keywords"]))
unset($data["keywords"]);
if (($keyword_blacklist != "") AND isset($data["keywords"])) {
$list = explode(",", $keyword_blacklist);
foreach ($list AS $keyword) {
$keyword = trim($keyword);
$index = array_search($keyword, $data["keywords"]);
if ($index !== false)
unset($data["keywords"][$index]);
}
}
$text = add_page_info_data($data);
return($text);
}
function add_page_info_to_body($body, $texturl = false, $no_photos = false) {
@ -1129,6 +1184,11 @@ function item_store($arr,$force_parent = false, $notify = false) {
$arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
$arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid(30));
$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['inform'] = ((x($arr,'inform')) ? trim($arr['inform']) : '');
$arr['file'] = ((x($arr,'file')) ? trim($arr['file']) : '');
if ($arr['plink'] == "") {
$a = get_app();
@ -1412,7 +1472,7 @@ function item_store($arr,$force_parent = false, $notify = false) {
if (!$deleted) {
// Store the fresh generated item into the cache
$cachefile = get_cachefile($arr["guid"]."-".hash("md5", $arr['body']));
$cachefile = get_cachefile(urlencode($arr["guid"])."-".hash("md5", $arr['body']));
if (($cachefile != '') AND !file_exists($cachefile)) {
$s = prepare_text($arr['body']);
@ -1938,6 +1998,7 @@ function edited_timestamp_is_newer($existing, $update) {
function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
require_once('library/simplepie/simplepie.inc');
require_once('include/contact_selectors.php');
if(! strlen($xml)) {
logger('consume_feed: empty input');
@ -2576,31 +2637,10 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0)
// This is my contact on another system, but it's really me.
// Turn this into a wall post.
if($contact['remote_self']) {
if ($contact['remote_self'] == 2) {
$r = q("SELECT `id`,`url`,`name`,`photo`,`network` FROM `contact` WHERE `uid` = %d AND `self`", intval($importer['uid']));
if (count($r)) {
$datarray['contact-id'] = $r[0]["id"];
$datarray['owner-name'] = $r[0]["name"];
$datarray['owner-link'] = $r[0]["url"];
$datarray['owner-avatar'] = $r[0]["photo"];
$datarray['author-name'] = $datarray['owner-name'];
$datarray['author-link'] = $datarray['owner-link'];
$datarray['author-avatar'] = $datarray['owner-avatar'];
}
}
$notify = true;
if($contact['network'] === NETWORK_FEED) {
$datarray['private'] = 0;
}
} else
$notify = false;
$notify = item_is_remote_self($contact, $datarray);
$r = item_store($datarray, false, $notify);
logger('Stored - Contact '.$contact['url'].' Notify '.$notify.' return '.$r.' Item '.print_r($datarray, true), LOGGER_DEBUG);
continue;
}
@ -2608,6 +2648,65 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0)
}
}
function item_is_remote_self($contact, &$datarray) {
$a = get_app();
if (!$contact['remote_self'])
return false;
// Prevent the forwarding of posts that are forwarded
if ($datarray["extid"] == NETWORK_DFRN)
return false;
// Prevent to forward already forwarded posts
if ($datarray["app"] == $a->get_hostname())
return false;
if (($contact['network'] != NETWORK_FEED) AND $datarray['private'])
return false;
$datarray2 = $datarray;
logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
if ($contact['remote_self'] == 2) {
$r = q("SELECT `id`,`url`,`name`,`photo`,`network` FROM `contact` WHERE `uid` = %d AND `self`",
intval($contact['uid']));
if (count($r)) {
$datarray['contact-id'] = $r[0]["id"];
$datarray['owner-name'] = $r[0]["name"];
$datarray['owner-link'] = $r[0]["url"];
$datarray['owner-avatar'] = $r[0]["avatar"];
$datarray['author-name'] = $datarray['owner-name'];
$datarray['author-link'] = $datarray['owner-link'];
$datarray['author-avatar'] = $datarray['owner-avatar'];
}
if ($contact['network'] != NETWORK_FEED) {
$datarray["guid"] = get_guid(32);
unset($datarray["plink"]);
$datarray["uri"] = item_new_uri($a->get_hostname(),$contact['uid']);
$datarray["parent-uri"] = $datarray["uri"];
$datarray["extid"] = $contact['network'];
$urlpart = parse_url($datarray2['author-link']);
$datarray["app"] = $urlpart["host"];
} else
$datarray['private'] = 0;
}
//if (!isset($datarray["app"]) OR ($datarray["app"] == ""))
// $datarray["app"] = network_to_name($contact['network']);
if ($contact['network'] != NETWORK_FEED) {
// Store the original post
$r = item_store($datarray2, false, false);
logger('remote-self post original item - Contact '.$contact['url'].' return '.$r.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
} else
$datarray["app"] = "Feed";
return true;
}
function local_delivery($importer,$data) {
$a = get_app();
@ -3689,27 +3788,7 @@ function local_delivery($importer,$data) {
// This is my contact on another system, but it's really me.
// Turn this into a wall post.
if($importer['remote_self']) {
if ($importer['remote_self'] == 2) {
$r = q("SELECT `id`,`url`,`name`,`photo`,`network` FROM `contact` WHERE `uid` = %d AND `self`",
intval($importer['importer_uid']));
if (count($r)) {
$datarray['contact-id'] = $r[0]["id"];
$datarray['owner-name'] = $r[0]["name"];
$datarray['owner-link'] = $r[0]["url"];
$datarray['owner-avatar'] = $r[0]["photo"];
$datarray['author-name'] = $datarray['owner-name'];
$datarray['author-link'] = $datarray['owner-link'];
$datarray['author-avatar'] = $datarray['owner-avatar'];
}
}
$notify = true;
} else
$notify = false;
$notify = item_is_remote_self($importer, $datarray);
$posted_id = item_store($datarray, false, $notify);
@ -3828,6 +3907,7 @@ function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
dbesc(datetime_convert())
);
}
$r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
intval($importer['uid'])
);
@ -3841,20 +3921,24 @@ function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
if(($r[0]['notify-flags'] & NOTIFY_INTRO) &&
(($r[0]['page-flags'] == PAGE_NORMAL) OR ($r[0]['page-flags'] == PAGE_SOAPBOX))) {
$email_tpl = get_intltext_template('follow_notify_eml.tpl');
$email = replace_macros($email_tpl, array(
'$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
'$url' => $url,
'$myname' => $r[0]['username'],
'$siteurl' => $a->get_baseurl(),
'$sitename' => $a->config['sitename']
notification(array(
'type' => NOTIFY_INTRO,
'notify_flags' => $r[0]['notify-flags'],
'language' => $r[0]['language'],
'to_name' => $r[0]['username'],
'to_email' => $r[0]['email'],
'uid' => $r[0]['uid'],
'link' => $a->get_baseurl() . '/notifications/intro',
'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : t('[Name Withheld]')),
'source_link' => $contact_record['url'],
'source_photo' => $contact_record['photo'],
'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
'otype' => 'intro'
));
$res = mail($r[0]['email'],
email_header_encode((($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],'UTF-8'),
$email,
'From: ' . 'Administrator' . '@' . $_SERVER['SERVER_NAME'] . "\n"
. 'Content-type: text/plain; charset=UTF-8' . "\n"
. 'Content-transfer-encoding: 8bit' );
}
}

View file

@ -35,7 +35,7 @@ function fetch_url($url,$binary = false, &$redirects = 0, $timeout = 0, $accept_
}
@curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
@curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION.")");
@curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
if(intval($timeout)) {
@ -134,7 +134,7 @@ function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0)
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION.")");
curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
if(intval($timeout)) {
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
@ -623,6 +623,9 @@ function fetch_xrd_links($url) {
if(! function_exists('validate_url')) {
function validate_url(&$url) {
if(get_config('system','disable_url_validation'))
return true;
// no naked subdomains (allow localhost for tests)
if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
return false;
@ -1114,6 +1117,8 @@ function xml2array($contents, $namespaces = true, $get_attributes=1, $priority =
function original_url($url, $depth=1, $fetchbody = false) {
$a = get_app();
// Remove Analytics Data from Google and other tracking platforms
$urldata = parse_url($url);
if (is_string($urldata["query"])) {
@ -1125,7 +1130,7 @@ function original_url($url, $depth=1, $fetchbody = false) {
if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
"wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
"fb_action_ids", "fb_action_types", "fb_ref",
"awesm",
"awesm", "wtrid",
"woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
$pair = $param."=".urlencode($value);
@ -1163,7 +1168,7 @@ function original_url($url, $depth=1, $fetchbody = false) {
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION.")");
curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
$header = curl_exec($ch);
$curl_info = @curl_getinfo($ch);

View file

@ -78,6 +78,11 @@ function oembed_fetch_url($embedurl, $no_rich_type = false){
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

View file

@ -57,17 +57,19 @@ function onepoll_run(&$argv, &$argc){
return;
}
// Test
$lockpath = get_lockpath();
if ($lockpath != '') {
$pidfile = new pidfile($lockpath, 'onepoll'.$contact_id);
if ($pidfile->is_already_running()) {
logger("onepoll: Already running for contact ".$contact_id);
if ($pidfile->running_time() > 9*60) {
$pidfile->kill();
logger("killed stale process");
}
exit;
}
}
$d = datetime_convert();
// Only poll from those with suitable relationships,

View file

@ -285,7 +285,13 @@ function poller_run(&$argv, &$argc){
continue;
}
// Don't run onepoll.php if the contact isn't pollable
// This check also is inside the onepoll.php - but this will reduce the load
if (in_array($contact["rel"], array(CONTACT_IS_SHARING, CONTACT_IS_FRIEND)) AND ($contact["poll"] != "")
AND !in_array($contact['network'], array(NETWORK_DIASPORA, NETWORK_FACEBOOK, NETWORK_PUMPIO, NETWORK_TWITTER, NETWORK_APPNET))
AND !$contact["self"] AND !$contact["blocked"] AND !$contact["readonly"] AND !$contact["archive"])
proc_run('php','include/onepoll.php',$contact['id']);
if($interval)
@time_sleep_until(microtime(true) + (float) $interval);
}

View file

@ -26,7 +26,7 @@ function create_tags_from_item($itemid) {
if ($message["deleted"])
return;
$cachefile = get_cachefile($message["guid"]."-".hash("md5", $message['body']));
$cachefile = get_cachefile(urlencode($message["guid"])."-".hash("md5", $message['body']));
if (($cachefile != '') AND !file_exists($cachefile)) {
$s = prepare_text($message['body']);

View file

@ -1330,8 +1330,7 @@ function prepare_body(&$item,$attach = false, $preview = false) {
$item['mentions'] = $mentions;
//$cachefile = get_cachefile($item["guid"]."-".strtotime($item["edited"])."-".hash("crc32", $item['body']));
$cachefile = get_cachefile($item["guid"]."-".hash("md5", $item['body']));
$cachefile = get_cachefile(urlencode($item["guid"])."-".hash("md5", $item['body']));
if (($cachefile != '')) {
if (file_exists($cachefile)) {
@ -1503,7 +1502,7 @@ function prepare_text($text) {
else
$s = smilies(bbcode($text));
return $s;
return trim($s);
}}
@ -2229,3 +2228,22 @@ function is_a_date_arg($s) {
}
return false;
}
/**
* remove intentation from a text
*/
function deindent($text, $chr="[\t ]", $count=NULL) {
$text = fix_mce_lf($text);
$lines = explode("\n", $text);
if (is_null($count)) {
$m = array();
$k=0; while($k<count($lines) && strlen($lines[$k])==0) $k++;
preg_match("|^".$chr."*|", $lines[$k], $m);
$count = strlen($m[0]);
}
for ($k=0; $k<count($lines); $k++){
$lines[$k] = preg_replace("|^".$chr."{".$count."}|", "", $lines[$k]);
}
return implode("\n", $lines);
}

View file

@ -6,6 +6,7 @@ require_once('include/plugin.php');
require_once('include/text.php');
require_once('include/pgettext.php');
require_once('include/datetime.php');
require_once('include/enotify.php');
function create_user($arr) {
@ -188,8 +189,8 @@ function create_user($arr) {
$spubkey = $sres['pubkey'];
$r = q("INSERT INTO `user` ( `guid`, `username`, `password`, `email`, `openid`, `nickname`,
`pubkey`, `prvkey`, `spubkey`, `sprvkey`, `register_date`, `verified`, `blocked`, `timezone`, `service_class` )
VALUES ( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, 'UTC', '%s' )",
`pubkey`, `prvkey`, `spubkey`, `sprvkey`, `register_date`, `verified`, `blocked`, `timezone`, `service_class`, `default-location` )
VALUES ( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, 'UTC', '%s', '' )",
dbesc(generate_user_guid()),
dbesc($username),
dbesc($new_password_encoded),
@ -365,3 +366,51 @@ function create_user($arr) {
return $result;
}
/*
* send registration confirmation.
* It's here as a function because the mail is sent
* from different parts
*/
function send_register_open_eml($email, $sitename, $siteurl, $username, $password){
$preamble = deindent(t('
Dear %1$s,
Thank you for registering at %2$s. Your account has been created.
'));
$body = deindent(t('
The login details are as follows:
Site Location: %3$s
Login Name: %1$s
Password: %5$s
You may change your password from your account "Settings" page after logging
in.
Please take a few moments to review the other account settings on that page.
You may also wish to add some basic information to your default profile
(on the "Profiles" page) so that other people can easily find you.
We recommend setting your full name, adding a profile photo,
adding some profile "keywords" (very useful in making new friends) - and
perhaps what country you live in; if you do not wish to be more specific
than that.
We fully respect your right to privacy, and none of these items are necessary.
If you are new and do not know anybody here, they may help
you to make some new and interesting friends.
Thank you and welcome to %2$s.'));
$preamble = sprintf($preamble, $username, $sitename);
$body = sprintf($body, $email, $sitename, $siteurl, $username, $password);
return notification(array(
'type' => "SYSTEM_EMAIL",
'to_email' => $email,
'subject'=> sprintf( t('Registration details for %s'), $sitename),
'preamble'=> $preamble,
'body' => $body));
}

View file

@ -53,6 +53,13 @@ if(!$install) {
load_config('config');
load_config('system');
if (get_config('system','force_ssl') AND ($a->get_scheme() == "http") AND
(intval(get_config('system','ssl_policy')) == SSL_POLICY_FULL) AND
(substr($a->get_baseurl(), 0, 8) == "https://")) {
header("HTTP/1.1 302 Moved Temporarily");
header("location: ".$a->get_baseurl()."/".$a->query_string);
}
require_once("include/session.php");
load_hooks();
call_hooks('init_1');
@ -136,9 +143,11 @@ if(! x($_SESSION,'sysmsg_info'))
* any plugins have been added or removed and reacts accordingly.
*/
if($install)
// in install mode, any url loads install module
// but we need "view" module for stylesheet
if($install && $a->module!="view")
$a->module = 'install';
elseif($maintenance)
elseif($maintenance && $a->module!="view")
$a->module = 'maintenance';
else {
check_url($a);

View file

@ -62,7 +62,7 @@ ACL.prototype.add_mention = function(id) {
that.element.val( searchText + that.element.val() );
} else {
if ( tinyMCE.activeEditor.getContent({format : 'raw'}).search(searchText) >= 0 ) return;
tinyMCE.activeEditor.dom.add(tinyMCE.activeEditor.getBody(), 'span', {}, searchText);
tinyMCE.activeEditor.dom.add(tinyMCE.activeEditor.getBody(), 'dummy', {}, searchText);
}
}

1
js/acl.min.js vendored

File diff suppressed because one or more lines are too long

41
js/ajaxupload.min.js vendored
View file

@ -1,41 +0,0 @@
(function(){function log(){if(typeof(console)!='undefined'&&typeof(console.log)=='function'){Array.prototype.unshift.call(arguments,'[Ajax Upload]');console.log(Array.prototype.join.call(arguments,' '));}}
function addEvent(el,type,fn){if(el.addEventListener){el.addEventListener(type,fn,false);}else if(el.attachEvent){el.attachEvent('on'+type,function(){fn.call(el);});}else{throw new Error('not supported or DOM not loaded');}}
function addResizeEvent(fn){var timeout;addEvent(window,'resize',function(){if(timeout){clearTimeout(timeout);}
timeout=setTimeout(fn,100);});}
var getOffsetSlow=function(el){var top=0,left=0;do{top+=el.offsetTop||0;left+=el.offsetLeft||0;el=el.offsetParent;}while(el);return{left:left,top:top};};if(document.documentElement.getBoundingClientRect){var getOffset=function(el){var box=el.getBoundingClientRect();var doc=el.ownerDocument;var body=doc.body;var docElem=doc.documentElement;var clientTop=docElem.clientTop||body.clientTop||0;var clientLeft=docElem.clientLeft||body.clientLeft||0;var zoom=1;if(body.getBoundingClientRect){var bound=body.getBoundingClientRect();zoom=(bound.right-bound.left)/body.clientWidth;}
if(zoom==0||body.clientWidth==0)
return getOffsetSlow(el);if(zoom>1){clientTop=0;clientLeft=0;}
var top=box.top/zoom+(window.pageYOffset||docElem&&docElem.scrollTop/zoom||body.scrollTop/zoom)-clientTop,left=box.left/zoom+(window.pageXOffset||docElem&&docElem.scrollLeft/zoom||body.scrollLeft/zoom)-clientLeft;return{top:top,left:left};};}else{var getOffset=getOffsetSlow;}
function getBox(el){var left,right,top,bottom;var offset=getOffset(el);left=offset.left;top=offset.top;right=left+el.offsetWidth;bottom=top+el.offsetHeight;return{left:left,right:right,top:top,bottom:bottom};}
function addStyles(el,styles){for(var name in styles){if(styles.hasOwnProperty(name)){el.style[name]=styles[name];}}}
function copyLayout(from,to){var box=getBox(from);addStyles(to,{position:'absolute',left:box.left+'px',top:box.top+'px',width:from.offsetWidth+'px',height:from.offsetHeight+'px'});to.title=from.title;}
var toElement=(function(){var div=document.createElement('div');return function(html){div.innerHTML=html;var el=div.firstChild;return div.removeChild(el);};})();var getUID=(function(){var id=0;return function(){return'ValumsAjaxUpload'+id++;};})();function fileFromPath(file){return file.replace(/.*(\/|\\)/,"");}
function getExt(file){return(-1!==file.indexOf('.'))?file.replace(/.*[.]/,''):'';}
function hasClass(el,name){var re=new RegExp('\\b'+name+'\\b');return re.test(el.className);}
function addClass(el,name){if(!hasClass(el,name)){el.className+=' '+name;}}
function removeClass(el,name){var re=new RegExp('\\b'+name+'\\b');el.className=el.className.replace(re,'');}
function removeNode(el){el.parentNode.removeChild(el);}
window.AjaxUpload=function(button,options){this._settings={action:'upload.php',name:'userfile',data:{},autoSubmit:true,responseType:false,hoverClass:'hover',focusClass:'focus',disabledClass:'disabled',onChange:function(file,extension){},onSubmit:function(file,extension){},onComplete:function(file,response){}};for(var i in options){if(options.hasOwnProperty(i)){this._settings[i]=options[i];}}
if(button.jquery){button=button[0];}else if(typeof button=="string"){if(/^#.*/.test(button)){button=button.slice(1);}
button=document.getElementById(button);}
if(!button||button.nodeType!==1){throw new Error("Please make sure that you're passing a valid element");}
if(button.nodeName.toUpperCase()=='A'){addEvent(button,'click',function(e){if(e&&e.preventDefault){e.preventDefault();}else if(window.event){window.event.returnValue=false;}});}
this._button=button;this._input=null;this._disabled=false;this.enable();this._rerouteClicks();};AjaxUpload.prototype={setData:function(data){this._settings.data=data;},disable:function(){addClass(this._button,this._settings.disabledClass);this._disabled=true;var nodeName=this._button.nodeName.toUpperCase();if(nodeName=='INPUT'||nodeName=='BUTTON'){this._button.setAttribute('disabled','disabled');}
if(this._input){this._input.parentNode.style.visibility='hidden';}},enable:function(){removeClass(this._button,this._settings.disabledClass);this._button.removeAttribute('disabled');this._disabled=false;},_createInput:function(){var self=this;var input=document.createElement("input");input.setAttribute('type','file');input.setAttribute('name',this._settings.name);addStyles(input,{'position':'absolute','right':0,'margin':0,'padding':0,'fontSize':'480px','fontFamily':'sans-serif','cursor':'pointer'});var div=document.createElement("div");addStyles(div,{'display':'block','position':'absolute','overflow':'hidden','margin':0,'padding':0,'opacity':0,'direction':'ltr','zIndex':2147483583,'cursor':'pointer'});if(div.style.opacity!=="0"){if(typeof(div.filters)=='undefined'){throw new Error('Opacity not supported by the browser');}
div.style.filter="alpha(opacity=0)";}
addEvent(input,'change',function(){if(!input||input.value===''){return;}
var file=fileFromPath(input.value);if(false===self._settings.onChange.call(self,file,getExt(file))){self._clearInput();return;}
if(self._settings.autoSubmit){self.submit();}});addEvent(input,'mouseover',function(){addClass(self._button,self._settings.hoverClass);});addEvent(input,'mouseout',function(){removeClass(self._button,self._settings.hoverClass);removeClass(self._button,self._settings.focusClass);input.parentNode.style.visibility='hidden';});addEvent(input,'focus',function(){addClass(self._button,self._settings.focusClass);});addEvent(input,'blur',function(){removeClass(self._button,self._settings.focusClass);});div.appendChild(input);document.body.appendChild(div);this._input=input;},_clearInput:function(){if(!this._input){return;}
removeNode(this._input.parentNode);this._input=null;this._createInput();removeClass(this._button,this._settings.hoverClass);removeClass(this._button,this._settings.focusClass);},_rerouteClicks:function(){var self=this;addEvent(self._button,'mouseover',function(){if(self._disabled){return;}
if(!self._input){self._createInput();}
var div=self._input.parentNode;copyLayout(self._button,div);div.style.visibility='visible';});},_createIframe:function(){var id=getUID();var iframe=toElement('<iframe src="javascript:false;" name="'+id+'" />');iframe.setAttribute('id',id);iframe.style.display='none';document.body.appendChild(iframe);return iframe;},_createForm:function(iframe){var settings=this._settings;var form=toElement('<form method="post" enctype="multipart/form-data"></form>');form.setAttribute('action',settings.action);form.setAttribute('target',iframe.name);form.style.display='none';document.body.appendChild(form);for(var prop in settings.data){if(settings.data.hasOwnProperty(prop)){var el=document.createElement("input");el.setAttribute('type','hidden');el.setAttribute('name',prop);el.setAttribute('value',settings.data[prop]);form.appendChild(el);}}
return form;},_getResponse:function(iframe,file){var toDeleteFlag=false,self=this,settings=this._settings;addEvent(iframe,'load',function(){if(iframe.src=="javascript:'%3Chtml%3E%3C/html%3E';"||iframe.src=="javascript:'<html></html>';"){if(toDeleteFlag){setTimeout(function(){removeNode(iframe);},0);}
return;}
var doc=iframe.contentDocument?iframe.contentDocument:window.frames[iframe.id].document;if(doc.readyState&&doc.readyState!='complete'){return;}
if(doc.body&&doc.body.innerHTML=="false"){return;}
var response;if(doc.XMLDocument){response=doc.XMLDocument;}else if(doc.body){response=doc.body.innerHTML;if(settings.responseType&&settings.responseType.toLowerCase()=='json'){if(doc.body.firstChild&&doc.body.firstChild.nodeName.toUpperCase()=='PRE'){doc.normalize();response=doc.body.firstChild.firstChild.nodeValue;}
if(response){response=eval("("+response+")");}else{response={};}}}else{response=doc;}
settings.onComplete.call(self,file,response);toDeleteFlag=true;iframe.src="javascript:'<html></html>';";});},submit:function(){var self=this,settings=this._settings;if(!this._input||this._input.value===''){return;}
var file=fileFromPath(this._input.value);if(false===settings.onSubmit.call(this,file,getExt(file))){this._clearInput();return;}
var iframe=this._createIframe();var form=this._createForm(iframe);removeNode(this._input.parentNode);removeClass(self._button,self._settings.hoverClass);removeClass(self._button,self._settings.focusClass);form.appendChild(this._input);form.submit();removeNode(form);form=null;removeNode(this._input);this._input=null;this._getResponse(iframe,file);this._createInput();}};})();

2
js/country.min.js vendored

File diff suppressed because one or more lines are too long

View file

@ -1 +0,0 @@
function ACPopup(elm,backend_url){this.idsel=-1;this.element=elm;this.searchText="";this.ready=true;this.kp_timer=false;this.url=backend_url;var w=530;var h=130;if(typeof elm.editorId=="undefined"){style=$(elm).offset();w=$(elm).width();h=$(elm).height()}else{var container=elm.getContainer();if(typeof container!="undefined"){style=$(container).offset();w=$(container).width();h=$(container).height()}}style.top=style.top+h;style.width=w;style.position="absolute";style.display="none";this.cont=$("<div class='acpopup'></div>");this.cont.css(style);$("body").append(this.cont)}ACPopup.prototype.close=function(){$(this.cont).remove();this.ready=false};ACPopup.prototype.search=function(text){var that=this;this.searchText=text;if(this.kp_timer)clearTimeout(this.kp_timer);this.kp_timer=setTimeout(function(){that._search()},500)};ACPopup.prototype._search=function(){console.log("_search");var that=this;var postdata={start:0,count:100,search:this.searchText,type:"c"};$.ajax({type:"POST",url:this.url,data:postdata,dataType:"json",success:function(data){that.cont.html("");if(data.tot>0){that.cont.show();$(data.items).each(function(){html="<img src='{0}' height='16px' width='16px'>{1} ({2})".format(this.photo,this.name,this.nick);that.add(html,this.nick.replace(" ","")+"+"+this.id+" - "+this.link)})}else{that.cont.hide()}}})};ACPopup.prototype.add=function(label,value){var that=this;var elm=$("<div class='acpopupitem' title='"+value+"'>"+label+"</div>");elm.click(function(e){t=$(this).attr("title").replace(new RegExp(" - .*"),"");if(typeof that.element.container==="undefined"){el=$(that.element);sel=el.getSelection();sel.start=sel.start-that.searchText.length;el.setSelection(sel.start,sel.end).replaceSelectedText(t+" ").collapseSelection(false);that.close()}else{txt=tinyMCE.activeEditor.getContent();newtxt=txt.replace("@"+that.searchText,"@"+t+" ");tinyMCE.activeEditor.setContent(newtxt);tinyMCE.activeEditor.focus();that.close()}});$(this.cont).append(elm)};ACPopup.prototype.onkey=function(event){if(event.keyCode=="13"){if(this.idsel>-1){this.cont.children()[this.idsel].click();event.preventDefault()}else this.close()}if(event.keyCode=="38"){cmax=this.cont.children().size()-1;this.idsel--;if(this.idsel<0)this.idsel=cmax;event.preventDefault()}if(event.keyCode=="40"||event.keyCode=="9"){cmax=this.cont.children().size()-1;this.idsel++;if(this.idsel>cmax)this.idsel=0;event.preventDefault()}if(event.keyCode=="38"||event.keyCode=="40"||event.keyCode=="9"){this.cont.children().removeClass("selected");$(this.cont.children()[this.idsel]).addClass("selected")}if(event.keyCode=="27"){this.close()}};function ContactAutocomplete(element,backend_url){this.pattern=/@([^ \n]+)$/;this.popup=null;var that=this;$(element).unbind("keydown");$(element).unbind("keyup");$(element).keydown(function(event){if(that.popup!==null)that.popup.onkey(event)});$(element).keyup(function(event){cpos=$(this).getSelection();if(cpos.start==cpos.end){match=$(this).val().substring(0,cpos.start).match(that.pattern);if(match!==null){if(that.popup===null){that.popup=new ACPopup(this,backend_url)}if(that.popup.ready&&match[1]!==that.popup.searchText)that.popup.search(match[1]);if(!that.popup.ready)that.popup=null}else{if(that.popup!==null){that.popup.close();that.popup=null}}}})}(function($){$.fn.contact_autocomplete=function(backend_url){this.each(function(){new ContactAutocomplete(this,backend_url)})}})(jQuery);

View file

@ -1 +0,0 @@
(function($){var ajax_old=$.ajax;var get_old=$.get;var post_old=$.post;var active=true;$.ajaxSetup({stream:false,pollInterval:500});$.enableAjaxStream=function(enable){if(typeof enable=="undefined")enable=!active;if(!enable){$.ajax=ajax_old;$.get=get_old;$.post=post_old;active=false}else{$.ajax=ajax_stream;$.get=ajax_get_stream;$.post=ajax_post_stream;active=true}};var ajax_stream=$.ajax=function(options){options=jQuery.extend(true,options,jQuery.extend(true,{},jQuery.ajaxSettings,options));if(options.stream){var timer=0;var offset=0;var xmlhttp=null;var lastlen=0;var done=false;var hook=function(xhr){xmlhttp=xhr;checkagain()};var fix=function(){check("stream")};var checkagain=function(){if(!done)timer=setTimeout(fix,options.pollInterval)};var check=function(status){if(typeof status=="undefined")status="stream";if(xmlhttp.status<3)return;var text=xmlhttp.responseText;if(status=="stream"){if(text.length<=lastlen){checkagain();return}lastlength=text.length;if(offset==text.length){checkagain();return}}var pkt=text.substr(offset);offset=text.length;if($.isFunction(options.OnDataRecieved)){options.OnDataRecieved(pkt,status,xmlhttp.responseText,xmlhttp)}if(xmlhttp.status!=4)checkagain()};var complete=function(xhr,s){clearTimeout(timer);done=true;check(s)};if($.isFunction(options.success)){var oc=options.success;options.success=function(xhr,s){complete(xhr,s);oc(xhr,s)}}else options.success=complete;if($.isFunction(options.beforeSend)){var obs=options.beforeSend;options.beforeSend=function(xhr){obs(xhr);hook(xhr)}}else options.beforeSend=hook}ajax_old(options)};var ajax_get_stream=$.get=function(url,data,callback,type,stream){if($.isFunction(data)){var orgcb=callback;callback=data;if($.isFunction(orgcb)){stream=orgcb}data=null}if($.isFunction(type)){stream=type;type=undefined}var dostream=$.isFunction(stream);return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type,stream:dostream,OnDataRecieved:stream})};var ajax_post_stream=$.post=function(url,data,callback,type,stream){if($.isFunction(data)){var orgcb=callback;callback=data}if($.isFunction(type)){stream=type;type=undefined}var dostream=$.isFunction(stream);return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type,stream:dostream,OnDataRecieved:stream})}})(jQuery);

View file

@ -80,19 +80,23 @@
}
}
$('a[rel^=#]').click(function(e){
e.preventDefault();
var parent = $(this).parent();
var isSelected = (last_popup_button && parent.attr('id') == last_popup_button.attr('id'));
close_last_popup_menu();
if(isSelected) return false;
menu = $( $(this).attr('rel') );
e.preventDefault();
e.stopPropagation();
if (menu.attr('popup')=="false") return false;
$(this).parent().toggleClass("selected");
parent.toggleClass("selected");
menu.toggle();
if (menu.css("display") == "none") {
last_popup_menu = null;
last_popup_button = null;
} else {
last_popup_menu = menu;
last_popup_button = $(this).parent();
last_popup_button = parent;
}
return false;
});
@ -101,10 +105,6 @@
});
// fancyboxes
/*$("a.popupbox").fancybox({
'transitionIn' : 'elastic',
'transitionOut' : 'elastic'
});*/
$("a.popupbox").colorbox({
'inline' : true,
'transition' : 'elastic'
@ -703,6 +703,7 @@ function setupFieldRichtext(){
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "center",
theme_advanced_blockformats : "blockquote,code",
theme_advanced_resizing : true,
paste_text_sticky : true,
entity_encoding : "raw",
add_unload_trigger : false,

1
js/main.min.js vendored

File diff suppressed because one or more lines are too long

View file

@ -1 +0,0 @@
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(input){var output="";var chr1,chr2,chr3,enc1,enc2,enc3,enc4;var i=0;input=Base64._utf8_encode(input);while(i<input.length){chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=(chr1&3)<<4|chr2>>4;enc3=(chr2&15)<<2|chr3>>6;enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64}else if(isNaN(chr3)){enc4=64}output=output+this._keyStr.charAt(enc1)+this._keyStr.charAt(enc2)+this._keyStr.charAt(enc3)+this._keyStr.charAt(enc4)}return output},decode:function(input){var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(i<input.length){enc1=this._keyStr.indexOf(input.charAt(i++));enc2=this._keyStr.indexOf(input.charAt(i++));enc3=this._keyStr.indexOf(input.charAt(i++));enc4=this._keyStr.indexOf(input.charAt(i++));chr1=enc1<<2|enc2>>4;chr2=(enc2&15)<<4|enc3>>2;chr3=(enc3&3)<<6|enc4;output=output+String.fromCharCode(chr1);if(enc3!=64){output=output+String.fromCharCode(chr2)}if(enc4!=64){output=output+String.fromCharCode(chr3)}}output=Base64._utf8_decode(output);return output},_utf8_encode:function(string){string=string.replace(/\r\n/g,"\n");var utftext="";for(var n=0;n<string.length;n++){var c=string.charCodeAt(n);if(c<128){utftext+=String.fromCharCode(c)}else if(c>127&&c<2048){utftext+=String.fromCharCode(c>>6|192);utftext+=String.fromCharCode(c&63|128)}else{utftext+=String.fromCharCode(c>>12|224);utftext+=String.fromCharCode(c>>6&63|128);utftext+=String.fromCharCode(c&63|128)}}return utftext},_utf8_decode:function(utftext){var string="";var i=0;var c=c1=c2=0;while(i<utftext.length){c=utftext.charCodeAt(i);if(c<128){string+=String.fromCharCode(c);i++}else if(c>191&&c<224){c2=utftext.charCodeAt(i+1);string+=String.fromCharCode((c&31)<<6|c2&63);i+=2}else{c2=utftext.charCodeAt(i+1);c3=utftext.charCodeAt(i+2);string+=String.fromCharCode((c&15)<<12|(c2&63)<<6|c3&63);i+=3}}return string}};

View file

@ -17,6 +17,12 @@ class HTML5_Parser
* @return Parsed HTML as DOMDocument
*/
static public function parse($text, $builder = null) {
// Cleanup invalid HTML
$doc = new DOMDocument();
@$doc->loadHTML($text);
$text = $doc->saveHTML();
$tokenizer = new HTML5_Tokenizer($text, $builder);
$tokenizer->parse();
return $tokenizer->save();

View file

@ -1,4 +1,4 @@
Smarty 3.1.11
Smarty 3.1.19
Author: Monte Ohrt <monte at ohrt dot com >
Author: Uwe Tews
@ -120,7 +120,7 @@ $smarty->unregisterObject($object_name)
$smarty->unregisterFilter($type, $function_name)
$smarty->unregisterResource($resource_type)
$smarty->compileAllTemplates($extention = '.tpl', $force_compile = false, $time_limit = 0, $max_errors = null)
$smarty->compileAllTemplates($extension = '.tpl', $force_compile = false, $time_limit = 0, $max_errors = null)
$smarty->clearCompiledTemplate($resource_name = null, $compile_id = null, $exp_time = null)
$smarty->testInstall()

View file

@ -199,7 +199,7 @@ Relative paths are available with {include file="..."} and
$smarty->fetch('./foo.tpl') cannot be relative to a template, an
exception is thrown.
Adressing a specific $template_dir
Addressing a specific $template_dir
Smarty 3.1 introduces the $template_dir index notation.
$smarty->fetch('[foo]bar.tpl') and {include file="[foo]bar.tpl"}

View file

@ -1,4 +1,297 @@
===== trunk =====
===== 3.1.20-dev ===== (xx.xx.2014)
===== 3.1.19 ===== (06.30.2014)
20.06.2014
- bugfix template variables could not be passed as paramter in {include} when the include was in a {nocache} section (topic 25131)
17.06.2014
- bugfix large template text of some charsets could cause parsing errors (topic 24630)
08.06.2014
- bugfix registered objects did not work after spelling fixes of 06.06.2014
- bugfix {block} tags within {literal} .. {/literal} got not displayed correctly (topic 25024)
- bugfix UNC WINDOWS PATH like "\\psf\path\to\dir" did not work as template directory (Issue 192)
- bugfix {html_image} security check did fail on files relative to basedir (Issue 191)
06.06.2014
- fixed PHPUnit outputFilterTrimWhitespaceTests.php assertion of test result
- fixed spelling, PHPDoc , minor errors, code cleanup
02.06.2014
- using multiple cwd with relative template dirs could result in identical compiled file names. (issue 194 and topic 25099)
19.04.2014
- bugfix calling createTemplate(template, data) with empty data array caused notice of array to string conversion (Issue 189)
- bugfix clearCompiledTemplate() did not delete files on WINDOWS when a compile_id was specified
18.04.2014
- revert bugfix of 5.4.2014 because %-e date format is not supported on all operating systems
===== 3.1.18 ===== (07.04.2014)
06.04.2014
- bugfix template inheritance fail when using custom resource after patch of 8.3.2014 (Issue 187)
- bugfix update of composer file (Issue 168 and 184)
05.04.2014
- bugfix default date format leads to extra spaces when displaying dates with single digit days (Issue 165)
26.03.2014
- bugfix Smart_Resource_Custom should not lowercase the resource name (Issue 183)
24.03.2014
- bugfix using a {foreach} property like @iteration could fail when used in inheritance parent templates (Issue 182)
20.03.2014
- bugfix $smarty->auto_literal and mbsting.func_overload 2, 6 or 7 did fail (forum topic 24899)
18.03.2014
- revert change of 17.03.2014
17.03.2014
- bugfix $smarty->auto_literal and mbsting.func_overload 2, 6 or 7 did fail (forum topic 24899)
15.03.2014
- bugfix Smarty_CacheResource_Keyvaluestore did use different keys on read/writes and clearCache() calls (Issue 169)
13.03.2014
- bugfix clearXxx() change of 27.1.2014 did not work when specifing cache_id or compile_id (forum topic 24868 and 24867)
===== 3.1.17 =====
08.03.2014
- bugfix relative file path {include} within {block} of child templates did throw exception on first call (Issue 177)
17.02.2014
- bugfix Smarty failed when executing PHP on HHVM (Hip Hop 2.4) because uniqid('',true) does return string with ',' (forum topic 20343)
16.02.2014
- bugfix a '//' or '\\' in template_dir path could produce wrong path on relative filepath in {include} (Issue 175)
05.02.2014
- bugfix shared.literal_compiler_param.php did throw an exception when literal did contain a '-' (smarty-developers group)
27.01.2014
- bugfix $smarty->debugging = true; did show the variable of the $smarty object not the variables used in display() call (forum topic 24764)
- bugfix clearCompiledTemplate(), clearAll() and clear() should use realpath to avoid possible exception from RecursiveDirectoryIterator (Issue 171)
26.01.2014
- bugfix undo block nesting checks for {nocache} for reasons like forum topic 23280 (forum topic 24762)
18.01.2014
- bugfix the compiler did fail when using template inheritance and recursive {include} (smarty-developers group)
11.01.2014
- bugfix "* }" (spaces before right delimiter) was interpreted by mistake as comment end tag (Issue 170)
- internals content cache should be clear when updating cache file
08.01.2014
- bugfix Smarty_CacheResource_Custom did not handle template resource type specifications on clearCache() calls (Issue 169)
- bugfix SmartyBC.class.php should use require_once to load Smarty.class.php (forum topic 24683)
===== 3.1.16 =====
15.12.2013
- bugfix {include} with {block} tag handling (forum topic 24599, 24594, 24682) (Issue 161)
Read 3.1.16_RELEASE_NOTES for more details
- enhancement additional debug output at $smarty->_parserdebug = true;
07.11.2013
- bugfix too restrictive handling of {include} within {block} tags. 3.1.15 did throw errors where 3.1.14 did not (forum topic 24599)
- bugfix compiler could fail if PHP mbstring.func_overload is enabled (Issue 164)
28.10.2013
- bugfix variable resource name at custom resource plugin did not work within {block} tags (Issue 163)
- bugfix notice "Trying to get property of non-object" removed (Issue 163)
- bugfix correction of modifier capitalize fix from 3.10.2013 (issue 159)
- bugfix multiple {block}s with same name in parent did not work (forum topic 24631)
20.10.2013
- bugfix a variable file name at {extends} tag did fail (forum topic 24618)
14.10.2013
- bugfix yesterdays fix could result in an undefined variable
13.10.2013
- bugfix variable names on {include} in template inheritance did unextepted error message (forum topic 24594) (Issue 161)
.- bugfix relative includes with same name like {include './foo.tpl'} from different folder failed (forum topic 24590)(Issue 161)
04.10.2013
- bugfix variable file names at {extends} had been disbabled by mistake with the rewrite of
template inheritance of 24.08.2013 (forum topic 24585)
03.10.2013
- bugfix loops using modifier capitalize did eat up memory (issue 159)
===== Smarty 3.1.15 =====
01.10.2013
- use current delimiters in compiler error messages (issue 157)
- improvement on performance when using error handler and multiple template folders (issue 152)
17.09.2013
- improvement added patch for additional SmartyCompilerException properties for better access to scource information (forum topic 24559)
16.09.2013
- bugfix recompiled templates did not show on first request with zend opcache cache (forum topic 24320)
13.09.2013
- bugfix html_select_time defaulting error for the Meridian dropdown (forum topic 24549)
09.09.2012
- bugfix incorrect compiled code with array(object,method) callback at registered Variable Filter (forum topic 24542)
27.08.2013
- bugfix delimiter followed by linebreak did not work as auto literal after update from 24.08.2013 (forum topic 24518)
24.08.2013
- bugfix and enhancement
Because several recent problems with template inheritance the {block} tag compiler has been rewriten
- Error messages shown now the correct child template file and line number
- The compiler could fail on some larger UTF-8 text block (forum topic 24455)
- The {strip} tag can now be placed outside {block} tags in child templates (forum topic 24289)
- change SmartyException::$escape is now false by default
- change PHP traceback has been remove for SmartyException and SmartyCompilerException
14.08.2013
- bugfix compiled filepath of config file did not observe different config_dir (forum topic 24493)
13.08.2013
- bugfix the internal resource cache did not observe config_dir changes (forum topic 24493)
12.08.2013
- bugfix internal $tmpx variables must be unique over all inheritance templates (Issue 149)
10.08.2013
- bugfix a newline was eaten when a <?xml ... ?> was passed by a Smarty variable and caching was enabled (forum topic 24482)
29.07.2013
- bugfix headers already send warning thrown when using 'SMARTY_DEBUG=on' from URL (Issue 148)
27.07.2013
- enhancement allow access to properties of registered opjects for Smarty2 BC (forum topic 24344)
26.07.2013
- bugfix template inheritance nesting problem (forum topic 24387)
15.7.2013
- update code generated by PSR-2 standards fixer which introduced PHP 5.4 incompatibilities of 14.7.2013
14.7.2013
- bugfix increase of internal maximum parser stacksize to allow more complex tag code {forum topic 24426}
- update for PHP 5.4 compatibility
- reformat source to PSR-2 standard
12.7.2013
- bugfix Do not remove '//' from file path at normalization (Issue 142)
2.7.2013
- bugfix trimwhitespace would replace captured items in wrong order (forum topic 24387)
===== Smarty-3.1.14 =====
27.06.2013
- bugfix removed PHP 5.5 deprecated preg_replace /e option in modifier capitalize (forum topic 24389)
17.06.2013
- fixed spelling in sources and documentation (from smarty-developers forum Veres Lajos)
- enhancement added constant SMARTY::CLEAR_EXPIRED for the change of 26.05.2013 (forum topic 24310)
- bugfix added smarty_security.php to composer.json (Issue 135)
26.05.2013
- enhancement an expire_time of -1 in clearCache() and clearAllCache() will delete outdated cache files
by their individual cache_lifetime used at creation (forum topic 24310)
21.05.2013
- bugfix modifier strip_tags:true was compiled into wrong code (Forum Topic 24287)
- bugfix /n after ?> in Smarty.class.php did start output buffering (Issue 138)
25.04.2013
- bugfix escape and wordrap modifier could be compiled into wrong code when used in {nocache}{/nocache}
section but caching is disabled (Forum Topic 24260)
05.04.2013
- bugfix post filter must not run when compiling inheritance child blocks (Forum Topic 24094)
- bugfix after the fix for Issue #130 compiler exceptions got double escaped (Forum Topic 24199)
28.02.2013
- bugfix nocache blocks could be lost when using CACHING_LIFETIME_SAVED (Issue #133)
- bugfix Compile ID gets nulled when compiling child blocks (Issue #134)
24.01.2013
- bugfix wrong tag type in smarty_internal_templatecompilerbase.php could cause wrong plugin search order (Forum Topic 24028)
===== Smarty-3.1.13 =====
13.01.2013
- enhancement allow to disable exception message escaping by SmartyException::$escape = false; (Issue #130)
09.01.2013
- bugfix compilation did fail when a prefilter did modify an {extends} tag c
- bugfix template inheritance could fail if nested {block} tags in childs did contain {$smarty.block.child} (Issue #127)
- bugfix template inheritance could fail if {block} tags in childs did have similar name as used plugins (Issue #128)
- added abstract method declaration doCompile() in Smarty_Internal_TemplateCompilerBase (Forum Topic 23969)
06.01.2013
- Allow '://' URL syntax in template names of stream resources (Issue #129)
27.11.2012
- bugfix wrong variable usage in smarty_internal_utility.php (Issue #125)
26.11.2012
- bugfix global variable assigned within template function are not seen after template function exit (Forum Topic 23800)
24.11.2012
- made SmartyBC loadable via composer (Issue #124)
20.11.2012
- bugfix assignGlobal() called from plugins did not work (Forum Topic 23771)
13.11.2012
- adding attribute "strict" to html_options, html_checkboxes, html_radios to only print disabled/readonly attributes if their values are true or "disabled"/"readonly" (Issue #120)
01.11.2012
- bugfix muteExcpetedErrors() would screw up for non-readable paths (Issue #118)
===== Smarty-3.1.12 =====
14.09.2012
- bugfix template inheritance failed to compile with delimiters {/ and /} (Forum Topic 23008)
11.09.2012
- bugfix escape Smarty exception messages to avoid possible script execution
10.09.2012
- bugfix tag option flags and shorttag attributes did not work when rdel started with '=' (Forum Topic 22979)
31.08.2012
- bugfix resolving relative paths broke in some circumstances (Issue #114)
22.08.2012
- bugfix test MBString availability through mb_split, as it could've been compiled without regex support (--enable-mbregex).
Either we get MBstring's full package, or we pretend it's not there at all.
21.08.2012
- bugfix $auto_literal = false did not work with { block} tags in child templates
(problem was reintroduced after fix in 3.1.7)(Forum Topic 20581)
17.08.2012
- bugfix compiled code of nocache sections could contain wrong escaping (Forum Topic 22810)
15.08.2012
- bugfix template inheritance did produce wrong code if subtemplates with {block} was
included several times (from smarty-developers forum)
14.08.2012
- bugfix PHP5.2 compatibility compromised by SplFileInfo::getBasename() (Issue 110)
01.08.2012
- bugfix avoid PHP error on $smarty->configLoad(...) with invalid section specification (Forum Topic 22608)
30.07.2012
-bugfix {assign} in a nocache section should not overwrite existing variable values
during compilation (issue 109)
28.07.2012
- bugfix array access of config variables did not work (Forum Topic 22527)
19.07.2012
- bugfix the default plugin handler did create wrong compiled code for static class methods
from external script files (issue 108)
===== Smarty-3.1.11 =====
30.06.2012
- bugfix {block.. hide} did not work as nested child (Forum Topic 22216)
@ -342,7 +635,7 @@
03/09/2011
- bugfix createTemplate() must default to cache_id and compile_id of Smarty object
- bugfix Smarty_CacheResource_KeyValueStore must include $source->uid in cache filepath to keep templates with same
name but different folders seperated
name but different folders separated
- added cacheresource.apc.php example in demo folder
02/09/2011
@ -533,7 +826,7 @@
- changed ./ and ../ behaviour
14/02/2011
- added {block ... hide} option to supress block if no child is defined
- added {block ... hide} option to suppress block if no child is defined
13/02/2011
- update handling of recursive subtemplate calls
@ -647,7 +940,7 @@
- bugfix on compiler object destruction. compiler_object property was by mistake unset.
09/03/2011
-bugfix a variable filter should run before modifers on an output tag (see change of 23/07/2010)
-bugfix a variable filter should run before modifiers on an output tag (see change of 23/07/2010)
08/03/2011
- bugfix loading config file without section should load only defaults
@ -951,10 +1244,10 @@ request_use_auto_globals
- bugfix passing scope attributes in doublequoted strings did not work at {include} {assign} and {append}
25/07/2010
- another bugfix of change from 23/07/2010 when compiling modifer
- another bugfix of change from 23/07/2010 when compiling modifier
24/07/2010
- bugfix of change from 23/07/2010 when compiling modifer
- bugfix of change from 23/07/2010 when compiling modifier
23/07/2010
- changed execution order. A variable filter does now run before modifiers on output of variables
@ -1261,7 +1554,7 @@ request_use_auto_globals
- bugfix on {if} tags
01/12/2010
- changed back modifer handling in parser. Some restrictions still apply:
- changed back modifier handling in parser. Some restrictions still apply:
if modifiers are used in side {if...} expression or in mathematical expressions
parentheses must be used.
- bugfix the {function..} tag did not accept the name attribute in double quotes
@ -1873,7 +2166,7 @@ NOTICE: existing compiled template and cache files must be deleted
- fixed exceptions in function plugins
- fixed notice error in Smarty.class.php
- allow chained objects to span multiple lines
- fixed error in modifers
- fixed error in modifiers
03/20/2009
- moved /plugins folder into /libs folder
@ -1881,7 +2174,7 @@ NOTICE: existing compiled template and cache files must be deleted
- autoappend a directory separator if the xxxxx_dir definition have no trailing one
03/19/2009
- allow array definition as modifer parameter
- allow array definition as modifier parameter
- changed modifier to use multi byte string funktions.
03/17/2009

View file

@ -1,16 +1,14 @@
<?php
/**
* Example Application
*
* @package Example-application
*/
require('../libs/Smarty.class.php');
require '../libs/Smarty.class.php';
$smarty = new Smarty;
//$smarty->force_compile = true;
$smarty->debugging = true;
$smarty->caching = true;
@ -30,4 +28,3 @@ $smarty->assign("option_output", array("New York","Nebraska","Kansas","Iowa","Ok
$smarty->assign("option_selected", "NE");
$smarty->display('index.tpl');
?>

View file

@ -2,15 +2,15 @@
/**
* APC CacheResource
*
* CacheResource Implementation based on the KeyValueStore API to use
* memcache as the storage resource for Smarty's output caching.
* *
*
* @package CacheResource-examples
* @author Uwe Tews
*/
class Smarty_CacheResource_Apc extends Smarty_CacheResource_KeyValueStore {
class Smarty_CacheResource_Apc extends Smarty_CacheResource_KeyValueStore
{
public function __construct()
{
// test if APC is present
@ -23,6 +23,7 @@ class Smarty_CacheResource_Apc extends Smarty_CacheResource_KeyValueStore {
* Read values for a set of keys from cache
*
* @param array $keys list of keys to fetch
*
* @return array list of values with the given keys used as indexes
* @return boolean true on success, false on failure
*/
@ -33,6 +34,7 @@ class Smarty_CacheResource_Apc extends Smarty_CacheResource_KeyValueStore {
foreach ($res as $k => $v) {
$_res[$k] = $v;
}
return $_res;
}
@ -41,6 +43,7 @@ class Smarty_CacheResource_Apc extends Smarty_CacheResource_KeyValueStore {
*
* @param array $keys list of values to save
* @param int $expire expiration time
*
* @return boolean true on success, false on failure
*/
protected function write(array $keys, $expire = null)
@ -48,6 +51,7 @@ class Smarty_CacheResource_Apc extends Smarty_CacheResource_KeyValueStore {
foreach ($keys as $k => $v) {
apc_store($k, $v, $expire);
}
return true;
}
@ -55,6 +59,7 @@ class Smarty_CacheResource_Apc extends Smarty_CacheResource_KeyValueStore {
* Remove values from cache
*
* @param array $keys list of keys to delete
*
* @return boolean true on success, false on failure
*/
protected function delete(array $keys)
@ -62,6 +67,7 @@ class Smarty_CacheResource_Apc extends Smarty_CacheResource_KeyValueStore {
foreach ($keys as $k) {
apc_delete($k);
}
return true;
}

View file

@ -2,19 +2,19 @@
/**
* Memcache CacheResource
*
* CacheResource Implementation based on the KeyValueStore API to use
* memcache as the storage resource for Smarty's output caching.
*
* Note that memcache has a limitation of 256 characters per cache-key.
* To avoid complications all cache-keys are translated to a sha1 hash.
*
* @package CacheResource-examples
* @author Rodney Rehm
*/
class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore {
class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore
{
/**
* memcache instance
*
* @var Memcache
*/
protected $memcache = null;
@ -29,6 +29,7 @@ class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore {
* Read values for a set of keys from cache
*
* @param array $keys list of keys to fetch
*
* @return array list of values with the given keys used as indexes
* @return boolean true on success, false on failure
*/
@ -45,6 +46,7 @@ class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore {
foreach ($res as $k => $v) {
$_res[$lookup[$k]] = $v;
}
return $_res;
}
@ -53,6 +55,7 @@ class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore {
*
* @param array $keys list of values to save
* @param int $expire expiration time
*
* @return boolean true on success, false on failure
*/
protected function write(array $keys, $expire = null)
@ -61,6 +64,7 @@ class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore {
$k = sha1($k);
$this->memcache->set($k, $v, 0, $expire);
}
return true;
}
@ -68,6 +72,7 @@ class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore {
* Remove values from cache
*
* @param array $keys list of keys to delete
*
* @return boolean true on success, false on failure
*/
protected function delete(array $keys)
@ -76,6 +81,7 @@ class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore {
$k = sha1($k);
$this->memcache->delete($k);
}
return true;
}
@ -86,6 +92,6 @@ class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore {
*/
protected function purge()
{
return $this->memcache->flush();
$this->memcache->flush();
}
}

View file

@ -2,10 +2,8 @@
/**
* MySQL CacheResource
*
* CacheResource Implementation based on the Custom API to use
* MySQL as the storage resource for Smarty's output caching.
*
* Table definition:
* <pre>CREATE TABLE IF NOT EXISTS `output_cache` (
* `id` CHAR(40) NOT NULL COMMENT 'sha1 hash',
@ -24,17 +22,20 @@
* @package CacheResource-examples
* @author Rodney Rehm
*/
class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom {
class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom
{
// PDO instance
protected $db;
protected $fetch;
protected $fetchTimestamp;
protected $save;
public function __construct() {
public function __construct()
{
try {
$this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty", "smarty");
} catch (PDOException $e) {
$this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty");
}
catch (PDOException $e) {
throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
}
$this->fetch = $this->db->prepare('SELECT modified, content FROM output_cache WHERE id = :id');
@ -52,6 +53,7 @@ class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom {
* @param string $compile_id compile id
* @param string $content cached content
* @param integer $mtime cache modification timestamp (epoch)
*
* @return void
*/
protected function fetch($id, $name, $cache_id, $compile_id, &$content, &$mtime)
@ -72,10 +74,12 @@ class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom {
* Fetch cached content's modification timestamp from data source
*
* @note implementing this method is optional. Only implement it if modification times can be accessed faster than loading the complete cached content.
*
* @param string $id unique cache content identifier
* @param string $name template name
* @param string $cache_id cache id
* @param string $compile_id compile id
*
* @return integer|boolean timestamp (epoch) the template was modified, or false if not found
*/
protected function fetchTimestamp($id, $name, $cache_id, $compile_id)
@ -83,6 +87,7 @@ class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom {
$this->fetchTimestamp->execute(array('id' => $id));
$mtime = strtotime($this->fetchTimestamp->fetchColumn());
$this->fetchTimestamp->closeCursor();
return $mtime;
}
@ -95,6 +100,7 @@ class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom {
* @param string $compile_id compile id
* @param integer|null $exp_time seconds till expiration time in seconds or null
* @param string $content content to cache
*
* @return boolean success
*/
protected function save($id, $name, $cache_id, $compile_id, $exp_time, $content)
@ -106,6 +112,7 @@ class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom {
'compile_id' => $compile_id,
'content' => $content,
));
return !!$this->save->rowCount();
}
@ -116,6 +123,7 @@ class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom {
* @param string $cache_id cache id
* @param string $compile_id compile id
* @param integer|null $exp_time seconds till expiration or null
*
* @return integer number of deleted caches
*/
protected function delete($name, $cache_id, $compile_id, $exp_time)
@ -124,6 +132,7 @@ class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom {
if ($name === null && $cache_id === null && $compile_id === null && $exp_time === null) {
// returning the number of deleted caches would require a second query to count them
$query = $this->db->query('TRUNCATE TABLE output_cache');
return - 1;
}
// build the filter
@ -147,6 +156,7 @@ class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom {
}
// run delete query
$query = $this->db->query('DELETE FROM output_cache WHERE ' . join(' AND ', $where));
return $query->rowCount();
}
}

View file

@ -2,20 +2,20 @@
/**
* Extends All Resource
*
* Resource Implementation modifying the extends-Resource to walk
* through the template_dirs and inherit all templates of the same name
*
* @package Resource-examples
* @author Rodney Rehm
*/
class Smarty_Resource_Extendsall extends Smarty_Internal_Resource_Extends {
class Smarty_Resource_Extendsall extends Smarty_Internal_Resource_Extends
{
/**
* populate Source Object with meta data from Resource
*
* @param Smarty_Template_Source $source source object
* @param Smarty_Internal_Template $_template template object
*
* @return void
*/
public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null)
@ -32,12 +32,14 @@ class Smarty_Resource_Extendsall extends Smarty_Internal_Resource_Extends {
$sources[$s->uid] = $s;
$uid .= $s->filepath;
}
catch (SmartyException $e) {}
catch (SmartyException $e) {
}
}
if (!$sources) {
$source->exists = false;
$source->template = $_template;
return;
}
@ -56,5 +58,3 @@ class Smarty_Resource_Extendsall extends Smarty_Internal_Resource_Extends {
$source->template = $_template;
}
}
?>

View file

@ -2,10 +2,8 @@
/**
* MySQL Resource
*
* Resource Implementation based on the Custom API to use
* MySQL as the storage resource for Smarty's templates and configs.
*
* Table definition:
* <pre>CREATE TABLE IF NOT EXISTS `templates` (
* `name` varchar(100) NOT NULL,
@ -13,14 +11,14 @@
* `source` text,
* PRIMARY KEY (`name`)
* ) ENGINE=InnoDB DEFAULT CHARSET=utf8;</pre>
*
* Demo data:
* <pre>INSERT INTO `templates` (`name`, `modified`, `source`) VALUES ('test.tpl', "2010-12-25 22:00:00", '{$x="hello world"}{$x}');</pre>
*
* @package Resource-examples
* @author Rodney Rehm
*/
class Smarty_Resource_Mysql extends Smarty_Resource_Custom {
class Smarty_Resource_Mysql extends Smarty_Resource_Custom
{
// PDO instance
protected $db;
// prepared fetch() statement
@ -28,10 +26,12 @@ class Smarty_Resource_Mysql extends Smarty_Resource_Custom {
// prepared fetchTimestamp() statement
protected $mtime;
public function __construct() {
public function __construct()
{
try {
$this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty", "smarty");
} catch (PDOException $e) {
$this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty");
}
catch (PDOException $e) {
throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
}
$this->fetch = $this->db->prepare('SELECT modified, source FROM templates WHERE name = :name');
@ -44,6 +44,7 @@ class Smarty_Resource_Mysql extends Smarty_Resource_Custom {
* @param string $name template name
* @param string $source template source
* @param integer $mtime template modification timestamp (epoch)
*
* @return void
*/
protected function fetch($name, &$source, &$mtime)
@ -64,13 +65,17 @@ class Smarty_Resource_Mysql extends Smarty_Resource_Custom {
* Fetch a template's modification time from database
*
* @note implementing this method is optional. Only implement it if modification times can be accessed faster than loading the comple template source.
*
* @param string $name template name
*
* @return integer timestamp (epoch) the template was modified
*/
protected function fetchTimestamp($name) {
protected function fetchTimestamp($name)
{
$this->mtime->execute(array('name' => $name));
$mtime = $this->mtime->fetchColumn();
$this->mtime->closeCursor();
return strtotime($mtime);
}
}

View file

@ -2,13 +2,10 @@
/**
* MySQL Resource
*
* Resource Implementation based on the Custom API to use
* MySQL as the storage resource for Smarty's templates and configs.
*
* Note that this MySQL implementation fetches the source and timestamps in
* a single database query, instead of two seperate like resource.mysql.php does.
*
* a single database query, instead of two separate like resource.mysql.php does.
* Table definition:
* <pre>CREATE TABLE IF NOT EXISTS `templates` (
* `name` varchar(100) NOT NULL,
@ -16,23 +13,25 @@
* `source` text,
* PRIMARY KEY (`name`)
* ) ENGINE=InnoDB DEFAULT CHARSET=utf8;</pre>
*
* Demo data:
* <pre>INSERT INTO `templates` (`name`, `modified`, `source`) VALUES ('test.tpl', "2010-12-25 22:00:00", '{$x="hello world"}{$x}');</pre>
*
* @package Resource-examples
* @author Rodney Rehm
*/
class Smarty_Resource_Mysqls extends Smarty_Resource_Custom {
class Smarty_Resource_Mysqls extends Smarty_Resource_Custom
{
// PDO instance
protected $db;
// prepared fetch() statement
protected $fetch;
public function __construct() {
public function __construct()
{
try {
$this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty", "smarty");
} catch (PDOException $e) {
$this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty");
}
catch (PDOException $e) {
throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
}
$this->fetch = $this->db->prepare('SELECT modified, source FROM templates WHERE name = :name');
@ -44,6 +43,7 @@ class Smarty_Resource_Mysqls extends Smarty_Resource_Custom {
* @param string $name template name
* @param string $source template source
* @param integer $mtime template modification timestamp (epoch)
*
* @return void
*/
protected function fetch($name, &$source, &$mtime)

View file

@ -38,9 +38,14 @@ loop=$FirstName}
An example of section looped key values:
{section name=sec1 loop=$contacts}
phone: {$contacts[sec1].phone}<br>
fax: {$contacts[sec1].fax}<br>
cell: {$contacts[sec1].cell}<br>
phone: {$contacts[sec1].phone}
<br>
fax: {$contacts[sec1].fax}
<br>
cell: {$contacts[sec1].cell}
<br>
{/section}
<p>

File diff suppressed because it is too large Load diff

View file

@ -3,21 +3,17 @@
* Project: Smarty: the PHP compiling template engine
* File: SmartyBC.class.php
* SVN: $Id: $
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* For questions, help, comments, discussion, etc., please join the
* Smarty mailing list. Send a blank e-mail to
* smarty-discussion-subscribe@googlegroups.com
@ -32,17 +28,18 @@
/**
* @ignore
*/
require(dirname(__FILE__) . '/Smarty.class.php');
require_once(dirname(__FILE__) . '/Smarty.class.php');
/**
* Smarty Backward Compatability Wrapper Class
*
* @package Smarty
*/
class SmartyBC extends Smarty {
class SmartyBC extends Smarty
{
/**
* Smarty 2 BC
*
* @var string
*/
public $_version = self::SMARTY_VERSION;
@ -122,7 +119,10 @@ class SmartyBC extends Smarty {
* @param object $object_impl the referenced PHP object to register
* @param array $allowed list of allowed methods (empty = all)
* @param boolean $smarty_args smarty argument format, else traditional
* @param array $block_functs list of methods that are block format
* @param array $block_methods list of methods that are block format
*
* @throws SmartyException
* @internal param array $block_functs list of methods that are block format
*/
public function register_object($object, $object_impl, $allowed = array(), $smarty_args = true, $block_methods = array())
{
@ -309,6 +309,7 @@ class SmartyBC extends Smarty {
* @param string $cache_id name of cache_id
* @param string $compile_id name of compile_id
* @param string $exp_time expiration time
*
* @return boolean
*/
public function clear_cache($tpl_file = null, $cache_id = null, $compile_id = null, $exp_time = null)
@ -320,6 +321,7 @@ class SmartyBC extends Smarty {
* clear the entire contents of cache (all templates)
*
* @param string $exp_time expire time
*
* @return boolean
*/
public function clear_all_cache($exp_time = null)
@ -333,6 +335,7 @@ class SmartyBC extends Smarty {
* @param string $tpl_file name of template file
* @param string $cache_id
* @param string $compile_id
*
* @return boolean
*/
public function is_cached($tpl_file, $cache_id = null, $compile_id = null)
@ -356,6 +359,7 @@ class SmartyBC extends Smarty {
* @param string $tpl_file
* @param string $compile_id
* @param string $exp_time
*
* @return boolean results of {@link smarty_core_rm_auto()}
*/
public function clear_compiled_tpl($tpl_file = null, $compile_id = null, $exp_time = null)
@ -367,6 +371,7 @@ class SmartyBC extends Smarty {
* Checks whether requested template exists.
*
* @param string $tpl_file
*
* @return boolean
*/
public function template_exists($tpl_file)
@ -378,6 +383,7 @@ class SmartyBC extends Smarty {
* Returns an array containing template variables
*
* @param string $name
*
* @return array
*/
public function get_template_vars($name = null)
@ -389,6 +395,7 @@ class SmartyBC extends Smarty {
* Returns an array containing config variables
*
* @param string $name
*
* @return array
*/
public function get_config_vars($name = null)
@ -412,6 +419,7 @@ class SmartyBC extends Smarty {
* return a reference to a registered object
*
* @param string $name
*
* @return object
*/
public function get_registered_object($name)
@ -439,7 +447,6 @@ class SmartyBC extends Smarty {
{
trigger_error("Smarty error: $error_msg", $error_type);
}
}
/**
@ -449,12 +456,12 @@ class SmartyBC extends Smarty {
* @param string $content contents of the block
* @param object $template template object
* @param boolean &$repeat repeat flag
*
* @return string content re-formatted
*/
function smarty_php_tag($params, $content, $template, &$repeat)
{
eval($content);
return '';
}
?>

View file

@ -81,21 +81,23 @@ td {
#table_config_vars th {
color: maroon;
}
{/literal}
</style>
</head>
<body>
<h1>Smarty Debug Console - {if isset($template_name)}{$template_name|debug_print_var nofilter}{else}Total Time {$execution_time|string_format:"%.5f"}{/if}</h1>
<h1>Smarty Debug Console
- {if isset($template_name)}{$template_name|debug_print_var nofilter}{else}Total Time {$execution_time|string_format:"%.5f"}{/if}</h1>
{if !empty($template_data)}
<h2>included templates &amp; config files (load time in seconds)</h2>
<div>
{foreach $template_data as $template}
<font color=brown>{$template.name}</font>
<span class="exectime">
(compile {$template['compile_time']|string_format:"%.5f"}) (render {$template['render_time']|string_format:"%.5f"}) (cache {$template['cache_time']|string_format:"%.5f"})
(compile {$template['compile_time']|string_format:"%.5f"}) (render {$template['render_time']|string_format:"%.5f"}) (cache {$template['cache_time']|string_format:"%.5f"}
)
</span>
<br>
{/foreach}
@ -108,7 +110,8 @@ td {
{foreach $assigned_vars as $vars}
<tr class="{if $vars@iteration % 2 eq 0}odd{else}even{/if}">
<th>${$vars@key|escape:'html'}</th>
<td>{$vars|debug_print_var nofilter}</td></tr>
<td>{$vars|debug_print_var nofilter}</td>
</tr>
{/foreach}
</table>
@ -118,7 +121,8 @@ td {
{foreach $config_vars as $vars}
<tr class="{if $vars@iteration % 2 eq 0}odd{else}even{/if}">
<th>{$vars@key|escape:'html'}</th>
<td>{$vars|debug_print_var nofilter}</td></tr>
<td>{$vars|debug_print_var nofilter}</td>
</tr>
{/foreach}
</table>

View file

@ -8,7 +8,6 @@
/**
* Smarty {textformat}{/textformat} block plugin
*
* Type: block function<br>
* Name: textformat<br>
* Purpose: format text a certain way with preset styles
@ -25,10 +24,12 @@
*
* @link http://www.smarty.net/manual/en/language.function.textformat.php {textformat}
* (Smarty online manual)
*
* @param array $params parameters
* @param string $content contents of the block
* @param Smarty_Internal_Template $template template object
* @param boolean &$repeat repeat flag
*
* @return string content re-formatted
* @author Monte Ohrt <monte at ohrt dot com>
*/
@ -76,8 +77,6 @@ function smarty_block_textformat($params, $content, $template, &$repeat)
}
// split into paragraphs
$_paragraphs = preg_split('![\r\n]{2}!', $content);
$_output = '';
foreach ($_paragraphs as &$_paragraph) {
if (!$_paragraph) {
@ -109,5 +108,3 @@ function smarty_block_textformat($params, $content, $template, &$repeat)
return $_output;
}
}
?>

View file

@ -1,13 +1,13 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {counter} function plugin
*
* Type: function<br>
* Name: counter<br>
* Purpose: print out a counter value
@ -15,8 +15,10 @@
* @author Monte Ohrt <monte at ohrt dot com>
* @link http://www.smarty.net/manual/en/language.function.counter.php {counter}
* (Smarty online manual)
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @return string|null
*/
function smarty_function_counter($params, $template)
@ -66,13 +68,11 @@ function smarty_function_counter($params, $template)
$counter['direction'] = $params['direction'];
}
if ($counter['direction'] == "down")
if ($counter['direction'] == "down") {
$counter['count'] -= $counter['skip'];
else
} else {
$counter['count'] += $counter['skip'];
return $retval;
}
?>
return $retval;
}

View file

@ -8,7 +8,6 @@
/**
* Smarty {cycle} function plugin
*
* Type: function<br>
* Name: cycle<br>
* Date: May 3, 2002<br>
@ -38,8 +37,10 @@
* @author credit to Gerard <gerard@interfold.com>
* @author credit to Jason Sweat <jsweat_php@yahoo.com>
* @version 1.3
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @return string|null
*/
@ -55,11 +56,13 @@ function smarty_function_cycle($params, $template)
if (!isset($params['values'])) {
if (!isset($cycle_vars[$name]['values'])) {
trigger_error("cycle: missing 'values' parameter");
return;
}
} else {
if (isset($cycle_vars[$name]['values'])
&& $cycle_vars[$name]['values'] != $params['values'] ) {
&& $cycle_vars[$name]['values'] != $params['values']
) {
$cycle_vars[$name]['index'] = 0;
}
$cycle_vars[$name]['values'] = $params['values'];
@ -102,5 +105,3 @@ function smarty_function_cycle($params, $template)
return $retval;
}
?>

View file

@ -8,7 +8,6 @@
/**
* Smarty {fetch} plugin
*
* Type: function<br>
* Name: fetch<br>
* Purpose: fetch file, web or ftp data and display results
@ -16,14 +15,18 @@
* @link http://www.smarty.net/manual/en/language.function.fetch.php {fetch}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @throws SmartyException
* @return string|null if the assign parameter is passed, Smarty assigns the result to a template variable
*/
function smarty_function_fetch($params, $template)
{
if (empty($params['file'])) {
trigger_error("[plugin] fetch parameter 'file' cannot be empty", E_USER_NOTICE);
return;
}
@ -101,6 +104,7 @@ function smarty_function_fetch($params, $template)
if (!empty($param_value)) {
if (!preg_match('![\w\d-]+: .+!', $param_value)) {
trigger_error("[plugin] invalid header format '" . $param_value . "'", E_USER_NOTICE);
return;
} else {
$extra_headers[] = $param_value;
@ -117,6 +121,7 @@ function smarty_function_fetch($params, $template)
$proxy_port = (int) $param_value;
} else {
trigger_error("[plugin] invalid value for attribute '" . $param_key . "'", E_USER_NOTICE);
return;
}
break;
@ -135,11 +140,13 @@ function smarty_function_fetch($params, $template)
$timeout = (int) $param_value;
} else {
trigger_error("[plugin] invalid value for attribute '" . $param_key . "'", E_USER_NOTICE);
return;
}
break;
default:
trigger_error("[plugin] unrecognized attribute '" . $param_key . "'", E_USER_NOTICE);
return;
}
}
@ -152,6 +159,7 @@ function smarty_function_fetch($params, $template)
if (!$fp) {
trigger_error("[plugin] unable to fetch: $errstr ($errno)", E_USER_NOTICE);
return;
} else {
if ($_is_proxy) {
@ -195,6 +203,7 @@ function smarty_function_fetch($params, $template)
}
} else {
trigger_error("[plugin fetch] unable to parse URL, check syntax", E_USER_NOTICE);
return;
}
} else {
@ -210,5 +219,3 @@ function smarty_function_fetch($params, $template)
return $content;
}
}
?>

View file

@ -8,7 +8,6 @@
/**
* Smarty {html_checkboxes} function plugin
*
* File: function.html_checkboxes.php<br>
* Type: function<br>
* Name: html_checkboxes<br>
@ -37,8 +36,10 @@
* @author Christopher Kvarme <christopher.kvarme@flashjab.com>
* @author credits to Monte Ohrt <monte at ohrt dot com>
* @version 1.0
*
* @param array $params parameters
* @param object $template template object
*
* @return string
* @uses smarty_function_escape_special_chars()
*/
@ -116,6 +117,24 @@ function smarty_function_html_checkboxes($params, $template)
case 'assign':
break;
case 'strict':
break;
case 'disabled':
case 'readonly':
if (!empty($params['strict'])) {
if (!is_scalar($_val)) {
trigger_error("html_options: $_key attribute must be a scalar, only boolean true or string '$_key' will actually add the attribute", E_USER_NOTICE);
}
if ($_val === true || $_val === $_key) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_key) . '"';
}
break;
}
// omit break; to fall through!
default:
if (!is_array($_val)) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"';
@ -126,8 +145,9 @@ function smarty_function_html_checkboxes($params, $template)
}
}
if (!isset($options) && !isset($values))
return ''; /* raise error here? */
if (!isset($options) && !isset($values)) {
return '';
} /* raise error here? */
$_html_result = array();
@ -147,10 +167,10 @@ function smarty_function_html_checkboxes($params, $template)
} else {
return implode("\n", $_html_result);
}
}
function smarty_function_html_checkboxes_output($name, $value, $output, $selected, $extra, $separator, $labels, $label_ids, $escape=true) {
function smarty_function_html_checkboxes_output($name, $value, $output, $selected, $extra, $separator, $labels, $label_ids, $escape = true)
{
$_output = '';
if (is_object($value)) {
@ -158,6 +178,7 @@ function smarty_function_html_checkboxes_output($name, $value, $output, $selecte
$value = (string) $value->__toString();
} else {
trigger_error("html_options: value is an object of class '" . get_class($value) . "' without __toString() method", E_USER_NOTICE);
return '';
}
} else {
@ -169,6 +190,7 @@ function smarty_function_html_checkboxes_output($name, $value, $output, $selecte
$output = (string) $output->__toString();
} else {
trigger_error("html_options: output is an object of class '" . get_class($output) . "' without __toString() method", E_USER_NOTICE);
return '';
}
} else {
@ -210,7 +232,6 @@ function smarty_function_html_checkboxes_output($name, $value, $output, $selecte
}
$_output .= $separator;
return $_output;
}
?>

View file

@ -8,7 +8,6 @@
/**
* Smarty {html_image} function plugin
*
* Type: function<br>
* Name: html_image<br>
* Date: Feb 24, 2003<br>
@ -29,8 +28,11 @@
* @author Monte Ohrt <monte at ohrt dot com>
* @author credits to Duda <duda@big.hu>
* @version 1.0
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @throws SmartyException
* @return string
* @uses smarty_function_escape_special_chars()
*/
@ -84,6 +86,7 @@ function smarty_function_html_image($params, $template)
if (empty($file)) {
trigger_error("html_image: missing 'file' parameter", E_USER_NOTICE);
return;
}
@ -111,7 +114,7 @@ function smarty_function_html_image($params, $template)
}
} else {
// local file
if(!$template->smarty->security_policy->isTrustedResourceDir($params['file'])) {
if (!$template->smarty->security_policy->isTrustedResourceDir($_image_path)) {
return;
}
}
@ -122,12 +125,15 @@ function smarty_function_html_image($params, $template)
if (!$_image_data = @getimagesize($_image_path)) {
if (!file_exists($_image_path)) {
trigger_error("html_image: unable to find '$_image_path'", E_USER_NOTICE);
return;
} elseif (!is_readable($_image_path)) {
trigger_error("html_image: unable to read '$_image_path'", E_USER_NOTICE);
return;
} else {
trigger_error("html_image: '$_image_path' is not a valid image file", E_USER_NOTICE);
return;
}
}
@ -155,5 +161,3 @@ function smarty_function_html_image($params, $template)
return $prefix . '<img src="' . $path_prefix . $file . '" alt="' . $alt . '" width="' . $width . '" height="' . $height . '"' . $extra . ' />' . $suffix;
}
?>

View file

@ -8,7 +8,6 @@
/**
* Smarty {html_options} function plugin
*
* Type: function<br>
* Name: html_options<br>
* Purpose: Prints the list of <option> tags generated from
@ -28,12 +27,13 @@
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @author Ralf Strehle (minor optimization) <ralf dot strehle at yahoo dot de>
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @return string
* @uses smarty_function_escape_special_chars()
*/
function smarty_function_html_options($params, $template)
function smarty_function_html_options($params)
{
require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php');
@ -91,6 +91,24 @@ function smarty_function_html_options($params, $template)
}
break;
case 'strict':
break;
case 'disabled':
case 'readonly':
if (!empty($params['strict'])) {
if (!is_scalar($_val)) {
trigger_error("html_options: $_key attribute must be a scalar, only boolean true or string '$_key' will actually add the attribute", E_USER_NOTICE);
}
if ($_val === true || $_val === $_key) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_key) . '"';
}
break;
}
// omit break; to fall through!
default:
if (!is_array($_val)) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"';
@ -103,6 +121,7 @@ function smarty_function_html_options($params, $template)
if (!isset($options) && !isset($values)) {
/* raise error here? */
return '';
}
@ -148,6 +167,7 @@ function smarty_function_html_options_optoutput($key, $value, $selected, $id, $c
$value = smarty_function_escape_special_chars((string) $value->__toString());
} else {
trigger_error("html_options: value is an object of class '" . get_class($value) . "' without __toString() method", E_USER_NOTICE);
return '';
}
} else {
@ -160,6 +180,7 @@ function smarty_function_html_options_optoutput($key, $value, $selected, $id, $c
$_html_result = smarty_function_html_options_optgroup($key, $value, $selected, !empty($id) ? ($id . '-' . $idx) : null, $class, $_idx);
$idx ++;
}
return $_html_result;
}
@ -170,7 +191,6 @@ function smarty_function_html_options_optgroup($key, $values, $selected, $id, $c
$optgroup_html .= smarty_function_html_options_optoutput($key, $value, $selected, $id, $class, $idx);
}
$optgroup_html .= "</optgroup>\n";
return $optgroup_html;
}
?>

View file

@ -8,7 +8,6 @@
/**
* Smarty {html_radios} function plugin
*
* File: function.html_radios.php<br>
* Type: function<br>
* Name: html_radios<br>
@ -37,8 +36,10 @@
* @author Christopher Kvarme <christopher.kvarme@flashjab.com>
* @author credits to Monte Ohrt <monte at ohrt dot com>
* @version 1.0
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @return string
* @uses smarty_function_escape_special_chars()
*/
@ -102,6 +103,24 @@ function smarty_function_html_radios($params, $template)
case 'assign':
break;
case 'strict':
break;
case 'disabled':
case 'readonly':
if (!empty($params['strict'])) {
if (!is_scalar($_val)) {
trigger_error("html_options: $_key attribute must be a scalar, only boolean true or string '$_key' will actually add the attribute", E_USER_NOTICE);
}
if ($_val === true || $_val === $_key) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_key) . '"';
}
break;
}
// omit break; to fall through!
default:
if (!is_array($_val)) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"';
@ -114,6 +133,7 @@ function smarty_function_html_radios($params, $template)
if (!isset($options) && !isset($values)) {
/* raise error here? */
return '';
}
@ -146,6 +166,7 @@ function smarty_function_html_radios_output($name, $value, $output, $selected, $
$value = (string) $value->__toString();
} else {
trigger_error("html_options: value is an object of class '" . get_class($value) . "' without __toString() method", E_USER_NOTICE);
return '';
}
} else {
@ -157,6 +178,7 @@ function smarty_function_html_radios_output($name, $value, $output, $selected, $
$output = (string) $output->__toString();
} else {
trigger_error("html_options: output is an object of class '" . get_class($output) . "' without __toString() method", E_USER_NOTICE);
return '';
}
} else {
@ -194,7 +216,6 @@ function smarty_function_html_radios_output($name, $value, $output, $selected, $
}
$_output .= $separator;
return $_output;
}
?>

View file

@ -17,11 +17,9 @@ require_once(SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php');
/**
* Smarty {html_select_date} plugin
*
* Type: function<br>
* Name: html_select_date<br>
* Purpose: Prints the dropdowns for date selection.
*
* ChangeLog:
* <pre>
* - 1.0 initial release
@ -47,11 +45,12 @@ require_once(SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php');
* @author Andrei Zmievski
* @author Monte Ohrt <monte at ohrt dot com>
* @author Rodney Rehm
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @return string
*/
function smarty_function_html_select_date($params, $template)
function smarty_function_html_select_date($params)
{
// generate timestamps used for month names only
static $_month_timestamps = null;
@ -187,7 +186,6 @@ function smarty_function_html_select_date($params, $template)
? $params['time'][$prefix . $_elementName]
: date($_elementKey);
}
$time = mktime(0, 0, 0, $_month, $_day, $_year);
} elseif (isset($params['time'][$field_array][$prefix . 'Year'])) {
// $_REQUEST given
foreach (array('Y' => 'Year', 'm' => 'Month', 'd' => 'Day') as $_elementKey => $_elementName) {
@ -196,7 +194,6 @@ function smarty_function_html_select_date($params, $template)
? $params['time'][$field_array][$prefix . $_elementName]
: date($_elementKey);
}
$time = mktime(0, 0, 0, $_month, $_day, $_year);
} else {
// no date found, use NOW
list($_year, $_month, $_day) = $time = explode('-', date('Y-m-d'));
@ -219,9 +216,9 @@ function smarty_function_html_select_date($params, $template)
if ($t === null) {
$$key = (int) $_current_year;
} elseif ($t[0] == '+') {
$$key = (int)($_current_year + trim(substr($t, 1)));
$$key = (int) ($_current_year + (int)trim(substr($t, 1)));
} elseif ($t[0] == '-') {
$$key = (int)($_current_year - trim(substr($t, 1)));
$$key = (int) ($_current_year - (int)trim(substr($t, 1)));
} else {
$$key = (int) $$key;
}
@ -236,7 +233,6 @@ function smarty_function_html_select_date($params, $template)
// generate year <select> or <input>
if ($display_years) {
$_html_years = '';
$_extra = '';
$_name = $field_array ? ($field_array . '[' . $prefix . 'Year]') : ($prefix . 'Year');
if ($all_extra) {
@ -277,7 +273,6 @@ function smarty_function_html_select_date($params, $template)
// generate month <select> or <input>
if ($display_months) {
$_html_month = '';
$_extra = '';
$_name = $field_array ? ($field_array . '[' . $prefix . 'Month]') : ($prefix . 'Month');
if ($all_extra) {
@ -316,7 +311,6 @@ function smarty_function_html_select_date($params, $template)
// generate day <select> or <input>
if ($display_days) {
$_html_day = '';
$_extra = '';
$_name = $field_array ? ($field_array . '[' . $prefix . 'Day]') : ($prefix . 'Day');
if ($all_extra) {
@ -388,7 +382,6 @@ function smarty_function_html_select_date($params, $template)
break;
}
}
return $_html;
}
?>

View file

@ -17,7 +17,6 @@ require_once(SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php');
/**
* Smarty {html_select_time} function plugin
*
* Type: function<br>
* Name: html_select_time<br>
* Purpose: Prints the dropdowns for time selection
@ -26,12 +25,13 @@ require_once(SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php');
* (Smarty online manual)
* @author Roberto Berto <roberto@berto.net>
* @author Monte Ohrt <monte AT ohrt DOT com>
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @return string
* @uses smarty_make_timestamp()
*/
function smarty_function_html_select_time($params, $template)
function smarty_function_html_select_time($params)
{
$prefix = "Time_";
$field_array = null;
@ -345,7 +345,7 @@ function smarty_function_html_select_time($params, $template)
$_html_meridian .= '<option value="">' . (isset($meridian_empty) ? $meridian_empty : $all_empty) . '</option>' . $option_separator;
}
$_html_meridian .= '<option value="am"'. ($_hour < 12 ? ' selected="selected"' : '') .'>AM</option>' . $option_separator
$_html_meridian .= '<option value="am"' . ($_hour > 0 && $_hour < 12 ? ' selected="selected"' : '') . '>AM</option>' . $option_separator
. '<option value="pm"' . ($_hour < 12 ? '' : ' selected="selected"') . '>PM</option>' . $option_separator
. '</select>';
}
@ -362,5 +362,3 @@ function smarty_function_html_select_time($params, $template)
return $_html;
}
?>

View file

@ -8,7 +8,6 @@
/**
* Smarty {html_table} function plugin
*
* Type: function<br>
* Name: html_table<br>
* Date: Feb 17, 2003<br>
@ -43,11 +42,12 @@
* @version 1.1
* @link http://www.smarty.net/manual/en/language.function.html.table.php {html_table}
* (Smarty online manual)
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @return string
*/
function smarty_function_html_table($params, $template)
function smarty_function_html_table($params)
{
$table_attr = 'border="1"';
$tr_attr = '';
@ -64,6 +64,7 @@ function smarty_function_html_table($params, $template)
if (!isset($params['loop'])) {
trigger_error("html_table: missing 'loop' parameter", E_USER_WARNING);
return;
}
@ -173,5 +174,3 @@ function smarty_function_html_table_cycle($name, $var, $no)
return ($ret) ? ' ' . $ret : '';
}
?>

View file

@ -8,7 +8,6 @@
/**
* Smarty {mailto} function plugin
*
* Type: function<br>
* Name: mailto<br>
* Date: May 21, 2002
@ -44,17 +43,19 @@
* @version 1.2
* @author Monte Ohrt <monte at ohrt dot com>
* @author credits to Jason Sweat (added cc, bcc and subject functionality)
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @return string
*/
function smarty_function_mailto($params, $template)
function smarty_function_mailto($params)
{
static $_allowed_encoding = array('javascript' => true, 'javascript_charcode' => true, 'hex' => true, 'none' => true);
$extra = '';
if (empty($params['address'])) {
trigger_error("mailto: missing 'address' parameter", E_USER_WARNING);
return;
} else {
$address = $params['address'];
@ -71,8 +72,9 @@ function smarty_function_mailto($params, $template)
case 'cc':
case 'bcc':
case 'followupto':
if (!empty($value))
if (!empty($value)) {
$mail_parms[] = $var . '=' . str_replace($search, $replace, rawurlencode($value));
}
break;
case 'subject':
@ -95,6 +97,7 @@ function smarty_function_mailto($params, $template)
$encode = (empty($params['encode'])) ? 'none' : $params['encode'];
if (!isset($_allowed_encoding[$encode])) {
trigger_error("mailto: 'encode' parameter must be none, javascript, javascript_charcode or hex", E_USER_WARNING);
return;
}
// FIXME: (rodneyrehm) document.write() excues me what? 1998 has passed!
@ -126,6 +129,7 @@ function smarty_function_mailto($params, $template)
preg_match('!^(.*)(\?.*)$!', $address, $match);
if (!empty($match[2])) {
trigger_error("mailto: hex encoding does not work with extra attributes. Try javascript.", E_USER_WARNING);
return;
}
$address_encode = '';
@ -142,11 +146,10 @@ function smarty_function_mailto($params, $template)
}
$mailto = "&#109;&#97;&#105;&#108;&#116;&#111;&#58;";
return '<a href="' . $mailto . $address_encode . '" ' . $extra . '>' . $text_encode . '</a>';
} else {
// no encoding
return '<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>';
}
}
?>

View file

@ -1,15 +1,14 @@
<?php
/**
* Smarty plugin
*
* This plugin is only for Smarty2 BC
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {math} function plugin
*
* Type: function<br>
* Name: math<br>
* Purpose: handle math computations in template
@ -17,8 +16,10 @@
* @link http://www.smarty.net/manual/en/language.function.math.php {math}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @return string|null
*/
function smarty_function_math($params, $template)
@ -31,6 +32,7 @@ function smarty_function_math($params, $template)
// be sure equation parameter is present
if (empty($params['equation'])) {
trigger_error("math: missing equation parameter", E_USER_WARNING);
return;
}
@ -39,6 +41,7 @@ function smarty_function_math($params, $template)
// make sure parenthesis are balanced
if (substr_count($equation, "(") != substr_count($equation, ")")) {
trigger_error("math: unbalanced parenthesis", E_USER_WARNING);
return;
}
@ -48,6 +51,7 @@ function smarty_function_math($params, $template)
foreach ($match[1] as $curr_var) {
if ($curr_var && !isset($params[$curr_var]) && !isset($_allowed_funcs[$curr_var])) {
trigger_error("math: function call $curr_var not allowed", E_USER_WARNING);
return;
}
}
@ -57,10 +61,12 @@ function smarty_function_math($params, $template)
// make sure value is not empty
if (strlen($val) == 0) {
trigger_error("math: parameter $key is empty", E_USER_WARNING);
return;
}
if (!is_numeric($val)) {
trigger_error("math: parameter $key: is not numeric", E_USER_WARNING);
return;
}
$equation = preg_replace("/\b$key\b/", " \$params['$key'] ", $equation);
@ -83,5 +89,3 @@ function smarty_function_math($params, $template)
}
}
}
?>

View file

@ -8,16 +8,15 @@
/**
* Smarty capitalize modifier plugin
*
* Type: modifier<br>
* Name: capitalize<br>
* Purpose: capitalize words in the string
*
* {@internal {$string|capitalize:true:true} is the fastest option for MBString enabled systems }}
*
* @param string $string string to capitalize
* @param boolean $uc_digits also capitalize "x123" to "X123"
* @param boolean $lc_rest capitalize first letters, lowercase all following letters "aAa" to "Aaa"
*
* @return string capitalized string
* @author Monte Ohrt <monte at ohrt dot com>
* @author Rodney Rehm
@ -30,7 +29,7 @@ function smarty_modifier_capitalize($string, $uc_digits = false, $lc_rest = fals
$upper_string = mb_convert_case($string, MB_CASE_TITLE, Smarty::$_CHARSET);
} else {
// uppercase word breaks
$upper_string = preg_replace("!(^|[^\p{L}'])([\p{Ll}])!eS" . Smarty::$_UTF8_MODIFIER, "stripslashes('\\1').mb_convert_case(stripslashes('\\2'),MB_CASE_UPPER, '" . addslashes(Smarty::$_CHARSET) . "')", $string);
$upper_string = preg_replace_callback("!(^|[^\p{L}'])([\p{Ll}])!S" . Smarty::$_UTF8_MODIFIER, 'smarty_mod_cap_mbconvert_cb', $string);
}
// check uc_digits case
if (!$uc_digits) {
@ -40,7 +39,7 @@ function smarty_modifier_capitalize($string, $uc_digits = false, $lc_rest = fals
}
}
}
$upper_string = preg_replace("!((^|\s)['\"])(\w)!e" . Smarty::$_UTF8_MODIFIER, "stripslashes('\\1').mb_convert_case(stripslashes('\\3'),MB_CASE_UPPER, '" . addslashes(Smarty::$_CHARSET) . "')", $upper_string);
$upper_string = preg_replace_callback("!((^|\s)['\"])(\w)!" . Smarty::$_UTF8_MODIFIER, 'smarty_mod_cap_mbconvert2_cb', $upper_string);
return $upper_string;
}
@ -49,7 +48,7 @@ function smarty_modifier_capitalize($string, $uc_digits = false, $lc_rest = fals
$string = strtolower($string);
}
// uppercase (including hyphenated words)
$upper_string = preg_replace("!(^|[^\p{L}'])([\p{Ll}])!eS" . Smarty::$_UTF8_MODIFIER, "stripslashes('\\1').ucfirst(stripslashes('\\2'))", $string);
$upper_string = preg_replace_callback("!(^|[^\p{L}'])([\p{Ll}])!S" . Smarty::$_UTF8_MODIFIER, 'smarty_mod_cap_ucfirst_cb', $string);
// check uc_digits case
if (!$uc_digits) {
if (preg_match_all("!\b([\p{L}]*[\p{N}]+[\p{L}]*)\b!" . Smarty::$_UTF8_MODIFIER, $string, $matches, PREG_OFFSET_CAPTURE)) {
@ -58,8 +57,34 @@ function smarty_modifier_capitalize($string, $uc_digits = false, $lc_rest = fals
}
}
}
$upper_string = preg_replace("!((^|\s)['\"])(\w)!e" . Smarty::$_UTF8_MODIFIER, "stripslashes('\\1').strtoupper(stripslashes('\\3'))", $upper_string);
$upper_string = preg_replace_callback("!((^|\s)['\"])(\w)!" . Smarty::$_UTF8_MODIFIER, 'smarty_mod_cap_ucfirst2_cb', $upper_string);
return $upper_string;
}
?>
/*
*
* Bug: create_function() use exhausts memory when used in long loops
* Fix: use declared functions for callbacks instead of using create_function()
* Note: This can be fixed using anonymous functions instead, but that requires PHP >= 5.3
*
* @author Kyle Renfrow
*/
function smarty_mod_cap_mbconvert_cb($matches)
{
return stripslashes($matches[1]) . mb_convert_case(stripslashes($matches[2]), MB_CASE_UPPER, Smarty::$_CHARSET);
}
function smarty_mod_cap_mbconvert2_cb($matches)
{
return stripslashes($matches[1]) . mb_convert_case(stripslashes($matches[3]), MB_CASE_UPPER, Smarty::$_CHARSET);
}
function smarty_mod_cap_ucfirst_cb($matches)
{
return stripslashes($matches[1]) . ucfirst(stripslashes($matches[2]));
}
function smarty_mod_cap_ucfirst2_cb($matches)
{
return stripslashes($matches[1]) . ucfirst(stripslashes($matches[3]));
}

View file

@ -8,7 +8,6 @@
/**
* Smarty date_format modifier plugin
*
* Type: modifier<br>
* Name: date_format<br>
* Purpose: format datestamps via strftime<br>
@ -19,10 +18,12 @@
*
* @link http://www.smarty.net/manual/en/language.modifier.date.format.php date_format (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string input date string
* @param string $format strftime format for output
* @param string $default_date default date if $string is empty
* @param string $formatter either 'strftime' or 'auto'
*
* @return string |void
* @uses smarty_make_timestamp()
*/
@ -56,10 +57,9 @@ function smarty_modifier_date_format($string, $format=null, $default_date='', $f
}
$format = str_replace($_win_from, $_win_to, $format);
}
return strftime($format, $timestamp);
} else {
return date($format, $timestamp);
}
}
?>

View file

@ -8,15 +8,16 @@
/**
* Smarty debug_print_var modifier plugin
*
* Type: modifier<br>
* Name: debug_print_var<br>
* Purpose: formats variable contents for display in the console
*
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param array|object $var variable to be formatted
* @param integer $depth maximum recursion depth if $var is an array
* @param integer $length maximum string length if $var is a string
*
* @return string
*/
function smarty_modifier_debug_print_var($var, $depth = 0, $length = 40)
@ -101,5 +102,3 @@ function smarty_modifier_debug_print_var ($var, $depth = 0, $length = 40)
return $results;
}
?>

View file

@ -8,17 +8,18 @@
/**
* Smarty escape modifier plugin
*
* Type: modifier<br>
* Name: escape<br>
* Purpose: escape string for output
*
* @link http://www.smarty.net/manual/en/language.modifier.count.characters.php count_characters (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string input string
* @param string $esc_type escape type
* @param string $char_set character set, used for htmlspecialchars() or htmlentities()
* @param boolean $double_encode encode already encoded entitites again, used for htmlspecialchars() or htmlentities()
*
* @return string escaped input string
*/
function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $double_encode = true)
@ -39,13 +40,14 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
return htmlspecialchars($string, ENT_QUOTES, $char_set, $double_encode);
} else {
if ($double_encode) {
// php <5.3.2 - only handle double encoding
// php <5.2.3 - only handle double encoding
return htmlspecialchars($string, ENT_QUOTES, $char_set);
} else {
// php <5.3.2 - prevent double encoding
// php <5.2.3 - prevent double encoding
$string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string);
$string = htmlspecialchars($string, ENT_QUOTES, $char_set);
$string = str_replace(array('%%%SMARTY_START%%%', '%%%SMARTY_END%%%'), array('&', ';'), $string);
return $string;
}
}
@ -58,13 +60,14 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
$string = htmlspecialchars($string, ENT_QUOTES, $char_set, $double_encode);
} else {
if ($double_encode) {
// php <5.3.2 - only handle double encoding
// php <5.2.3 - only handle double encoding
$string = htmlspecialchars($string, ENT_QUOTES, $char_set);
} else {
// php <5.3.2 - prevent double encoding
// php <5.2.3 - prevent double encoding
$string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string);
$string = htmlspecialchars($string, ENT_QUOTES, $char_set);
$string = str_replace(array('%%%SMARTY_START%%%', '%%%SMARTY_END%%%'), array('&', ';'), $string);
return $string;
}
}
@ -83,6 +86,7 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
$string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string);
$string = htmlentities($string, ENT_QUOTES, $char_set);
$string = str_replace(array('%%%SMARTY_START%%%', '%%%SMARTY_END%%%'), array('&', ';'), $string);
return $string;
}
}
@ -105,6 +109,7 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
for ($x = 0; $x < $_length; $x ++) {
$return .= '%' . bin2hex($string[$x]);
}
return $return;
case 'hexentity':
@ -115,6 +120,7 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
foreach (smarty_mb_to_unicode($string, Smarty::$_CHARSET) as $unicode) {
$return .= '&#x' . strtoupper(dechex($unicode)) . ';';
}
return $return;
}
// no MBString fallback
@ -122,6 +128,7 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
for ($x = 0; $x < $_length; $x ++) {
$return .= '&#x' . bin2hex($string[$x]) . ';';
}
return $return;
case 'decentity':
@ -132,6 +139,7 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
foreach (smarty_mb_to_unicode($string, Smarty::$_CHARSET) as $unicode) {
$return .= '&#' . $unicode . ';';
}
return $return;
}
// no MBString fallback
@ -139,6 +147,7 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
for ($x = 0; $x < $_length; $x ++) {
$return .= '&#' . ord($string[$x]) . ';';
}
return $return;
case 'javascript':
@ -148,6 +157,7 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
case 'mail':
if (Smarty::$_MBSTRING) {
require_once(SMARTY_PLUGINS_DIR . 'shared.mb_str_replace.php');
return smarty_mb_str_replace(array('@', '.'), array(' [AT] ', ' [DOT] '), $string);
}
// no MBString fallback
@ -165,6 +175,7 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
$return .= chr($unicode);
}
}
return $return;
}
@ -178,11 +189,10 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
$return .= substr($string, $_i, 1);
}
}
return $return;
default:
return $string;
}
}
?>

View file

@ -8,7 +8,6 @@
/**
* Smarty regex_replace modifier plugin
*
* Type: modifier<br>
* Name: regex_replace<br>
* Purpose: regular expression search/replace
@ -16,9 +15,11 @@
* @link http://smarty.php.net/manual/en/language.modifier.regex.replace.php
* regex_replace (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string input string
* @param string|array $search regular expression(s) to search for
* @param string|array $replace string(s) that should be replaced
*
* @return string
*/
function smarty_modifier_regex_replace($string, $search, $replace)
@ -30,11 +31,13 @@ function smarty_modifier_regex_replace($string, $search, $replace)
} else {
$search = _smarty_regex_replace_check($search);
}
return preg_replace($search, $replace, $string);
}
/**
* @param string $search string(s) that should be replaced
*
* @return string
* @ignore
*/
@ -49,7 +52,6 @@ function _smarty_regex_replace_check($search)
if (preg_match('!([a-zA-Z\s]+)$!s', $search, $match) && (strpos($match[1], 'e') !== false)) {
$search = substr($search, 0, - strlen($match[1])) . preg_replace('![e\s]+!', '', $match[1]);
}
return $search;
}
?>

View file

@ -1,13 +1,13 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty replace modifier plugin
*
* Type: modifier<br>
* Name: replace<br>
* Purpose: simple search/replace
@ -15,19 +15,20 @@
* @link http://smarty.php.net/manual/en/language.modifier.replace.php replace (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @author Uwe Tews
*
* @param string $string input string
* @param string $search text to search for
* @param string $replace replacement text
*
* @return string
*/
function smarty_modifier_replace($string, $search, $replace)
{
if (Smarty::$_MBSTRING) {
require_once(SMARTY_PLUGINS_DIR . 'shared.mb_str_replace.php');
return smarty_mb_str_replace($search, $replace, $string);
}
return str_replace($search, $replace, $string);
}
?>

View file

@ -1,21 +1,23 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty spacify modifier plugin
*
* Type: modifier<br>
* Name: spacify<br>
* Purpose: add spaces between characters in a string
*
* @link http://smarty.php.net/manual/en/language.modifier.spacify.php spacify (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string input string
* @param string $spacify_char string to insert between characters.
*
* @return string
*/
function smarty_modifier_spacify($string, $spacify_char = ' ')
@ -23,5 +25,3 @@ function smarty_modifier_spacify($string, $spacify_char = ' ')
// well… what about charsets besides latin and UTF-8?
return implode($spacify_char, preg_split('//' . Smarty::$_UTF8_MODIFIER, $string, - 1, PREG_SPLIT_NO_EMPTY));
}
?>

View file

@ -8,7 +8,6 @@
/**
* Smarty truncate modifier plugin
*
* Type: modifier<br>
* Name: truncate<br>
* Purpose: Truncate a string to a certain length if necessary,
@ -17,16 +16,20 @@
*
* @link http://smarty.php.net/manual/en/language.modifier.truncate.php truncate (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string input string
* @param integer $length length of truncated text
* @param string $etc end string
* @param boolean $break_words truncate at word boundary
* @param boolean $middle truncate in the middle of text
*
* @return string truncated string
*/
function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false) {
if ($length == 0)
function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false)
{
if ($length == 0) {
return '';
}
if (Smarty::$_MBSTRING) {
if (mb_strlen($string, Smarty::$_CHARSET) > $length) {
@ -37,8 +40,10 @@ function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_wo
if (!$middle) {
return mb_substr($string, 0, $length, Smarty::$_CHARSET) . $etc;
}
return mb_substr($string, 0, $length / 2, Smarty::$_CHARSET) . $etc . mb_substr($string, - $length / 2, $length, Smarty::$_CHARSET);
}
return $string;
}
@ -51,9 +56,9 @@ function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_wo
if (!$middle) {
return substr($string, 0, $length) . $etc;
}
return substr($string, 0, $length / 2) . $etc . substr($string, - $length / 2);
}
return $string;
}
?>

View file

@ -8,7 +8,6 @@
/**
* Smarty cat modifier plugin
*
* Type: modifier<br>
* Name: cat<br>
* Date: Feb 24, 2003<br>
@ -19,12 +18,12 @@
* @link http://smarty.php.net/manual/en/language.modifier.cat.php cat
* (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_cat($params, $compiler)
function smarty_modifiercompiler_cat($params)
{
return '(' . implode(').(', $params) . ')';
}
?>

View file

@ -8,17 +8,18 @@
/**
* Smarty count_characters modifier plugin
*
* Type: modifier<br>
* Name: count_characteres<br>
* Purpose: count the number of characters in a text
*
* @link http://www.smarty.net/manual/en/language.modifier.count.characters.php count_characters (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_count_characters($params, $compiler)
function smarty_modifiercompiler_count_characters($params)
{
if (!isset($params[1]) || $params[1] != 'true') {
return 'preg_match_all(\'/[^\s]/' . Smarty::$_UTF8_MODIFIER . '\',' . $params[0] . ', $tmp)';
@ -29,5 +30,3 @@ function smarty_modifiercompiler_count_characters($params, $compiler)
// no MBString fallback
return 'strlen(' . $params[0] . ')';
}
?>

View file

@ -8,7 +8,6 @@
/**
* Smarty count_paragraphs modifier plugin
*
* Type: modifier<br>
* Name: count_paragraphs<br>
* Purpose: count the number of paragraphs in a text
@ -16,13 +15,13 @@
* @link http://www.smarty.net/manual/en/language.modifier.count.paragraphs.php
* count_paragraphs (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_count_paragraphs($params, $compiler)
function smarty_modifiercompiler_count_paragraphs($params)
{
// count \r or \n characters
return '(preg_match_all(\'#[\r\n]+#\', ' . $params[0] . ', $tmp)+1)';
}
?>

View file

@ -8,7 +8,6 @@
/**
* Smarty count_sentences modifier plugin
*
* Type: modifier<br>
* Name: count_sentences
* Purpose: count the number of sentences in a text
@ -16,13 +15,13 @@
* @link http://www.smarty.net/manual/en/language.modifier.count.paragraphs.php
* count_sentences (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_count_sentences($params, $compiler)
function smarty_modifiercompiler_count_sentences($params)
{
// find periods, question marks, exclamation marks with a word before but not after.
return 'preg_match_all("#\w[\.\?\!](\W|$)#S' . Smarty::$_UTF8_MODIFIER . '", ' . $params[0] . ', $tmp)';
}
?>

View file

@ -8,17 +8,18 @@
/**
* Smarty count_words modifier plugin
*
* Type: modifier<br>
* Name: count_words<br>
* Purpose: count the number of words in a text
*
* @link http://www.smarty.net/manual/en/language.modifier.count.words.php count_words (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_count_words($params, $compiler)
function smarty_modifiercompiler_count_words($params)
{
if (Smarty::$_MBSTRING) {
// return 'preg_match_all(\'#[\w\pL]+#' . Smarty::$_UTF8_MODIFIER . '\', ' . $params[0] . ', $tmp)';
@ -28,5 +29,3 @@ function smarty_modifiercompiler_count_words($params, $compiler)
// no MBString fallback
return 'str_word_count(' . $params[0] . ')';
}
?>

View file

@ -8,17 +8,18 @@
/**
* Smarty default modifier plugin
*
* Type: modifier<br>
* Name: default<br>
* Purpose: designate default value for empty variables
*
* @link http://www.smarty.net/manual/en/language.modifier.default.php default (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_default ($params, $compiler)
function smarty_modifiercompiler_default($params)
{
$output = $params[0];
if (!isset($params[1])) {
@ -29,7 +30,6 @@ function smarty_modifiercompiler_default ($params, $compiler)
foreach ($params as $param) {
$output = '(($tmp = @' . $output . ')===null||$tmp===\'\' ? ' . $param . ' : $tmp)';
}
return $output;
}
?>

View file

@ -13,14 +13,16 @@ require_once( SMARTY_PLUGINS_DIR .'shared.literal_compiler_param.php' );
/**
* Smarty escape modifier plugin
*
* Type: modifier<br>
* Name: escape<br>
* Purpose: escape string for output
*
* @link http://www.smarty.net/docsv2/en/language.modifier.escape count_characters (Smarty online manual)
* @author Rodney Rehm
*
* @param array $params parameters
* @param $compiler
*
* @return string with compiled code
*/
function smarty_modifiercompiler_escape($params, $compiler)
@ -57,7 +59,7 @@ function smarty_modifiercompiler_escape($params, $compiler)
case 'htmlall':
if (Smarty::$_MBSTRING) {
if ($_double_encode) {
// php >=5.3.2 - go native
// php >=5.2.3 - go native
return 'mb_convert_encoding(htmlspecialchars('
. $params[0] . ', ENT_QUOTES, '
. var_export($char_set, true) . ', '
@ -65,7 +67,7 @@ function smarty_modifiercompiler_escape($params, $compiler)
. '), "HTML-ENTITIES", '
. var_export($char_set, true) . ')';
} elseif ($double_encode) {
// php <5.3.2 - only handle double encoding
// php <5.2.3 - only handle double encoding
return 'mb_convert_encoding(htmlspecialchars('
. $params[0] . ', ENT_QUOTES, '
. var_export($char_set, true)
@ -78,13 +80,13 @@ function smarty_modifiercompiler_escape($params, $compiler)
// no MBString fallback
if ($_double_encode) {
// php >=5.3.2 - go native
// php >=5.2.3 - go native
return 'htmlentities('
. $params[0] . ', ENT_QUOTES, '
. var_export($char_set, true) . ', '
. var_export($double_encode, true) . ')';
} elseif ($double_encode) {
// php <5.3.2 - only handle double encoding
// php <5.2.3 - only handle double encoding
return 'htmlentities('
. $params[0] . ', ENT_QUOTES, '
. var_export($char_set, true) . ')';
@ -105,21 +107,20 @@ function smarty_modifiercompiler_escape($params, $compiler)
case 'javascript':
// escape quotes and backslashes, newlines, etc.
return 'strtr(' . $params[0] . ', array("\\\\" => "\\\\\\\\", "\'" => "\\\\\'", "\"" => "\\\\\"", "\\r" => "\\\\r", "\\n" => "\\\n", "</" => "<\/" ))';
}
} catch(SmartyException $e) {
}
catch (SmartyException $e) {
// pass through to regular plugin fallback
}
// could not optimize |escape call, so fallback to regular plugin
if ($compiler->tag_nocache | $compiler->nocache) {
if ($compiler->template->caching && ($compiler->tag_nocache | $compiler->nocache)) {
$compiler->template->required_plugins['nocache']['escape']['modifier']['file'] = SMARTY_PLUGINS_DIR . 'modifier.escape.php';
$compiler->template->required_plugins['nocache']['escape']['modifier']['function'] = 'smarty_modifier_escape';
} else {
$compiler->template->required_plugins['compiled']['escape']['modifier']['file'] = SMARTY_PLUGINS_DIR . 'modifier.escape.php';
$compiler->template->required_plugins['compiled']['escape']['modifier']['function'] = 'smarty_modifier_escape';
}
return 'smarty_modifier_escape(' . join(', ', $params) . ')';
}
?>

View file

@ -8,16 +8,17 @@
/**
* Smarty from_charset modifier plugin
*
* Type: modifier<br>
* Name: from_charset<br>
* Purpose: convert character encoding from $charset to internal encoding
*
* @author Rodney Rehm
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_from_charset($params, $compiler)
function smarty_modifiercompiler_from_charset($params)
{
if (!Smarty::$_MBSTRING) {
// FIXME: (rodneyrehm) shouldn't this throw an error?
@ -30,5 +31,3 @@ function smarty_modifiercompiler_from_charset($params, $compiler)
return 'mb_convert_encoding(' . $params[0] . ', "' . addslashes(Smarty::$_CHARSET) . '", ' . $params[1] . ')';
}
?>

View file

@ -1,24 +1,26 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty indent modifier plugin
*
* Type: modifier<br>
* Name: indent<br>
* Purpose: indent lines of text
*
* @link http://www.smarty.net/manual/en/language.modifier.indent.php indent (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_indent($params, $compiler)
function smarty_modifiercompiler_indent($params)
{
if (!isset($params[1])) {
$params[1] = 4;
@ -26,7 +28,6 @@ function smarty_modifiercompiler_indent($params, $compiler)
if (!isset($params[2])) {
$params[2] = "' '";
}
return 'preg_replace(\'!^!m\',str_repeat(' . $params[2] . ',' . $params[1] . '),' . $params[0] . ')';
}
?>

View file

@ -1,13 +1,13 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty lower modifier plugin
*
* Type: modifier<br>
* Name: lower<br>
* Purpose: convert string to lowercase
@ -15,11 +15,13 @@
* @link http://www.smarty.net/manual/en/language.modifier.lower.php lower (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_lower($params, $compiler)
function smarty_modifiercompiler_lower($params)
{
if (Smarty::$_MBSTRING) {
return 'mb_strtolower(' . $params[0] . ', \'' . addslashes(Smarty::$_CHARSET) . '\')';
@ -27,5 +29,3 @@ function smarty_modifiercompiler_lower($params, $compiler)
// no MBString fallback
return 'strtolower(' . $params[0] . ')';
}
?>

View file

@ -8,18 +8,14 @@
/**
* Smarty noprint modifier plugin
*
* Type: modifier<br>
* Name: noprint<br>
* Purpose: return an empty string
*
* @author Uwe Tews
* @param array $params parameters
* @return string with compiled code
*/
function smarty_modifiercompiler_noprint($params, $compiler)
function smarty_modifiercompiler_noprint()
{
return "''";
}
?>

View file

@ -8,19 +8,18 @@
/**
* Smarty string_format modifier plugin
*
* Type: modifier<br>
* Name: string_format<br>
* Purpose: format strings via sprintf
*
* @link http://www.smarty.net/manual/en/language.modifier.string.format.php string_format (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_string_format($params, $compiler)
function smarty_modifiercompiler_string_format($params)
{
return 'sprintf(' . $params[1] . ',' . $params[0] . ')';
}
?>

Some files were not shown because too many files have changed in this diff Show more