From c5cc2821311012a8a4385a304a043c4b41f2afbb Mon Sep 17 00:00:00 2001 From: brettp Date: Mon, 31 Aug 2009 19:05:21 +0000 Subject: All line endings are now Unix-style. git-svn-id: https://code.elgg.org/elgg/trunk@3451 36083f99-b078-4883-b0ff-0f9b5a30f544 --- CONTRIBUTORS.txt | 70 +- INSTALL.txt | 238 +- README.txt | 70 +- _css/css.php | 68 +- _css/js.php | 82 +- account/register.php | 54 +- actions/admin/plugins/disable.php | 4 +- actions/admin/plugins/disableall.php | 4 +- actions/admin/plugins/enable.php | 2 +- actions/admin/plugins/reorder.php | 98 +- actions/admin/site/update_basic.php | 190 +- actions/admin/user/ban.php | 12 +- actions/comments/add.php | 110 +- actions/comments/delete.php | 64 +- actions/email/save.php | 4 +- actions/friends/add.php | 72 +- actions/friends/addcollection.php | 92 +- actions/friends/deletecollection.php | 92 +- actions/friends/editcollection.php | 34 +- actions/friends/remove.php | 64 +- actions/login.php | 108 +- actions/logout.php | 44 +- actions/register.php | 62 +- actions/systemsettings/install.php | 234 +- actions/user/default_access.php | 8 +- actions/user/requestnewpassword.php | 20 +- actions/user/spotlight.php | 28 +- actions/useradd.php | 8 +- actions/usersettings/save.php | 38 +- actions/widgets/add.php | 80 +- actions/widgets/reorder.php | 58 +- actions/widgets/save.php | 68 +- admin/index.php | 36 +- admin/plugins.php | 6 +- admin/site.php | 46 +- admin/user.php | 88 +- dashboard/index.php | 60 +- dashboard/latest.php | 54 +- engine/handlers/action_handler.php | 38 +- engine/handlers/cron_handler.php | 2 +- engine/handlers/pagehandler.php | 48 +- engine/handlers/xml-rpc_handler.php | 2 +- engine/lib/access.php | 1324 ++--- engine/lib/activity.php | 302 +- engine/lib/admin.php | 348 +- engine/lib/api.php | 4 +- engine/lib/configuration.php | 266 +- engine/lib/database.php | 750 +-- engine/lib/elgglib.php | 20 +- engine/lib/entities.php | 5534 ++++++++++---------- engine/lib/extender.php | 100 +- engine/lib/input.php | 348 +- engine/lib/install.php | 100 +- engine/lib/languages.php | 312 +- engine/lib/metadata.php | 1820 +++---- engine/lib/metastrings.php | 40 +- engine/lib/notification.php | 846 +-- engine/lib/objects.php | 416 +- engine/lib/pagehandler.php | 230 +- engine/lib/pageowner.php | 306 +- engine/lib/pam.php | 24 +- engine/lib/plugins.php | 1384 ++--- engine/lib/query.php | 12 +- engine/lib/relationships.php | 316 +- engine/lib/river2.php | 596 +-- engine/lib/sessions.php | 384 +- engine/lib/sites.php | 140 +- engine/lib/social.php | 214 +- engine/lib/statistics.php | 4 +- engine/lib/tags.php | 322 +- engine/lib/upgrades/2008101303.php | 20 +- engine/lib/users.php | 3000 +++++------ engine/lib/version.php | 116 +- engine/lib/widgets.php | 1050 ++-- engine/settings.example.php | 208 +- engine/start.php | 432 +- entities/index.php | 130 +- entities/list.php | 36 +- friends/add.php | 50 +- friends/collections.php | 50 +- friends/edit.php | 72 +- friends/index.php | 46 +- friends/of.php | 46 +- friends/pickercallback.php | 116 +- index.php | 66 +- install.php | 70 +- languages/en.php | 2154 ++++---- mod/garbagecollector/languages/en.php | 2 +- mod/logbrowser/index.php | 126 +- mod/logbrowser/languages/en.php | 14 +- mod/logbrowser/start.php | 44 +- .../views/default/logbrowser/adminlinks.php | 6 +- mod/logbrowser/views/default/logbrowser/form.php | 130 +- mod/logbrowser/views/default/object/logwrapper.php | 94 +- mod/uservalidationbyemail/start.php | 4 +- settings/index.php | 22 +- simplecache/view.php | 124 +- upgrade.php | 20 +- vendors/calendarpopup/CalendarPopup.js | 2924 +++++------ vendors/jquery/jquery.form.js | 1286 ++--- version.php | 32 +- views/default/account/forms/login.php | 56 +- views/default/account/forms/register.php | 42 +- views/default/admin/main.php | 32 +- views/default/admin/plugins_opt/plugin.php | 64 +- views/default/admin/statistics.php | 24 +- views/default/admin/statistics_opt/numentities.php | 102 +- views/default/admin/statistics_opt/online.php | 40 +- views/default/admin/user_opt/search.php | 10 +- views/default/ajax/loader.php | 52 +- views/default/annotation/annotate.php | 46 +- views/default/annotation/generic_comment.php | 120 +- views/default/basic_elements/welcome.php | 32 +- views/default/canvas/default.php | 36 +- views/default/canvas/layouts/edit_layout.php | 34 +- views/default/canvas/layouts/sidebar_boxes.php | 60 +- views/default/canvas_header/submenu_group.php | 28 +- views/default/canvas_header/submenu_template.php | 30 +- views/default/comments/forms/edit.php | 44 +- views/default/dashboard/blurb.php | 22 +- views/default/embed/addcontentjs.php | 6 +- views/default/embed/js.php | 12 +- views/default/friends/collection.php | 114 +- views/default/friends/collections.php | 104 +- views/default/friends/collectiontabs.php | 96 +- views/default/friends/forms/collectionfields.php | 44 +- views/default/friends/forms/edit.php | 4 +- views/default/friends/list.php | 48 +- views/default/friends/picker.php | 652 +-- views/default/friends/river/create.php | 36 +- views/default/friends/tablelistcountupdate.php | 38 +- views/default/input/access.php | 108 +- views/default/input/calendar.php | 82 +- views/default/input/checkboxes.php | 84 +- views/default/input/email.php | 38 +- views/default/input/file.php | 42 +- views/default/input/longtext.php | 38 +- views/default/input/password.php | 38 +- views/default/input/plaintext.php | 44 +- views/default/input/pulldown.php | 70 +- views/default/input/radio.php | 62 +- views/default/input/tags.php | 78 +- views/default/input/text.php | 38 +- views/default/input/url.php | 38 +- views/default/js/friendsPickerv1.php | 186 +- views/default/js/initialise_elgg.php | 592 +-- views/default/js/upload_js.php | 112 +- views/default/messages/errors/error.php | 34 +- views/default/messages/errors/list.php | 112 +- views/default/messages/exceptions/exception.php | 30 +- views/default/messages/list.php | 44 +- views/default/messages/messages/list.php | 114 +- views/default/messages/messages/message.php | 34 +- views/default/navigation/viewtype.php | 62 +- .../notifications/settings/usersettings.php | 84 +- views/default/object/widget.php | 26 +- views/default/output/calendar.php | 26 +- views/default/output/checkboxes.php | 32 +- views/default/output/confirmlink.php | 54 +- views/default/output/date.php | 36 +- views/default/output/email.php | 36 +- views/default/output/longtext.php | 36 +- views/default/output/pulldown.php | 32 +- views/default/output/radio.php | 32 +- views/default/output/tagcloud.php | 98 +- views/default/output/tags.php | 104 +- views/default/output/text.php | 32 +- views/default/output/url.php | 46 +- views/default/page_elements/contentwrapper.php | 20 +- views/default/page_elements/header_contents.php | 44 +- views/default/page_elements/owner_block.php | 194 +- views/default/river/item/list.php | 100 +- views/default/river/item/noaccess.php | 8 +- views/default/river/item/wrapper.php | 74 +- views/default/river/wrapper.php | 20 +- views/default/settings/install.php | 32 +- views/default/settings/system.php | 138 +- views/default/settings/upgrading.php | 36 +- views/default/spotlight/default.php | 72 +- views/default/text/about.php | 28 +- views/default/text/privacy_view.php | 30 +- views/default/text/tos_view.php | 22 +- views/default/upload/upload_form_content.php | 230 +- views/default/user/default.php | 40 +- views/default/user/settings/default_access.php | 54 +- views/default/user/settings/email.php | 48 +- views/default/user/settings/name.php | 48 +- views/default/user/settings/password.php | 50 +- .../usersettings/statistics_opt/numentities.php | 100 +- views/default/welcome.php | 34 +- views/default/widgets/editwrapper.php | 74 +- views/default/widgets/wrapper.php | 224 +- views/failsafe/canvas/default.php | 36 +- views/failsafe/input/access.php | 100 +- views/failsafe/input/checkboxes.php | 78 +- views/failsafe/input/longtext.php | 38 +- views/failsafe/input/pulldown.php | 70 +- views/failsafe/input/text.php | 38 +- views/failsafe/messages/errors/error.php | 34 +- views/failsafe/messages/errors/list.php | 94 +- views/failsafe/messages/list.php | 44 +- views/failsafe/messages/messages/list.php | 100 +- views/failsafe/messages/messages/message.php | 34 +- views/failsafe/messages/sanitisation/htaccess.php | 22 +- views/failsafe/settings/install.php | 32 +- views/failsafe/settings/system.php | 126 +- views/foaf/canvas/default.php | 36 +- views/foaf/page_elements/contentwrapper.php | 8 +- views/foaf/pageshells/pageshell.php | 64 +- views/foaf/user/default.php | 46 +- views/js/object/default.php | 34 +- views/js/pageshells/pageshell.php | 48 +- views/js/user/default.php | 34 +- views/json/api/output.php | 6 +- views/json/canvas/default.php | 4 +- views/json/export/entity.php | 8 +- views/json/export/metadata.php | 4 +- views/json/export/relationship.php | 4 +- views/json/messages/exceptions/exception.php | 4 +- views/json/page_elements/contentwrapper.php | 8 +- views/json/pageshells/pageshell.php | 16 +- views/json/river/item/list.php | 96 +- views/opendd/messages/exceptions/exception.php | 32 +- views/rss/annotation/default.php | 54 +- views/rss/canvas/default.php | 36 +- views/rss/group/default.php | 40 +- views/rss/object/default.php | 56 +- views/rss/page_elements/contentwrapper.php | 8 +- views/rss/river/item/list.php | 82 +- views/rss/user/default.php | 40 +- views/xml/messages/exceptions/exception.php | 32 +- 231 files changed, 19830 insertions(+), 19830 deletions(-) diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt index af850a2b4..dc10fafaf 100644 --- a/CONTRIBUTORS.txt +++ b/CONTRIBUTORS.txt @@ -1,36 +1,36 @@ - -CONTRIBUTORS - -The core Elgg team: - -David Tosh -http://twitter.com/davetosh - -Marcus Povey -http://marcuspovey.co.uk/ -http://twitter.com/mapkyca - -Brett Profitt -http://twitter.com/brettprofitt - -Pete Harris - - -CONTRIBUTING/ALUMNI DEVELOPERS - -Kevin Jardine -http://radagast.biz/ - -Milan Magudia - -Ben Werdmuller -http://benwerd.com/ -http://twitter.com/benwerd - - -Thanks to the following developers for contributing patches and/or suggestions - -Diego Andrés Ramírez Aragón -Corporación Somos Más - + +CONTRIBUTORS + +The core Elgg team: + +David Tosh +http://twitter.com/davetosh + +Marcus Povey +http://marcuspovey.co.uk/ +http://twitter.com/mapkyca + +Brett Profitt +http://twitter.com/brettprofitt + +Pete Harris + + +CONTRIBUTING/ALUMNI DEVELOPERS + +Kevin Jardine +http://radagast.biz/ + +Milan Magudia + +Ben Werdmuller +http://benwerd.com/ +http://twitter.com/benwerd + + +Thanks to the following developers for contributing patches and/or suggestions + +Diego Andrés Ramírez Aragón +Corporación Somos Más + Cash Costello \ No newline at end of file diff --git a/INSTALL.txt b/INSTALL.txt index 2df994a87..b5a6e1e8b 100644 --- a/INSTALL.txt +++ b/INSTALL.txt @@ -1,120 +1,120 @@ - -ELGG INSTALLATION INSTRUCTIONS - -TECHNICAL REQUIREMENTS - -Elgg runs on a combination of the Apache web server, MySQL database -system and the PHP interpreted scripting language. This is the most -popular web server environment in the world. - -Due to Elgg's advanced functionality, there are some extra -configuration requirements: - - * The Apache web server needs to be installed with the following - modules: - o mod_rewrite - o PHP - * MySQL 5+ is needed for data storage - * PHP 5.2+ needs to be installed as an Apache module (not in CGI - mode or safe mode) with the following libraries: - o GD (for graphics processing, eg user icon rescaling) - o JSON (for API functionality) - -It is recommended that you increase the memory available to PHP -threads beyond the standard 8 or 12M, and increase the maximum -uploaded filesize (which defaults to 2M). In both cases, this can be -found in your php.ini. - - * The following PHP libraries are also recommended for some - plugins and extra functionality: - o mbstring (to allow emails to be sent with non-Latin - characters) - o SOAP - o DOM - - -INSTALLING ELGG - -Before you begin, make sure you have read Elgg's technical -requirements. If you discover problems after following these -instructions, check out the troubleshooting page at -[http://docs.elgg.org/wiki/Troubleshooting]. - - -1. Upload Elgg - -Unzip Elgg and upload it to your site's document root. - - -2. Create a data folder - -Elgg needs a special folder to store uploaded files, including -profile icons and photos. You will need to create this for it. - -We recommend that this folder is called data, and is stored outside -of your document root. For example, if Elgg is installed in -/home/elgg/html/, you might create it in /home/elgg/data. - -Once this folder has been created, you'll need to make sure Elgg has -permission to write to it. This shouldn't be a problem on Windows- -based servers, but if your server runs Linux or a UNIX variant, -you'll need to type something like: - -chmod 777 /home/elgg/data/ - -If you use a graphical client to upload files, you can usually set -this by right or shift-clicking on the folder and selecting -'properties'. - - -3. Create a database - -Using your database administration tool of choice (if you're unsure -about this, ask your system administrator), create a new database for -Elgg. Make sure you know the username and password necessary to -access this. - -4. Install your crontab (UNIX ONLY) - -Cron is a UNIX command which allows programs to be run at set -times of the day. - -If you want to take advantage of some of the maintenance -functions such as log rotation or garbage collection, you must -install a cron tab to trigger these events. - -We have provided an example crontab as /crontab.example. Edit this -with a text editor to provide the details of your site, rename it -to another filename (eg 'crontab.mine') and install it with the -following command: - - crontab crontab.mine - -Substitute your filename for 'crontab.mine'. - -5. Visit your Elgg site - -Once you've performed these steps, visit your Elgg site in your web -browser. Elgg will take you through the rest of the installation -process from there. - -A note on settings and .htaccess - -The Elgg installer will try and create two files for you: - - * engine/settings.php, which contains the database settings for - your installation - * .htaccess, which allows Elgg to generate dynamic URLs - -If these files can't be automatically generated, for example because -you don't have the correct directory permissions, Elgg will tell you -how to create them. If, for some reason, this won't work, you will -need to: - - * Copy engine/settings.example.php to engine/settings.php, open - it up in a text editor and fill in your database details - * Copy /htaccess_dist to /.htaccess - - -The latest version of this document is available at: + +ELGG INSTALLATION INSTRUCTIONS + +TECHNICAL REQUIREMENTS + +Elgg runs on a combination of the Apache web server, MySQL database +system and the PHP interpreted scripting language. This is the most +popular web server environment in the world. + +Due to Elgg's advanced functionality, there are some extra +configuration requirements: + + * The Apache web server needs to be installed with the following + modules: + o mod_rewrite + o PHP + * MySQL 5+ is needed for data storage + * PHP 5.2+ needs to be installed as an Apache module (not in CGI + mode or safe mode) with the following libraries: + o GD (for graphics processing, eg user icon rescaling) + o JSON (for API functionality) + +It is recommended that you increase the memory available to PHP +threads beyond the standard 8 or 12M, and increase the maximum +uploaded filesize (which defaults to 2M). In both cases, this can be +found in your php.ini. + + * The following PHP libraries are also recommended for some + plugins and extra functionality: + o mbstring (to allow emails to be sent with non-Latin + characters) + o SOAP + o DOM + + +INSTALLING ELGG + +Before you begin, make sure you have read Elgg's technical +requirements. If you discover problems after following these +instructions, check out the troubleshooting page at +[http://docs.elgg.org/wiki/Troubleshooting]. + + +1. Upload Elgg + +Unzip Elgg and upload it to your site's document root. + + +2. Create a data folder + +Elgg needs a special folder to store uploaded files, including +profile icons and photos. You will need to create this for it. + +We recommend that this folder is called data, and is stored outside +of your document root. For example, if Elgg is installed in +/home/elgg/html/, you might create it in /home/elgg/data. + +Once this folder has been created, you'll need to make sure Elgg has +permission to write to it. This shouldn't be a problem on Windows- +based servers, but if your server runs Linux or a UNIX variant, +you'll need to type something like: + +chmod 777 /home/elgg/data/ + +If you use a graphical client to upload files, you can usually set +this by right or shift-clicking on the folder and selecting +'properties'. + + +3. Create a database + +Using your database administration tool of choice (if you're unsure +about this, ask your system administrator), create a new database for +Elgg. Make sure you know the username and password necessary to +access this. + +4. Install your crontab (UNIX ONLY) + +Cron is a UNIX command which allows programs to be run at set +times of the day. + +If you want to take advantage of some of the maintenance +functions such as log rotation or garbage collection, you must +install a cron tab to trigger these events. + +We have provided an example crontab as /crontab.example. Edit this +with a text editor to provide the details of your site, rename it +to another filename (eg 'crontab.mine') and install it with the +following command: + + crontab crontab.mine + +Substitute your filename for 'crontab.mine'. + +5. Visit your Elgg site + +Once you've performed these steps, visit your Elgg site in your web +browser. Elgg will take you through the rest of the installation +process from there. + +A note on settings and .htaccess + +The Elgg installer will try and create two files for you: + + * engine/settings.php, which contains the database settings for + your installation + * .htaccess, which allows Elgg to generate dynamic URLs + +If these files can't be automatically generated, for example because +you don't have the correct directory permissions, Elgg will tell you +how to create them. If, for some reason, this won't work, you will +need to: + + * Copy engine/settings.example.php to engine/settings.php, open + it up in a text editor and fill in your database details + * Copy /htaccess_dist to /.htaccess + + +The latest version of this document is available at: [http://docs.elgg.org/wiki/Installation] \ No newline at end of file diff --git a/README.txt b/README.txt index b7196c842..4ae9a4358 100644 --- a/README.txt +++ b/README.txt @@ -1,35 +1,35 @@ -Elgg version 1.5 -Copyright (c) 2008-2009 Curverider Ltd - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. - -This program 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 General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA - - -ABOUT: - -See CONTRIBUTORS.txt for development credits. - -Elgg concept originally by: -Ben Werdmuller and David Tosh - -Commercial services: http://elgg.com/ - -The open source project site can be found at http://elgg.org/ - -Elgg 1.5 is released under the GNU Public License (GPL), which -is supplied in this distribution as LICENSE. - -For installation instructions, please see the INSTALL file. - +Elgg version 1.5 +Copyright (c) 2008-2009 Curverider Ltd + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 +USA + + +ABOUT: + +See CONTRIBUTORS.txt for development credits. + +Elgg concept originally by: +Ben Werdmuller and David Tosh + +Commercial services: http://elgg.com/ + +The open source project site can be found at http://elgg.org/ + +Elgg 1.5 is released under the GNU Public License (GPL), which +is supplied in this distribution as LICENSE. + +For installation instructions, please see the INSTALL file. + diff --git a/_css/css.php b/_css/css.php index 1cc3eb038..0db16d8a9 100644 --- a/_css/css.php +++ b/_css/css.php @@ -1,44 +1,44 @@ - \ No newline at end of file diff --git a/_css/js.php b/_css/js.php index 3839b76e4..89c748cab 100644 --- a/_css/js.php +++ b/_css/js.php @@ -1,44 +1,44 @@ - \ No newline at end of file diff --git a/account/register.php b/account/register.php index 350a770e9..be7f9892e 100644 --- a/account/register.php +++ b/account/register.php @@ -1,30 +1,30 @@ - $friend_guid, 'invitecode' => $invitecode))); - // Otherwise, forward to the index page - } else { - forward(); - } - + * @author Curverider Ltd + + * @link http://elgg.org/ + */ + + /** + * Start the Elgg engine + */ + require_once(dirname(dirname(__FILE__)) . "/engine/start.php"); + + $friend_guid = (int) get_input('friend_guid',0); + $invitecode = get_input('invitecode'); + + // If we're not logged in, display the registration page + if (!isloggedin()) { + page_draw(elgg_echo('register'), elgg_view("account/forms/register", array('friend_guid' => $friend_guid, 'invitecode' => $invitecode))); + // Otherwise, forward to the index page + } else { + forward(); + } + ?> \ No newline at end of file diff --git a/actions/admin/plugins/disable.php b/actions/admin/plugins/disable.php index 2241730ad..90825bc2f 100644 --- a/actions/admin/plugins/disable.php +++ b/actions/admin/plugins/disable.php @@ -29,9 +29,9 @@ else register_error(sprintf(elgg_echo('admin:plugins:disable:no'), $p)); } - + elgg_view_regenerate_simplecache(); - elgg_filepath_cache_reset(); + elgg_filepath_cache_reset(); forward($_SERVER['HTTP_REFERER']); exit; diff --git a/actions/admin/plugins/disableall.php b/actions/admin/plugins/disableall.php index 5d0be4ad6..672915bce 100644 --- a/actions/admin/plugins/disableall.php +++ b/actions/admin/plugins/disableall.php @@ -26,9 +26,9 @@ else register_error(sprintf(elgg_echo('admin:plugins:disable:no'), $p)); } - + elgg_view_regenerate_simplecache(); - elgg_filepath_cache_reset(); + elgg_filepath_cache_reset(); forward($_SERVER['HTTP_REFERER']); exit; diff --git a/actions/admin/plugins/enable.php b/actions/admin/plugins/enable.php index 26d7abaf4..890e6648e 100644 --- a/actions/admin/plugins/enable.php +++ b/actions/admin/plugins/enable.php @@ -29,7 +29,7 @@ else register_error(sprintf(elgg_echo('admin:plugins:enable:no'), $p)); } - + elgg_view_regenerate_simplecache(); elgg_filepath_cache_reset(); diff --git a/actions/admin/plugins/reorder.php b/actions/admin/plugins/reorder.php index 50409df95..36ba1f66d 100644 --- a/actions/admin/plugins/reorder.php +++ b/actions/admin/plugins/reorder.php @@ -1,54 +1,54 @@ - \ No newline at end of file diff --git a/actions/admin/site/update_basic.php b/actions/admin/site/update_basic.php index d56e1d296..31a6b401e 100644 --- a/actions/admin/site/update_basic.php +++ b/actions/admin/site/update_basic.php @@ -1,103 +1,103 @@ -description = get_input('sitedescription'); - $site->name = get_input('sitename'); - $site->email = get_input('siteemail'); - $site->url = get_input('wwwroot'); - - datalist_set('path',sanitise_filepath(get_input('path'))); - datalist_set('dataroot',sanitise_filepath(get_input('dataroot'))); - if (get_input('simplecache_enabled')) { - elgg_view_enable_simplecache(); - } else { - elgg_view_disable_simplecache(); + * @author Curverider Ltd + + * @link http://elgg.org/ + */ + + global $CONFIG; + + // block non-admin users + admin_gatekeeper(); + action_gatekeeper(); + + if (get_input('settings') == 'go') { + + if (datalist_get('default_site')) { + + $site = get_entity(datalist_get('default_site')); + if (!($site instanceof ElggSite)) + throw new InstallationException(elgg_echo('InvalidParameterException:NonElggSite')); + + $site->description = get_input('sitedescription'); + $site->name = get_input('sitename'); + $site->email = get_input('siteemail'); + $site->url = get_input('wwwroot'); + + datalist_set('path',sanitise_filepath(get_input('path'))); + datalist_set('dataroot',sanitise_filepath(get_input('dataroot'))); + if (get_input('simplecache_enabled')) { + elgg_view_enable_simplecache(); + } else { + elgg_view_disable_simplecache(); } if (get_input('viewpath_cache_enabled')) { elgg_enable_filepath_cache(); } else { elgg_disable_filepath_cache(); - } - - set_config('language', get_input('language'), $site->getGUID()); - - set_config('default_access', get_input('default_access'), $site->getGUID()); - - if (get_input('allow_user_default_access')) { - set_config('allow_user_default_access', 1, $site->getGUID()); - } else { - set_config('allow_user_default_access', 0, $site->getGUID()); - } - - set_config('view', get_input('view'), $site->getGUID()); - - $debug = get_input('debug'); - if ($debug) - set_config('debug', 1, $site->getGUID()); - else - unset_config('debug', $site->getGUID()); - - $https_login = get_input('https_login'); - if ($https_login) - set_config('https_login', 1, $site->getGUID()); - else - unset_config('https_login', $site->getGUID()); - - $usage = get_input('usage'); - if ($usage) - unset_config('ping_home', $site->getGUID()); - else - set_config('ping_home', 'disabled', $site->getGUID()); - - $api = get_input('api'); - if ($api) - unset_config('disable_api', $site->getGUID()); - else - set_config('disable_api', 'disabled', $site->getGUID()); - - // Now ping home - //if ((!isset($usage)) || ($usage!='disabled')) - //{ - // ping_home($site); - //} - - if ($site->save()) - system_message(elgg_echo("admin:configuration:success")); - else - register_error(elgg_echo("admin:configuration:fail")); - - //header("Location: {$CONFIG->wwwroot}admin/site/"); - forward($_SERVER['HTTP_REFERER']); - exit; - - } - - } - + } + + set_config('language', get_input('language'), $site->getGUID()); + + set_config('default_access', get_input('default_access'), $site->getGUID()); + + if (get_input('allow_user_default_access')) { + set_config('allow_user_default_access', 1, $site->getGUID()); + } else { + set_config('allow_user_default_access', 0, $site->getGUID()); + } + + set_config('view', get_input('view'), $site->getGUID()); + + $debug = get_input('debug'); + if ($debug) + set_config('debug', 1, $site->getGUID()); + else + unset_config('debug', $site->getGUID()); + + $https_login = get_input('https_login'); + if ($https_login) + set_config('https_login', 1, $site->getGUID()); + else + unset_config('https_login', $site->getGUID()); + + $usage = get_input('usage'); + if ($usage) + unset_config('ping_home', $site->getGUID()); + else + set_config('ping_home', 'disabled', $site->getGUID()); + + $api = get_input('api'); + if ($api) + unset_config('disable_api', $site->getGUID()); + else + set_config('disable_api', 'disabled', $site->getGUID()); + + // Now ping home + //if ((!isset($usage)) || ($usage!='disabled')) + //{ + // ping_home($site); + //} + + if ($site->save()) + system_message(elgg_echo("admin:configuration:success")); + else + register_error(elgg_echo("admin:configuration:fail")); + + //header("Location: {$CONFIG->wwwroot}admin/site/"); + forward($_SERVER['HTTP_REFERER']); + exit; + + } + + } + ?> \ No newline at end of file diff --git a/actions/admin/user/ban.php b/actions/admin/user/ban.php index 831513a29..1033ec00a 100644 --- a/actions/admin/user/ban.php +++ b/actions/admin/user/ban.php @@ -21,15 +21,15 @@ if ( ($obj instanceof ElggUser) && ($obj->canEdit())) { // Now actually disable it - if ($obj->ban('banned')) { - system_message(elgg_echo('admin:user:ban:yes')); + if ($obj->ban('banned')) { + system_message(elgg_echo('admin:user:ban:yes')); } else register_error(elgg_echo('admin:user:ban:no')); - } else { - $canedit = $obj->canEdit(); - $isinstance = ($obj instanceof ElggUser); - register_error(elgg_echo('admin:user:ban:no')); + } else { + $canedit = $obj->canEdit(); + $isinstance = ($obj instanceof ElggUser); + register_error(elgg_echo('admin:user:ban:no')); } forward('pg/admin/user/'); diff --git a/actions/comments/add.php b/actions/comments/add.php index b026c64f0..80478b9ad 100644 --- a/actions/comments/add.php +++ b/actions/comments/add.php @@ -1,58 +1,58 @@ - + /** + * Elgg add comment action + * + * @package Elgg + + * @author Curverider + + * @link http://elgg.org/ + */ + + // Make sure we're logged in; forward to the front page if not + gatekeeper(); + action_gatekeeper(); + + // Get input + $entity_guid = (int) get_input('entity_guid'); + $comment_text = get_input('generic_comment'); + + // Let's see if we can get an entity with the specified GUID + if ($entity = get_entity($entity_guid)) { + + // If posting the comment was successful, say so + if ($entity->annotate('generic_comment',$comment_text,$entity->access_id, $_SESSION['guid'])) { + + if ($entity->owner_guid != $_SESSION['user']->getGUID()) + notify_user($entity->owner_guid, $_SESSION['user']->getGUID(), elgg_echo('generic_comment:email:subject'), + sprintf( + elgg_echo('generic_comment:email:body'), + $entity->title, + $_SESSION['user']->name, + $comment_text, + $entity->getURL(), + $_SESSION['user']->name, + $_SESSION['user']->getURL() + ) + ); + + system_message(elgg_echo("generic_comment:posted")); + //add to river + add_to_river('annotation/annotate','comment',$_SESSION['user']->guid,$entity->guid); + + + } else { + register_error(elgg_echo("generic_comment:failure")); + } + + } else { + + register_error(elgg_echo("generic_comment:notfound")); + + } + + // Forward to the + forward($entity->getURL()); - * @link http://elgg.org/ - */ - - // Make sure we're logged in; forward to the front page if not - gatekeeper(); - action_gatekeeper(); - - // Get input - $entity_guid = (int) get_input('entity_guid'); - $comment_text = get_input('generic_comment'); - - // Let's see if we can get an entity with the specified GUID - if ($entity = get_entity($entity_guid)) { - - // If posting the comment was successful, say so - if ($entity->annotate('generic_comment',$comment_text,$entity->access_id, $_SESSION['guid'])) { - - if ($entity->owner_guid != $_SESSION['user']->getGUID()) - notify_user($entity->owner_guid, $_SESSION['user']->getGUID(), elgg_echo('generic_comment:email:subject'), - sprintf( - elgg_echo('generic_comment:email:body'), - $entity->title, - $_SESSION['user']->name, - $comment_text, - $entity->getURL(), - $_SESSION['user']->name, - $_SESSION['user']->getURL() - ) - ); - - system_message(elgg_echo("generic_comment:posted")); - //add to river - add_to_river('annotation/annotate','comment',$_SESSION['user']->guid,$entity->guid); - - - } else { - register_error(elgg_echo("generic_comment:failure")); - } - - } else { - - register_error(elgg_echo("generic_comment:notfound")); - - } - - // Forward to the - forward($entity->getURL()); - ?> \ No newline at end of file diff --git a/actions/comments/delete.php b/actions/comments/delete.php index 2d3b9b3fd..dc701973b 100644 --- a/actions/comments/delete.php +++ b/actions/comments/delete.php @@ -1,35 +1,35 @@ - + /** + * Elgg delete comment action + * + * @package Elgg + + * @author Curverider + + * @link http://elgg.org/ + */ + + // Ensure we're logged in + if (!isloggedin()) forward(); + + // Make sure we can get the comment in question + $annotation_id = (int) get_input('annotation_id'); + if ($comment = get_annotation($annotation_id)) { + + $entity = get_entity($comment->entity_guid); + + if ($comment->canEdit()) { + $comment->delete(); + system_message(elgg_echo("generic_comment:deleted")); + forward($entity->getURL()); + } + + } else { + $url = ""; + } + + register_error(elgg_echo("generic_comment:notdeleted")); + forward($entity->getURL()); - * @link http://elgg.org/ - */ - - // Ensure we're logged in - if (!isloggedin()) forward(); - - // Make sure we can get the comment in question - $annotation_id = (int) get_input('annotation_id'); - if ($comment = get_annotation($annotation_id)) { - - $entity = get_entity($comment->entity_guid); - - if ($comment->canEdit()) { - $comment->delete(); - system_message(elgg_echo("generic_comment:deleted")); - forward($entity->getURL()); - } - - } else { - $url = ""; - } - - register_error(elgg_echo("generic_comment:notdeleted")); - forward($entity->getURL()); - ?> \ No newline at end of file diff --git a/actions/email/save.php b/actions/email/save.php index 6c166242b..2d226552a 100644 --- a/actions/email/save.php +++ b/actions/email/save.php @@ -29,7 +29,7 @@ if (!get_user_by_email($email)) { - + if ($user->email != $email) { $user->email = $email; if ($user->save()) @@ -38,7 +38,7 @@ system_message(elgg_echo('email:save:success')); } else - register_error(elgg_echo('email:save:fail')); + register_error(elgg_echo('email:save:fail')); } } else diff --git a/actions/friends/add.php b/actions/friends/add.php index 004b0eaad..63f1e2d94 100644 --- a/actions/friends/add.php +++ b/actions/friends/add.php @@ -1,40 +1,40 @@ -addFriend($friend_guid)) $errors = true; - } catch (Exception $e) { - register_error(sprintf(elgg_echo("friends:add:failure"),$friend->name)); - $errors = true; - } - if (!$errors){ - // add to river - add_to_river('friends/river/create','friend',$_SESSION['user']->guid,$friend_guid); - system_message(sprintf(elgg_echo("friends:add:successful"),$friend->name)); - } - - // Forward to the user friends page - forward("pg/friends/" . $_SESSION['user']->username . "/"); - + action_gatekeeper(); + + // Get the GUID of the user to friend + $friend_guid = get_input('friend'); + $friend = get_entity($friend_guid); + + $errors = false; + + // Get the user + try { + if (!$_SESSION['user']->addFriend($friend_guid)) $errors = true; + } catch (Exception $e) { + register_error(sprintf(elgg_echo("friends:add:failure"),$friend->name)); + $errors = true; + } + if (!$errors){ + // add to river + add_to_river('friends/river/create','friend',$_SESSION['user']->guid,$friend_guid); + system_message(sprintf(elgg_echo("friends:add:successful"),$friend->name)); + } + + // Forward to the user friends page + forward("pg/friends/" . $_SESSION['user']->username . "/"); + ?> \ No newline at end of file diff --git a/actions/friends/addcollection.php b/actions/friends/addcollection.php index bda98984b..7dfba1ee7 100644 --- a/actions/friends/addcollection.php +++ b/actions/friends/addcollection.php @@ -1,50 +1,50 @@ -getGUID()); - - //if the collection was created and the user passed some friends from the form, add them - if($create_collection && (!empty($friends))){ - - //add friends to the collection - foreach($friends as $friend){ - add_user_to_access_collection($friend, $create_collection); - } - - } - - // Success message - system_message(elgg_echo("friends:collectionadded")); - // Forward to the collections page - forward("pg/collections/" . $_SESSION['user']->username); - - } else { - - register_error(elgg_echo("friends:nocollectionname")); - // Forward to the add collection page - forward("pg/collections/add"); - - } - + action_gatekeeper(); + + $collection_name = get_input('collection_name'); + $friends = get_input('friends_collection'); + + //first check to make sure that a collection name has been set and create the new colection + if($collection_name){ + + //create the collection + $create_collection = create_access_collection($collection_name, $_SESSION['user']->getGUID()); + + //if the collection was created and the user passed some friends from the form, add them + if($create_collection && (!empty($friends))){ + + //add friends to the collection + foreach($friends as $friend){ + add_user_to_access_collection($friend, $create_collection); + } + + } + + // Success message + system_message(elgg_echo("friends:collectionadded")); + // Forward to the collections page + forward("pg/collections/" . $_SESSION['user']->username); + + } else { + + register_error(elgg_echo("friends:nocollectionname")); + // Forward to the add collection page + forward("pg/collections/add"); + + } + ?> \ No newline at end of file diff --git a/actions/friends/deletecollection.php b/actions/friends/deletecollection.php index 674e68751..bdfcc9b2c 100644 --- a/actions/friends/deletecollection.php +++ b/actions/friends/deletecollection.php @@ -1,52 +1,52 @@ -owner_guid == $_SESSION['user']->getGUID()){ - - $delete_collection = delete_access_collection($collection_id); - - // Success message + * @author Curverider Ltd + + * @link http://elgg.org/ + */ + + // Make sure we're logged in (send us to the front page if not) + gatekeeper(); + + // Get input data + $collection_id = (int) get_input('collection'); + + // Check to see that the access collection exist and grab its owner + $get_collection = get_access_collection($collection_id); + + if($get_collection){ + + if($get_collection->owner_guid == $_SESSION['user']->getGUID()){ + + $delete_collection = delete_access_collection($collection_id); + + // Success message if ($delete_collection) system_message(elgg_echo("friends:collectiondeleted")); else - register_error(elgg_echo("friends:collectiondeletefailed")); - - } else { - - // Failure message - register_error(elgg_echo("friends:collectiondeletefailed")); - - } - - } else { - - // Failure message - register_error(elgg_echo("friends:collectiondeletefailed")); - - } - - // Forward to the collections page - forward("pg/collections/" . $_SESSION['user']->username); - + register_error(elgg_echo("friends:collectiondeletefailed")); + + } else { + + // Failure message + register_error(elgg_echo("friends:collectiondeletefailed")); + + } + + } else { + + // Failure message + register_error(elgg_echo("friends:collectiondeletefailed")); + + } + + // Forward to the collections page + forward("pg/collections/" . $_SESSION['user']->username); + ?> \ No newline at end of file diff --git a/actions/friends/editcollection.php b/actions/friends/editcollection.php index a1a38845f..ede61b4b0 100644 --- a/actions/friends/editcollection.php +++ b/actions/friends/editcollection.php @@ -1,20 +1,20 @@ - \ No newline at end of file diff --git a/actions/friends/remove.php b/actions/friends/remove.php index d1911bb90..20181bc84 100644 --- a/actions/friends/remove.php +++ b/actions/friends/remove.php @@ -1,42 +1,42 @@ -removeFriend($friend_guid); else { register_error(sprintf(elgg_echo("friends:remove:failure"),$friend->name)); $errors = true; - } - } catch (Exception $e) { - register_error(sprintf(elgg_echo("friends:remove:failure"),$friend->name)); - $errors = true; - } - if (!$errors) - system_message(sprintf(elgg_echo("friends:remove:successful"),$friend->name)); - - // Forward to the user friends page - forward("pg/friends/" . $_SESSION['user']->username . "/"); - + } + } catch (Exception $e) { + register_error(sprintf(elgg_echo("friends:remove:failure"),$friend->name)); + $errors = true; + } + if (!$errors) + system_message(sprintf(elgg_echo("friends:remove:successful"),$friend->name)); + + // Forward to the user friends page + forward("pg/friends/" . $_SESSION['user']->username . "/"); + ?> \ No newline at end of file diff --git a/actions/login.php b/actions/login.php index 1d2b7bc07..f3a60af6d 100644 --- a/actions/login.php +++ b/actions/login.php @@ -1,37 +1,37 @@ -validated) { - // give plugins a chance to respond - if (!trigger_plugin_hook('unvalidated_login_attempt','user',array('entity'=>$user))) { - // if plugins have not registered an action, the default action is to - // trigger the validation event again and assume that the validation - // event will display an appropriate message - trigger_elgg_event('validate', 'user', $user); - } - } else { - register_error(elgg_echo('loginerror')); - } - access_show_hidden_entities($access_status); - } else { - register_error(elgg_echo('loginerror')); - } - } - + } + } else { + $error_msg = elgg_echo('loginerror'); + // figure out why the login failed + if (!empty($username) && !empty($password)) { + // See if it exists and is disabled + $access_status = access_get_show_hidden_status(); + access_show_hidden_entities(true); + if (($user = get_user_by_username($username)) && !$user->validated) { + // give plugins a chance to respond + if (!trigger_plugin_hook('unvalidated_login_attempt','user',array('entity'=>$user))) { + // if plugins have not registered an action, the default action is to + // trigger the validation event again and assume that the validation + // event will display an appropriate message + trigger_elgg_event('validate', 'user', $user); + } + } else { + register_error(elgg_echo('loginerror')); + } + access_show_hidden_entities($access_status); + } else { + register_error(elgg_echo('loginerror')); + } + } + ?> \ No newline at end of file diff --git a/actions/logout.php b/actions/logout.php index 078e5a7aa..67ca6ad65 100644 --- a/actions/logout.php +++ b/actions/logout.php @@ -1,25 +1,25 @@ - \ No newline at end of file diff --git a/actions/register.php b/actions/register.php index 75721822c..5c69624b3 100644 --- a/actions/register.php +++ b/actions/register.php @@ -1,39 +1,39 @@ -disable_registration) - { + { // For now, just try and register the user - try { + try { if ( ( (trim($password)!="") && @@ -49,21 +49,21 @@ $new_user->admin = 'yes'; } - // Send user validation request on register only - global $registering_admin; + // Send user validation request on register only + global $registering_admin; if (!$registering_admin) request_user_validation($guid); if (!$new_user->admin) - $new_user->disable('new_user', false); // Now disable if not an admin - // Don't do a recursive disable. Any entities owned by the user at this point + $new_user->disable('new_user', false); // Now disable if not an admin + // Don't do a recursive disable. Any entities owned by the user at this point // are products of plugins that - + system_message(sprintf(elgg_echo("registerok"),$CONFIG->sitename)); - forward(); // Forward on success, assume everything else is an error... - } else { - register_error(elgg_echo("registerbad")); + forward(); // Forward on success, assume everything else is an error... + } else { + register_error(elgg_echo("registerbad")); } } catch (RegistrationException $r) { register_error($r->getMessage()); @@ -76,6 +76,6 @@ $qs = $qs[0]; $qs .= "?u=" . urlencode($username) . "&e=" . urlencode($email) . "&n=" . urlencode($name) . "&friend_guid=" . $friend_guid; - forward($qs); - + forward($qs); + ?> \ No newline at end of file diff --git a/actions/systemsettings/install.php b/actions/systemsettings/install.php index 1d9f63a9f..8b0a31ced 100644 --- a/actions/systemsettings/install.php +++ b/actions/systemsettings/install.php @@ -1,125 +1,125 @@ -name = get_input('sitename'); - $site->url = get_input('wwwroot'); - $site->description = get_input('sitedescription'); - $site->email = get_input('siteemail'); - $site->access_id = ACCESS_PUBLIC; - $guid = $site->save(); - - if (!$guid) - throw new InstallationException(sprintf(elgg_echo('InstallationException:CantCreateSite'), get_input('sitename'), get_input('wwwroot'))); - - datalist_set('installed',time()); - - datalist_set('path', $path); - datalist_set('dataroot', $dataroot); - - datalist_set('default_site',$site->getGUID()); - - set_config('view', get_input('view'), $site->getGUID()); - set_config('language', get_input('language'), $site->getGUID()); - set_config('default_access', get_input('default_access'), $site->getGUID()); - - $debug = get_input('debug'); - if ($debug) - set_config('debug', 1, $site->getGUID()); - else - unset_config('debug', $site->getGUID()); - - $usage = get_input('usage'); - if (is_array($usage)) $usage = $usage[0]; - - if ($usage) - unset_config('ping_home', $site->getGUID()); - else - set_config('ping_home', 'disabled', $site->getGUID()); - - $api = get_input('api'); - if ($api) - unset_config('disable_api', $site->getGUID()); - else - set_config('disable_api', 'disabled', $site->getGUID()); - - $https_login = get_input('https_login'); - if ($https_login) - set_config('https_login', 1, $site->getGUID()); - else - unset_config('https_login', $site->getGUID()); - - // activate some plugins by default - if (isset($CONFIG->default_plugins)) + * @author Curverider Ltd + + * @link http://elgg.org/ + */ + + elgg_set_viewtype('failsafe'); // Set failsafe again incase we get an exception thrown + + if (is_installed()) forward(); + + if (get_input('settings') == 'go') { + + if (!datalist_get('default_site')) { + + // Sanitise + $path = sanitise_filepath(get_input('path')); + $dataroot = sanitise_filepath(get_input('dataroot')); + + // Blank? + if ($dataroot == "/") + throw new InstallationException(elgg_echo('InstallationException:DatarootBlank')); + + // That it's valid + if (stripos($dataroot, $path)!==false) + throw new InstallationException(sprintf(elgg_echo('InstallationException:DatarootUnderPath'), $dataroot)); + + // Check data root is writable + if (!is_writable($dataroot)) + throw new InstallationException(sprintf(elgg_echo('InstallationException:DatarootNotWritable'), $dataroot)); + + + $site = new ElggSite(); + $site->name = get_input('sitename'); + $site->url = get_input('wwwroot'); + $site->description = get_input('sitedescription'); + $site->email = get_input('siteemail'); + $site->access_id = ACCESS_PUBLIC; + $guid = $site->save(); + + if (!$guid) + throw new InstallationException(sprintf(elgg_echo('InstallationException:CantCreateSite'), get_input('sitename'), get_input('wwwroot'))); + + datalist_set('installed',time()); + + datalist_set('path', $path); + datalist_set('dataroot', $dataroot); + + datalist_set('default_site',$site->getGUID()); + + set_config('view', get_input('view'), $site->getGUID()); + set_config('language', get_input('language'), $site->getGUID()); + set_config('default_access', get_input('default_access'), $site->getGUID()); + + $debug = get_input('debug'); + if ($debug) + set_config('debug', 1, $site->getGUID()); + else + unset_config('debug', $site->getGUID()); + + $usage = get_input('usage'); + if (is_array($usage)) $usage = $usage[0]; + + if ($usage) + unset_config('ping_home', $site->getGUID()); + else + set_config('ping_home', 'disabled', $site->getGUID()); + + $api = get_input('api'); + if ($api) + unset_config('disable_api', $site->getGUID()); + else + set_config('disable_api', 'disabled', $site->getGUID()); + + $https_login = get_input('https_login'); + if ($https_login) + set_config('https_login', 1, $site->getGUID()); + else + unset_config('https_login', $site->getGUID()); + + // activate some plugins by default + if (isset($CONFIG->default_plugins)) { - if (!is_array($CONFIG->default_plugins)) + if (!is_array($CONFIG->default_plugins)) $plugins = explode(',', $CONFIG->default_plugins); else $CONFIG->default_plugins = $CONFIG->default_plugins; - - foreach ($plugins as $plugin) - enable_plugin(trim($plugin), $site->getGUID()); - } - else - { - enable_plugin('profile', $site->getGUID()); - enable_plugin('river', $site->getGUID()); - enable_plugin('logbrowser', $site->getGUID()); - enable_plugin('diagnostics', $site->getGUID()); + + foreach ($plugins as $plugin) + enable_plugin(trim($plugin), $site->getGUID()); + } + else + { + enable_plugin('profile', $site->getGUID()); + enable_plugin('river', $site->getGUID()); + enable_plugin('logbrowser', $site->getGUID()); + enable_plugin('diagnostics', $site->getGUID()); enable_plugin('uservalidationbyemail', $site->getGUID()); - enable_plugin('htmlawed', $site->getGUID()); - } - - // Now ping home - if ($usage) - { - ping_home($site); - } - - system_message(elgg_echo("installation:configuration:success")); - - header("Location: ../../account/register.php"); - exit; - - } - - } - + enable_plugin('htmlawed', $site->getGUID()); + } + + // Now ping home + if ($usage) + { + ping_home($site); + } + + system_message(elgg_echo("installation:configuration:success")); + + header("Location: ../../account/register.php"); + exit; + + } + + } + ?> \ No newline at end of file diff --git a/actions/user/default_access.php b/actions/user/default_access.php index 0f062ed19..b79200ad0 100644 --- a/actions/user/default_access.php +++ b/actions/user/default_access.php @@ -9,8 +9,8 @@ */ require_once(dirname(dirname(dirname(__FILE__))) . "/engine/start.php"); - global $CONFIG; - + global $CONFIG; + if ($CONFIG->allow_user_default_access) { gatekeeper(); @@ -25,7 +25,7 @@ $user = get_entity($user_id); if ($user) - { + { $current_default_access = $user->getPrivateSetting('elgg_default_access'); if ($default_access != $current_default_access) { @@ -36,7 +36,7 @@ } } else - register_error(elgg_echo('user:default_access:fail')); + register_error(elgg_echo('user:default_access:fail')); } //forward($_SERVER['HTTP_REFERER']); diff --git a/actions/user/requestnewpassword.php b/actions/user/requestnewpassword.php index 2dff5f34d..a54e71b7e 100644 --- a/actions/user/requestnewpassword.php +++ b/actions/user/requestnewpassword.php @@ -14,26 +14,26 @@ action_gatekeeper(); $username = get_input('username'); - - $access_status = access_get_show_hidden_status(); + + $access_status = access_get_show_hidden_status(); access_show_hidden_entities(true); $user = get_user_by_username($username); if ($user) - { + { if ($user->validated) { if (send_new_password_request($user->guid)) system_message(elgg_echo('user:password:resetreq:success')); else - register_error(elgg_echo('user:password:resetreq:fail')); - } else if (!trigger_plugin_hook('unvalidated_requestnewpassword','user',array('entity'=>$user))) { - // if plugins have not registered an action, the default action is to - // trigger the validation event again and assume that the validation - // event will display an appropriate message - trigger_elgg_event('validate', 'user', $user); + register_error(elgg_echo('user:password:resetreq:fail')); + } else if (!trigger_plugin_hook('unvalidated_requestnewpassword','user',array('entity'=>$user))) { + // if plugins have not registered an action, the default action is to + // trigger the validation event again and assume that the validation + // event will display an appropriate message + trigger_elgg_event('validate', 'user', $user); } } else - register_error(sprintf(elgg_echo('user:username:notfound'), $username)); + register_error(sprintf(elgg_echo('user:username:notfound'), $username)); access_show_hidden_entities($access_status); forward(); diff --git a/actions/user/spotlight.php b/actions/user/spotlight.php index b43af2f16..8f50df2c8 100644 --- a/actions/user/spotlight.php +++ b/actions/user/spotlight.php @@ -1,15 +1,15 @@ -spotlightclosed = $closed; - exit; - +spotlightclosed = $closed; + exit; + ?> \ No newline at end of file diff --git a/actions/useradd.php b/actions/useradd.php index cf4f03ffe..0149a9753 100644 --- a/actions/useradd.php +++ b/actions/useradd.php @@ -14,7 +14,7 @@ admin_gatekeeper(); // Only admins can add a user action_gatekeeper(); - // Get variables + // Get variables global $CONFIG; $username = get_input('username'); $password = get_input('password'); @@ -40,9 +40,9 @@ $new_user->admin_created = true; $new_user->created_by_guid = get_loggedin_userid(); - - - notify_user($new_user->guid, $CONFIG->site->guid, elgg_echo('useradd:subject'), sprintf(elgg_echo('useradd:body'), $name, $CONFIG->site->name, $CONFIG->site->url, $username, $password)); + + + notify_user($new_user->guid, $CONFIG->site->guid, elgg_echo('useradd:subject'), sprintf(elgg_echo('useradd:body'), $name, $CONFIG->site->name, $CONFIG->site->url, $username, $password)); system_message(sprintf(elgg_echo("adduser:ok"),$CONFIG->sitename)); } else { diff --git a/actions/usersettings/save.php b/actions/usersettings/save.php index b720c371a..8c920def1 100644 --- a/actions/usersettings/save.php +++ b/actions/usersettings/save.php @@ -1,22 +1,22 @@ - + action_gatekeeper(); + + trigger_plugin_hook('usersettings:save','user'); + + forward($_SERVER['HTTP_REFERER']); + +?> diff --git a/actions/widgets/add.php b/actions/widgets/add.php index 76aaa3b17..14653eb18 100644 --- a/actions/widgets/add.php +++ b/actions/widgets/add.php @@ -1,43 +1,43 @@ -canEdit()) { + + $result = add_widget($user->getGUID(),$handler,$context,0,$column); + + } + + } + + } + + if ($result) { + system_message(elgg_echo('widgets:save:success')); + } else { + register_error(elgg_echo('widgets:save:failure')); + } + + forward($_SERVER['HTTP_REFERER']); - * @link http://elgg.org/ - */ - - $guid = get_input('user'); - $handler = get_input('handler'); - $context = get_input('context'); - $column = get_input('column'); - - $result = false; - - if (!empty($guid)) { - - if ($user = get_entity($guid)) { - - if ($user->canEdit()) { - - $result = add_widget($user->getGUID(),$handler,$context,0,$column); - - } - - } - - } - - if ($result) { - system_message(elgg_echo('widgets:save:success')); - } else { - register_error(elgg_echo('widgets:save:failure')); - } - - forward($_SERVER['HTTP_REFERER']); - ?> \ No newline at end of file diff --git a/actions/widgets/reorder.php b/actions/widgets/reorder.php index 6f3142e8d..3e3a98ebb 100644 --- a/actions/widgets/reorder.php +++ b/actions/widgets/reorder.php @@ -1,32 +1,32 @@ - \ No newline at end of file diff --git a/actions/widgets/save.php b/actions/widgets/save.php index c6e06a12f..6fdf79c11 100644 --- a/actions/widgets/save.php +++ b/actions/widgets/save.php @@ -1,38 +1,38 @@ - \ No newline at end of file diff --git a/admin/index.php b/admin/index.php index 969d91f7e..98466cb20 100644 --- a/admin/index.php +++ b/admin/index.php @@ -1,21 +1,21 @@ - \ No newline at end of file diff --git a/admin/plugins.php b/admin/plugins.php index dcf0fead0..9900c98e9 100644 --- a/admin/plugins.php +++ b/admin/plugins.php @@ -17,9 +17,9 @@ admin_gatekeeper(); // Set admin user for user block - //set_page_owner($_SESSION['guid']); - - // Regenerate plugin list + //set_page_owner($_SESSION['guid']); + + // Regenerate plugin list regenerate_plugin_list(); // Display main admin menu diff --git a/admin/site.php b/admin/site.php index dc8aed1a1..c66dc290a 100644 --- a/admin/site.php +++ b/admin/site.php @@ -1,26 +1,26 @@ - \ No newline at end of file diff --git a/admin/user.php b/admin/user.php index 84e4f1d83..16b5bf172 100644 --- a/admin/user.php +++ b/admin/user.php @@ -1,45 +1,45 @@ - \ No newline at end of file diff --git a/dashboard/index.php b/dashboard/index.php index 260d5b46e..101e74d6d 100644 --- a/dashboard/index.php +++ b/dashboard/index.php @@ -1,33 +1,33 @@ - \ No newline at end of file diff --git a/dashboard/latest.php b/dashboard/latest.php index c49b6fc20..cf214a060 100644 --- a/dashboard/latest.php +++ b/dashboard/latest.php @@ -1,30 +1,30 @@ - \ No newline at end of file diff --git a/engine/handlers/action_handler.php b/engine/handlers/action_handler.php index 1e769eebd..4878084ad 100644 --- a/engine/handlers/action_handler.php +++ b/engine/handlers/action_handler.php @@ -1,21 +1,21 @@ - + * @author Curverider Ltd + + * @link http://elgg.org/ + */ + /** + * Load Elgg framework + */ + define('externalpage',true); + require_once("../start.php"); + $action = get_input("action"); + action($action); + +?> diff --git a/engine/handlers/cron_handler.php b/engine/handlers/cron_handler.php index a379a0e20..71a8cf2a4 100644 --- a/engine/handlers/cron_handler.php +++ b/engine/handlers/cron_handler.php @@ -8,7 +8,7 @@ * @link http://elgg.org/ */ - // Load Elgg engine + // Load Elgg engine define('externalpage',true); require_once("../start.php"); global $CONFIG; diff --git a/engine/handlers/pagehandler.php b/engine/handlers/pagehandler.php index 167d54957..506ae9802 100644 --- a/engine/handlers/pagehandler.php +++ b/engine/handlers/pagehandler.php @@ -1,27 +1,27 @@ - \ No newline at end of file diff --git a/engine/handlers/xml-rpc_handler.php b/engine/handlers/xml-rpc_handler.php index 6be9b4a09..bc87306c7 100644 --- a/engine/handlers/xml-rpc_handler.php +++ b/engine/handlers/xml-rpc_handler.php @@ -8,7 +8,7 @@ * @link http://elgg.org/ */ - // Load Elgg engine + // Load Elgg engine define('externalpage',true); require_once("../start.php"); global $CONFIG; diff --git a/engine/lib/access.php b/engine/lib/access.php index 7f3a8131f..392c89a2f 100644 --- a/engine/lib/access.php +++ b/engine/lib/access.php @@ -1,665 +1,665 @@ -site_id))) $site_id = $CONFIG->site_id; - $user_id = (int) $user_id; - $site_id = (int) $site_id; - - if (isset($access_list[$user_id])) return $access_list[$user_id]; - - $access_list[$user_id] = "(" . implode(",",get_access_array($user_id, $site_id, $flush)) . ")"; - - return $access_list[$user_id]; - - } - - /** - * Gets an array of access restrictions the given user is allowed to see on this site - * - * @param int $user_id User ID; defaults to currently logged in user - * @param int $site_id Site ID; defaults to current site - * @param boolean $flush If set to true, will refresh the access list from the database - * @return array An array of access collections suitable for injection in an SQL call - */ - function get_access_array($user_id = 0, $site_id = 0, $flush = false) { - - global $CONFIG, $init_finished; - static $access_array, $acm, $ac; // Caches. $ac* flag whether we have executed a query previously, and stop it being run again if no data is returned. - - if (!isset($access_array) || (!isset($init_finished)) || (!$init_finished)) - $access_array = array(); - - if ($user_id == 0) $user_id = get_loggedin_userid(); - - if (($site_id == 0) && (isset($CONFIG->site_guid))) $site_id = $CONFIG->site_guid; - $user_id = (int) $user_id; - $site_id = (int) $site_id; - - if (empty($access_array[$user_id]) || $flush == true) { - - $query = "SELECT am.access_collection_id FROM {$CONFIG->dbprefix}access_collection_membership am "; - $query .= " LEFT JOIN {$CONFIG->dbprefix}access_collections ag ON ag.id = am.access_collection_id "; - $query .= " WHERE am.user_guid = {$user_id} AND (ag.site_guid = {$site_id} OR ag.site_guid = 0)"; - - $tmp_access_array = array(ACCESS_PUBLIC); - if (isloggedin()) { - $tmp_access_array[] = ACCESS_LOGGED_IN; - - // The following can only return sensible data if the user is logged in. - - if ($collections = get_data($query)) { - foreach($collections as $collection) - if (!empty($collection->access_collection_id)) $tmp_access_array[] = $collection->access_collection_id; - - } - - $query = "SELECT ag.id FROM {$CONFIG->dbprefix}access_collections ag "; - $query .= " WHERE ag.owner_guid = {$user_id} AND (ag.site_guid = {$site_id} OR ag.site_guid = 0)"; - - if ($collections = get_data($query)) { - foreach($collections as $collection) - if (!empty($collection->id)) $tmp_access_array[] = $collection->id; - } - - - global $is_admin; - - if (isset($is_admin) && $is_admin == true) { - $tmp_access_array[] = ACCESS_PRIVATE; - } - - $access_array[$user_id] = $tmp_access_array; - } - else - $tmp_return = $tmp_access_array; // No user id logged in so we can only access public info - - - } else { - $tmp_access_array = $access_array[$user_id]; - } - - $tmp_return = $access_array[$user_id]; - - return trigger_plugin_hook('access:collections:read','user',array('user_id' => $user_id, 'site_id' => $site_id),$tmp_access_array); - } - - /** - * Gets the default access permission for new content - * - * @return int default access id (see ACCESS defines in elgglib.php) - */ - function get_default_access($user=null) - { - global $CONFIG; - - if (!$CONFIG->allow_user_default_access) { - return $CONFIG->default_access; - } - - if (!$user) { - if (isloggedin()) { - $user = $_SESSION['user']; - } else { - return $CONFIG->default_access; - } - } - - if (false !== ($default_access = $user->getPrivateSetting('elgg_default_access'))) { - return $default_access; - } else { - return $CONFIG->default_access; - } - } - - /** - * Override the default behaviour and allow results to show hidden entities as well. - * THIS IS A HACK. - * - * TODO: Replace this with query object! - */ - $ENTITY_SHOW_HIDDEN_OVERRIDE = false; - - /** - * This will be replaced. Do not use in plugins! - * - * @param bool $show - */ - function access_show_hidden_entities($show_hidden) - { - global $ENTITY_SHOW_HIDDEN_OVERRIDE; - $ENTITY_SHOW_HIDDEN_OVERRIDE = $show_hidden; - } - - /** - * This will be replaced. Do not use in plugins! - */ - function access_get_show_hidden_status() - { - global $ENTITY_SHOW_HIDDEN_OVERRIDE; - return $ENTITY_SHOW_HIDDEN_OVERRIDE; - } - - /** - * Add annotation restriction - * - * Returns an SQL fragment that is true (or optionally false) if the given user has - * added an annotation with the given name to the given entity. - * - * TODO: This is fairly generic so perhaps it could be moved to annotations.php - * - * @param string $annotation_name name of the annotation - * @param string $entity_guid SQL string that evaluates to the GUID of the entity the annotation should be attached to - * @param string $owner_guid SQL string that evaluates to the GUID of the owner of the annotation * - * @param boolean $exists If set to true, will return true if the annotation exists, otherwise returns false - * @return string An SQL fragment suitable for inserting into a WHERE clause - */ - - function get_annotation_sql($annotation_name,$entity_guid,$owner_guid,$exists) { - global $CONFIG; - - if ($exists) { - $not = ''; - } else { - $not = 'NOT'; - } - - $sql = <<dbprefix}annotations a -INNER JOIN {$CONFIG->dbprefix}metastrings ms ON (a.name_id = ms.id) -WHERE ms.string = '$annotation_name' -AND a.entity_guid = $entity_guid -AND a.owner_guid = $owner_guid) -END; - return $sql; - } - - /** - * Add access restriction sql code to a given query. - * - * Note that if this code is executed in privileged mode it will return blank. - * - * TODO: DELETE once Query classes are fully integrated - * - * @param string $table_prefix Optional xxx. prefix for the access code. - */ - function get_access_sql_suffix($table_prefix = "",$owner=null) - { - global $ENTITY_SHOW_HIDDEN_OVERRIDE, $CONFIG; - - $sql = ""; - $friends_bit = ""; - $enemies_bit = ""; - - if ($table_prefix) - $table_prefix = sanitise_string($table_prefix) . "."; - - $access = get_access_list(); - - if (!isset($owner)) { - $owner = get_loggedin_userid(); - } - if (!$owner) $owner = -1; - - global $is_admin; - - if (isset($is_admin) && $is_admin == true) { - $sql = " (1 = 1) "; - } else if ($owner != -1) { - $friends_bit = $table_prefix.'access_id = '.ACCESS_FRIENDS.' AND '; - $friends_bit .= "{$table_prefix}owner_guid IN (SELECT guid_one FROM {$CONFIG->dbprefix}entity_relationships WHERE relationship='friend' AND guid_two=$owner)"; - $friends_bit = '('.$friends_bit.') OR '; - - if ((isset($CONFIG->user_block_and_filter_enabled)) && ($CONFIG->user_block_and_filter_enabled)) { - // check to see if the user is in the entity owner's block list - // or if the entity owner is in the user's filter list - // if so, disallow access - - $enemies_bit = get_annotation_sql('elgg_block_list',"{$table_prefix}owner_guid",$owner,false); - $enemies_bit = '('.$enemies_bit. ' AND '.get_annotation_sql('elgg_filter_list',$owner,"{$table_prefix}owner_guid",false).')'; - } - } - - if (empty($sql)) - $sql = " $friends_bit ({$table_prefix}access_id in {$access} or ({$table_prefix}owner_guid = {$owner}) or ({$table_prefix}access_id = " . ACCESS_PRIVATE . " and {$table_prefix}owner_guid = $owner))"; - - if ($enemies_bit) { - $sql = "$enemies_bit AND ($sql)"; - } - - if (!$ENTITY_SHOW_HIDDEN_OVERRIDE) - $sql .= " and {$table_prefix}enabled='yes'"; - return '('.$sql.')'; - } - - /** - * Determines whether the given user has access to the given entity - * - * @param ElggEntity $entity The entity to check access for. - * @param ElggUser $user Optionally the user to check access for. - * - * @return boolean True if the user can access the entity - */ - - function has_access_to_entity($entity,$user = null) { - global $CONFIG; - - if (!isset($user)) { - $access_bit = get_access_sql_suffix("e"); - } else { - $access_bit = get_access_sql_suffix("e",$user->getGUID()); - } - - $query = "SELECT guid from {$CONFIG->dbprefix}entities e WHERE e.guid = ".$entity->getGUID(); - $query .= " AND ".$access_bit; // Add access controls - if (get_data($query)) { - return true; - } else { - return false; - } - } - - /** - * Returns an array of access permissions that the specified user is allowed to save objects with. - * Permissions are of the form ('id' => 'Description') - * - * @param int $user_id The user's GUID. - * @param int $site_id The current site. - * @param true|false $flush If this is set to true, this will shun any cached version - * @return array List of access permissions= - */ - function get_write_access_array($user_id = 0, $site_id = 0, $flush = false) { - - global $CONFIG; - static $access_array; - - if ($user_id == 0) $user_id = get_loggedin_userid(); - if (($site_id == 0) && (isset($CONFIG->site_id))) $site_id = $CONFIG->site_id; - $user_id = (int) $user_id; - $site_id = (int) $site_id; - - if (empty($access_array[$user_id]) || $flush == true) { - - $query = "SELECT ag.* FROM {$CONFIG->dbprefix}access_collections ag "; - $query .= " WHERE (ag.site_guid = {$site_id} OR ag.site_guid = 0)"; - $query .= " AND (ag.owner_guid = {$user_id})"; - $query .= " AND ag.id >= 3"; - - $tmp_access_array = array(0 => elgg_echo("PRIVATE"), ACCESS_FRIENDS => elgg_echo("access:friends:label"), 1 => elgg_echo("LOGGED_IN"), 2 => elgg_echo("PUBLIC")); - if ($collections = get_data($query)) { - foreach($collections as $collection) - $tmp_access_array[$collection->id] = $collection->name; - } - - $access_array[$user_id] = $tmp_access_array; - - } else { - $tmp_access_array = $access_array[$user_id]; - } - - $tmp_access_array = trigger_plugin_hook('access:collections:write','user',array('user_id' => $user_id, 'site_id' => $site_id),$tmp_access_array); - - return $tmp_access_array; - - } - - /** - * Creates a new access control collection owned by the specified user. - * - * @param string $name The name of the collection. - * @param int $owner_guid The GUID of the owner (default: currently logged in user). - * @param int $site_guid The GUID of the site (default: current site). - * @return int|false Depending on success (the collection ID if successful). - */ - function create_access_collection($name, $owner_guid = 0, $site_guid = 0) { - - global $CONFIG; - - $name = trim($name); - if (empty($name)) return false; - - if ($owner_guid == 0) $owner_guid = get_loggedin_userid(); - if (($site_id == 0) && (isset($CONFIG->site_guid))) $site_id = $CONFIG->site_guid; - $name = sanitise_string($name); - - return insert_data("insert into {$CONFIG->dbprefix}access_collections set name = '{$name}', owner_guid = {$owner_guid}, site_guid = {$site_id}"); - - } - - /** - * Updates the membership in an access collection. - * - * @param int $collection_id The ID of the collection. - * @param array $members Array of member GUIDs - * @return true|false Depending on success - */ - function update_access_collection($collection_id, $members) { - - global $CONFIG; - $collection_id = (int) $collection_id; - - $collections = get_write_access_array(); - - if (array_key_exists($collection_id, $collections)) { - - delete_data("delete from {$CONFIG->dbprefix}access_collection_membership where access_collection_id = {$collection_id}"); - - if (is_array($members) && sizeof($members) > 0) { - foreach($members as $member) { - $member = (int) $member; - if (get_user($member)) - insert_data("insert into {$CONFIG->dbprefix}access_collection_membership set access_collection_id = {$collection_id}, user_guid = {$member}"); - } - return true; - } - - } - - return false; - } - - /** - * Deletes a specified access collection - * - * @param int $collection_id The collection ID - * @return true|false Depending on success - */ - function delete_access_collection($collection_id) { - - $collection_id = (int) $collection_id; - $collections = get_write_access_array(); - if (array_key_exists($collection_id, $collections)) { - global $CONFIG; - delete_data("delete from {$CONFIG->dbprefix}access_collection_membership where access_collection_id = {$collection_id}"); - delete_data("delete from {$CONFIG->dbprefix}access_collections where id = {$collection_id}"); - return true; - } else { - return false; - } - - } - - /** - * Get a specified access collection - * - * @param int $collection_id The collection ID - * @return array|false Depending on success - */ - function get_access_collection($collection_id) { - - $collection_id = (int) $collection_id; - global $CONFIG; - $get_collection = get_data_row("SELECT * FROM {$CONFIG->dbprefix}access_collections WHERE id = {$collection_id}"); - - return $get_collection; - - } - - /** - * Adds a user to the specified user collection - * - * @param int $user_guid The GUID of the user to add - * @param int $collection_id The ID of the collection to add them to - * @return true|false Depending on success - */ - function add_user_to_access_collection($user_guid, $collection_id) { - - $collection_id = (int) $collection_id; - $user_guid = (int) $user_guid; - $collections = get_write_access_array(); - - if (!($collection = get_access_collection($collection_id))) - return false; - - if ((array_key_exists($collection_id, $collections) || $collection->owner_guid == 0) - && $user = get_user($user_guid)) { - - global $CONFIG; - try { - insert_data("insert into {$CONFIG->dbprefix}access_collection_membership set access_collection_id = {$collection_id}, user_guid = {$user_guid}"); - } catch (DatabaseException $e) {} - return true; - - } - - return false; - - } - - /** - * Removes a user from an access collection - * - * @param int $user_guid The user GUID - * @param int $collection_id The access collection ID - * @return true|false Depending on success - */ - function remove_user_from_access_collection($user_guid, $collection_id) { - - $collection_id = (int) $collection_id; - $user_guid = (int) $user_guid; - $collections = get_write_access_array(); - - if (!($collection = get_access_collection($collection_id))) - return false; - - if ((array_key_exists($collection_id, $collections) || $collection->owner_guid == 0) && $user = get_user($user_guid)) { - - global $CONFIG; - delete_data("delete from {$CONFIG->dbprefix}access_collection_membership where access_collection_id = {$collection_id} and user_guid = {$user_guid}"); - return true; - - } - - return false; - - } - - /** - * Get all of a users collections - * - * @param int $owner_guid The user ID - * @return true|false Depending on success - */ - function get_user_access_collections($owner_guid) { - - $owner_guid = (int) $owner_guid; - - global $CONFIG; - - $collections = get_data("SELECT * FROM {$CONFIG->dbprefix}access_collections WHERE owner_guid = {$owner_guid}"); - - return $collections; - - } - - /** - * Get all of members of a friend collection - * - * @param int $collection The collection's ID - * @param true|false $idonly If set to true, will only return the members' IDs (default: false) - * @return ElggUser entities if successful, false if not - */ - function get_members_of_access_collection($collection, $idonly = false) { - - $collection = (int)$collection; - - global $CONFIG; - - if (!$idonly) { - $query = "SELECT e.* FROM {$CONFIG->dbprefix}access_collection_membership m JOIN {$CONFIG->dbprefix}entities e ON e.guid = m.user_guid WHERE m.access_collection_id = {$collection}"; - $collection_members = get_data($query, "entity_row_to_elggstar"); - } else { - $query = "SELECT e.guid FROM {$CONFIG->dbprefix}access_collection_membership m JOIN {$CONFIG->dbprefix}entities e ON e.guid = m.user_guid WHERE m.access_collection_id = {$collection}"; - $collection_members = get_data($query); - foreach($collection_members as $key => $val) - $collection_members[$key] = $val->guid; - } - - return $collection_members; - - } - - /** - * Displays a user's access collections, using the friends/collections view - * - * @param int $owner_guid The GUID of the owning user - * @return string A formatted rendition of the collections - */ - function elgg_view_access_collections($owner_guid) { - - if ($collections = get_user_access_collections($owner_guid)) { - - foreach($collections as $key => $collection) { - $collections[$key]->members = get_members_of_access_collection($collection->id, true); - $collections[$key]->entities = get_user_friends($owner_guid,"",9999); - } - - } - - return elgg_view('friends/collections',array('collections' => $collections)); - - } - - /** - * Get entities with the specified access collection id. - * - * @param $collection_id - * @param $entity_type - * @param $entity_subtype - * @param $owner_guid - * @param $limit - * @param $offset - * @param $order_by - * @param $site_guid - * @param $count - * @return unknown_type - */ - function get_entities_from_access_collection($collection_id, $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $order_by = "", $site_guid = 0, $count = false) { - global $CONFIG; - - if (!$collection_id) - return false; - - $entity_type = sanitise_string($entity_type); - $entity_subtype = get_subtype_id($entity_type, $entity_subtype); - $limit = (int)$limit; - $offset = (int)$offset; - if ($order_by == "") - $order_by = "e.time_created desc"; - else - $order_by = "e.time_created, {$order_by}"; - $order_by = sanitise_string($order_by); - $site_guid = (int) $site_guid; - if ((is_array($owner_guid) && (count($owner_guid)))) { - foreach($owner_guid as $key => $guid) { - $owner_guid[$key] = (int) $guid; - } - } else { - $owner_guid = (int) $owner_guid; - } - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - //$access = get_access_list(); - - $where = array("e.access_id = $collection_id"); - - if ($entity_type!=="") - $where[] = "e.type='$entity_type'"; - if ($entity_subtype) - $where[] = "e.subtype=$entity_subtype"; - if ($site_guid > 0) - $where[] = "e.site_guid = {$site_guid}"; - if (is_array($owner_guid)) { - $where[] = "e.container_guid in (".implode(",",$owner_guid).")"; - } else if ($owner_guid > 0) - $where[] = "e.container_guid = {$owner_guid}"; - - if (!$count) { - $query = "SELECT distinct e.* "; - } else { - $query = "SELECT count(distinct e.guid) as total "; - } - - $query .= "from {$CONFIG->dbprefix}entities e where"; - foreach ($where as $w) - $query .= " $w and "; - $query .= get_access_sql_suffix("e"); // Add access controls - //$query .= ' and ' . get_access_sql_suffix("m"); // Add access controls - - if (!$count) { - $query .= " order by $order_by limit $offset, $limit"; // Add order and limit - return get_data($query, "entity_row_to_elggstar"); - } else { - if ($row = get_data_row($query)) - return $row->total; - } - return false; - } - - /** - * Lists entities from an access collection - * - * @param $collection_id - * @param $entity_type - * @param $entity_subtype - * @param $owner_guid - * @param $limit - * @param $fullview - * @param $viewtypetoggle - * @param $pagination - * @return str - */ - function list_entities_from_access_collection($collection_id, $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true) { - $offset = (int) get_input('offset'); - $limit = (int) $limit; - $count = get_entities_from_access_collection($collection_id, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", 0, true); - $entities = get_entities_from_access_collection($collection_id, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", 0, false); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); - } - - global $init_finished; - $init_finished = false; - - /** - * A quick and dirty way to make sure the access permissions have been correctly set up - * - */ - function access_init() { - global $init_finished; - $init_finished = true; - } - - // This function will let us know when 'init' has finished - register_elgg_event_handler('init','system','access_init',9999); - + * @author Curverider Ltd + + * @link http://elgg.org/ + */ + + /** + * Get the list of access restrictions the given user is allowed to see on this site + * + * @uses get_access_array + * @param int $user_id User ID; defaults to currently logged in user + * @param int $site_id Site ID; defaults to current site + * @param boolean $flush If set to true, will refresh the access list from the database + * @return string A list of access collections suitable for injection in an SQL call + */ + function get_access_list($user_id = 0, $site_id = 0, $flush = false) { + + global $CONFIG, $init_finished, $SESSION; + static $access_list; + + if (!isset($access_list) || !$init_finished) + $access_list = array(); + + if ($user_id == 0) $user_id = $SESSION['id']; + if (($site_id == 0) && (isset($CONFIG->site_id))) $site_id = $CONFIG->site_id; + $user_id = (int) $user_id; + $site_id = (int) $site_id; + + if (isset($access_list[$user_id])) return $access_list[$user_id]; + + $access_list[$user_id] = "(" . implode(",",get_access_array($user_id, $site_id, $flush)) . ")"; + + return $access_list[$user_id]; + + } + + /** + * Gets an array of access restrictions the given user is allowed to see on this site + * + * @param int $user_id User ID; defaults to currently logged in user + * @param int $site_id Site ID; defaults to current site + * @param boolean $flush If set to true, will refresh the access list from the database + * @return array An array of access collections suitable for injection in an SQL call + */ + function get_access_array($user_id = 0, $site_id = 0, $flush = false) { + + global $CONFIG, $init_finished; + static $access_array, $acm, $ac; // Caches. $ac* flag whether we have executed a query previously, and stop it being run again if no data is returned. + + if (!isset($access_array) || (!isset($init_finished)) || (!$init_finished)) + $access_array = array(); + + if ($user_id == 0) $user_id = get_loggedin_userid(); + + if (($site_id == 0) && (isset($CONFIG->site_guid))) $site_id = $CONFIG->site_guid; + $user_id = (int) $user_id; + $site_id = (int) $site_id; + + if (empty($access_array[$user_id]) || $flush == true) { + + $query = "SELECT am.access_collection_id FROM {$CONFIG->dbprefix}access_collection_membership am "; + $query .= " LEFT JOIN {$CONFIG->dbprefix}access_collections ag ON ag.id = am.access_collection_id "; + $query .= " WHERE am.user_guid = {$user_id} AND (ag.site_guid = {$site_id} OR ag.site_guid = 0)"; + + $tmp_access_array = array(ACCESS_PUBLIC); + if (isloggedin()) { + $tmp_access_array[] = ACCESS_LOGGED_IN; + + // The following can only return sensible data if the user is logged in. + + if ($collections = get_data($query)) { + foreach($collections as $collection) + if (!empty($collection->access_collection_id)) $tmp_access_array[] = $collection->access_collection_id; + + } + + $query = "SELECT ag.id FROM {$CONFIG->dbprefix}access_collections ag "; + $query .= " WHERE ag.owner_guid = {$user_id} AND (ag.site_guid = {$site_id} OR ag.site_guid = 0)"; + + if ($collections = get_data($query)) { + foreach($collections as $collection) + if (!empty($collection->id)) $tmp_access_array[] = $collection->id; + } + + + global $is_admin; + + if (isset($is_admin) && $is_admin == true) { + $tmp_access_array[] = ACCESS_PRIVATE; + } + + $access_array[$user_id] = $tmp_access_array; + } + else + $tmp_return = $tmp_access_array; // No user id logged in so we can only access public info + + + } else { + $tmp_access_array = $access_array[$user_id]; + } + + $tmp_return = $access_array[$user_id]; + + return trigger_plugin_hook('access:collections:read','user',array('user_id' => $user_id, 'site_id' => $site_id),$tmp_access_array); + } + + /** + * Gets the default access permission for new content + * + * @return int default access id (see ACCESS defines in elgglib.php) + */ + function get_default_access($user=null) + { + global $CONFIG; + + if (!$CONFIG->allow_user_default_access) { + return $CONFIG->default_access; + } + + if (!$user) { + if (isloggedin()) { + $user = $_SESSION['user']; + } else { + return $CONFIG->default_access; + } + } + + if (false !== ($default_access = $user->getPrivateSetting('elgg_default_access'))) { + return $default_access; + } else { + return $CONFIG->default_access; + } + } + + /** + * Override the default behaviour and allow results to show hidden entities as well. + * THIS IS A HACK. + * + * TODO: Replace this with query object! + */ + $ENTITY_SHOW_HIDDEN_OVERRIDE = false; + + /** + * This will be replaced. Do not use in plugins! + * + * @param bool $show + */ + function access_show_hidden_entities($show_hidden) + { + global $ENTITY_SHOW_HIDDEN_OVERRIDE; + $ENTITY_SHOW_HIDDEN_OVERRIDE = $show_hidden; + } + + /** + * This will be replaced. Do not use in plugins! + */ + function access_get_show_hidden_status() + { + global $ENTITY_SHOW_HIDDEN_OVERRIDE; + return $ENTITY_SHOW_HIDDEN_OVERRIDE; + } + + /** + * Add annotation restriction + * + * Returns an SQL fragment that is true (or optionally false) if the given user has + * added an annotation with the given name to the given entity. + * + * TODO: This is fairly generic so perhaps it could be moved to annotations.php + * + * @param string $annotation_name name of the annotation + * @param string $entity_guid SQL string that evaluates to the GUID of the entity the annotation should be attached to + * @param string $owner_guid SQL string that evaluates to the GUID of the owner of the annotation * + * @param boolean $exists If set to true, will return true if the annotation exists, otherwise returns false + * @return string An SQL fragment suitable for inserting into a WHERE clause + */ + + function get_annotation_sql($annotation_name,$entity_guid,$owner_guid,$exists) { + global $CONFIG; + + if ($exists) { + $not = ''; + } else { + $not = 'NOT'; + } + + $sql = <<dbprefix}annotations a +INNER JOIN {$CONFIG->dbprefix}metastrings ms ON (a.name_id = ms.id) +WHERE ms.string = '$annotation_name' +AND a.entity_guid = $entity_guid +AND a.owner_guid = $owner_guid) +END; + return $sql; + } + + /** + * Add access restriction sql code to a given query. + * + * Note that if this code is executed in privileged mode it will return blank. + * + * TODO: DELETE once Query classes are fully integrated + * + * @param string $table_prefix Optional xxx. prefix for the access code. + */ + function get_access_sql_suffix($table_prefix = "",$owner=null) + { + global $ENTITY_SHOW_HIDDEN_OVERRIDE, $CONFIG; + + $sql = ""; + $friends_bit = ""; + $enemies_bit = ""; + + if ($table_prefix) + $table_prefix = sanitise_string($table_prefix) . "."; + + $access = get_access_list(); + + if (!isset($owner)) { + $owner = get_loggedin_userid(); + } + if (!$owner) $owner = -1; + + global $is_admin; + + if (isset($is_admin) && $is_admin == true) { + $sql = " (1 = 1) "; + } else if ($owner != -1) { + $friends_bit = $table_prefix.'access_id = '.ACCESS_FRIENDS.' AND '; + $friends_bit .= "{$table_prefix}owner_guid IN (SELECT guid_one FROM {$CONFIG->dbprefix}entity_relationships WHERE relationship='friend' AND guid_two=$owner)"; + $friends_bit = '('.$friends_bit.') OR '; + + if ((isset($CONFIG->user_block_and_filter_enabled)) && ($CONFIG->user_block_and_filter_enabled)) { + // check to see if the user is in the entity owner's block list + // or if the entity owner is in the user's filter list + // if so, disallow access + + $enemies_bit = get_annotation_sql('elgg_block_list',"{$table_prefix}owner_guid",$owner,false); + $enemies_bit = '('.$enemies_bit. ' AND '.get_annotation_sql('elgg_filter_list',$owner,"{$table_prefix}owner_guid",false).')'; + } + } + + if (empty($sql)) + $sql = " $friends_bit ({$table_prefix}access_id in {$access} or ({$table_prefix}owner_guid = {$owner}) or ({$table_prefix}access_id = " . ACCESS_PRIVATE . " and {$table_prefix}owner_guid = $owner))"; + + if ($enemies_bit) { + $sql = "$enemies_bit AND ($sql)"; + } + + if (!$ENTITY_SHOW_HIDDEN_OVERRIDE) + $sql .= " and {$table_prefix}enabled='yes'"; + return '('.$sql.')'; + } + + /** + * Determines whether the given user has access to the given entity + * + * @param ElggEntity $entity The entity to check access for. + * @param ElggUser $user Optionally the user to check access for. + * + * @return boolean True if the user can access the entity + */ + + function has_access_to_entity($entity,$user = null) { + global $CONFIG; + + if (!isset($user)) { + $access_bit = get_access_sql_suffix("e"); + } else { + $access_bit = get_access_sql_suffix("e",$user->getGUID()); + } + + $query = "SELECT guid from {$CONFIG->dbprefix}entities e WHERE e.guid = ".$entity->getGUID(); + $query .= " AND ".$access_bit; // Add access controls + if (get_data($query)) { + return true; + } else { + return false; + } + } + + /** + * Returns an array of access permissions that the specified user is allowed to save objects with. + * Permissions are of the form ('id' => 'Description') + * + * @param int $user_id The user's GUID. + * @param int $site_id The current site. + * @param true|false $flush If this is set to true, this will shun any cached version + * @return array List of access permissions= + */ + function get_write_access_array($user_id = 0, $site_id = 0, $flush = false) { + + global $CONFIG; + static $access_array; + + if ($user_id == 0) $user_id = get_loggedin_userid(); + if (($site_id == 0) && (isset($CONFIG->site_id))) $site_id = $CONFIG->site_id; + $user_id = (int) $user_id; + $site_id = (int) $site_id; + + if (empty($access_array[$user_id]) || $flush == true) { + + $query = "SELECT ag.* FROM {$CONFIG->dbprefix}access_collections ag "; + $query .= " WHERE (ag.site_guid = {$site_id} OR ag.site_guid = 0)"; + $query .= " AND (ag.owner_guid = {$user_id})"; + $query .= " AND ag.id >= 3"; + + $tmp_access_array = array(0 => elgg_echo("PRIVATE"), ACCESS_FRIENDS => elgg_echo("access:friends:label"), 1 => elgg_echo("LOGGED_IN"), 2 => elgg_echo("PUBLIC")); + if ($collections = get_data($query)) { + foreach($collections as $collection) + $tmp_access_array[$collection->id] = $collection->name; + } + + $access_array[$user_id] = $tmp_access_array; + + } else { + $tmp_access_array = $access_array[$user_id]; + } + + $tmp_access_array = trigger_plugin_hook('access:collections:write','user',array('user_id' => $user_id, 'site_id' => $site_id),$tmp_access_array); + + return $tmp_access_array; + + } + + /** + * Creates a new access control collection owned by the specified user. + * + * @param string $name The name of the collection. + * @param int $owner_guid The GUID of the owner (default: currently logged in user). + * @param int $site_guid The GUID of the site (default: current site). + * @return int|false Depending on success (the collection ID if successful). + */ + function create_access_collection($name, $owner_guid = 0, $site_guid = 0) { + + global $CONFIG; + + $name = trim($name); + if (empty($name)) return false; + + if ($owner_guid == 0) $owner_guid = get_loggedin_userid(); + if (($site_id == 0) && (isset($CONFIG->site_guid))) $site_id = $CONFIG->site_guid; + $name = sanitise_string($name); + + return insert_data("insert into {$CONFIG->dbprefix}access_collections set name = '{$name}', owner_guid = {$owner_guid}, site_guid = {$site_id}"); + + } + + /** + * Updates the membership in an access collection. + * + * @param int $collection_id The ID of the collection. + * @param array $members Array of member GUIDs + * @return true|false Depending on success + */ + function update_access_collection($collection_id, $members) { + + global $CONFIG; + $collection_id = (int) $collection_id; + + $collections = get_write_access_array(); + + if (array_key_exists($collection_id, $collections)) { + + delete_data("delete from {$CONFIG->dbprefix}access_collection_membership where access_collection_id = {$collection_id}"); + + if (is_array($members) && sizeof($members) > 0) { + foreach($members as $member) { + $member = (int) $member; + if (get_user($member)) + insert_data("insert into {$CONFIG->dbprefix}access_collection_membership set access_collection_id = {$collection_id}, user_guid = {$member}"); + } + return true; + } + + } + + return false; + } + + /** + * Deletes a specified access collection + * + * @param int $collection_id The collection ID + * @return true|false Depending on success + */ + function delete_access_collection($collection_id) { + + $collection_id = (int) $collection_id; + $collections = get_write_access_array(); + if (array_key_exists($collection_id, $collections)) { + global $CONFIG; + delete_data("delete from {$CONFIG->dbprefix}access_collection_membership where access_collection_id = {$collection_id}"); + delete_data("delete from {$CONFIG->dbprefix}access_collections where id = {$collection_id}"); + return true; + } else { + return false; + } + + } + + /** + * Get a specified access collection + * + * @param int $collection_id The collection ID + * @return array|false Depending on success + */ + function get_access_collection($collection_id) { + + $collection_id = (int) $collection_id; + global $CONFIG; + $get_collection = get_data_row("SELECT * FROM {$CONFIG->dbprefix}access_collections WHERE id = {$collection_id}"); + + return $get_collection; + + } + + /** + * Adds a user to the specified user collection + * + * @param int $user_guid The GUID of the user to add + * @param int $collection_id The ID of the collection to add them to + * @return true|false Depending on success + */ + function add_user_to_access_collection($user_guid, $collection_id) { + + $collection_id = (int) $collection_id; + $user_guid = (int) $user_guid; + $collections = get_write_access_array(); + + if (!($collection = get_access_collection($collection_id))) + return false; + + if ((array_key_exists($collection_id, $collections) || $collection->owner_guid == 0) + && $user = get_user($user_guid)) { + + global $CONFIG; + try { + insert_data("insert into {$CONFIG->dbprefix}access_collection_membership set access_collection_id = {$collection_id}, user_guid = {$user_guid}"); + } catch (DatabaseException $e) {} + return true; + + } + + return false; + + } + + /** + * Removes a user from an access collection + * + * @param int $user_guid The user GUID + * @param int $collection_id The access collection ID + * @return true|false Depending on success + */ + function remove_user_from_access_collection($user_guid, $collection_id) { + + $collection_id = (int) $collection_id; + $user_guid = (int) $user_guid; + $collections = get_write_access_array(); + + if (!($collection = get_access_collection($collection_id))) + return false; + + if ((array_key_exists($collection_id, $collections) || $collection->owner_guid == 0) && $user = get_user($user_guid)) { + + global $CONFIG; + delete_data("delete from {$CONFIG->dbprefix}access_collection_membership where access_collection_id = {$collection_id} and user_guid = {$user_guid}"); + return true; + + } + + return false; + + } + + /** + * Get all of a users collections + * + * @param int $owner_guid The user ID + * @return true|false Depending on success + */ + function get_user_access_collections($owner_guid) { + + $owner_guid = (int) $owner_guid; + + global $CONFIG; + + $collections = get_data("SELECT * FROM {$CONFIG->dbprefix}access_collections WHERE owner_guid = {$owner_guid}"); + + return $collections; + + } + + /** + * Get all of members of a friend collection + * + * @param int $collection The collection's ID + * @param true|false $idonly If set to true, will only return the members' IDs (default: false) + * @return ElggUser entities if successful, false if not + */ + function get_members_of_access_collection($collection, $idonly = false) { + + $collection = (int)$collection; + + global $CONFIG; + + if (!$idonly) { + $query = "SELECT e.* FROM {$CONFIG->dbprefix}access_collection_membership m JOIN {$CONFIG->dbprefix}entities e ON e.guid = m.user_guid WHERE m.access_collection_id = {$collection}"; + $collection_members = get_data($query, "entity_row_to_elggstar"); + } else { + $query = "SELECT e.guid FROM {$CONFIG->dbprefix}access_collection_membership m JOIN {$CONFIG->dbprefix}entities e ON e.guid = m.user_guid WHERE m.access_collection_id = {$collection}"; + $collection_members = get_data($query); + foreach($collection_members as $key => $val) + $collection_members[$key] = $val->guid; + } + + return $collection_members; + + } + + /** + * Displays a user's access collections, using the friends/collections view + * + * @param int $owner_guid The GUID of the owning user + * @return string A formatted rendition of the collections + */ + function elgg_view_access_collections($owner_guid) { + + if ($collections = get_user_access_collections($owner_guid)) { + + foreach($collections as $key => $collection) { + $collections[$key]->members = get_members_of_access_collection($collection->id, true); + $collections[$key]->entities = get_user_friends($owner_guid,"",9999); + } + + } + + return elgg_view('friends/collections',array('collections' => $collections)); + + } + + /** + * Get entities with the specified access collection id. + * + * @param $collection_id + * @param $entity_type + * @param $entity_subtype + * @param $owner_guid + * @param $limit + * @param $offset + * @param $order_by + * @param $site_guid + * @param $count + * @return unknown_type + */ + function get_entities_from_access_collection($collection_id, $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $order_by = "", $site_guid = 0, $count = false) { + global $CONFIG; + + if (!$collection_id) + return false; + + $entity_type = sanitise_string($entity_type); + $entity_subtype = get_subtype_id($entity_type, $entity_subtype); + $limit = (int)$limit; + $offset = (int)$offset; + if ($order_by == "") + $order_by = "e.time_created desc"; + else + $order_by = "e.time_created, {$order_by}"; + $order_by = sanitise_string($order_by); + $site_guid = (int) $site_guid; + if ((is_array($owner_guid) && (count($owner_guid)))) { + foreach($owner_guid as $key => $guid) { + $owner_guid[$key] = (int) $guid; + } + } else { + $owner_guid = (int) $owner_guid; + } + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + //$access = get_access_list(); + + $where = array("e.access_id = $collection_id"); + + if ($entity_type!=="") + $where[] = "e.type='$entity_type'"; + if ($entity_subtype) + $where[] = "e.subtype=$entity_subtype"; + if ($site_guid > 0) + $where[] = "e.site_guid = {$site_guid}"; + if (is_array($owner_guid)) { + $where[] = "e.container_guid in (".implode(",",$owner_guid).")"; + } else if ($owner_guid > 0) + $where[] = "e.container_guid = {$owner_guid}"; + + if (!$count) { + $query = "SELECT distinct e.* "; + } else { + $query = "SELECT count(distinct e.guid) as total "; + } + + $query .= "from {$CONFIG->dbprefix}entities e where"; + foreach ($where as $w) + $query .= " $w and "; + $query .= get_access_sql_suffix("e"); // Add access controls + //$query .= ' and ' . get_access_sql_suffix("m"); // Add access controls + + if (!$count) { + $query .= " order by $order_by limit $offset, $limit"; // Add order and limit + return get_data($query, "entity_row_to_elggstar"); + } else { + if ($row = get_data_row($query)) + return $row->total; + } + return false; + } + + /** + * Lists entities from an access collection + * + * @param $collection_id + * @param $entity_type + * @param $entity_subtype + * @param $owner_guid + * @param $limit + * @param $fullview + * @param $viewtypetoggle + * @param $pagination + * @return str + */ + function list_entities_from_access_collection($collection_id, $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true) { + $offset = (int) get_input('offset'); + $limit = (int) $limit; + $count = get_entities_from_access_collection($collection_id, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", 0, true); + $entities = get_entities_from_access_collection($collection_id, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", 0, false); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); + } + + global $init_finished; + $init_finished = false; + + /** + * A quick and dirty way to make sure the access permissions have been correctly set up + * + */ + function access_init() { + global $init_finished; + $init_finished = true; + } + + // This function will let us know when 'init' has finished + register_elgg_event_handler('init','system','access_init',9999); + ?> \ No newline at end of file diff --git a/engine/lib/activity.php b/engine/lib/activity.php index 2528f2d3c..10374e386 100644 --- a/engine/lib/activity.php +++ b/engine/lib/activity.php @@ -1,154 +1,154 @@ -owner_guid" - * @return array An array of system log entries. - */ - function get_activity_stream_data($limit = 10, $offset = 0, $type = "", $subtype = "", $owner_guid = "", $owner_relationship = "") - { - global $CONFIG; - - $limit = (int)$limit; - $offset = (int)$offset; - - if ($type) { - if (!is_array($type)) - $type = array(sanitise_string($type)); - else - foreach ($type as $k => $v) - $type[$k] = sanitise_string($v); - } - - if ($subtype) { - if (!is_array($subtype)) - $subtype = array(sanitise_string($subtype)); - else - foreach ($subtype as $k => $v) - $subtype[$k] = sanitise_string($v); - } - - if ($owner_guid) { - if (is_array($owner_guid)) - foreach ($owner_guid as $k => $v) - $owner_guid[$k] = (int)$v; - else - $owner_guid = array((int)$owner_guid); - } - - $owner_relationship = sanitise_string($owner_relationship); - - // Get a list of possible views - $activity_events= array(); - $activity_views = array_merge(elgg_view_tree('activity', 'default'), elgg_view_tree('river', 'default')); // Join activity with river - - $done = array(); - - foreach ($activity_views as $view) - { - $fragments = explode('/', $view); - $tmp = explode('/',$view, 2); - $tmp = $tmp[1]; - - if ((isset($fragments[0])) && (($fragments[0] == 'river') || ($fragments[0] == 'activity')) - && (!in_array($tmp, $done))) - { - if (isset($fragments[1])) - { - $f = array(); - for ($n = 1; $n < count($fragments); $n++) - { - $val = sanitise_string($fragments[$n]); - switch($n) - { - case 1: $key = 'type'; break; - case 2: $key = 'subtype'; break; - case 3: $key = 'event'; break; - } - $f[$key] = $val; - } - - // Filter result based on parameters - $add = true; - if ($type) { - if (!in_array($f['type'], $type)) $add = false; - } - if (($add) && ($subtype)) { - if (!in_array($f['subtype'], $subtype)) $add = false; - } - if (($add) && ($event)) { - if (!in_array($f['event'], $event)) $add = false; - } - - if ($add) - $activity_events[] = $f; - } - - $done[] = $tmp; - } - - - } - - $n = 0; - foreach ($activity_events as $details) - { - // Get what we're talking about - - if ($details['subtype'] == 'default') $details['subtype'] = ''; - - if (($details['type']) && ($details['event'])) { - if ($n>0) $obj_query .= " or "; - - $access = ""; - if ($details['type']!='relationship') - $access = " and " . get_access_sql_suffix('sl'); - - $obj_query .= "( sl.object_type='{$details['type']}' and sl.object_subtype='{$details['subtype']}' and sl.event='{$details['event']}' $access )"; - - $n++; - } - - } - - // User - if ((count($owner_guid)) && ($owner_guid[0]!=0)) { - $user = " and sl.performed_by_guid in (".implode(',', $owner_guid).")"; - - if ($owner_relationship) - { - $friendsarray = ""; - if ($friends = get_entities_from_relationship($owner_relationship,$owner_guid[0],false,"user",$subtype,0,"time_created desc",9999)) { - $friendsarray = array(); - foreach($friends as $friend) { - $friendsarray[] = $friend->getGUID(); - } - - $user = " and sl.performed_by_guid in (".implode(',', $friendsarray).")"; - } - - } - } - - $query = "SELECT sl.* from {$CONFIG->dbprefix}system_log sl where 1 $user and ($obj_query) order by sl.time_created desc limit $offset, $limit"; - return get_data($query); - } + * @link http://elgg.org/ + */ + + /** + * Construct and execute the query required for the activity stream. + * + * @param int $limit Limit the query. + * @param int $offset Execute from the given object + * @param mixed $type A type, or array of types to look for. Note: This is how they appear in the SYSTEM LOG. + * @param mixed $subtype A subtype, or array of types to look for. Note: This is how they appear in the SYSTEM LOG. + * @param mixed $owner_guid The guid or a collection of GUIDs + * @param string $owner_relationship If defined, the relationship between $owner_guid and the entity owner_guid - so "is $owner_guid $owner_relationship with $entity->owner_guid" + * @return array An array of system log entries. + */ + function get_activity_stream_data($limit = 10, $offset = 0, $type = "", $subtype = "", $owner_guid = "", $owner_relationship = "") + { + global $CONFIG; + + $limit = (int)$limit; + $offset = (int)$offset; + + if ($type) { + if (!is_array($type)) + $type = array(sanitise_string($type)); + else + foreach ($type as $k => $v) + $type[$k] = sanitise_string($v); + } + + if ($subtype) { + if (!is_array($subtype)) + $subtype = array(sanitise_string($subtype)); + else + foreach ($subtype as $k => $v) + $subtype[$k] = sanitise_string($v); + } + + if ($owner_guid) { + if (is_array($owner_guid)) + foreach ($owner_guid as $k => $v) + $owner_guid[$k] = (int)$v; + else + $owner_guid = array((int)$owner_guid); + } + + $owner_relationship = sanitise_string($owner_relationship); + + // Get a list of possible views + $activity_events= array(); + $activity_views = array_merge(elgg_view_tree('activity', 'default'), elgg_view_tree('river', 'default')); // Join activity with river + + $done = array(); + + foreach ($activity_views as $view) + { + $fragments = explode('/', $view); + $tmp = explode('/',$view, 2); + $tmp = $tmp[1]; + + if ((isset($fragments[0])) && (($fragments[0] == 'river') || ($fragments[0] == 'activity')) + && (!in_array($tmp, $done))) + { + if (isset($fragments[1])) + { + $f = array(); + for ($n = 1; $n < count($fragments); $n++) + { + $val = sanitise_string($fragments[$n]); + switch($n) + { + case 1: $key = 'type'; break; + case 2: $key = 'subtype'; break; + case 3: $key = 'event'; break; + } + $f[$key] = $val; + } + + // Filter result based on parameters + $add = true; + if ($type) { + if (!in_array($f['type'], $type)) $add = false; + } + if (($add) && ($subtype)) { + if (!in_array($f['subtype'], $subtype)) $add = false; + } + if (($add) && ($event)) { + if (!in_array($f['event'], $event)) $add = false; + } + + if ($add) + $activity_events[] = $f; + } + + $done[] = $tmp; + } + + + } + + $n = 0; + foreach ($activity_events as $details) + { + // Get what we're talking about + + if ($details['subtype'] == 'default') $details['subtype'] = ''; + + if (($details['type']) && ($details['event'])) { + if ($n>0) $obj_query .= " or "; + + $access = ""; + if ($details['type']!='relationship') + $access = " and " . get_access_sql_suffix('sl'); + + $obj_query .= "( sl.object_type='{$details['type']}' and sl.object_subtype='{$details['subtype']}' and sl.event='{$details['event']}' $access )"; + + $n++; + } + + } + + // User + if ((count($owner_guid)) && ($owner_guid[0]!=0)) { + $user = " and sl.performed_by_guid in (".implode(',', $owner_guid).")"; + + if ($owner_relationship) + { + $friendsarray = ""; + if ($friends = get_entities_from_relationship($owner_relationship,$owner_guid[0],false,"user",$subtype,0,"time_created desc",9999)) { + $friendsarray = array(); + foreach($friends as $friend) { + $friendsarray[] = $friend->getGUID(); + } + + $user = " and sl.performed_by_guid in (".implode(',', $friendsarray).")"; + } + + } + } + + $query = "SELECT sl.* from {$CONFIG->dbprefix}system_log sl where 1 $user and ($obj_query) order by sl.time_created desc limit $offset, $limit"; + return get_data($query); + } ?> \ No newline at end of file diff --git a/engine/lib/admin.php b/engine/lib/admin.php index a8272dc83..f09167bfa 100644 --- a/engine/lib/admin.php +++ b/engine/lib/admin.php @@ -1,177 +1,177 @@ -wwwroot . 'pg/admin/statistics/'); - add_submenu_item(elgg_echo('admin:site'), $CONFIG->wwwroot . 'pg/admin/site/'); - add_submenu_item(elgg_echo('admin:user'), $CONFIG->wwwroot . 'pg/admin/user/'); - add_submenu_item(elgg_echo('admin:plugins'), $CONFIG->wwwroot . 'pg/admin/plugins/'); - - } - - } - - function admin_settings_page_handler($page) - { - global $CONFIG; - - $path = $CONFIG->path . "admin/index.php"; - - if ($page[0]) - { - switch ($page[0]) - { - case 'user' : $path = $CONFIG->path . "admin/user.php"; break; - case 'statistics' : $path = $CONFIG->path . "admin/statistics.php"; break; - case 'plugins' : $path = $CONFIG->path . "admin/plugins.php"; break; - case 'site' : $path = $CONFIG->path . "admin/site.php"; break; - } - } - - if ($page[1]) - set_input('username', $page[1]); - - include($path); - } - - - /** - * Admin permissions system - * - * @return true|null True if the current user is an admin. - */ - function admin_permissions($hook, $type, $returnval, $params) { - - if (is_array($params) && !empty($params['user']) && $params['user'] instanceof ElggUser) { - $admin = $params['user']->admin; - if ($admin) { - return true; - } - } - - } - - /** - * Write a persistent message to the administrator's notification window. - * - * Currently this writes a message to the admin store, we may want to come up with another way at some point. - * - * @param string $subject Subject of the message - * @param string $message Body of the message - */ - function send_admin_message($subject, $message) - { - $subject = sanitise_string($subject); - $message = sanitise_string($message); - - if (($subject) && ($message)) - { - $admin_message = new ElggObject(); - $admin_message->subtype = 'admin_message'; - $admin_message->access_id = ACCESS_PUBLIC; - $admin_message->title = $subject; - $admin_message->description = $message; - - return $admin_message->save(); - } - - return false; - } - - /** - * List all admin messages. - * - * @param int $limit Limit - */ - function list_admin_messages($limit = 10) - { - return list_entities('object','admin_message',0,$limit); - } - - /** - * Remove an admin message. - * - * @param int $guid The - */ - function clear_admin_message($guid) - { - return delete_entity($guid); - } - - /// Register init functions - register_elgg_event_handler('init','system','admin_init'); - register_elgg_event_handler('pagesetup','system','admin_pagesetup'); - - // Register a plugin hook for permissions - register_plugin_hook('permissions_check','all','admin_permissions'); - register_plugin_hook('container_permissions_check','all','admin_permissions'); - -?> + register_action('admin/user/removeadmin', false, "", true); + + // Register some actions + register_action('admin/site/update_basic', false, "", true); // Register basic site admin action + + // Page handler + register_page_handler('admin','admin_settings_page_handler'); + + if (isadminloggedin()) { + global $is_admin; + $is_admin = true; + } + + } + + function admin_pagesetup() { + + if (get_context() == 'admin') { + + global $CONFIG; + add_submenu_item(elgg_echo('admin:statistics'), $CONFIG->wwwroot . 'pg/admin/statistics/'); + add_submenu_item(elgg_echo('admin:site'), $CONFIG->wwwroot . 'pg/admin/site/'); + add_submenu_item(elgg_echo('admin:user'), $CONFIG->wwwroot . 'pg/admin/user/'); + add_submenu_item(elgg_echo('admin:plugins'), $CONFIG->wwwroot . 'pg/admin/plugins/'); + + } + + } + + function admin_settings_page_handler($page) + { + global $CONFIG; + + $path = $CONFIG->path . "admin/index.php"; + + if ($page[0]) + { + switch ($page[0]) + { + case 'user' : $path = $CONFIG->path . "admin/user.php"; break; + case 'statistics' : $path = $CONFIG->path . "admin/statistics.php"; break; + case 'plugins' : $path = $CONFIG->path . "admin/plugins.php"; break; + case 'site' : $path = $CONFIG->path . "admin/site.php"; break; + } + } + + if ($page[1]) + set_input('username', $page[1]); + + include($path); + } + + + /** + * Admin permissions system + * + * @return true|null True if the current user is an admin. + */ + function admin_permissions($hook, $type, $returnval, $params) { + + if (is_array($params) && !empty($params['user']) && $params['user'] instanceof ElggUser) { + $admin = $params['user']->admin; + if ($admin) { + return true; + } + } + + } + + /** + * Write a persistent message to the administrator's notification window. + * + * Currently this writes a message to the admin store, we may want to come up with another way at some point. + * + * @param string $subject Subject of the message + * @param string $message Body of the message + */ + function send_admin_message($subject, $message) + { + $subject = sanitise_string($subject); + $message = sanitise_string($message); + + if (($subject) && ($message)) + { + $admin_message = new ElggObject(); + $admin_message->subtype = 'admin_message'; + $admin_message->access_id = ACCESS_PUBLIC; + $admin_message->title = $subject; + $admin_message->description = $message; + + return $admin_message->save(); + } + + return false; + } + + /** + * List all admin messages. + * + * @param int $limit Limit + */ + function list_admin_messages($limit = 10) + { + return list_entities('object','admin_message',0,$limit); + } + + /** + * Remove an admin message. + * + * @param int $guid The + */ + function clear_admin_message($guid) + { + return delete_entity($guid); + } + + /// Register init functions + register_elgg_event_handler('init','system','admin_init'); + register_elgg_event_handler('pagesetup','system','admin_pagesetup'); + + // Register a plugin hook for permissions + register_plugin_hook('permissions_check','all','admin_permissions'); + register_plugin_hook('container_permissions_check','all','admin_permissions'); + +?> diff --git a/engine/lib/api.php b/engine/lib/api.php index a8e8549fc..3f5cd198f 100644 --- a/engine/lib/api.php +++ b/engine/lib/api.php @@ -259,7 +259,7 @@ /** * Clean out old stuff. * - */ + */ public function __destruct() { global $CONFIG; @@ -270,7 +270,7 @@ $expires = $time-$age; delete_data("DELETE from {$CONFIG->dbprefix}hmac_cache where ts<$expires"); - } + } } // API Call functions ///////////////////////////////////////////////////////////////////// diff --git a/engine/lib/configuration.php b/engine/lib/configuration.php index 0317c821c..9aa5d2174 100644 --- a/engine/lib/configuration.php +++ b/engine/lib/configuration.php @@ -1,17 +1,17 @@ -dbprefix}config where name='$name' and site_guid=$site_guid"); } - - /** - * Sets a configuration value - * - * @param string $name The name of the configuration value - * @param string $value Its value - * @param int $site_guid Optionally, the GUID of the site (current site is assumed by default) - * @return false|int 1 or false depending on success or failure - */ - function set_config($name, $value, $site_guid = 0) { - + + /** + * Sets a configuration value + * + * @param string $name The name of the configuration value + * @param string $value Its value + * @param int $site_guid Optionally, the GUID of the site (current site is assumed by default) + * @return false|int 1 or false depending on success or failure + */ + function set_config($name, $value, $site_guid = 0) { + global $CONFIG; // Unset existing unset_config($name,$site_guid); - - $name = mysql_real_escape_string($name); - $value = mysql_real_escape_string($value); - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = (int) $CONFIG->site_id; - $CONFIG->$name = $value; + + $name = mysql_real_escape_string($name); + $value = mysql_real_escape_string($value); + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = (int) $CONFIG->site_id; + $CONFIG->$name = $value; $value = sanitise_string(serialize($value)); - - return insert_data("insert into {$CONFIG->dbprefix}config set name = '{$name}', value = '{$value}', site_guid = {$site_guid}"); - - } - - /** - * Gets a configuration value - * - * @param string $name The name of the config value - * @param int $site_guid Optionally, the GUID of the site (current site is assumed by default) - * @return mixed|false Depending on success - */ - function get_config($name, $site_guid = 0) { - - global $CONFIG; - if (isset($CONFIG->$name)) - return $CONFIG->$name; - $name = mysql_real_escape_string($name); - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = (int) $CONFIG->site_id; - if ($result = get_data_row("SELECT value from {$CONFIG->dbprefix}config where name = '{$name}' and site_guid = {$site_guid}")) { - $result = $result->value; - $result = unserialize($result->value); - $CONFIG->$name = $result; - return $result; - } - return false; - + + return insert_data("insert into {$CONFIG->dbprefix}config set name = '{$name}', value = '{$value}', site_guid = {$site_guid}"); + + } + + /** + * Gets a configuration value + * + * @param string $name The name of the config value + * @param int $site_guid Optionally, the GUID of the site (current site is assumed by default) + * @return mixed|false Depending on success + */ + function get_config($name, $site_guid = 0) { + + global $CONFIG; + if (isset($CONFIG->$name)) + return $CONFIG->$name; + $name = mysql_real_escape_string($name); + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = (int) $CONFIG->site_id; + if ($result = get_data_row("SELECT value from {$CONFIG->dbprefix}config where name = '{$name}' and site_guid = {$site_guid}")) { + $result = $result->value; + $result = unserialize($result->value); + $CONFIG->$name = $result; + return $result; + } + return false; + } /** @@ -110,28 +110,28 @@ return true; } return false; - } - - /** - * If certain configuration elements don't exist, autodetect sensible defaults - * - * @uses $CONFIG The main configuration global - * - */ - function set_default_config() { - - global $CONFIG; - if (empty($CONFIG->path)) - $CONFIG->path = str_replace("\\","/",dirname(dirname(dirname(__FILE__)))) . "/"; - - if (empty($CONFIG->viewpath)) - $CONFIG->viewpath = $CONFIG->path . "views/"; - - if (empty($CONFIG->pluginspath)) - $CONFIG->pluginspath = $CONFIG->path . "mod/"; - - if (empty($CONFIG->wwwroot)) { - /* + } + + /** + * If certain configuration elements don't exist, autodetect sensible defaults + * + * @uses $CONFIG The main configuration global + * + */ + function set_default_config() { + + global $CONFIG; + if (empty($CONFIG->path)) + $CONFIG->path = str_replace("\\","/",dirname(dirname(dirname(__FILE__)))) . "/"; + + if (empty($CONFIG->viewpath)) + $CONFIG->viewpath = $CONFIG->path . "views/"; + + if (empty($CONFIG->pluginspath)) + $CONFIG->pluginspath = $CONFIG->path . "mod/"; + + if (empty($CONFIG->wwwroot)) { + /* $CONFIG->wwwroot = "http://" . $_SERVER['SERVER_NAME']; $request = $_SERVER['REQUEST_URI']; @@ -142,72 +142,72 @@ } $CONFIG->wwwroot .= $request; - */ - $pathpart = str_replace("//","/",str_replace($_SERVER['DOCUMENT_ROOT'],"",$CONFIG->path)); - if (substr($pathpart,0,1) != "/") $pathpart = "/" . $pathpart; + */ + $pathpart = str_replace("//","/",str_replace($_SERVER['DOCUMENT_ROOT'],"",$CONFIG->path)); + if (substr($pathpart,0,1) != "/") $pathpart = "/" . $pathpart; $CONFIG->wwwroot = "http://" . $_SERVER['HTTP_HOST'] . $pathpart; - - } - - if (empty($CONFIG->url)) - $CONFIG->url = $CONFIG->wwwroot; - - if (empty($CONFIG->sitename)) - $CONFIG->sitename = "New Elgg site"; + + } + + if (empty($CONFIG->url)) + $CONFIG->url = $CONFIG->wwwroot; + + if (empty($CONFIG->sitename)) + $CONFIG->sitename = "New Elgg site"; if (empty($CONFIG->language)) $CONFIG->language = "en"; - - } - - /** - * Function that provides some config initialisation on system init - * - */ - - function configuration_init() { - - global $CONFIG; - + + } + + /** + * Function that provides some config initialisation on system init + * + */ + + function configuration_init() { + + global $CONFIG; + if (is_installed() || is_db_installed()) { - - $path = datalist_get('path'); - if (!empty($path)) - $CONFIG->path = $path; - $dataroot = datalist_get('dataroot'); - if (!empty($dataroot)) - $CONFIG->dataroot = $dataroot; - $simplecache_enabled = datalist_get('simplecache_enabled'); - if ($simplecache_enabled !== false) { - $CONFIG->simplecache_enabled = $simplecache_enabled; - } else { - $CONFIG->simplecache_enabled = 1; + + $path = datalist_get('path'); + if (!empty($path)) + $CONFIG->path = $path; + $dataroot = datalist_get('dataroot'); + if (!empty($dataroot)) + $CONFIG->dataroot = $dataroot; + $simplecache_enabled = datalist_get('simplecache_enabled'); + if ($simplecache_enabled !== false) { + $CONFIG->simplecache_enabled = $simplecache_enabled; + } else { + $CONFIG->simplecache_enabled = 1; } $viewpath_cache_enabled = datalist_get('viewpath_cache_enabled'); if ($viewpath_cache_enabled !== false) { $CONFIG->viewpath_cache_enabled = $viewpath_cache_enabled; } else { $CONFIG->viewpath_cache_enabled = 1; - } - if (isset($CONFIG->site) && ($CONFIG->site instanceof ElggSite)) { - $CONFIG->wwwroot = $CONFIG->site->url; + } + if (isset($CONFIG->site) && ($CONFIG->site instanceof ElggSite)) { + $CONFIG->wwwroot = $CONFIG->site->url; $CONFIG->sitename = $CONFIG->site->name; $CONFIG->sitedescription = $CONFIG->site->description; - $CONFIG->siteemail = $CONFIG->site->email; - } - $CONFIG->url = $CONFIG->wwwroot; + $CONFIG->siteemail = $CONFIG->site->email; + } + $CONFIG->url = $CONFIG->wwwroot; // Load default settings from database get_all_config(); - - return true; - } - } - - /** - * Register config_init - */ - - register_elgg_event_handler('boot','system','configuration_init',10); - + + return true; + } + } + + /** + * Register config_init + */ + + register_elgg_event_handler('boot','system','configuration_init',10); + ?> \ No newline at end of file diff --git a/engine/lib/database.php b/engine/lib/database.php index 8b154eefe..fa3a91fbb 100644 --- a/engine/lib/database.php +++ b/engine/lib/database.php @@ -1,60 +1,60 @@ -db[$dblinkname])) { - if (is_array($CONFIG->db[$dblinkname])) { - $index = rand(0,sizeof($CONFIG->db[$dblinkname])); - $dbhost = $CONFIG->db[$dblinkname][$index]->dbhost; - $dbuser = $CONFIG->db[$dblinkname][$index]->dbuser; - $dbpass = $CONFIG->db[$dblinkname][$index]->dbpass; - $dbname = $CONFIG->db[$dblinkname][$index]->dbname; - } else { - $dbhost = $CONFIG->db[$dblinkname]->dbhost; - $dbuser = $CONFIG->db[$dblinkname]->dbuser; - $dbpass = $CONFIG->db[$dblinkname]->dbpass; - $dbname = $CONFIG->db[$dblinkname]->dbname; - } - } else { - $dbhost = $CONFIG->dbhost; - $dbuser = $CONFIG->dbuser; - $dbpass = $CONFIG->dbpass; - $dbname = $CONFIG->dbname; - } - - // Connect to database - if (!$dblink[$dblinkname] = mysql_connect($CONFIG->dbhost, $CONFIG->dbuser, $CONFIG->dbpass, true)) - throw new DatabaseException(sprintf(elgg_echo('DatabaseException:WrongCredentials'), $CONFIG->dbuser, $CONFIG->dbhost, $CONFIG->debug ? $CONFIG->dbpass : "****")); - if (!mysql_select_db($CONFIG->dbname, $dblink[$dblinkname])) - throw new DatabaseException(sprintf(elgg_echo('DatabaseException:NoConnect'), $CONFIG->dbname)); + + /** + * Connect to the database server and use the Elgg database for a particular database link + * + * @param string $dblinkname Default "readwrite"; you can change this to set up additional global database links, eg "read" and "write" + */ + function establish_db_link($dblinkname = "readwrite") { + + // Get configuration, and globalise database link + global $CONFIG, $dblink, $DB_QUERY_CACHE, $dbcalls; + + if (!isset($dblink)) { + $dblink = array(); + } + + if ($dblinkname != "readwrite" && isset($CONFIG->db[$dblinkname])) { + if (is_array($CONFIG->db[$dblinkname])) { + $index = rand(0,sizeof($CONFIG->db[$dblinkname])); + $dbhost = $CONFIG->db[$dblinkname][$index]->dbhost; + $dbuser = $CONFIG->db[$dblinkname][$index]->dbuser; + $dbpass = $CONFIG->db[$dblinkname][$index]->dbpass; + $dbname = $CONFIG->db[$dblinkname][$index]->dbname; + } else { + $dbhost = $CONFIG->db[$dblinkname]->dbhost; + $dbuser = $CONFIG->db[$dblinkname]->dbuser; + $dbpass = $CONFIG->db[$dblinkname]->dbpass; + $dbname = $CONFIG->db[$dblinkname]->dbname; + } + } else { + $dbhost = $CONFIG->dbhost; + $dbuser = $CONFIG->dbuser; + $dbpass = $CONFIG->dbpass; + $dbname = $CONFIG->dbname; + } + + // Connect to database + if (!$dblink[$dblinkname] = mysql_connect($CONFIG->dbhost, $CONFIG->dbuser, $CONFIG->dbpass, true)) + throw new DatabaseException(sprintf(elgg_echo('DatabaseException:WrongCredentials'), $CONFIG->dbuser, $CONFIG->dbhost, $CONFIG->debug ? $CONFIG->dbpass : "****")); + if (!mysql_select_db($CONFIG->dbname, $dblink[$dblinkname])) + throw new DatabaseException(sprintf(elgg_echo('DatabaseException:NoConnect'), $CONFIG->dbname)); // Set up cache if ((!$DB_QUERY_CACHE) && (!$CONFIG->db_disable_query_cache)) @@ -62,29 +62,29 @@ //$DB_QUERY_CACHE = select_default_memcache('db_query_cache'); //array(); //if ($DB_QUERY_CACHE instanceof ElggMemcache) - // $DB_QUERY_CACHE->setDefaultExpiry(30); - } - - /** - * Establish all database connections - * - * If the configuration has been set up for multiple read/write databases, set those - * links up separately; otherwise just create the one database link - * - */ - - function setup_db_connections() { - - // Get configuration and globalise database link - global $CONFIG, $dblink; - - if (!empty($CONFIG->db->split)) { - establish_db_link('read'); - establish_db_link('write'); - } else { - establish_db_link('readwrite'); - } - + // $DB_QUERY_CACHE->setDefaultExpiry(30); + } + + /** + * Establish all database connections + * + * If the configuration has been set up for multiple read/write databases, set those + * links up separately; otherwise just create the one database link + * + */ + + function setup_db_connections() { + + // Get configuration and globalise database link + global $CONFIG, $dblink; + + if (!empty($CONFIG->db->split)) { + establish_db_link('read'); + establish_db_link('write'); + } else { + establish_db_link('readwrite'); + } + } /** @@ -125,43 +125,43 @@ if (isset($CONFIG->debug) && $CONFIG->debug) error_log($e); } } - } - - /** - * Alias to setup_db_connections, for use in the event handler - * - * @param string $event The event type - * @param string $object_type The object type - * @param mixed $object Used for nothing in this context - */ + } + + /** + * Alias to setup_db_connections, for use in the event handler + * + * @param string $event The event type + * @param string $object_type The object type + * @param mixed $object Used for nothing in this context + */ function init_db($event, $object_type, $object = null) { register_shutdown_function('db_delayedexecution_shutdown_hook'); - register_shutdown_function('db_profiling_shutdown_hook'); - //setup_db_connections(); // [Marcus Povey 20090213: Db connection moved to first db connection attempt] - return true; - } - - /** - * Gets the appropriate db link for the operation mode requested - * - * @param string $dblinktype The type of link we want - "read", "write" or "readwrite" (the default) - * @return object Database link - */ - function get_db_link($dblinktype) { - - global $dblink; - - - if (isset($dblink[$dblinktype])) { - return $dblink[$dblinktype]; - } else if (isset($dblink['readwrite'])) { - return $dblink['readwrite']; - } - else - { - setup_db_connections(); - return get_db_link($dblinktype); - } + register_shutdown_function('db_profiling_shutdown_hook'); + //setup_db_connections(); // [Marcus Povey 20090213: Db connection moved to first db connection attempt] + return true; + } + + /** + * Gets the appropriate db link for the operation mode requested + * + * @param string $dblinktype The type of link we want - "read", "write" or "readwrite" (the default) + * @return object Database link + */ + function get_db_link($dblinktype) { + + global $dblink; + + + if (isset($dblink[$dblinktype])) { + return $dblink[$dblinktype]; + } else if (isset($dblink['readwrite'])) { + return $dblink['readwrite']; + } + else + { + setup_db_connections(); + return get_db_link($dblinktype); + } } /** @@ -185,7 +185,7 @@ */ function execute_query($query, $dblink) { - global $CONFIG, $dbcalls, $DB_PROFILE, $DB_QUERY_CACHE; + global $CONFIG, $dbcalls, $DB_PROFILE, $DB_QUERY_CACHE; $dbcalls++; @@ -244,18 +244,18 @@ * @param string $query The query to execute * @param string $handler The handler if you care about the result. */ - function execute_delayed_read_query($query, $handler = "") { return execute_delayed_query($query, get_db_link('read'), $handler); } - - /** - * Use this function to get data from the database - * @param mixed $query The query being passed. - * @param string $call Optionally, the name of a function to call back to on each row (which takes $row as a single parameter) - * @return array An array of database result objects - */ - - function get_data($query, $callback = "") { - - global $CONFIG, $DB_QUERY_CACHE; + function execute_delayed_read_query($query, $handler = "") { return execute_delayed_query($query, get_db_link('read'), $handler); } + + /** + * Use this function to get data from the database + * @param mixed $query The query being passed. + * @param string $call Optionally, the name of a function to call back to on each row (which takes $row as a single parameter) + * @return array An array of database result objects + */ + + function get_data($query, $callback = "") { + + global $CONFIG, $DB_QUERY_CACHE; // Is cached? if ($DB_QUERY_CACHE) $cached_query = $DB_QUERY_CACHE[$query]; @@ -270,17 +270,17 @@ } $dblink = get_db_link('read'); - - $resultarray = array(); - - if ($result = execute_query("$query", $dblink)) { - while ($row = mysql_fetch_object($result)) { - if (!empty($callback) && is_callable($callback)) { - $row = $callback($row); - } - if ($row) $resultarray[] = $row; - } - } + + $resultarray = array(); + + if ($result = execute_query("$query", $dblink)) { + while ($row = mysql_fetch_object($result)) { + if (!empty($callback) && is_callable($callback)) { + $row = $callback($row); + } + if ($row) $resultarray[] = $row; + } + } if (empty($resultarray)) { if ((isset($CONFIG->debug)) && ($CONFIG->debug==true)) @@ -293,18 +293,18 @@ if ((isset($CONFIG->debug)) && ($CONFIG->debug==true)) error_log("$query results cached"); if ($DB_QUERY_CACHE) $DB_QUERY_CACHE[$query] = $resultarray; - - return $resultarray; - } - - /** - * Use this function to get a single data row from the database - * @param mixed $query The query to run. - * @return object A single database result object - */ - - function get_data_row($query, $callback = "") { - + + return $resultarray; + } + + /** + * Use this function to get a single data row from the database + * @param mixed $query The query to run. + * @return object A single database result object + */ + + function get_data_row($query, $callback = "") { + global $CONFIG, $DB_QUERY_CACHE; // Is cached @@ -317,10 +317,10 @@ return false; // Last time this query returned nothing, so return false return $cached_query; - } - + } + $dblink = get_db_link('read'); - + if ($result = execute_query("$query", $dblink)) { $row = mysql_fetch_object($result); @@ -333,127 +333,127 @@ if (!empty($callback) && is_callable($callback)) { $row = $callback($row); } - - if ($row) return $row; + + if ($row) return $row; } if ((isset($CONFIG->debug)) && ($CONFIG->debug==true)) error_log("WARNING: DB query \"$query\" returned no results."); - - return false; - } - - /** - * Use this function to insert database data; returns id or false - * - * @param mixed $query The query to run. - * @return int $id the database id of the inserted row. - */ - - function insert_data($query) { - - global $CONFIG, $DB_QUERY_CACHE; - - $dblink = get_db_link('write'); + + return false; + } + + /** + * Use this function to insert database data; returns id or false + * + * @param mixed $query The query to run. + * @return int $id the database id of the inserted row. + */ + + function insert_data($query) { + + global $CONFIG, $DB_QUERY_CACHE; + + $dblink = get_db_link('write'); // Invalidate query cache if ($DB_QUERY_CACHE) $DB_QUERY_CACHE->clear(); if ((isset($CONFIG->debug)) && ($CONFIG->debug==true)) - error_log("Query cache invalidated"); - - if (execute_query("$query", $dblink)) + error_log("Query cache invalidated"); + + if (execute_query("$query", $dblink)) return mysql_insert_id($dblink); - return false; - } - - /** - * Update database data - * - * @param mixed $query The query to run. - * @return int|false Either the number of affected rows, or false on failure - */ - - function update_data($query) { - - global $CONFIG, $DB_QUERY_CACHE; - + return false; + } + + /** + * Update database data + * + * @param mixed $query The query to run. + * @return int|false Either the number of affected rows, or false on failure + */ + + function update_data($query) { + + global $CONFIG, $DB_QUERY_CACHE; + $dblink = get_db_link('write'); // Invalidate query cache if ($DB_QUERY_CACHE) $DB_QUERY_CACHE->clear(); if ((isset($CONFIG->debug)) && ($CONFIG->debug==true)) - error_log("Query cache invalidated"); - - if (execute_query("$query", $dblink)) + error_log("Query cache invalidated"); + + if (execute_query("$query", $dblink)) return true; //return mysql_affected_rows(); - - return false; - - } - - /** - * Use this function to delete data - * - * @param mixed $query The SQL query to run - * @return int|false Either the number of affected rows, or false on failure - */ - - function delete_data($query) { - - global $CONFIG, $DB_QUERY_CACHE; - - $dblink = get_db_link('write'); + + return false; + + } + + /** + * Use this function to delete data + * + * @param mixed $query The SQL query to run + * @return int|false Either the number of affected rows, or false on failure + */ + + function delete_data($query) { + + global $CONFIG, $DB_QUERY_CACHE; + + $dblink = get_db_link('write'); // Invalidate query cache if ($DB_QUERY_CACHE) $DB_QUERY_CACHE->clear(); if ((isset($CONFIG->debug)) && ($CONFIG->debug==true)) error_log("Query cache invalidated"); - - if (execute_query("$query", $dblink)) - return mysql_affected_rows($dblink); + + if (execute_query("$query", $dblink)) + return mysql_affected_rows($dblink); - return false; - } - - - /** - * Get the tables currently installed in the Elgg database - * - * @return array List of tables - */ - function get_db_tables() { - global $CONFIG; - static $tables, $count; - - if (isset($tables)) { - return $tables; - } + return false; + } + + + /** + * Get the tables currently installed in the Elgg database + * + * @return array List of tables + */ + function get_db_tables() { + global $CONFIG; + static $tables, $count; + + if (isset($tables)) { + return $tables; + } - try{ + try{ $result = get_data("show tables like '" . $CONFIG->dbprefix . "%'"); } catch (DatabaseException $d) { // Likely we can't handle an exception here, so just return false. return false; - } - - $tables = array(); - - if (is_array($result) && !empty($result)) { - foreach($result as $row) { - $row = (array) $row; - if (is_array($row) && !empty($row)) - foreach($row as $element) { - $tables[] = $element; - } - } + } + + $tables = array(); + + if (is_array($result) && !empty($result)) { + foreach($result as $row) { + $row = (array) $row; + if (is_array($row) && !empty($row)) + foreach($row as $element) { + $tables[] = $element; + } + } } else - return false; - - return $tables; + return false; + + return $tables; } /** @@ -464,57 +464,57 @@ { $table = sanitise_string($table); return update_data("optimize table $table"); - } - - /** - * Get the last database error for a particular database link - * - * @param database link $dblink - * @return string Database error message - */ - function get_db_error($dblink) { - return mysql_error($dblink); - } - - /** - * Runs a full database script from disk - * - * @uses $CONFIG - * @param string $scriptlocation The full path to the script - */ - function run_sql_script($scriptlocation) { - - if ($script = file_get_contents($scriptlocation)) { - - global $CONFIG; - - $errors = array(); - - $script = preg_replace('/\-\-.*\n/', '', $script); - $sql_statements = preg_split('/;[\n\r]+/', $script); - foreach($sql_statements as $statement) { - $statement = trim($statement); - $statement = str_replace("prefix_",$CONFIG->dbprefix,$statement); - if (!empty($statement)) { - try { - $result = update_data($statement); - } catch (DatabaseException $e) { - $errors[] = $e->getMessage(); - } - } - } - if (!empty($errors)) { - $errortxt = ""; - foreach($errors as $error) - $errortxt .= " {$error};"; - throw new DatabaseException(elgg_echo('DatabaseException:DBSetupIssues') . $errortxt); - } - - } else { - throw new DatabaseException(sprintf(elgg_echo('DatabaseException:ScriptNotFound'), $scriptlocation)); - } - - } + } + + /** + * Get the last database error for a particular database link + * + * @param database link $dblink + * @return string Database error message + */ + function get_db_error($dblink) { + return mysql_error($dblink); + } + + /** + * Runs a full database script from disk + * + * @uses $CONFIG + * @param string $scriptlocation The full path to the script + */ + function run_sql_script($scriptlocation) { + + if ($script = file_get_contents($scriptlocation)) { + + global $CONFIG; + + $errors = array(); + + $script = preg_replace('/\-\-.*\n/', '', $script); + $sql_statements = preg_split('/;[\n\r]+/', $script); + foreach($sql_statements as $statement) { + $statement = trim($statement); + $statement = str_replace("prefix_",$CONFIG->dbprefix,$statement); + if (!empty($statement)) { + try { + $result = update_data($statement); + } catch (DatabaseException $e) { + $errors[] = $e->getMessage(); + } + } + } + if (!empty($errors)) { + $errortxt = ""; + foreach($errors as $error) + $errortxt .= " {$error};"; + throw new DatabaseException(elgg_echo('DatabaseException:DBSetupIssues') . $errortxt); + } + + } else { + throw new DatabaseException(sprintf(elgg_echo('DatabaseException:ScriptNotFound'), $scriptlocation)); + } + + } /** * Upgrade the database schema in an ordered sequence. @@ -526,49 +526,49 @@ * @param int $version The version you are upgrading from (usually given in the Elgg version format of YYYYMMDDXX - see version.php for example) * @param string $fromdir Optional directory to load upgrades from (default: engine/schema/upgrades/) * @return bool - */ - function db_upgrade($version, $fromdir = "") { - - global $CONFIG; - - // Elgg and its database must be installed to upgrade it! + */ + function db_upgrade($version, $fromdir = "") { + + global $CONFIG; + + // Elgg and its database must be installed to upgrade it! if (!is_db_installed() || !is_installed()) return false; - + $version = (int) $version; if (!$fromdir) - $fromdir = $CONFIG->path . 'engine/schema/upgrades/'; - - if ($handle = opendir($fromdir)) { - - $sqlupgrades = array(); - - while ($sqlfile = readdir($handle)) { - - if (!is_dir($fromdir . $sqlfile)) { - if (preg_match('/([0-9]*)\.sql/',$sqlfile,$matches)) { - $sql_version = (int) $matches[1]; - if ($sql_version > $version) { - $sqlupgrades[] = $sqlfile; - } - } - } - - } - - asort($sqlupgrades); - if (sizeof($sqlupgrades) > 0) { - foreach($sqlupgrades as $sqlfile) { - try { - run_sql_script($fromdir . $sqlfile); - } catch (DatabaseException $e) { - error_log($e->getmessage()); - } - } - } - - } + $fromdir = $CONFIG->path . 'engine/schema/upgrades/'; - return true; + if ($handle = opendir($fromdir)) { + + $sqlupgrades = array(); + + while ($sqlfile = readdir($handle)) { + + if (!is_dir($fromdir . $sqlfile)) { + if (preg_match('/([0-9]*)\.sql/',$sqlfile,$matches)) { + $sql_version = (int) $matches[1]; + if ($sql_version > $version) { + $sqlupgrades[] = $sqlfile; + } + } + } + + } + + asort($sqlupgrades); + if (sizeof($sqlupgrades) > 0) { + foreach($sqlupgrades as $sqlfile) { + try { + run_sql_script($fromdir . $sqlfile); + } catch (DatabaseException $e) { + error_log($e->getmessage()); + } + } + } + + } + + return true; } /** @@ -603,52 +603,52 @@ $string = str_replace($extra_escapeable[$n], "\\" . $extra_escapeable[$n], $string); return $string; - } - - /** - * Sanitise a string for database use - * - * @param string $string The string to sanitise - * @return string Sanitised string - */ - function sanitise_string($string) { - return mysql_real_escape_string(trim($string)); - } - - /** - * Wrapper function for alternate English spelling - * - * @param string $string The string to sanitise - * @return string Sanitised string - * @uses sanitise_string - */ - function sanitize_string($string) { - return sanitise_string($string); - } - - /** - * Sanitises an integer for database use - * - * @param int $int - * @return int Sanitised integer - */ - function sanitise_int($int) { - return (int) $int; - } - - /** - * Wrapper function for alternate English spelling - * - * @param int $int - * @return int Sanitised integer - * @uses sanitise_string - */ - function sanitize_int($int) { - return (int) $int; - } - - // Stuff for initialisation - - register_elgg_event_handler('boot','system','init_db',0); - + } + + /** + * Sanitise a string for database use + * + * @param string $string The string to sanitise + * @return string Sanitised string + */ + function sanitise_string($string) { + return mysql_real_escape_string(trim($string)); + } + + /** + * Wrapper function for alternate English spelling + * + * @param string $string The string to sanitise + * @return string Sanitised string + * @uses sanitise_string + */ + function sanitize_string($string) { + return sanitise_string($string); + } + + /** + * Sanitises an integer for database use + * + * @param int $int + * @return int Sanitised integer + */ + function sanitise_int($int) { + return (int) $int; + } + + /** + * Wrapper function for alternate English spelling + * + * @param int $int + * @return int Sanitised integer + * @uses sanitise_string + */ + function sanitize_int($int) { + return (int) $int; + } + + // Stuff for initialisation + + register_elgg_event_handler('boot','system','init_db',0); + ?> \ No newline at end of file diff --git a/engine/lib/elgglib.php b/engine/lib/elgglib.php index 06af14fcb..fc87c1dc1 100644 --- a/engine/lib/elgglib.php +++ b/engine/lib/elgglib.php @@ -131,13 +131,13 @@ /** * Return the location of a given view. * - * @param string $view The view. + * @param string $view The view. * @param string $viewtype The viewtype */ function elgg_get_view_location($view, $viewtype = '') { global $CONFIG; - + if (empty($viewtype)) $viewtype = elgg_get_viewtype(); @@ -162,7 +162,7 @@ * @param string $view The name and location of the view to use * @param array $vars Any variables that the view requires, passed as an array * @param boolean $bypass If set to true, elgg_view will bypass any specified alternative template handler; by default, it will hand off to this if requested (see set_template_handler) - * @param boolean $debug If set to true, the viewer will complain if it can't find a view + * @param boolean $debug If set to true, the viewer will complain if it can't find a view * @param string $viewtype If set, forces the viewtype for the elgg_view call to be this value (default: standard detection) * @return string The HTML content */ @@ -228,7 +228,7 @@ } - // Get the current viewtype + // Get the current viewtype if (empty($viewtype)) $viewtype = elgg_get_viewtype(); @@ -278,7 +278,7 @@ /** * Returns whether the specified view exists * - * @param string $view The view name + * @param string $view The view name * @param string $viewtype If set, forces the viewtype * @return true|false Depending on success */ @@ -286,7 +286,7 @@ global $CONFIG; - // Detect view type + // Detect view type if (empty($viewtype)) $viewtype = elgg_get_viewtype(); @@ -625,14 +625,14 @@ $subtype = $entity->getSubtype(); if (empty($subtype)) { $subtype = $entity_type; } - + $contents = ''; if (elgg_view_exists("{$entity_type}/{$subtype}")) { $contents = elgg_view("{$entity_type}/{$subtype}",array( 'entity' => $entity, 'full' => $full ), $bypass, $debug); - } + } if (empty($contents)) { $contents = elgg_view("{$entity_type}/default",array( 'entity' => $entity, @@ -645,7 +645,7 @@ if ($annotations) $contents .= $annotations; - } + } return $contents; } @@ -2303,7 +2303,7 @@ define('ACCESS_DEFAULT',-1); define('ACCESS_PRIVATE',0); define('ACCESS_LOGGED_IN',1); - define('ACCESS_PUBLIC',2); + define('ACCESS_PUBLIC',2); define('ACCESS_FRIENDS',-2); register_elgg_event_handler('init','system','elgg_init'); diff --git a/engine/lib/entities.php b/engine/lib/entities.php index b8c92ec42..4d2e17b56 100644 --- a/engine/lib/entities.php +++ b/engine/lib/entities.php @@ -1,2750 +1,2750 @@ - + + * @link http://elgg.org/ + */ + + /// Cache objects in order to minimise database access. + $ENTITY_CACHE = NULL; + + /// Cache subtype searches + $SUBTYPE_CACHE = NULL; + + /// Require the locatable interface TODO: Move this into start.php? + require_once('location.php'); + + /** + * ElggEntity The elgg entity superclass + * This class holds methods for accessing the main entities table. + * + * @author Curverider Ltd + * @package Elgg + * @subpackage Core + */ + abstract class ElggEntity implements + Notable, // Calendar interface + Locatable, // Geocoding interface + Exportable, // Allow export of data + Importable, // Allow import of data + Loggable, // Can events related to this object class be logged + Iterator, // Override foreach behaviour + ArrayAccess // Override for array access + { + /** + * The main attributes of an entity. + * Blank entries for all database fields should be created by the constructor. + * Subclasses should add to this in their constructors. + * Any field not appearing in this will be viewed as a + */ + protected $attributes; + + /** + * If set, overrides the value of getURL() + */ + protected $url_override; + + /** + * Icon override, overrides the value of getIcon(). + */ + protected $icon_override; + + /** + * Temporary cache for metadata, permitting meta data access before a guid has obtained. + */ + protected $temp_metadata; + + /** + * Temporary cache for annotations, permitting meta data access before a guid has obtained. + */ + protected $temp_annotations; + + /** + * Initialise the attributes array. + * This is vital to distinguish between metadata and base parameters. + * + * Place your base parameters here. + * + * @return void + */ + protected function initialise_attributes() + { + initialise_entity_cache(); + + // Create attributes array if not already created + if (!is_array($this->attributes)) $this->attributes = array(); + if (!is_array($this->temp_metadata)) $this->temp_metadata = array(); + if (!is_array($this->temp_annotations)) $this->temp_annotations = array(); + + $this->attributes['guid'] = ""; + $this->attributes['type'] = ""; + $this->attributes['subtype'] = ""; + + $this->attributes['owner_guid'] = get_loggedin_userid(); + $this->attributes['container_guid'] = get_loggedin_userid(); + + $this->attributes['site_guid'] = 0; + $this->attributes['access_id'] = ACCESS_PRIVATE; + $this->attributes['time_created'] = ""; + $this->attributes['time_updated'] = ""; + $this->attributes['enabled'] = "yes"; + + // There now follows a bit of a hack + /* Problem: To speed things up, some objects are split over several tables, this means that it requires + * n number of database reads to fully populate an entity. This causes problems for caching and create events + * since it is not possible to tell whether a subclassed entity is complete. + * Solution: We have two counters, one 'tables_split' which tells whatever is interested how many tables + * are going to need to be searched in order to fully populate this object, and 'tables_loaded' which is how + * many have been loaded thus far. + * If the two are the same then this object is complete. + * + * Use: isFullyLoaded() to check + */ + $this->attributes['tables_split'] = 1; + $this->attributes['tables_loaded'] = 0; + } + + /** + * Return the value of a given key. + * If $name is a key field (as defined in $this->attributes) that value is returned, otherwise it will + * then look to see if the value is in this object's metadata. + * + * Q: Why are we not using __get overload here? + * A: Because overload operators cause problems during subclassing, so we put the code here and + * create overloads in subclasses. + * + * @param string $name + * @return mixed Returns the value of a given value, or null. + */ + public function get($name) + { + // See if its in our base attribute + if (isset($this->attributes[$name])) { + return $this->attributes[$name]; + } + + // No, so see if its in the meta data for this entity + $meta = $this->getMetaData($name); + if ($meta) + return $meta; + + // Can't find it, so return null + return null; + } - * @author Curverider Ltd + /** + * Set the value of a given key, replacing it if necessary. + * If $name is a base attribute (as defined in $this->attributes) that value is set, otherwise it will + * set the appropriate item of metadata. + * + * Note: It is important that your class populates $this->attributes with keys for all base attributes, anything + * not in their gets set as METADATA. + * + * Q: Why are we not using __set overload here? + * A: Because overload operators cause problems during subclassing, so we put the code here and + * create overloads in subclasses. + * + * @param string $name + * @param mixed $value + */ + public function set($name, $value) + { + if (array_key_exists($name, $this->attributes)) + { + // Check that we're not trying to change the guid! + if ((array_key_exists('guid', $this->attributes)) && ($name=='guid')) + return false; + + $this->attributes[$name] = $value; + } + else + return $this->setMetaData($name, $value); + + return true; + } + + /** + * Get a given piece of metadata. + * + * @param string $name + */ + public function getMetaData($name) + { + if ((int) ($this->guid) > 0) { + $md = get_metadata_byname($this->getGUID(), $name); + } else { + if (isset($this->temp_metadata[$name])) + return $this->temp_metadata[$name]; + } - * @link http://elgg.org/ - */ - - /// Cache objects in order to minimise database access. - $ENTITY_CACHE = NULL; - - /// Cache subtype searches - $SUBTYPE_CACHE = NULL; - - /// Require the locatable interface TODO: Move this into start.php? - require_once('location.php'); - - /** - * ElggEntity The elgg entity superclass - * This class holds methods for accessing the main entities table. - * - * @author Curverider Ltd - * @package Elgg - * @subpackage Core - */ - abstract class ElggEntity implements - Notable, // Calendar interface - Locatable, // Geocoding interface - Exportable, // Allow export of data - Importable, // Allow import of data - Loggable, // Can events related to this object class be logged - Iterator, // Override foreach behaviour - ArrayAccess // Override for array access - { - /** - * The main attributes of an entity. - * Blank entries for all database fields should be created by the constructor. - * Subclasses should add to this in their constructors. - * Any field not appearing in this will be viewed as a - */ - protected $attributes; - - /** - * If set, overrides the value of getURL() - */ - protected $url_override; - - /** - * Icon override, overrides the value of getIcon(). - */ - protected $icon_override; - - /** - * Temporary cache for metadata, permitting meta data access before a guid has obtained. - */ - protected $temp_metadata; - - /** - * Temporary cache for annotations, permitting meta data access before a guid has obtained. - */ - protected $temp_annotations; - - /** - * Initialise the attributes array. - * This is vital to distinguish between metadata and base parameters. - * - * Place your base parameters here. - * - * @return void - */ - protected function initialise_attributes() - { - initialise_entity_cache(); - - // Create attributes array if not already created - if (!is_array($this->attributes)) $this->attributes = array(); - if (!is_array($this->temp_metadata)) $this->temp_metadata = array(); - if (!is_array($this->temp_annotations)) $this->temp_annotations = array(); - - $this->attributes['guid'] = ""; - $this->attributes['type'] = ""; - $this->attributes['subtype'] = ""; - - $this->attributes['owner_guid'] = get_loggedin_userid(); - $this->attributes['container_guid'] = get_loggedin_userid(); - - $this->attributes['site_guid'] = 0; - $this->attributes['access_id'] = ACCESS_PRIVATE; - $this->attributes['time_created'] = ""; - $this->attributes['time_updated'] = ""; - $this->attributes['enabled'] = "yes"; - - // There now follows a bit of a hack - /* Problem: To speed things up, some objects are split over several tables, this means that it requires - * n number of database reads to fully populate an entity. This causes problems for caching and create events - * since it is not possible to tell whether a subclassed entity is complete. - * Solution: We have two counters, one 'tables_split' which tells whatever is interested how many tables - * are going to need to be searched in order to fully populate this object, and 'tables_loaded' which is how - * many have been loaded thus far. - * If the two are the same then this object is complete. - * - * Use: isFullyLoaded() to check - */ - $this->attributes['tables_split'] = 1; - $this->attributes['tables_loaded'] = 0; - } - - /** - * Return the value of a given key. - * If $name is a key field (as defined in $this->attributes) that value is returned, otherwise it will - * then look to see if the value is in this object's metadata. - * - * Q: Why are we not using __get overload here? - * A: Because overload operators cause problems during subclassing, so we put the code here and - * create overloads in subclasses. - * - * @param string $name - * @return mixed Returns the value of a given value, or null. - */ - public function get($name) - { - // See if its in our base attribute - if (isset($this->attributes[$name])) { - return $this->attributes[$name]; - } - - // No, so see if its in the meta data for this entity - $meta = $this->getMetaData($name); - if ($meta) - return $meta; - - // Can't find it, so return null - return null; - } - - /** - * Set the value of a given key, replacing it if necessary. - * If $name is a base attribute (as defined in $this->attributes) that value is set, otherwise it will - * set the appropriate item of metadata. - * - * Note: It is important that your class populates $this->attributes with keys for all base attributes, anything - * not in their gets set as METADATA. - * - * Q: Why are we not using __set overload here? - * A: Because overload operators cause problems during subclassing, so we put the code here and - * create overloads in subclasses. - * - * @param string $name - * @param mixed $value - */ - public function set($name, $value) - { - if (array_key_exists($name, $this->attributes)) - { - // Check that we're not trying to change the guid! - if ((array_key_exists('guid', $this->attributes)) && ($name=='guid')) - return false; - - $this->attributes[$name] = $value; - } - else - return $this->setMetaData($name, $value); - - return true; - } - - /** - * Get a given piece of metadata. - * - * @param string $name - */ - public function getMetaData($name) - { - if ((int) ($this->guid) > 0) { - $md = get_metadata_byname($this->getGUID(), $name); - } else { - if (isset($this->temp_metadata[$name])) - return $this->temp_metadata[$name]; - } - - if ($md && !is_array($md)) { - return $md->value; - } else if ($md && is_array($md)) { - return metadata_array_to_values($md); - } - - return null; - } - - /** - * Class member get overloading - * - * @param string $name - * @return mixed - */ - function __get($name) { return $this->get($name); } - - /** - * Class member set overloading - * - * @param string $name - * @param mixed $value - * @return mixed - */ - function __set($name, $value) { return $this->set($name, $value); } - - /** - * Supporting isset. - * - * @param string $name The name of the attribute or metadata. - * @return bool - */ - function __isset($name) { if ($this->$name!="") return true; else return false; } - - /** - * Supporting unsetting of magic attributes. - * - * @param string $name The name of the attribute or metadata. - */ - function __unset($name) - { - if (array_key_exists($name, $this->attributes)) - $this->attributes[$name] = ""; - else - $this->clearMetaData($name); - } - - /** - * Set a piece of metadata. - * - * @param string $name - * @param mixed $value - * @param string $value_type - * @param bool $multiple - * @return bool - */ - public function setMetaData($name, $value, $value_type = "", $multiple = false) - { - if (is_array($value)) - { - unset($this->temp_metadata[$name]); - remove_metadata($this->getGUID(), $name); - foreach ($value as $v) { - if ((int) $this->guid > 0) { - $multiple = true; - if (!create_metadata($this->getGUID(), $name, $v, $value_type, $this->getOwner(), $this->getAccessID(), $multiple)) return false; - } else { - if (($multiple) && (isset($this->temp_metadata[$name]))) - { - if (!is_array($this->temp_metadata[$name])) - { - $tmp = $this->temp_metadata[$name]; - $this->temp_metadata[$name] = array(); - $this->temp_metadata[$name][] = $tmp; - } - - $this->temp_metadata[$name][] = $value; - } - else - $this->temp_metadata[$name] = $value; - } - } - - return true; - } - else - { - unset($this->temp_metadata[$name]); - if ((int) $this->guid > 0) { - return create_metadata($this->getGUID(), $name, $value, $value_type, $this->getOwner(), $this->getAccessID(), $multiple); - } else { - //$this->temp_metadata[$name] = $value; - - if (($multiple) && (isset($this->temp_metadata[$name]))) - { - if (!is_array($this->temp_metadata[$name])) - { - $tmp = $this->temp_metadata[$name]; - $this->temp_metadata[$name] = array(); - $this->temp_metadata[$name][] = $tmp; - } - - $this->temp_metadata[$name][] = $value; - } - else - $this->temp_metadata[$name] = $value; - - return true; - } - } - } - - /** - * Clear metadata. - */ - public function clearMetaData($name = "") - { - if (empty($name)) { - return clear_metadata($this->getGUID()); - } else { - return remove_metadata($this->getGUID(),$name); - } - } - - /** - * Remove all entities associated with this entity - * - * @return true - */ - public function clearRelationships() { - remove_entity_relationships($this->getGUID()); - remove_entity_relationships($this->getGUID(),"",true); - return true; - } - - /** - * Add a relationship. - * - * @param int $guid Relationship to link to. - * @param string $relationship The type of relationship. - */ - public function addRelationship($guid, $relationship) - { - return add_entity_relationship($this->getGUID(), $relationship, $guid); - } - - function setPrivateSetting($name, $value) { - return set_private_setting($this->getGUID(), $name, $value); - } - - function getPrivateSetting($name) { - return get_private_setting($this->getGUID(), $name); - } - - function removePrivateSetting($name) { - return remove_private_setting($this->getGUID(), $name); - } - - /** - * Adds an annotation to an entity. By default, the type is detected automatically; however, - * it can also be set. Note that by default, annotations are private. - * - * @param string $name - * @param mixed $value - * @param int $access_id - * @param int $owner_id - * @param string $vartype - */ - function annotate($name, $value, $access_id = ACCESS_PRIVATE, $owner_id = 0, $vartype = "") - { - if ((int) $this->guid > 0) { - return create_annotation($this->getGUID(), $name, $value, $vartype, $owner_id, $access_id); - } else { - $this->temp_annotations[$name] = $value; - } - return true; - } - - /** - * Get the annotations for an entity. - * - * @param string $name - * @param int $limit - * @param int $offset - * @param string $order - */ - function getAnnotations($name, $limit = 50, $offset = 0, $order="asc") - { - if ((int) ($this->guid) > 0) { - return get_annotations($this->getGUID(), "", "", $name, "", 0, $limit, $offset, $order); - } else { - return $this->temp_annotations[$name]; - } - } - - /** - * Remove all annotations or all annotations for this entity. - * - * @param string $name - */ - function clearAnnotations($name = "") - { - return clear_annotations($this->getGUID(), $name); - } - - /** - * Return the annotations for the entity. - * - * @param string $name The type of annotation. - */ - function countAnnotations($name = "") - { - return count_annotations($this->getGUID(), "","",$name); - } - - /** - * Get the average of an integer type annotation. - * - * @param string $name - */ - function getAnnotationsAvg($name) - { - return get_annotations_avg($this->getGUID(), "","",$name); - } - - /** - * Get the sum of integer type annotations of a given name. - * - * @param string $name - */ - function getAnnotationsSum($name) - { - return get_annotations_sum($this->getGUID(), "","",$name); - } - - /** - * Get the minimum of integer type annotations of given name. - * - * @param string $name - */ - function getAnnotationsMin($name) - { - return get_annotations_min($this->getGUID(), "","",$name); - } - - /** - * Get the maximum of integer type annotations of a given name. - * - * @param string $name - */ - function getAnnotationsMax($name) - { - return get_annotations_max($this->getGUID(), "","",$name); - } - - /** - * Gets an array of entities from a specific relationship type - * - * @param string $relationship Relationship type (eg "friends") - * @param true|false $inverse Is this an inverse relationship? - * @param int $limit Number of elements to return - * @param int $offset Indexing offset - * @return array|false An array of entities or false on failure - */ - function getEntitiesFromRelationship($relationship, $inverse = false, $limit = 50, $offset = 0) { - return get_entities_from_relationship($relationship,$this->getGUID(),$inverse,"","","","time_created desc",$limit,$offset); - } - - /** - * Gets the number of of entities from a specific relationship type - * - * @param string $relationship Relationship type (eg "friends") - * @return int|false The number of entities or false on failure - */ - function countEntitiesFromRelationship($relationship) { - return get_entities_from_relationship($relationship,$this->getGUID(),false,"","","","time_created desc",null,null,true); - } - - /** - * Determines whether or not the specified user (by default the current one) can edit the entity - * - * @param int $user_guid The user GUID, optionally (defaults to the currently logged in user) - * @return true|false - */ - function canEdit($user_guid = 0) { - return can_edit_entity($this->getGUID(),$user_guid); - } - - /** - * Determines whether or not the specified user (by default the current one) can edit metadata on the entity - * - * @param ElggMetadata $metadata The piece of metadata to specifically check - * @param int $user_guid The user GUID, optionally (defaults to the currently logged in user) - * @return true|false - */ - function canEditMetadata($metadata = null, $user_guid = 0) { - return can_edit_entity_metadata($this->getGUID(), $user_guid, $metadata); - } - - /** - * Returns whether the given user (or current user) has the ability to write to this group. - * - * @param int $user_guid The user. - * @return bool - */ - public function canWriteToContainer($user_guid = 0) - { - return can_write_to_container($user_guid, $this->getGUID()); - } - - /** - * Obtain this entity's access ID - * - * @return int The access ID - */ - public function getAccessID() { return $this->get('access_id'); } - - /** - * Obtain this entity's GUID - * - * @return int GUID - */ - public function getGUID() { return $this->get('guid'); } - - /** - * Get the owner of this entity - * - * @return int The owner GUID - */ - public function getOwner() { return $this->get('owner_guid'); } - - /** - * Returns the actual entity of the user who owns this entity, if any - * - * @return ElggEntity The owning user - */ - public function getOwnerEntity() { return get_entity($this->get('owner_guid')); } - - /** - * Gets the type of entity this is - * - * @return string Entity type - */ - public function getType() { return $this->get('type'); } - - /** - * Returns the subtype of this entity - * - * @return string The entity subtype - */ - public function getSubtype() { - if (!((int) $this->guid > 0)) return $this->get('subtype'); // If this object hasn't been saved, then return the subtype string. - - return get_subtype_from_id($this->get('subtype')); - } - - /** - * Gets the UNIX epoch time that this entity was created - * - * @return int UNIX epoch time - */ - public function getTimeCreated() { return $this->get('time_created'); } - - /** - * Gets the UNIX epoch time that this entity was last updated - * - * @return int UNIX epoch time - */ - public function getTimeUpdated() { return $this->get('time_updated'); } - - /** - * Gets the display URL for this entity - * - * @return string The URL - */ - public function getURL() { - if (!empty($this->url_override)) return $this->url_override; - return get_entity_url($this->getGUID()); - } - - /** - * Overrides the URL returned by getURL - * - * @param string $url The new item URL - * @return string The URL - */ - public function setURL($url) { - $this->url_override = $url; - return $url; - } - - /** - * Return a url for the entity's icon, trying multiple alternatives. - * - * @param string $size Either 'large','medium','small' or 'tiny' - * @return string The url or false if no url could be worked out. - */ - public function getIcon($size = 'medium') - { - if (isset($this->icon_override[$size])) return $this->icon_override[$size]; - return get_entity_icon_url($this, $size); - } - - /** - * Set an icon override for an icon and size. - * - * @param string $url The url of the icon. - * @param string $size The size its for. - * @return bool - */ - public function setIcon($url, $size = 'medium') - { - $url = sanitise_string($url); - $size = sanitise_string($size); - - if (!$this->icon_override) $this->icon_override = array(); - $this->icon_override[$size] = $url; - - return true; - } - - /** - * Tests to see whether the object has been fully loaded. - * - * @return bool - */ - public function isFullyLoaded() { return ! ($this->attributes['tables_loaded'] < $this->attributes['tables_split']); } - - /** - * Save generic attributes to the entities table. - */ - public function save() - { - $guid = (int) $this->guid; - if ($guid > 0) - { - cache_entity($this); - - return update_entity( - $this->get('guid'), - $this->get('owner_guid'), - $this->get('access_id'), - $this->get('container_guid') - ); - } - else - { - $this->attributes['guid'] = create_entity($this->attributes['type'], $this->attributes['subtype'], $this->attributes['owner_guid'], $this->attributes['access_id'], $this->attributes['site_guid'], $this->attributes['container_guid']); // Create a new entity (nb: using attribute array directly 'cos set function does something special!) - if (!$this->attributes['guid']) throw new IOException(elgg_echo('IOException:BaseEntitySaveFailed')); - - // Save any unsaved metadata TODO: How to capture extra information (access id etc) - if (sizeof($this->temp_metadata) > 0) { - foreach($this->temp_metadata as $name => $value) { - $this->$name = $value; - unset($this->temp_metadata[$name]); - } - } - - // Save any unsaved annotations metadata. TODO: How to capture extra information (access id etc) - if (sizeof($this->temp_annotations) > 0) { - foreach($this->temp_annotations as $name => $value) { - $this->annotate($name, $value); - unset($this->temp_annotations[$name]); - } - } - - // Cache object handle - if ($this->attributes['guid']) cache_entity($this); - - return $this->attributes['guid']; - } - } - - /** - * Load the basic entity information and populate base attributes array. - * - * @param int $guid - */ - protected function load($guid) - { - $row = get_entity_as_row($guid); - - if ($row) - { - // Create the array if necessary - all subclasses should test before creating - if (!is_array($this->attributes)) $this->attributes = array(); - - // Now put these into the attributes array as core values - $objarray = (array) $row; - foreach($objarray as $key => $value) - $this->attributes[$key] = $value; - - // Increment the portion counter - if (!$this->isFullyLoaded()) $this->attributes['tables_loaded'] ++; - - // Cache object handle - if ($this->attributes['guid']) cache_entity($this); - - return true; - } - - return false; - } - - /** - * Disable this entity. - * - * @param string $reason Optional reason - * @param bool $recursive Recursively disable all contained entities? - */ - public function disable($reason = "", $recursive = true) - { - return disable_entity($this->get('guid'), $reason, $recursive); - } - - /** - * Re-enable this entity. - */ - public function enable() - { - return enable_entity($this->get('guid')); - } - - /** - * Is this entity enabled? - * - * @return boolean - */ - public function isEnabled() - { - if ($this->enabled == 'yes') - return true; - - return false; - } - - /** - * Delete this entity. - */ - public function delete() - { - return delete_entity($this->get('guid')); - } - - // LOCATABLE INTERFACE ///////////////////////////////////////////////////////////// - - /** Interface to set the location */ - public function setLocation($location) - { - $location = sanitise_string($location); - - $this->location = $location; - - return true; - } - - /** - * Set latitude and longitude tags for a given entity. - * - * @param float $lat - * @param float $long - */ - public function setLatLong($lat, $long) - { - $lat = sanitise_string($lat); - $long = sanitise_string($long); - - $this->set('geo:lat', $lat); - $this->set('geo:long', $long); - - return true; - } - - /** - * Get the contents of the ->geo:lat field. - * - */ - public function getLatitude() { return $this->get('geo:lat'); } - - /** - * Get the contents of the ->geo:lat field. - * - */ - public function getLongitude() { return $this->get('geo:long'); } - - /** - * Get the ->location metadata. - * - */ - public function getLocation() { return $this->get('location'); } - - // NOTABLE INTERFACE /////////////////////////////////////////////////////////////// - - /** - * Calendar functionality. - * This function sets the time of an object on a calendar listing. - * - * @param int $hour If ommitted, now is assumed. - * @param int $minute If ommitted, now is assumed. - * @param int $second If ommitted, now is assumed. - * @param int $day If ommitted, now is assumed. - * @param int $month If ommitted, now is assumed. - * @param int $year If ommitted, now is assumed. - * @param int $duration Duration of event, remainder of the day is assumed. - */ - public function setCalendarTimeAndDuration($hour = NULL, $minute = NULL, $second = NULL, $day = NULL, $month = NULL, $year = NULL, $duration = NULL) - { - $start = mktime($hour, $minute, $second, $month, $day, $year); - $end = $start + abs($duration); - if (!$duration) - $end = get_day_end($day,$month,$year); - - $this->calendar_start = $start; - $this->calendar_end = $end; - - return true; - } - - /** - * Return the start timestamp. - */ - public function getCalendarStartTime() { return (int)$this->calendar_start; } - - /** - * Return the end timestamp. - */ - public function getCalendarEndTime() { return (int)$this->calendar_end; } - - // EXPORTABLE INTERFACE //////////////////////////////////////////////////////////// - - /** - * Return an array of fields which can be exported. - */ - public function getExportableValues() - { - return array( - 'guid', - 'type', - 'subtype', - 'time_created', - 'container_guid', - 'owner_guid', - ); - } - - /** - * Export this class into an array of ODD Elements containing all necessary fields. - * Override if you wish to return more information than can be found in $this->attributes (shouldn't happen) - */ - public function export() - { - $tmp = array(); - - // Generate uuid - $uuid = guid_to_uuid($this->getGUID()); - - // Create entity - $odd = new ODDEntity( - $uuid, - $this->attributes['type'], - get_subtype_from_id($this->attributes['subtype']) - ); - - $tmp[] = $odd; - - $exportable_values = $this->getExportableValues(); - - // Now add its attributes - foreach ($this->attributes as $k => $v) - { - $meta = NULL; - - if (in_array( $k, $exportable_values)) { - switch ($k) - { - case 'guid' : // Dont use guid in OpenDD - case 'type' : // Type and subtype already taken care of - case 'subtype' : - break; - - case 'time_created' : // Created = published - $odd->setAttribute('published', date("r", $v)); - break; - - case 'site_guid' : // Container - $k = 'site_uuid'; - $v = guid_to_uuid($v); - $meta = new ODDMetaData($uuid . "attr/$k/", $uuid, $k, $v); - break; - - case 'container_guid' : // Container - $k = 'container_uuid'; - $v = guid_to_uuid($v); - $meta = new ODDMetaData($uuid . "attr/$k/", $uuid, $k, $v); - break; - - case 'owner_guid' : // Convert owner guid to uuid, this will be stored in metadata - $k = 'owner_uuid'; - $v = guid_to_uuid($v); - $meta = new ODDMetaData($uuid . "attr/$k/", $uuid, $k, $v); - break; - - default : - $meta = new ODDMetaData($uuid . "attr/$k/", $uuid, $k, $v); - } - - // set the time of any metadata created - if ($meta) - { - $meta->setAttribute('published', date("r",$this->time_created)); - $tmp[] = $meta; - } - } - } - - // Now we do something a bit special. - /* - * This provides a rendered view of the entity to foreign sites. - */ - - elgg_set_viewtype('default'); - $view = elgg_view_entity($this, true); - elgg_set_viewtype(); - - $tmp[] = new ODDMetaData($uuid . "volatile/renderedentity/", $uuid, 'renderedentity', $view , 'volatile'); - - - return $tmp; - } - - // IMPORTABLE INTERFACE //////////////////////////////////////////////////////////// - - /** - * Import data from an parsed xml data array. - * - * @param array $data - * @param int $version - */ - public function import(ODD $data) - { - if (!($data instanceof ODDEntity)) - throw new InvalidParameterException(elgg_echo('InvalidParameterException:UnexpectedODDClass')); - - // Set type and subtype - $this->attributes['type'] = $data->getAttribute('class'); - $this->attributes['subtype'] = $data->getAttribute('subclass'); - - // Set owner - $this->attributes['owner_guid'] = get_loggedin_userid(); // Import as belonging to importer. - - // Set time - $this->attributes['time_created'] = strtotime($data->getAttribute('published')); - $this->attributes['time_updated'] = time(); - - return true; - } - - // SYSTEM LOG INTERFACE //////////////////////////////////////////////////////////// - - /** - * Return an identification for the object for storage in the system log. - * This id must be an integer. - * - * @return int - */ - public function getSystemLogID() { return $this->getGUID(); } - - /** - * Return the class name of the object. - */ - public function getClassName() { return get_class($this); } - - /** - * For a given ID, return the object associated with it. - * This is used by the river functionality primarily. - * This is useful for checking access permissions etc on objects. - */ - public function getObjectFromID($id) { return get_entity($id); } - - /** - * Return the GUID of the owner of this object. - */ - public function getObjectOwnerGUID() { return $this->owner_guid; } - - // ITERATOR INTERFACE ////////////////////////////////////////////////////////////// - /* - * This lets an entity's attributes be displayed using foreach as a normal array. - * Example: http://www.sitepoint.com/print/php5-standard-library - */ - - private $valid = FALSE; - - function rewind() - { - $this->valid = (FALSE !== reset($this->attributes)); - } - - function current() - { - return current($this->attributes); - } - - function key() - { - return key($this->attributes); - } - - function next() - { - $this->valid = (FALSE !== next($this->attributes)); - } - - function valid() - { - return $this->valid; - } - - // ARRAY ACCESS INTERFACE ////////////////////////////////////////////////////////// - /* - * This lets an entity's attributes be accessed like an associative array. - * Example: http://www.sitepoint.com/print/php5-standard-library - */ - - function offsetSet($key, $value) - { - if ( array_key_exists($key, $this->attributes) ) { - $this->attributes[$key] = $value; - } - } - - function offsetGet($key) - { - if ( array_key_exists($key, $this->attributes) ) { - return $this->attributes[$key]; - } - } - - function offsetUnset($key) - { - if ( array_key_exists($key, $this->attributes) ) { - $this->attributes[$key] = ""; // Full unsetting is dangerious for our objects - } - } - - function offsetExists($offset) - { - return array_key_exists($offset, $this->attributes); - } - } - - /** - * Initialise the entity cache. - */ - function initialise_entity_cache() - { - global $ENTITY_CACHE; - - if (!$ENTITY_CACHE) - $ENTITY_CACHE = array(); //select_default_memcache('entity_cache'); // TODO: Replace with memcache? - } - - /** - * Invalidate this class' entry in the cache. - * - * @param int $guid The guid - */ - function invalidate_cache_for_entity($guid) - { - global $ENTITY_CACHE; - - $guid = (int)$guid; - - unset($ENTITY_CACHE[$guid]); - //$ENTITY_CACHE->delete($guid); - } - - /** - * Cache an entity. - * - * @param ElggEntity $entity Entity to cache - */ - function cache_entity(ElggEntity $entity) - { - global $ENTITY_CACHE; - - $ENTITY_CACHE[$entity->guid] = $entity; - } - - /** - * Retrieve a entity from the cache. - * - * @param int $guid The guid - */ - function retrieve_cached_entity($guid) - { - global $ENTITY_CACHE; - - $guid = (int)$guid; - - if (isset($ENTITY_CACHE[$guid])) - if ($ENTITY_CACHE[$guid]->isFullyLoaded()) return $ENTITY_CACHE[$guid]; - - return false; - } - - /** - * As retrieve_cached_entity, but returns the result as a stdClass (compatible with load functions that - * expect a database row.) - * - * @param int $guid The guid - */ - function retrieve_cached_entity_row($guid) - { - $obj = retrieve_cached_entity($guid); - if ($obj) - { - $tmp = new stdClass; - - foreach ($obj as $k => $v) - $tmp->$k = $v; - - return $tmp; - } - - return false; - } - - /** - * Return the integer ID for a given subtype, or false. - * - * TODO: Move to a nicer place? - * - * @param string $type - * @param string $subtype - */ - function get_subtype_id($type, $subtype) - { - global $CONFIG, $SUBTYPE_CACHE; - - $type = sanitise_string($type); - $subtype = sanitise_string($subtype); - - if ($subtype=="") return $subtype; - - // Todo: cache here? Or is looping less efficient that going to the db each time? - - $result = get_data_row("SELECT * from {$CONFIG->dbprefix}entity_subtypes where type='$type' and subtype='$subtype'"); - - if ($result) { - - if (!$SUBTYPE_CACHE) - $SUBTYPE_CACHE = array(); //select_default_memcache('subtype_cache'); - - $SUBTYPE_CACHE[$result->id] = $result; - return $result->id; - } - - return 0; - } - - /** - * For a given subtype ID, return its identifier text. - * - * TODO: Move to a nicer place? - * - * @param int $subtype_id - */ - function get_subtype_from_id($subtype_id) - { - global $CONFIG, $SUBTYPE_CACHE; - - $subtype_id = (int)$subtype_id; - - if (!$subtype_id) return false; - - if (isset($SUBTYPE_CACHE[$subtype_id])) - return $SUBTYPE_CACHE[$subtype_id]->subtype; - - $result = get_data_row("SELECT * from {$CONFIG->dbprefix}entity_subtypes where id=$subtype_id"); - if ($result) { - - if (!$SUBTYPE_CACHE) - $SUBTYPE_CACHE = array(); //select_default_memcache('subtype_cache'); - - $SUBTYPE_CACHE[$subtype_id] = $result; - return $result->subtype; - } - - return false; - } - - /** - * This function tests to see if a subtype has a registered class handler. - * - * @param string $type The type - * @param string $subtype The subtype - * @return a class name or null - */ - function get_subtype_class($type, $subtype) - { - global $CONFIG, $SUBTYPE_CACHE; - - $type = sanitise_string($type); - $subtype = sanitise_string($subtype); - - // Todo: cache here? Or is looping less efficient that going to the db each time? - - $result = get_data_row("SELECT * from {$CONFIG->dbprefix}entity_subtypes where type='$type' and subtype='$subtype'"); - if ($result) { - - if (!$SUBTYPE_CACHE) - $SUBTYPE_CACHE = array(); //select_default_memcache('subtype_cache'); - - $SUBTYPE_CACHE[$result->id] = $result; - return $result->class; - } - - return NULL; - } - - /** - * This function tests to see if a subtype has a registered class handler by its id. - * - * @param int $subtype_id The subtype - * @return a class name or null - */ - function get_subtype_class_from_id($subtype_id) - { - global $CONFIG, $SUBTYPE_CACHE; - - $subtype_id = (int)$subtype_id; - - if (!$subtype_id) return false; - - if (isset($SUBTYPE_CACHE[$subtype_id])) - return $SUBTYPE_CACHE[$subtype_id]->class; - - $result = get_data_row("SELECT * from {$CONFIG->dbprefix}entity_subtypes where id=$subtype_id"); - if ($result) { - - if (!$SUBTYPE_CACHE) - $SUBTYPE_CACHE = array(); //select_default_memcache('subtype_cache'); - - $SUBTYPE_CACHE[$subtype_id] = $result; - return $result->class; - } - - return NULL; - } - - /** - * This function will register a new subtype, returning its ID as required. - * - * @param string $type The type you're subtyping - * @param string $subtype The subtype label - * @param string $class Optional class handler (if you don't want it handled by the generic elgg handler for the type) - */ - function add_subtype($type, $subtype, $class = "") - { - global $CONFIG; - $type = sanitise_string($type); - $subtype = sanitise_string($subtype); - $class = sanitise_string($class); - - // Short circuit if no subtype is given - if ($subtype == "") - return 0; - - $id = get_subtype_id($type, $subtype); - - if ($id==0) - return insert_data("insert into {$CONFIG->dbprefix}entity_subtypes (type, subtype, class) values ('$type','$subtype','$class')"); - - return $id; - } - - /** - * Update an existing entity. - * - * @param int $guid - * @param int $owner_guid - * @param int $access_id - * @param int $container_guid - */ - function update_entity($guid, $owner_guid, $access_id, $container_guid = null) - { - global $CONFIG, $ENTITY_CACHE; - - $guid = (int)$guid; - $owner_guid = (int)$owner_guid; - $access_id = (int)$access_id; - $container_guid = (int) $container_guid; - if (is_null($container_guid)) $container_guid = $owner_guid; - $time = time(); - - $entity = get_entity($guid); - - if ($entity->canEdit()) { - - if (trigger_elgg_event('update',$entity->type,$entity)) { - $ret = update_data("UPDATE {$CONFIG->dbprefix}entities set owner_guid='$owner_guid', access_id='$access_id', container_guid='$container_guid', time_updated='$time' WHERE guid=$guid"); - - if ($entity instanceof ElggObject) - update_river_access_by_object($guid,$access_id); - - // If memcache is available then delete this entry from the cache - static $newentity_cache; - if ((!$newentity_cache) && (is_memcache_available())) - $newentity_cache = new ElggMemcache('new_entity_cache'); - if ($newentity_cache) $new_entity = $newentity_cache->delete($guid); - - // Handle cases where there was no error BUT no rows were updated! - if ($ret===false) - return false; - - return true; - } - - } - } - - /** - * Determine whether a given user is able to write to a given container. - * - * @param int $user_guid The user guid, or 0 for get_loggedin_userid() - * @param int $container_guid The container, or 0 for the current page owner. - */ - function can_write_to_container($user_guid = 0, $container_guid = 0, $entity_type = 'all') - { - global $CONFIG; - - $user_guid = (int)$user_guid; - $user = get_entity($user_guid); - if (!$user) $user = get_loggedin_user(); - - $container_guid = (int)$container_guid; - if (!$container_guid) $container_guid = page_owner(); - if (!$container_guid) return true; - - $container = get_entity($container_guid); - - if ($container) - { - - // If the user can edit the container, they can also write to it - if ($container->canEdit($user_guid)) return true; - - // Basics, see if the user is a member of the group. - if ($user && $container instanceof ElggGroup) { - if (!$container->isMember($user)) { - return false; - } else { - return true; - } - } - - // See if anyone else has anything to say - return trigger_plugin_hook('container_permissions_check',$entity_type,array('container' => $container, 'user' => $user), false); - - } - - return false; - } - - /** - * Create a new entity of a given type. - * - * @param string $type The type of the entity (site, user, object). - * @param string $subtype The subtype of the entity. - * @param int $owner_guid The GUID of the object's owner. - * @param int $access_id The access control group to create the entity with. - * @param int $site_guid The site to add this entity to. Leave as 0 (default) for the current site. - * @return mixed The new entity's GUID, or false on failure - */ - function create_entity($type, $subtype, $owner_guid, $access_id, $site_guid = 0, $container_guid = 0) - { - global $CONFIG; - - $type = sanitise_string($type); - $subtype = add_subtype($type, $subtype); - $owner_guid = (int)$owner_guid; - $access_id = (int)$access_id; - $time = time(); - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - $site_guid = (int) $site_guid; - if ($container_guid == 0) $container_guid = $owner_guid; - - $user = get_loggedin_user(); - if (!can_write_to_container($user->guid, $owner_guid, $type)) return false; - if ($owner_guid != $container_guid) - if (!can_write_to_container($user->guid, $container_guid, $type)) return false; - - if ($type=="") throw new InvalidParameterException(elgg_echo('InvalidParameterException:EntityTypeNotSet')); - - return insert_data("INSERT into {$CONFIG->dbprefix}entities (type, subtype, owner_guid, site_guid, container_guid, access_id, time_created, time_updated) values ('$type',$subtype, $owner_guid, $site_guid, $container_guid, $access_id, $time, $time)"); - } - - /** - * Retrieve the entity details for a specific GUID, returning it as a stdClass db row. - * - * You will only get an object if a) it exists, b) you have access to it. - * - * @param int $guid The GUID of the object to extract - */ - function get_entity_as_row($guid) - { - global $CONFIG; - - if (!$guid) return false; - - $guid = (int) $guid; - - /*$row = retrieve_cached_entity_row($guid); - if ($row) - { - // We have already cached this object, so retrieve its value from the cache - if (isset($CONFIG->debug) && $CONFIG->debug) - error_log("** Retrieving GUID:$guid from cache"); - - return $row; - } - else - {*/ - // Object not cached, load it. - if (isset($CONFIG->debug) && $CONFIG->debug == true) - error_log("** GUID:$guid loaded from DB"); - - $access = get_access_sql_suffix(); - - return get_data_row("SELECT * from {$CONFIG->dbprefix}entities where guid=$guid and $access"); - //} - } - - /** - * Create an Elgg* object from a given entity row. - */ - function entity_row_to_elggstar($row) - { - if (!($row instanceof stdClass)) - return $row; - - if ((!isset($row->guid)) || (!isset($row->subtype))) - return $row; - - $new_entity = false; - - // Create a memcache cache if we can - static $newentity_cache; - if ((!$newentity_cache) && (is_memcache_available())) - $newentity_cache = new ElggMemcache('new_entity_cache'); - if ($newentity_cache) $new_entity = $newentity_cache->load($row->guid); - if ($new_entity) return $new_entity; - - $classname = get_subtype_class_from_id($row->subtype); - if ($classname!="") - { - if (class_exists($classname)) - { - $new_entity = new $classname($row); - - if (!($new_entity instanceof ElggEntity)) - throw new ClassException(sprintf(elgg_echo('ClassException:ClassnameNotClass'), $classname, 'ElggEntity')); - } - else - error_log(sprintf(elgg_echo('ClassNotFoundException:MissingClass'), $classname)); - } - else - { - switch ($row->type) - { - case 'object' : - $new_entity = new ElggObject($row); break; - case 'user' : - $new_entity = new ElggUser($row); break; - case 'group' : - $new_entity = new ElggGroup($row); break; - case 'site' : - $new_entity = new ElggSite($row); break; - default: throw new InstallationException(sprintf(elgg_echo('InstallationException:TypeNotSupported'), $row->type)); - } - - } - - // Cache entity if we have a cache available - if (($newentity_cache) && ($new_entity)) $newentity_cache->save($new_entity->guid, $new_entity); - - return $new_entity; - } - - /** - * Return the entity for a given guid as the correct object. - * @param int $guid The GUID of the entity - * @return a child of ElggEntity appropriate for the type. - */ - function get_entity($guid) - { - static $newentity_cache; - $new_entity = false; - if ((!$newentity_cache) && (is_memcache_available())) - $newentity_cache = new ElggMemcache('new_entity_cache'); - if ($newentity_cache) $new_entity = $newentity_cache->load($guid); - if ($new_entity) return $new_entity; - - return entity_row_to_elggstar(get_entity_as_row($guid)); - } - - /** - * Return entities matching a given query, or the number thereof - * - * @param string $type The type of entity (eg "user", "object" etc) - * @param string|array $subtype The arbitrary subtype of the entity or array(type1 => array('subtype1', ...'subtypeN'), ...) - * @param int $owner_guid The GUID of the owning user - * @param string $order_by The field to order by; by default, time_created desc - * @param int $limit The number of entities to return; 10 by default - * @param int $offset The indexing offset, 0 by default - * @param boolean $count Set to true to get a count rather than the entities themselves (limits and offsets don't apply in this context). Defaults to false. - * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. - * @param int|array $container_guid The container or containers to get entities from (default: all containers). - * @param int $timelower The earliest time the entity can have been created. Default: all - * @param int $timeupper The latest time the entity can have been created. Default: all - * @return array A list of entities. - */ - function get_entities($type = "", $subtype = "", $owner_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false, $site_guid = 0, $container_guid = null, $timelower = 0, $timeupper = 0) - { - global $CONFIG; - - if ($subtype === false || $subtype === null || $subtype === 0) - return false; - - if ($order_by == "") $order_by = "time_created desc"; - $order_by = sanitise_string($order_by); - $limit = (int)$limit; - $offset = (int)$offset; - $site_guid = (int) $site_guid; - $timelower = (int) $timelower; - $timeupper = (int) $timeupper; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - $where = array(); - - if (is_array($subtype)) { - $tempwhere = ""; - if (sizeof($subtype)) - foreach($subtype as $typekey => $subtypearray) { - foreach($subtypearray as $subtypeval) { - $typekey = sanitise_string($typekey); - if (!empty($subtypeval)) { - if (!$subtypeval = (int) get_subtype_id($typekey, $subtypeval)) - return false; - } else { - // @todo: Setting subtype to 0 when $subtype = '' returns entities with - // no subtype. This is different to the non-array behavior - // but may be required in some cases. - $subtypeval = 0; - } - if (!empty($tempwhere)) $tempwhere .= " or "; - $tempwhere .= "(type = '{$typekey}' and subtype = {$subtypeval})"; - } - } - if (!empty($tempwhere)) $where[] = "({$tempwhere})"; - - } else { - - $type = sanitise_string($type); - if ($subtype !== "" AND !$subtype = get_subtype_id($type, $subtype)) - return false; - - if ($type != "") - $where[] = "type='$type'"; - if ($subtype!=="") - $where[] = "subtype=$subtype"; - } - - if ($owner_guid != "") { - if (!is_array($owner_guid)) { - $owner_array = array($owner_guid); - $owner_guid = (int) $owner_guid; - // $where[] = "owner_guid = '$owner_guid'"; - } else if (sizeof($owner_guid) > 0) { - $owner_array = array_map('sanitise_int', $owner_guid); - // Cast every element to the owner_guid array to int - // $owner_guid = array_map("sanitise_int", $owner_guid); - // $owner_guid = implode(",",$owner_guid); - // $where[] = "owner_guid in ({$owner_guid})"; - } - if (is_null($container_guid)) { - $container_guid = $owner_array; - } - } - if ($site_guid > 0) - $where[] = "site_guid = {$site_guid}"; - - if (!is_null($container_guid)) { - if (is_array($container_guid)) { - foreach($container_guid as $key => $val) $container_guid[$key] = (int) $val; - $where[] = "container_guid in (" . implode(",",$container_guid) . ")"; - } else { - $container_guid = (int) $container_guid; - $where[] = "container_guid = {$container_guid}"; - } - } - if ($timelower) - $where[] = "time_created >= {$timelower}"; - if ($timeupper) - $where[] = "time_created <= {$timeupper}"; - - if (!$count) { - $query = "SELECT * from {$CONFIG->dbprefix}entities where "; - } else { - $query = "SELECT count(guid) as total from {$CONFIG->dbprefix}entities where "; - } - foreach ($where as $w) - $query .= " $w and "; - $query .= get_access_sql_suffix(); // Add access controls - if (!$count) { - $query .= " order by $order_by"; - if ($limit) $query .= " limit $offset, $limit"; // Add order and limit - $dt = get_data($query, "entity_row_to_elggstar"); - return $dt; - } else { - $total = get_data_row($query); - return $total->total; - } - } - - /** - * Returns a viewable list of entities - * - * @see elgg_view_entity_list - * - * @param string $type The type of entity (eg "user", "object" etc) - * @param string $subtype The arbitrary subtype of the entity - * @param int $owner_guid The GUID of the owning user - * @param int $limit The number of entities to display per page (default: 10) - * @param true|false $fullview Whether or not to display the full view (default: true) - * @param true|false $viewtypetoggle Whether or not to allow gallery view - * @param true|false $pagination Display pagination? Default: true - * @return string A viewable list of entities - */ - function list_entities($type= "", $subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = false, $pagination = true) { - - $offset = (int) get_input('offset'); - $count = get_entities($type, $subtype, $owner_guid, "", $limit, $offset, true); - $entities = get_entities($type, $subtype, $owner_guid, "", $limit, $offset); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); - - } - - /** - * Returns a viewable list of entities contained in a number of groups. - * - * @param string $subtype The arbitrary subtype of the entity - * @param int $owner_guid The GUID of the owning user - * @param int $container_guid The GUID of the containing group - * @param int $limit The number of entities to display per page (default: 10) - * @param true|false $fullview Whether or not to display the full view (default: true) - * @return string A viewable list of entities - */ - function list_entities_groups($subtype = "", $owner_guid = 0, $container_guid = 0, $limit = 10, $fullview = true) - { - $offset = (int) get_input('offset'); - $count = get_objects_in_group($container_guid, $subtype, $owner_guid, 0, "", $limit, $offset, true); - $entities = get_objects_in_group($container_guid, $subtype, $owner_guid, 0, "", $limit, $offset); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview); - } - - /** - * Returns a list of months containing content specified by the parameters - * - * @param string $type The type of entity - * @param string $subtype The subtype of entity - * @param int $container_guid The container GUID that the entinties belong to - * @param int $site_guid The site GUID - * @return array|false Either an array of timestamps, or false on failure - */ - function get_entity_dates($type = '', $subtype = '', $container_guid = 0, $site_guid = 0) { - - global $CONFIG; - - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - $where = array(); - - if ($type != "") { - $type = sanitise_string($type); - $where[] = "type='$type'"; - } - - if (is_array($subtype)) { - $tempwhere = ""; - if (sizeof($subtype)) - foreach($subtype as $typekey => $subtypearray) { - foreach($subtypearray as $subtypeval) { - $typekey = sanitise_string($typekey); - if (!empty($subtypeval)) { - if (!$subtypeval = (int) get_subtype_id($typekey, $subtypeval)) - return false; - } else { - $subtypeval = 0; - } - if (!empty($tempwhere)) $tempwhere .= " or "; - $tempwhere .= "(type = '{$typekey}' and subtype = {$subtypeval})"; - } - } - if (!empty($tempwhere)) $where[] = "({$tempwhere})"; - - } else { - if ($subtype AND !$subtype = get_subtype_id($type, $subtype)) { - return false; - } else { - $where[] = "subtype=$subtype"; - } - } - - if ($container_guid !== 0) { - if (is_array($container_guid)) { - foreach($container_guid as $key => $val) $container_guid[$key] = (int) $val; - $where[] = "container_guid in (" . implode(",",$container_guid) . ")"; - } else { - $container_guid = (int) $container_guid; - $where[] = "container_guid = {$container_guid}"; - } - } - - if ($site_guid > 0) - $where[] = "site_guid = {$site_guid}"; - - $where[] = get_access_sql_suffix(); - - $sql = "SELECT DISTINCT EXTRACT(YEAR_MONTH FROM FROM_UNIXTIME(time_created)) AS yearmonth FROM {$CONFIG->dbprefix}entities where "; - foreach ($where as $w) - $sql .= " $w and "; - $sql .= "1=1"; - if ($result = get_data($sql)) { - $endresult = array(); - foreach($result as $res) { - $endresult[] = $res->yearmonth; - } - return $endresult; - } - return false; - - } - - /** - * Disable an entity but not delete it. - * - * @param int $guid The guid - * @param string $reason Optional reason - */ - function disable_entity($guid, $reason = "", $recursive = true) - { - global $CONFIG; - - $guid = (int)$guid; - $reason = sanitise_string($reason); - - if ($entity = get_entity($guid)) { - if (trigger_elgg_event('disable',$entity->type,$entity)) { - if ($entity->canEdit()) { - - if ($reason) - create_metadata($guid, 'disable_reason', $reason,'', 0, ACCESS_PUBLIC); - - if ($recursive) - { - // Temporary token overriding access controls TODO: Do this better. - static $__RECURSIVE_DELETE_TOKEN; - $__RECURSIVE_DELETE_TOKEN = md5(get_loggedin_userid()); // Make it slightly harder to guess - - $sub_entities = get_data("SELECT * from {$CONFIG->dbprefix}entities WHERE container_guid=$guid or owner_guid=$guid or site_guid=$guid", 'entity_row_to_elggstar'); - if ($sub_entities) { - foreach ($sub_entities as $e) - $e->disable($reason); - } - - $__RECURSIVE_DELETE_TOKEN = null; - } - - $res = update_data("UPDATE {$CONFIG->dbprefix}entities set enabled='no' where guid={$guid}"); - - return $res; - } - } - } - return false; - } - - /** - * Enable an entity again. - * - * @param int $guid - */ - function enable_entity($guid) - { - global $CONFIG; - - $guid = (int)$guid; - - // Override access only visible entities - $access_status = access_get_show_hidden_status(); - access_show_hidden_entities(true); - - if ($entity = get_entity($guid)) { - if (trigger_elgg_event('enable',$entity->type,$entity)) { - if ($entity->canEdit()) { - - access_show_hidden_entities($access_status); - - $result = update_data("UPDATE {$CONFIG->dbprefix}entities set enabled='yes' where guid={$guid}"); - $entity->clearMetaData('disable_reason'); - - return $result; - } - } - } - - access_show_hidden_entities($access_status); - return false; - } - - /** - * Delete a given entity. - * - * @param int $guid - * @param bool $recursive If true (default) then all entities which are owned or contained by $guid will also be deleted. - * Note: this bypasses ownership of sub items. - */ - function delete_entity($guid, $recursive = true) - { - global $CONFIG; - - $guid = (int)$guid; - if ($entity = get_entity($guid)) { - if (trigger_elgg_event('delete',$entity->type,$entity)) { - if ($entity->canEdit()) { - - // Delete contained owned and otherwise releated objects (depth first) - if ($recursive) - { - // Temporary token overriding access controls TODO: Do this better. - static $__RECURSIVE_DELETE_TOKEN; - $__RECURSIVE_DELETE_TOKEN = md5(get_loggedin_userid()); // Make it slightly harder to guess - - $sub_entities = get_data("SELECT * from {$CONFIG->dbprefix}entities WHERE container_guid=$guid or owner_guid=$guid or site_guid=$guid", 'entity_row_to_elggstar'); - if ($sub_entities) { - foreach ($sub_entities as $e) - $e->delete(); - } - - $__RECURSIVE_DELETE_TOKEN = null; - } - - // Now delete the entity itself - $entity->clearMetadata(); - $entity->clearAnnotations(); - $entity->clearRelationships(); - remove_from_river_by_subject($guid); + if ($md && !is_array($md)) { + return $md->value; + } else if ($md && is_array($md)) { + return metadata_array_to_values($md); + } + + return null; + } + + /** + * Class member get overloading + * + * @param string $name + * @return mixed + */ + function __get($name) { return $this->get($name); } + + /** + * Class member set overloading + * + * @param string $name + * @param mixed $value + * @return mixed + */ + function __set($name, $value) { return $this->set($name, $value); } + + /** + * Supporting isset. + * + * @param string $name The name of the attribute or metadata. + * @return bool + */ + function __isset($name) { if ($this->$name!="") return true; else return false; } + + /** + * Supporting unsetting of magic attributes. + * + * @param string $name The name of the attribute or metadata. + */ + function __unset($name) + { + if (array_key_exists($name, $this->attributes)) + $this->attributes[$name] = ""; + else + $this->clearMetaData($name); + } + + /** + * Set a piece of metadata. + * + * @param string $name + * @param mixed $value + * @param string $value_type + * @param bool $multiple + * @return bool + */ + public function setMetaData($name, $value, $value_type = "", $multiple = false) + { + if (is_array($value)) + { + unset($this->temp_metadata[$name]); + remove_metadata($this->getGUID(), $name); + foreach ($value as $v) { + if ((int) $this->guid > 0) { + $multiple = true; + if (!create_metadata($this->getGUID(), $name, $v, $value_type, $this->getOwner(), $this->getAccessID(), $multiple)) return false; + } else { + if (($multiple) && (isset($this->temp_metadata[$name]))) + { + if (!is_array($this->temp_metadata[$name])) + { + $tmp = $this->temp_metadata[$name]; + $this->temp_metadata[$name] = array(); + $this->temp_metadata[$name][] = $tmp; + } + + $this->temp_metadata[$name][] = $value; + } + else + $this->temp_metadata[$name] = $value; + } + } + + return true; + } + else + { + unset($this->temp_metadata[$name]); + if ((int) $this->guid > 0) { + return create_metadata($this->getGUID(), $name, $value, $value_type, $this->getOwner(), $this->getAccessID(), $multiple); + } else { + //$this->temp_metadata[$name] = $value; + + if (($multiple) && (isset($this->temp_metadata[$name]))) + { + if (!is_array($this->temp_metadata[$name])) + { + $tmp = $this->temp_metadata[$name]; + $this->temp_metadata[$name] = array(); + $this->temp_metadata[$name][] = $tmp; + } + + $this->temp_metadata[$name][] = $value; + } + else + $this->temp_metadata[$name] = $value; + + return true; + } + } + } + + /** + * Clear metadata. + */ + public function clearMetaData($name = "") + { + if (empty($name)) { + return clear_metadata($this->getGUID()); + } else { + return remove_metadata($this->getGUID(),$name); + } + } + + /** + * Remove all entities associated with this entity + * + * @return true + */ + public function clearRelationships() { + remove_entity_relationships($this->getGUID()); + remove_entity_relationships($this->getGUID(),"",true); + return true; + } + + /** + * Add a relationship. + * + * @param int $guid Relationship to link to. + * @param string $relationship The type of relationship. + */ + public function addRelationship($guid, $relationship) + { + return add_entity_relationship($this->getGUID(), $relationship, $guid); + } + + function setPrivateSetting($name, $value) { + return set_private_setting($this->getGUID(), $name, $value); + } + + function getPrivateSetting($name) { + return get_private_setting($this->getGUID(), $name); + } + + function removePrivateSetting($name) { + return remove_private_setting($this->getGUID(), $name); + } + + /** + * Adds an annotation to an entity. By default, the type is detected automatically; however, + * it can also be set. Note that by default, annotations are private. + * + * @param string $name + * @param mixed $value + * @param int $access_id + * @param int $owner_id + * @param string $vartype + */ + function annotate($name, $value, $access_id = ACCESS_PRIVATE, $owner_id = 0, $vartype = "") + { + if ((int) $this->guid > 0) { + return create_annotation($this->getGUID(), $name, $value, $vartype, $owner_id, $access_id); + } else { + $this->temp_annotations[$name] = $value; + } + return true; + } + + /** + * Get the annotations for an entity. + * + * @param string $name + * @param int $limit + * @param int $offset + * @param string $order + */ + function getAnnotations($name, $limit = 50, $offset = 0, $order="asc") + { + if ((int) ($this->guid) > 0) { + return get_annotations($this->getGUID(), "", "", $name, "", 0, $limit, $offset, $order); + } else { + return $this->temp_annotations[$name]; + } + } + + /** + * Remove all annotations or all annotations for this entity. + * + * @param string $name + */ + function clearAnnotations($name = "") + { + return clear_annotations($this->getGUID(), $name); + } + + /** + * Return the annotations for the entity. + * + * @param string $name The type of annotation. + */ + function countAnnotations($name = "") + { + return count_annotations($this->getGUID(), "","",$name); + } + + /** + * Get the average of an integer type annotation. + * + * @param string $name + */ + function getAnnotationsAvg($name) + { + return get_annotations_avg($this->getGUID(), "","",$name); + } + + /** + * Get the sum of integer type annotations of a given name. + * + * @param string $name + */ + function getAnnotationsSum($name) + { + return get_annotations_sum($this->getGUID(), "","",$name); + } + + /** + * Get the minimum of integer type annotations of given name. + * + * @param string $name + */ + function getAnnotationsMin($name) + { + return get_annotations_min($this->getGUID(), "","",$name); + } + + /** + * Get the maximum of integer type annotations of a given name. + * + * @param string $name + */ + function getAnnotationsMax($name) + { + return get_annotations_max($this->getGUID(), "","",$name); + } + + /** + * Gets an array of entities from a specific relationship type + * + * @param string $relationship Relationship type (eg "friends") + * @param true|false $inverse Is this an inverse relationship? + * @param int $limit Number of elements to return + * @param int $offset Indexing offset + * @return array|false An array of entities or false on failure + */ + function getEntitiesFromRelationship($relationship, $inverse = false, $limit = 50, $offset = 0) { + return get_entities_from_relationship($relationship,$this->getGUID(),$inverse,"","","","time_created desc",$limit,$offset); + } + + /** + * Gets the number of of entities from a specific relationship type + * + * @param string $relationship Relationship type (eg "friends") + * @return int|false The number of entities or false on failure + */ + function countEntitiesFromRelationship($relationship) { + return get_entities_from_relationship($relationship,$this->getGUID(),false,"","","","time_created desc",null,null,true); + } + + /** + * Determines whether or not the specified user (by default the current one) can edit the entity + * + * @param int $user_guid The user GUID, optionally (defaults to the currently logged in user) + * @return true|false + */ + function canEdit($user_guid = 0) { + return can_edit_entity($this->getGUID(),$user_guid); + } + + /** + * Determines whether or not the specified user (by default the current one) can edit metadata on the entity + * + * @param ElggMetadata $metadata The piece of metadata to specifically check + * @param int $user_guid The user GUID, optionally (defaults to the currently logged in user) + * @return true|false + */ + function canEditMetadata($metadata = null, $user_guid = 0) { + return can_edit_entity_metadata($this->getGUID(), $user_guid, $metadata); + } + + /** + * Returns whether the given user (or current user) has the ability to write to this group. + * + * @param int $user_guid The user. + * @return bool + */ + public function canWriteToContainer($user_guid = 0) + { + return can_write_to_container($user_guid, $this->getGUID()); + } + + /** + * Obtain this entity's access ID + * + * @return int The access ID + */ + public function getAccessID() { return $this->get('access_id'); } + + /** + * Obtain this entity's GUID + * + * @return int GUID + */ + public function getGUID() { return $this->get('guid'); } + + /** + * Get the owner of this entity + * + * @return int The owner GUID + */ + public function getOwner() { return $this->get('owner_guid'); } + + /** + * Returns the actual entity of the user who owns this entity, if any + * + * @return ElggEntity The owning user + */ + public function getOwnerEntity() { return get_entity($this->get('owner_guid')); } + + /** + * Gets the type of entity this is + * + * @return string Entity type + */ + public function getType() { return $this->get('type'); } + + /** + * Returns the subtype of this entity + * + * @return string The entity subtype + */ + public function getSubtype() { + if (!((int) $this->guid > 0)) return $this->get('subtype'); // If this object hasn't been saved, then return the subtype string. + + return get_subtype_from_id($this->get('subtype')); + } + + /** + * Gets the UNIX epoch time that this entity was created + * + * @return int UNIX epoch time + */ + public function getTimeCreated() { return $this->get('time_created'); } + + /** + * Gets the UNIX epoch time that this entity was last updated + * + * @return int UNIX epoch time + */ + public function getTimeUpdated() { return $this->get('time_updated'); } + + /** + * Gets the display URL for this entity + * + * @return string The URL + */ + public function getURL() { + if (!empty($this->url_override)) return $this->url_override; + return get_entity_url($this->getGUID()); + } + + /** + * Overrides the URL returned by getURL + * + * @param string $url The new item URL + * @return string The URL + */ + public function setURL($url) { + $this->url_override = $url; + return $url; + } + + /** + * Return a url for the entity's icon, trying multiple alternatives. + * + * @param string $size Either 'large','medium','small' or 'tiny' + * @return string The url or false if no url could be worked out. + */ + public function getIcon($size = 'medium') + { + if (isset($this->icon_override[$size])) return $this->icon_override[$size]; + return get_entity_icon_url($this, $size); + } + + /** + * Set an icon override for an icon and size. + * + * @param string $url The url of the icon. + * @param string $size The size its for. + * @return bool + */ + public function setIcon($url, $size = 'medium') + { + $url = sanitise_string($url); + $size = sanitise_string($size); + + if (!$this->icon_override) $this->icon_override = array(); + $this->icon_override[$size] = $url; + + return true; + } + + /** + * Tests to see whether the object has been fully loaded. + * + * @return bool + */ + public function isFullyLoaded() { return ! ($this->attributes['tables_loaded'] < $this->attributes['tables_split']); } + + /** + * Save generic attributes to the entities table. + */ + public function save() + { + $guid = (int) $this->guid; + if ($guid > 0) + { + cache_entity($this); + + return update_entity( + $this->get('guid'), + $this->get('owner_guid'), + $this->get('access_id'), + $this->get('container_guid') + ); + } + else + { + $this->attributes['guid'] = create_entity($this->attributes['type'], $this->attributes['subtype'], $this->attributes['owner_guid'], $this->attributes['access_id'], $this->attributes['site_guid'], $this->attributes['container_guid']); // Create a new entity (nb: using attribute array directly 'cos set function does something special!) + if (!$this->attributes['guid']) throw new IOException(elgg_echo('IOException:BaseEntitySaveFailed')); + + // Save any unsaved metadata TODO: How to capture extra information (access id etc) + if (sizeof($this->temp_metadata) > 0) { + foreach($this->temp_metadata as $name => $value) { + $this->$name = $value; + unset($this->temp_metadata[$name]); + } + } + + // Save any unsaved annotations metadata. TODO: How to capture extra information (access id etc) + if (sizeof($this->temp_annotations) > 0) { + foreach($this->temp_annotations as $name => $value) { + $this->annotate($name, $value); + unset($this->temp_annotations[$name]); + } + } + + // Cache object handle + if ($this->attributes['guid']) cache_entity($this); + + return $this->attributes['guid']; + } + } + + /** + * Load the basic entity information and populate base attributes array. + * + * @param int $guid + */ + protected function load($guid) + { + $row = get_entity_as_row($guid); + + if ($row) + { + // Create the array if necessary - all subclasses should test before creating + if (!is_array($this->attributes)) $this->attributes = array(); + + // Now put these into the attributes array as core values + $objarray = (array) $row; + foreach($objarray as $key => $value) + $this->attributes[$key] = $value; + + // Increment the portion counter + if (!$this->isFullyLoaded()) $this->attributes['tables_loaded'] ++; + + // Cache object handle + if ($this->attributes['guid']) cache_entity($this); + + return true; + } + + return false; + } + + /** + * Disable this entity. + * + * @param string $reason Optional reason + * @param bool $recursive Recursively disable all contained entities? + */ + public function disable($reason = "", $recursive = true) + { + return disable_entity($this->get('guid'), $reason, $recursive); + } + + /** + * Re-enable this entity. + */ + public function enable() + { + return enable_entity($this->get('guid')); + } + + /** + * Is this entity enabled? + * + * @return boolean + */ + public function isEnabled() + { + if ($this->enabled == 'yes') + return true; + + return false; + } + + /** + * Delete this entity. + */ + public function delete() + { + return delete_entity($this->get('guid')); + } + + // LOCATABLE INTERFACE ///////////////////////////////////////////////////////////// + + /** Interface to set the location */ + public function setLocation($location) + { + $location = sanitise_string($location); + + $this->location = $location; + + return true; + } + + /** + * Set latitude and longitude tags for a given entity. + * + * @param float $lat + * @param float $long + */ + public function setLatLong($lat, $long) + { + $lat = sanitise_string($lat); + $long = sanitise_string($long); + + $this->set('geo:lat', $lat); + $this->set('geo:long', $long); + + return true; + } + + /** + * Get the contents of the ->geo:lat field. + * + */ + public function getLatitude() { return $this->get('geo:lat'); } + + /** + * Get the contents of the ->geo:lat field. + * + */ + public function getLongitude() { return $this->get('geo:long'); } + + /** + * Get the ->location metadata. + * + */ + public function getLocation() { return $this->get('location'); } + + // NOTABLE INTERFACE /////////////////////////////////////////////////////////////// + + /** + * Calendar functionality. + * This function sets the time of an object on a calendar listing. + * + * @param int $hour If ommitted, now is assumed. + * @param int $minute If ommitted, now is assumed. + * @param int $second If ommitted, now is assumed. + * @param int $day If ommitted, now is assumed. + * @param int $month If ommitted, now is assumed. + * @param int $year If ommitted, now is assumed. + * @param int $duration Duration of event, remainder of the day is assumed. + */ + public function setCalendarTimeAndDuration($hour = NULL, $minute = NULL, $second = NULL, $day = NULL, $month = NULL, $year = NULL, $duration = NULL) + { + $start = mktime($hour, $minute, $second, $month, $day, $year); + $end = $start + abs($duration); + if (!$duration) + $end = get_day_end($day,$month,$year); + + $this->calendar_start = $start; + $this->calendar_end = $end; + + return true; + } + + /** + * Return the start timestamp. + */ + public function getCalendarStartTime() { return (int)$this->calendar_start; } + + /** + * Return the end timestamp. + */ + public function getCalendarEndTime() { return (int)$this->calendar_end; } + + // EXPORTABLE INTERFACE //////////////////////////////////////////////////////////// + + /** + * Return an array of fields which can be exported. + */ + public function getExportableValues() + { + return array( + 'guid', + 'type', + 'subtype', + 'time_created', + 'container_guid', + 'owner_guid', + ); + } + + /** + * Export this class into an array of ODD Elements containing all necessary fields. + * Override if you wish to return more information than can be found in $this->attributes (shouldn't happen) + */ + public function export() + { + $tmp = array(); + + // Generate uuid + $uuid = guid_to_uuid($this->getGUID()); + + // Create entity + $odd = new ODDEntity( + $uuid, + $this->attributes['type'], + get_subtype_from_id($this->attributes['subtype']) + ); + + $tmp[] = $odd; + + $exportable_values = $this->getExportableValues(); + + // Now add its attributes + foreach ($this->attributes as $k => $v) + { + $meta = NULL; + + if (in_array( $k, $exportable_values)) { + switch ($k) + { + case 'guid' : // Dont use guid in OpenDD + case 'type' : // Type and subtype already taken care of + case 'subtype' : + break; + + case 'time_created' : // Created = published + $odd->setAttribute('published', date("r", $v)); + break; + + case 'site_guid' : // Container + $k = 'site_uuid'; + $v = guid_to_uuid($v); + $meta = new ODDMetaData($uuid . "attr/$k/", $uuid, $k, $v); + break; + + case 'container_guid' : // Container + $k = 'container_uuid'; + $v = guid_to_uuid($v); + $meta = new ODDMetaData($uuid . "attr/$k/", $uuid, $k, $v); + break; + + case 'owner_guid' : // Convert owner guid to uuid, this will be stored in metadata + $k = 'owner_uuid'; + $v = guid_to_uuid($v); + $meta = new ODDMetaData($uuid . "attr/$k/", $uuid, $k, $v); + break; + + default : + $meta = new ODDMetaData($uuid . "attr/$k/", $uuid, $k, $v); + } + + // set the time of any metadata created + if ($meta) + { + $meta->setAttribute('published', date("r",$this->time_created)); + $tmp[] = $meta; + } + } + } + + // Now we do something a bit special. + /* + * This provides a rendered view of the entity to foreign sites. + */ + + elgg_set_viewtype('default'); + $view = elgg_view_entity($this, true); + elgg_set_viewtype(); + + $tmp[] = new ODDMetaData($uuid . "volatile/renderedentity/", $uuid, 'renderedentity', $view , 'volatile'); + + + return $tmp; + } + + // IMPORTABLE INTERFACE //////////////////////////////////////////////////////////// + + /** + * Import data from an parsed xml data array. + * + * @param array $data + * @param int $version + */ + public function import(ODD $data) + { + if (!($data instanceof ODDEntity)) + throw new InvalidParameterException(elgg_echo('InvalidParameterException:UnexpectedODDClass')); + + // Set type and subtype + $this->attributes['type'] = $data->getAttribute('class'); + $this->attributes['subtype'] = $data->getAttribute('subclass'); + + // Set owner + $this->attributes['owner_guid'] = get_loggedin_userid(); // Import as belonging to importer. + + // Set time + $this->attributes['time_created'] = strtotime($data->getAttribute('published')); + $this->attributes['time_updated'] = time(); + + return true; + } + + // SYSTEM LOG INTERFACE //////////////////////////////////////////////////////////// + + /** + * Return an identification for the object for storage in the system log. + * This id must be an integer. + * + * @return int + */ + public function getSystemLogID() { return $this->getGUID(); } + + /** + * Return the class name of the object. + */ + public function getClassName() { return get_class($this); } + + /** + * For a given ID, return the object associated with it. + * This is used by the river functionality primarily. + * This is useful for checking access permissions etc on objects. + */ + public function getObjectFromID($id) { return get_entity($id); } + + /** + * Return the GUID of the owner of this object. + */ + public function getObjectOwnerGUID() { return $this->owner_guid; } + + // ITERATOR INTERFACE ////////////////////////////////////////////////////////////// + /* + * This lets an entity's attributes be displayed using foreach as a normal array. + * Example: http://www.sitepoint.com/print/php5-standard-library + */ + + private $valid = FALSE; + + function rewind() + { + $this->valid = (FALSE !== reset($this->attributes)); + } + + function current() + { + return current($this->attributes); + } + + function key() + { + return key($this->attributes); + } + + function next() + { + $this->valid = (FALSE !== next($this->attributes)); + } + + function valid() + { + return $this->valid; + } + + // ARRAY ACCESS INTERFACE ////////////////////////////////////////////////////////// + /* + * This lets an entity's attributes be accessed like an associative array. + * Example: http://www.sitepoint.com/print/php5-standard-library + */ + + function offsetSet($key, $value) + { + if ( array_key_exists($key, $this->attributes) ) { + $this->attributes[$key] = $value; + } + } + + function offsetGet($key) + { + if ( array_key_exists($key, $this->attributes) ) { + return $this->attributes[$key]; + } + } + + function offsetUnset($key) + { + if ( array_key_exists($key, $this->attributes) ) { + $this->attributes[$key] = ""; // Full unsetting is dangerious for our objects + } + } + + function offsetExists($offset) + { + return array_key_exists($offset, $this->attributes); + } + } + + /** + * Initialise the entity cache. + */ + function initialise_entity_cache() + { + global $ENTITY_CACHE; + + if (!$ENTITY_CACHE) + $ENTITY_CACHE = array(); //select_default_memcache('entity_cache'); // TODO: Replace with memcache? + } + + /** + * Invalidate this class' entry in the cache. + * + * @param int $guid The guid + */ + function invalidate_cache_for_entity($guid) + { + global $ENTITY_CACHE; + + $guid = (int)$guid; + + unset($ENTITY_CACHE[$guid]); + //$ENTITY_CACHE->delete($guid); + } + + /** + * Cache an entity. + * + * @param ElggEntity $entity Entity to cache + */ + function cache_entity(ElggEntity $entity) + { + global $ENTITY_CACHE; + + $ENTITY_CACHE[$entity->guid] = $entity; + } + + /** + * Retrieve a entity from the cache. + * + * @param int $guid The guid + */ + function retrieve_cached_entity($guid) + { + global $ENTITY_CACHE; + + $guid = (int)$guid; + + if (isset($ENTITY_CACHE[$guid])) + if ($ENTITY_CACHE[$guid]->isFullyLoaded()) return $ENTITY_CACHE[$guid]; + + return false; + } + + /** + * As retrieve_cached_entity, but returns the result as a stdClass (compatible with load functions that + * expect a database row.) + * + * @param int $guid The guid + */ + function retrieve_cached_entity_row($guid) + { + $obj = retrieve_cached_entity($guid); + if ($obj) + { + $tmp = new stdClass; + + foreach ($obj as $k => $v) + $tmp->$k = $v; + + return $tmp; + } + + return false; + } + + /** + * Return the integer ID for a given subtype, or false. + * + * TODO: Move to a nicer place? + * + * @param string $type + * @param string $subtype + */ + function get_subtype_id($type, $subtype) + { + global $CONFIG, $SUBTYPE_CACHE; + + $type = sanitise_string($type); + $subtype = sanitise_string($subtype); + + if ($subtype=="") return $subtype; + + // Todo: cache here? Or is looping less efficient that going to the db each time? + + $result = get_data_row("SELECT * from {$CONFIG->dbprefix}entity_subtypes where type='$type' and subtype='$subtype'"); + + if ($result) { + + if (!$SUBTYPE_CACHE) + $SUBTYPE_CACHE = array(); //select_default_memcache('subtype_cache'); + + $SUBTYPE_CACHE[$result->id] = $result; + return $result->id; + } + + return 0; + } + + /** + * For a given subtype ID, return its identifier text. + * + * TODO: Move to a nicer place? + * + * @param int $subtype_id + */ + function get_subtype_from_id($subtype_id) + { + global $CONFIG, $SUBTYPE_CACHE; + + $subtype_id = (int)$subtype_id; + + if (!$subtype_id) return false; + + if (isset($SUBTYPE_CACHE[$subtype_id])) + return $SUBTYPE_CACHE[$subtype_id]->subtype; + + $result = get_data_row("SELECT * from {$CONFIG->dbprefix}entity_subtypes where id=$subtype_id"); + if ($result) { + + if (!$SUBTYPE_CACHE) + $SUBTYPE_CACHE = array(); //select_default_memcache('subtype_cache'); + + $SUBTYPE_CACHE[$subtype_id] = $result; + return $result->subtype; + } + + return false; + } + + /** + * This function tests to see if a subtype has a registered class handler. + * + * @param string $type The type + * @param string $subtype The subtype + * @return a class name or null + */ + function get_subtype_class($type, $subtype) + { + global $CONFIG, $SUBTYPE_CACHE; + + $type = sanitise_string($type); + $subtype = sanitise_string($subtype); + + // Todo: cache here? Or is looping less efficient that going to the db each time? + + $result = get_data_row("SELECT * from {$CONFIG->dbprefix}entity_subtypes where type='$type' and subtype='$subtype'"); + if ($result) { + + if (!$SUBTYPE_CACHE) + $SUBTYPE_CACHE = array(); //select_default_memcache('subtype_cache'); + + $SUBTYPE_CACHE[$result->id] = $result; + return $result->class; + } + + return NULL; + } + + /** + * This function tests to see if a subtype has a registered class handler by its id. + * + * @param int $subtype_id The subtype + * @return a class name or null + */ + function get_subtype_class_from_id($subtype_id) + { + global $CONFIG, $SUBTYPE_CACHE; + + $subtype_id = (int)$subtype_id; + + if (!$subtype_id) return false; + + if (isset($SUBTYPE_CACHE[$subtype_id])) + return $SUBTYPE_CACHE[$subtype_id]->class; + + $result = get_data_row("SELECT * from {$CONFIG->dbprefix}entity_subtypes where id=$subtype_id"); + if ($result) { + + if (!$SUBTYPE_CACHE) + $SUBTYPE_CACHE = array(); //select_default_memcache('subtype_cache'); + + $SUBTYPE_CACHE[$subtype_id] = $result; + return $result->class; + } + + return NULL; + } + + /** + * This function will register a new subtype, returning its ID as required. + * + * @param string $type The type you're subtyping + * @param string $subtype The subtype label + * @param string $class Optional class handler (if you don't want it handled by the generic elgg handler for the type) + */ + function add_subtype($type, $subtype, $class = "") + { + global $CONFIG; + $type = sanitise_string($type); + $subtype = sanitise_string($subtype); + $class = sanitise_string($class); + + // Short circuit if no subtype is given + if ($subtype == "") + return 0; + + $id = get_subtype_id($type, $subtype); + + if ($id==0) + return insert_data("insert into {$CONFIG->dbprefix}entity_subtypes (type, subtype, class) values ('$type','$subtype','$class')"); + + return $id; + } + + /** + * Update an existing entity. + * + * @param int $guid + * @param int $owner_guid + * @param int $access_id + * @param int $container_guid + */ + function update_entity($guid, $owner_guid, $access_id, $container_guid = null) + { + global $CONFIG, $ENTITY_CACHE; + + $guid = (int)$guid; + $owner_guid = (int)$owner_guid; + $access_id = (int)$access_id; + $container_guid = (int) $container_guid; + if (is_null($container_guid)) $container_guid = $owner_guid; + $time = time(); + + $entity = get_entity($guid); + + if ($entity->canEdit()) { + + if (trigger_elgg_event('update',$entity->type,$entity)) { + $ret = update_data("UPDATE {$CONFIG->dbprefix}entities set owner_guid='$owner_guid', access_id='$access_id', container_guid='$container_guid', time_updated='$time' WHERE guid=$guid"); + + if ($entity instanceof ElggObject) + update_river_access_by_object($guid,$access_id); + + // If memcache is available then delete this entry from the cache + static $newentity_cache; + if ((!$newentity_cache) && (is_memcache_available())) + $newentity_cache = new ElggMemcache('new_entity_cache'); + if ($newentity_cache) $new_entity = $newentity_cache->delete($guid); + + // Handle cases where there was no error BUT no rows were updated! + if ($ret===false) + return false; + + return true; + } + + } + } + + /** + * Determine whether a given user is able to write to a given container. + * + * @param int $user_guid The user guid, or 0 for get_loggedin_userid() + * @param int $container_guid The container, or 0 for the current page owner. + */ + function can_write_to_container($user_guid = 0, $container_guid = 0, $entity_type = 'all') + { + global $CONFIG; + + $user_guid = (int)$user_guid; + $user = get_entity($user_guid); + if (!$user) $user = get_loggedin_user(); + + $container_guid = (int)$container_guid; + if (!$container_guid) $container_guid = page_owner(); + if (!$container_guid) return true; + + $container = get_entity($container_guid); + + if ($container) + { + + // If the user can edit the container, they can also write to it + if ($container->canEdit($user_guid)) return true; + + // Basics, see if the user is a member of the group. + if ($user && $container instanceof ElggGroup) { + if (!$container->isMember($user)) { + return false; + } else { + return true; + } + } + + // See if anyone else has anything to say + return trigger_plugin_hook('container_permissions_check',$entity_type,array('container' => $container, 'user' => $user), false); + + } + + return false; + } + + /** + * Create a new entity of a given type. + * + * @param string $type The type of the entity (site, user, object). + * @param string $subtype The subtype of the entity. + * @param int $owner_guid The GUID of the object's owner. + * @param int $access_id The access control group to create the entity with. + * @param int $site_guid The site to add this entity to. Leave as 0 (default) for the current site. + * @return mixed The new entity's GUID, or false on failure + */ + function create_entity($type, $subtype, $owner_guid, $access_id, $site_guid = 0, $container_guid = 0) + { + global $CONFIG; + + $type = sanitise_string($type); + $subtype = add_subtype($type, $subtype); + $owner_guid = (int)$owner_guid; + $access_id = (int)$access_id; + $time = time(); + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + $site_guid = (int) $site_guid; + if ($container_guid == 0) $container_guid = $owner_guid; + + $user = get_loggedin_user(); + if (!can_write_to_container($user->guid, $owner_guid, $type)) return false; + if ($owner_guid != $container_guid) + if (!can_write_to_container($user->guid, $container_guid, $type)) return false; + + if ($type=="") throw new InvalidParameterException(elgg_echo('InvalidParameterException:EntityTypeNotSet')); + + return insert_data("INSERT into {$CONFIG->dbprefix}entities (type, subtype, owner_guid, site_guid, container_guid, access_id, time_created, time_updated) values ('$type',$subtype, $owner_guid, $site_guid, $container_guid, $access_id, $time, $time)"); + } + + /** + * Retrieve the entity details for a specific GUID, returning it as a stdClass db row. + * + * You will only get an object if a) it exists, b) you have access to it. + * + * @param int $guid The GUID of the object to extract + */ + function get_entity_as_row($guid) + { + global $CONFIG; + + if (!$guid) return false; + + $guid = (int) $guid; + + /*$row = retrieve_cached_entity_row($guid); + if ($row) + { + // We have already cached this object, so retrieve its value from the cache + if (isset($CONFIG->debug) && $CONFIG->debug) + error_log("** Retrieving GUID:$guid from cache"); + + return $row; + } + else + {*/ + // Object not cached, load it. + if (isset($CONFIG->debug) && $CONFIG->debug == true) + error_log("** GUID:$guid loaded from DB"); + + $access = get_access_sql_suffix(); + + return get_data_row("SELECT * from {$CONFIG->dbprefix}entities where guid=$guid and $access"); + //} + } + + /** + * Create an Elgg* object from a given entity row. + */ + function entity_row_to_elggstar($row) + { + if (!($row instanceof stdClass)) + return $row; + + if ((!isset($row->guid)) || (!isset($row->subtype))) + return $row; + + $new_entity = false; + + // Create a memcache cache if we can + static $newentity_cache; + if ((!$newentity_cache) && (is_memcache_available())) + $newentity_cache = new ElggMemcache('new_entity_cache'); + if ($newentity_cache) $new_entity = $newentity_cache->load($row->guid); + if ($new_entity) return $new_entity; + + $classname = get_subtype_class_from_id($row->subtype); + if ($classname!="") + { + if (class_exists($classname)) + { + $new_entity = new $classname($row); + + if (!($new_entity instanceof ElggEntity)) + throw new ClassException(sprintf(elgg_echo('ClassException:ClassnameNotClass'), $classname, 'ElggEntity')); + } + else + error_log(sprintf(elgg_echo('ClassNotFoundException:MissingClass'), $classname)); + } + else + { + switch ($row->type) + { + case 'object' : + $new_entity = new ElggObject($row); break; + case 'user' : + $new_entity = new ElggUser($row); break; + case 'group' : + $new_entity = new ElggGroup($row); break; + case 'site' : + $new_entity = new ElggSite($row); break; + default: throw new InstallationException(sprintf(elgg_echo('InstallationException:TypeNotSupported'), $row->type)); + } + + } + + // Cache entity if we have a cache available + if (($newentity_cache) && ($new_entity)) $newentity_cache->save($new_entity->guid, $new_entity); + + return $new_entity; + } + + /** + * Return the entity for a given guid as the correct object. + * @param int $guid The GUID of the entity + * @return a child of ElggEntity appropriate for the type. + */ + function get_entity($guid) + { + static $newentity_cache; + $new_entity = false; + if ((!$newentity_cache) && (is_memcache_available())) + $newentity_cache = new ElggMemcache('new_entity_cache'); + if ($newentity_cache) $new_entity = $newentity_cache->load($guid); + if ($new_entity) return $new_entity; + + return entity_row_to_elggstar(get_entity_as_row($guid)); + } + + /** + * Return entities matching a given query, or the number thereof + * + * @param string $type The type of entity (eg "user", "object" etc) + * @param string|array $subtype The arbitrary subtype of the entity or array(type1 => array('subtype1', ...'subtypeN'), ...) + * @param int $owner_guid The GUID of the owning user + * @param string $order_by The field to order by; by default, time_created desc + * @param int $limit The number of entities to return; 10 by default + * @param int $offset The indexing offset, 0 by default + * @param boolean $count Set to true to get a count rather than the entities themselves (limits and offsets don't apply in this context). Defaults to false. + * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. + * @param int|array $container_guid The container or containers to get entities from (default: all containers). + * @param int $timelower The earliest time the entity can have been created. Default: all + * @param int $timeupper The latest time the entity can have been created. Default: all + * @return array A list of entities. + */ + function get_entities($type = "", $subtype = "", $owner_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false, $site_guid = 0, $container_guid = null, $timelower = 0, $timeupper = 0) + { + global $CONFIG; + + if ($subtype === false || $subtype === null || $subtype === 0) + return false; + + if ($order_by == "") $order_by = "time_created desc"; + $order_by = sanitise_string($order_by); + $limit = (int)$limit; + $offset = (int)$offset; + $site_guid = (int) $site_guid; + $timelower = (int) $timelower; + $timeupper = (int) $timeupper; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + $where = array(); + + if (is_array($subtype)) { + $tempwhere = ""; + if (sizeof($subtype)) + foreach($subtype as $typekey => $subtypearray) { + foreach($subtypearray as $subtypeval) { + $typekey = sanitise_string($typekey); + if (!empty($subtypeval)) { + if (!$subtypeval = (int) get_subtype_id($typekey, $subtypeval)) + return false; + } else { + // @todo: Setting subtype to 0 when $subtype = '' returns entities with + // no subtype. This is different to the non-array behavior + // but may be required in some cases. + $subtypeval = 0; + } + if (!empty($tempwhere)) $tempwhere .= " or "; + $tempwhere .= "(type = '{$typekey}' and subtype = {$subtypeval})"; + } + } + if (!empty($tempwhere)) $where[] = "({$tempwhere})"; + + } else { + + $type = sanitise_string($type); + if ($subtype !== "" AND !$subtype = get_subtype_id($type, $subtype)) + return false; + + if ($type != "") + $where[] = "type='$type'"; + if ($subtype!=="") + $where[] = "subtype=$subtype"; + } + + if ($owner_guid != "") { + if (!is_array($owner_guid)) { + $owner_array = array($owner_guid); + $owner_guid = (int) $owner_guid; + // $where[] = "owner_guid = '$owner_guid'"; + } else if (sizeof($owner_guid) > 0) { + $owner_array = array_map('sanitise_int', $owner_guid); + // Cast every element to the owner_guid array to int + // $owner_guid = array_map("sanitise_int", $owner_guid); + // $owner_guid = implode(",",$owner_guid); + // $where[] = "owner_guid in ({$owner_guid})"; + } + if (is_null($container_guid)) { + $container_guid = $owner_array; + } + } + if ($site_guid > 0) + $where[] = "site_guid = {$site_guid}"; + + if (!is_null($container_guid)) { + if (is_array($container_guid)) { + foreach($container_guid as $key => $val) $container_guid[$key] = (int) $val; + $where[] = "container_guid in (" . implode(",",$container_guid) . ")"; + } else { + $container_guid = (int) $container_guid; + $where[] = "container_guid = {$container_guid}"; + } + } + if ($timelower) + $where[] = "time_created >= {$timelower}"; + if ($timeupper) + $where[] = "time_created <= {$timeupper}"; + + if (!$count) { + $query = "SELECT * from {$CONFIG->dbprefix}entities where "; + } else { + $query = "SELECT count(guid) as total from {$CONFIG->dbprefix}entities where "; + } + foreach ($where as $w) + $query .= " $w and "; + $query .= get_access_sql_suffix(); // Add access controls + if (!$count) { + $query .= " order by $order_by"; + if ($limit) $query .= " limit $offset, $limit"; // Add order and limit + $dt = get_data($query, "entity_row_to_elggstar"); + return $dt; + } else { + $total = get_data_row($query); + return $total->total; + } + } + + /** + * Returns a viewable list of entities + * + * @see elgg_view_entity_list + * + * @param string $type The type of entity (eg "user", "object" etc) + * @param string $subtype The arbitrary subtype of the entity + * @param int $owner_guid The GUID of the owning user + * @param int $limit The number of entities to display per page (default: 10) + * @param true|false $fullview Whether or not to display the full view (default: true) + * @param true|false $viewtypetoggle Whether or not to allow gallery view + * @param true|false $pagination Display pagination? Default: true + * @return string A viewable list of entities + */ + function list_entities($type= "", $subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = false, $pagination = true) { + + $offset = (int) get_input('offset'); + $count = get_entities($type, $subtype, $owner_guid, "", $limit, $offset, true); + $entities = get_entities($type, $subtype, $owner_guid, "", $limit, $offset); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); + + } + + /** + * Returns a viewable list of entities contained in a number of groups. + * + * @param string $subtype The arbitrary subtype of the entity + * @param int $owner_guid The GUID of the owning user + * @param int $container_guid The GUID of the containing group + * @param int $limit The number of entities to display per page (default: 10) + * @param true|false $fullview Whether or not to display the full view (default: true) + * @return string A viewable list of entities + */ + function list_entities_groups($subtype = "", $owner_guid = 0, $container_guid = 0, $limit = 10, $fullview = true) + { + $offset = (int) get_input('offset'); + $count = get_objects_in_group($container_guid, $subtype, $owner_guid, 0, "", $limit, $offset, true); + $entities = get_objects_in_group($container_guid, $subtype, $owner_guid, 0, "", $limit, $offset); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview); + } + + /** + * Returns a list of months containing content specified by the parameters + * + * @param string $type The type of entity + * @param string $subtype The subtype of entity + * @param int $container_guid The container GUID that the entinties belong to + * @param int $site_guid The site GUID + * @return array|false Either an array of timestamps, or false on failure + */ + function get_entity_dates($type = '', $subtype = '', $container_guid = 0, $site_guid = 0) { + + global $CONFIG; + + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + $where = array(); + + if ($type != "") { + $type = sanitise_string($type); + $where[] = "type='$type'"; + } + + if (is_array($subtype)) { + $tempwhere = ""; + if (sizeof($subtype)) + foreach($subtype as $typekey => $subtypearray) { + foreach($subtypearray as $subtypeval) { + $typekey = sanitise_string($typekey); + if (!empty($subtypeval)) { + if (!$subtypeval = (int) get_subtype_id($typekey, $subtypeval)) + return false; + } else { + $subtypeval = 0; + } + if (!empty($tempwhere)) $tempwhere .= " or "; + $tempwhere .= "(type = '{$typekey}' and subtype = {$subtypeval})"; + } + } + if (!empty($tempwhere)) $where[] = "({$tempwhere})"; + + } else { + if ($subtype AND !$subtype = get_subtype_id($type, $subtype)) { + return false; + } else { + $where[] = "subtype=$subtype"; + } + } + + if ($container_guid !== 0) { + if (is_array($container_guid)) { + foreach($container_guid as $key => $val) $container_guid[$key] = (int) $val; + $where[] = "container_guid in (" . implode(",",$container_guid) . ")"; + } else { + $container_guid = (int) $container_guid; + $where[] = "container_guid = {$container_guid}"; + } + } + + if ($site_guid > 0) + $where[] = "site_guid = {$site_guid}"; + + $where[] = get_access_sql_suffix(); + + $sql = "SELECT DISTINCT EXTRACT(YEAR_MONTH FROM FROM_UNIXTIME(time_created)) AS yearmonth FROM {$CONFIG->dbprefix}entities where "; + foreach ($where as $w) + $sql .= " $w and "; + $sql .= "1=1"; + if ($result = get_data($sql)) { + $endresult = array(); + foreach($result as $res) { + $endresult[] = $res->yearmonth; + } + return $endresult; + } + return false; + + } + + /** + * Disable an entity but not delete it. + * + * @param int $guid The guid + * @param string $reason Optional reason + */ + function disable_entity($guid, $reason = "", $recursive = true) + { + global $CONFIG; + + $guid = (int)$guid; + $reason = sanitise_string($reason); + + if ($entity = get_entity($guid)) { + if (trigger_elgg_event('disable',$entity->type,$entity)) { + if ($entity->canEdit()) { + + if ($reason) + create_metadata($guid, 'disable_reason', $reason,'', 0, ACCESS_PUBLIC); + + if ($recursive) + { + // Temporary token overriding access controls TODO: Do this better. + static $__RECURSIVE_DELETE_TOKEN; + $__RECURSIVE_DELETE_TOKEN = md5(get_loggedin_userid()); // Make it slightly harder to guess + + $sub_entities = get_data("SELECT * from {$CONFIG->dbprefix}entities WHERE container_guid=$guid or owner_guid=$guid or site_guid=$guid", 'entity_row_to_elggstar'); + if ($sub_entities) { + foreach ($sub_entities as $e) + $e->disable($reason); + } + + $__RECURSIVE_DELETE_TOKEN = null; + } + + $res = update_data("UPDATE {$CONFIG->dbprefix}entities set enabled='no' where guid={$guid}"); + + return $res; + } + } + } + return false; + } + + /** + * Enable an entity again. + * + * @param int $guid + */ + function enable_entity($guid) + { + global $CONFIG; + + $guid = (int)$guid; + + // Override access only visible entities + $access_status = access_get_show_hidden_status(); + access_show_hidden_entities(true); + + if ($entity = get_entity($guid)) { + if (trigger_elgg_event('enable',$entity->type,$entity)) { + if ($entity->canEdit()) { + + access_show_hidden_entities($access_status); + + $result = update_data("UPDATE {$CONFIG->dbprefix}entities set enabled='yes' where guid={$guid}"); + $entity->clearMetaData('disable_reason'); + + return $result; + } + } + } + + access_show_hidden_entities($access_status); + return false; + } + + /** + * Delete a given entity. + * + * @param int $guid + * @param bool $recursive If true (default) then all entities which are owned or contained by $guid will also be deleted. + * Note: this bypasses ownership of sub items. + */ + function delete_entity($guid, $recursive = true) + { + global $CONFIG; + + $guid = (int)$guid; + if ($entity = get_entity($guid)) { + if (trigger_elgg_event('delete',$entity->type,$entity)) { + if ($entity->canEdit()) { + + // Delete contained owned and otherwise releated objects (depth first) + if ($recursive) + { + // Temporary token overriding access controls TODO: Do this better. + static $__RECURSIVE_DELETE_TOKEN; + $__RECURSIVE_DELETE_TOKEN = md5(get_loggedin_userid()); // Make it slightly harder to guess + + $sub_entities = get_data("SELECT * from {$CONFIG->dbprefix}entities WHERE container_guid=$guid or owner_guid=$guid or site_guid=$guid", 'entity_row_to_elggstar'); + if ($sub_entities) { + foreach ($sub_entities as $e) + $e->delete(); + } + + $__RECURSIVE_DELETE_TOKEN = null; + } + + // Now delete the entity itself + $entity->clearMetadata(); + $entity->clearAnnotations(); + $entity->clearRelationships(); + remove_from_river_by_subject($guid); remove_from_river_by_object($guid); - remove_all_private_settings($guid); + remove_all_private_settings($guid); $res = delete_data("DELETE from {$CONFIG->dbprefix}entities where guid={$guid}"); if ($res) { $sub_table = ""; - // Where appropriate delete the sub table - switch ($entity->type) - { - case 'object' : $sub_table = $CONFIG->dbprefix . 'objects_entity'; break; - case 'user' : $sub_table = $CONFIG->dbprefix . 'users_entity'; break; - case 'group' : $sub_table = $CONFIG->dbprefix . 'groups_entity'; break; - case 'site' : $sub_table = $CONFIG->dbprefix . 'sites_entity'; break; - } + // Where appropriate delete the sub table + switch ($entity->type) + { + case 'object' : $sub_table = $CONFIG->dbprefix . 'objects_entity'; break; + case 'user' : $sub_table = $CONFIG->dbprefix . 'users_entity'; break; + case 'group' : $sub_table = $CONFIG->dbprefix . 'groups_entity'; break; + case 'site' : $sub_table = $CONFIG->dbprefix . 'sites_entity'; break; + } + + if ($sub_table) + delete_data("DELETE from $sub_table where guid={$guid}"); + } + + return $res; + } + } + } + return false; + + } + + /** + * Delete multiple entities that match a given query. + * This function itterates through and calls delete_entity on each one, this is somewhat inefficient but lets + * the 'delete' even be called for each entity. + * + * @param string $type The type of entity (eg "user", "object" etc) + * @param string $subtype The arbitrary subtype of the entity + * @param int $owner_guid The GUID of the owning user + */ + function delete_entities($type = "", $subtype = "", $owner_guid = 0) + { + $entities = get_entities($type, $subtype, $owner_guid, "time_created desc", 0); + + foreach ($entities as $entity) + delete_entity($entity->guid); + + return true; + } + + /** + * A plugin hook to get certain volitile (generated on the fly) attributes about an entity in order to export them. + * + * @param unknown_type $hook + * @param unknown_type $entity_type + * @param unknown_type $returnvalue + * @param unknown_type $params The parameters, passed 'guid' and 'varname' + * @return unknown + */ + function volatile_data_export_plugin_hook($hook, $entity_type, $returnvalue, $params) + { + $guid = (int)$params['guid']; + $variable_name = sanitise_string($params['varname']); + + if (($hook == 'volatile') && ($entity_type == 'metadata')) + { + if (($guid) && ($variable_name)) + { + switch ($variable_name) + { + case 'renderedentity' : + elgg_set_viewtype('default'); + $view = elgg_view_entity(get_entity($guid)); + elgg_set_viewtype(); + + $tmp = new ElggMetadata(); + $tmp->type = 'volatile'; + $tmp->name = 'renderedentity'; + $tmp->value = $view; + $tmp->entity_guid = $guid; - if ($sub_table) - delete_data("DELETE from $sub_table where guid={$guid}"); - } - - return $res; - } - } - } - return false; - - } - - /** - * Delete multiple entities that match a given query. - * This function itterates through and calls delete_entity on each one, this is somewhat inefficient but lets - * the 'delete' even be called for each entity. - * - * @param string $type The type of entity (eg "user", "object" etc) - * @param string $subtype The arbitrary subtype of the entity - * @param int $owner_guid The GUID of the owning user - */ - function delete_entities($type = "", $subtype = "", $owner_guid = 0) - { - $entities = get_entities($type, $subtype, $owner_guid, "time_created desc", 0); - - foreach ($entities as $entity) - delete_entity($entity->guid); - - return true; - } - - /** - * A plugin hook to get certain volitile (generated on the fly) attributes about an entity in order to export them. - * - * @param unknown_type $hook - * @param unknown_type $entity_type - * @param unknown_type $returnvalue - * @param unknown_type $params The parameters, passed 'guid' and 'varname' - * @return unknown - */ - function volatile_data_export_plugin_hook($hook, $entity_type, $returnvalue, $params) - { - $guid = (int)$params['guid']; - $variable_name = sanitise_string($params['varname']); - - if (($hook == 'volatile') && ($entity_type == 'metadata')) - { - if (($guid) && ($variable_name)) - { - switch ($variable_name) - { - case 'renderedentity' : - elgg_set_viewtype('default'); - $view = elgg_view_entity(get_entity($guid)); - elgg_set_viewtype(); - - $tmp = new ElggMetadata(); - $tmp->type = 'volatile'; - $tmp->name = 'renderedentity'; - $tmp->value = $view; - $tmp->entity_guid = $guid; - - return $tmp; - - break; - } - } - } - } - - /** - * Handler called by trigger_plugin_hook on the "export" event. - */ - function export_entity_plugin_hook($hook, $entity_type, $returnvalue, $params) - { - // Sanity check values - if ((!is_array($params)) && (!isset($params['guid']))) - throw new InvalidParameterException(elgg_echo('InvalidParameterException:GUIDNotForExport')); - - if (!is_array($returnvalue)) - throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonArrayReturnValue')); - - $guid = (int)$params['guid']; - - // Get the entity - $entity = get_entity($guid); - if (!($entity instanceof ElggEntity)) - throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $guid, get_class())); - - $export = $entity->export(); - - if (is_array($export)) - foreach ($export as $e) - $returnvalue[] = $e; - else - $returnvalue[] = $export; - - return $returnvalue; - } - - /** - * Utility function used by import_entity_plugin_hook() to process an ODDEntity into an unsaved ElggEntity. - * - * @param ODDEntity $element The OpenDD element - * @return ElggEntity the unsaved entity which should be populated by items. - */ - function oddentity_to_elggentity(ODDEntity $element) - { - $class = $element->getAttribute('class'); - $subclass = $element->getAttribute('subclass'); - - // See if we already have imported this uuid - $tmp = get_entity_from_uuid($element->getAttribute('uuid')); - - if (!$tmp) - { - // Construct new class with owner from session - $classname = get_subtype_class($class, $subclass); - if ($classname!="") - { - if (class_exists($classname)) - { - $tmp = new $classname(); - - if (!($tmp instanceof ElggEntity)) - throw new ClassException(sprintf(elgg_echo('ClassException:ClassnameNotClass', $classname, get_class()))); - } - else - error_log(sprintf(elgg_echo('ClassNotFoundException:MissingClass'), $classname)); - } - else - { - switch ($class) - { - case 'object' : $tmp = new ElggObject($row); break; - case 'user' : $tmp = new ElggUser($row); break; - case 'group' : $tmp = new ElggGroup($row); break; - case 'site' : $tmp = new ElggSite($row); break; - default: throw new InstallationException(sprintf(elgg_echo('InstallationException:TypeNotSupported'), $class)); - } - } - } - - if ($tmp) - { - if (!$tmp->import($element)) - throw new ImportException(sprintf(elgg_echo('ImportException:ImportFailed'), $element->getAttribute('uuid'))); - - return $tmp; - } - - return NULL; - } - - /** - * Import an entity. - * This function checks the passed XML doc (as array) to see if it is a user, if so it constructs a new - * elgg user and returns "true" to inform the importer that it's been handled. - */ - function import_entity_plugin_hook($hook, $entity_type, $returnvalue, $params) - { - $element = $params['element']; - - $tmp = NULL; - - if ($element instanceof ODDEntity) - { - $tmp = oddentity_to_elggentity($element); - - if ($tmp) - { - if (!$tmp->save()) // Make sure its saved - throw new ImportException(sprintf(elgg_echo('ImportException:ProblemSaving'), $element->getAttribute('uuid'))); - - // Belts and braces - if (!$tmp->guid) - throw new ImportException(elgg_echo('ImportException:NoGUID')); - - add_uuid_to_guid($tmp->guid, $element->getAttribute('uuid')); // We have saved, so now tag - - return $tmp; - } - - } - } - - /** - * Determines whether or not the specified user can edit the specified entity. - * - * This is extendible by registering a plugin hook taking in the parameters 'entity' and 'user', - * which are the entity and user entities respectively - * - * @see register_plugin_hook - * - * @param int $entity_guid The GUID of the entity - * @param int $user_guid The GUID of the user - * @return true|false Whether the specified user can edit the specified entity. - */ - function can_edit_entity($entity_guid, $user_guid = 0) { - global $CONFIG; - - $user_guid = (int)$user_guid; - $user = get_entity($user_guid); - if (!$user) $user = get_loggedin_user(); - - if ($entity = get_entity($entity_guid)) { - - $return = false; - - // Test user if possible - should default to false unless a plugin hook says otherwise - if (!is_null($user)) - { - if ($entity->getOwner() == $user->getGUID()) $return = true; - if ($entity->container_guid == $user->getGUID()) $return = true; - if ($entity->type == "user" && $entity->getGUID() == $user->getGUID()) $return = true; - if ($container_entity = get_entity($entity->container_guid)) { - if ($container_entity->canEdit()) $return = true; - } - } - - return trigger_plugin_hook('permissions_check',$entity->type,array('entity' => $entity, 'user' => $user), $return); - - } else { - return false; - - } - - } - - /** - * Determines whether or not the specified user can edit metadata on the specified entity. - * - * This is extendible by registering a plugin hook taking in the parameters 'entity' and 'user', - * which are the entity and user entities respectively - * - * @see register_plugin_hook - * - * @param int $entity_guid The GUID of the entity - * @param int $user_guid The GUID of the user - * @param ElggMetadata $metadata The metadata to specifically check (if any; default null) - * @return true|false Whether the specified user can edit the specified entity. - */ - function can_edit_entity_metadata($entity_guid, $user_guid = 0, $metadata = null) { - - if ($entity = get_entity($entity_guid)) { - - $return = null; - - if ($metadata->owner_guid == 0) $return = true; - if (is_null($return)) - $return = can_edit_entity($entity_guid, $user_guid); - - $user = get_entity($user_guid); - $return = trigger_plugin_hook('permissions_check:metadata',$entity->type,array('entity' => $entity, 'user' => $user, 'metadata' => $metadata),$return); - return $return; - - } else { - return false; - } - - } - - - /** - * Get the icon for an entity - * - * @param ElggEntity $entity The entity (passed an entity rather than a guid to handle non-created entities) - * @param string $size - */ - function get_entity_icon_url(ElggEntity $entity, $size = 'medium') - { - global $CONFIG; - - $size = sanitise_string($size); - switch (strtolower($size)) - { + return $tmp; + + break; + } + } + } + } + + /** + * Handler called by trigger_plugin_hook on the "export" event. + */ + function export_entity_plugin_hook($hook, $entity_type, $returnvalue, $params) + { + // Sanity check values + if ((!is_array($params)) && (!isset($params['guid']))) + throw new InvalidParameterException(elgg_echo('InvalidParameterException:GUIDNotForExport')); + + if (!is_array($returnvalue)) + throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonArrayReturnValue')); + + $guid = (int)$params['guid']; + + // Get the entity + $entity = get_entity($guid); + if (!($entity instanceof ElggEntity)) + throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $guid, get_class())); + + $export = $entity->export(); + + if (is_array($export)) + foreach ($export as $e) + $returnvalue[] = $e; + else + $returnvalue[] = $export; + + return $returnvalue; + } + + /** + * Utility function used by import_entity_plugin_hook() to process an ODDEntity into an unsaved ElggEntity. + * + * @param ODDEntity $element The OpenDD element + * @return ElggEntity the unsaved entity which should be populated by items. + */ + function oddentity_to_elggentity(ODDEntity $element) + { + $class = $element->getAttribute('class'); + $subclass = $element->getAttribute('subclass'); + + // See if we already have imported this uuid + $tmp = get_entity_from_uuid($element->getAttribute('uuid')); + + if (!$tmp) + { + // Construct new class with owner from session + $classname = get_subtype_class($class, $subclass); + if ($classname!="") + { + if (class_exists($classname)) + { + $tmp = new $classname(); + + if (!($tmp instanceof ElggEntity)) + throw new ClassException(sprintf(elgg_echo('ClassException:ClassnameNotClass', $classname, get_class()))); + } + else + error_log(sprintf(elgg_echo('ClassNotFoundException:MissingClass'), $classname)); + } + else + { + switch ($class) + { + case 'object' : $tmp = new ElggObject($row); break; + case 'user' : $tmp = new ElggUser($row); break; + case 'group' : $tmp = new ElggGroup($row); break; + case 'site' : $tmp = new ElggSite($row); break; + default: throw new InstallationException(sprintf(elgg_echo('InstallationException:TypeNotSupported'), $class)); + } + } + } + + if ($tmp) + { + if (!$tmp->import($element)) + throw new ImportException(sprintf(elgg_echo('ImportException:ImportFailed'), $element->getAttribute('uuid'))); + + return $tmp; + } + + return NULL; + } + + /** + * Import an entity. + * This function checks the passed XML doc (as array) to see if it is a user, if so it constructs a new + * elgg user and returns "true" to inform the importer that it's been handled. + */ + function import_entity_plugin_hook($hook, $entity_type, $returnvalue, $params) + { + $element = $params['element']; + + $tmp = NULL; + + if ($element instanceof ODDEntity) + { + $tmp = oddentity_to_elggentity($element); + + if ($tmp) + { + if (!$tmp->save()) // Make sure its saved + throw new ImportException(sprintf(elgg_echo('ImportException:ProblemSaving'), $element->getAttribute('uuid'))); + + // Belts and braces + if (!$tmp->guid) + throw new ImportException(elgg_echo('ImportException:NoGUID')); + + add_uuid_to_guid($tmp->guid, $element->getAttribute('uuid')); // We have saved, so now tag + + return $tmp; + } + + } + } + + /** + * Determines whether or not the specified user can edit the specified entity. + * + * This is extendible by registering a plugin hook taking in the parameters 'entity' and 'user', + * which are the entity and user entities respectively + * + * @see register_plugin_hook + * + * @param int $entity_guid The GUID of the entity + * @param int $user_guid The GUID of the user + * @return true|false Whether the specified user can edit the specified entity. + */ + function can_edit_entity($entity_guid, $user_guid = 0) { + global $CONFIG; + + $user_guid = (int)$user_guid; + $user = get_entity($user_guid); + if (!$user) $user = get_loggedin_user(); + + if ($entity = get_entity($entity_guid)) { + + $return = false; + + // Test user if possible - should default to false unless a plugin hook says otherwise + if (!is_null($user)) + { + if ($entity->getOwner() == $user->getGUID()) $return = true; + if ($entity->container_guid == $user->getGUID()) $return = true; + if ($entity->type == "user" && $entity->getGUID() == $user->getGUID()) $return = true; + if ($container_entity = get_entity($entity->container_guid)) { + if ($container_entity->canEdit()) $return = true; + } + } + + return trigger_plugin_hook('permissions_check',$entity->type,array('entity' => $entity, 'user' => $user), $return); + + } else { + return false; + + } + + } + + /** + * Determines whether or not the specified user can edit metadata on the specified entity. + * + * This is extendible by registering a plugin hook taking in the parameters 'entity' and 'user', + * which are the entity and user entities respectively + * + * @see register_plugin_hook + * + * @param int $entity_guid The GUID of the entity + * @param int $user_guid The GUID of the user + * @param ElggMetadata $metadata The metadata to specifically check (if any; default null) + * @return true|false Whether the specified user can edit the specified entity. + */ + function can_edit_entity_metadata($entity_guid, $user_guid = 0, $metadata = null) { + + if ($entity = get_entity($entity_guid)) { + + $return = null; + + if ($metadata->owner_guid == 0) $return = true; + if (is_null($return)) + $return = can_edit_entity($entity_guid, $user_guid); + + $user = get_entity($user_guid); + $return = trigger_plugin_hook('permissions_check:metadata',$entity->type,array('entity' => $entity, 'user' => $user, 'metadata' => $metadata),$return); + return $return; + + } else { + return false; + } + + } + + + /** + * Get the icon for an entity + * + * @param ElggEntity $entity The entity (passed an entity rather than a guid to handle non-created entities) + * @param string $size + */ + function get_entity_icon_url(ElggEntity $entity, $size = 'medium') + { + global $CONFIG; + + $size = sanitise_string($size); + switch (strtolower($size)) + { case 'master': $size = 'master'; break; - - case 'large' : $size = 'large'; break; - - case 'topbar' : $size = 'topbar'; break; - - case 'tiny' : $size = 'tiny'; break; - - case 'small' : $size = 'small'; break; - - case 'medium' : - default: $size = 'medium'; - } - - $url = false; - - $viewtype = elgg_get_viewtype(); - - // Step one, see if anyone knows how to render this in the current view - $url = trigger_plugin_hook('entity:icon:url', $entity->getType(), array('entity' => $entity, 'viewtype' => $viewtype, 'size' => $size), $url); - - // Fail, so use default - if (!$url) { - - $type = $entity->getType(); - $subtype = $entity->getSubtype(); - - if (!empty($subtype)) { - $overrideurl = elgg_view("icon/{$type}/{$subtype}/{$size}",array('entity' => $entity)); - if (!empty($overrideurl)) return $overrideurl; - } - - $overrideurl = elgg_view("icon/{$type}/default/{$size}",array('entity' => $entity)); - if (!empty($overrideurl)) return $overrideurl; - - $url = $CONFIG->url . "_graphics/icons/default/$size.png"; - } - - return $url; - } - - /** - * Gets the URL for an entity, given a particular GUID - * - * @param int $entity_guid The GUID of the entity - * @return string The URL of the entity - */ - function get_entity_url($entity_guid) { - - global $CONFIG; - if ($entity = get_entity($entity_guid)) { - - $url = ""; - - if (isset($CONFIG->entity_url_handler[$entity->getType()][$entity->getSubType()])) { - $function = $CONFIG->entity_url_handler[$entity->getType()][$entity->getSubType()]; - if (is_callable($function)) { - $url = $function($entity); - } - } elseif (isset($CONFIG->entity_url_handler[$entity->getType()]['all'])) { - $function = $CONFIG->entity_url_handler[$entity->getType()]['all']; - if (is_callable($function)) { - $url = $function($entity); - } - } elseif (isset($CONFIG->entity_url_handler['all']['all'])) { - $function = $CONFIG->entity_url_handler['all']['all']; - if (is_callable($function)) { - $url = $function($entity); - } - } - - if ($url == "") { - $url = $CONFIG->url . "pg/view/" . $entity_guid; - } - return $url; - - } - return false; - - } - - /** - * Sets the URL handler for a particular entity type and subtype - * - * @param string $function_name The function to register - * @param string $entity_type The entity type - * @param string $entity_subtype The entity subtype - * @return true|false Depending on success - */ - function register_entity_url_handler($function_name, $entity_type = "all", $entity_subtype = "all") { - global $CONFIG; - - if (!is_callable($function_name)) return false; - - if (!isset($CONFIG->entity_url_handler)) { - $CONFIG->entity_url_handler = array(); - } - if (!isset($CONFIG->entity_url_handler[$entity_type])) { - $CONFIG->entity_url_handler[$entity_type] = array(); - } - $CONFIG->entity_url_handler[$entity_type][$entity_subtype] = $function_name; - - return true; - - } - - /** - * Default Icon URL handler for entities. - * This will attempt to find a default entity for the current view and return a url. This is registered at - * a low priority so that other handlers will pick it up first. - * - * @param unknown_type $hook - * @param unknown_type $entity_type - * @param unknown_type $returnvalue - * @param unknown_type $params - */ - function default_entity_icon_hook($hook, $entity_type, $returnvalue, $params) - { - global $CONFIG; - - if ((!$returnvalue) && ($hook == 'entity:icon:url')) - { - $entity = $params['entity']; - $type = $entity->type; - $subtype = get_subtype_from_id($entity->subtype); - $viewtype = $params['viewtype']; - $size = $params['size']; - - $url = "views/$viewtype/graphics/icons/$type/$subtype/$size.png"; - - if (!@file_exists($CONFIG->path . $url)) - $url = "views/$viewtype/graphics/icons/$type/default/$size.png"; - - if(!@file_exists($CONFIG->path . $url)) - $url = "views/$viewtype/graphics/icons/default/$size.png"; - - if (@file_exists($CONFIG->path . $url)) - return $CONFIG->url . $url; - } - } - - /** - * Registers and entity type and subtype to return in search and other places. - * A description in the elgg_echo languages file of the form item:type:subtype - * is also expected. - * - * @param string $type The type of entity (object, site, user, group) - * @param string $subtype The subtype to register (may be blank) - * @return true|false Depending on success - */ - function register_entity_type($type, $subtype) { - - global $CONFIG; - - $type = strtolower($type); - if (!in_array($type,array('object','site','group','user'))) return false; - - if (!isset($CONFIG->registered_entities)) $CONFIG->registered_entities = array(); - $CONFIG->registered_entities[$type][] = $subtype; - - return true; - - } - - /** - * Returns registered entity types and subtypes - * - * @see register_entity_type - * - * @param string $type The type of entity (object, site, user, group) or blank for all - * @return array|false Depending on whether entities have been registered - */ - function get_registered_entity_types($type = '') { - - global $CONFIG; - - if (!isset($CONFIG->registered_entities)) return false; - if (!empty($type)) $type = strtolower($type); - if (!empty($type) && empty($CONFIG->registered_entities[$type])) return false; - - if (empty($type)) - return $CONFIG->registered_entities; - - return $CONFIG->registered_entities[$type]; - - } - - /** - * Determines whether or not the specified entity type and subtype have been registered in the system - * - * @param string $type The type of entity (object, site, user, group) - * @param string $subtype The subtype (may be blank) - * @return true|false Depending on whether or not the type has been registered - */ - function is_registered_entity_type($type, $subtype) { - - global $CONFIG; - - if (!isset($CONFIG->registered_entities)) return false; - $type = strtolower($type); - if (empty($CONFIG->registered_entities[$type])) return false; - if (in_array($subtype, $CONFIG->registered_entities[$type])) return true; - - } - - /** - * Page handler for generic entities view system - * - * @param array $page Page elements from pain page handler - */ - function entities_page_handler($page) { - if (isset($page[0])) { - global $CONFIG; - set_input('guid',$page[0]); - @include($CONFIG->path . "entities/index.php"); - } - } - - /** - * Returns a viewable list of entities based on the registered types - * - * @see elgg_view_entity_list - * - * @param string $type The type of entity (eg "user", "object" etc) - * @param string $subtype The arbitrary subtype of the entity - * @param int $owner_guid The GUID of the owning user - * @param int $limit The number of entities to display per page (default: 10) - * @param true|false $fullview Whether or not to display the full view (default: true) - * @param true|false $viewtypetoggle Whether or not to allow gallery view - * @return string A viewable list of entities - */ - function list_registered_entities($owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = false, $allowedtypes = true) { - - $typearray = array(); - - if ($object_types = get_registered_entity_types()) { - foreach($object_types as $object_type => $subtype_array) { - if (is_array($subtype_array) && sizeof($subtype_array) && (in_array($object_type,$allowedtypes) || $allowedtypes === true)) - foreach($subtype_array as $object_subtype) { - $typearray[$object_type][] = $object_subtype; - } - } - } - - $offset = (int) get_input('offset'); - $count = get_entities('', $typearray, $owner_guid, "", $limit, $offset, true); - $entities = get_entities('', $typearray,$owner_guid, "", $limit, $offset); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle); - - } - - /** - * Get entities based on their private data, in a similar way to metadata. - * - * @param string $name The name of the setting - * @param string $value The value of the setting - * @param string $type The type of entity (eg "user", "object" etc) - * @param string $subtype The arbitrary subtype of the entity - * @param int $owner_guid The GUID of the owning user - * @param string $order_by The field to order by; by default, time_created desc - * @param int $limit The number of entities to return; 10 by default - * @param int $offset The indexing offset, 0 by default - * @param boolean $count Set to true to get a count rather than the entities themselves (limits and offsets don't apply in this context). Defaults to false. - * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. - * @param int|array $container_guid The container or containers to get entities from (default: all containers). - * @return array A list of entities. - */ - function get_entities_from_private_setting($name = "", $value = "", $type = "", $subtype = "", $owner_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false, $site_guid = 0, $container_guid = null) - { - global $CONFIG; - - if ($subtype === false || $subtype === null || $subtype === 0) - return false; - - $name = sanitise_string($name); - $value = sanitise_string($value); - - if ($order_by == "") $order_by = "e.time_created desc"; - $order_by = sanitise_string($order_by); - $limit = (int)$limit; - $offset = (int)$offset; - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - $where = array(); - - if (is_array($type)) { - $tempwhere = ""; - if (sizeof($type)) - foreach($type as $typekey => $subtypearray) { - foreach($subtypearray as $subtypeval) { - $typekey = sanitise_string($typekey); - if (!empty($subtypeval)) { - if (!$subtypeval = (int) get_subtype_id($typekey, $subtypeval)) { - return false; - } - } else { - $subtypeval = 0; - } - if (!empty($tempwhere)) $tempwhere .= " or "; - $tempwhere .= "(e.type = '{$typekey}' and e.subtype = {$subtypeval})"; - } - } - if (!empty($tempwhere)) $where[] = "({$tempwhere})"; - - } else { - - $type = sanitise_string($type); - if ($subtype AND !$subtype = get_subtype_id($type, $subtype)) { - return false; - } - - if ($type != "") - $where[] = "e.type='$type'"; - if ($subtype!=="") - $where[] = "e.subtype=$subtype"; - - } - - if ($owner_guid != "") { - if (!is_array($owner_guid)) { - $owner_array = array($owner_guid); - $owner_guid = (int) $owner_guid; - // $where[] = "owner_guid = '$owner_guid'"; - } else if (sizeof($owner_guid) > 0) { - $owner_array = array_map('sanitise_int', $owner_guid); - // Cast every element to the owner_guid array to int - // $owner_guid = array_map("sanitise_int", $owner_guid); - // $owner_guid = implode(",",$owner_guid); - // $where[] = "owner_guid in ({$owner_guid})"; - } - if (is_null($container_guid)) { - $container_guid = $owner_array; - } - } - if ($site_guid > 0) - $where[] = "e.site_guid = {$site_guid}"; - - if (!is_null($container_guid)) { - if (is_array($container_guid)) { - foreach($container_guid as $key => $val) $container_guid[$key] = (int) $val; - $where[] = "e.container_guid in (" . implode(",",$container_guid) . ")"; - } else { - $container_guid = (int) $container_guid; - $where[] = "e.container_guid = {$container_guid}"; - } - } - - if ($name!="") - $where[] = "s.name = '$name'"; - if ($value!="") - $where[] = "s.value='$value'"; - - if (!$count) { - $query = "SELECT distinct e.* from {$CONFIG->dbprefix}entities e JOIN {$CONFIG->dbprefix}private_settings s ON e.guid=s.entity_guid where "; - } else { - $query = "SELECT count(distinct e.guid) as total from {$CONFIG->dbprefix}entities e JOIN {$CONFIG->dbprefix}private_settings s ON e.guid=s.entity_guid where "; - } - foreach ($where as $w) - $query .= " $w and "; - $query .= get_access_sql_suffix('e'); // Add access controls - if (!$count) { - $query .= " order by $order_by"; - if ($limit) $query .= " limit $offset, $limit"; // Add order and limit - - $dt = get_data($query, "entity_row_to_elggstar"); - return $dt; - } else { - $total = get_data_row($query); - return $total->total; - } - } - - /** - * Get entities based on their private data by multiple keys, in a similar way to metadata. - * - * @param string $name The name of the setting - * @param string $value The value of the setting - * @param string|array $type The type of entity (eg "user", "object" etc) or array(type1 => array('subtype1', ...'subtypeN'), ...) - * @param string $subtype The arbitrary subtype of the entity - * @param int $owner_guid The GUID of the owning user - * @param string $order_by The field to order by; by default, time_created desc - * @param int $limit The number of entities to return; 10 by default - * @param int $offset The indexing offset, 0 by default - * @param boolean $count Set to true to get a count rather than the entities themselves (limits and offsets don't apply in this context). Defaults to false. - * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. - * @param int|array $container_guid The container or containers to get entities from (default: all containers). - * @return array A list of entities. - */ - function get_entities_from_private_setting_multi(array $name, $type = "", $subtype = "", $owner_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false, $site_guid = 0, $container_guid = null) - { - global $CONFIG; - - if ($subtype === false || $subtype === null || $subtype === 0) - return false; - - if ($order_by == "") $order_by = "e.time_created desc"; - $order_by = sanitise_string($order_by); - $limit = (int)$limit; - $offset = (int)$offset; - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - $where = array(); - - if (is_array($type)) { - $tempwhere = ""; - if (sizeof($type)) - foreach($type as $typekey => $subtypearray) { - foreach($subtypearray as $subtypeval) { - $typekey = sanitise_string($typekey); - if (!empty($subtypeval)) { - if (!$subtypeval = (int) get_subtype_id($typekey, $subtypeval)) { - return false; - } - } else { - $subtypeval = 0; - } - if (!empty($tempwhere)) $tempwhere .= " or "; - $tempwhere .= "(e.type = '{$typekey}' and e.subtype = {$subtypeval})"; - } - } - if (!empty($tempwhere)) $where[] = "({$tempwhere})"; - - } else { - $type = sanitise_string($type); - if ($subtype AND !$subtype = get_subtype_id($type, $subtype)) - return false; - - if ($type != "") - $where[] = "e.type='$type'"; - if ($subtype!=="") - $where[] = "e.subtype=$subtype"; - - } - - if ($owner_guid != "") { - if (!is_array($owner_guid)) { - $owner_array = array($owner_guid); - $owner_guid = (int) $owner_guid; - // $where[] = "owner_guid = '$owner_guid'"; - } else if (sizeof($owner_guid) > 0) { - $owner_array = array_map('sanitise_int', $owner_guid); - // Cast every element to the owner_guid array to int - // $owner_guid = array_map("sanitise_int", $owner_guid); - // $owner_guid = implode(",",$owner_guid); - // $where[] = "owner_guid in ({$owner_guid})"; - } - if (is_null($container_guid)) { - $container_guid = $owner_array; - } - } - if ($site_guid > 0) - $where[] = "e.site_guid = {$site_guid}"; - - if (!is_null($container_guid)) { - if (is_array($container_guid)) { - foreach($container_guid as $key => $val) $container_guid[$key] = (int) $val; - $where[] = "e.container_guid in (" . implode(",",$container_guid) . ")"; - } else { - $container_guid = (int) $container_guid; - $where[] = "e.container_guid = {$container_guid}"; - } - } - - if ($name) - { - $s_join = ""; - $i = 1; - foreach ($name as $k => $n) - { - $k = sanitise_string($k); - $s_join .= " JOIN {$CONFIG->dbprefix}private_settings s$i ON e.guid=s$i.entity_guid"; - $where[] = "s$i.name = '$k'"; - $where[] = "s$i.value = '$n'"; - $i++; - } - } - - if (!$count) { - $query = "SELECT distinct e.* from {$CONFIG->dbprefix}entities e $s_join where "; - } else { - $query = "SELECT count(distinct e.guid) as total from {$CONFIG->dbprefix}entities e $s_join where "; - } - foreach ($where as $w) - $query .= " $w and "; - $query .= get_access_sql_suffix('e'); // Add access controls - if (!$count) { - $query .= " order by $order_by"; - if ($limit) $query .= " limit $offset, $limit"; // Add order and limit - - $dt = get_data($query, "entity_row_to_elggstar"); - return $dt; - } else { - $total = get_data_row($query); - return $total->total; - } - } - - /** - * Gets a private setting for an entity. - * - * @param int $entity_guid The entity GUID - * @param string $name The name of the setting - * @return mixed The setting value, or false on failure - */ - function get_private_setting($entity_guid, $name) { - - global $CONFIG; - $entity_guid = (int) $entity_guid; - $name = sanitise_string($name); - - if ($setting = get_data_row("SELECT value from {$CONFIG->dbprefix}private_settings where name = '{$name}' and entity_guid = {$entity_guid}")) { - return $setting->value; - } - return false; - - } - - /** - * Return an array of all private settings for a given - * - * @param int $entity_guid The entity GUID - */ - function get_all_private_settings($entity_guid) { - global $CONFIG; - - $entity_guid = (int) $entity_guid; - - $result = get_data("SELECT * from {$CONFIG->dbprefix}private_settings where entity_guid = {$entity_guid}"); - if ($result) - { - $return = array(); - foreach ($result as $r) - $return[$r->name] = $r->value; - - return $return; - } - - return false; - } - - /** - * Sets a private setting for an entity. - * - * @param int $entity_guid The entity GUID - * @param string $name The name of the setting - * @param string $value The value of the setting - * @return mixed The setting ID, or false on failure - */ - function set_private_setting($entity_guid, $name, $value) { - - global $CONFIG; - $entity_guid = (int) $entity_guid; - $name = sanitise_string($name); - $value = sanitise_string($value); - - $result = insert_data("INSERT into {$CONFIG->dbprefix}private_settings (entity_guid, name, value) VALUES ($entity_guid, '{$name}', '{$value}') ON DUPLICATE KEY UPDATE value='$value'"); - if ($result === 0) return true; - return $result; - - } - - /** - * Deletes a private setting for an entity. - * - * @param int $entity_guid The Entity GUID - * @param string $name The name of the setting - * @return true|false depending on success - * - */ - function remove_private_setting($entity_guid, $name) { - - global $CONFIG; - $entity_guid = (int) $entity_guid; - $name = sanitise_string($name); - return delete_data("DELETE from {$CONFIG->dbprefix}private_settings where name = '{$name}' and entity_guid = {$entity_guid}"); - - } - - /** - * Deletes all private settings for an entity. - * - * @param int $entity_guid The Entity GUID - * @return true|false depending on success - * - */ - function remove_all_private_settings($entity_guid) { - - global $CONFIG; - $entity_guid = (int) $entity_guid; - return delete_data("DELETE from {$CONFIG->dbprefix}private_settings where entity_guid = {$entity_guid}"); - } - - function recursive_delete_permissions_check($hook, $entity_type, $returnvalue, $params) - { - static $__RECURSIVE_DELETE_TOKEN; - - $entity = $params['entity']; - - if ((isloggedin()) && ($__RECURSIVE_DELETE_TOKEN) && (strcmp($__RECURSIVE_DELETE_TOKEN, md5(get_loggedin_userid())))) - return true; - + + case 'large' : $size = 'large'; break; + + case 'topbar' : $size = 'topbar'; break; + + case 'tiny' : $size = 'tiny'; break; + + case 'small' : $size = 'small'; break; + + case 'medium' : + default: $size = 'medium'; + } + + $url = false; + + $viewtype = elgg_get_viewtype(); + + // Step one, see if anyone knows how to render this in the current view + $url = trigger_plugin_hook('entity:icon:url', $entity->getType(), array('entity' => $entity, 'viewtype' => $viewtype, 'size' => $size), $url); + + // Fail, so use default + if (!$url) { + + $type = $entity->getType(); + $subtype = $entity->getSubtype(); + + if (!empty($subtype)) { + $overrideurl = elgg_view("icon/{$type}/{$subtype}/{$size}",array('entity' => $entity)); + if (!empty($overrideurl)) return $overrideurl; + } + + $overrideurl = elgg_view("icon/{$type}/default/{$size}",array('entity' => $entity)); + if (!empty($overrideurl)) return $overrideurl; + + $url = $CONFIG->url . "_graphics/icons/default/$size.png"; + } + + return $url; + } + + /** + * Gets the URL for an entity, given a particular GUID + * + * @param int $entity_guid The GUID of the entity + * @return string The URL of the entity + */ + function get_entity_url($entity_guid) { + + global $CONFIG; + if ($entity = get_entity($entity_guid)) { + + $url = ""; + + if (isset($CONFIG->entity_url_handler[$entity->getType()][$entity->getSubType()])) { + $function = $CONFIG->entity_url_handler[$entity->getType()][$entity->getSubType()]; + if (is_callable($function)) { + $url = $function($entity); + } + } elseif (isset($CONFIG->entity_url_handler[$entity->getType()]['all'])) { + $function = $CONFIG->entity_url_handler[$entity->getType()]['all']; + if (is_callable($function)) { + $url = $function($entity); + } + } elseif (isset($CONFIG->entity_url_handler['all']['all'])) { + $function = $CONFIG->entity_url_handler['all']['all']; + if (is_callable($function)) { + $url = $function($entity); + } + } + + if ($url == "") { + $url = $CONFIG->url . "pg/view/" . $entity_guid; + } + return $url; + + } + return false; + + } + + /** + * Sets the URL handler for a particular entity type and subtype + * + * @param string $function_name The function to register + * @param string $entity_type The entity type + * @param string $entity_subtype The entity subtype + * @return true|false Depending on success + */ + function register_entity_url_handler($function_name, $entity_type = "all", $entity_subtype = "all") { + global $CONFIG; + + if (!is_callable($function_name)) return false; + + if (!isset($CONFIG->entity_url_handler)) { + $CONFIG->entity_url_handler = array(); + } + if (!isset($CONFIG->entity_url_handler[$entity_type])) { + $CONFIG->entity_url_handler[$entity_type] = array(); + } + $CONFIG->entity_url_handler[$entity_type][$entity_subtype] = $function_name; + + return true; + + } + + /** + * Default Icon URL handler for entities. + * This will attempt to find a default entity for the current view and return a url. This is registered at + * a low priority so that other handlers will pick it up first. + * + * @param unknown_type $hook + * @param unknown_type $entity_type + * @param unknown_type $returnvalue + * @param unknown_type $params + */ + function default_entity_icon_hook($hook, $entity_type, $returnvalue, $params) + { + global $CONFIG; + + if ((!$returnvalue) && ($hook == 'entity:icon:url')) + { + $entity = $params['entity']; + $type = $entity->type; + $subtype = get_subtype_from_id($entity->subtype); + $viewtype = $params['viewtype']; + $size = $params['size']; + + $url = "views/$viewtype/graphics/icons/$type/$subtype/$size.png"; + + if (!@file_exists($CONFIG->path . $url)) + $url = "views/$viewtype/graphics/icons/$type/default/$size.png"; + + if(!@file_exists($CONFIG->path . $url)) + $url = "views/$viewtype/graphics/icons/default/$size.png"; + + if (@file_exists($CONFIG->path . $url)) + return $CONFIG->url . $url; + } + } + + /** + * Registers and entity type and subtype to return in search and other places. + * A description in the elgg_echo languages file of the form item:type:subtype + * is also expected. + * + * @param string $type The type of entity (object, site, user, group) + * @param string $subtype The subtype to register (may be blank) + * @return true|false Depending on success + */ + function register_entity_type($type, $subtype) { + + global $CONFIG; + + $type = strtolower($type); + if (!in_array($type,array('object','site','group','user'))) return false; + + if (!isset($CONFIG->registered_entities)) $CONFIG->registered_entities = array(); + $CONFIG->registered_entities[$type][] = $subtype; + + return true; + + } + + /** + * Returns registered entity types and subtypes + * + * @see register_entity_type + * + * @param string $type The type of entity (object, site, user, group) or blank for all + * @return array|false Depending on whether entities have been registered + */ + function get_registered_entity_types($type = '') { + + global $CONFIG; + + if (!isset($CONFIG->registered_entities)) return false; + if (!empty($type)) $type = strtolower($type); + if (!empty($type) && empty($CONFIG->registered_entities[$type])) return false; + + if (empty($type)) + return $CONFIG->registered_entities; + + return $CONFIG->registered_entities[$type]; + + } + + /** + * Determines whether or not the specified entity type and subtype have been registered in the system + * + * @param string $type The type of entity (object, site, user, group) + * @param string $subtype The subtype (may be blank) + * @return true|false Depending on whether or not the type has been registered + */ + function is_registered_entity_type($type, $subtype) { + + global $CONFIG; + + if (!isset($CONFIG->registered_entities)) return false; + $type = strtolower($type); + if (empty($CONFIG->registered_entities[$type])) return false; + if (in_array($subtype, $CONFIG->registered_entities[$type])) return true; + + } + + /** + * Page handler for generic entities view system + * + * @param array $page Page elements from pain page handler + */ + function entities_page_handler($page) { + if (isset($page[0])) { + global $CONFIG; + set_input('guid',$page[0]); + @include($CONFIG->path . "entities/index.php"); + } + } + + /** + * Returns a viewable list of entities based on the registered types + * + * @see elgg_view_entity_list + * + * @param string $type The type of entity (eg "user", "object" etc) + * @param string $subtype The arbitrary subtype of the entity + * @param int $owner_guid The GUID of the owning user + * @param int $limit The number of entities to display per page (default: 10) + * @param true|false $fullview Whether or not to display the full view (default: true) + * @param true|false $viewtypetoggle Whether or not to allow gallery view + * @return string A viewable list of entities + */ + function list_registered_entities($owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = false, $allowedtypes = true) { + + $typearray = array(); + + if ($object_types = get_registered_entity_types()) { + foreach($object_types as $object_type => $subtype_array) { + if (is_array($subtype_array) && sizeof($subtype_array) && (in_array($object_type,$allowedtypes) || $allowedtypes === true)) + foreach($subtype_array as $object_subtype) { + $typearray[$object_type][] = $object_subtype; + } + } + } + + $offset = (int) get_input('offset'); + $count = get_entities('', $typearray, $owner_guid, "", $limit, $offset, true); + $entities = get_entities('', $typearray,$owner_guid, "", $limit, $offset); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle); + + } + + /** + * Get entities based on their private data, in a similar way to metadata. + * + * @param string $name The name of the setting + * @param string $value The value of the setting + * @param string $type The type of entity (eg "user", "object" etc) + * @param string $subtype The arbitrary subtype of the entity + * @param int $owner_guid The GUID of the owning user + * @param string $order_by The field to order by; by default, time_created desc + * @param int $limit The number of entities to return; 10 by default + * @param int $offset The indexing offset, 0 by default + * @param boolean $count Set to true to get a count rather than the entities themselves (limits and offsets don't apply in this context). Defaults to false. + * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. + * @param int|array $container_guid The container or containers to get entities from (default: all containers). + * @return array A list of entities. + */ + function get_entities_from_private_setting($name = "", $value = "", $type = "", $subtype = "", $owner_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false, $site_guid = 0, $container_guid = null) + { + global $CONFIG; + + if ($subtype === false || $subtype === null || $subtype === 0) + return false; + + $name = sanitise_string($name); + $value = sanitise_string($value); + + if ($order_by == "") $order_by = "e.time_created desc"; + $order_by = sanitise_string($order_by); + $limit = (int)$limit; + $offset = (int)$offset; + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + $where = array(); + + if (is_array($type)) { + $tempwhere = ""; + if (sizeof($type)) + foreach($type as $typekey => $subtypearray) { + foreach($subtypearray as $subtypeval) { + $typekey = sanitise_string($typekey); + if (!empty($subtypeval)) { + if (!$subtypeval = (int) get_subtype_id($typekey, $subtypeval)) { + return false; + } + } else { + $subtypeval = 0; + } + if (!empty($tempwhere)) $tempwhere .= " or "; + $tempwhere .= "(e.type = '{$typekey}' and e.subtype = {$subtypeval})"; + } + } + if (!empty($tempwhere)) $where[] = "({$tempwhere})"; + + } else { + + $type = sanitise_string($type); + if ($subtype AND !$subtype = get_subtype_id($type, $subtype)) { + return false; + } + + if ($type != "") + $where[] = "e.type='$type'"; + if ($subtype!=="") + $where[] = "e.subtype=$subtype"; + + } + + if ($owner_guid != "") { + if (!is_array($owner_guid)) { + $owner_array = array($owner_guid); + $owner_guid = (int) $owner_guid; + // $where[] = "owner_guid = '$owner_guid'"; + } else if (sizeof($owner_guid) > 0) { + $owner_array = array_map('sanitise_int', $owner_guid); + // Cast every element to the owner_guid array to int + // $owner_guid = array_map("sanitise_int", $owner_guid); + // $owner_guid = implode(",",$owner_guid); + // $where[] = "owner_guid in ({$owner_guid})"; + } + if (is_null($container_guid)) { + $container_guid = $owner_array; + } + } + if ($site_guid > 0) + $where[] = "e.site_guid = {$site_guid}"; + + if (!is_null($container_guid)) { + if (is_array($container_guid)) { + foreach($container_guid as $key => $val) $container_guid[$key] = (int) $val; + $where[] = "e.container_guid in (" . implode(",",$container_guid) . ")"; + } else { + $container_guid = (int) $container_guid; + $where[] = "e.container_guid = {$container_guid}"; + } + } + + if ($name!="") + $where[] = "s.name = '$name'"; + if ($value!="") + $where[] = "s.value='$value'"; + + if (!$count) { + $query = "SELECT distinct e.* from {$CONFIG->dbprefix}entities e JOIN {$CONFIG->dbprefix}private_settings s ON e.guid=s.entity_guid where "; + } else { + $query = "SELECT count(distinct e.guid) as total from {$CONFIG->dbprefix}entities e JOIN {$CONFIG->dbprefix}private_settings s ON e.guid=s.entity_guid where "; + } + foreach ($where as $w) + $query .= " $w and "; + $query .= get_access_sql_suffix('e'); // Add access controls + if (!$count) { + $query .= " order by $order_by"; + if ($limit) $query .= " limit $offset, $limit"; // Add order and limit + + $dt = get_data($query, "entity_row_to_elggstar"); + return $dt; + } else { + $total = get_data_row($query); + return $total->total; + } + } + + /** + * Get entities based on their private data by multiple keys, in a similar way to metadata. + * + * @param string $name The name of the setting + * @param string $value The value of the setting + * @param string|array $type The type of entity (eg "user", "object" etc) or array(type1 => array('subtype1', ...'subtypeN'), ...) + * @param string $subtype The arbitrary subtype of the entity + * @param int $owner_guid The GUID of the owning user + * @param string $order_by The field to order by; by default, time_created desc + * @param int $limit The number of entities to return; 10 by default + * @param int $offset The indexing offset, 0 by default + * @param boolean $count Set to true to get a count rather than the entities themselves (limits and offsets don't apply in this context). Defaults to false. + * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. + * @param int|array $container_guid The container or containers to get entities from (default: all containers). + * @return array A list of entities. + */ + function get_entities_from_private_setting_multi(array $name, $type = "", $subtype = "", $owner_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false, $site_guid = 0, $container_guid = null) + { + global $CONFIG; + + if ($subtype === false || $subtype === null || $subtype === 0) + return false; + + if ($order_by == "") $order_by = "e.time_created desc"; + $order_by = sanitise_string($order_by); + $limit = (int)$limit; + $offset = (int)$offset; + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + $where = array(); + + if (is_array($type)) { + $tempwhere = ""; + if (sizeof($type)) + foreach($type as $typekey => $subtypearray) { + foreach($subtypearray as $subtypeval) { + $typekey = sanitise_string($typekey); + if (!empty($subtypeval)) { + if (!$subtypeval = (int) get_subtype_id($typekey, $subtypeval)) { + return false; + } + } else { + $subtypeval = 0; + } + if (!empty($tempwhere)) $tempwhere .= " or "; + $tempwhere .= "(e.type = '{$typekey}' and e.subtype = {$subtypeval})"; + } + } + if (!empty($tempwhere)) $where[] = "({$tempwhere})"; + + } else { + $type = sanitise_string($type); + if ($subtype AND !$subtype = get_subtype_id($type, $subtype)) + return false; + + if ($type != "") + $where[] = "e.type='$type'"; + if ($subtype!=="") + $where[] = "e.subtype=$subtype"; + + } + + if ($owner_guid != "") { + if (!is_array($owner_guid)) { + $owner_array = array($owner_guid); + $owner_guid = (int) $owner_guid; + // $where[] = "owner_guid = '$owner_guid'"; + } else if (sizeof($owner_guid) > 0) { + $owner_array = array_map('sanitise_int', $owner_guid); + // Cast every element to the owner_guid array to int + // $owner_guid = array_map("sanitise_int", $owner_guid); + // $owner_guid = implode(",",$owner_guid); + // $where[] = "owner_guid in ({$owner_guid})"; + } + if (is_null($container_guid)) { + $container_guid = $owner_array; + } + } + if ($site_guid > 0) + $where[] = "e.site_guid = {$site_guid}"; + + if (!is_null($container_guid)) { + if (is_array($container_guid)) { + foreach($container_guid as $key => $val) $container_guid[$key] = (int) $val; + $where[] = "e.container_guid in (" . implode(",",$container_guid) . ")"; + } else { + $container_guid = (int) $container_guid; + $where[] = "e.container_guid = {$container_guid}"; + } + } + + if ($name) + { + $s_join = ""; + $i = 1; + foreach ($name as $k => $n) + { + $k = sanitise_string($k); + $s_join .= " JOIN {$CONFIG->dbprefix}private_settings s$i ON e.guid=s$i.entity_guid"; + $where[] = "s$i.name = '$k'"; + $where[] = "s$i.value = '$n'"; + $i++; + } + } + + if (!$count) { + $query = "SELECT distinct e.* from {$CONFIG->dbprefix}entities e $s_join where "; + } else { + $query = "SELECT count(distinct e.guid) as total from {$CONFIG->dbprefix}entities e $s_join where "; + } + foreach ($where as $w) + $query .= " $w and "; + $query .= get_access_sql_suffix('e'); // Add access controls + if (!$count) { + $query .= " order by $order_by"; + if ($limit) $query .= " limit $offset, $limit"; // Add order and limit + + $dt = get_data($query, "entity_row_to_elggstar"); + return $dt; + } else { + $total = get_data_row($query); + return $total->total; + } + } + + /** + * Gets a private setting for an entity. + * + * @param int $entity_guid The entity GUID + * @param string $name The name of the setting + * @return mixed The setting value, or false on failure + */ + function get_private_setting($entity_guid, $name) { + + global $CONFIG; + $entity_guid = (int) $entity_guid; + $name = sanitise_string($name); + + if ($setting = get_data_row("SELECT value from {$CONFIG->dbprefix}private_settings where name = '{$name}' and entity_guid = {$entity_guid}")) { + return $setting->value; + } + return false; + + } + + /** + * Return an array of all private settings for a given + * + * @param int $entity_guid The entity GUID + */ + function get_all_private_settings($entity_guid) { + global $CONFIG; + + $entity_guid = (int) $entity_guid; + + $result = get_data("SELECT * from {$CONFIG->dbprefix}private_settings where entity_guid = {$entity_guid}"); + if ($result) + { + $return = array(); + foreach ($result as $r) + $return[$r->name] = $r->value; + + return $return; + } + + return false; + } + + /** + * Sets a private setting for an entity. + * + * @param int $entity_guid The entity GUID + * @param string $name The name of the setting + * @param string $value The value of the setting + * @return mixed The setting ID, or false on failure + */ + function set_private_setting($entity_guid, $name, $value) { + + global $CONFIG; + $entity_guid = (int) $entity_guid; + $name = sanitise_string($name); + $value = sanitise_string($value); + + $result = insert_data("INSERT into {$CONFIG->dbprefix}private_settings (entity_guid, name, value) VALUES ($entity_guid, '{$name}', '{$value}') ON DUPLICATE KEY UPDATE value='$value'"); + if ($result === 0) return true; + return $result; + + } + + /** + * Deletes a private setting for an entity. + * + * @param int $entity_guid The Entity GUID + * @param string $name The name of the setting + * @return true|false depending on success + * + */ + function remove_private_setting($entity_guid, $name) { + + global $CONFIG; + $entity_guid = (int) $entity_guid; + $name = sanitise_string($name); + return delete_data("DELETE from {$CONFIG->dbprefix}private_settings where name = '{$name}' and entity_guid = {$entity_guid}"); + + } + + /** + * Deletes all private settings for an entity. + * + * @param int $entity_guid The Entity GUID + * @return true|false depending on success + * + */ + function remove_all_private_settings($entity_guid) { + + global $CONFIG; + $entity_guid = (int) $entity_guid; + return delete_data("DELETE from {$CONFIG->dbprefix}private_settings where entity_guid = {$entity_guid}"); + } + + function recursive_delete_permissions_check($hook, $entity_type, $returnvalue, $params) + { + static $__RECURSIVE_DELETE_TOKEN; + + $entity = $params['entity']; + + if ((isloggedin()) && ($__RECURSIVE_DELETE_TOKEN) && (strcmp($__RECURSIVE_DELETE_TOKEN, md5(get_loggedin_userid())))) + return true; + } /** @@ -2763,37 +2763,37 @@ foreach ($tables as $table) { delete_data("DELETE from {$CONFIG->dbprefix}{$table} where guid NOT IN (SELECT guid from {$CONFIG->dbprefix}entities)"); } - } - - /** - * Entities init function; establishes the page handler - * - */ + } + + /** + * Entities init function; establishes the page handler + * + */ function entities_init() - { - register_page_handler('view','entities_page_handler'); - - // Allow a permission override for recursive entity deletion - // TODO: Can this be done better? + { + register_page_handler('view','entities_page_handler'); + + // Allow a permission override for recursive entity deletion + // TODO: Can this be done better? register_plugin_hook('permissions_check','all','recursive_delete_permissions_check'); register_plugin_hook('permissions_check:metadata','all','recursive_delete_permissions_check'); - register_plugin_hook('gc','system','entities_gc'); - } - - /** Register the import hook */ - register_plugin_hook("import", "all", "import_entity_plugin_hook", 0); - - /** Register the hook, ensuring entities are serialised first */ - register_plugin_hook("export", "all", "export_entity_plugin_hook", 0); - - /** Hook to get certain named bits of volatile data about an entity */ - register_plugin_hook('volatile', 'metadata', 'volatile_data_export_plugin_hook'); - - /** Hook for rendering a default icon for entities */ - register_plugin_hook('entity:icon:url', 'all', 'default_entity_icon_hook', 1000); - - /** Register init system event **/ - register_elgg_event_handler('init','system','entities_init'); - -?> + register_plugin_hook('gc','system','entities_gc'); + } + + /** Register the import hook */ + register_plugin_hook("import", "all", "import_entity_plugin_hook", 0); + + /** Register the hook, ensuring entities are serialised first */ + register_plugin_hook("export", "all", "export_entity_plugin_hook", 0); + + /** Hook to get certain named bits of volatile data about an entity */ + register_plugin_hook('volatile', 'metadata', 'volatile_data_export_plugin_hook'); + + /** Hook for rendering a default icon for entities */ + register_plugin_hook('entity:icon:url', 'all', 'default_entity_icon_hook', 1000); + + /** Register init system event **/ + register_elgg_event_handler('init','system','entities_init'); + +?> diff --git a/engine/lib/extender.php b/engine/lib/extender.php index a298671f3..f3f3753bc 100644 --- a/engine/lib/extender.php +++ b/engine/lib/extender.php @@ -66,7 +66,7 @@ */ protected function set($name, $value, $value_type = "") { - $this->attributes[$name] = $value; + $this->attributes[$name] = $value; if ($name == 'value') $this->attributes['value_type'] = detect_extender_valuetype($value, $value_type); @@ -82,15 +82,15 @@ { return get_user($this->owner_guid); } - - /** - * Returns the entity this is attached to - * - * @return ElggEntity The enttiy - */ - public function getEntity() { - return get_entity($this->entity_guid); - } + + /** + * Returns the entity this is attached to + * + * @return ElggEntity The enttiy + */ + public function getEntity() { + return get_entity($this->entity_guid); + } /** * Save this data to the appropriate database table. @@ -101,15 +101,15 @@ * Delete this data. */ abstract public function delete(); - - /** - * Determines whether or not the specified user can edit this - * - * @param int $user_guid The GUID of the user (defaults to currently logged in user) - * @return true|false - */ - public function canEdit($user_guid = 0) { - return can_edit_extender($this->id,$this->type,$user_guid); + + /** + * Determines whether or not the specified user can edit this + * + * @param int $user_guid The GUID of the user (defaults to currently logged in user) + * @return true|false + */ + public function canEdit($user_guid = 0) { + return can_edit_extender($this->id,$this->type,$user_guid); } /** @@ -333,40 +333,40 @@ return true; } } - - /** - * Determines whether or not the specified user can edit the specified piece of extender - * - * @param int $extender_id The ID of the piece of extender - * @param string $type 'metadata' or 'annotation' - * @param int $user_guid The GUID of the user - * @return true|false - */ + + /** + * Determines whether or not the specified user can edit the specified piece of extender + * + * @param int $extender_id The ID of the piece of extender + * @param string $type 'metadata' or 'annotation' + * @param int $user_guid The GUID of the user + * @return true|false + */ function can_edit_extender($extender_id, $type, $user_guid = 0) { - - if (!isloggedin()) - return false; + + if (!isloggedin()) + return false; $user_guid = (int)$user_guid; $user = get_entity($user_guid); - if (!$user) $user = get_loggedin_user(); - - $functionname = "get_{$type}"; - if (is_callable($functionname)) { - $extender = $functionname($extender_id); - } else return false; - - if (!is_a($extender,"ElggExtender")) return false; - - // If the owner is the specified user, great! They can edit. - if ($extender->getOwner() == $user->getGUID()) return true; - - // If the user can edit the entity this is attached to, great! They can edit. - if (can_edit_entity($extender->entity_guid,$user->getGUID())) return true; - - // Trigger plugin hooks - return trigger_plugin_hook('permissions_check',$type,array('entity' => $entity, 'user' => $user),false); - + if (!$user) $user = get_loggedin_user(); + + $functionname = "get_{$type}"; + if (is_callable($functionname)) { + $extender = $functionname($extender_id); + } else return false; + + if (!is_a($extender,"ElggExtender")) return false; + + // If the owner is the specified user, great! They can edit. + if ($extender->getOwner() == $user->getGUID()) return true; + + // If the user can edit the entity this is attached to, great! They can edit. + if (can_edit_entity($extender->entity_guid,$user->getGUID())) return true; + + // Trigger plugin hooks + return trigger_plugin_hook('permissions_check',$type,array('entity' => $entity, 'user' => $user),false); + } /** @@ -432,7 +432,7 @@ $url = $CONFIG->wwwroot . "export/$view/$guid/$type/$nameid/"; } return $url; - } + } /** Register the hook */ register_plugin_hook("import", "all", "import_extender_plugin_hook", 2); diff --git a/engine/lib/input.php b/engine/lib/input.php index 338df2a08..71abbb330 100644 --- a/engine/lib/input.php +++ b/engine/lib/input.php @@ -1,66 +1,66 @@ - - * @author Curverider Ltd + * @link http://elgg.org/ + */ - * @link http://elgg.org/ - */ - - /** - * Get some input from variables passed on the GET or POST line. - * - * @param $variable string The variable we want to return. + /** + * Get some input from variables passed on the GET or POST line. + * + * @param $variable string The variable we want to return. * @param $default mixed A default value for the variable if it is not found. - * @param $filter_result If true then the result is filtered for bad tags. - */ - function get_input($variable, $default = "", $filter_result = true) - { - - global $CONFIG; - - if (isset($CONFIG->input[$variable])) { + * @param $filter_result If true then the result is filtered for bad tags. + */ + function get_input($variable, $default = "", $filter_result = true) + { + + global $CONFIG; + + if (isset($CONFIG->input[$variable])) { $var = $CONFIG->input[$variable]; if ($filter_result) $var = filter_tags($var); return $var; - } - + } + if (isset($_REQUEST[$variable])) { - + if (is_array($_REQUEST[$variable])) { $var = $_REQUEST[$variable]; } else { - $var = trim($_REQUEST[$variable]); - } + $var = trim($_REQUEST[$variable]); + } if ($filter_result) - $var = filter_tags($var); - - return $var; - - } - - return $default; - - } - - /** - * Sets an input value that may later be retrieved by get_input - * - * @param string $variable The name of the variable - * @param string $value The value of the variable - */ - function set_input($variable, $value) { - - global $CONFIG; - if (!isset($CONFIG->input)) + $var = filter_tags($var); + + return $var; + + } + + return $default; + + } + + /** + * Sets an input value that may later be retrieved by get_input + * + * @param string $variable The name of the variable + * @param string $value The value of the variable + */ + function set_input($variable, $value) { + + global $CONFIG; + if (!isset($CONFIG->input)) $CONFIG->input = array(); if (is_array($value)) @@ -70,19 +70,19 @@ $CONFIG->input[trim($variable)] = $value; } - else - $CONFIG->input[trim($variable)] = trim($value); - - } - - /** - * Filter tags from a given string based on registered hooks. - * @param $var - * @return mixed The filtered result - */ - function filter_tags($var) - { - return trigger_plugin_hook('validate', 'input', null, $var); + else + $CONFIG->input[trim($variable)] = trim($value); + + } + + /** + * Filter tags from a given string based on registered hooks. + * @param $var + * @return mixed The filtered result + */ + function filter_tags($var) + { + return trigger_plugin_hook('validate', 'input', null, $var); } /** @@ -102,15 +102,15 @@ $path = $path . "/"; return $path; - } + } + - - /** - * Takes a string and turns any URLs into formatted links - * - * @param string $text The input string - * @return string The output stirng with formatted links - **/ + /** + * Takes a string and turns any URLs into formatted links + * + * @param string $text The input string + * @return string The output stirng with formatted links + **/ function parse_urls($text) { return preg_replace_callback('/(?"\'\!\(\)]+)/i', @@ -121,110 +121,110 @@ $urltext = str_replace("/", "/", $url); return "$urltext"; ' - ), $text); - } - - function autop($pee, $br = 1) { - $pee = $pee . "\n"; // just to make things a little easier, pad the end - $pee = preg_replace('|
\s*
|', "\n\n", $pee); - // Space things out a little - $allblocks = '(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr)'; - $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee); - $pee = preg_replace('!()!', "$1\n\n", $pee); - $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines - if ( strpos($pee, ']*)>\s*|', "", $pee); // no pee inside object/embed - $pee = preg_replace('|\s*\s*|', '', $pee); - } - $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates - $pee = preg_replace('/\n?(.+?)(?:\n\s*\n|\z)/s', "

$1

\n", $pee); // make paragraphs, including one at the end - $pee = preg_replace('|

\s*?

|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace - $pee = preg_replace('!

([^<]+)\s*?(]*>)!', "

$1

$2", $pee); - $pee = preg_replace( '|

|', "$1

", $pee ); - $pee = preg_replace('!

\s*(]*>)\s*

!', "$1", $pee); // don't pee all over a tag - $pee = preg_replace("|

(|", "$1", $pee); // problem with nested lists - $pee = preg_replace('|

]*)>|i', "

", $pee); - $pee = str_replace('

', '

', $pee); - $pee = preg_replace('!

\s*(]*>)!', "$1", $pee); - $pee = preg_replace('!(]*>)\s*

!', "$1", $pee); - if ($br) { - $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', create_function('$matches', 'return str_replace("\n", "", $matches[0]);'), $pee); - $pee = preg_replace('|(?)\s*\n|', "
\n", $pee); // optionally make line breaks - $pee = str_replace('', "\n", $pee); - } - $pee = preg_replace('!(]*>)\s*
!', "$1", $pee); - $pee = preg_replace('!
(\s*]*>)!', '$1', $pee); - if (strpos($pee, ')(.*?)!is', 'clean_pre', $pee ); - $pee = preg_replace( "|\n

$|", '

', $pee ); - - return $pee; - } - - function input_init() { - - if (ini_get_bool('magic_quotes_gpc') ) { - - //do keys as well, cos array_map ignores them - function stripslashes_arraykeys($array) { - if (is_array($array)) { - $array2 = array(); - foreach ($array as $key => $data) { - if ($key != stripslashes($key)) { - $array2[stripslashes($key)] = $data; - } else { - $array2[$key] = $data; - } - } - return $array2; - } else { - return $array; - } - } - - function stripslashes_deep($value) { - if (is_array($value)) { - $value = stripslashes_arraykeys($value); - $value = array_map('stripslashes_deep', $value); - } else { - $value = stripslashes($value); - } - return $value; - } - - $_POST = stripslashes_arraykeys($_POST); - $_GET = stripslashes_arraykeys($_GET); - $_COOKIE = stripslashes_arraykeys($_COOKIE); - $_REQUEST = stripslashes_arraykeys($_REQUEST); - - $_POST = array_map('stripslashes_deep', $_POST); - $_GET = array_map('stripslashes_deep', $_GET); - $_COOKIE = array_map('stripslashes_deep', $_COOKIE); - $_REQUEST = array_map('stripslashes_deep', $_REQUEST); - if (!empty($_SERVER['REQUEST_URI'])) { - $_SERVER['REQUEST_URI'] = stripslashes($_SERVER['REQUEST_URI']); - } - if (!empty($_SERVER['QUERY_STRING'])) { - $_SERVER['QUERY_STRING'] = stripslashes($_SERVER['QUERY_STRING']); - } - if (!empty($_SERVER['HTTP_REFERER'])) { - $_SERVER['HTTP_REFERER'] = stripslashes($_SERVER['HTTP_REFERER']); - } - if (!empty($_SERVER['PATH_INFO'])) { - $_SERVER['PATH_INFO'] = stripslashes($_SERVER['PATH_INFO']); - } - if (!empty($_SERVER['PHP_SELF'])) { - $_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']); - } - if (!empty($_SERVER['PATH_TRANSLATED'])) { - $_SERVER['PATH_TRANSLATED'] = stripslashes($_SERVER['PATH_TRANSLATED']); - } - + ), $text); + } + + function autop($pee, $br = 1) { + $pee = $pee . "\n"; // just to make things a little easier, pad the end + $pee = preg_replace('|
\s*
|', "\n\n", $pee); + // Space things out a little + $allblocks = '(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr)'; + $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee); + $pee = preg_replace('!()!', "$1\n\n", $pee); + $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines + if ( strpos($pee, ']*)>\s*|', "", $pee); // no pee inside object/embed + $pee = preg_replace('|\s*\s*|', '', $pee); + } + $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates + $pee = preg_replace('/\n?(.+?)(?:\n\s*\n|\z)/s', "

$1

\n", $pee); // make paragraphs, including one at the end + $pee = preg_replace('|

\s*?

|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace + $pee = preg_replace('!

([^<]+)\s*?(]*>)!', "

$1

$2", $pee); + $pee = preg_replace( '|

|', "$1

", $pee ); + $pee = preg_replace('!

\s*(]*>)\s*

!', "$1", $pee); // don't pee all over a tag + $pee = preg_replace("|

(|", "$1", $pee); // problem with nested lists + $pee = preg_replace('|

]*)>|i', "

", $pee); + $pee = str_replace('

', '

', $pee); + $pee = preg_replace('!

\s*(]*>)!', "$1", $pee); + $pee = preg_replace('!(]*>)\s*

!', "$1", $pee); + if ($br) { + $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', create_function('$matches', 'return str_replace("\n", "", $matches[0]);'), $pee); + $pee = preg_replace('|(?)\s*\n|', "
\n", $pee); // optionally make line breaks + $pee = str_replace('', "\n", $pee); + } + $pee = preg_replace('!(]*>)\s*
!', "$1", $pee); + $pee = preg_replace('!
(\s*]*>)!', '$1', $pee); + if (strpos($pee, ')(.*?)!is', 'clean_pre', $pee ); + $pee = preg_replace( "|\n

$|", '

', $pee ); + + return $pee; + } + + function input_init() { + + if (ini_get_bool('magic_quotes_gpc') ) { + + //do keys as well, cos array_map ignores them + function stripslashes_arraykeys($array) { + if (is_array($array)) { + $array2 = array(); + foreach ($array as $key => $data) { + if ($key != stripslashes($key)) { + $array2[stripslashes($key)] = $data; + } else { + $array2[$key] = $data; + } + } + return $array2; + } else { + return $array; + } + } + + function stripslashes_deep($value) { + if (is_array($value)) { + $value = stripslashes_arraykeys($value); + $value = array_map('stripslashes_deep', $value); + } else { + $value = stripslashes($value); + } + return $value; + } + + $_POST = stripslashes_arraykeys($_POST); + $_GET = stripslashes_arraykeys($_GET); + $_COOKIE = stripslashes_arraykeys($_COOKIE); + $_REQUEST = stripslashes_arraykeys($_REQUEST); + + $_POST = array_map('stripslashes_deep', $_POST); + $_GET = array_map('stripslashes_deep', $_GET); + $_COOKIE = array_map('stripslashes_deep', $_COOKIE); + $_REQUEST = array_map('stripslashes_deep', $_REQUEST); + if (!empty($_SERVER['REQUEST_URI'])) { + $_SERVER['REQUEST_URI'] = stripslashes($_SERVER['REQUEST_URI']); + } + if (!empty($_SERVER['QUERY_STRING'])) { + $_SERVER['QUERY_STRING'] = stripslashes($_SERVER['QUERY_STRING']); + } + if (!empty($_SERVER['HTTP_REFERER'])) { + $_SERVER['HTTP_REFERER'] = stripslashes($_SERVER['HTTP_REFERER']); + } + if (!empty($_SERVER['PATH_INFO'])) { + $_SERVER['PATH_INFO'] = stripslashes($_SERVER['PATH_INFO']); + } + if (!empty($_SERVER['PHP_SELF'])) { + $_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']); + } + if (!empty($_SERVER['PATH_TRANSLATED'])) { + $_SERVER['PATH_TRANSLATED'] = stripslashes($_SERVER['PATH_TRANSLATED']); + } + } - - } - - register_elgg_event_handler('init','system','input_init'); - - + + } + + register_elgg_event_handler('init','system','input_init'); + + ?> \ No newline at end of file diff --git a/engine/lib/install.php b/engine/lib/install.php index 6faa70ef5..03abede14 100644 --- a/engine/lib/install.php +++ b/engine/lib/install.php @@ -1,16 +1,16 @@ -=')) && (version_compare(phpversion(), '5.2.0', '<')) ) - register_error(elgg_echo('configurationwarning:phpversion')); + register_error(elgg_echo('configurationwarning:phpversion')); */ if (version_compare(phpversion(), '5.1.2', '>=')) @@ -53,12 +53,12 @@ return true; } - - /** - * Returns whether or not the database has been installed - * - * @return true|false Whether the database has been installed - */ + + /** + * Returns whether or not the database has been installed + * + * @return true|false Whether the database has been installed + */ function is_db_installed() { global $CONFIG; @@ -66,29 +66,29 @@ if (isset($CONFIG->db_installed)) { return $CONFIG->db_installed; } - - if ($dblink = get_db_link('read')) { - mysql_query("select name from {$CONFIG->dbprefix}datalists limit 1",$dblink); - if (mysql_errno($dblink) > 0) return false; + + if ($dblink = get_db_link('read')) { + mysql_query("select name from {$CONFIG->dbprefix}datalists limit 1",$dblink); + if (mysql_errno($dblink) > 0) return false; } else return false; $CONFIG->db_installed = true; // Set flag if db is installed (if false then we want to check every time) - - return true; - - } - - /** - * Returns whether or not other settings have been set - * - * @return true|false Whether or not the rest of the installation has been followed through with - */ - function is_installed() { - - global $CONFIG; - return datalist_get('installed'); - - } + + return true; + + } + + /** + * Returns whether or not other settings have been set + * + * @return true|false Whether or not the rest of the installation has been followed through with + */ + function is_installed() { + + global $CONFIG; + return datalist_get('installed'); + + } /** * Copy and create a new settings.php from settings.example.php, substituting the variables in @@ -112,15 +112,15 @@ return $file; } - - /** - * Initialisation for installation functions - * - */ - function install_init() { - register_action("systemsettings/install",true); - } - - register_elgg_event_handler("boot","system","install_init"); - + + /** + * Initialisation for installation functions + * + */ + function install_init() { + register_action("systemsettings/install",true); + } + + register_elgg_event_handler("boot","system","install_init"); + ?> \ No newline at end of file diff --git a/engine/lib/languages.php b/engine/lib/languages.php index bca0466ea..dd97d0927 100644 --- a/engine/lib/languages.php +++ b/engine/lib/languages.php @@ -1,51 +1,51 @@ - 'message1', 'message2' => 'message2'); + * $german = array('message1' => 'Nachricht1','message2' => 'Nachricht2'); + * + * @param string $country_code Standard country code (eg 'en', 'nl', 'es') + * @param array $language_array Formatted array of strings + * @return true|false Depending on success + */ - * @link http://elgg.org/ - */ - - /** - * Add a translation. - * - * Translations are arrays in the Zend Translation array format, eg: - * - * $english = array('message1' => 'message1', 'message2' => 'message2'); - * $german = array('message1' => 'Nachricht1','message2' => 'Nachricht2'); - * - * @param string $country_code Standard country code (eg 'en', 'nl', 'es') - * @param array $language_array Formatted array of strings - * @return true|false Depending on success - */ - - function add_translation($country_code, $language_array) { - - global $CONFIG; - if (!isset($CONFIG->translations)) - $CONFIG->translations = array(); - - $country_code = strtolower($country_code); - $country_code = trim($country_code); - if (is_array($language_array) && sizeof($language_array) > 0 && $country_code != "") { - - if (!isset($CONFIG->translations[$country_code])) { - $CONFIG->translations[$country_code] = $language_array; - } else { - $CONFIG->translations[$country_code] = $language_array + $CONFIG->translations[$country_code]; - } - - return true; - - } - return false; - + function add_translation($country_code, $language_array) { + + global $CONFIG; + if (!isset($CONFIG->translations)) + $CONFIG->translations = array(); + + $country_code = strtolower($country_code); + $country_code = trim($country_code); + if (is_array($language_array) && sizeof($language_array) > 0 && $country_code != "") { + + if (!isset($CONFIG->translations[$country_code])) { + $CONFIG->translations[$country_code] = $language_array; + } else { + $CONFIG->translations[$country_code] = $language_array + $CONFIG->translations[$country_code]; + } + + return true; + + } + return false; + } /** @@ -62,130 +62,130 @@ $language = 'en'; return $language; - } - - /** - * Gets the current language in use by the system or user. - * - * [Marcus Povey 20090216: Not sure why this func is necessary.] - * - * @return string The language code (eg "en") - */ - function get_language() { - - global $CONFIG; - + } + + /** + * Gets the current language in use by the system or user. + * + * [Marcus Povey 20090216: Not sure why this func is necessary.] + * + * @return string The language code (eg "en") + */ + function get_language() { + + global $CONFIG; + $user = get_loggedin_user(); - $language = false; - - if (($user) && ($user->language)) - $language = $user->language; - - if ((!$language) && (isset($CONFIG->language)) && ($CONFIG->language)) + $language = false; + + if (($user) && ($user->language)) + $language = $user->language; + + if ((!$language) && (isset($CONFIG->language)) && ($CONFIG->language)) $language = $CONFIG->language; - if ($language) { - return $language; - } - return false; - - } - - /** - * Given a message shortcode, returns an appropriately translated full-text string - * - * @param string $message_key The short message code - * @param string $language Optionally, the standard language code (defaults to the site default, then English) - * @return string Either the translated string, or the original English string, or an empty string - */ - function elgg_echo($message_key, $language = "") { - + if ($language) { + return $language; + } + return false; + + } + + /** + * Given a message shortcode, returns an appropriately translated full-text string + * + * @param string $message_key The short message code + * @param string $language Optionally, the standard language code (defaults to the site default, then English) + * @return string Either the translated string, or the original English string, or an empty string + */ + function elgg_echo($message_key, $language = "") { + global $CONFIG; static $CURRENT_LANGUAGE; - if ((!$CURRENT_LANGUAGE) && (!$language)) + if ((!$CURRENT_LANGUAGE) && (!$language)) $CURRENT_LANGUAGE = $language = get_language(); else - $language = $CURRENT_LANGUAGE; - - if (isset($CONFIG->translations[$language][$message_key])) { - return $CONFIG->translations[$language][$message_key]; - } else if (isset($CONFIG->translations["en"][$message_key])) { - return $CONFIG->translations["en"][$message_key]; - } - - return $message_key; - - } - - /** - * When given a full path, finds translation files and loads them - * - * @param string $path Full path - * @param bool $load_all If true all languages are loaded, if false only the current language + en are loaded - */ + $language = $CURRENT_LANGUAGE; + + if (isset($CONFIG->translations[$language][$message_key])) { + return $CONFIG->translations[$language][$message_key]; + } else if (isset($CONFIG->translations["en"][$message_key])) { + return $CONFIG->translations["en"][$message_key]; + } + + return $message_key; + + } + + /** + * When given a full path, finds translation files and loads them + * + * @param string $path Full path + * @param bool $load_all If true all languages are loaded, if false only the current language + en are loaded + */ function register_translations($path, $load_all = false) { global $CONFIG; - - // Make a note of this path just incase we need to register this language later - if(!isset($CONFIG->language_paths)) $CONFIG->language_paths = array(); - $CONFIG->language_paths[$path] = true; - - // Get the current language based on site defaults and user preference - $current_language = get_current_language(); - - if (isset($CONFIG->debug) && $CONFIG->debug == true) error_log("Translations loaded from : $path"); + + // Make a note of this path just incase we need to register this language later + if(!isset($CONFIG->language_paths)) $CONFIG->language_paths = array(); + $CONFIG->language_paths[$path] = true; + + // Get the current language based on site defaults and user preference + $current_language = get_current_language(); + + if (isset($CONFIG->debug) && $CONFIG->debug == true) error_log("Translations loaded from : $path"); - if ($handle = opendir($path)) { - while ($language = readdir($handle)) { - - if ( - ((in_array($language, array('en.php', $current_language . '.php'))) /*&& (!is_dir($path . $language))*/) || - (($load_all) && (strpos($language, '.php')!==false)/* && (!is_dir($path . $language))*/) - ) - include_once($path . $language); - - } + if ($handle = opendir($path)) { + while ($language = readdir($handle)) { + + if ( + ((in_array($language, array('en.php', $current_language . '.php'))) /*&& (!is_dir($path . $language))*/) || + (($load_all) && (strpos($language, '.php')!==false)/* && (!is_dir($path . $language))*/) + ) + include_once($path . $language); + + } } else - error_log("Missing translation path $path"); - - } - - /** - * Reload all translations from all registered paths. - * - * This is only called by functions which need to know all possible translations, namely the - * statistic gathering ones. - * - * TODO: Better on demand loading based on language_paths array - * - * @return bool - */ - function reload_all_translations() - { - global $CONFIG; - - static $LANG_RELOAD_ALL_RUN; - if ($LANG_RELOAD_ALL_RUN) return null; - - foreach ($CONFIG->language_paths as $path => $dummy) - register_translations($path, true); - - $LANG_RELOAD_ALL_RUN = true; - } + error_log("Missing translation path $path"); + + } + + /** + * Reload all translations from all registered paths. + * + * This is only called by functions which need to know all possible translations, namely the + * statistic gathering ones. + * + * TODO: Better on demand loading based on language_paths array + * + * @return bool + */ + function reload_all_translations() + { + global $CONFIG; + + static $LANG_RELOAD_ALL_RUN; + if ($LANG_RELOAD_ALL_RUN) return null; + + foreach ($CONFIG->language_paths as $path => $dummy) + register_translations($path, true); + + $LANG_RELOAD_ALL_RUN = true; + } /** * Return an array of installed translations as an associative array "two letter code" => "native language name". */ function get_installed_translations() { - global $CONFIG; - - // Ensure that all possible translations are loaded + global $CONFIG; + + // Ensure that all possible translations are loaded reload_all_translations(); - $installed = array(); + $installed = array(); foreach ($CONFIG->translations as $k => $v) { @@ -204,9 +204,9 @@ */ function get_language_completeness($language) { - global $CONFIG; - - // Ensure that all possible translations are loaded + global $CONFIG; + + // Ensure that all possible translations are loaded reload_all_translations(); $language = sanitise_string($language); @@ -227,9 +227,9 @@ */ function get_missing_language_keys($language) { - global $CONFIG; - - // Ensure that all possible translations are loaded + global $CONFIG; + + // Ensure that all possible translations are loaded reload_all_translations(); $missing = array(); @@ -248,5 +248,5 @@ } register_translations(dirname(dirname(dirname(__FILE__))) . "/languages/"); - + ?> \ No newline at end of file diff --git a/engine/lib/metadata.php b/engine/lib/metadata.php index 9aa033061..c6e5db4cd 100644 --- a/engine/lib/metadata.php +++ b/engine/lib/metadata.php @@ -1,912 +1,912 @@ - + * @author Curverider Ltd - * @link http://elgg.org/ - */ - - /** - * ElggMetadata - * This class describes metadata that can be attached to ElggEntities. - * - * @author Curverider Ltd - * @package Elgg - * @subpackage Core - */ - class ElggMetadata extends ElggExtender - { - - /** - * Construct a new site object, optionally from a given id value or row. - * - * @param mixed $id - */ - function __construct($id = null) - { - $this->attributes = array(); - - if (!empty($id)) { - - if ($id instanceof stdClass) - $metadata = $id; // Create from db row - else - $metadata = get_metadata($id); - - if ($metadata) { - $objarray = (array) $metadata; - foreach($objarray as $key => $value) { - $this->attributes[$key] = $value; - } - $this->attributes['type'] = "metadata"; - } - } - } - - /** - * Class member get overloading - * - * @param string $name - * @return mixed - */ - function __get($name) { - return $this->get($name); - } - - /** - * Class member set overloading - * - * @param string $name - * @param mixed $value - * @return mixed - */ - function __set($name, $value) { - return $this->set($name, $value); - } - - /** - * Determines whether or not the user can edit this piece of metadata - * - * @return true|false Depending on permissions - */ - function canEdit() { - - if ($entity = get_entity($this->get('entity_guid'))) { - return $entity->canEditMetadata($this); - } - return false; - - } - - /** - * Save matadata object - * - * @return int the metadata object id - */ - function save() - { - if ($this->id > 0) - return update_metadata($this->id, $this->name, $this->value, $this->value_type, $this->owner_guid, $this->access_id); - else - { - $this->id = create_metadata($this->entity_guid, $this->name, $this->value, $this->value_type, $this->owner_guid, $this->access_id); - if (!$this->id) throw new IOException(sprintf(elgg_new('IOException:UnableToSaveNew'), get_class())); - return $this->id; - } - - } - - /** - * Delete a given metadata. - */ - function delete() - { - return delete_metadata($this->id); - } - - /** - * Get a url for this item of metadata. - * - * @return string - */ - public function getURL() { return get_metadata_url($this->id); } - - // SYSTEM LOG INTERFACE //////////////////////////////////////////////////////////// - - /** - * For a given ID, return the object associated with it. - * This is used by the river functionality primarily. - * This is useful for checking access permissions etc on objects. - */ - public function getObjectFromID($id) { return get_metadata($id); } - } - - /** - * Convert a database row to a new ElggMetadata - * - * @param stdClass $row - * @return stdClass or ElggMetadata - */ - function row_to_elggmetadata($row) - { - if (!($row instanceof stdClass)) - return $row; - - return new ElggMetadata($row); - } - - - /** - * Get a specific item of metadata. - * - * @param $id int The item of metadata being retrieved. - */ - function get_metadata($id) - { - global $CONFIG; - - $id = (int)$id; - $access = get_access_sql_suffix("e"); - $md_access = get_access_sql_suffix("m"); - - return row_to_elggmetadata(get_data_row("SELECT m.*, n.string as name, v.string as value from {$CONFIG->dbprefix}metadata m JOIN {$CONFIG->dbprefix}entities e on e.guid = m.entity_guid JOIN {$CONFIG->dbprefix}metastrings v on m.value_id = v.id JOIN {$CONFIG->dbprefix}metastrings n on m.name_id = n.id where m.id=$id and $access and $md_access")); - } - - /** - * Removes metadata on an entity with a particular name, optionally with a given value. - * - * @param int $entity_guid The entity GUID - * @param string $name The name of the metadata - * @param string $value The optional value of the item (useful for removing a single item in a multiple set) - * @return true|false Depending on success - */ - function remove_metadata($entity_guid, $name, $value = "") { - - global $CONFIG; - $entity_guid = (int) $entity_guid; - $name = sanitise_string($name); - $value = sanitise_string($value); - - $query = "SELECT * from {$CONFIG->dbprefix}metadata WHERE entity_guid = $entity_guid and name_id=" . add_metastring($name); - if ($value!="") - $query .= " and value_id=" . add_metastring($value); - - if ($existing = get_data($query)) { - foreach($existing as $ex) - delete_metadata($ex->id); - return true; - } - return false; - - } - - /** - * Create a new metadata object, or update an existing one. - * - * @param int $entity_guid - * @param string $name - * @param string $value - * @param string $value_type - * @param int $owner_guid - * @param int $access_id - * @param bool $allow_multiple - */ - function create_metadata($entity_guid, $name, $value, $value_type, $owner_guid, $access_id = ACCESS_PRIVATE, $allow_multiple = false) - { - global $CONFIG; - - $entity_guid = (int)$entity_guid; - //$name = sanitise_string(trim($name)); - //$value = sanitise_string(trim($value)); - $value_type = detect_extender_valuetype($value, sanitise_string(trim($value_type))); - $time = time(); - $owner_guid = (int)$owner_guid; - $allow_multiple = (boolean)$allow_multiple; - - if ($owner_guid==0) $owner_guid = get_loggedin_userid(); - - $access_id = (int)$access_id; - - $id = false; - - $existing = get_data_row("SELECT * from {$CONFIG->dbprefix}metadata WHERE entity_guid = $entity_guid and name_id=" . add_metastring($name) . " limit 1"); - if (($existing) && (!$allow_multiple) && (isset($value))) - { - $id = $existing->id; - $result = update_metadata($id, $name, $value, $value_type, $owner_guid, $access_id); - - if (!$result) return false; - } - else if (isset($value)) - { - // Support boolean types - if (is_bool($value)) { - if ($value) - $value = 1; - else - $value = 0; - } - - // Add the metastrings - $value = add_metastring($value); - if (!$value) return false; - - $name = add_metastring($name); - if (!$name) return false; - - // If ok then add it - $id = insert_data("INSERT into {$CONFIG->dbprefix}metadata (entity_guid, name_id, value_id, value_type, owner_guid, time_created, access_id) VALUES ($entity_guid, '$name','$value','$value_type', $owner_guid, $time, $access_id)"); - - if ($id!==false) { - $obj = get_metadata($id); - if (trigger_elgg_event('create', 'metadata', $obj)) { - return true; - } else { - delete_metadata($id); - } - } - - } else if ($existing) { -// TODO: Check... are you sure you meant to do this Ben? :) - $id = $existing->id; - delete_metadata($id); - - } - - return $id; - } - - /** - * Update an item of metadata. - * - * @param int $id - * @param string $name - * @param string $value - * @param string $value_type - * @param int $owner_guid - * @param int $access_id - */ - function update_metadata($id, $name, $value, $value_type, $owner_guid, $access_id) - { - global $CONFIG; - - $id = (int)$id; - - if (!$md = get_metadata($id)) return false; - if (!$md->canEdit()) return false; - - // If memcached then we invalidate the cache for this entry - static $metabyname_memcache; - if ((!$metabyname_memcache) && (is_memcache_available())) - $metabyname_memcache = new ElggMemcache('metabyname_memcache'); - if ($metabyname_memcache) $metabyname_memcache->delete("{$md->entity_guid}:{$md->name_id}"); - - //$name = sanitise_string(trim($name)); - //$value = sanitise_string(trim($value)); - $value_type = detect_extender_valuetype($value, sanitise_string(trim($value_type))); - - $owner_guid = (int)$owner_guid; - if ($owner_guid==0) $owner_guid = get_loggedin_userid(); - - $access_id = (int)$access_id; - - $access = get_access_sql_suffix(); - - // Support boolean types (as integers) - if (is_bool($value)) { - if ($value) - $value = 1; - else - $value = 0; - } - - // Add the metastring - $value = add_metastring($value); - if (!$value) return false; - - $name = add_metastring($name); - if (!$name) return false; - - // If ok then add it - $result = update_data("UPDATE {$CONFIG->dbprefix}metadata set value_id='$value', value_type='$value_type', access_id=$access_id, owner_guid=$owner_guid where id=$id and name_id='$name'"); - if ($result!==false) { - $obj = get_metadata($id); - if (trigger_elgg_event('update', 'metadata', $obj)) { - return true; - } else { - delete_metadata($id); - } - } - - return $result; - } - - /** - * This function creates metadata from an associative array of "key => value" pairs. - * - * @param int $entity_guid - * @param string $name_and_values - * @param string $value_type - * @param int $owner_guid - * @param int $access_id - * @param bool $allow_multiple - */ - function create_metadata_from_array($entity_guid, array $name_and_values, $value_type, $owner_guid, $access_id = ACCESS_PRIVATE, $allow_multiple = false) - { - foreach ($name_and_values as $k => $v) - if (!create_metadata($entity_guid, $k, $v, $value_type, $owner_guid, $access_id, $allow_multiple)) return false; - - return true; - } - - /** - * Delete an item of metadata, where the current user has access. - * - * @param $id int The item of metadata to delete. - */ - function delete_metadata($id) - { - global $CONFIG; - - $id = (int)$id; - $metadata = get_metadata($id); - - if ($metadata) { - // Tidy up if memcache is enabled. - static $metabyname_memcache; - if ((!$metabyname_memcache) && (is_memcache_available())) - $metabyname_memcache = new ElggMemcache('metabyname_memcache'); - if ($metabyname_memcache) $metabyname_memcache->delete("{$metadata->entity_guid}:{$metadata->name_id}"); - - if (($metadata->canEdit()) && (trigger_elgg_event('delete', 'metadata', $metadata))) - return delete_data("DELETE from {$CONFIG->dbprefix}metadata where id=$id"); - } - - return false; - } - - /** - * Return the metadata values that match your query. - * - * @param string $meta_name - * @return mixed either a value, an array of ElggMetadata or false. - */ - function get_metadata_byname($entity_guid, $meta_name) - { - global $CONFIG; - - $meta_name = get_metastring_id($meta_name); - - if (empty($meta_name)) return false; - - $entity_guid = (int)$entity_guid; - $access = get_access_sql_suffix("e"); - $md_access = get_access_sql_suffix("m"); - - // If memcache is available then cache this (cache only by name for now since this is the most common query) - $meta = null; - static $metabyname_memcache; - if ((!$metabyname_memcache) && (is_memcache_available())) - $metabyname_memcache = new ElggMemcache('metabyname_memcache'); - if ($metabyname_memcache) $meta = $metabyname_memcache->load("{$entity_guid}:{$meta_name}"); - if ($meta) return $meta; - - $result = get_data("SELECT m.*, n.string as name, v.string as value from {$CONFIG->dbprefix}metadata m JOIN {$CONFIG->dbprefix}entities e ON e.guid = m.entity_guid JOIN {$CONFIG->dbprefix}metastrings v on m.value_id = v.id JOIN {$CONFIG->dbprefix}metastrings n on m.name_id = n.id where m.entity_guid=$entity_guid and m.name_id='$meta_name' and $access and $md_access", "row_to_elggmetadata"); - if (!$result) - return false; - - // Cache if memcache available - if ($metabyname_memcache) - { - if (count($result) == 1) $r = $result[0]; else $r = $result; - $metabyname_memcache->setDefaultExpiry(3600); // This is a bit of a hack - we shorten the expiry on object metadata so that it'll be gone in an hour. This means that deletions and more importantly updates will filter through eventually. - $metabyname_memcache->save("{$entity_guid}:{$meta_name}", $r); - - } - if (count($result) == 1) - return $result[0]; - - return $result; - } - - /** - * Return all the metadata for a given GUID. - * - * @param int $entity_guid - */ - function get_metadata_for_entity($entity_guid) - { - global $CONFIG; - - $entity_guid = (int)$entity_guid; - $access = get_access_sql_suffix("e"); - $md_access = get_access_sql_suffix("m"); - - return get_data("SELECT m.*, n.string as name, v.string as value from {$CONFIG->dbprefix}metadata m JOIN {$CONFIG->dbprefix}entities e ON e.guid = m.entity_guid JOIN {$CONFIG->dbprefix}metastrings v on m.value_id = v.id JOIN {$CONFIG->dbprefix}metastrings n on m.name_id = n.id where m.entity_guid=$entity_guid and $access and $md_access", "row_to_elggmetadata"); - } - - /** - * Get the metadata where the entities they are referring to match a given criteria. - * - * @param mixed $meta_name - * @param mixed $meta_value - * @param string $entity_type The type of entity to look for, eg 'site' or 'object' - * @param string $entity_subtype The subtype of the entity. - * @param int $limit - * @param int $offset - * @param string $order_by Optional ordering. - * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. - */ - function find_metadata($meta_name = "", $meta_value = "", $entity_type = "", $entity_subtype = "", $limit = 10, $offset = 0, $order_by = "", $site_guid = 0) - { - global $CONFIG; - - $meta_n = get_metastring_id($meta_name); - $meta_v = get_metastring_id($meta_value); - - $entity_type = sanitise_string($entity_type); - $entity_subtype = get_subtype_id($entity_type, $entity_subtype); - $limit = (int)$limit; - $offset = (int)$offset; - if ($order_by == "") $order_by = "e.time_created desc"; - $order_by = sanitise_string($order_by); - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - - $where = array(); - - if ($entity_type!="") - $where[] = "e.type='$entity_type'"; - if ($entity_subtype) - $where[] = "e.subtype=$entity_subtype"; - if ($meta_name!="") { - if (!$meta_v) return false; // The value is set, but we didn't get a value... so something went wrong. - $where[] = "m.name_id='$meta_n'"; - } - if ($meta_value!="") { - if (!$meta_v) return false; // The value is set, but we didn't get a value... so something went wrong. - $where[] = "m.value_id='$meta_v'"; - } - if ($site_guid > 0) - $where[] = "e.site_guid = {$site_guid}"; - - $query = "SELECT m.*, n.string as name, v.string as value from {$CONFIG->dbprefix}entities e JOIN {$CONFIG->dbprefix}metadata m on e.guid = m.entity_guid JOIN {$CONFIG->dbprefix}metastrings v on m.value_id = v.id JOIN {$CONFIG->dbprefix}metastrings n on m.name_id = n.id where"; - foreach ($where as $w) - $query .= " $w and "; - $query .= get_access_sql_suffix("e"); // Add access controls - $query .= ' and ' . get_access_sql_suffix("m"); // Add access controls - $query .= " order by $order_by limit $offset, $limit"; // Add order and limit - - return get_data($query, "row_to_elggmetadata"); - } - - /** - * Return a list of entities based on the given search criteria. - * - * @param mixed $meta_name - * @param mixed $meta_value - * @param string $entity_type The type of entity to look for, eg 'site' or 'object' - * @param string $entity_subtype The subtype of the entity. - * @param int $limit - * @param int $offset - * @param string $order_by Optional ordering. - * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. - * @param true|false $count If set to true, returns the total number of entities rather than a list. (Default: false) - * - * @return int|array A list of entities, or a count if $count is set to true - */ - function get_entities_from_metadata($meta_name, $meta_value = "", $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $order_by = "", $site_guid = 0, $count = false) - { - global $CONFIG; - - $meta_n = get_metastring_id($meta_name); - $meta_v = get_metastring_id($meta_value); - - $entity_type = sanitise_string($entity_type); - $entity_subtype = get_subtype_id($entity_type, $entity_subtype); - $limit = (int)$limit; - $offset = (int)$offset; - if ($order_by == "") - $order_by = "e.time_created desc"; - else - $order_by = "e.time_created, {$order_by}"; - $order_by = sanitise_string($order_by); - $site_guid = (int) $site_guid; - if ((is_array($owner_guid) && (count($owner_guid)))) { - foreach($owner_guid as $key => $guid) { - $owner_guid[$key] = (int) $guid; - } - } else { - $owner_guid = (int) $owner_guid; - } - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - //$access = get_access_list(); - - $where = array(); - - if ($entity_type!=="") - $where[] = "e.type='$entity_type'"; - if ($entity_subtype) - $where[] = "e.subtype=$entity_subtype"; - if ($meta_name!=="") - $where[] = "m.name_id='$meta_n'"; - if ($meta_value!=="") - $where[] = "m.value_id='$meta_v'"; - if ($site_guid > 0) - $where[] = "e.site_guid = {$site_guid}"; - if (is_array($owner_guid)) { - $where[] = "e.container_guid in (".implode(",",$owner_guid).")"; - } else if ($owner_guid > 0) - $where[] = "e.container_guid = {$owner_guid}"; - - if (!$count) { - $query = "SELECT distinct e.* "; - } else { - $query = "SELECT count(distinct e.guid) as total "; - } - - $query .= "from {$CONFIG->dbprefix}entities e JOIN {$CONFIG->dbprefix}metadata m on e.guid = m.entity_guid where"; - foreach ($where as $w) - $query .= " $w and "; - $query .= get_access_sql_suffix("e"); // Add access controls - $query .= ' and ' . get_access_sql_suffix("m"); // Add access controls - - if (!$count) { - $query .= " order by $order_by limit $offset, $limit"; // Add order and limit - return get_data($query, "entity_row_to_elggstar"); - } else { - if ($row = get_data_row($query)) - return $row->total; - } - return false; - } - - /** - * Return a list of entities suitable for display based on the given search criteria. - * - * @see elgg_view_entity_list - * - * @param mixed $meta_name Metadata name to search on - * @param mixed $meta_value The value to match, optionally - * @param string $entity_type The type of entity to look for, eg 'site' or 'object' - * @param string $entity_subtype The subtype of the entity - * @param int $limit Number of entities to display per page - * @param true|false $fullview Whether or not to display the full view (default: true) - * @param true|false $viewtypetoggle Whether or not to allow users to toggle to the gallery view. Default: true - * @param true|false $pagination Display pagination? Default: true - * - * @return string A list of entities suitable for display - */ - function list_entities_from_metadata($meta_name, $meta_value = "", $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true) { - - $offset = (int) get_input('offset'); - $limit = (int) $limit; - $count = get_entities_from_metadata($meta_name, $meta_value, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", 0, true); - $entities = get_entities_from_metadata($meta_name, $meta_value, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", 0, false); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); - - } - - /** - * Returns a list of entities based on the given search criteria. - * - * @param array $meta_array Array of 'name' => 'value' pairs - * @param string $entity_type The type of entity to look for, eg 'site' or 'object' - * @param string $entity_subtype The subtype of the entity. - * @param int $limit - * @param int $offset - * @param string $order_by Optional ordering. - * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. - * @param true|false $count If set to true, returns the total number of entities rather than a list. (Default: false) - * @param string $meta_array_operator Operator used for joining the metadata array together - * @return int|array List of ElggEntities, or the total number if count is set to false - */ - function get_entities_from_metadata_multi($meta_array, $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $order_by = "", $site_guid = 0, $count = false, $meta_array_operator = 'and') - { - global $CONFIG; - - if (!is_array($meta_array) || sizeof($meta_array) == 0) { - return false; - } - - $where = array(); - - $mindex = 1; - $join = ""; - $metawhere = array(); - $meta_array_operator = sanitise_string($meta_array_operator); - foreach($meta_array as $meta_name => $meta_value) { - $meta_n = get_metastring_id($meta_name); - $meta_v = get_metastring_id($meta_value); - $join .= " JOIN {$CONFIG->dbprefix}metadata m{$mindex} on e.guid = m{$mindex}.entity_guid "; - /*if ($meta_name!=="") - $where[] = "m{$mindex}.name_id='$meta_n'"; - if ($meta_value!=="") - $where[] = "m{$mindex}.value_id='$meta_v'";*/ - $metawhere[] = "(m{$mindex}.name_id='$meta_n' AND m{$mindex}.value_id='$meta_v')"; - $mindex++; - } - $where[] = "(".implode($meta_array_operator, $metawhere).")"; - - $entity_type = sanitise_string($entity_type); - $entity_subtype = get_subtype_id($entity_type, $entity_subtype); - $limit = (int)$limit; - $offset = (int)$offset; - if ($order_by == "") $order_by = "e.time_created desc"; - $order_by = sanitise_string($order_by); - if ((is_array($owner_guid) && (count($owner_guid)))) { - foreach($owner_guid as $key => $guid) { - $owner_guid[$key] = (int) $guid; - } - } else { - $owner_guid = (int) $owner_guid; - } - - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - //$access = get_access_list(); - - if ($entity_type!="") - $where[] = "e.type = '{$entity_type}'"; - if ($entity_subtype) - $where[] = "e.subtype = {$entity_subtype}"; - if ($site_guid > 0) - $where[] = "e.site_guid = {$site_guid}"; - if (is_array($owner_guid)) { - $where[] = "e.container_guid in (".implode(",",$owner_guid).")"; - } else if ($owner_guid > 0) - $where[] = "e.container_guid = {$owner_guid}"; - //if ($owner_guid > 0) - // $where[] = "e.container_guid = {$owner_guid}"; - - if ($count) { - $query = "SELECT count(distinct e.guid) as total "; - } else { - $query = "SELECT distinct e.* "; - } - - $query .= " from {$CONFIG->dbprefix}entities e {$join} where"; - foreach ($where as $w) - $query .= " $w and "; - $query .= get_access_sql_suffix("e"); // Add access controls - - $mindex = 1; - foreach($meta_array as $meta_name => $meta_value) { - $query .= ' and ' . get_access_sql_suffix("m{$mindex}"); // Add access controls - $mindex++; - } - - if (!$count) { - $query .= " order by $order_by limit $offset, $limit"; // Add order and limit - return get_data($query, "entity_row_to_elggstar"); - } else { - if ($count = get_data_row($query)) { - return $count->total; - } - } - return false; - } - - /** - * Returns a viewable list of entities based on the given search criteria. - * - * @see elgg_view_entity_list - * - * @param array $meta_array Array of 'name' => 'value' pairs - * @param string $entity_type The type of entity to look for, eg 'site' or 'object' - * @param string $entity_subtype The subtype of the entity. - * @param int $limit - * @param int $offset - * @param string $order_by Optional ordering. - * @param true|false $fullview Whether or not to display the full view (default: true) - * @param true|false $viewtypetoggle Whether or not to allow users to toggle to the gallery view. Default: true - * @param true|false $pagination Display pagination? Default: true - * @return string List of ElggEntities suitable for display - */ - function list_entities_from_metadata_multi($meta_array, $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true) { - - $offset = (int) get_input('offset'); - $limit = (int) $limit; - $count = get_entities_from_metadata_multi($meta_array, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", $site_guid, true); - $entities = get_entities_from_metadata_multi($meta_array, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", $site_guid, false); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); - - } - - /** - * Clear all the metadata for a given entity, assuming you have access to that metadata. - * - * @param int $guid - */ - function clear_metadata($entity_guid) - { - global $CONFIG; - - $entity_guid = (int)$entity_guid; - if ($entity = get_entity($entity_guid)) { - if ($entity->canEdit()) - return delete_data("DELETE from {$CONFIG->dbprefix}metadata where entity_guid={$entity_guid}"); - } - return false; - } - - /** - * Clear all annotations belonging to a given owner_guid - * - * @param int $owner_guid The owner - */ - function clear_metadata_by_owner($owner_guid) - { - global $CONFIG; - - $owner_guid = (int)$owner_guid; - - $metas = get_data("SELECT id from {$CONFIG->dbprefix}metadata WHERE owner_guid=$owner_guid"); - $deleted = 0; - - foreach ($metas as $id) - { - if (delete_metadata($id->id)) // Is this the best way? - $deleted++; - } - - return $deleted; - } - - /** - * Handler called by trigger_plugin_hook on the "export" event. - */ - function export_metadata_plugin_hook($hook, $entity_type, $returnvalue, $params) - { - // Sanity check values - if ((!is_array($params)) && (!isset($params['guid']))) - throw new InvalidParameterException(elgg_echo('InvalidParameterException:GUIDNotForExport')); - - if (!is_array($returnvalue)) - throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonArrayReturnValue')); - - $guid = (int)$params['guid']; - $name = $params['name']; - - $result = get_metadata_for_entity($guid); - - if ($result) - { - foreach ($result as $r) - $returnvalue[] = $r->export(); - } - - return $returnvalue; - } - - /** - * Takes in a comma-separated string and returns an array of tags which have been trimmed and set to lower case - * - * @param string $string Comma-separated tag string - * @return array|false An array of strings, or false on failure - */ - function string_to_tag_array($string) { - - if (is_string($string)) { - $ar = explode(",",$string); - $ar = array_map('trim', $ar); // trim blank spaces - $ar = array_map('elgg_strtolower', $ar); // make lower case : [Marcus Povey 20090605 - Using mb wrapper function using UTF8 safe function where available] - $ar = array_filter($ar, 'is_not_null'); // Remove null values - return $ar; - } - return false; - - } - - /** - * Takes a metadata array (which has all kinds of properties) and turns it into a simple array of strings - * - * @param array $array Metadata array - * @return array Array of strings - */ - function metadata_array_to_values($array) { - - $valuearray = array(); - - if (is_array($array)) { - foreach($array as $element) { - $valuearray[] = $element->value; - } - } - - return $valuearray; - - } - - /** - * Get the URL for this item of metadata, by default this links to the export handler in the current view. - * - * @param int $id - */ - function get_metadata_url($id) - { - $id = (int)$id; - - if ($extender = get_metadata($id)) { - return get_extender_url($extender); - } - return false; - } - - /** - * Mark entities with a particular type and subtype as having access permissions - * that can be changed independently from their parent entity - * - * @param string $type The type - object, user, etc - * @param string $subtype The subtype; all subtypes by default - */ - function register_metadata_as_independent($type, $subtype = '*') { - global $CONFIG; - if (!isset($CONFIG->independents)) $CONFIG->independents = array(); - $CONFIG->independents[$type][$subtype] = true; - } - - /** - * Determines whether entities of a given type and subtype should not change - * their metadata in line with their parent entity - * - * @param string $type The type - object, user, etc - * @param string $subtype The entity subtype - * @return true|false - */ - function is_metadata_independent($type, $subtype) { - global $CONFIG; - if (empty($CONFIG->independents)) return false; - if (!empty($CONFIG->independents[$type][$subtype]) - || !empty($CONFIG->independents[$type]['*'])) return true; - return false; - } - - /** - * When an entity is updated, resets the access ID on all of its child metadata - * - * @param string $event The name of the event - * @param string $object_type The type of object - * @param ElggEntity $object The entity itself - */ - function metadata_update($event, $object_type, $object) { - if ($object instanceof ElggEntity) { - if (!is_metadata_independent($object->getType(), $object->getSubtype())) { - global $CONFIG; - $access_id = (int) $object->access_id; - $guid = (int) $object->getGUID(); - update_data("update {$CONFIG->dbprefix}metadata set access_id = {$access_id} where entity_guid = {$guid}"); - } - } - return true; - } - - /** - * Register a metadata url handler. - * - * @param string $function_name The function. - * @param string $extender_name The name, default 'all'. - */ - function register_metadata_url_handler($function_name, $extender_name = "all") { - return register_extender_url_handler($function_name, 'metadata', $extender_name); - } - - /** Register the hook */ - register_plugin_hook("export", "all", "export_metadata_plugin_hook", 2); - /** Call a function whenever an entity is updated **/ - register_elgg_event_handler('update','all','metadata_update'); - -?> + * @link http://elgg.org/ + */ + + /** + * ElggMetadata + * This class describes metadata that can be attached to ElggEntities. + * + * @author Curverider Ltd + * @package Elgg + * @subpackage Core + */ + class ElggMetadata extends ElggExtender + { + + /** + * Construct a new site object, optionally from a given id value or row. + * + * @param mixed $id + */ + function __construct($id = null) + { + $this->attributes = array(); + + if (!empty($id)) { + + if ($id instanceof stdClass) + $metadata = $id; // Create from db row + else + $metadata = get_metadata($id); + + if ($metadata) { + $objarray = (array) $metadata; + foreach($objarray as $key => $value) { + $this->attributes[$key] = $value; + } + $this->attributes['type'] = "metadata"; + } + } + } + + /** + * Class member get overloading + * + * @param string $name + * @return mixed + */ + function __get($name) { + return $this->get($name); + } + + /** + * Class member set overloading + * + * @param string $name + * @param mixed $value + * @return mixed + */ + function __set($name, $value) { + return $this->set($name, $value); + } + + /** + * Determines whether or not the user can edit this piece of metadata + * + * @return true|false Depending on permissions + */ + function canEdit() { + + if ($entity = get_entity($this->get('entity_guid'))) { + return $entity->canEditMetadata($this); + } + return false; + + } + + /** + * Save matadata object + * + * @return int the metadata object id + */ + function save() + { + if ($this->id > 0) + return update_metadata($this->id, $this->name, $this->value, $this->value_type, $this->owner_guid, $this->access_id); + else + { + $this->id = create_metadata($this->entity_guid, $this->name, $this->value, $this->value_type, $this->owner_guid, $this->access_id); + if (!$this->id) throw new IOException(sprintf(elgg_new('IOException:UnableToSaveNew'), get_class())); + return $this->id; + } + + } + + /** + * Delete a given metadata. + */ + function delete() + { + return delete_metadata($this->id); + } + + /** + * Get a url for this item of metadata. + * + * @return string + */ + public function getURL() { return get_metadata_url($this->id); } + + // SYSTEM LOG INTERFACE //////////////////////////////////////////////////////////// + + /** + * For a given ID, return the object associated with it. + * This is used by the river functionality primarily. + * This is useful for checking access permissions etc on objects. + */ + public function getObjectFromID($id) { return get_metadata($id); } + } + + /** + * Convert a database row to a new ElggMetadata + * + * @param stdClass $row + * @return stdClass or ElggMetadata + */ + function row_to_elggmetadata($row) + { + if (!($row instanceof stdClass)) + return $row; + + return new ElggMetadata($row); + } + + + /** + * Get a specific item of metadata. + * + * @param $id int The item of metadata being retrieved. + */ + function get_metadata($id) + { + global $CONFIG; + + $id = (int)$id; + $access = get_access_sql_suffix("e"); + $md_access = get_access_sql_suffix("m"); + + return row_to_elggmetadata(get_data_row("SELECT m.*, n.string as name, v.string as value from {$CONFIG->dbprefix}metadata m JOIN {$CONFIG->dbprefix}entities e on e.guid = m.entity_guid JOIN {$CONFIG->dbprefix}metastrings v on m.value_id = v.id JOIN {$CONFIG->dbprefix}metastrings n on m.name_id = n.id where m.id=$id and $access and $md_access")); + } + + /** + * Removes metadata on an entity with a particular name, optionally with a given value. + * + * @param int $entity_guid The entity GUID + * @param string $name The name of the metadata + * @param string $value The optional value of the item (useful for removing a single item in a multiple set) + * @return true|false Depending on success + */ + function remove_metadata($entity_guid, $name, $value = "") { + + global $CONFIG; + $entity_guid = (int) $entity_guid; + $name = sanitise_string($name); + $value = sanitise_string($value); + + $query = "SELECT * from {$CONFIG->dbprefix}metadata WHERE entity_guid = $entity_guid and name_id=" . add_metastring($name); + if ($value!="") + $query .= " and value_id=" . add_metastring($value); + + if ($existing = get_data($query)) { + foreach($existing as $ex) + delete_metadata($ex->id); + return true; + } + return false; + + } + + /** + * Create a new metadata object, or update an existing one. + * + * @param int $entity_guid + * @param string $name + * @param string $value + * @param string $value_type + * @param int $owner_guid + * @param int $access_id + * @param bool $allow_multiple + */ + function create_metadata($entity_guid, $name, $value, $value_type, $owner_guid, $access_id = ACCESS_PRIVATE, $allow_multiple = false) + { + global $CONFIG; + + $entity_guid = (int)$entity_guid; + //$name = sanitise_string(trim($name)); + //$value = sanitise_string(trim($value)); + $value_type = detect_extender_valuetype($value, sanitise_string(trim($value_type))); + $time = time(); + $owner_guid = (int)$owner_guid; + $allow_multiple = (boolean)$allow_multiple; + + if ($owner_guid==0) $owner_guid = get_loggedin_userid(); + + $access_id = (int)$access_id; + + $id = false; + + $existing = get_data_row("SELECT * from {$CONFIG->dbprefix}metadata WHERE entity_guid = $entity_guid and name_id=" . add_metastring($name) . " limit 1"); + if (($existing) && (!$allow_multiple) && (isset($value))) + { + $id = $existing->id; + $result = update_metadata($id, $name, $value, $value_type, $owner_guid, $access_id); + + if (!$result) return false; + } + else if (isset($value)) + { + // Support boolean types + if (is_bool($value)) { + if ($value) + $value = 1; + else + $value = 0; + } + + // Add the metastrings + $value = add_metastring($value); + if (!$value) return false; + + $name = add_metastring($name); + if (!$name) return false; + + // If ok then add it + $id = insert_data("INSERT into {$CONFIG->dbprefix}metadata (entity_guid, name_id, value_id, value_type, owner_guid, time_created, access_id) VALUES ($entity_guid, '$name','$value','$value_type', $owner_guid, $time, $access_id)"); + + if ($id!==false) { + $obj = get_metadata($id); + if (trigger_elgg_event('create', 'metadata', $obj)) { + return true; + } else { + delete_metadata($id); + } + } + + } else if ($existing) { +// TODO: Check... are you sure you meant to do this Ben? :) + $id = $existing->id; + delete_metadata($id); + + } + + return $id; + } + + /** + * Update an item of metadata. + * + * @param int $id + * @param string $name + * @param string $value + * @param string $value_type + * @param int $owner_guid + * @param int $access_id + */ + function update_metadata($id, $name, $value, $value_type, $owner_guid, $access_id) + { + global $CONFIG; + + $id = (int)$id; + + if (!$md = get_metadata($id)) return false; + if (!$md->canEdit()) return false; + + // If memcached then we invalidate the cache for this entry + static $metabyname_memcache; + if ((!$metabyname_memcache) && (is_memcache_available())) + $metabyname_memcache = new ElggMemcache('metabyname_memcache'); + if ($metabyname_memcache) $metabyname_memcache->delete("{$md->entity_guid}:{$md->name_id}"); + + //$name = sanitise_string(trim($name)); + //$value = sanitise_string(trim($value)); + $value_type = detect_extender_valuetype($value, sanitise_string(trim($value_type))); + + $owner_guid = (int)$owner_guid; + if ($owner_guid==0) $owner_guid = get_loggedin_userid(); + + $access_id = (int)$access_id; + + $access = get_access_sql_suffix(); + + // Support boolean types (as integers) + if (is_bool($value)) { + if ($value) + $value = 1; + else + $value = 0; + } + + // Add the metastring + $value = add_metastring($value); + if (!$value) return false; + + $name = add_metastring($name); + if (!$name) return false; + + // If ok then add it + $result = update_data("UPDATE {$CONFIG->dbprefix}metadata set value_id='$value', value_type='$value_type', access_id=$access_id, owner_guid=$owner_guid where id=$id and name_id='$name'"); + if ($result!==false) { + $obj = get_metadata($id); + if (trigger_elgg_event('update', 'metadata', $obj)) { + return true; + } else { + delete_metadata($id); + } + } + + return $result; + } + + /** + * This function creates metadata from an associative array of "key => value" pairs. + * + * @param int $entity_guid + * @param string $name_and_values + * @param string $value_type + * @param int $owner_guid + * @param int $access_id + * @param bool $allow_multiple + */ + function create_metadata_from_array($entity_guid, array $name_and_values, $value_type, $owner_guid, $access_id = ACCESS_PRIVATE, $allow_multiple = false) + { + foreach ($name_and_values as $k => $v) + if (!create_metadata($entity_guid, $k, $v, $value_type, $owner_guid, $access_id, $allow_multiple)) return false; + + return true; + } + + /** + * Delete an item of metadata, where the current user has access. + * + * @param $id int The item of metadata to delete. + */ + function delete_metadata($id) + { + global $CONFIG; + + $id = (int)$id; + $metadata = get_metadata($id); + + if ($metadata) { + // Tidy up if memcache is enabled. + static $metabyname_memcache; + if ((!$metabyname_memcache) && (is_memcache_available())) + $metabyname_memcache = new ElggMemcache('metabyname_memcache'); + if ($metabyname_memcache) $metabyname_memcache->delete("{$metadata->entity_guid}:{$metadata->name_id}"); + + if (($metadata->canEdit()) && (trigger_elgg_event('delete', 'metadata', $metadata))) + return delete_data("DELETE from {$CONFIG->dbprefix}metadata where id=$id"); + } + + return false; + } + + /** + * Return the metadata values that match your query. + * + * @param string $meta_name + * @return mixed either a value, an array of ElggMetadata or false. + */ + function get_metadata_byname($entity_guid, $meta_name) + { + global $CONFIG; + + $meta_name = get_metastring_id($meta_name); + + if (empty($meta_name)) return false; + + $entity_guid = (int)$entity_guid; + $access = get_access_sql_suffix("e"); + $md_access = get_access_sql_suffix("m"); + + // If memcache is available then cache this (cache only by name for now since this is the most common query) + $meta = null; + static $metabyname_memcache; + if ((!$metabyname_memcache) && (is_memcache_available())) + $metabyname_memcache = new ElggMemcache('metabyname_memcache'); + if ($metabyname_memcache) $meta = $metabyname_memcache->load("{$entity_guid}:{$meta_name}"); + if ($meta) return $meta; + + $result = get_data("SELECT m.*, n.string as name, v.string as value from {$CONFIG->dbprefix}metadata m JOIN {$CONFIG->dbprefix}entities e ON e.guid = m.entity_guid JOIN {$CONFIG->dbprefix}metastrings v on m.value_id = v.id JOIN {$CONFIG->dbprefix}metastrings n on m.name_id = n.id where m.entity_guid=$entity_guid and m.name_id='$meta_name' and $access and $md_access", "row_to_elggmetadata"); + if (!$result) + return false; + + // Cache if memcache available + if ($metabyname_memcache) + { + if (count($result) == 1) $r = $result[0]; else $r = $result; + $metabyname_memcache->setDefaultExpiry(3600); // This is a bit of a hack - we shorten the expiry on object metadata so that it'll be gone in an hour. This means that deletions and more importantly updates will filter through eventually. + $metabyname_memcache->save("{$entity_guid}:{$meta_name}", $r); + + } + if (count($result) == 1) + return $result[0]; + + return $result; + } + + /** + * Return all the metadata for a given GUID. + * + * @param int $entity_guid + */ + function get_metadata_for_entity($entity_guid) + { + global $CONFIG; + + $entity_guid = (int)$entity_guid; + $access = get_access_sql_suffix("e"); + $md_access = get_access_sql_suffix("m"); + + return get_data("SELECT m.*, n.string as name, v.string as value from {$CONFIG->dbprefix}metadata m JOIN {$CONFIG->dbprefix}entities e ON e.guid = m.entity_guid JOIN {$CONFIG->dbprefix}metastrings v on m.value_id = v.id JOIN {$CONFIG->dbprefix}metastrings n on m.name_id = n.id where m.entity_guid=$entity_guid and $access and $md_access", "row_to_elggmetadata"); + } + + /** + * Get the metadata where the entities they are referring to match a given criteria. + * + * @param mixed $meta_name + * @param mixed $meta_value + * @param string $entity_type The type of entity to look for, eg 'site' or 'object' + * @param string $entity_subtype The subtype of the entity. + * @param int $limit + * @param int $offset + * @param string $order_by Optional ordering. + * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. + */ + function find_metadata($meta_name = "", $meta_value = "", $entity_type = "", $entity_subtype = "", $limit = 10, $offset = 0, $order_by = "", $site_guid = 0) + { + global $CONFIG; + + $meta_n = get_metastring_id($meta_name); + $meta_v = get_metastring_id($meta_value); + + $entity_type = sanitise_string($entity_type); + $entity_subtype = get_subtype_id($entity_type, $entity_subtype); + $limit = (int)$limit; + $offset = (int)$offset; + if ($order_by == "") $order_by = "e.time_created desc"; + $order_by = sanitise_string($order_by); + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + + $where = array(); + + if ($entity_type!="") + $where[] = "e.type='$entity_type'"; + if ($entity_subtype) + $where[] = "e.subtype=$entity_subtype"; + if ($meta_name!="") { + if (!$meta_v) return false; // The value is set, but we didn't get a value... so something went wrong. + $where[] = "m.name_id='$meta_n'"; + } + if ($meta_value!="") { + if (!$meta_v) return false; // The value is set, but we didn't get a value... so something went wrong. + $where[] = "m.value_id='$meta_v'"; + } + if ($site_guid > 0) + $where[] = "e.site_guid = {$site_guid}"; + + $query = "SELECT m.*, n.string as name, v.string as value from {$CONFIG->dbprefix}entities e JOIN {$CONFIG->dbprefix}metadata m on e.guid = m.entity_guid JOIN {$CONFIG->dbprefix}metastrings v on m.value_id = v.id JOIN {$CONFIG->dbprefix}metastrings n on m.name_id = n.id where"; + foreach ($where as $w) + $query .= " $w and "; + $query .= get_access_sql_suffix("e"); // Add access controls + $query .= ' and ' . get_access_sql_suffix("m"); // Add access controls + $query .= " order by $order_by limit $offset, $limit"; // Add order and limit + + return get_data($query, "row_to_elggmetadata"); + } + + /** + * Return a list of entities based on the given search criteria. + * + * @param mixed $meta_name + * @param mixed $meta_value + * @param string $entity_type The type of entity to look for, eg 'site' or 'object' + * @param string $entity_subtype The subtype of the entity. + * @param int $limit + * @param int $offset + * @param string $order_by Optional ordering. + * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. + * @param true|false $count If set to true, returns the total number of entities rather than a list. (Default: false) + * + * @return int|array A list of entities, or a count if $count is set to true + */ + function get_entities_from_metadata($meta_name, $meta_value = "", $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $order_by = "", $site_guid = 0, $count = false) + { + global $CONFIG; + + $meta_n = get_metastring_id($meta_name); + $meta_v = get_metastring_id($meta_value); + + $entity_type = sanitise_string($entity_type); + $entity_subtype = get_subtype_id($entity_type, $entity_subtype); + $limit = (int)$limit; + $offset = (int)$offset; + if ($order_by == "") + $order_by = "e.time_created desc"; + else + $order_by = "e.time_created, {$order_by}"; + $order_by = sanitise_string($order_by); + $site_guid = (int) $site_guid; + if ((is_array($owner_guid) && (count($owner_guid)))) { + foreach($owner_guid as $key => $guid) { + $owner_guid[$key] = (int) $guid; + } + } else { + $owner_guid = (int) $owner_guid; + } + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + //$access = get_access_list(); + + $where = array(); + + if ($entity_type!=="") + $where[] = "e.type='$entity_type'"; + if ($entity_subtype) + $where[] = "e.subtype=$entity_subtype"; + if ($meta_name!=="") + $where[] = "m.name_id='$meta_n'"; + if ($meta_value!=="") + $where[] = "m.value_id='$meta_v'"; + if ($site_guid > 0) + $where[] = "e.site_guid = {$site_guid}"; + if (is_array($owner_guid)) { + $where[] = "e.container_guid in (".implode(",",$owner_guid).")"; + } else if ($owner_guid > 0) + $where[] = "e.container_guid = {$owner_guid}"; + + if (!$count) { + $query = "SELECT distinct e.* "; + } else { + $query = "SELECT count(distinct e.guid) as total "; + } + + $query .= "from {$CONFIG->dbprefix}entities e JOIN {$CONFIG->dbprefix}metadata m on e.guid = m.entity_guid where"; + foreach ($where as $w) + $query .= " $w and "; + $query .= get_access_sql_suffix("e"); // Add access controls + $query .= ' and ' . get_access_sql_suffix("m"); // Add access controls + + if (!$count) { + $query .= " order by $order_by limit $offset, $limit"; // Add order and limit + return get_data($query, "entity_row_to_elggstar"); + } else { + if ($row = get_data_row($query)) + return $row->total; + } + return false; + } + + /** + * Return a list of entities suitable for display based on the given search criteria. + * + * @see elgg_view_entity_list + * + * @param mixed $meta_name Metadata name to search on + * @param mixed $meta_value The value to match, optionally + * @param string $entity_type The type of entity to look for, eg 'site' or 'object' + * @param string $entity_subtype The subtype of the entity + * @param int $limit Number of entities to display per page + * @param true|false $fullview Whether or not to display the full view (default: true) + * @param true|false $viewtypetoggle Whether or not to allow users to toggle to the gallery view. Default: true + * @param true|false $pagination Display pagination? Default: true + * + * @return string A list of entities suitable for display + */ + function list_entities_from_metadata($meta_name, $meta_value = "", $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true) { + + $offset = (int) get_input('offset'); + $limit = (int) $limit; + $count = get_entities_from_metadata($meta_name, $meta_value, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", 0, true); + $entities = get_entities_from_metadata($meta_name, $meta_value, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", 0, false); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); + + } + + /** + * Returns a list of entities based on the given search criteria. + * + * @param array $meta_array Array of 'name' => 'value' pairs + * @param string $entity_type The type of entity to look for, eg 'site' or 'object' + * @param string $entity_subtype The subtype of the entity. + * @param int $limit + * @param int $offset + * @param string $order_by Optional ordering. + * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. + * @param true|false $count If set to true, returns the total number of entities rather than a list. (Default: false) + * @param string $meta_array_operator Operator used for joining the metadata array together + * @return int|array List of ElggEntities, or the total number if count is set to false + */ + function get_entities_from_metadata_multi($meta_array, $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $order_by = "", $site_guid = 0, $count = false, $meta_array_operator = 'and') + { + global $CONFIG; + + if (!is_array($meta_array) || sizeof($meta_array) == 0) { + return false; + } + + $where = array(); + + $mindex = 1; + $join = ""; + $metawhere = array(); + $meta_array_operator = sanitise_string($meta_array_operator); + foreach($meta_array as $meta_name => $meta_value) { + $meta_n = get_metastring_id($meta_name); + $meta_v = get_metastring_id($meta_value); + $join .= " JOIN {$CONFIG->dbprefix}metadata m{$mindex} on e.guid = m{$mindex}.entity_guid "; + /*if ($meta_name!=="") + $where[] = "m{$mindex}.name_id='$meta_n'"; + if ($meta_value!=="") + $where[] = "m{$mindex}.value_id='$meta_v'";*/ + $metawhere[] = "(m{$mindex}.name_id='$meta_n' AND m{$mindex}.value_id='$meta_v')"; + $mindex++; + } + $where[] = "(".implode($meta_array_operator, $metawhere).")"; + + $entity_type = sanitise_string($entity_type); + $entity_subtype = get_subtype_id($entity_type, $entity_subtype); + $limit = (int)$limit; + $offset = (int)$offset; + if ($order_by == "") $order_by = "e.time_created desc"; + $order_by = sanitise_string($order_by); + if ((is_array($owner_guid) && (count($owner_guid)))) { + foreach($owner_guid as $key => $guid) { + $owner_guid[$key] = (int) $guid; + } + } else { + $owner_guid = (int) $owner_guid; + } + + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + //$access = get_access_list(); + + if ($entity_type!="") + $where[] = "e.type = '{$entity_type}'"; + if ($entity_subtype) + $where[] = "e.subtype = {$entity_subtype}"; + if ($site_guid > 0) + $where[] = "e.site_guid = {$site_guid}"; + if (is_array($owner_guid)) { + $where[] = "e.container_guid in (".implode(",",$owner_guid).")"; + } else if ($owner_guid > 0) + $where[] = "e.container_guid = {$owner_guid}"; + //if ($owner_guid > 0) + // $where[] = "e.container_guid = {$owner_guid}"; + + if ($count) { + $query = "SELECT count(distinct e.guid) as total "; + } else { + $query = "SELECT distinct e.* "; + } + + $query .= " from {$CONFIG->dbprefix}entities e {$join} where"; + foreach ($where as $w) + $query .= " $w and "; + $query .= get_access_sql_suffix("e"); // Add access controls + + $mindex = 1; + foreach($meta_array as $meta_name => $meta_value) { + $query .= ' and ' . get_access_sql_suffix("m{$mindex}"); // Add access controls + $mindex++; + } + + if (!$count) { + $query .= " order by $order_by limit $offset, $limit"; // Add order and limit + return get_data($query, "entity_row_to_elggstar"); + } else { + if ($count = get_data_row($query)) { + return $count->total; + } + } + return false; + } + + /** + * Returns a viewable list of entities based on the given search criteria. + * + * @see elgg_view_entity_list + * + * @param array $meta_array Array of 'name' => 'value' pairs + * @param string $entity_type The type of entity to look for, eg 'site' or 'object' + * @param string $entity_subtype The subtype of the entity. + * @param int $limit + * @param int $offset + * @param string $order_by Optional ordering. + * @param true|false $fullview Whether or not to display the full view (default: true) + * @param true|false $viewtypetoggle Whether or not to allow users to toggle to the gallery view. Default: true + * @param true|false $pagination Display pagination? Default: true + * @return string List of ElggEntities suitable for display + */ + function list_entities_from_metadata_multi($meta_array, $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true) { + + $offset = (int) get_input('offset'); + $limit = (int) $limit; + $count = get_entities_from_metadata_multi($meta_array, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", $site_guid, true); + $entities = get_entities_from_metadata_multi($meta_array, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", $site_guid, false); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); + + } + + /** + * Clear all the metadata for a given entity, assuming you have access to that metadata. + * + * @param int $guid + */ + function clear_metadata($entity_guid) + { + global $CONFIG; + + $entity_guid = (int)$entity_guid; + if ($entity = get_entity($entity_guid)) { + if ($entity->canEdit()) + return delete_data("DELETE from {$CONFIG->dbprefix}metadata where entity_guid={$entity_guid}"); + } + return false; + } + + /** + * Clear all annotations belonging to a given owner_guid + * + * @param int $owner_guid The owner + */ + function clear_metadata_by_owner($owner_guid) + { + global $CONFIG; + + $owner_guid = (int)$owner_guid; + + $metas = get_data("SELECT id from {$CONFIG->dbprefix}metadata WHERE owner_guid=$owner_guid"); + $deleted = 0; + + foreach ($metas as $id) + { + if (delete_metadata($id->id)) // Is this the best way? + $deleted++; + } + + return $deleted; + } + + /** + * Handler called by trigger_plugin_hook on the "export" event. + */ + function export_metadata_plugin_hook($hook, $entity_type, $returnvalue, $params) + { + // Sanity check values + if ((!is_array($params)) && (!isset($params['guid']))) + throw new InvalidParameterException(elgg_echo('InvalidParameterException:GUIDNotForExport')); + + if (!is_array($returnvalue)) + throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonArrayReturnValue')); + + $guid = (int)$params['guid']; + $name = $params['name']; + + $result = get_metadata_for_entity($guid); + + if ($result) + { + foreach ($result as $r) + $returnvalue[] = $r->export(); + } + + return $returnvalue; + } + + /** + * Takes in a comma-separated string and returns an array of tags which have been trimmed and set to lower case + * + * @param string $string Comma-separated tag string + * @return array|false An array of strings, or false on failure + */ + function string_to_tag_array($string) { + + if (is_string($string)) { + $ar = explode(",",$string); + $ar = array_map('trim', $ar); // trim blank spaces + $ar = array_map('elgg_strtolower', $ar); // make lower case : [Marcus Povey 20090605 - Using mb wrapper function using UTF8 safe function where available] + $ar = array_filter($ar, 'is_not_null'); // Remove null values + return $ar; + } + return false; + + } + + /** + * Takes a metadata array (which has all kinds of properties) and turns it into a simple array of strings + * + * @param array $array Metadata array + * @return array Array of strings + */ + function metadata_array_to_values($array) { + + $valuearray = array(); + + if (is_array($array)) { + foreach($array as $element) { + $valuearray[] = $element->value; + } + } + + return $valuearray; + + } + + /** + * Get the URL for this item of metadata, by default this links to the export handler in the current view. + * + * @param int $id + */ + function get_metadata_url($id) + { + $id = (int)$id; + + if ($extender = get_metadata($id)) { + return get_extender_url($extender); + } + return false; + } + + /** + * Mark entities with a particular type and subtype as having access permissions + * that can be changed independently from their parent entity + * + * @param string $type The type - object, user, etc + * @param string $subtype The subtype; all subtypes by default + */ + function register_metadata_as_independent($type, $subtype = '*') { + global $CONFIG; + if (!isset($CONFIG->independents)) $CONFIG->independents = array(); + $CONFIG->independents[$type][$subtype] = true; + } + + /** + * Determines whether entities of a given type and subtype should not change + * their metadata in line with their parent entity + * + * @param string $type The type - object, user, etc + * @param string $subtype The entity subtype + * @return true|false + */ + function is_metadata_independent($type, $subtype) { + global $CONFIG; + if (empty($CONFIG->independents)) return false; + if (!empty($CONFIG->independents[$type][$subtype]) + || !empty($CONFIG->independents[$type]['*'])) return true; + return false; + } + + /** + * When an entity is updated, resets the access ID on all of its child metadata + * + * @param string $event The name of the event + * @param string $object_type The type of object + * @param ElggEntity $object The entity itself + */ + function metadata_update($event, $object_type, $object) { + if ($object instanceof ElggEntity) { + if (!is_metadata_independent($object->getType(), $object->getSubtype())) { + global $CONFIG; + $access_id = (int) $object->access_id; + $guid = (int) $object->getGUID(); + update_data("update {$CONFIG->dbprefix}metadata set access_id = {$access_id} where entity_guid = {$guid}"); + } + } + return true; + } + + /** + * Register a metadata url handler. + * + * @param string $function_name The function. + * @param string $extender_name The name, default 'all'. + */ + function register_metadata_url_handler($function_name, $extender_name = "all") { + return register_extender_url_handler($function_name, 'metadata', $extender_name); + } + + /** Register the hook */ + register_plugin_hook("export", "all", "export_metadata_plugin_hook", 2); + /** Call a function whenever an entity is updated **/ + register_elgg_event_handler('update','all','metadata_update'); + +?> diff --git a/engine/lib/metastrings.php b/engine/lib/metastrings.php index 94529e16f..31981efab 100644 --- a/engine/lib/metastrings.php +++ b/engine/lib/metastrings.php @@ -68,18 +68,18 @@ $METASTRINGS_DEADNAME_CACHE[$string] = $string; return false; - } - - /** - * When given an ID, returns the corresponding metastring - * - * @param int $id Metastring ID - * @return string Metastring - */ - function get_metastring($id) { - - global $CONFIG, $METASTRINGS_CACHE; - + } + + /** + * When given an ID, returns the corresponding metastring + * + * @param int $id Metastring ID + * @return string Metastring + */ + function get_metastring($id) { + + global $CONFIG, $METASTRINGS_CACHE; + $id = (int) $id; if (isset($METASTRINGS_CACHE[$id])) { @@ -88,20 +88,20 @@ error_log("** Returning string for id:$id from cache."); return $METASTRINGS_CACHE[$id]; - } - - $row = get_data_row("SELECT * from {$CONFIG->dbprefix}metastrings where id='$id' limit 1"); + } + + $row = get_data_row("SELECT * from {$CONFIG->dbprefix}metastrings where id='$id' limit 1"); if ($row) { $METASTRINGS_CACHE[$id] = $row->string; // Cache it if ($CONFIG->debug) error_log("** Cacheing string '{$row->string}'"); - + return $row->string; - } - - return false; - + } + + return false; + } /** diff --git a/engine/lib/notification.php b/engine/lib/notification.php index f1336d1b8..6b91a67cf 100644 --- a/engine/lib/notification.php +++ b/engine/lib/notification.php @@ -1,430 +1,430 @@ -handler = $handler; - if ($params) - { - foreach ($params as $k => $v) - $NOTIFICATION_HANDLERS[$method]->$k = $v; - } - - return true; - } - - return false; - } - - /** - * Notify a user via their preferences. - * - * @param mixed $to Either a guid or an array of guid's to notify. - * @param int $from GUID of the sender, which may be a user, site or object. - * @param string $subject Message subject. - * @param string $message Message body. - * @param array $params Misc additional parameters specific to various methods. - * @param mixed $methods_override A string, or an array of strings specifying the delivery methods to use - or leave blank - * for delivery using the user's chosen delivery methods. - * @return array Compound array of each delivery user/delivery method's success or failure. - * @throws NotificationException - */ - function notify_user($to, $from, $subject, $message, array $params = NULL, $methods_override = "") - { - global $NOTIFICATION_HANDLERS, $CONFIG; - - // Sanitise - if (!is_array($to)) - $to = array((int)$to); - $from = (int)$from; - //$subject = sanitise_string($subject); - - // Get notification methods - if (($methods_override) && (!is_array($methods_override))) - $methods_override = array($methods_override); - - $result = array(); - - foreach ($to as $guid) - { - // Results for a user are... - $result[$guid] = array(); - - if ($guid) { // Is the guid > 0? - // Are we overriding delivery? - $methods = $methods_override; - if (!$methods) - { - $tmp = (array)get_user_notification_settings($guid); - $methods = array(); - foreach($tmp as $k => $v) - if ($v) $methods[] = $k; // Add method if method is turned on for user! - } - - if ($methods) - { - // Deliver - foreach ($methods as $method) - { - // Extract method details from list - $details = $NOTIFICATION_HANDLERS[$method]; - $handler = $details->handler; - - if ((!$NOTIFICATION_HANDLERS[$method]) || (!$handler)) - error_log(sprintf(elgg_echo('NotificationException:NoHandlerFound'), $method)); - - if ($CONFIG->debug) - error_log("Sending message to $guid using $method"); - - // Trigger handler and retrieve result. - try { - $result[$guid][$method] = $handler( - $from ? get_entity($from) : NULL, // From entity - get_entity($guid), // To entity - $subject, // The subject - $message, // Message - $params // Params - ); - } catch (Exception $e) { - error_log($e->getMessage()); - } - - } - } - } - } - - return $result; - } - - /** - * Get the notification settings for a given user. - * - * @param int $user_guid The user id - * @return stdClass - */ - function get_user_notification_settings($user_guid = 0) - { - $user_guid = (int)$user_guid; - - if ($user_guid == 0) $user_guid = get_loggedin_userid(); - - $all_metadata = get_metadata_for_entity($user_guid); - if ($all_metadata) - { - $prefix = "notification:method:"; - $return = new stdClass; - - foreach ($all_metadata as $meta) - { - $name = substr($meta->name, strlen($prefix)); - $value = $meta->value; - - if (strpos($meta->name, $prefix) === 0) - $return->$name = $value; - } - - return $return; - } - - return false; - } - - /** - * Set a user notification pref. - * - * @param int $user_guid The user id. - * @param string $method The delivery method (eg. email) - * @param bool $value On(true) or off(false). - * @return bool - */ - function set_user_notification_setting($user_guid, $method, $value) - { - $user_guid = (int)$user_guid; - $method = sanitise_string($method); - - $user = get_entity($user_guid); - if (!$user) $user = get_loggedin_user(); - - if (($user) && ($user instanceof ElggUser)) - { - $prefix = "notification:method:$method"; - $user->$prefix = $value; - $user->save(); - - return true; - } - - return false; - } - - /** - * Notification exception. - * @author Curverider Ltd - */ - class NotificationException extends Exception {} - - - /** - * Send a notification via email. - * - * @param ElggEntity $from The from user/site/object - * @param ElggUser $to To which user? - * @param string $subject The subject of the message. - * @param string $message The message body - * @param array $params Optional parameters (none taken in this instance) - * @return bool - */ - function email_notify_handler(ElggEntity $from, ElggUser $to, $subject, $message, array $params = NULL) - { - global $CONFIG; - - if (!$from) - throw new NotificationException(sprintf(elgg_echo('NotificationException:MissingParameter'), 'from')); - - if (!$to) - throw new NotificationException(sprintf(elgg_echo('NotificationException:MissingParameter'), 'to')); - - if ($to->email=="") - throw new NotificationException(sprintf(elgg_echo('NotificationException:NoEmailAddress'), $to->guid)); - - // Sanitise subject - $subject = preg_replace("/(\r\n|\r|\n)/", " ", $subject); // Strip line endings - - // To - $to = $to->email; - - // From - $site = get_entity($CONFIG->site_guid); - if ((isset($from->email)) && (!($from instanceof ElggUser))) // If there's an email address, use it - but only if its not from a user. - $from = $from->email; - else if (($site) && (isset($site->email))) // Has the current site got a from email address? - $from = $site->email; - else if (isset($from->url)) // If we have a url then try and use that. - { - $breakdown = parse_url($from->url); - $from = 'noreply@' . $breakdown['host']; // Handle anything with a url - } - else // If all else fails, use the domain of the site. - $from = 'noreply@' . get_site_domain($CONFIG->site_guid); - - if (is_callable('mb_internal_encoding')) { - mb_internal_encoding('UTF-8'); - } - $site = get_entity($CONFIG->site_guid); - $sitename = $site->name; - if (is_callable('mb_encode_mimeheader')) { - $sitename = mb_encode_mimeheader($site->name,"UTF-8", "B"); - } - - $header_eol = "\r\n"; - if ( - (isset($CONFIG->broken_mta)) && - ($CONFIG->broken_mta) - ) - $header_eol = "\n"; // Allow non-RFC 2822 mail headers to support some broken MTAs + * @link http://elgg.org/ + */ + + /** Notification handlers */ + $NOTIFICATION_HANDLERS = array(); + + /** + * This function registers a handler for a given notification type (eg "email") + * + * @param string $method The method + * @param string $handler The handler function, in the format "handler(ElggEntity $from, ElggUser $to, $subject, $message, array $params = NULL)". This function should return false on failure, and true/a tracking message ID on success. + * @param array $params A associated array of other parameters for this handler defining some properties eg. supported message length or rich text support. + */ + function register_notification_handler($method, $handler, $params = NULL) + { + global $NOTIFICATION_HANDLERS; + + if (is_callable($handler)) + { + $NOTIFICATION_HANDLERS[$method] = new stdClass; + + $NOTIFICATION_HANDLERS[$method]->handler = $handler; + if ($params) + { + foreach ($params as $k => $v) + $NOTIFICATION_HANDLERS[$method]->$k = $v; + } + + return true; + } + + return false; + } + + /** + * Notify a user via their preferences. + * + * @param mixed $to Either a guid or an array of guid's to notify. + * @param int $from GUID of the sender, which may be a user, site or object. + * @param string $subject Message subject. + * @param string $message Message body. + * @param array $params Misc additional parameters specific to various methods. + * @param mixed $methods_override A string, or an array of strings specifying the delivery methods to use - or leave blank + * for delivery using the user's chosen delivery methods. + * @return array Compound array of each delivery user/delivery method's success or failure. + * @throws NotificationException + */ + function notify_user($to, $from, $subject, $message, array $params = NULL, $methods_override = "") + { + global $NOTIFICATION_HANDLERS, $CONFIG; + + // Sanitise + if (!is_array($to)) + $to = array((int)$to); + $from = (int)$from; + //$subject = sanitise_string($subject); + + // Get notification methods + if (($methods_override) && (!is_array($methods_override))) + $methods_override = array($methods_override); + + $result = array(); + + foreach ($to as $guid) + { + // Results for a user are... + $result[$guid] = array(); + + if ($guid) { // Is the guid > 0? + // Are we overriding delivery? + $methods = $methods_override; + if (!$methods) + { + $tmp = (array)get_user_notification_settings($guid); + $methods = array(); + foreach($tmp as $k => $v) + if ($v) $methods[] = $k; // Add method if method is turned on for user! + } + + if ($methods) + { + // Deliver + foreach ($methods as $method) + { + // Extract method details from list + $details = $NOTIFICATION_HANDLERS[$method]; + $handler = $details->handler; + + if ((!$NOTIFICATION_HANDLERS[$method]) || (!$handler)) + error_log(sprintf(elgg_echo('NotificationException:NoHandlerFound'), $method)); + + if ($CONFIG->debug) + error_log("Sending message to $guid using $method"); + + // Trigger handler and retrieve result. + try { + $result[$guid][$method] = $handler( + $from ? get_entity($from) : NULL, // From entity + get_entity($guid), // To entity + $subject, // The subject + $message, // Message + $params // Params + ); + } catch (Exception $e) { + error_log($e->getMessage()); + } + + } + } + } + } + + return $result; + } + + /** + * Get the notification settings for a given user. + * + * @param int $user_guid The user id + * @return stdClass + */ + function get_user_notification_settings($user_guid = 0) + { + $user_guid = (int)$user_guid; + + if ($user_guid == 0) $user_guid = get_loggedin_userid(); + + $all_metadata = get_metadata_for_entity($user_guid); + if ($all_metadata) + { + $prefix = "notification:method:"; + $return = new stdClass; + + foreach ($all_metadata as $meta) + { + $name = substr($meta->name, strlen($prefix)); + $value = $meta->value; + + if (strpos($meta->name, $prefix) === 0) + $return->$name = $value; + } + + return $return; + } + + return false; + } + + /** + * Set a user notification pref. + * + * @param int $user_guid The user id. + * @param string $method The delivery method (eg. email) + * @param bool $value On(true) or off(false). + * @return bool + */ + function set_user_notification_setting($user_guid, $method, $value) + { + $user_guid = (int)$user_guid; + $method = sanitise_string($method); + + $user = get_entity($user_guid); + if (!$user) $user = get_loggedin_user(); + + if (($user) && ($user instanceof ElggUser)) + { + $prefix = "notification:method:$method"; + $user->$prefix = $value; + $user->save(); + + return true; + } + + return false; + } + + /** + * Notification exception. + * @author Curverider Ltd + */ + class NotificationException extends Exception {} + + + /** + * Send a notification via email. + * + * @param ElggEntity $from The from user/site/object + * @param ElggUser $to To which user? + * @param string $subject The subject of the message. + * @param string $message The message body + * @param array $params Optional parameters (none taken in this instance) + * @return bool + */ + function email_notify_handler(ElggEntity $from, ElggUser $to, $subject, $message, array $params = NULL) + { + global $CONFIG; + + if (!$from) + throw new NotificationException(sprintf(elgg_echo('NotificationException:MissingParameter'), 'from')); + + if (!$to) + throw new NotificationException(sprintf(elgg_echo('NotificationException:MissingParameter'), 'to')); + + if ($to->email=="") + throw new NotificationException(sprintf(elgg_echo('NotificationException:NoEmailAddress'), $to->guid)); + + // Sanitise subject + $subject = preg_replace("/(\r\n|\r|\n)/", " ", $subject); // Strip line endings + + // To + $to = $to->email; + + // From + $site = get_entity($CONFIG->site_guid); + if ((isset($from->email)) && (!($from instanceof ElggUser))) // If there's an email address, use it - but only if its not from a user. + $from = $from->email; + else if (($site) && (isset($site->email))) // Has the current site got a from email address? + $from = $site->email; + else if (isset($from->url)) // If we have a url then try and use that. + { + $breakdown = parse_url($from->url); + $from = 'noreply@' . $breakdown['host']; // Handle anything with a url + } + else // If all else fails, use the domain of the site. + $from = 'noreply@' . get_site_domain($CONFIG->site_guid); + + if (is_callable('mb_internal_encoding')) { + mb_internal_encoding('UTF-8'); + } + $site = get_entity($CONFIG->site_guid); + $sitename = $site->name; + if (is_callable('mb_encode_mimeheader')) { + $sitename = mb_encode_mimeheader($site->name,"UTF-8", "B"); + } + + $header_eol = "\r\n"; + if ( + (isset($CONFIG->broken_mta)) && + ($CONFIG->broken_mta) + ) + $header_eol = "\n"; // Allow non-RFC 2822 mail headers to support some broken MTAs $from_email = "\"$sitename\" <$from>"; if (strtolower(substr(PHP_OS, 0 , 3)) == 'win') $from_email = "$from"; // Windows is somewhat broken, so we use a different format from header - - $headers = "From: $from_email{$header_eol}" - . "Content-Type: text/plain; charset=UTF-8; format=flowed{$header_eol}" - . "MIME-Version: 1.0{$header_eol}" - . "Content-Transfer-Encoding: 8bit{$header_eol}"; - - if (is_callable('mb_encode_mimeheader')) { - $subject = mb_encode_mimeheader($subject,"UTF-8", "B"); - } - + + $headers = "From: $from_email{$header_eol}" + . "Content-Type: text/plain; charset=UTF-8; format=flowed{$header_eol}" + . "MIME-Version: 1.0{$header_eol}" + . "Content-Transfer-Encoding: 8bit{$header_eol}"; + + if (is_callable('mb_encode_mimeheader')) { + $subject = mb_encode_mimeheader($subject,"UTF-8", "B"); + } + // Format message - $message = html_entity_decode($message, ENT_COMPAT, 'UTF-8'); // Decode any html entities - $message = strip_tags($message); // Strip tags from message - $message = preg_replace("/(\r\n|\r)/", "\n", $message); // Convert to unix line endings in body - $message = preg_replace("/^From/", ">From", $message); // Change lines starting with From to >From - - return mail($to, $subject, wordwrap($message), $headers); - } - - /** - * Correctly initialise notifications and register the email handler. - * - */ - function notification_init() - { - // Register a notification handler for the default email method - register_notification_handler("email", "email_notify_handler"); - - // Add settings view to user settings & register action - extend_elgg_settings_page('notifications/settings/usersettings', 'usersettings/user'); - - register_plugin_hook('usersettings:save','user','notification_user_settings_save'); - - //register_action("notifications/settings/usersettings/save"); - - - // Register some APIs - expose_function('user.notification.get', 'get_user_notification_settings', array( - 'user_guid' => array ('type' => 'int') - ), elgg_echo('user.notification.get')); - - expose_function('user.notification.set', 'set_user_notification_settings', array( - 'user_guid' => array ('type' => 'int'), - 'method' => array ('type' => 'string'), - 'value' => array ('type' => 'bool') - ), elgg_echo('user.notification.set')); - - } - - function notification_user_settings_save() { - - global $CONFIG; - @include($CONFIG->path . "actions/notifications/settings/usersettings/save.php"); - - } - - /** - * Register an entity type and subtype to be eligible for notifications - * - * @param string $entity_type The type of entity - * @param string $object_subtype Its subtype - * @param string $english_name It's English notification string (eg "New blog post") - */ - function register_notification_object($entity_type, $object_subtype, $english_name) { - global $CONFIG; - - if ($entity_type == '') $entity_type = '__BLANK__'; - if ($object_subtype == '') $object_subtype = '__BLANK__'; - - if (!isset($CONFIG->register_objects)) { - $CONFIG->register_objects = array(); - } - if (!isset($CONFIG->register_objects[$entity_type])) { - $CONFIG->register_objects[$entity_type] = array(); - } - $CONFIG->register_objects[$entity_type][$object_subtype] = $english_name; - } - - /** - * Establish a 'notify' relationship between the user and a content author - * - * @param int $user_guid The GUID of the user who wants to follow a user's content - * @param int $author_guid The GUID of the user whose content the user wants to follow - * @return true|false Depending on success - */ - function register_notification_interest($user_guid, $author_guid) { - return add_entity_relationship($user_guid, 'notify', $author_guid); - } - - /** - * Remove a 'notify' relationship between the user and a content author - * - * @param int $user_guid The GUID of the user who is following a user's content - * @param int $author_guid The GUID of the user whose content the user wants to unfollow - * @return true|false Depending on success - */ - function remove_notification_interest($user_guid, $author_guid) { - return remove_entity_relationship($user_guid, 'notify', $author_guid); - } - - /** - * Automatically triggered notification on 'create' events that looks at registered - * objects and attempts to send notifications to anybody who's interested - * - * @see register_notification_object - */ - function object_notifications($event, $object_type, $object) { - - // We only want to trigger notification events for ElggEntities - if ($object instanceof ElggEntity) { - - // Get config data - global $CONFIG, $SESSION, $NOTIFICATION_HANDLERS; - - $hookresult = trigger_plugin_hook('object:notifications',$object_type,array( - 'event' => $event, - 'object_type' => $object_type, - 'object' => $object, - ),false); - if ($hookresult === true) return true; - - // Have we registered notifications for this type of entity? - $object_type = $object->getType(); if (empty($object_type)) $object_type = '__BLANK__'; - $object_subtype = $object->getSubtype(); if (empty($object_subtype)) $object_subtype = '__BLANK__'; - if (isset($CONFIG->register_objects[$object_type][$object_subtype])) { - - $descr = $CONFIG->register_objects[$object_type][$object_subtype]; - $string = $descr . ": " . $object->getURL(); - - // Get users interested in content from this person and notify them - // (Person defined by container_guid so we can also subscribe to groups if we want) - foreach($NOTIFICATION_HANDLERS as $method => $foo) - if ($interested_users = get_entities_from_relationship('notify' . $method,$object->container_guid,true,'user','',0,'',99999)) { - - if (is_array($interested_users)) - foreach($interested_users as $user) { - if ($user instanceof ElggUser) { - - if (!$user->isBanned()) - if (($user->guid != $SESSION['user']->guid) && has_access_to_entity($object,$user) - && $object->access_id != ACCESS_PRIVATE) { - - $methodstring = trigger_plugin_hook('notify:entity:message',$object->getType(),array( - 'entity' => $object, - 'to_entity' => $user, - 'method' => $method),$string); - if (empty($methodstring) && $methodstring !== false) $methodstring = $string; - if ($methodstring !== false) - notify_user($user->guid,$object->container_guid,$descr,$methodstring,NULL,array($method)); - } - } - } - } - - } - - } - - } - - // Register a startup event - register_elgg_event_handler('init','system','notification_init',0); - register_elgg_event_handler('create','object','object_notifications'); - -?> + $message = html_entity_decode($message, ENT_COMPAT, 'UTF-8'); // Decode any html entities + $message = strip_tags($message); // Strip tags from message + $message = preg_replace("/(\r\n|\r)/", "\n", $message); // Convert to unix line endings in body + $message = preg_replace("/^From/", ">From", $message); // Change lines starting with From to >From + + return mail($to, $subject, wordwrap($message), $headers); + } + + /** + * Correctly initialise notifications and register the email handler. + * + */ + function notification_init() + { + // Register a notification handler for the default email method + register_notification_handler("email", "email_notify_handler"); + + // Add settings view to user settings & register action + extend_elgg_settings_page('notifications/settings/usersettings', 'usersettings/user'); + + register_plugin_hook('usersettings:save','user','notification_user_settings_save'); + + //register_action("notifications/settings/usersettings/save"); + + + // Register some APIs + expose_function('user.notification.get', 'get_user_notification_settings', array( + 'user_guid' => array ('type' => 'int') + ), elgg_echo('user.notification.get')); + + expose_function('user.notification.set', 'set_user_notification_settings', array( + 'user_guid' => array ('type' => 'int'), + 'method' => array ('type' => 'string'), + 'value' => array ('type' => 'bool') + ), elgg_echo('user.notification.set')); + + } + + function notification_user_settings_save() { + + global $CONFIG; + @include($CONFIG->path . "actions/notifications/settings/usersettings/save.php"); + + } + + /** + * Register an entity type and subtype to be eligible for notifications + * + * @param string $entity_type The type of entity + * @param string $object_subtype Its subtype + * @param string $english_name It's English notification string (eg "New blog post") + */ + function register_notification_object($entity_type, $object_subtype, $english_name) { + global $CONFIG; + + if ($entity_type == '') $entity_type = '__BLANK__'; + if ($object_subtype == '') $object_subtype = '__BLANK__'; + + if (!isset($CONFIG->register_objects)) { + $CONFIG->register_objects = array(); + } + if (!isset($CONFIG->register_objects[$entity_type])) { + $CONFIG->register_objects[$entity_type] = array(); + } + $CONFIG->register_objects[$entity_type][$object_subtype] = $english_name; + } + + /** + * Establish a 'notify' relationship between the user and a content author + * + * @param int $user_guid The GUID of the user who wants to follow a user's content + * @param int $author_guid The GUID of the user whose content the user wants to follow + * @return true|false Depending on success + */ + function register_notification_interest($user_guid, $author_guid) { + return add_entity_relationship($user_guid, 'notify', $author_guid); + } + + /** + * Remove a 'notify' relationship between the user and a content author + * + * @param int $user_guid The GUID of the user who is following a user's content + * @param int $author_guid The GUID of the user whose content the user wants to unfollow + * @return true|false Depending on success + */ + function remove_notification_interest($user_guid, $author_guid) { + return remove_entity_relationship($user_guid, 'notify', $author_guid); + } + + /** + * Automatically triggered notification on 'create' events that looks at registered + * objects and attempts to send notifications to anybody who's interested + * + * @see register_notification_object + */ + function object_notifications($event, $object_type, $object) { + + // We only want to trigger notification events for ElggEntities + if ($object instanceof ElggEntity) { + + // Get config data + global $CONFIG, $SESSION, $NOTIFICATION_HANDLERS; + + $hookresult = trigger_plugin_hook('object:notifications',$object_type,array( + 'event' => $event, + 'object_type' => $object_type, + 'object' => $object, + ),false); + if ($hookresult === true) return true; + + // Have we registered notifications for this type of entity? + $object_type = $object->getType(); if (empty($object_type)) $object_type = '__BLANK__'; + $object_subtype = $object->getSubtype(); if (empty($object_subtype)) $object_subtype = '__BLANK__'; + if (isset($CONFIG->register_objects[$object_type][$object_subtype])) { + + $descr = $CONFIG->register_objects[$object_type][$object_subtype]; + $string = $descr . ": " . $object->getURL(); + + // Get users interested in content from this person and notify them + // (Person defined by container_guid so we can also subscribe to groups if we want) + foreach($NOTIFICATION_HANDLERS as $method => $foo) + if ($interested_users = get_entities_from_relationship('notify' . $method,$object->container_guid,true,'user','',0,'',99999)) { + + if (is_array($interested_users)) + foreach($interested_users as $user) { + if ($user instanceof ElggUser) { + + if (!$user->isBanned()) + if (($user->guid != $SESSION['user']->guid) && has_access_to_entity($object,$user) + && $object->access_id != ACCESS_PRIVATE) { + + $methodstring = trigger_plugin_hook('notify:entity:message',$object->getType(),array( + 'entity' => $object, + 'to_entity' => $user, + 'method' => $method),$string); + if (empty($methodstring) && $methodstring !== false) $methodstring = $string; + if ($methodstring !== false) + notify_user($user->guid,$object->container_guid,$descr,$methodstring,NULL,array($method)); + } + } + } + } + + } + + } + + } + + // Register a startup event + register_elgg_event_handler('init','system','notification_init',0); + register_elgg_event_handler('create','object','object_notifications'); + +?> diff --git a/engine/lib/objects.php b/engine/lib/objects.php index 4090c1c24..7e7e956a4 100644 --- a/engine/lib/objects.php +++ b/engine/lib/objects.php @@ -1,147 +1,147 @@ -attributes['type'] = "object"; - $this->attributes['title'] = ""; + * @subpackage Core + */ + class ElggObject extends ElggEntity + { + /** + * Initialise the attributes array. + * This is vital to distinguish between metadata and base parameters. + * + * Place your base parameters here. + */ + protected function initialise_attributes() + { + parent::initialise_attributes(); + + $this->attributes['type'] = "object"; + $this->attributes['title'] = ""; $this->attributes['description'] = ""; - $this->attributes['tables_split'] = 2; - } - - /** - * Construct a new object entity, optionally from a given id value. - * - * @param mixed $guid If an int, load that GUID. - * If a db row then will attempt to load the rest of the data. - * @throws Exception if there was a problem creating the object. - */ - function __construct($guid = null) - { + $this->attributes['tables_split'] = 2; + } + + /** + * Construct a new object entity, optionally from a given id value. + * + * @param mixed $guid If an int, load that GUID. + * If a db row then will attempt to load the rest of the data. + * @throws Exception if there was a problem creating the object. + */ + function __construct($guid = null) + { $this->initialise_attributes(); - - if (!empty($guid)) - { - // Is $guid is a DB row - either a entity row, or a object table row. - if ($guid instanceof stdClass) { - // Load the rest + + if (!empty($guid)) + { + // Is $guid is a DB row - either a entity row, or a object table row. + if ($guid instanceof stdClass) { + // Load the rest if (!$this->load($guid->guid)) - throw new IOException(sprintf(elgg_echo('IOException:FailedToLoadGUID'), get_class(), $guid->guid)); - } - - // Is $guid is an ElggObject? Use a copy constructor - else if ($guid instanceof ElggObject) - { - foreach ($guid->attributes as $key => $value) - $this->attributes[$key] = $value; - } - - // Is this is an ElggEntity but not an ElggObject = ERROR! - else if ($guid instanceof ElggEntity) - throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonElggObject')); - - // We assume if we have got this far, $guid is an int - else if (is_numeric($guid)) { - if (!$this->load($guid)) IOException(sprintf(elgg_echo('IOException:FailedToLoadGUID'), get_class(), $guid)); + throw new IOException(sprintf(elgg_echo('IOException:FailedToLoadGUID'), get_class(), $guid->guid)); + } + + // Is $guid is an ElggObject? Use a copy constructor + else if ($guid instanceof ElggObject) + { + foreach ($guid->attributes as $key => $value) + $this->attributes[$key] = $value; + } + + // Is this is an ElggEntity but not an ElggObject = ERROR! + else if ($guid instanceof ElggEntity) + throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonElggObject')); + + // We assume if we have got this far, $guid is an int + else if (is_numeric($guid)) { + if (!$this->load($guid)) IOException(sprintf(elgg_echo('IOException:FailedToLoadGUID'), get_class(), $guid)); } else - throw new InvalidParameterException(elgg_echo('InvalidParameterException:UnrecognisedValue')); - } - } - - /** - * Override the load function. - * This function will ensure that all data is loaded (were possible), so - * if only part of the ElggObject is loaded, it'll load the rest. - * - * @param int $guid - * @return true|false - */ - protected function load($guid) - { - // Test to see if we have the generic stuff - if (!parent::load($guid)) - return false; - - // Check the type - if ($this->attributes['type']!='object') - throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $guid, get_class())); - - // Load missing data + throw new InvalidParameterException(elgg_echo('InvalidParameterException:UnrecognisedValue')); + } + } + + /** + * Override the load function. + * This function will ensure that all data is loaded (were possible), so + * if only part of the ElggObject is loaded, it'll load the rest. + * + * @param int $guid + * @return true|false + */ + protected function load($guid) + { + // Test to see if we have the generic stuff + if (!parent::load($guid)) + return false; + + // Check the type + if ($this->attributes['type']!='object') + throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $guid, get_class())); + + // Load missing data $row = get_object_entity_as_row($guid); - if (($row) && (!$this->isFullyLoaded())) $this->attributes['tables_loaded'] ++; // If $row isn't a cached copy then increment the counter - - // Now put these into the attributes array as core values - $objarray = (array) $row; - foreach($objarray as $key => $value) - $this->attributes[$key] = $value; - - return true; - } - - /** - * Override the save function. - * @return true|false - */ - public function save() - { - // Save generic stuff - if (!parent::save()) - return false; - - // Now save specific stuff + if (($row) && (!$this->isFullyLoaded())) $this->attributes['tables_loaded'] ++; // If $row isn't a cached copy then increment the counter + + // Now put these into the attributes array as core values + $objarray = (array) $row; + foreach($objarray as $key => $value) + $this->attributes[$key] = $value; + + return true; + } + + /** + * Override the save function. + * @return true|false + */ + public function save() + { + // Save generic stuff + if (!parent::save()) + return false; + + // Now save specific stuff return create_object_entity($this->get('guid'), $this->get('title'), $this->get('description'), $this->get('container_guid')); } - - /** - * Get sites that this object is a member of - * - * @param string $subtype Optionally, the subtype of result we want to limit to - * @param int $limit The number of results to return - * @param int $offset Any indexing offset - */ - function getSites($subtype="", $limit = 10, $offset = 0) { - return get_site_objects($this->getGUID(), $subtype, $limit, $offset); - } - - /** - * Add this object to a particular site - * - * @param int $site_guid The guid of the site to add it to - * @return true|false - */ - function addToSite($site_guid) { - return add_site_object($this->getGUID(), $site_guid); - } + + /** + * Get sites that this object is a member of + * + * @param string $subtype Optionally, the subtype of result we want to limit to + * @param int $limit The number of results to return + * @param int $offset Any indexing offset + */ + function getSites($subtype="", $limit = 10, $offset = 0) { + return get_site_objects($this->getGUID(), $subtype, $limit, $offset); + } + + /** + * Add this object to a particular site + * + * @param int $site_guid The guid of the site to add it to + * @return true|false + */ + function addToSite($site_guid) { + return add_site_object($this->getGUID(), $site_guid); + } /** * Set the container for this object. @@ -180,16 +180,16 @@ return false; } - - /** - * Get the collections associated with a object. - * - * @param string $subtype Optionally, the subtype of result we want to limit to - * @param int $limit The number of results to return - * @param int $offset Any indexing offset - * @return unknown - */ - //public function getCollections($subtype="", $limit = 10, $offset = 0) { get_object_collections($this->getGUID(), $subtype, $limit, $offset); } + + /** + * Get the collections associated with a object. + * + * @param string $subtype Optionally, the subtype of result we want to limit to + * @param int $limit The number of results to return + * @param int $offset Any indexing offset + * @return unknown + */ + //public function getCollections($subtype="", $limit = 10, $offset = 0) { get_object_collections($this->getGUID(), $subtype, $limit, $offset); } // EXPORTABLE INTERFACE //////////////////////////////////////////////////////////// @@ -202,18 +202,18 @@ 'title', 'description', )); - } - } - - /** - * Return the object specific details of a object by a row. - * - * @param int $guid - */ - function get_object_entity_as_row($guid) - { - global $CONFIG; - + } + } + + /** + * Return the object specific details of a object by a row. + * + * @param int $guid + */ + function get_object_entity_as_row($guid) + { + global $CONFIG; + $guid = (int)$guid; /*$row = retrieve_cached_entity_row($guid); @@ -229,31 +229,31 @@ {*/ // Object not cached, load it. if ($CONFIG->debug) - error_log("** Sub part of GUID:$guid loaded from DB"); - + error_log("** Sub part of GUID:$guid loaded from DB"); + return get_data_row("SELECT * from {$CONFIG->dbprefix}objects_entity where guid=$guid"); - //} - } - - /** - * Create or update the extras table for a given object. - * Call create_entity first. - * - * @param int $guid The guid of the entity you're creating (as obtained by create_entity) - * @param string $title The title of the object - * @param string $description The object's description - */ - function create_object_entity($guid, $title, $description) - { - global $CONFIG; - - $guid = (int)$guid; - $title = sanitise_string($title); + //} + } + + /** + * Create or update the extras table for a given object. + * Call create_entity first. + * + * @param int $guid The guid of the entity you're creating (as obtained by create_entity) + * @param string $title The title of the object + * @param string $description The object's description + */ + function create_object_entity($guid, $title, $description) + { + global $CONFIG; + + $guid = (int)$guid; + $title = sanitise_string($title); $description = sanitise_string($description); - - $row = get_entity_as_row($guid); - - if ($row) + + $row = get_entity_as_row($guid); + + if ($row) { // Core entities row exists and we have access to it if ($exists = get_data_row("SELECT guid from {$CONFIG->dbprefix}objects_entity where guid = {$guid}")) { @@ -267,7 +267,7 @@ } else { $entity->delete(); } - } + } } else { @@ -283,25 +283,25 @@ //delete_entity($guid); } } - } - - } - - return false; - } - + } + + } + + return false; + } + /** * THIS FUNCTION IS DEPRECATED. - * - * Delete a object's extra data. - * - * @param int $guid - */ - function delete_object_entity($guid) + * + * Delete a object's extra data. + * + * @param int $guid + */ + function delete_object_entity($guid) { system_message(sprintf(elgg_echo('deprecatedfunction'), 'delete_user_entity')); - return 1; // Always return that we have deleted one row in order to not break existing code. + return 1; // Always return that we have deleted one row in order to not break existing code. } /** @@ -347,22 +347,22 @@ } } return false; - } - - /** - * Get the sites this object is part of - * - * @param int $object_guid The object's GUID - * @param int $limit Number of results to return - * @param int $offset Any indexing offset - * @return false|array On success, an array of ElggSites - */ - function get_object_sites($object_guid, $limit = 10, $offset = 0) { - $object_guid = (int)$object_guid; - $limit = (int)$limit; - $offset = (int)$offset; - - return get_entities_from_relationship("member_of_site", $object_guid, false, "site", "", 0, "time_created desc", $limit, $offset); - } - + } + + /** + * Get the sites this object is part of + * + * @param int $object_guid The object's GUID + * @param int $limit Number of results to return + * @param int $offset Any indexing offset + * @return false|array On success, an array of ElggSites + */ + function get_object_sites($object_guid, $limit = 10, $offset = 0) { + $object_guid = (int)$object_guid; + $limit = (int)$limit; + $offset = (int)$offset; + + return get_entities_from_relationship("member_of_site", $object_guid, false, "site", "", 0, "time_created desc", $limit, $offset); + } + ?> \ No newline at end of file diff --git a/engine/lib/pagehandler.php b/engine/lib/pagehandler.php index 3669635e2..e602590b3 100644 --- a/engine/lib/pagehandler.php +++ b/engine/lib/pagehandler.php @@ -1,120 +1,120 @@ - $val) { - set_input($name, $val); - } - } - } - $page = explode('/',$page); - - if (!isset($CONFIG->pagehandler) || empty($handler)) { - $result = false; - } else if (isset($CONFIG->pagehandler[$handler]) && is_callable($CONFIG->pagehandler[$handler])) { - $function = $CONFIG->pagehandler[$handler]; - $result = $function($page, $handler); - if ($result !== false) { - $result = true; - } - } else { - $result = false; - } - - if (!$result) { - $result = default_page_handler($page, $handler); - } - if ($result !== false) $result = true; - - return $result; - - } - - /** - * Registers a page handler for a particular identifier - * - * eg, you can register a function called 'blog_page_handler' for handler type 'blog' - * - * Now for all URLs of type http://yoururl/blog/*, the blog_page_handler function will be called. - * The part of the URL marked with * above will be exploded on '/' characters and passed as an - * array to that function, eg: - * - * For the URL http://yoururl/blog/username/friends/: - * blog_page_handler('blog', array('username','friends')); - * - * @param string $handler The page type to handle - * @param string $function Your function name - * @return true|false Depending on success - */ - function register_page_handler($handler, $function) { - - global $CONFIG; - if (!isset($CONFIG->pagehandler)) - $CONFIG->pagehandler = array(); - if (is_callable($function)) { - $CONFIG->pagehandler[$handler] = $function; - return true; - } - return false; - - } - - /** - * A default page handler that attempts to load the actual file at a given page handler location - * - * @param array $page The page URL elements - * @param string $handler The base handler - * @return true|false Depending on success - */ - function default_page_handler($page, $handler) { - + * @author Curverider Ltd + + * @link http://elgg.org/ + */ + + /** + * Turns the current page over to the page handler, allowing registered handlers to take over + * + * @param string $handler The name of the handler type (eg 'blog') + * @param array $page The parameters to the page, as an array (exploded by '/' slashes) + * @return true|false Depending on whether a registered page handler was found + */ + function page_handler($handler, $page) { + + global $CONFIG; + + set_context($handler); + + $query = substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?')+1);//parse_url($_SERVER['REQUEST_URI']); + if (isset($query)) { + parse_str($query, $query_arr); + if (is_array($query_arr)) { + foreach($query_arr as $name => $val) { + set_input($name, $val); + } + } + } + $page = explode('/',$page); + + if (!isset($CONFIG->pagehandler) || empty($handler)) { + $result = false; + } else if (isset($CONFIG->pagehandler[$handler]) && is_callable($CONFIG->pagehandler[$handler])) { + $function = $CONFIG->pagehandler[$handler]; + $result = $function($page, $handler); + if ($result !== false) { + $result = true; + } + } else { + $result = false; + } + + if (!$result) { + $result = default_page_handler($page, $handler); + } + if ($result !== false) $result = true; + + return $result; + + } + + /** + * Registers a page handler for a particular identifier + * + * eg, you can register a function called 'blog_page_handler' for handler type 'blog' + * + * Now for all URLs of type http://yoururl/blog/*, the blog_page_handler function will be called. + * The part of the URL marked with * above will be exploded on '/' characters and passed as an + * array to that function, eg: + * + * For the URL http://yoururl/blog/username/friends/: + * blog_page_handler('blog', array('username','friends')); + * + * @param string $handler The page type to handle + * @param string $function Your function name + * @return true|false Depending on success + */ + function register_page_handler($handler, $function) { + + global $CONFIG; + if (!isset($CONFIG->pagehandler)) + $CONFIG->pagehandler = array(); + if (is_callable($function)) { + $CONFIG->pagehandler[$handler] = $function; + return true; + } + return false; + + } + + /** + * A default page handler that attempts to load the actual file at a given page handler location + * + * @param array $page The page URL elements + * @param string $handler The base handler + * @return true|false Depending on success + */ + function default_page_handler($page, $handler) { + global $CONFIG; $script = ""; - - $page = implode('/',$page); - if (($questionmark = strripos($page, '?'))) - $page = substr($page, 0, $questionmark); - - $script = str_replace("..","",$script); - $callpath = $CONFIG->path . $handler . "/" . $page; - if (!file_exists($callpath) || is_dir($callpath) || substr_count($callpath,'.php') == 0) { - if (substr($callpath,strlen($callpath) - 1, 1) != "/") - $callpath .= "/"; - $callpath .= "index.php"; - if (!include($callpath)) - return false; - } else { - include($callpath); - } - - return true; - - } - + + $page = implode('/',$page); + if (($questionmark = strripos($page, '?'))) + $page = substr($page, 0, $questionmark); + + $script = str_replace("..","",$script); + $callpath = $CONFIG->path . $handler . "/" . $page; + if (!file_exists($callpath) || is_dir($callpath) || substr_count($callpath,'.php') == 0) { + if (substr($callpath,strlen($callpath) - 1, 1) != "/") + $callpath .= "/"; + $callpath .= "index.php"; + if (!include($callpath)) + return false; + } else { + include($callpath); + } + + return true; + + } + ?> \ No newline at end of file diff --git a/engine/lib/pageowner.php b/engine/lib/pageowner.php index 3737f42f4..cc3e2e8a3 100644 --- a/engine/lib/pageowner.php +++ b/engine/lib/pageowner.php @@ -1,61 +1,61 @@ -getGUID(); - } - } - if ((!isset($returnval)) && ($user = get_user_by_username($username))) { - $returnval = $user->getGUID(); - } + $returnval = $entity->getGUID(); + } + } + if ((!isset($returnval)) && ($user = get_user_by_username($username))) { + $returnval = $user->getGUID(); + } } - - if ((!isset($returnval)) && ($owner = get_input("owner_guid"))) { - if ($user = get_entity($owner)) { - $returnval = $user->getGUID(); - } + + if ((!isset($returnval)) && ($owner = get_input("owner_guid"))) { + if ($user = get_entity($owner)) { + $returnval = $user->getGUID(); + } } - - if ((!isset($returnval)) && (!empty($CONFIG->page_owner_handlers) && is_array($CONFIG->page_owner_handlers))) { - foreach($CONFIG->page_owner_handlers as $handler) { - if ((!isset($returnval)) && ($guid = $handler())) { - $returnval = $guid; - } - } + + if ((!isset($returnval)) && (!empty($CONFIG->page_owner_handlers) && is_array($CONFIG->page_owner_handlers))) { + foreach($CONFIG->page_owner_handlers as $handler) { + if ((!isset($returnval)) && ($guid = $handler())) { + $returnval = $guid; + } + } } if (isset($returnval)) { @@ -78,109 +78,109 @@ return $returnval; } - - return 0; - - } - - /** - * Gets the page owner for the current page. - * @uses $CONFIG - * @return ElggUser|false The current page owner (false if none). - */ - function page_owner_entity() { - - global $CONFIG; - $page_owner = page_owner(); - if ($page_owner > 0) - return get_entity($page_owner); - - return false; - //return new ElggDummy(); - } - - /** - * Adds a page owner handler - a function that will - * return the page owner if required - * (Such functions are required to return false if they don't know) - * @uses $CONFIG + + return 0; + + } + + /** + * Gets the page owner for the current page. + * @uses $CONFIG + * @return ElggUser|false The current page owner (false if none). + */ + function page_owner_entity() { + + global $CONFIG; + $page_owner = page_owner(); + if ($page_owner > 0) + return get_entity($page_owner); + + return false; + //return new ElggDummy(); + } + + /** + * Adds a page owner handler - a function that will + * return the page owner if required + * (Such functions are required to return false if they don't know) + * @uses $CONFIG * @param string $functionname The name of the function to call - * @return mixed The guid of the owner or false - */ - - function add_page_owner_handler($functionname) { - - global $CONFIG; - if (empty($CONFIG->page_owner_handlers)) { - $CONFIG->page_owner_handlers = array(); - } - if (is_callable($functionname)) { - $CONFIG->page_owner_handlers[] = $functionname; - } - - } - - /** - * Allows a page to manually set a page owner - * - * @param int $entitytoset The GUID of the page owner - * @return int|false Either the page owner we've just set, or false if unset - */ - function set_page_owner($entitytoset = -1) { - - static $entity; - - if (!isset($entity)) $entity = false; - - if ($entitytoset > -1) { - $entity = $entitytoset; - } - - return $entity; - - } - - /** - * Sets the functional context of a page - * - * @param string $context The context of the page - * @return string|false Either the context string, or false on failure - */ - function set_context($context) { - - global $CONFIG; - if (!empty($context)) { - $context = trim($context); - $context = strtolower($context); - $CONFIG->context = $context; - return $context; - } else { - return false; - } - - } - - /** - * Returns the functional context of a page - * - * @return string The context, or 'main' if no context has been provided - */ - function get_context() { - - global $CONFIG; - if (isset($CONFIG->context) && !empty($CONFIG->context)) { - return $CONFIG->context; - } - if ($context = get_plugin_name(true)) { - return $context; - } - return "main"; - - } - - if (defined('context')) { - global $CONFIG; - $CONFIG->context = context; - } - + * @return mixed The guid of the owner or false + */ + + function add_page_owner_handler($functionname) { + + global $CONFIG; + if (empty($CONFIG->page_owner_handlers)) { + $CONFIG->page_owner_handlers = array(); + } + if (is_callable($functionname)) { + $CONFIG->page_owner_handlers[] = $functionname; + } + + } + + /** + * Allows a page to manually set a page owner + * + * @param int $entitytoset The GUID of the page owner + * @return int|false Either the page owner we've just set, or false if unset + */ + function set_page_owner($entitytoset = -1) { + + static $entity; + + if (!isset($entity)) $entity = false; + + if ($entitytoset > -1) { + $entity = $entitytoset; + } + + return $entity; + + } + + /** + * Sets the functional context of a page + * + * @param string $context The context of the page + * @return string|false Either the context string, or false on failure + */ + function set_context($context) { + + global $CONFIG; + if (!empty($context)) { + $context = trim($context); + $context = strtolower($context); + $CONFIG->context = $context; + return $context; + } else { + return false; + } + + } + + /** + * Returns the functional context of a page + * + * @return string The context, or 'main' if no context has been provided + */ + function get_context() { + + global $CONFIG; + if (isset($CONFIG->context) && !empty($CONFIG->context)) { + return $CONFIG->context; + } + if ($context = get_plugin_name(true)) { + return $context; + } + return "main"; + + } + + if (defined('context')) { + global $CONFIG; + $CONFIG->context = context; + } + ?> \ No newline at end of file diff --git a/engine/lib/pam.php b/engine/lib/pam.php index 255a10089..efebb45ec 100644 --- a/engine/lib/pam.php +++ b/engine/lib/pam.php @@ -1,16 +1,16 @@ - \ No newline at end of file diff --git a/engine/lib/plugins.php b/engine/lib/plugins.php index 4f8cd8bbe..1fcd2d138 100644 --- a/engine/lib/plugins.php +++ b/engine/lib/plugins.php @@ -1,739 +1,739 @@ -attributes['subtype'] = "plugin"; + } + + public function __construct($guid = null) + { + parent::__construct($guid); + } + + /** + * Override entity get and sets in order to save data to private data store. + */ + public function get($name) + { + // See if its in our base attribute + if (isset($this->attributes[$name])) { + return $this->attributes[$name]; + } + + // No, so see if its in the private data store. + $meta = get_private_setting($this->guid, $name); + if ($meta) + return $meta; + + // Can't find it, so return null + return null; + } + + /** + * Override entity get and sets in order to save data to private data store. + */ + public function set($name, $value) + { + if (array_key_exists($name, $this->attributes)) + { + // Check that we're not trying to change the guid! + if ((array_key_exists('guid', $this->attributes)) && ($name=='guid')) + return false; + + $this->attributes[$name] = $value; + } + else + return set_private_setting($this->guid, $name, $value); + + return true; + } + } + + /** + * Returns a list of plugins to load, in the order that they should be loaded. + * + * @return array List of plugins + */ + function get_plugin_list() { - * @link http://elgg.org/ - */ - - - /// Cache enabled plugins per page - $ENABLED_PLUGINS_CACHE = NULL; - - /** - * PluginException - * - * A plugin Exception, thrown when an Exception occurs relating to the plugin mechanism. Subclass for specific plugin Exceptions. - * - * @package Elgg - * @subpackage Exceptions - */ - class PluginException extends Exception {} - - /** - * @class ElggPlugin Object representing a plugin's settings for a given site. - * This class is currently a stub, allowing a plugin to saving settings in an object's metadata for each site. - * @author Curverider Ltd - */ - class ElggPlugin extends ElggObject - { - protected function initialise_attributes() - { - parent::initialise_attributes(); - - $this->attributes['subtype'] = "plugin"; - } - - public function __construct($guid = null) - { - parent::__construct($guid); - } - - /** - * Override entity get and sets in order to save data to private data store. - */ - public function get($name) - { - // See if its in our base attribute - if (isset($this->attributes[$name])) { - return $this->attributes[$name]; - } - - // No, so see if its in the private data store. - $meta = get_private_setting($this->guid, $name); - if ($meta) - return $meta; - - // Can't find it, so return null - return null; - } - - /** - * Override entity get and sets in order to save data to private data store. - */ - public function set($name, $value) - { - if (array_key_exists($name, $this->attributes)) - { - // Check that we're not trying to change the guid! - if ((array_key_exists('guid', $this->attributes)) && ($name=='guid')) - return false; - - $this->attributes[$name] = $value; - } - else - return set_private_setting($this->guid, $name, $value); - - return true; - } - } - - /** - * Returns a list of plugins to load, in the order that they should be loaded. - * - * @return array List of plugins - */ - function get_plugin_list() { - - global $CONFIG; - - if (!empty($CONFIG->pluginlistcache)) - return $CONFIG->pluginlistcache; - - if ($site = get_entity($CONFIG->site_guid)) { - - $pluginorder = $site->pluginorder; - if (!empty($pluginorder)) { - - $plugins = unserialize($pluginorder); - - $CONFIG->pluginlistcache = $plugins; - return $plugins; - - } else { - - $plugins = array(); - - if ($handle = opendir($CONFIG->pluginspath)) { - while ($mod = readdir($handle)) { - if (!in_array($mod,array('.','..','.svn','CVS')) && is_dir($CONFIG->pluginspath . "/" . $mod)) { - $plugins[] = $mod; - } - } - } - - sort($plugins); - - $CONFIG->pluginlistcache = $plugins; - return $plugins; - - } - - } - - return false; - - } - - /** + global $CONFIG; + + if (!empty($CONFIG->pluginlistcache)) + return $CONFIG->pluginlistcache; + + if ($site = get_entity($CONFIG->site_guid)) { + + $pluginorder = $site->pluginorder; + if (!empty($pluginorder)) { + + $plugins = unserialize($pluginorder); + + $CONFIG->pluginlistcache = $plugins; + return $plugins; + + } else { + + $plugins = array(); + + if ($handle = opendir($CONFIG->pluginspath)) { + while ($mod = readdir($handle)) { + if (!in_array($mod,array('.','..','.svn','CVS')) && is_dir($CONFIG->pluginspath . "/" . $mod)) { + $plugins[] = $mod; + } + } + } + + sort($plugins); + + $CONFIG->pluginlistcache = $plugins; + return $plugins; + + } + + } + + return false; + + } + + /** * Regenerates the list of known plugins and saves it to the current site * * Important: You should regenerate simplecache and the viewpath cache after executing this function * otherwise you may experience view display artifacts. Do this with the following code: * * elgg_view_regenerate_simplecache(); - * elgg_filepath_cache_reset(); - * - * @param array $pluginorder Optionally, a list of existing plugins and their orders - * @return array The new list of plugins and their orders - */ - function regenerate_plugin_list($pluginorder = false) { - - global $CONFIG; - - $CONFIG->pluginlistcache = null; - - if ($site = get_entity($CONFIG->site_guid)) { - - if (empty($pluginorder)) { - $pluginorder = $site->pluginorder; - $pluginorder = unserialize($pluginorder); - } else { - ksort($pluginorder); - } - - if (empty($pluginorder)) { - $pluginorder = array(); - } - - $max = 0; - if (sizeof($pluginorder)) - foreach($pluginorder as $key => $plugin) { - if (is_dir($CONFIG->pluginspath . "/" . $plugin)) { - if ($key > $max) - $max = $key; - } else { - unset($pluginorder[$key]); - } - } - - // Add new plugins to the end - if ($handle = opendir($CONFIG->pluginspath)) { - while ($mod = readdir($handle)) { - if (!in_array($mod,array('.','..','.svn','CVS')) && is_dir($CONFIG->pluginspath . "/" . $mod)) { - if (!in_array($mod, $pluginorder)) { - $max = $max + 10; - $pluginorder[$max] = $mod; - } - } - } - } - - ksort($pluginorder); - - // Now reorder the keys .. - $key = 10; - $plugins = array(); - if (sizeof($pluginorder)) - foreach($pluginorder as $plugin) { - $plugins[$key] = $plugin; - $key = $key + 10; - } - - $plugins = serialize($plugins); - + * elgg_filepath_cache_reset(); + * + * @param array $pluginorder Optionally, a list of existing plugins and their orders + * @return array The new list of plugins and their orders + */ + function regenerate_plugin_list($pluginorder = false) { + + global $CONFIG; + + $CONFIG->pluginlistcache = null; + + if ($site = get_entity($CONFIG->site_guid)) { + + if (empty($pluginorder)) { + $pluginorder = $site->pluginorder; + $pluginorder = unserialize($pluginorder); + } else { + ksort($pluginorder); + } + + if (empty($pluginorder)) { + $pluginorder = array(); + } + + $max = 0; + if (sizeof($pluginorder)) + foreach($pluginorder as $key => $plugin) { + if (is_dir($CONFIG->pluginspath . "/" . $plugin)) { + if ($key > $max) + $max = $key; + } else { + unset($pluginorder[$key]); + } + } + + // Add new plugins to the end + if ($handle = opendir($CONFIG->pluginspath)) { + while ($mod = readdir($handle)) { + if (!in_array($mod,array('.','..','.svn','CVS')) && is_dir($CONFIG->pluginspath . "/" . $mod)) { + if (!in_array($mod, $pluginorder)) { + $max = $max + 10; + $pluginorder[$max] = $mod; + } + } + } + } + + ksort($pluginorder); + + // Now reorder the keys .. + $key = 10; + $plugins = array(); + if (sizeof($pluginorder)) + foreach($pluginorder as $plugin) { + $plugins[$key] = $plugin; + $key = $key + 10; + } + + $plugins = serialize($plugins); + $site->pluginorder = $plugins; // Regenerate caches elgg_view_regenerate_simplecache(); - elgg_filepath_cache_reset(); - - return $plugins; - - } - - return false; - - } - - - /** - * For now, loads plugins directly - * - * @todo Add proper plugin handler that launches plugins in an admin-defined order and activates them on admin request - * @package Elgg - * @subpackage Core - */ + elgg_filepath_cache_reset(); + + return $plugins; + + } + + return false; + + } + + + /** + * For now, loads plugins directly + * + * @todo Add proper plugin handler that launches plugins in an admin-defined order and activates them on admin request + * @package Elgg + * @subpackage Core + */ function load_plugins() { - + global $CONFIG; - + if (!empty($CONFIG->pluginspath)) { // See if we have cached values for things $cached_view_paths = elgg_filepath_cache_load(); if ($cached_view_paths) $CONFIG->views = unserialize($cached_view_paths); - - // temporary disable all plugins if there is a file called 'disabled' in the plugin dir - if (file_exists($CONFIG->pluginspath . "disabled")) - return; - - $plugins = get_plugin_list(); - + + // temporary disable all plugins if there is a file called 'disabled' in the plugin dir + if (file_exists($CONFIG->pluginspath . "disabled")) + return; + + $plugins = get_plugin_list(); + if (sizeof($plugins)) - { - foreach($plugins as $mod) { - if (is_plugin_enabled($mod)) { - if (file_exists($CONFIG->pluginspath . $mod)) { - if (!include($CONFIG->pluginspath . $mod . "/start.php")) + { + foreach($plugins as $mod) { + if (is_plugin_enabled($mod)) { + if (file_exists($CONFIG->pluginspath . $mod)) { + if (!include($CONFIG->pluginspath . $mod . "/start.php")) throw new PluginException(sprintf(elgg_echo('PluginException:MisconfiguredPlugin'), $mod)); if (!$cached_view_paths) - { - if (is_dir($CONFIG->pluginspath . $mod . "/views")) { - if ($handle = opendir($CONFIG->pluginspath . $mod . "/views")) { - while ($viewtype = readdir($handle)) { - if (!in_array($viewtype,array('.','..','.svn','CVS')) && is_dir($CONFIG->pluginspath . $mod . "/views/" . $viewtype)) { - autoregister_views("",$CONFIG->pluginspath . $mod . "/views/" . $viewtype,$CONFIG->pluginspath . $mod . "/views/", $viewtype); - } - } - } + { + if (is_dir($CONFIG->pluginspath . $mod . "/views")) { + if ($handle = opendir($CONFIG->pluginspath . $mod . "/views")) { + while ($viewtype = readdir($handle)) { + if (!in_array($viewtype,array('.','..','.svn','CVS')) && is_dir($CONFIG->pluginspath . $mod . "/views/" . $viewtype)) { + autoregister_views("",$CONFIG->pluginspath . $mod . "/views/" . $viewtype,$CONFIG->pluginspath . $mod . "/views/", $viewtype); + } + } + } } } - - if (is_dir($CONFIG->pluginspath . $mod . "/languages")) { - register_translations($CONFIG->pluginspath . $mod . "/languages/"); - } - } - } - } + + if (is_dir($CONFIG->pluginspath . $mod . "/languages")) { + register_translations($CONFIG->pluginspath . $mod . "/languages/"); + } + } + } + } } // Cache results if (!$cached_view_paths) elgg_filepath_cache_save(serialize($CONFIG->views)); - } - - } - - /** - * Get the name of the most recent plugin to be called in the call stack (or the plugin that owns the current page, if any). - * - * i.e., if the last plugin was in /mod/foobar/, get_plugin_name would return foo_bar. - * - * @param boolean $mainfilename If set to true, this will instead determine the context from the main script filename called by the browser. Default = false. - * @return string|false Plugin name, or false if no plugin name was called - */ - function get_plugin_name($mainfilename = false) { - if (!$mainfilename) { - if ($backtrace = debug_backtrace()) { - foreach($backtrace as $step) { - $file = $step['file']; - $file = str_replace("\\","/",$file); - $file = str_replace("//","/",$file); - if (preg_match("/mod\/([a-zA-Z0-9\-\_]*)\/start\.php$/",$file,$matches)) { - return $matches[1]; - } - } - } - } else { - //if (substr_count($file,'handlers/pagehandler')) { - if (preg_match("/pg\/([a-zA-Z0-9\-\_]*)\//",$_SERVER['REQUEST_URI'],$matches)) { - return $matches[1]; - } else { - $file = $_SERVER["SCRIPT_NAME"]; - $file = str_replace("\\","/",$file); - $file = str_replace("//","/",$file); - if (preg_match("/mod\/([a-zA-Z0-9\-\_]*)\//",$file,$matches)) { - return $matches[1]; - } - } - } - return false; - } - - /** - * Load and parse a plugin manifest from a plugin XML file. - * - * Example file: - * - * - * - * - * - * - * - * - * - * - * @param string $plugin Plugin name. - * @return array of values - */ - function load_plugin_manifest($plugin) - { - global $CONFIG; - - $xml = xml_2_object(file_get_contents($CONFIG->pluginspath . $plugin. "/manifest.xml")); - - if ($xml) - { - $elements = array(); - - foreach ($xml->children as $element) - { - $key = $element->attributes['key']; - $value = $element->attributes['value']; - - $elements[$key] = $value; - } - - return $elements; - } - - return false; - } - - /** - * This function checks a plugin manifest 'elgg_version' value against the current install - * returning TRUE if the elgg_version is <= the current install's version. - * @param $manifest_elgg_version_string The build version (eg 2009010201). - * @return bool - */ - function check_plugin_compatibility($manifest_elgg_version_string) - { - $version = get_version(); - - if (strpos($manifest_elgg_version_string, '.')===false) - { - // Using version - $req_version = (int)$manifest_elgg_version_string; - - return ($version >= $req_version); - } - - return false; - } - - /** - * Shorthand function for finding the plugin settings. - * - * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you - * are calling from. - */ - function find_plugin_settings($plugin_name = "") - { - $plugins = get_entities('object', 'plugin', 0, "", 9999); - $plugin_name = sanitise_string($plugin_name); - if (!$plugin_name) - $plugin_name = get_plugin_name(); - - if ($plugins) - { - foreach ($plugins as $plugin) - if (strcmp($plugin->title, $plugin_name)==0) - return $plugin; - } - - return false; - } - - /** - * Find the plugin settings for a user. - * - * @param string $plugin_name Plugin name. - * @param int $user_guid The guid who's settings to retrieve. - * @return array of settings in an associative array minus prefix. - */ - function find_plugin_usersettings($plugin_name = "", $user_guid = 0) - { - $plugin_name = sanitise_string($plugin_name); - $user_guid = (int)$user_guid; - - if (!$plugin_name) - $plugin_name = get_plugin_name(); - - if ($user_guid == 0) $user_guid = get_loggedin_userid(); - - // Get metadata for user - $all_metadata = get_all_private_settings($user_guid); //get_metadata_for_entity($user_guid); - if ($all_metadata) - { - $prefix = "plugin:settings:$plugin_name:"; - $return = new stdClass; - - foreach ($all_metadata as $key => $meta) - { - $name = substr($key, strlen($prefix)); - $value = $meta; - - if (strpos($key, $prefix) === 0) - $return->$name = $value; - } - - return $return; - } - - return false; - } - - /** - * Set a user specific setting for a plugin. - * - * @param string $name The name - note, can't be "title". - * @param mixed $value The value. - * @param int $user_guid Optional user. - * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. - */ - function set_plugin_usersetting($name, $value, $user_guid = 0, $plugin_name = "") - { - $plugin_name = sanitise_string($plugin_name); - $user_guid = (int)$user_guid; - $name = sanitise_string($name); - - if (!$plugin_name) - $plugin_name = get_plugin_name(); - - $user = get_entity($user_guid); - if (!$user) $user = get_loggedin_user(); - - if (($user) && ($user instanceof ElggUser)) - { - $prefix = "plugin:settings:$plugin_name:$name"; - //$user->$prefix = $value; - //$user->save(); - - // Hook to validate setting - $value = trigger_plugin_hook('plugin:usersetting', 'user', array( - 'user' => $user, - 'plugin' => $plugin_name, - 'name' => $name, - 'value' => $value - ), $value); - - return set_private_setting($user->guid, $prefix, $value); - } - - return false; - } - - /** - * Get a user specific setting for a plugin. - * - * @param string $name The name. - * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. - */ - function get_plugin_usersetting($name, $user_guid = 0, $plugin_name = "") - { - $plugin_name = sanitise_string($plugin_name); - $user_guid = (int)$user_guid; - $name = sanitise_string($name); - - if (!$plugin_name) - $plugin_name = get_plugin_name(); - - $user = get_entity($user_guid); - if (!$user) $user = get_loggedin_user(); - - if (($user) && ($user instanceof ElggUser)) - { - $prefix = "plugin:settings:$plugin_name:$name"; - return get_private_setting($user->guid, $prefix); //$user->$prefix; - } - - return false; - } - - /** - * Set a setting for a plugin. - * - * @param string $name The name - note, can't be "title". - * @param mixed $value The value. - * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. - */ - function set_plugin_setting($name, $value, $plugin_name = "") - { - if (!$plugin_name) $plugin_name = get_plugin_name(); - $plugin = find_plugin_settings($plugin_name); - - if (!$plugin) - $plugin = new ElggPlugin(); - - if ($name!='title') - { - // Hook to validate setting - $value = trigger_plugin_hook('plugin:setting', 'plugin', array( - 'plugin' => $plugin_name, - 'name' => $name, - 'value' => $value - ), $value); - - $plugin->title = $plugin_name; - $plugin->access_id = ACCESS_PUBLIC; - $plugin->save(); - $plugin->$name = $value; - - return $plugin->getGUID(); - } - - return false; - } - - /** - * Get setting for a plugin. - * - * @param string $name The name. - * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. - */ - function get_plugin_setting($name, $plugin_name = "") - { - $plugin = find_plugin_settings($plugin_name); - - if ($plugin) - return $plugin->$name; - - return false; - } - - /** - * Clear a plugin setting. - * - * @param string $name The name. - * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. - */ - function clear_plugin_setting($name, $plugin_name = "") - { - $plugin = find_plugin_settings($plugin_name); - - if ($plugin) - return remove_all_private_settings($plugin->guid); //$plugin->clearMetaData($name); - - return false; - } - - /** - * Return an array of installed plugins. - */ - function get_installed_plugins() - { - global $CONFIG; - - $installed_plugins = array(); - - if (!empty($CONFIG->pluginspath)) { - - $plugins = get_plugin_list(); - - foreach($plugins as $mod) { - $installed_plugins[$mod] = array(); - $installed_plugins[$mod]['active'] = is_plugin_enabled($mod); - $installed_plugins[$mod]['manifest'] = load_plugin_manifest($mod); - } - - } - - return $installed_plugins; - } - - /** + } + + } + + /** + * Get the name of the most recent plugin to be called in the call stack (or the plugin that owns the current page, if any). + * + * i.e., if the last plugin was in /mod/foobar/, get_plugin_name would return foo_bar. + * + * @param boolean $mainfilename If set to true, this will instead determine the context from the main script filename called by the browser. Default = false. + * @return string|false Plugin name, or false if no plugin name was called + */ + function get_plugin_name($mainfilename = false) { + if (!$mainfilename) { + if ($backtrace = debug_backtrace()) { + foreach($backtrace as $step) { + $file = $step['file']; + $file = str_replace("\\","/",$file); + $file = str_replace("//","/",$file); + if (preg_match("/mod\/([a-zA-Z0-9\-\_]*)\/start\.php$/",$file,$matches)) { + return $matches[1]; + } + } + } + } else { + //if (substr_count($file,'handlers/pagehandler')) { + if (preg_match("/pg\/([a-zA-Z0-9\-\_]*)\//",$_SERVER['REQUEST_URI'],$matches)) { + return $matches[1]; + } else { + $file = $_SERVER["SCRIPT_NAME"]; + $file = str_replace("\\","/",$file); + $file = str_replace("//","/",$file); + if (preg_match("/mod\/([a-zA-Z0-9\-\_]*)\//",$file,$matches)) { + return $matches[1]; + } + } + } + return false; + } + + /** + * Load and parse a plugin manifest from a plugin XML file. + * + * Example file: + * + * + * + * + * + * + * + * + * + * + * @param string $plugin Plugin name. + * @return array of values + */ + function load_plugin_manifest($plugin) + { + global $CONFIG; + + $xml = xml_2_object(file_get_contents($CONFIG->pluginspath . $plugin. "/manifest.xml")); + + if ($xml) + { + $elements = array(); + + foreach ($xml->children as $element) + { + $key = $element->attributes['key']; + $value = $element->attributes['value']; + + $elements[$key] = $value; + } + + return $elements; + } + + return false; + } + + /** + * This function checks a plugin manifest 'elgg_version' value against the current install + * returning TRUE if the elgg_version is <= the current install's version. + * @param $manifest_elgg_version_string The build version (eg 2009010201). + * @return bool + */ + function check_plugin_compatibility($manifest_elgg_version_string) + { + $version = get_version(); + + if (strpos($manifest_elgg_version_string, '.')===false) + { + // Using version + $req_version = (int)$manifest_elgg_version_string; + + return ($version >= $req_version); + } + + return false; + } + + /** + * Shorthand function for finding the plugin settings. + * + * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you + * are calling from. + */ + function find_plugin_settings($plugin_name = "") + { + $plugins = get_entities('object', 'plugin', 0, "", 9999); + $plugin_name = sanitise_string($plugin_name); + if (!$plugin_name) + $plugin_name = get_plugin_name(); + + if ($plugins) + { + foreach ($plugins as $plugin) + if (strcmp($plugin->title, $plugin_name)==0) + return $plugin; + } + + return false; + } + + /** + * Find the plugin settings for a user. + * + * @param string $plugin_name Plugin name. + * @param int $user_guid The guid who's settings to retrieve. + * @return array of settings in an associative array minus prefix. + */ + function find_plugin_usersettings($plugin_name = "", $user_guid = 0) + { + $plugin_name = sanitise_string($plugin_name); + $user_guid = (int)$user_guid; + + if (!$plugin_name) + $plugin_name = get_plugin_name(); + + if ($user_guid == 0) $user_guid = get_loggedin_userid(); + + // Get metadata for user + $all_metadata = get_all_private_settings($user_guid); //get_metadata_for_entity($user_guid); + if ($all_metadata) + { + $prefix = "plugin:settings:$plugin_name:"; + $return = new stdClass; + + foreach ($all_metadata as $key => $meta) + { + $name = substr($key, strlen($prefix)); + $value = $meta; + + if (strpos($key, $prefix) === 0) + $return->$name = $value; + } + + return $return; + } + + return false; + } + + /** + * Set a user specific setting for a plugin. + * + * @param string $name The name - note, can't be "title". + * @param mixed $value The value. + * @param int $user_guid Optional user. + * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. + */ + function set_plugin_usersetting($name, $value, $user_guid = 0, $plugin_name = "") + { + $plugin_name = sanitise_string($plugin_name); + $user_guid = (int)$user_guid; + $name = sanitise_string($name); + + if (!$plugin_name) + $plugin_name = get_plugin_name(); + + $user = get_entity($user_guid); + if (!$user) $user = get_loggedin_user(); + + if (($user) && ($user instanceof ElggUser)) + { + $prefix = "plugin:settings:$plugin_name:$name"; + //$user->$prefix = $value; + //$user->save(); + + // Hook to validate setting + $value = trigger_plugin_hook('plugin:usersetting', 'user', array( + 'user' => $user, + 'plugin' => $plugin_name, + 'name' => $name, + 'value' => $value + ), $value); + + return set_private_setting($user->guid, $prefix, $value); + } + + return false; + } + + /** + * Get a user specific setting for a plugin. + * + * @param string $name The name. + * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. + */ + function get_plugin_usersetting($name, $user_guid = 0, $plugin_name = "") + { + $plugin_name = sanitise_string($plugin_name); + $user_guid = (int)$user_guid; + $name = sanitise_string($name); + + if (!$plugin_name) + $plugin_name = get_plugin_name(); + + $user = get_entity($user_guid); + if (!$user) $user = get_loggedin_user(); + + if (($user) && ($user instanceof ElggUser)) + { + $prefix = "plugin:settings:$plugin_name:$name"; + return get_private_setting($user->guid, $prefix); //$user->$prefix; + } + + return false; + } + + /** + * Set a setting for a plugin. + * + * @param string $name The name - note, can't be "title". + * @param mixed $value The value. + * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. + */ + function set_plugin_setting($name, $value, $plugin_name = "") + { + if (!$plugin_name) $plugin_name = get_plugin_name(); + $plugin = find_plugin_settings($plugin_name); + + if (!$plugin) + $plugin = new ElggPlugin(); + + if ($name!='title') + { + // Hook to validate setting + $value = trigger_plugin_hook('plugin:setting', 'plugin', array( + 'plugin' => $plugin_name, + 'name' => $name, + 'value' => $value + ), $value); + + $plugin->title = $plugin_name; + $plugin->access_id = ACCESS_PUBLIC; + $plugin->save(); + $plugin->$name = $value; + + return $plugin->getGUID(); + } + + return false; + } + + /** + * Get setting for a plugin. + * + * @param string $name The name. + * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. + */ + function get_plugin_setting($name, $plugin_name = "") + { + $plugin = find_plugin_settings($plugin_name); + + if ($plugin) + return $plugin->$name; + + return false; + } + + /** + * Clear a plugin setting. + * + * @param string $name The name. + * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. + */ + function clear_plugin_setting($name, $plugin_name = "") + { + $plugin = find_plugin_settings($plugin_name); + + if ($plugin) + return remove_all_private_settings($plugin->guid); //$plugin->clearMetaData($name); + + return false; + } + + /** + * Return an array of installed plugins. + */ + function get_installed_plugins() + { + global $CONFIG; + + $installed_plugins = array(); + + if (!empty($CONFIG->pluginspath)) { + + $plugins = get_plugin_list(); + + foreach($plugins as $mod) { + $installed_plugins[$mod] = array(); + $installed_plugins[$mod]['active'] = is_plugin_enabled($mod); + $installed_plugins[$mod]['manifest'] = load_plugin_manifest($mod); + } + + } + + return $installed_plugins; + } + + /** * Enable a plugin for a site (default current site) * * Important: You should regenerate simplecache and the viewpath cache after executing this function * otherwise you may experience view display artifacts. Do this with the following code: * * elgg_view_regenerate_simplecache(); - * elgg_filepath_cache_reset(); - * - * @param string $plugin The plugin name. - * @param int $site_guid The site id, if not specified then this is detected. - */ - function enable_plugin($plugin, $site_guid = 0) - { - global $CONFIG, $ENABLED_PLUGINS_CACHE; - - $plugin = sanitise_string($plugin); - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - $site = get_entity($site_guid); - if (!($site instanceof ElggSite)) - throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $site_guid, "ElggSite")); - - $enabled = $site->getMetaData('enabled_plugins'); - $new_enabled = array(); - if ($enabled) - { - if (!is_array($enabled)) - $new_enabled[] = $enabled; - else - $new_enabled = $enabled; - } - $new_enabled[] = $plugin; - $new_enabled = array_unique($new_enabled); - + * elgg_filepath_cache_reset(); + * + * @param string $plugin The plugin name. + * @param int $site_guid The site id, if not specified then this is detected. + */ + function enable_plugin($plugin, $site_guid = 0) + { + global $CONFIG, $ENABLED_PLUGINS_CACHE; + + $plugin = sanitise_string($plugin); + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + $site = get_entity($site_guid); + if (!($site instanceof ElggSite)) + throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $site_guid, "ElggSite")); + + $enabled = $site->getMetaData('enabled_plugins'); + $new_enabled = array(); + if ($enabled) + { + if (!is_array($enabled)) + $new_enabled[] = $enabled; + else + $new_enabled = $enabled; + } + $new_enabled[] = $plugin; + $new_enabled = array_unique($new_enabled); + $return = $site->setMetaData('enabled_plugins', $new_enabled); - $ENABLED_PLUGINS_CACHE = $new_enabled; - - return $return; - } - - /** - * Disable a plugin for a site (default current site) + $ENABLED_PLUGINS_CACHE = $new_enabled; + + return $return; + } + + /** + * Disable a plugin for a site (default current site) * * Important: You should regenerate simplecache and the viewpath cache after executing this function * otherwise you may experience view display artifacts. Do this with the following code: * * elgg_view_regenerate_simplecache(); * elgg_filepath_cache_reset(); - * - * @param string $plugin The plugin name. - * @param int $site_guid The site id, if not specified then this is detected. - */ - function disable_plugin($plugin, $site_guid = 0) - { - global $CONFIG, $ENABLED_PLUGINS_CACHE; - - $plugin = sanitise_string($plugin); - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - $site = get_entity($site_guid); - if (!($site instanceof ElggSite)) - throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $site_guid, "ElggSite")); - - $enabled = $site->getMetaData('enabled_plugins'); - $new_enabled = array(); - - foreach ($enabled as $plug) - if ($plugin != $plug) - $new_enabled[] = $plug; - + * + * @param string $plugin The plugin name. + * @param int $site_guid The site id, if not specified then this is detected. + */ + function disable_plugin($plugin, $site_guid = 0) + { + global $CONFIG, $ENABLED_PLUGINS_CACHE; + + $plugin = sanitise_string($plugin); + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + $site = get_entity($site_guid); + if (!($site instanceof ElggSite)) + throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $site_guid, "ElggSite")); + + $enabled = $site->getMetaData('enabled_plugins'); + $new_enabled = array(); + + foreach ($enabled as $plug) + if ($plugin != $plug) + $new_enabled[] = $plug; + $return = $site->setMetaData('enabled_plugins', $new_enabled); - $ENABLED_PLUGINS_CACHE = $new_enabled; - - return $return; - } - - /** - * Return whether a plugin is enabled or not. - * - * @param string $plugin The plugin name. - * @param int $site_guid The site id, if not specified then this is detected. - * @return bool - */ - function is_plugin_enabled($plugin, $site_guid = 0) - { - global $CONFIG, $ENABLED_PLUGINS_CACHE; - - if (!file_exists($CONFIG->pluginspath . $plugin)) return false; - - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - - if (!$ENABLED_PLUGINS_CACHE) { - $site = get_entity($site_guid); - if (!($site instanceof ElggSite)) - throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $site_guid, "ElggSite")); - - $ENABLED_PLUGINS_CACHE = $site->enabled_plugins; - } - - foreach ($ENABLED_PLUGINS_CACHE as $e) - if ($e == $plugin) return true; - - return false; - } - - /** - * Run once and only once. - */ - function plugin_run_once() - { - // Register a class - add_subtype("object", "plugin", "ElggPlugin"); - } - - /** - * Initialise the file modules. - * Listens to system boot and registers any appropriate file types and classes - */ - function plugin_init() - { - // Now run this stuff, but only once - run_function_once("plugin_run_once"); - - // Register some actions - register_action("plugins/settings/save", false, "", true); - register_action("plugins/usersettings/save"); - - register_action('admin/plugins/enable', false, "", true); // Enable + $ENABLED_PLUGINS_CACHE = $new_enabled; + + return $return; + } + + /** + * Return whether a plugin is enabled or not. + * + * @param string $plugin The plugin name. + * @param int $site_guid The site id, if not specified then this is detected. + * @return bool + */ + function is_plugin_enabled($plugin, $site_guid = 0) + { + global $CONFIG, $ENABLED_PLUGINS_CACHE; + + if (!file_exists($CONFIG->pluginspath . $plugin)) return false; + + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + + if (!$ENABLED_PLUGINS_CACHE) { + $site = get_entity($site_guid); + if (!($site instanceof ElggSite)) + throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $site_guid, "ElggSite")); + + $ENABLED_PLUGINS_CACHE = $site->enabled_plugins; + } + + foreach ($ENABLED_PLUGINS_CACHE as $e) + if ($e == $plugin) return true; + + return false; + } + + /** + * Run once and only once. + */ + function plugin_run_once() + { + // Register a class + add_subtype("object", "plugin", "ElggPlugin"); + } + + /** + * Initialise the file modules. + * Listens to system boot and registers any appropriate file types and classes + */ + function plugin_init() + { + // Now run this stuff, but only once + run_function_once("plugin_run_once"); + + // Register some actions + register_action("plugins/settings/save", false, "", true); + register_action("plugins/usersettings/save"); + + register_action('admin/plugins/enable', false, "", true); // Enable register_action('admin/plugins/disable', false, "", true); // Disable register_action('admin/plugins/enableall', false, "", true); // Enable all - register_action('admin/plugins/disableall', false, "", true); // Disable all - - register_action('admin/plugins/reorder', false, "", true); // Reorder - - } - - // Register a startup event - register_elgg_event_handler('init','system','plugin_init'); + register_action('admin/plugins/disableall', false, "", true); // Disable all + + register_action('admin/plugins/reorder', false, "", true); // Reorder + + } + + // Register a startup event + register_elgg_event_handler('init','system','plugin_init'); ?> \ No newline at end of file diff --git a/engine/lib/query.php b/engine/lib/query.php index 9d8b00be2..75b9eddeb 100644 --- a/engine/lib/query.php +++ b/engine/lib/query.php @@ -178,12 +178,12 @@ function __toString() { - //$access = get_access_list(); - // KJ - changed to use get_access_sql_suffix - // Note: currently get_access_sql_suffix is hardwired to use - // $acl_field = "access_id", $object_owner_table = $acl_table, and - // $object_owner_id_field = "owner_guid" - // TODO: recode get_access_sql_suffix to make it possible to specify alternate field names + //$access = get_access_list(); + // KJ - changed to use get_access_sql_suffix + // Note: currently get_access_sql_suffix is hardwired to use + // $acl_field = "access_id", $object_owner_table = $acl_table, and + // $object_owner_id_field = "owner_guid" + // TODO: recode get_access_sql_suffix to make it possible to specify alternate field names return "and ".get_access_sql_suffix($this->acl_table); // Add access controls //return "and ({$this->acl_table}.{$this->acl_field} in {$access} or ({$this->acl_table}.{$this->acl_field} = 0 and {$this->object_owner_table}.{$this->object_owner_id_field} = {$_SESSION['id']}))"; diff --git a/engine/lib/relationships.php b/engine/lib/relationships.php index 92a88781f..2ba8a553e 100644 --- a/engine/lib/relationships.php +++ b/engine/lib/relationships.php @@ -415,14 +415,14 @@ $guid_one = (int)$guid_one; $relationship = sanitise_string($relationship); $guid_two = (int)$guid_two; - - $obj = check_entity_relationship($guid_one, $relationship, $guid_two); - if ($obj == false) return false; - - if (trigger_elgg_event('delete', $relationship, $obj)) { - return delete_data("DELETE from {$CONFIG->dbprefix}entity_relationships where guid_one=$guid_one and relationship='$relationship' and guid_two=$guid_two"); - } else { - return false; + + $obj = check_entity_relationship($guid_one, $relationship, $guid_two); + if ($obj == false) return false; + + if (trigger_elgg_event('delete', $relationship, $obj)) { + return delete_data("DELETE from {$CONFIG->dbprefix}entity_relationships where guid_one=$guid_one and relationship='$relationship' and guid_two=$guid_two"); + } else { + return false; } } @@ -431,7 +431,7 @@ * * @param int $guid_one The GUID of the entity * @param string $relationship The name of the relationship (optionally) - * @param true|false $inverse Whether we're deleting inverse relationships (default false) + * @param true|false $inverse Whether we're deleting inverse relationships (default false) * @param string $type The type of entity to limit this relationship delete to (defaults to all) * @return true|false Depending on success */ @@ -446,25 +446,25 @@ $where = "and er.relationship='$relationship'"; } else { $where = ""; - } - - if (!empty($type)) { - $type = sanitise_string($type); - if (!$inverse) { - $join = " join {$CONFIG->dbprefix}entities e on e.guid = er.guid_two "; - } else { - $join = " join {$CONFIG->dbprefix}entities e on e.guid = er.guid_one "; - $where .= " and "; - } - $where .= " and e.type = '{$type}' "; - } else { - $join = ""; } - if (!$inverse) { + if (!empty($type)) { + $type = sanitise_string($type); + if (!$inverse) { + $join = " join {$CONFIG->dbprefix}entities e on e.guid = er.guid_two "; + } else { + $join = " join {$CONFIG->dbprefix}entities e on e.guid = er.guid_one "; + $where .= " and "; + } + $where .= " and e.type = '{$type}' "; + } else { + $join = ""; + } + + if (!$inverse) { $sql = "DELETE er from {$CONFIG->dbprefix}entity_relationships as er {$join} where guid_one={$guid_one} {$where}"; return delete_data($sql); - } else { + } else { $sql = "DELETE er from {$CONFIG->dbprefix}entity_relationships as er {$join} where guid_two={$guid_one} {$where}"; return delete_data($sql); } @@ -513,7 +513,7 @@ $type = sanitise_string($type); if ($subtype AND !$subtype = get_subtype_id($type, $subtype)) return false; - $owner_guid = (int)$owner_guid; + $owner_guid = (int)$owner_guid; if ($order_by == "") $order_by = "time_created desc"; $order_by = sanitise_string($order_by); $limit = (int)$limit; @@ -563,140 +563,140 @@ } return false; - } - - /** - * Returns a viewable list of entities by relationship - * - * @see elgg_view_entity_list - * - * @param string $relationship The relationship eg "friends_of" - * @param int $relationship_guid The guid of the entity to use query - * @param bool $inverse_relationship Reverse the normal function of the query to instead say "give me all entities for whome $relationship_guid is a $relationship of" - * @param string $type The type of entity (eg 'object') - * @param string $subtype The entity subtype - * @param int $owner_guid The owner (default: all) - * @param int $limit The number of entities to display on a page - * @param true|false $fullview Whether or not to display the full view (default: true) - * @param true|false $viewtypetoggle Whether or not to allow gallery view - * @param true|false $pagination Whether to display pagination (default: true) - * @return string The viewable list of entities - */ - function list_entities_from_relationship($relationship, $relationship_guid, $inverse_relationship = false, $type = "", $subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = false, $pagination = true) { - - $limit = (int) $limit; - $offset = (int) get_input('offset'); - $count = get_entities_from_relationship($relationship, $relationship_guid, $inverse_relationship, $type, $subtype, $owner_guid, "", $limit, $offset, true); - $entities = get_entities_from_relationship($relationship, $relationship_guid, $inverse_relationship, $type, $subtype, $owner_guid, "", $limit, $offset); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); - - } - - /** - * Gets the number of entities by a the number of entities related to them in a particular way. - * This is a good way to get out the users with the most friends, or the groups with the most members. - * - * @param string $relationship The relationship eg "friends_of" - * @param bool $inverse_relationship Reverse the normal function of the query to instead say "give me all entities for whome $relationship_guid is a $relationship of" (default: true) - * @param string $type The type of entity (default: all) - * @param string $subtype The entity subtype (default: all) - * @param int $owner_guid The owner of the entities (default: none) - * @param int $limit - * @param int $offset - * @param boolean $count Set to true if you want to count the number of entities instead (default false) - * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. - * @return array|int|false An array of entities, or the number of entities, or false on failure - */ - - function get_entities_by_relationship_count($relationship, $inverse_relationship = true, $type = "", $subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $count = false, $site_guid = 0) { - - global $CONFIG; - - $relationship = sanitise_string($relationship); - $inverse_relationship = (bool)$inverse_relationship; - $type = sanitise_string($type); + } + + /** + * Returns a viewable list of entities by relationship + * + * @see elgg_view_entity_list + * + * @param string $relationship The relationship eg "friends_of" + * @param int $relationship_guid The guid of the entity to use query + * @param bool $inverse_relationship Reverse the normal function of the query to instead say "give me all entities for whome $relationship_guid is a $relationship of" + * @param string $type The type of entity (eg 'object') + * @param string $subtype The entity subtype + * @param int $owner_guid The owner (default: all) + * @param int $limit The number of entities to display on a page + * @param true|false $fullview Whether or not to display the full view (default: true) + * @param true|false $viewtypetoggle Whether or not to allow gallery view + * @param true|false $pagination Whether to display pagination (default: true) + * @return string The viewable list of entities + */ + function list_entities_from_relationship($relationship, $relationship_guid, $inverse_relationship = false, $type = "", $subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = false, $pagination = true) { + + $limit = (int) $limit; + $offset = (int) get_input('offset'); + $count = get_entities_from_relationship($relationship, $relationship_guid, $inverse_relationship, $type, $subtype, $owner_guid, "", $limit, $offset, true); + $entities = get_entities_from_relationship($relationship, $relationship_guid, $inverse_relationship, $type, $subtype, $owner_guid, "", $limit, $offset); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); + + } + + /** + * Gets the number of entities by a the number of entities related to them in a particular way. + * This is a good way to get out the users with the most friends, or the groups with the most members. + * + * @param string $relationship The relationship eg "friends_of" + * @param bool $inverse_relationship Reverse the normal function of the query to instead say "give me all entities for whome $relationship_guid is a $relationship of" (default: true) + * @param string $type The type of entity (default: all) + * @param string $subtype The entity subtype (default: all) + * @param int $owner_guid The owner of the entities (default: none) + * @param int $limit + * @param int $offset + * @param boolean $count Set to true if you want to count the number of entities instead (default false) + * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. + * @return array|int|false An array of entities, or the number of entities, or false on failure + */ + + function get_entities_by_relationship_count($relationship, $inverse_relationship = true, $type = "", $subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $count = false, $site_guid = 0) { + + global $CONFIG; + + $relationship = sanitise_string($relationship); + $inverse_relationship = (bool)$inverse_relationship; + $type = sanitise_string($type); if ($subtype AND !$subtype = get_subtype_id($type, $subtype)) - return false; - $owner_guid = (int)$owner_guid; - $order_by = sanitise_string($order_by); - $limit = (int)$limit; - $offset = (int)$offset; - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - //$access = get_access_list(); - - $where = array(); - - if ($relationship!="") - $where[] = "r.relationship='$relationship'"; - if ($inverse_relationship) { - $on = 'e.guid = r.guid_two'; - } else { - $on = 'e.guid = r.guid_one'; - } - if ($type != "") - $where[] = "e.type='$type'"; - if ($subtype) - $where[] = "e.subtype=$subtype"; - if ($owner_guid != "") - $where[] = "e.container_guid='$owner_guid'"; - if ($site_guid > 0) - $where[] = "e.site_guid = {$site_guid}"; - - if ($count) { - $query = "SELECT count(distinct e.guid) as total "; - } else { - $query = "SELECT e.*, count(e.guid) as total "; - } - - $query .= " from {$CONFIG->dbprefix}entity_relationships r JOIN {$CONFIG->dbprefix}entities e on {$on} where "; - - if (!empty($where)) - foreach ($where as $w) - $query .= " $w and "; - $query .= get_access_sql_suffix("e"); // Add access controls - - if (!$count) { - $query .= " group by e.guid "; - $query .= " order by total desc limit {$offset}, {$limit}"; // Add order and limit - return get_data($query, "entity_row_to_elggstar"); - } else { - if ($count = get_data_row($query)) { - return $count->total; - } - } - - return false; - - } - - /** - * Displays a human-readable list of entities - * - * @param string $relationship The relationship eg "friends_of" - * @param bool $inverse_relationship Reverse the normal function of the query to instead say "give me all entities for whome $relationship_guid is a $relationship of" (default: true) - * @param string $type The type of entity (eg 'object') - * @param string $subtype The entity subtype - * @param int $owner_guid The owner (default: all) - * @param int $limit The number of entities to display on a page - * @param true|false $fullview Whether or not to display the full view (default: true) - * @param true|false $viewtypetoggle Whether or not to allow gallery view - * @param true|false $pagination Whether to display pagination (default: true) - * @return string The viewable list of entities - */ - - function list_entities_by_relationship_count($relationship, $inverse_relationship = true, $type = "", $subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = false, $pagination = true) { - - $limit = (int) $limit; - $offset = (int) get_input('offset'); - $count = get_entities_by_relationship_count($relationship,$inverse_relationship,$type,$subtype,$owner_guid,0,0,true); - $entities = get_entities_by_relationship_count($relationship,$inverse_relationship,$type,$subtype,$owner_guid,$limit,$offset); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); - + return false; + $owner_guid = (int)$owner_guid; + $order_by = sanitise_string($order_by); + $limit = (int)$limit; + $offset = (int)$offset; + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + //$access = get_access_list(); + + $where = array(); + + if ($relationship!="") + $where[] = "r.relationship='$relationship'"; + if ($inverse_relationship) { + $on = 'e.guid = r.guid_two'; + } else { + $on = 'e.guid = r.guid_one'; + } + if ($type != "") + $where[] = "e.type='$type'"; + if ($subtype) + $where[] = "e.subtype=$subtype"; + if ($owner_guid != "") + $where[] = "e.container_guid='$owner_guid'"; + if ($site_guid > 0) + $where[] = "e.site_guid = {$site_guid}"; + + if ($count) { + $query = "SELECT count(distinct e.guid) as total "; + } else { + $query = "SELECT e.*, count(e.guid) as total "; + } + + $query .= " from {$CONFIG->dbprefix}entity_relationships r JOIN {$CONFIG->dbprefix}entities e on {$on} where "; + + if (!empty($where)) + foreach ($where as $w) + $query .= " $w and "; + $query .= get_access_sql_suffix("e"); // Add access controls + + if (!$count) { + $query .= " group by e.guid "; + $query .= " order by total desc limit {$offset}, {$limit}"; // Add order and limit + return get_data($query, "entity_row_to_elggstar"); + } else { + if ($count = get_data_row($query)) { + return $count->total; + } + } + + return false; + + } + + /** + * Displays a human-readable list of entities + * + * @param string $relationship The relationship eg "friends_of" + * @param bool $inverse_relationship Reverse the normal function of the query to instead say "give me all entities for whome $relationship_guid is a $relationship of" (default: true) + * @param string $type The type of entity (eg 'object') + * @param string $subtype The entity subtype + * @param int $owner_guid The owner (default: all) + * @param int $limit The number of entities to display on a page + * @param true|false $fullview Whether or not to display the full view (default: true) + * @param true|false $viewtypetoggle Whether or not to allow gallery view + * @param true|false $pagination Whether to display pagination (default: true) + * @return string The viewable list of entities + */ + + function list_entities_by_relationship_count($relationship, $inverse_relationship = true, $type = "", $subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = false, $pagination = true) { + + $limit = (int) $limit; + $offset = (int) get_input('offset'); + $count = get_entities_by_relationship_count($relationship,$inverse_relationship,$type,$subtype,$owner_guid,0,0,true); + $entities = get_entities_by_relationship_count($relationship,$inverse_relationship,$type,$subtype,$owner_guid,$limit,$offset); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); + } /** diff --git a/engine/lib/river2.php b/engine/lib/river2.php index dd0d2f76f..1a982e6a4 100644 --- a/engine/lib/river2.php +++ b/engine/lib/river2.php @@ -1,301 +1,301 @@ -access_id; + + $type = $object->getType(); + $subtype = $object->getSubtype(); + + $action_type = sanitise_string($action_type); + + // Load config + global $CONFIG; + + // Attempt to save river item; return success status + return insert_data("insert into {$CONFIG->dbprefix}river " . + " set type = '{$type}', " . + " subtype = '{$subtype}', " . + " action_type = '{$action_type}', " . + " access_id = {$access_id}, " . + " view = '{$view}', " . + " subject_guid = {$subject_guid}, " . + " object_guid = {$object_guid}, " . + " posted = {$posted} "); + + } + + /** + * Removes all items relating to a particular acting entity from the river + * + * @param int $subject_guid The GUID of the entity + * @return true|false Depending on success + */ + function remove_from_river_by_subject( + $subject_guid + ) { + + // Sanitise + $subject_guid = (int) $subject_guid; + + // Load config + global $CONFIG; + + // Remove + return delete_data("delete from {$CONFIG->dbprefix}river where subject_guid = {$subject_guid}"); + + } + + /** + * Removes all items relating to a particular entity being acted upon from the river + * + * @param int $object_guid The GUID of the entity + * @return true|false Depending on success + */ + function remove_from_river_by_object( + $object_guid + ) { + + // Sanitise + $object_guid = (int) $object_guid; + + // Load config + global $CONFIG; + + // Remove + return delete_data("delete from {$CONFIG->dbprefix}river where object_guid = {$object_guid}"); + + } + + /** + * Sets the access ID on river items for a particular object + * + * @param int $object_guid The GUID of the entity + * @param int $access_id The access ID + * @return true|false Depending on success + */ + function update_river_access_by_object( + $object_guid, $access_id + ) { + + // Sanitise + $object_guid = (int) $object_guid; + $access_id = (int) $access_id; + + // Load config + global $CONFIG; + + // Remove + return update_data("update {$CONFIG->dbprefix}river set access_id = {$access_id} where object_guid = {$object_guid}"); + + } + + /** + * Retrieves items from the river. All parameters are optional. + * + * @param int|array $subject_guid Acting entity to restrict to. Default: all + * @param int|array $object_guid Entity being acted on to restrict to. Default: all + * @param string $subject_relationship If set to a relationship type, this will use $subject_guid as the starting point and set the subjects to be all users this entity has this relationship with (eg 'friend'). Default: blank + * @param string $type The type of entity to restrict to. Default: all + * @param string $subtype The subtype of entity to restrict to. Default: all + * @param string $action_type The type of river action to restrict to. Default: all + * @param int $limit The number of items to retrieve. Default: 20 + * @param int $offset The page offset. Default: 0 + * @param int $posted_min The minimum time period to look at. Default: none + * @param int $posted_max The maximum time period to look at. Default: none + * @return array|false Depending on success + */ + function get_river_items( + $subject_guid = 0, + $object_guid = 0, + $subject_relationship = '', + $type = '', + $subtype = '', + $action_type = '', + $limit = 20, + $offset = 0, + $posted_min = 0, + $posted_max = 0 + ) { + + // Get config + global $CONFIG; + + // Sanitise variables + if (!is_array($subject_guid)) { + $subject_guid = (int) $subject_guid; + } else { + foreach($subject_guid as $key => $temp) { + $subject_guid[$key] = (int) $temp; + } + } + if (!is_array($object_guid)) { + $object_guid = (int) $object_guid; + } else { + foreach($object_guid as $key => $temp) { + $object_guid[$key] = (int) $temp; + } + } + if (!empty($type)) $type = sanitise_string($type); + if (!empty($subtype)) $subtype = sanitise_string($subtype); + if (!empty($action_type)) $action_type = sanitise_string($action_type); + $limit = (int) $limit; + $offset = (int) $offset; + $posted_min = (int) $posted_min; + $posted_max = (int) $posted_max; + + // Construct 'where' clauses for the river + $where = array(); + $where[] = str_replace("and enabled='yes'",'',str_replace('owner_guid','subject_guid',get_access_sql_suffix())); + + if (empty($subject_relationship)) { + if (!empty($subject_guid)) + if (!is_array($subject_guid)) { + $where[] = " subject_guid = {$subject_guid} "; + } else { + $where[] = " subject_guid in (" . implode(',',$subject_guid) . ") "; + } + } else { + if (!is_array($subject_guid)) + if ($entities = get_entities_from_relationship($subject_relationship,$subject_guid,false,'','',0,'',9999)) { + $guids = array(); + foreach($entities as $entity) $guids[] = (int) $entity->guid; + // $guids[] = $subject_guid; + $where[] = " subject_guid in (" . implode(',',$guids) . ") "; + } else { + return array(); + } + } + if (!empty($object_guid)) + if (!is_array($object_guid)) { + $where[] = " object_guid = {$object_guid} "; + } else { + $where[] = " object_guid in (" . implode(',',$object_guid) . ") "; + } + if (!empty($type)) $where[] = " type = '{$type}' "; + if (!empty($subtype)) $where[] = " subtype = '{$subtype}' "; + if (!empty($action_type)) $where[] = " action_type = '{$action_type}' "; + if (!empty($posted_min)) $where[] = " posted > {$posted_min} "; + if (!empty($posted_max)) $where[] = " posted < {$posted_max} "; + + $whereclause = implode(' and ', $where); + + // Construct main SQL + $sql = "select id,type,subtype,action_type,access_id,view,subject_guid,object_guid,posted from {$CONFIG->dbprefix}river where {$whereclause} order by posted desc limit {$offset},{$limit}"; + + // Get data + return get_data($sql); + + } + + /** + * Returns a human-readable representation of a river item + * + * @see get_river_items + * + * @param stdClass $item A river item object as returned from get_river_items + * @return string|false Depending on success + */ + function elgg_view_river_item($item) { + if (isset($item->view)) { + + $object = get_entity($item->object_guid); + if (!$object) { + $body = elgg_view('river/item/noaccess'); + } else { + if (elgg_view_exists($item->view)) { + $body = elgg_view($item->view,array( + 'item' => $item + )); + } + } + return elgg_view('river/item/wrapper',array( + 'item' => $item, + 'body' => $body + )); + + } + return false; + } + + /** + * Returns a human-readable version of the river. + * + * @param int|array $subject_guid Acting entity to restrict to. Default: all + * @param int|array $object_guid Entity being acted on to restrict to. Default: all + * @param string $subject_relationship If set to a relationship type, this will use $subject_guid as the starting point and set the subjects to be all users this entity has this relationship with (eg 'friend'). Default: blank + * @param string $type The type of entity to restrict to. Default: all + * @param string $subtype The subtype of entity to restrict to. Default: all + * @param string $action_type The type of river action to restrict to. Default: all + * @param int $limit The number of items to retrieve. Default: 20 + * @param int $posted_min The minimum time period to look at. Default: none + * @param int $posted_max The maximum time period to look at. Default: none + * @return string Human-readable river. + */ + function elgg_view_river_items($subject_guid = 0, + $object_guid = 0, + $subject_relationship = '', + $type = '', + $subtype = '', + $action_type = '', + $limit = 20, + $posted_min = 0, + $posted_max = 0, + $pagination = true) { + + // Get input from outside world and sanitise it + $offset = (int) get_input('offset',0); + + // Get river items, if they exist + if ($riveritems = get_river_items($subject_guid,$object_guid,$subject_relationship,$type,$subtype,$action_type,($limit + 1),$offset,$posted_min,$posted_max)) { + + return elgg_view('river/item/list',array( + 'limit' => $limit, + 'offset' => $offset, + 'items' => $riveritems, + 'pagination' => $pagination + )); + + } + + return ''; + + } - * @link http://elgg.org/ - */ - - /** - * Adds an item to the river. - * - * @param string $view The view that will handle the river item (must exist) - * @param string $action_type An arbitrary one-word string to define the action (eg 'comment', 'create') - * @param int $subject_guid The GUID of the entity doing the action - * @param int $object_guid The GUID of the entity being acted upon - * @param int $access_id The access ID of the river item (default: same as the object) - * @param int $posted The UNIX epoch timestamp of the river item (default: now) - * @return true|false Depending on success - */ - function add_to_river( - $view, - $action_type, - $subject_guid, - $object_guid, - $access_id = "", - $posted = 0 - ) { - - // Sanitise variables - if (!elgg_view_exists($view)) return false; - if (!($subject = get_entity($subject_guid))) return false; - if (!($object = get_entity($object_guid))) return false; - if (empty($action_type)) return false; - if ($posted == 0) $posted = time(); - if ($access_id === "") $access_id = $object->access_id; - - $type = $object->getType(); - $subtype = $object->getSubtype(); - - $action_type = sanitise_string($action_type); - - // Load config - global $CONFIG; - - // Attempt to save river item; return success status - return insert_data("insert into {$CONFIG->dbprefix}river " . - " set type = '{$type}', " . - " subtype = '{$subtype}', " . - " action_type = '{$action_type}', " . - " access_id = {$access_id}, " . - " view = '{$view}', " . - " subject_guid = {$subject_guid}, " . - " object_guid = {$object_guid}, " . - " posted = {$posted} "); - - } - - /** - * Removes all items relating to a particular acting entity from the river - * - * @param int $subject_guid The GUID of the entity - * @return true|false Depending on success - */ - function remove_from_river_by_subject( - $subject_guid - ) { - - // Sanitise - $subject_guid = (int) $subject_guid; - - // Load config - global $CONFIG; - - // Remove - return delete_data("delete from {$CONFIG->dbprefix}river where subject_guid = {$subject_guid}"); - - } - - /** - * Removes all items relating to a particular entity being acted upon from the river - * - * @param int $object_guid The GUID of the entity - * @return true|false Depending on success - */ - function remove_from_river_by_object( - $object_guid - ) { - - // Sanitise - $object_guid = (int) $object_guid; - - // Load config - global $CONFIG; - - // Remove - return delete_data("delete from {$CONFIG->dbprefix}river where object_guid = {$object_guid}"); - - } - - /** - * Sets the access ID on river items for a particular object - * - * @param int $object_guid The GUID of the entity - * @param int $access_id The access ID - * @return true|false Depending on success - */ - function update_river_access_by_object( - $object_guid, $access_id - ) { - - // Sanitise - $object_guid = (int) $object_guid; - $access_id = (int) $access_id; - - // Load config - global $CONFIG; - - // Remove - return update_data("update {$CONFIG->dbprefix}river set access_id = {$access_id} where object_guid = {$object_guid}"); - - } - - /** - * Retrieves items from the river. All parameters are optional. - * - * @param int|array $subject_guid Acting entity to restrict to. Default: all - * @param int|array $object_guid Entity being acted on to restrict to. Default: all - * @param string $subject_relationship If set to a relationship type, this will use $subject_guid as the starting point and set the subjects to be all users this entity has this relationship with (eg 'friend'). Default: blank - * @param string $type The type of entity to restrict to. Default: all - * @param string $subtype The subtype of entity to restrict to. Default: all - * @param string $action_type The type of river action to restrict to. Default: all - * @param int $limit The number of items to retrieve. Default: 20 - * @param int $offset The page offset. Default: 0 - * @param int $posted_min The minimum time period to look at. Default: none - * @param int $posted_max The maximum time period to look at. Default: none - * @return array|false Depending on success - */ - function get_river_items( - $subject_guid = 0, - $object_guid = 0, - $subject_relationship = '', - $type = '', - $subtype = '', - $action_type = '', - $limit = 20, - $offset = 0, - $posted_min = 0, - $posted_max = 0 - ) { - - // Get config - global $CONFIG; - - // Sanitise variables - if (!is_array($subject_guid)) { - $subject_guid = (int) $subject_guid; - } else { - foreach($subject_guid as $key => $temp) { - $subject_guid[$key] = (int) $temp; - } - } - if (!is_array($object_guid)) { - $object_guid = (int) $object_guid; - } else { - foreach($object_guid as $key => $temp) { - $object_guid[$key] = (int) $temp; - } - } - if (!empty($type)) $type = sanitise_string($type); - if (!empty($subtype)) $subtype = sanitise_string($subtype); - if (!empty($action_type)) $action_type = sanitise_string($action_type); - $limit = (int) $limit; - $offset = (int) $offset; - $posted_min = (int) $posted_min; - $posted_max = (int) $posted_max; - - // Construct 'where' clauses for the river - $where = array(); - $where[] = str_replace("and enabled='yes'",'',str_replace('owner_guid','subject_guid',get_access_sql_suffix())); - - if (empty($subject_relationship)) { - if (!empty($subject_guid)) - if (!is_array($subject_guid)) { - $where[] = " subject_guid = {$subject_guid} "; - } else { - $where[] = " subject_guid in (" . implode(',',$subject_guid) . ") "; - } - } else { - if (!is_array($subject_guid)) - if ($entities = get_entities_from_relationship($subject_relationship,$subject_guid,false,'','',0,'',9999)) { - $guids = array(); - foreach($entities as $entity) $guids[] = (int) $entity->guid; - // $guids[] = $subject_guid; - $where[] = " subject_guid in (" . implode(',',$guids) . ") "; - } else { - return array(); - } - } - if (!empty($object_guid)) - if (!is_array($object_guid)) { - $where[] = " object_guid = {$object_guid} "; - } else { - $where[] = " object_guid in (" . implode(',',$object_guid) . ") "; - } - if (!empty($type)) $where[] = " type = '{$type}' "; - if (!empty($subtype)) $where[] = " subtype = '{$subtype}' "; - if (!empty($action_type)) $where[] = " action_type = '{$action_type}' "; - if (!empty($posted_min)) $where[] = " posted > {$posted_min} "; - if (!empty($posted_max)) $where[] = " posted < {$posted_max} "; - - $whereclause = implode(' and ', $where); - - // Construct main SQL - $sql = "select id,type,subtype,action_type,access_id,view,subject_guid,object_guid,posted from {$CONFIG->dbprefix}river where {$whereclause} order by posted desc limit {$offset},{$limit}"; - - // Get data - return get_data($sql); - - } - - /** - * Returns a human-readable representation of a river item - * - * @see get_river_items - * - * @param stdClass $item A river item object as returned from get_river_items - * @return string|false Depending on success - */ - function elgg_view_river_item($item) { - if (isset($item->view)) { - - $object = get_entity($item->object_guid); - if (!$object) { - $body = elgg_view('river/item/noaccess'); - } else { - if (elgg_view_exists($item->view)) { - $body = elgg_view($item->view,array( - 'item' => $item - )); - } - } - return elgg_view('river/item/wrapper',array( - 'item' => $item, - 'body' => $body - )); - - } - return false; - } - - /** - * Returns a human-readable version of the river. - * - * @param int|array $subject_guid Acting entity to restrict to. Default: all - * @param int|array $object_guid Entity being acted on to restrict to. Default: all - * @param string $subject_relationship If set to a relationship type, this will use $subject_guid as the starting point and set the subjects to be all users this entity has this relationship with (eg 'friend'). Default: blank - * @param string $type The type of entity to restrict to. Default: all - * @param string $subtype The subtype of entity to restrict to. Default: all - * @param string $action_type The type of river action to restrict to. Default: all - * @param int $limit The number of items to retrieve. Default: 20 - * @param int $posted_min The minimum time period to look at. Default: none - * @param int $posted_max The maximum time period to look at. Default: none - * @return string Human-readable river. - */ - function elgg_view_river_items($subject_guid = 0, - $object_guid = 0, - $subject_relationship = '', - $type = '', - $subtype = '', - $action_type = '', - $limit = 20, - $posted_min = 0, - $posted_max = 0, - $pagination = true) { - - // Get input from outside world and sanitise it - $offset = (int) get_input('offset',0); - - // Get river items, if they exist - if ($riveritems = get_river_items($subject_guid,$object_guid,$subject_relationship,$type,$subtype,$action_type,($limit + 1),$offset,$posted_min,$posted_max)) { - - return elgg_view('river/item/list',array( - 'limit' => $limit, - 'offset' => $offset, - 'items' => $riveritems, - 'pagination' => $pagination - )); - - } - - return ''; - - } - ?> \ No newline at end of file diff --git a/engine/lib/sessions.php b/engine/lib/sessions.php index fd569a0e1..18fb9e73c 100644 --- a/engine/lib/sessions.php +++ b/engine/lib/sessions.php @@ -1,19 +1,19 @@ -guid > 0)) + + if ((isset($user)) && ($user instanceof ElggUser) && ($user->guid > 0)) return true; - - return false; - - } + + return false; + + } /** * Returns whether or not the user is currently logged in and that they are an admin user. @@ -155,24 +155,24 @@ return false; } - - /** - * Perform standard authentication with a given username and password. - * Returns an ElggUser object for use with login. - * - * @see login - * @param string $username The username, optionally (for standard logins) - * @param string $password The password, optionally (for standard logins) - * @return ElggUser|false The authenticated user object, or false on failure. - */ - - function authenticate($username, $password) { + + /** + * Perform standard authentication with a given username and password. + * Returns an ElggUser object for use with login. + * + * @see login + * @param string $username The username, optionally (for standard logins) + * @param string $password The password, optionally (for standard logins) + * @return ElggUser|false The authenticated user object, or false on failure. + */ + + function authenticate($username, $password) { if (pam_authenticate(array('username' => $username, 'password' => $password))) - return get_user_by_username($username); - - return false; - + return get_user_by_username($username); + + return false; + } /** @@ -198,9 +198,9 @@ // Let admins log in without validating their email, but normal users must have validated their email or been admin created if ((!$user->admin) && (!$user->validated) && (!$user->admin_created)) return false; - - // User has been banned, so bin them. - if ($user->isBanned()) return false; + + // User has been banned, so bin them. + if ($user->isBanned()) return false; if ($user->password == generate_user_password($user, $credentials['password'])) @@ -274,52 +274,52 @@ } return false; - } - - /** - * Logs in a specified ElggUser. For standard registration, use in conjunction - * with authenticate. - * - * @see authenticate - * @param ElggUser $user A valid Elgg user object - * @param boolean $persistent Should this be a persistent login? - * @return true|false Whether login was successful - */ - function login(ElggUser $user, $persistent = false) { - + } + + /** + * Logs in a specified ElggUser. For standard registration, use in conjunction + * with authenticate. + * + * @see authenticate + * @param ElggUser $user A valid Elgg user object + * @param boolean $persistent Should this be a persistent login? + * @return true|false Whether login was successful + */ + function login(ElggUser $user, $persistent = false) { + global $CONFIG; if ($user->isBanned()) return false; // User is banned, return false. if (check_rate_limit_exceeded($user->guid)) return false; // Check rate limit - - $_SESSION['user'] = $user; - $_SESSION['guid'] = $user->getGUID(); - $_SESSION['id'] = $_SESSION['guid']; - $_SESSION['username'] = $user->username; - $_SESSION['name'] = $user->name; - - $code = (md5($user->name . $user->username . time() . rand())); - - $user->code = md5($code); - - $_SESSION['code'] = $code; - - if (($persistent)) - setcookie("elggperm", $code, (time()+(86400 * 30)),"/"); - - if (!$user->save() || !trigger_elgg_event('login','user',$user)) { - unset($_SESSION['username']); - unset($_SESSION['name']); - unset($_SESSION['code']); - unset($_SESSION['guid']); - unset($_SESSION['id']); - unset($_SESSION['user']); - setcookie("elggperm", "", (time()-(86400 * 30)),"/"); - return false; + + $_SESSION['user'] = $user; + $_SESSION['guid'] = $user->getGUID(); + $_SESSION['id'] = $_SESSION['guid']; + $_SESSION['username'] = $user->username; + $_SESSION['name'] = $user->name; + + $code = (md5($user->name . $user->username . time() . rand())); + + $user->code = md5($code); + + $_SESSION['code'] = $code; + + if (($persistent)) + setcookie("elggperm", $code, (time()+(86400 * 30)),"/"); + + if (!$user->save() || !trigger_elgg_event('login','user',$user)) { + unset($_SESSION['username']); + unset($_SESSION['name']); + unset($_SESSION['code']); + unset($_SESSION['guid']); + unset($_SESSION['id']); + unset($_SESSION['user']); + setcookie("elggperm", "", (time()-(86400 * 30)),"/"); + return false; } // Users privilege has been elevated, so change the session id (help prevent session hijacking) - session_regenerate_id(); + session_regenerate_id(); // Update statistics set_last_login($_SESSION['guid']); @@ -330,37 +330,37 @@ global $is_admin; $is_admin = true; } - - return true; - - } - - /** - * Log the current user out - * - * @return true|false - */ - function logout() { - global $CONFIG; - - if (isset($_SESSION['user'])) { - if (!trigger_elgg_event('logout','user',$_SESSION['user'])) return false; - $_SESSION['user']->code = ""; - $_SESSION['user']->save(); + + return true; + + } + + /** + * Log the current user out + * + * @return true|false + */ + function logout() { + global $CONFIG; + + if (isset($_SESSION['user'])) { + if (!trigger_elgg_event('logout','user',$_SESSION['user'])) return false; + $_SESSION['user']->code = ""; + $_SESSION['user']->save(); } - - unset($_SESSION['username']); - unset($_SESSION['name']); - unset($_SESSION['code']); - unset($_SESSION['guid']); - unset($_SESSION['id']); - unset($_SESSION['user']); - + + unset($_SESSION['username']); + unset($_SESSION['name']); + unset($_SESSION['code']); + unset($_SESSION['guid']); + unset($_SESSION['id']); + unset($_SESSION['user']); + setcookie("elggperm", "", (time()-(86400 * 30)),"/"); - session_destroy(); - - return true; + session_destroy(); + + return true; } function get_session_fingerprint() @@ -368,33 +368,33 @@ global $CONFIG; return md5($_SERVER['HTTP_USER_AGENT'] . get_site_secret()); - } - - /** - * Initialises the system session and potentially logs the user in - * - * This function looks for: - * - * 1. $_SESSION['id'] - if not present, we're logged out, and this is set to 0 - * 2. The cookie 'elggperm' - if present, checks it for an authentication token, validates it, and potentially logs the user in - * - * @uses $_SESSION - * @param unknown_type $event - * @param unknown_type $object_type - * @param unknown_type $object - */ - function session_init($event, $object_type, $object) { + } + + /** + * Initialises the system session and potentially logs the user in + * + * This function looks for: + * + * 1. $_SESSION['id'] - if not present, we're logged out, and this is set to 0 + * 2. The cookie 'elggperm' - if present, checks it for an authentication token, validates it, and potentially logs the user in + * + * @uses $_SESSION + * @param unknown_type $event + * @param unknown_type $object_type + * @param unknown_type $object + */ + function session_init($event, $object_type, $object) { global $DB_PREFIX, $CONFIG; - + if (!is_db_installed()) return false; // Use database for sessions $DB_PREFIX = $CONFIG->dbprefix; // HACK to allow access to prefix after object distruction if ((!isset($CONFIG->use_file_sessions))) session_set_save_handler("__elgg_session_open", "__elgg_session_close", "__elgg_session_read", "__elgg_session_write", "__elgg_session_destroy", "__elgg_session_gc"); - - session_name('Elgg'); + + session_name('Elgg'); session_start(); // Do some sanity checking by generating a fingerprint (makes some XSS attacks harder) @@ -413,50 +413,50 @@ // Generate a simple token (private from potentially public session id) if (!isset($_SESSION['__elgg_session'])) $_SESSION['__elgg_session'] = md5(microtime().rand()); - - if (empty($_SESSION['guid'])) { - if (isset($_COOKIE['elggperm'])) { - $code = $_COOKIE['elggperm']; - $code = md5($code); - unset($_SESSION['guid']);//$_SESSION['guid'] = 0; - unset($_SESSION['id']);//$_SESSION['id'] = 0; - if ($user = get_user_by_code($code)) { - $_SESSION['user'] = $user; - $_SESSION['id'] = $user->getGUID(); - $_SESSION['guid'] = $_SESSION['id']; - $_SESSION['code'] = $_COOKIE['elggperm']; - } + + if (empty($_SESSION['guid'])) { + if (isset($_COOKIE['elggperm'])) { + $code = $_COOKIE['elggperm']; + $code = md5($code); + unset($_SESSION['guid']);//$_SESSION['guid'] = 0; + unset($_SESSION['id']);//$_SESSION['id'] = 0; + if ($user = get_user_by_code($code)) { + $_SESSION['user'] = $user; + $_SESSION['id'] = $user->getGUID(); + $_SESSION['guid'] = $_SESSION['id']; + $_SESSION['code'] = $_COOKIE['elggperm']; + } } else { - unset($_SESSION['id']); //$_SESSION['id'] = 0; + unset($_SESSION['id']); //$_SESSION['id'] = 0; unset($_SESSION['guid']);//$_SESSION['guid'] = 0; - unset($_SESSION['code']);//$_SESSION['code'] = ""; - } - } else { - if (!empty($_SESSION['code'])) { - $code = md5($_SESSION['code']); - if ($user = get_user_by_code($code)) { + unset($_SESSION['code']);//$_SESSION['code'] = ""; + } + } else { + if (!empty($_SESSION['code'])) { + $code = md5($_SESSION['code']); + if ($user = get_user_by_code($code)) { $_SESSION['user'] = $user; $_SESSION['id'] = $user->getGUID(); - $_SESSION['guid'] = $_SESSION['id']; - } else { - unset($_SESSION['user']); + $_SESSION['guid'] = $_SESSION['id']; + } else { + unset($_SESSION['user']); unset($_SESSION['id']); //$_SESSION['id'] = 0; unset($_SESSION['guid']);//$_SESSION['guid'] = 0; - unset($_SESSION['code']);//$_SESSION['code'] = ""; - } + unset($_SESSION['code']);//$_SESSION['code'] = ""; + } } else { - //$_SESSION['user'] = new ElggDummy(); + //$_SESSION['user'] = new ElggDummy(); unset($_SESSION['id']); //$_SESSION['id'] = 0; unset($_SESSION['guid']);//$_SESSION['guid'] = 0; - unset($_SESSION['code']);//$_SESSION['code'] = ""; - } - } - if ($_SESSION['id'] > 0) { - set_last_action($_SESSION['id']); - } - - register_action("login",true); - register_action("logout"); + unset($_SESSION['code']);//$_SESSION['code'] = ""; + } + } + if ($_SESSION['id'] > 0) { + set_last_action($_SESSION['id']); + } + + register_action("login",true); + register_action("logout"); // Register a default PAM handler register_pam_handler('pam_auth_userpass'); @@ -470,24 +470,24 @@ { session_destroy(); return false; - } - - // Since we have loaded a new user, this user may have different language preferences + } + + // Since we have loaded a new user, this user may have different language preferences register_translations(dirname(dirname(dirname(__FILE__))) . "/languages/"); - - return true; - + + return true; + } - - /** - * Used at the top of a page to mark it as logged in users only. - * - */ - function gatekeeper() { - if (!isloggedin()) { - $_SESSION['last_forward_from'] = current_page_url(); - forward(); - } + + /** + * Used at the top of a page to mark it as logged in users only. + * + */ + function gatekeeper() { + if (!isloggedin()) { + $_SESSION['last_forward_from'] = current_page_url(); + forward(); + } } /** @@ -497,11 +497,11 @@ function admin_gatekeeper() { gatekeeper(); - if (!isadminloggedin()) { - $_SESSION['last_forward_from'] = current_page_url(); - forward(); + if (!isadminloggedin()) { + $_SESSION['last_forward_from'] = current_page_url(); + forward(); } - } + } /** * DB Based session handling code. @@ -627,8 +627,8 @@ return true; } - - register_elgg_event_handler("boot","system","session_init",20); - - + + register_elgg_event_handler("boot","system","session_init",20); + + ?> \ No newline at end of file diff --git a/engine/lib/sites.php b/engine/lib/sites.php index c088e2476..14cc2039d 100644 --- a/engine/lib/sites.php +++ b/engine/lib/sites.php @@ -1,16 +1,16 @@ - + /** + * Elgg sites + * Functions to manage multiple or single sites in an Elgg install + * + * @package Elgg + * @subpackage Core - * @link http://elgg.org/ - */ + * @author Curverider Ltd + + * @link http://elgg.org/ + */ /** * ElggSite @@ -280,7 +280,7 @@ if ($row) { - // Exists and you have access to it + // Exists and you have access to it if ($exists = get_data_row("SELECT guid from {$CONFIG->dbprefix}sites_entity where guid = {$guid}")) { $result = update_data("UPDATE {$CONFIG->dbprefix}sites_entity set name='$name', description='$description', url='$url' where guid=$guid"); if ($result!=false) @@ -293,7 +293,7 @@ $entity->delete(); //delete_entity($guid); } - } + } } else { @@ -372,25 +372,25 @@ $offset = (int)$offset; return get_entities_from_relationship("member_of_site", $site_guid, true, "user", "", 0, "time_created desc", $limit, $offset); - } - - /** - * Display a list of site members - * - * @param int $site_guid The GUID of the site - * @param int $limit The number of members to display on a page - * @param true|false $fullview Whether or not to display the full view (default: true) - * @return string A displayable list of members - */ - function list_site_members($site_guid, $limit = 10, $fullview = true) { - - $offset = (int) get_input('offset'); - $limit = (int) $limit; - $count = (int) get_entities_from_relationship("member_of_site", $site_guid, true, "user", "", 0, "time_created desc", $limit, $offset, true); - $entities = get_site_members($site_guid, $limit, $offset); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview); - + } + + /** + * Display a list of site members + * + * @param int $site_guid The GUID of the site + * @param int $limit The number of members to display on a page + * @param true|false $fullview Whether or not to display the full view (default: true) + * @return string A displayable list of members + */ + function list_site_members($site_guid, $limit = 10, $fullview = true) { + + $offset = (int) get_input('offset'); + $limit = (int) $limit; + $count = (int) get_entities_from_relationship("member_of_site", $site_guid, true, "user", "", 0, "time_created desc", $limit, $offset, true); + $entities = get_site_members($site_guid, $limit, $offset); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview); + } /** @@ -439,8 +439,8 @@ $offset = (int)$offset; return get_entities_from_relationship("member_of_site", $site_guid, true, "object", $subtype, 0, "time_created desc", $limit, $offset); - } - + } + /** * Add a collection to a site. * @@ -567,43 +567,43 @@ return false; } - - /** - * Initialise site handling - * - * Called at the beginning of system running, to set the ID of the current site. - * This is 0 by default, but plugins may alter this behaviour by attaching functions - * to the sites init event and changing $CONFIG->site_id. - * - * @uses $CONFIG - * @param string $event Event API required parameter - * @param string $object_type Event API required parameter - * @param null $object Event API required parameter - * @return true - */ - function sites_init($event, $object_type, $object) { - - global $CONFIG; - + + /** + * Initialise site handling + * + * Called at the beginning of system running, to set the ID of the current site. + * This is 0 by default, but plugins may alter this behaviour by attaching functions + * to the sites init event and changing $CONFIG->site_id. + * + * @uses $CONFIG + * @param string $event Event API required parameter + * @param string $object_type Event API required parameter + * @param null $object Event API required parameter + * @return true + */ + function sites_init($event, $object_type, $object) { + + global $CONFIG; + if (is_installed() && is_db_installed()) { - - $site = trigger_plugin_hook("siteid","system"); - if ($site === null || $site === false) { - $CONFIG->site_id = (int) datalist_get('default_site'); - } else { - $CONFIG->site_id = $site; - } - $CONFIG->site_guid = $CONFIG->site_id; - $CONFIG->site = get_entity($CONFIG->site_guid); - - return true; + + $site = trigger_plugin_hook("siteid","system"); + if ($site === null || $site === false) { + $CONFIG->site_id = (int) datalist_get('default_site'); + } else { + $CONFIG->site_id = $site; + } + $CONFIG->site_guid = $CONFIG->site_id; + $CONFIG->site = get_entity($CONFIG->site_guid); + + return true; } - return true; - } - - // Register event handlers - - register_elgg_event_handler('boot','system','sites_init',2); - + return true; + } + + // Register event handlers + + register_elgg_event_handler('boot','system','sites_init',2); + ?> \ No newline at end of file diff --git a/engine/lib/social.php b/engine/lib/social.php index b00b56d79..e8bfccda5 100644 --- a/engine/lib/social.php +++ b/engine/lib/social.php @@ -1,76 +1,76 @@ -wordblacklist)) - return $input; - - if (strlen($input) < 3 || in_array($input,$CONFIG->wordblacklist)) - return false; - - return true; - - } - + * @author Curverider + + * @link http://elgg.org/ + + /** + * Filters a string into an array of significant words + * + * @param string $string + * @return array + */ + function filter_string($string) { + + // Convert it to lower and trim + $string = strtolower($string); + $string = trim($string); + + // Remove links and email addresses + // match protocol://address/path/file.extension?some=variable&another=asf% + $string = preg_replace("/\s([a-zA-Z]+:\/\/[a-z][a-z0-9\_\.\-]*[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%\=]*)([\s|\.|\,])/iu"," ", $string); + // match www.something.domain/path/file.extension?some=variable&another=asf% + $string = preg_replace("/\s(www\.[a-z][a-z0-9\_\.\-]*[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%\=]*)([\s|\.|\,])/iu"," ", $string); + // match name@address + $string = preg_replace("/\s([a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]*\@[a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]{2,6})([\s|\.|\,])/iu"," ", $string); + + // Sanitise the string; remove unwanted characters + $string = preg_replace('/\W/ui', ' ', $string); + + // Explode it into an array + $terms = explode(' ',$string); + + // Remove any blacklist terms + //$terms = array_filter($terms, 'remove_blacklist'); + + return $terms; + + } + + /** + * Returns true if the word in $input is considered significant + * + * @param string $input + * @return true|false + */ + function remove_blacklist($input) { + + global $CONFIG; + + if (!is_array($CONFIG->wordblacklist)) + return $input; + + if (strlen($input) < 3 || in_array($input,$CONFIG->wordblacklist)) + return false; + + return true; + + } + /** * Initialise. * * Sets a blacklist of words in the current language. This is a comma separated list in word:blacklist. - */ - function social_init() { + */ + function social_init() { global $CONFIG; $CONFIG->wordblacklist = array(); @@ -83,46 +83,46 @@ } else { - // Fallback - shouldn't happen - $CONFIG->wordblacklist = array( - 'and', - 'the', - 'then', - 'but', - 'she', - 'his', - 'her', - 'him', - 'one', - 'not', - 'also', - 'about', - 'now', - 'hence', - 'however', - 'still', - 'likewise', - 'otherwise', - 'therefore', - 'conversely', - 'rather', - 'consequently', - 'furthermore', - 'nevertheless', - 'instead', - 'meanwhile', - 'accordingly', - 'this', - 'seems', - 'what', - 'whom', - 'whose', - 'whoever', - 'whomever', + // Fallback - shouldn't happen + $CONFIG->wordblacklist = array( + 'and', + 'the', + 'then', + 'but', + 'she', + 'his', + 'her', + 'him', + 'one', + 'not', + 'also', + 'about', + 'now', + 'hence', + 'however', + 'still', + 'likewise', + 'otherwise', + 'therefore', + 'conversely', + 'rather', + 'consequently', + 'furthermore', + 'nevertheless', + 'instead', + 'meanwhile', + 'accordingly', + 'this', + 'seems', + 'what', + 'whom', + 'whose', + 'whoever', + 'whomever', ); - } - } - - register_elgg_event_handler("init","system","social_init"); - + } + } + + register_elgg_event_handler("init","system","social_init"); + ?> \ No newline at end of file diff --git a/engine/lib/statistics.php b/engine/lib/statistics.php index b79938aab..24d2e4155 100644 --- a/engine/lib/statistics.php +++ b/engine/lib/statistics.php @@ -79,8 +79,8 @@ * Return a list of how many users are currently online, rendered as a view. */ function get_online_users() - { - $offset = get_input('offset',0); + { + $offset = get_input('offset',0); $count = count(find_active_users(600,9999)); $objects = find_active_users(600,10,$offset); diff --git a/engine/lib/tags.php b/engine/lib/tags.php index 8fdb6ecb7..d3db842d1 100644 --- a/engine/lib/tags.php +++ b/engine/lib/tags.php @@ -1,138 +1,138 @@ - + * @author Curverider Ltd - * @link http://elgg.org/ - */ - - - /** - * The algorithm working out the size of font based on the number of tags. - * This is quick and dirty. - */ - function calculate_tag_size($min, $max, $number_of_tags, $buckets = 6) - { - - $delta = (($max - $min) / $buckets); - $thresholds = array(); - - for ($n=1; $n <= $buckets; $n++) { - $thresholds[$n-1] = ($min + $n) * $delta; - } - - // Correction - if ($thresholds[$buckets-1]>$max) $thresholds[$buckets-1] = $max; - - $size = 0; - for ($n = 0; $n < count($thresholds); $n++) { - if ($number_of_tags >= $thresholds[$n]) - $size = $n; - } - - return $size; - } - - /** - * This function generates an array of tags with a weighting. - * - * @param array $tags The array of tags. - * @return An associated array of tags with a weighting, this can then be mapped to a display class. - */ - function generate_tag_cloud(array $tags, $buckets = 6) - { - $cloud = array(); - - $min = 65535; - $max = 0; - - foreach ($tags as $tag) - { - $cloud[$tag]++; - - if ($cloud[$tag]>$max) $max = $cloud[$tag]; - if ($cloud[$tag]<$min) $min = $cloud[$tag]; - } - - foreach ($cloud as $k => $v) - $cloud[$k] = calculate_tag_size($min, $max, $v, $buckets); - - return $cloud; - } - - /** - * Get an array of tags with weights for use with the output/tagcloud view. - * - * @param int $threshold Get the threshold of minimum number of each tags to bother with (ie only show tags where there are more than $threshold occurances) - * @param int $limit Number of tags to return - * @param string $metadata_name Optionally, the name of the field you want to grab for - * @param string $entity_type Optionally, the entity type ('object' etc) - * @param string $entity_subtype The entity subtype, optionally - * @param int $owner_guid The GUID of the tags owner, optionally + * @link http://elgg.org/ + */ + + + /** + * The algorithm working out the size of font based on the number of tags. + * This is quick and dirty. + */ + function calculate_tag_size($min, $max, $number_of_tags, $buckets = 6) + { + + $delta = (($max - $min) / $buckets); + $thresholds = array(); + + for ($n=1; $n <= $buckets; $n++) { + $thresholds[$n-1] = ($min + $n) * $delta; + } + + // Correction + if ($thresholds[$buckets-1]>$max) $thresholds[$buckets-1] = $max; + + $size = 0; + for ($n = 0; $n < count($thresholds); $n++) { + if ($number_of_tags >= $thresholds[$n]) + $size = $n; + } + + return $size; + } + + /** + * This function generates an array of tags with a weighting. + * + * @param array $tags The array of tags. + * @return An associated array of tags with a weighting, this can then be mapped to a display class. + */ + function generate_tag_cloud(array $tags, $buckets = 6) + { + $cloud = array(); + + $min = 65535; + $max = 0; + + foreach ($tags as $tag) + { + $cloud[$tag]++; + + if ($cloud[$tag]>$max) $max = $cloud[$tag]; + if ($cloud[$tag]<$min) $min = $cloud[$tag]; + } + + foreach ($cloud as $k => $v) + $cloud[$k] = calculate_tag_size($min, $max, $v, $buckets); + + return $cloud; + } + + /** + * Get an array of tags with weights for use with the output/tagcloud view. + * + * @param int $threshold Get the threshold of minimum number of each tags to bother with (ie only show tags where there are more than $threshold occurances) + * @param int $limit Number of tags to return + * @param string $metadata_name Optionally, the name of the field you want to grab for + * @param string $entity_type Optionally, the entity type ('object' etc) + * @param string $entity_subtype The entity subtype, optionally + * @param int $owner_guid The GUID of the tags owner, optionally * @param int $site_guid Optionally, the site to restrict to (default is the current site) * @param int $start_ts Optionally specify a start timestamp for tags used to generate cloud. - * @param int $ent_ts Optionally specify an end timestamp for tags used to generate cloud. - * @return array|false Array of objects with ->tag and ->total values, or false on failure - */ - - function get_tags($threshold = 1, $limit = 10, $metadata_name = "", $entity_type = "object", $entity_subtype = "", $owner_guid = "", $site_guid = -1, $start_ts = "", $end_ts = "") { - - global $CONFIG; - - $threshold = (int) $threshold; - $limit = (int) $limit; - - if (!empty($metadata_name)) { - $metadata_name = (int) get_metastring_id($metadata_name); - } else { - $metadata_name = 0; - } - $entity_subtype = get_subtype_id($entity_type, $entity_subtype); - $entity_type = sanitise_string($entity_type); - - if ($owner_guid != "") - if (is_array($owner_guid)) { - foreach($owner_guid as $key => $val) - $owner_guid[$key] = (int) $val; - } else { - $owner_guid = (int) $owner_guid; - } - - if ($site_guid < 0) { - $site_guid = $CONFIG->site_id; - } - - //$access = get_access_list(); - - $query = "SELECT msvalue.string as tag, count(msvalue.id) as total "; + * @param int $ent_ts Optionally specify an end timestamp for tags used to generate cloud. + * @return array|false Array of objects with ->tag and ->total values, or false on failure + */ + + function get_tags($threshold = 1, $limit = 10, $metadata_name = "", $entity_type = "object", $entity_subtype = "", $owner_guid = "", $site_guid = -1, $start_ts = "", $end_ts = "") { + + global $CONFIG; + + $threshold = (int) $threshold; + $limit = (int) $limit; + + if (!empty($metadata_name)) { + $metadata_name = (int) get_metastring_id($metadata_name); + } else { + $metadata_name = 0; + } + $entity_subtype = get_subtype_id($entity_type, $entity_subtype); + $entity_type = sanitise_string($entity_type); + + if ($owner_guid != "") + if (is_array($owner_guid)) { + foreach($owner_guid as $key => $val) + $owner_guid[$key] = (int) $val; + } else { + $owner_guid = (int) $owner_guid; + } + + if ($site_guid < 0) { + $site_guid = $CONFIG->site_id; + } + + //$access = get_access_list(); + + $query = "SELECT msvalue.string as tag, count(msvalue.id) as total "; $query .= "FROM {$CONFIG->dbprefix}entities e join {$CONFIG->dbprefix}metadata md on md.entity_guid = e.guid "; - if ($entity_subtype > 0) - $query .= " join {$CONFIG->dbprefix}entity_subtypes subtype on subtype.id = e.subtype "; - $query .= " join {$CONFIG->dbprefix}metastrings msvalue on msvalue.id = md.value_id "; - - $query .= " where msvalue.string != '' "; - - if ($metadata_name > 0) { - $query .= " and md.name_id = {$metadata_name} "; - } - if ($site_guid > 0) { - $query .= " and e.site_guid = {$site_guid} "; - } - if ($entity_subtype > 0) { - $query .= " and e.subtype = {$entity_subtype} "; - } - if ($entity_type != "") { - $query .= " and e.type = '{$entity_type}' "; - } - if (is_array($owner_guid)) { - $query .= " and e.container_guid in (".implode(",",$owner_guid).")"; - } else if (is_int($owner_guid)) { - $query .= " and e.container_guid = {$owner_guid} "; + if ($entity_subtype > 0) + $query .= " join {$CONFIG->dbprefix}entity_subtypes subtype on subtype.id = e.subtype "; + $query .= " join {$CONFIG->dbprefix}metastrings msvalue on msvalue.id = md.value_id "; + + $query .= " where msvalue.string != '' "; + + if ($metadata_name > 0) { + $query .= " and md.name_id = {$metadata_name} "; + } + if ($site_guid > 0) { + $query .= " and e.site_guid = {$site_guid} "; + } + if ($entity_subtype > 0) { + $query .= " and e.subtype = {$entity_subtype} "; + } + if ($entity_type != "") { + $query .= " and e.type = '{$entity_type}' "; + } + if (is_array($owner_guid)) { + $query .= " and e.container_guid in (".implode(",",$owner_guid).")"; + } else if (is_int($owner_guid)) { + $query .= " and e.container_guid = {$owner_guid} "; } if ($start_ts) { $start_ts = (int)$start_ts; @@ -142,35 +142,35 @@ if ($end_ts) { $end_ts = (int)$end_ts; $query .= " and e.time_created<=$end_ts"; - } - - //$userid = get_loggedin_userid(); - //$query .= " and (e.access_id in {$access} or (e.access_id = " . ACCESS_PRIVATE . " and e.owner_guid = {$userid}))"; - $query .= ' and ' . get_access_sql_suffix("e"); // Add access controls - - $query .= " group by msvalue.string having total > {$threshold} order by total desc limit {$limit} "; - - return get_data($query); - - } - - /** - * Loads and displays a tagcloud given particular criteria. - * - * @param int $threshold Get the threshold of minimum number of each tags to bother with (ie only show tags where there are more than $threshold occurances) - * @param int $limit Number of tags to return - * @param string $metadata_name Optionally, the name of the field you want to grab for - * @param string $entity_type Optionally, the entity type ('object' etc) - * @param string $entity_subtype The entity subtype, optionally - * @param int $owner_guid The GUID of the tags owner, optionally - * @param int $site_guid Optionally, the site to restrict to (default is the current site) - * @return string THe HTML (or other, depending on view type) of the tagcloud. - */ - - function display_tagcloud($threshold = 1, $limit = 10, $metadata_name = "", $entity_type = "object", $entity_subtype = "", $owner_guid = "", $site_guid = -1) { - - return elgg_view("output/tagcloud",array('value' => get_tags($threshold, $limit, $metadata_name, $entity_type, $entity_subtype, $owner_guid, $site_guid),'object' => $entity_type, 'subtype' => $entity_subtype)); - - } - + } + + //$userid = get_loggedin_userid(); + //$query .= " and (e.access_id in {$access} or (e.access_id = " . ACCESS_PRIVATE . " and e.owner_guid = {$userid}))"; + $query .= ' and ' . get_access_sql_suffix("e"); // Add access controls + + $query .= " group by msvalue.string having total > {$threshold} order by total desc limit {$limit} "; + + return get_data($query); + + } + + /** + * Loads and displays a tagcloud given particular criteria. + * + * @param int $threshold Get the threshold of minimum number of each tags to bother with (ie only show tags where there are more than $threshold occurances) + * @param int $limit Number of tags to return + * @param string $metadata_name Optionally, the name of the field you want to grab for + * @param string $entity_type Optionally, the entity type ('object' etc) + * @param string $entity_subtype The entity subtype, optionally + * @param int $owner_guid The GUID of the tags owner, optionally + * @param int $site_guid Optionally, the site to restrict to (default is the current site) + * @return string THe HTML (or other, depending on view type) of the tagcloud. + */ + + function display_tagcloud($threshold = 1, $limit = 10, $metadata_name = "", $entity_type = "object", $entity_subtype = "", $owner_guid = "", $site_guid = -1) { + + return elgg_view("output/tagcloud",array('value' => get_tags($threshold, $limit, $metadata_name, $entity_type, $entity_subtype, $owner_guid, $site_guid),'object' => $entity_type, 'subtype' => $entity_subtype)); + + } + ?> \ No newline at end of file diff --git a/engine/lib/upgrades/2008101303.php b/engine/lib/upgrades/2008101303.php index ac189b956..c98eace74 100644 --- a/engine/lib/upgrades/2008101303.php +++ b/engine/lib/upgrades/2008101303.php @@ -1,11 +1,11 @@ -guid, true, 'email'); - } - } - +guid, true, 'email'); + } + } + ?> \ No newline at end of file diff --git a/engine/lib/users.php b/engine/lib/users.php index b56ecdcf6..e086c8236 100644 --- a/engine/lib/users.php +++ b/engine/lib/users.php @@ -1,148 +1,148 @@ -attributes['type'] = "user"; + $this->attributes['name'] = ""; + $this->attributes['username'] = ""; + $this->attributes['password'] = ""; + $this->attributes['salt'] = ""; + $this->attributes['email'] = ""; + $this->attributes['language'] = ""; + $this->attributes['code'] = ""; + $this->attributes['banned'] = "no"; + $this->attributes['tables_split'] = 2; + } + + /** + * Construct a new user entity, optionally from a given id value. + * + * @param mixed $guid If an int, load that GUID. + * If a db row then will attempt to load the rest of the data. + * @throws Exception if there was a problem creating the user. + */ + function __construct($guid = null) + { + $this->initialise_attributes(); + + if (!empty($guid)) + { + // Is $guid is a DB row - either a entity row, or a user table row. + if ($guid instanceof stdClass) { + // Load the rest + if (!$this->load($guid->guid)) + throw new IOException(sprintf(elgg_echo('IOException:FailedToLoadGUID'), get_class(), $guid->guid)); + } + + // See if this is a username + else if (is_string($guid)) + { + $guid = get_user_by_username($guid); + foreach ($guid->attributes as $key => $value) + $this->attributes[$key] = $value; + + } + + // Is $guid is an ElggUser? Use a copy constructor + else if ($guid instanceof ElggUser) + { + foreach ($guid->attributes as $key => $value) + $this->attributes[$key] = $value; + } + + // Is this is an ElggEntity but not an ElggUser = ERROR! + else if ($guid instanceof ElggEntity) + throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonElggUser')); + + // We assume if we have got this far, $guid is an int + else if (is_numeric($guid)) { + if (!$this->load($guid)) IOException(sprintf(elgg_echo('IOException:FailedToLoadGUID'), get_class(), $guid)); + } + + else + throw new InvalidParameterException(elgg_echo('InvalidParameterException:UnrecognisedValue')); + } + } + + /** + * Override the load function. + * This function will ensure that all data is loaded (were possible), so + * if only part of the ElggUser is loaded, it'll load the rest. + * + * @param int $guid + * @return true|false + */ + protected function load($guid) + { + // Test to see if we have the generic stuff + if (!parent::load($guid)) + return false; - * @link http://elgg.org/ - */ - - /// Map a username to a cached GUID - $USERNAME_TO_GUID_MAP_CACHE = array(); - - /// Map a user code to a cached GUID - $CODE_TO_GUID_MAP_CACHE = array(); - - /** - * ElggUser - * - * Representation of a "user" in the system. - * - * @package Elgg - * @subpackage Core - */ - class ElggUser extends ElggEntity - implements Friendable - { - /** - * Initialise the attributes array. - * This is vital to distinguish between metadata and base parameters. - * - * Place your base parameters here. - */ - protected function initialise_attributes() - { - parent::initialise_attributes(); - - $this->attributes['type'] = "user"; - $this->attributes['name'] = ""; - $this->attributes['username'] = ""; - $this->attributes['password'] = ""; - $this->attributes['salt'] = ""; - $this->attributes['email'] = ""; - $this->attributes['language'] = ""; - $this->attributes['code'] = ""; - $this->attributes['banned'] = "no"; - $this->attributes['tables_split'] = 2; - } - - /** - * Construct a new user entity, optionally from a given id value. - * - * @param mixed $guid If an int, load that GUID. - * If a db row then will attempt to load the rest of the data. - * @throws Exception if there was a problem creating the user. - */ - function __construct($guid = null) - { - $this->initialise_attributes(); - - if (!empty($guid)) - { - // Is $guid is a DB row - either a entity row, or a user table row. - if ($guid instanceof stdClass) { - // Load the rest - if (!$this->load($guid->guid)) - throw new IOException(sprintf(elgg_echo('IOException:FailedToLoadGUID'), get_class(), $guid->guid)); - } - - // See if this is a username - else if (is_string($guid)) - { - $guid = get_user_by_username($guid); - foreach ($guid->attributes as $key => $value) - $this->attributes[$key] = $value; - - } - - // Is $guid is an ElggUser? Use a copy constructor - else if ($guid instanceof ElggUser) - { - foreach ($guid->attributes as $key => $value) - $this->attributes[$key] = $value; - } - - // Is this is an ElggEntity but not an ElggUser = ERROR! - else if ($guid instanceof ElggEntity) - throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonElggUser')); - - // We assume if we have got this far, $guid is an int - else if (is_numeric($guid)) { - if (!$this->load($guid)) IOException(sprintf(elgg_echo('IOException:FailedToLoadGUID'), get_class(), $guid)); - } - - else - throw new InvalidParameterException(elgg_echo('InvalidParameterException:UnrecognisedValue')); - } - } - - /** - * Override the load function. - * This function will ensure that all data is loaded (were possible), so - * if only part of the ElggUser is loaded, it'll load the rest. - * - * @param int $guid - * @return true|false - */ - protected function load($guid) - { - // Test to see if we have the generic stuff - if (!parent::load($guid)) - return false; - - // Check the type - if ($this->attributes['type']!='user') - throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $guid, get_class())); - - // Load missing data - $row = get_user_entity_as_row($guid); - if (($row) && (!$this->isFullyLoaded())) $this->attributes['tables_loaded'] ++; // If $row isn't a cached copy then increment the counter - - // Now put these into the attributes array as core values - $objarray = (array) $row; - foreach($objarray as $key => $value) - $this->attributes[$key] = $value; - - return true; - } - - /** - * Saves this user to the database. - * @return true|false - */ - public function save() - { - // Save generic stuff - if (!parent::save()) - return false; - - // Now save specific stuff - return create_user_entity($this->get('guid'), $this->get('name'), $this->get('username'), $this->get('password'), $this->get('salt'), $this->get('email'), $this->get('language'), $this->get('code')); + // Check the type + if ($this->attributes['type']!='user') + throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $guid, get_class())); + + // Load missing data + $row = get_user_entity_as_row($guid); + if (($row) && (!$this->isFullyLoaded())) $this->attributes['tables_loaded'] ++; // If $row isn't a cached copy then increment the counter + + // Now put these into the attributes array as core values + $objarray = (array) $row; + foreach($objarray as $key => $value) + $this->attributes[$key] = $value; + + return true; + } + + /** + * Saves this user to the database. + * @return true|false + */ + public function save() + { + // Save generic stuff + if (!parent::save()) + return false; + + // Now save specific stuff + return create_user_entity($this->get('guid'), $this->get('name'), $this->get('username'), $this->get('password'), $this->get('salt'), $this->get('email'), $this->get('language'), $this->get('code')); } /** @@ -158,876 +158,876 @@ // Delete entity return parent::delete(); - } - - /** - * Ban this user. - * - * @param string $reason Optional reason - */ - public function ban($reason = "") { return ban_user($this->guid, $reason); } - - /** - * Unban this user. - */ - public function unban() { return unban_user($this->guid); } - - /** - * Is this user banned or not? - * - * @return bool - */ - public function isBanned() { return $this->banned == 'yes'; } - - /** - * Get sites that this user is a member of - * - * @param string $subtype Optionally, the subtype of result we want to limit to - * @param int $limit The number of results to return - * @param int $offset Any indexing offset - */ - function getSites($subtype="", $limit = 10, $offset = 0) { - // return get_site_users($this->getGUID(), $subtype, $limit, $offset); - return get_user_sites($this->getGUID(), $subtype, $limit, $offset); - } - - /** - * Add this user to a particular site - * - * @param int $site_guid The guid of the site to add it to - * @return true|false - */ - function addToSite($site_guid) { - // return add_site_user($this->getGUID(), $site_guid); - return add_site_user($site_guid, $this->getGUID()); - } - - /** - * Remove this user from a particular site - * - * @param int $site_guid The guid of the site to remove it from - * @return true|false - */ - function removeFromSite($site_guid) { - //return remove_site_user($this->getGUID(), $site_guid); - return remove_site_user($site_guid, $this->getGUID()); - } - - /** - * Adds a user to this user's friends list - * - * @param int $friend_guid The GUID of the user to add - * @return true|false Depending on success - */ - function addFriend($friend_guid) { return user_add_friend($this->getGUID(), $friend_guid); } - - /** - * Removes a user from this user's friends list - * - * @param int $friend_guid The GUID of the user to remove - * @return true|false Depending on success - */ - function removeFriend($friend_guid) { return user_remove_friend($this->getGUID(), $friend_guid); } - - /** - * Determines whether or not this user is a friend of the currently logged in user - * - * @return true|false - */ - function isFriend() { return user_is_friend(get_loggedin_userid(), $this->getGUID()); } - - /** - * Determines whether this user is friends with another user - * - * @param int $user_guid The GUID of the user to check is on this user's friends list - * @return true|false - */ - function isFriendsWith($user_guid) { return user_is_friend($this->getGUID(), $user_guid); } - - /** - * Determines whether or not this user is on another user's friends list - * - * @param int $user_guid The GUID of the user to check against - * @return true|false - */ - function isFriendOf($user_guid) { return user_is_friend($user_guid, $this->getGUID()); } - - /** - * Retrieves a list of this user's friends - * - * @param string $subtype Optionally, the subtype of user to filter to (leave blank for all) - * @param int $limit The number of users to retrieve - * @param int $offset Indexing offset, if any - * @return array|false Array of ElggUsers, or false, depending on success - */ - function getFriends($subtype = "", $limit = 10, $offset = 0) { return get_user_friends($this->getGUID(), $subtype, $limit, $offset); } - - /** - * Retrieves a list of people who have made this user a friend - * - * @param string $subtype Optionally, the subtype of user to filter to (leave blank for all) - * @param int $limit The number of users to retrieve - * @param int $offset Indexing offset, if any - * @return array|false Array of ElggUsers, or false, depending on success - */ - function getFriendsOf($subtype = "", $limit = 10, $offset = 0) { return get_user_friends_of($this->getGUID(), $subtype, $limit, $offset); } - - /** - * Get an array of ElggObjects owned by this user. - * - * @param string $subtype The subtype of the objects, if any - * @param int $limit Number of results to return - * @param int $offset Any indexing offset - */ - public function getObjects($subtype="", $limit = 10, $offset = 0) { return get_user_objects($this->getGUID(), $subtype, $limit, $offset); } - - /** - * Get an array of ElggObjects owned by this user's friends. - * - * @param string $subtype The subtype of the objects, if any - * @param int $limit Number of results to return - * @param int $offset Any indexing offset - */ - public function getFriendsObjects($subtype = "", $limit = 10, $offset = 0) { return get_user_friends_objects($this->getGUID(), $subtype, $limit, $offset); } - - /** - * Counts the number of ElggObjects owned by this user - * - * @param string $subtype The subtypes of the objects, if any - * @return int The number of ElggObjects - */ - public function countObjects($subtype = "") { - return count_user_objects($this->getGUID(), $subtype); - } - - /** - * Get the collections associated with a user. - * - * @param string $subtype Optionally, the subtype of result we want to limit to - * @param int $limit The number of results to return - * @param int $offset Any indexing offset - * @return unknown - */ - public function getCollections($subtype="", $limit = 10, $offset = 0) { return get_user_collections($this->getGUID(), $subtype, $limit, $offset); } - - /** - * If a user's owner is blank, return its own GUID as the owner - * - * @return int User GUID - */ - function getOwner() { - if ($this->owner_guid == 0) - return $this->getGUID(); - - return $this->owner_guid; - } - - // EXPORTABLE INTERFACE //////////////////////////////////////////////////////////// - - /** - * Return an array of fields which can be exported. - */ - public function getExportableValues() - { - return array_merge(parent::getExportableValues(), array( - 'name', - 'username', - 'language', - )); - } - } - - /** - * Return the user specific details of a user by a row. - * - * @param int $guid - */ - function get_user_entity_as_row($guid) - { - global $CONFIG; - - /*$row = retrieve_cached_entity_row($guid); - if ($row) - { - // We have already cached this object, so retrieve its value from the cache - if (isset($CONFIG->debug) && $CONFIG->debug == true) - error_log("** Retrieving sub part of GUID:$guid from cache"); - - return $row; - } - else - {*/ - // Object not cached, load it. - if (isset($CONFIG->debug) && $CONFIG->debug == true) - error_log("** Sub part of GUID:$guid loaded from DB"); - - $guid = (int)$guid; - - return get_data_row("SELECT * from {$CONFIG->dbprefix}users_entity where guid=$guid"); - //} - } - - /** - * Create or update the extras table for a given user. - * Call create_entity first. - * - * @param int $guid - * @param string $name - * @param string $description - * @param string $url - */ - function create_user_entity($guid, $name, $username, $password, $salt, $email, $language, $code) - { - global $CONFIG; - - $guid = (int)$guid; - $name = sanitise_string($name); - $username = sanitise_string($username); - $password = sanitise_string($password); - $salt = sanitise_string($salt); - $email = sanitise_string($email); - $language = sanitise_string($language); - $code = sanitise_string($code); - - $row = get_entity_as_row($guid); - if ($row) - { - // Exists and you have access to it - - if ($exists = get_data_row("SELECT guid from {$CONFIG->dbprefix}users_entity where guid = {$guid}")) { - $result = update_data("UPDATE {$CONFIG->dbprefix}users_entity set name='$name', username='$username', password='$password', salt='$salt', email='$email', language='$language', code='$code', last_action = ". time() ." where guid = {$guid}"); - if ($result != false) - { - // Update succeeded, continue - $entity = get_entity($guid); - if (trigger_elgg_event('update',$entity->type,$entity)) { - return $guid; - } else { - $entity->delete(); - } - } - } - else - { - // Update failed, attempt an insert. - $result = insert_data("INSERT into {$CONFIG->dbprefix}users_entity (guid, name, username, password, salt, email, language, code) values ($guid, '$name', '$username', '$password', '$salt', '$email', '$language', '$code')"); - if ($result!==false) { - $entity = get_entity($guid); - if (trigger_elgg_event('create',$entity->type,$entity)) { - return $guid; - } else { - $entity->delete(); //delete_entity($guid); - } - } - } - - } - - return false; - } - - /** - * Disables all of a user's entities - * - * @param int $owner_guid The owner GUID - * @return true|false Depending on success - */ - function disable_user_entities($owner_guid) { - - global $CONFIG; - $owner_guid = (int) $owner_guid; - if ($entity = get_entity($owner_guid)) { - if (trigger_elgg_event('disable',$entity->type,$entity)) { - if ($entity->canEdit()) { - $res = update_data("UPDATE {$CONFIG->dbprefix}entities set enabled='no' where owner_guid={$owner_guid} or container_guid = {$owner_guid}"); - return $res; - } - } - } - return false; - - } - - /** - * Ban a user - * - * @param int $user_guid The user guid - * @param string $reason A reason - */ - function ban_user($user_guid, $reason = "") - { - global $CONFIG; - - $user_guid = (int)$user_guid; - $reason = sanitise_string($reason); - - $user = get_entity($user_guid); - - if (($user) && ($user->canEdit()) && ($user instanceof ElggUser)) + } + + /** + * Ban this user. + * + * @param string $reason Optional reason + */ + public function ban($reason = "") { return ban_user($this->guid, $reason); } + + /** + * Unban this user. + */ + public function unban() { return unban_user($this->guid); } + + /** + * Is this user banned or not? + * + * @return bool + */ + public function isBanned() { return $this->banned == 'yes'; } + + /** + * Get sites that this user is a member of + * + * @param string $subtype Optionally, the subtype of result we want to limit to + * @param int $limit The number of results to return + * @param int $offset Any indexing offset + */ + function getSites($subtype="", $limit = 10, $offset = 0) { + // return get_site_users($this->getGUID(), $subtype, $limit, $offset); + return get_user_sites($this->getGUID(), $subtype, $limit, $offset); + } + + /** + * Add this user to a particular site + * + * @param int $site_guid The guid of the site to add it to + * @return true|false + */ + function addToSite($site_guid) { + // return add_site_user($this->getGUID(), $site_guid); + return add_site_user($site_guid, $this->getGUID()); + } + + /** + * Remove this user from a particular site + * + * @param int $site_guid The guid of the site to remove it from + * @return true|false + */ + function removeFromSite($site_guid) { + //return remove_site_user($this->getGUID(), $site_guid); + return remove_site_user($site_guid, $this->getGUID()); + } + + /** + * Adds a user to this user's friends list + * + * @param int $friend_guid The GUID of the user to add + * @return true|false Depending on success + */ + function addFriend($friend_guid) { return user_add_friend($this->getGUID(), $friend_guid); } + + /** + * Removes a user from this user's friends list + * + * @param int $friend_guid The GUID of the user to remove + * @return true|false Depending on success + */ + function removeFriend($friend_guid) { return user_remove_friend($this->getGUID(), $friend_guid); } + + /** + * Determines whether or not this user is a friend of the currently logged in user + * + * @return true|false + */ + function isFriend() { return user_is_friend(get_loggedin_userid(), $this->getGUID()); } + + /** + * Determines whether this user is friends with another user + * + * @param int $user_guid The GUID of the user to check is on this user's friends list + * @return true|false + */ + function isFriendsWith($user_guid) { return user_is_friend($this->getGUID(), $user_guid); } + + /** + * Determines whether or not this user is on another user's friends list + * + * @param int $user_guid The GUID of the user to check against + * @return true|false + */ + function isFriendOf($user_guid) { return user_is_friend($user_guid, $this->getGUID()); } + + /** + * Retrieves a list of this user's friends + * + * @param string $subtype Optionally, the subtype of user to filter to (leave blank for all) + * @param int $limit The number of users to retrieve + * @param int $offset Indexing offset, if any + * @return array|false Array of ElggUsers, or false, depending on success + */ + function getFriends($subtype = "", $limit = 10, $offset = 0) { return get_user_friends($this->getGUID(), $subtype, $limit, $offset); } + + /** + * Retrieves a list of people who have made this user a friend + * + * @param string $subtype Optionally, the subtype of user to filter to (leave blank for all) + * @param int $limit The number of users to retrieve + * @param int $offset Indexing offset, if any + * @return array|false Array of ElggUsers, or false, depending on success + */ + function getFriendsOf($subtype = "", $limit = 10, $offset = 0) { return get_user_friends_of($this->getGUID(), $subtype, $limit, $offset); } + + /** + * Get an array of ElggObjects owned by this user. + * + * @param string $subtype The subtype of the objects, if any + * @param int $limit Number of results to return + * @param int $offset Any indexing offset + */ + public function getObjects($subtype="", $limit = 10, $offset = 0) { return get_user_objects($this->getGUID(), $subtype, $limit, $offset); } + + /** + * Get an array of ElggObjects owned by this user's friends. + * + * @param string $subtype The subtype of the objects, if any + * @param int $limit Number of results to return + * @param int $offset Any indexing offset + */ + public function getFriendsObjects($subtype = "", $limit = 10, $offset = 0) { return get_user_friends_objects($this->getGUID(), $subtype, $limit, $offset); } + + /** + * Counts the number of ElggObjects owned by this user + * + * @param string $subtype The subtypes of the objects, if any + * @return int The number of ElggObjects + */ + public function countObjects($subtype = "") { + return count_user_objects($this->getGUID(), $subtype); + } + + /** + * Get the collections associated with a user. + * + * @param string $subtype Optionally, the subtype of result we want to limit to + * @param int $limit The number of results to return + * @param int $offset Any indexing offset + * @return unknown + */ + public function getCollections($subtype="", $limit = 10, $offset = 0) { return get_user_collections($this->getGUID(), $subtype, $limit, $offset); } + + /** + * If a user's owner is blank, return its own GUID as the owner + * + * @return int User GUID + */ + function getOwner() { + if ($this->owner_guid == 0) + return $this->getGUID(); + + return $this->owner_guid; + } + + // EXPORTABLE INTERFACE //////////////////////////////////////////////////////////// + + /** + * Return an array of fields which can be exported. + */ + public function getExportableValues() + { + return array_merge(parent::getExportableValues(), array( + 'name', + 'username', + 'language', + )); + } + } + + /** + * Return the user specific details of a user by a row. + * + * @param int $guid + */ + function get_user_entity_as_row($guid) + { + global $CONFIG; + + /*$row = retrieve_cached_entity_row($guid); + if ($row) + { + // We have already cached this object, so retrieve its value from the cache + if (isset($CONFIG->debug) && $CONFIG->debug == true) + error_log("** Retrieving sub part of GUID:$guid from cache"); + + return $row; + } + else + {*/ + // Object not cached, load it. + if (isset($CONFIG->debug) && $CONFIG->debug == true) + error_log("** Sub part of GUID:$guid loaded from DB"); + + $guid = (int)$guid; + + return get_data_row("SELECT * from {$CONFIG->dbprefix}users_entity where guid=$guid"); + //} + } + + /** + * Create or update the extras table for a given user. + * Call create_entity first. + * + * @param int $guid + * @param string $name + * @param string $description + * @param string $url + */ + function create_user_entity($guid, $name, $username, $password, $salt, $email, $language, $code) + { + global $CONFIG; + + $guid = (int)$guid; + $name = sanitise_string($name); + $username = sanitise_string($username); + $password = sanitise_string($password); + $salt = sanitise_string($salt); + $email = sanitise_string($email); + $language = sanitise_string($language); + $code = sanitise_string($code); + + $row = get_entity_as_row($guid); + if ($row) + { + // Exists and you have access to it + + if ($exists = get_data_row("SELECT guid from {$CONFIG->dbprefix}users_entity where guid = {$guid}")) { + $result = update_data("UPDATE {$CONFIG->dbprefix}users_entity set name='$name', username='$username', password='$password', salt='$salt', email='$email', language='$language', code='$code', last_action = ". time() ." where guid = {$guid}"); + if ($result != false) + { + // Update succeeded, continue + $entity = get_entity($guid); + if (trigger_elgg_event('update',$entity->type,$entity)) { + return $guid; + } else { + $entity->delete(); + } + } + } + else + { + // Update failed, attempt an insert. + $result = insert_data("INSERT into {$CONFIG->dbprefix}users_entity (guid, name, username, password, salt, email, language, code) values ($guid, '$name', '$username', '$password', '$salt', '$email', '$language', '$code')"); + if ($result!==false) { + $entity = get_entity($guid); + if (trigger_elgg_event('create',$entity->type,$entity)) { + return $guid; + } else { + $entity->delete(); //delete_entity($guid); + } + } + } + + } + + return false; + } + + /** + * Disables all of a user's entities + * + * @param int $owner_guid The owner GUID + * @return true|false Depending on success + */ + function disable_user_entities($owner_guid) { + + global $CONFIG; + $owner_guid = (int) $owner_guid; + if ($entity = get_entity($owner_guid)) { + if (trigger_elgg_event('disable',$entity->type,$entity)) { + if ($entity->canEdit()) { + $res = update_data("UPDATE {$CONFIG->dbprefix}entities set enabled='no' where owner_guid={$owner_guid} or container_guid = {$owner_guid}"); + return $res; + } + } + } + return false; + + } + + /** + * Ban a user + * + * @param int $user_guid The user guid + * @param string $reason A reason + */ + function ban_user($user_guid, $reason = "") + { + global $CONFIG; + + $user_guid = (int)$user_guid; + $reason = sanitise_string($reason); + + $user = get_entity($user_guid); + + if (($user) && ($user->canEdit()) && ($user instanceof ElggUser)) { - if (trigger_elgg_event('ban', 'user', $user)) { - // Add reason - if ($reason) - create_metadata($user_guid, 'ban_reason', $reason,'', 0, ACCESS_PUBLIC); - - // Set ban flag + if (trigger_elgg_event('ban', 'user', $user)) { + // Add reason + if ($reason) + create_metadata($user_guid, 'ban_reason', $reason,'', 0, ACCESS_PUBLIC); + + // Set ban flag return update_data("UPDATE {$CONFIG->dbprefix}users_entity set banned='yes' where guid=$user_guid"); - } - } - - return false; - } - - /** - * Unban a user. - * - * @param int $user_guid Unban a user. - */ - function unban_user($user_guid) - { - global $CONFIG; - - $user_guid = (int)$user_guid; - - $user = get_entity($user_guid); - - if (($user) && ($user->canEdit()) && ($user instanceof ElggUser)) + } + } + + return false; + } + + /** + * Unban a user. + * + * @param int $user_guid Unban a user. + */ + function unban_user($user_guid) + { + global $CONFIG; + + $user_guid = (int)$user_guid; + + $user = get_entity($user_guid); + + if (($user) && ($user->canEdit()) && ($user instanceof ElggUser)) { - if (trigger_elgg_event('unban', 'user', $user)) { - create_metadata($user_guid, 'ban_reason', '','', 0, ACCESS_PUBLIC); + if (trigger_elgg_event('unban', 'user', $user)) { + create_metadata($user_guid, 'ban_reason', '','', 0, ACCESS_PUBLIC); return update_data("UPDATE {$CONFIG->dbprefix}users_entity set banned='no' where guid=$user_guid"); - } - } - - return false; - } - + } + } + + return false; + } + /** * THIS FUNCTION IS DEPRECATED. - * - * Delete a user's extra data. - * - * @param int $guid - */ - function delete_user_entity($guid) + * + * Delete a user's extra data. + * + * @param int $guid + */ + function delete_user_entity($guid) { system_message(sprintf(elgg_echo('deprecatedfunction'), 'delete_user_entity')); - return 1; // Always return that we have deleted one row in order to not break existing code. - } - - /** - * Get the sites this user is part of - * - * @param int $user_guid The user's GUID - * @param int $limit Number of results to return - * @param int $offset Any indexing offset - * @return false|array On success, an array of ElggSites - */ - function get_user_sites($user_guid, $limit = 10, $offset = 0) { - $user_guid = (int)$user_guid; - $limit = (int)$limit; - $offset = (int)$offset; - - return get_entities_from_relationship("member_of_site", $user_guid, false, "site", "", 0, "time_created desc", $limit, $offset); - } - - /** - * Adds a user to another user's friends list. - * - * @param int $user_guid The GUID of the friending user - * @param int $friend_guid The GUID of the user to friend - * @return true|false Depending on success - */ - function user_add_friend($user_guid, $friend_guid) { - $user_guid = (int) $user_guid; - $friend_guid = (int) $friend_guid; - if ($user_guid == $friend_guid) return false; - if (!$friend = get_entity($friend_guid)) return false; - if (!$user = get_entity($user_guid)) return false; - if ( (!($user instanceof ElggUser)) || (!($friend instanceof ElggUser)) ) return false; - return add_entity_relationship($user_guid, "friend", $friend_guid); - } - - /** - * Removes a user from another user's friends list. - * - * @param int $user_guid The GUID of the friending user - * @param int $friend_guid The GUID of the user on the friends list - * @return true|false Depending on success - */ - function user_remove_friend($user_guid, $friend_guid) { - global $CONFIG; - - $user_guid = (int) $user_guid; - $friend_guid = (int) $friend_guid; - - // perform cleanup for access lists. - $collections = get_user_access_collections($user_guid); - foreach ($collections as $collection) { - remove_user_from_access_collection($friend_guid, $collection->id); - } - - return remove_entity_relationship($user_guid, "friend", $friend_guid); - } - - /** - * Determines whether or not a user is another user's friend. - * - * @param int $user_guid The GUID of the user - * @param int $friend_guid The GUID of the friend - * @return true|false - */ - function user_is_friend($user_guid, $friend_guid) { - return check_entity_relationship($user_guid, "friend", $friend_guid); - } - - /** - * Obtains a given user's friends - * - * @param int $user_guid The user's GUID - * @param string $subtype The subtype of users, if any - * @param int $limit Number of results to return (default 10) - * @param int $offset Indexing offset, if any - * @return false|array Either an array of ElggUsers or false, depending on success - */ - function get_user_friends($user_guid, $subtype = "", $limit = 10, $offset = 0) { - return get_entities_from_relationship("friend",$user_guid,false,"user",$subtype,0,"time_created desc",$limit,$offset); - } - - /** - * Obtains the people who have made a given user a friend - * - * @param int $user_guid The user's GUID - * @param string $subtype The subtype of users, if any - * @param int $limit Number of results to return (default 10) - * @param int $offset Indexing offset, if any - * @return false|array Either an array of ElggUsers or false, depending on success - */ - function get_user_friends_of($user_guid, $subtype = "", $limit = 10, $offset = 0) { - return get_entities_from_relationship("friend",$user_guid,true,"user",$subtype,0,"time_created desc",$limit,$offset); - } - - /** - * Obtains a list of objects owned by a user - * - * @param int $user_guid The GUID of the owning user - * @param string $subtype Optionally, the subtype of objects - * @param int $limit The number of results to return (default 10) - * @param int $offset Indexing offset, if any - * @param int $timelower The earliest time the entity can have been created. Default: all - * @param int $timeupper The latest time the entity can have been created. Default: all - * @return false|array An array of ElggObjects or false, depending on success - */ - function get_user_objects($user_guid, $subtype = "", $limit = 10, $offset = 0, $timelower = 0, $timeupper = 0) { - $ntt = get_entities('object',$subtype, $user_guid, "time_created desc", $limit, $offset,false,0,$user_guid,$timelower, $timeupper); - return $ntt; - } - - /** - * Counts the objects (optionally of a particular subtype) owned by a user - * - * @param int $user_guid The GUID of the owning user - * @param string $subtype Optionally, the subtype of objects - * @param int $timelower The earliest time the entity can have been created. Default: all - * @param int $timeupper The latest time the entity can have been created. Default: all - * @return int The number of objects the user owns (of this subtype) - */ - function count_user_objects($user_guid, $subtype = "", $timelower, $timeupper) { - $total = get_entities('object', $subtype, $user_guid, "time_created desc", null, null, true, 0, $user_guid,$timelower,$timeupper); - return $total; - } - - /** - * Displays a list of user objects of a particular subtype, with navigation. - * - * @see elgg_view_entity_list - * - * @param int $user_guid The GUID of the user - * @param string $subtype The object subtype - * @param int $limit The number of entities to display on a page - * @param true|false $fullview Whether or not to display the full view (default: true) - * @param int $timelower The earliest time the entity can have been created. Default: all - * @param int $timeupper The latest time the entity can have been created. Default: all - * @return string The list in a form suitable to display - */ - function list_user_objects($user_guid, $subtype = "", $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true, $timelower = 0, $timeupper = 0) { - - $offset = (int) get_input('offset'); - $limit = (int) $limit; - $count = (int) count_user_objects($user_guid, $subtype,$timelower,$timeupper); - $entities = get_user_objects($user_guid, $subtype, $limit, $offset, $timelower, $timeupper); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); - - } - - /** - * Obtains a list of objects owned by a user's friends - * - * @param int $user_guid The GUID of the user to get the friends of - * @param string $subtype Optionally, the subtype of objects - * @param int $limit The number of results to return (default 10) - * @param int $offset Indexing offset, if any - * @return false|array An array of ElggObjects or false, depending on success - */ - function get_user_friends_objects($user_guid, $subtype = "", $limit = 10, $offset = 0) { - if ($friends = get_user_friends($user_guid, $subtype, 999999, 0)) { - $friendguids = array(); - foreach($friends as $friend) { - $friendguids[] = $friend->getGUID(); - } - return get_entities('object',$subtype,$friendguids, "time_created desc", $limit, $offset, false, 0, $friendguids); - } - return false; - } - - /** - * Counts the number of objects owned by a user's friends - * - * @param int $user_guid The GUID of the user to get the friends of - * @param string $subtype Optionally, the subtype of objects - * @return int The number of objects - */ - function count_user_friends_objects($user_guid, $subtype = "") { - if ($friends = get_user_friends($user_guid, $subtype, 999999, 0)) { - $friendguids = array(); - foreach($friends as $friend) { - $friendguids[] = $friend->getGUID(); - } - return get_entities('object',$subtype,$friendguids, "time_created desc", $limit, $offset, true, 0, $friendguids); - } - return 0; - } - - /** - * Displays a list of a user's friends' objects of a particular subtype, with navigation. - * - * @see elgg_view_entity_list - * - * @param int $user_guid The GUID of the user - * @param string $subtype The object subtype - * @param int $limit The number of entities to display on a page - * @param true|false $fullview Whether or not to display the full view (default: true) - * @param true|false $viewtypetoggle Whether or not to allow you to flip to gallery mode (default: true) - * @return string The list in a form suitable to display - */ - function list_user_friends_objects($user_guid, $subtype = "", $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true) { - - $offset = (int) get_input('offset'); - $limit = (int) $limit; - $count = (int) count_user_friends_objects($user_guid, $subtype); - $entities = get_user_friends_objects($user_guid, $subtype, $limit, $offset); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); - - } - - /** - * Get user objects by an array of metadata - * - * @param int $user_guid The GUID of the owning user - * @param string $subtype Optionally, the subtype of objects - * @paran array $metadata An array of metadata - * @param int $limit The number of results to return (default 10) - * @param int $offset Indexing offset, if any - * @return false|array An array of ElggObjects or false, depending on success - * @return unknown - */ - function get_user_objects_by_metadata($user_guid, $subtype = "", $metadata = array(), $limit = 0, $offset = 0) { - - return get_entities_from_metadata_multi($metadata,"object",$subtype,$user_guid,$limit,$offset); - - } - - /** - * Get a user object from a GUID. - * - * This function returns an ElggUser from a given GUID. - * @param int $guid The GUID - * @return ElggUser|false - */ - function get_user($guid) - { - if (!empty($guid)) // Fixes "Exception thrown without stack frame" when db_select fails - $result = get_entity($guid); - - if ((!empty($result)) && (!($result instanceof ElggUser))) - //throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $guid, 'ElggUser')); - return false; - - if (!empty($result)) - return $result; - - return false; - } - - /** - * Get user by username - * - * @param string $username The user's username - * @return ElggUser|false Depending on success - */ - function get_user_by_username($username) - { - global $CONFIG, $USERNAME_TO_GUID_MAP_CACHE; - - $username = sanitise_string($username); - $access = get_access_sql_suffix('e'); - - // Caching - if ( (isset($USERNAME_TO_GUID_MAP_CACHE[$username])) && (retrieve_cached_entity($USERNAME_TO_GUID_MAP_CACHE[$username])) ) - return retrieve_cached_entity($USERNAME_TO_GUID_MAP_CACHE[$username]); - - $row = get_data_row("SELECT e.* from {$CONFIG->dbprefix}users_entity u join {$CONFIG->dbprefix}entities e on e.guid=u.guid where u.username='$username' and $access "); - if ($row) { - $USERNAME_TO_GUID_MAP_CACHE[$username] = $row->guid; - return new ElggUser($row); - } - - return false; - } - - /** - * Get user by session code - * - * @param string $code The session code - * @return ElggUser|false Depending on success - */ - function get_user_by_code($code) - { - global $CONFIG, $CODE_TO_GUID_MAP_CACHE; - - $code = sanitise_string($code); - - $access = get_access_sql_suffix('e'); - - // Caching - if ( (isset($CODE_TO_GUID_MAP_CACHE[$code])) && (retrieve_cached_entity($CODE_TO_GUID_MAP_CACHE[$code])) ) - return retrieve_cached_entity($CODE_TO_GUID_MAP_CACHE[$code]); - - $row = get_data_row("SELECT e.* from {$CONFIG->dbprefix}users_entity u join {$CONFIG->dbprefix}entities e on e.guid=u.guid where u.code='$code' and $access"); - if ($row) { - $CODE_TO_GUID_MAP_CACHE[$code] = $row->guid; - return new ElggUser($row); - } - - return false; - } - - /** - * Get an array of users from their - * - * @param string $email Email address. - * @return Array of users - */ - function get_user_by_email($email) - { - global $CONFIG; - - $email = sanitise_string($email); - - $access = get_access_sql_suffix('e'); - - $query = "SELECT e.* from {$CONFIG->dbprefix}entities e join {$CONFIG->dbprefix}users_entity u on e.guid=u.guid where email='$email' and $access"; - - return get_data($query, 'entity_row_to_elggstar'); - } - - /** - * Searches for a user based on a complete or partial name or username. - * - * @param string $criteria The partial or full name or username. - * @param int $limit Limit of the search. - * @param int $offset Offset. - * @param string $order_by The order. - * @param boolean $count Whether to return the count of results or just the results. - */ - function search_for_user($criteria, $limit = 10, $offset = 0, $order_by = "", $count = false) - { - global $CONFIG; - - $criteria = sanitise_string($criteria); - $limit = (int)$limit; - $offset = (int)$offset; - $order_by = sanitise_string($order_by); - - $access = get_access_sql_suffix("e"); - - if ($order_by == "") $order_by = "e.time_created desc"; - - if ($count) { - $query = "SELECT count(e.guid) as total "; - } else { - $query = "SELECT e.* "; - } - $query .= "from {$CONFIG->dbprefix}entities e join {$CONFIG->dbprefix}users_entity u on e.guid=u.guid where "; - // $query .= " match(u.name,u.username) against ('$criteria') "; - $query .= "(u.name like \"%{$criteria}%\" or u.username like \"%{$criteria}%\")"; - $query .= " and $access"; - - if (!$count) { - $query .= " order by $order_by limit $offset, $limit"; // Add order and limit - return get_data($query, "entity_row_to_elggstar"); - } else { - if ($count = get_data_row($query)) { - return $count->total; - } - } - return false; - } - - /** - * Displays a list of user objects that have been searched for. - * - * @see elgg_view_entity_list - * + return 1; // Always return that we have deleted one row in order to not break existing code. + } + + /** + * Get the sites this user is part of + * + * @param int $user_guid The user's GUID + * @param int $limit Number of results to return + * @param int $offset Any indexing offset + * @return false|array On success, an array of ElggSites + */ + function get_user_sites($user_guid, $limit = 10, $offset = 0) { + $user_guid = (int)$user_guid; + $limit = (int)$limit; + $offset = (int)$offset; + + return get_entities_from_relationship("member_of_site", $user_guid, false, "site", "", 0, "time_created desc", $limit, $offset); + } + + /** + * Adds a user to another user's friends list. + * + * @param int $user_guid The GUID of the friending user + * @param int $friend_guid The GUID of the user to friend + * @return true|false Depending on success + */ + function user_add_friend($user_guid, $friend_guid) { + $user_guid = (int) $user_guid; + $friend_guid = (int) $friend_guid; + if ($user_guid == $friend_guid) return false; + if (!$friend = get_entity($friend_guid)) return false; + if (!$user = get_entity($user_guid)) return false; + if ( (!($user instanceof ElggUser)) || (!($friend instanceof ElggUser)) ) return false; + return add_entity_relationship($user_guid, "friend", $friend_guid); + } + + /** + * Removes a user from another user's friends list. + * + * @param int $user_guid The GUID of the friending user + * @param int $friend_guid The GUID of the user on the friends list + * @return true|false Depending on success + */ + function user_remove_friend($user_guid, $friend_guid) { + global $CONFIG; + + $user_guid = (int) $user_guid; + $friend_guid = (int) $friend_guid; + + // perform cleanup for access lists. + $collections = get_user_access_collections($user_guid); + foreach ($collections as $collection) { + remove_user_from_access_collection($friend_guid, $collection->id); + } + + return remove_entity_relationship($user_guid, "friend", $friend_guid); + } + + /** + * Determines whether or not a user is another user's friend. + * + * @param int $user_guid The GUID of the user + * @param int $friend_guid The GUID of the friend + * @return true|false + */ + function user_is_friend($user_guid, $friend_guid) { + return check_entity_relationship($user_guid, "friend", $friend_guid); + } + + /** + * Obtains a given user's friends + * + * @param int $user_guid The user's GUID + * @param string $subtype The subtype of users, if any + * @param int $limit Number of results to return (default 10) + * @param int $offset Indexing offset, if any + * @return false|array Either an array of ElggUsers or false, depending on success + */ + function get_user_friends($user_guid, $subtype = "", $limit = 10, $offset = 0) { + return get_entities_from_relationship("friend",$user_guid,false,"user",$subtype,0,"time_created desc",$limit,$offset); + } + + /** + * Obtains the people who have made a given user a friend + * + * @param int $user_guid The user's GUID + * @param string $subtype The subtype of users, if any + * @param int $limit Number of results to return (default 10) + * @param int $offset Indexing offset, if any + * @return false|array Either an array of ElggUsers or false, depending on success + */ + function get_user_friends_of($user_guid, $subtype = "", $limit = 10, $offset = 0) { + return get_entities_from_relationship("friend",$user_guid,true,"user",$subtype,0,"time_created desc",$limit,$offset); + } + + /** + * Obtains a list of objects owned by a user + * + * @param int $user_guid The GUID of the owning user + * @param string $subtype Optionally, the subtype of objects + * @param int $limit The number of results to return (default 10) + * @param int $offset Indexing offset, if any + * @param int $timelower The earliest time the entity can have been created. Default: all + * @param int $timeupper The latest time the entity can have been created. Default: all + * @return false|array An array of ElggObjects or false, depending on success + */ + function get_user_objects($user_guid, $subtype = "", $limit = 10, $offset = 0, $timelower = 0, $timeupper = 0) { + $ntt = get_entities('object',$subtype, $user_guid, "time_created desc", $limit, $offset,false,0,$user_guid,$timelower, $timeupper); + return $ntt; + } + + /** + * Counts the objects (optionally of a particular subtype) owned by a user + * + * @param int $user_guid The GUID of the owning user + * @param string $subtype Optionally, the subtype of objects + * @param int $timelower The earliest time the entity can have been created. Default: all + * @param int $timeupper The latest time the entity can have been created. Default: all + * @return int The number of objects the user owns (of this subtype) + */ + function count_user_objects($user_guid, $subtype = "", $timelower, $timeupper) { + $total = get_entities('object', $subtype, $user_guid, "time_created desc", null, null, true, 0, $user_guid,$timelower,$timeupper); + return $total; + } + + /** + * Displays a list of user objects of a particular subtype, with navigation. + * + * @see elgg_view_entity_list + * + * @param int $user_guid The GUID of the user + * @param string $subtype The object subtype + * @param int $limit The number of entities to display on a page + * @param true|false $fullview Whether or not to display the full view (default: true) + * @param int $timelower The earliest time the entity can have been created. Default: all + * @param int $timeupper The latest time the entity can have been created. Default: all + * @return string The list in a form suitable to display + */ + function list_user_objects($user_guid, $subtype = "", $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true, $timelower = 0, $timeupper = 0) { + + $offset = (int) get_input('offset'); + $limit = (int) $limit; + $count = (int) count_user_objects($user_guid, $subtype,$timelower,$timeupper); + $entities = get_user_objects($user_guid, $subtype, $limit, $offset, $timelower, $timeupper); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); + + } + + /** + * Obtains a list of objects owned by a user's friends + * + * @param int $user_guid The GUID of the user to get the friends of + * @param string $subtype Optionally, the subtype of objects + * @param int $limit The number of results to return (default 10) + * @param int $offset Indexing offset, if any + * @return false|array An array of ElggObjects or false, depending on success + */ + function get_user_friends_objects($user_guid, $subtype = "", $limit = 10, $offset = 0) { + if ($friends = get_user_friends($user_guid, $subtype, 999999, 0)) { + $friendguids = array(); + foreach($friends as $friend) { + $friendguids[] = $friend->getGUID(); + } + return get_entities('object',$subtype,$friendguids, "time_created desc", $limit, $offset, false, 0, $friendguids); + } + return false; + } + + /** + * Counts the number of objects owned by a user's friends + * + * @param int $user_guid The GUID of the user to get the friends of + * @param string $subtype Optionally, the subtype of objects + * @return int The number of objects + */ + function count_user_friends_objects($user_guid, $subtype = "") { + if ($friends = get_user_friends($user_guid, $subtype, 999999, 0)) { + $friendguids = array(); + foreach($friends as $friend) { + $friendguids[] = $friend->getGUID(); + } + return get_entities('object',$subtype,$friendguids, "time_created desc", $limit, $offset, true, 0, $friendguids); + } + return 0; + } + + /** + * Displays a list of a user's friends' objects of a particular subtype, with navigation. + * + * @see elgg_view_entity_list + * + * @param int $user_guid The GUID of the user + * @param string $subtype The object subtype + * @param int $limit The number of entities to display on a page + * @param true|false $fullview Whether or not to display the full view (default: true) + * @param true|false $viewtypetoggle Whether or not to allow you to flip to gallery mode (default: true) + * @return string The list in a form suitable to display + */ + function list_user_friends_objects($user_guid, $subtype = "", $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true) { + + $offset = (int) get_input('offset'); + $limit = (int) $limit; + $count = (int) count_user_friends_objects($user_guid, $subtype); + $entities = get_user_friends_objects($user_guid, $subtype, $limit, $offset); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); + + } + + /** + * Get user objects by an array of metadata + * + * @param int $user_guid The GUID of the owning user + * @param string $subtype Optionally, the subtype of objects + * @paran array $metadata An array of metadata + * @param int $limit The number of results to return (default 10) + * @param int $offset Indexing offset, if any + * @return false|array An array of ElggObjects or false, depending on success + * @return unknown + */ + function get_user_objects_by_metadata($user_guid, $subtype = "", $metadata = array(), $limit = 0, $offset = 0) { + + return get_entities_from_metadata_multi($metadata,"object",$subtype,$user_guid,$limit,$offset); + + } + + /** + * Get a user object from a GUID. + * + * This function returns an ElggUser from a given GUID. + * @param int $guid The GUID + * @return ElggUser|false + */ + function get_user($guid) + { + if (!empty($guid)) // Fixes "Exception thrown without stack frame" when db_select fails + $result = get_entity($guid); + + if ((!empty($result)) && (!($result instanceof ElggUser))) + //throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $guid, 'ElggUser')); + return false; + + if (!empty($result)) + return $result; + + return false; + } + + /** + * Get user by username + * + * @param string $username The user's username + * @return ElggUser|false Depending on success + */ + function get_user_by_username($username) + { + global $CONFIG, $USERNAME_TO_GUID_MAP_CACHE; + + $username = sanitise_string($username); + $access = get_access_sql_suffix('e'); + + // Caching + if ( (isset($USERNAME_TO_GUID_MAP_CACHE[$username])) && (retrieve_cached_entity($USERNAME_TO_GUID_MAP_CACHE[$username])) ) + return retrieve_cached_entity($USERNAME_TO_GUID_MAP_CACHE[$username]); + + $row = get_data_row("SELECT e.* from {$CONFIG->dbprefix}users_entity u join {$CONFIG->dbprefix}entities e on e.guid=u.guid where u.username='$username' and $access "); + if ($row) { + $USERNAME_TO_GUID_MAP_CACHE[$username] = $row->guid; + return new ElggUser($row); + } + + return false; + } + + /** + * Get user by session code + * + * @param string $code The session code + * @return ElggUser|false Depending on success + */ + function get_user_by_code($code) + { + global $CONFIG, $CODE_TO_GUID_MAP_CACHE; + + $code = sanitise_string($code); + + $access = get_access_sql_suffix('e'); + + // Caching + if ( (isset($CODE_TO_GUID_MAP_CACHE[$code])) && (retrieve_cached_entity($CODE_TO_GUID_MAP_CACHE[$code])) ) + return retrieve_cached_entity($CODE_TO_GUID_MAP_CACHE[$code]); + + $row = get_data_row("SELECT e.* from {$CONFIG->dbprefix}users_entity u join {$CONFIG->dbprefix}entities e on e.guid=u.guid where u.code='$code' and $access"); + if ($row) { + $CODE_TO_GUID_MAP_CACHE[$code] = $row->guid; + return new ElggUser($row); + } + + return false; + } + + /** + * Get an array of users from their + * + * @param string $email Email address. + * @return Array of users + */ + function get_user_by_email($email) + { + global $CONFIG; + + $email = sanitise_string($email); + + $access = get_access_sql_suffix('e'); + + $query = "SELECT e.* from {$CONFIG->dbprefix}entities e join {$CONFIG->dbprefix}users_entity u on e.guid=u.guid where email='$email' and $access"; + + return get_data($query, 'entity_row_to_elggstar'); + } + + /** + * Searches for a user based on a complete or partial name or username. + * + * @param string $criteria The partial or full name or username. + * @param int $limit Limit of the search. + * @param int $offset Offset. + * @param string $order_by The order. + * @param boolean $count Whether to return the count of results or just the results. + */ + function search_for_user($criteria, $limit = 10, $offset = 0, $order_by = "", $count = false) + { + global $CONFIG; + + $criteria = sanitise_string($criteria); + $limit = (int)$limit; + $offset = (int)$offset; + $order_by = sanitise_string($order_by); + + $access = get_access_sql_suffix("e"); + + if ($order_by == "") $order_by = "e.time_created desc"; + + if ($count) { + $query = "SELECT count(e.guid) as total "; + } else { + $query = "SELECT e.* "; + } + $query .= "from {$CONFIG->dbprefix}entities e join {$CONFIG->dbprefix}users_entity u on e.guid=u.guid where "; + // $query .= " match(u.name,u.username) against ('$criteria') "; + $query .= "(u.name like \"%{$criteria}%\" or u.username like \"%{$criteria}%\")"; + $query .= " and $access"; + + if (!$count) { + $query .= " order by $order_by limit $offset, $limit"; // Add order and limit + return get_data($query, "entity_row_to_elggstar"); + } else { + if ($count = get_data_row($query)) { + return $count->total; + } + } + return false; + } + + /** + * Displays a list of user objects that have been searched for. + * + * @see elgg_view_entity_list + * * @param string $tag Search criteria * @param int $limit The number of entities to display on a page - * @return string The list in a form suitable to display - */ - function list_user_search($tag, $limit = 10) { - - $offset = (int) get_input('offset'); - $limit = (int) $limit; - $count = (int) search_for_user($tag, 10, 0, '', true); - $entities = search_for_user($tag, $limit, $offset); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, false); - - } - - /** - * A function that returns a maximum of $limit users who have done something within the last - * $seconds seconds. - * - * @param int $seconds Number of seconds (default 600 = 10min) - * @param int $limit Limit, default 10. - * @param int $offset Offset, defualt 0. - */ - function find_active_users($seconds = 600, $limit = 10, $offset = 0) - { - global $CONFIG; - - $seconds = (int)$seconds; - $limit = (int)$limit; - $offset = (int)$offset; - - $time = time() - $seconds; - - $access = get_access_sql_suffix("e"); - - $query = "SELECT distinct e.* from {$CONFIG->dbprefix}entities e join {$CONFIG->dbprefix}users_entity u on e.guid = u.guid where u.last_action >= {$time} and $access order by u.last_action desc limit {$offset},{$limit}"; - - return get_data($query, "entity_row_to_elggstar"); - } - - /** - * Generate and send a password request email to a given user's registered email address. - * - * @param int $user_guid - */ - function send_new_password_request($user_guid) - { - global $CONFIG; - - $user_guid = (int)$user_guid; - - $user = get_entity($user_guid); - if ($user) - { - // generate code - $code = generate_random_cleartext_password(); - //create_metadata($user_guid, 'conf_code', $code,'', 0, ACCESS_PRIVATE); - set_private_setting($user_guid, 'passwd_conf_code', $code); - - // generate link - $link = $CONFIG->site->url . "action/user/passwordreset?u=$user_guid&c=$code"; - - // generate email - $email = sprintf(elgg_echo('email:resetreq:body'), $user->name, $_SERVER['REMOTE_ADDR'], $link); - - return notify_user($user->guid, $CONFIG->site->guid, elgg_echo('email:resetreq:subject'), $email, NULL, 'email'); - - } - - return false; - } - - /** - * Low level function to reset a given user's password. - * - * This can only be called from execute_new_password_request(). - * - * @param int $user_guid The user. - * @param string $password password text (which will then be converted into a hash and stored) - */ - function force_user_password_reset($user_guid, $password) - { - global $CONFIG; - - if (call_gatekeeper('execute_new_password_request', __FILE__)) - { - $user = get_entity($user_guid); - - if ($user) - { + * @return string The list in a form suitable to display + */ + function list_user_search($tag, $limit = 10) { + + $offset = (int) get_input('offset'); + $limit = (int) $limit; + $count = (int) search_for_user($tag, 10, 0, '', true); + $entities = search_for_user($tag, $limit, $offset); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, false); + + } + + /** + * A function that returns a maximum of $limit users who have done something within the last + * $seconds seconds. + * + * @param int $seconds Number of seconds (default 600 = 10min) + * @param int $limit Limit, default 10. + * @param int $offset Offset, defualt 0. + */ + function find_active_users($seconds = 600, $limit = 10, $offset = 0) + { + global $CONFIG; + + $seconds = (int)$seconds; + $limit = (int)$limit; + $offset = (int)$offset; + + $time = time() - $seconds; + + $access = get_access_sql_suffix("e"); + + $query = "SELECT distinct e.* from {$CONFIG->dbprefix}entities e join {$CONFIG->dbprefix}users_entity u on e.guid = u.guid where u.last_action >= {$time} and $access order by u.last_action desc limit {$offset},{$limit}"; + + return get_data($query, "entity_row_to_elggstar"); + } + + /** + * Generate and send a password request email to a given user's registered email address. + * + * @param int $user_guid + */ + function send_new_password_request($user_guid) + { + global $CONFIG; + + $user_guid = (int)$user_guid; + + $user = get_entity($user_guid); + if ($user) + { + // generate code + $code = generate_random_cleartext_password(); + //create_metadata($user_guid, 'conf_code', $code,'', 0, ACCESS_PRIVATE); + set_private_setting($user_guid, 'passwd_conf_code', $code); + + // generate link + $link = $CONFIG->site->url . "action/user/passwordreset?u=$user_guid&c=$code"; + + // generate email + $email = sprintf(elgg_echo('email:resetreq:body'), $user->name, $_SERVER['REMOTE_ADDR'], $link); + + return notify_user($user->guid, $CONFIG->site->guid, elgg_echo('email:resetreq:subject'), $email, NULL, 'email'); + + } + + return false; + } + + /** + * Low level function to reset a given user's password. + * + * This can only be called from execute_new_password_request(). + * + * @param int $user_guid The user. + * @param string $password password text (which will then be converted into a hash and stored) + */ + function force_user_password_reset($user_guid, $password) + { + global $CONFIG; + + if (call_gatekeeper('execute_new_password_request', __FILE__)) + { + $user = get_entity($user_guid); + + if ($user) + { $salt = generate_random_cleartext_password(); // Reset the salt $user->salt = $salt; - - $hash = generate_user_password($user, $password); - - return update_data("UPDATE {$CONFIG->dbprefix}users_entity set password='$hash', salt='$salt' where guid=$user_guid"); - } - } - - return false; - } - - /** - * Validate and execute a password reset for a user. - * - * @param int $user_guid The user id - * @param string $conf_code Confirmation code as sent in the request email. - */ - function execute_new_password_request($user_guid, $conf_code) - { - global $CONFIG; - - $user_guid = (int)$user_guid; - - $user = get_entity($user_guid); - if (($user) && (get_private_setting($user_guid, 'passwd_conf_code') == $conf_code)) - { - $password = generate_random_cleartext_password(); - - if (force_user_password_reset($user_guid, $password)) - { - //remove_metadata($user_guid, 'conf_code'); - remove_private_setting($user_guid, 'passwd_conf_code'); - - $email = sprintf(elgg_echo('email:resetpassword:body'), $user->name, $password); - - return notify_user($user->guid, $CONFIG->site->guid, elgg_echo('email:resetpassword:subject'), $email, NULL, 'email'); - } - } - - return false; - } - - /** - * Set the validation status for a user. - * - * @param bool $status Validated (true) or false - * @param string $method Optional method to say how a user was validated - * @return bool - */ - function set_user_validation_status($user_guid, $status, $method = '') - { - if (!$status) $method = ''; + + $hash = generate_user_password($user, $password); + + return update_data("UPDATE {$CONFIG->dbprefix}users_entity set password='$hash', salt='$salt' where guid=$user_guid"); + } + } + + return false; + } + + /** + * Validate and execute a password reset for a user. + * + * @param int $user_guid The user id + * @param string $conf_code Confirmation code as sent in the request email. + */ + function execute_new_password_request($user_guid, $conf_code) + { + global $CONFIG; + + $user_guid = (int)$user_guid; + + $user = get_entity($user_guid); + if (($user) && (get_private_setting($user_guid, 'passwd_conf_code') == $conf_code)) + { + $password = generate_random_cleartext_password(); + + if (force_user_password_reset($user_guid, $password)) + { + //remove_metadata($user_guid, 'conf_code'); + remove_private_setting($user_guid, 'passwd_conf_code'); + + $email = sprintf(elgg_echo('email:resetpassword:body'), $user->name, $password); + + return notify_user($user->guid, $CONFIG->site->guid, elgg_echo('email:resetpassword:subject'), $email, NULL, 'email'); + } + } + + return false; + } + + /** + * Set the validation status for a user. + * + * @param bool $status Validated (true) or false + * @param string $method Optional method to say how a user was validated + * @return bool + */ + function set_user_validation_status($user_guid, $status, $method = '') + { + if (!$status) $method = ''; if ($status) - { + { if ( (create_metadata($user_guid, 'validated', $status,'', 0, ACCESS_PUBLIC)) && (create_metadata($user_guid, 'validated_method', $method,'', 0, ACCESS_PUBLIC)) @@ -1046,521 +1046,521 @@ (delete_metadata($validated_method->id)) ) return true; - } - - return false; - } - - /** - * Trigger an event requesting that a user guid be validated somehow - either by email address or some other way. - * - * This event invalidates any existing values and returns - * - * @param unknown_type $user_guid - */ - function request_user_validation($user_guid) - { - $user = get_entity($user_guid); - - if (($user) && ($user instanceof ElggUser)) - { - // invalidate any existing validations - set_user_validation_status($user_guid, false); - - // request validation - trigger_elgg_event('validate', 'user', $user); - - } - } - - /** - * Validates an email address. - * - * @param string $address Email address. - * @return bool - */ - function is_email_address($address) - { - // TODO: Make this better! - - if (strpos($address, '@')=== false) - return false; - - if (strpos($address, '.')=== false) - return false; - - return true; - } - - /** - * Simple function that will generate a random clear text password suitable for feeding into generate_user_password(). - * - * @see generate_user_password - * @return string - */ - function generate_random_cleartext_password() - { - return substr(md5(microtime() . rand()), 0, 8); - } - - /** - * Generate a password for a user, currently uses MD5. - * - * Later may introduce salting etc. - * - * @param ElggUser $user The user this is being generated for. - * @param string $password Password in clear text - */ - function generate_user_password(ElggUser $user, $password) - { - return md5($password . $user->salt); - } - - /** - * Simple function which ensures that a username contains only valid characters. - * - * This should only permit chars that are valid on the file system as well. - * - * @param string $username - * @throws RegistrationException on invalid - */ - function validate_username($username) + } + + return false; + } + + /** + * Trigger an event requesting that a user guid be validated somehow - either by email address or some other way. + * + * This event invalidates any existing values and returns + * + * @param unknown_type $user_guid + */ + function request_user_validation($user_guid) + { + $user = get_entity($user_guid); + + if (($user) && ($user instanceof ElggUser)) + { + // invalidate any existing validations + set_user_validation_status($user_guid, false); + + // request validation + trigger_elgg_event('validate', 'user', $user); + + } + } + + /** + * Validates an email address. + * + * @param string $address Email address. + * @return bool + */ + function is_email_address($address) + { + // TODO: Make this better! + + if (strpos($address, '@')=== false) + return false; + + if (strpos($address, '.')=== false) + return false; + + return true; + } + + /** + * Simple function that will generate a random clear text password suitable for feeding into generate_user_password(). + * + * @see generate_user_password + * @return string + */ + function generate_random_cleartext_password() + { + return substr(md5(microtime() . rand()), 0, 8); + } + + /** + * Generate a password for a user, currently uses MD5. + * + * Later may introduce salting etc. + * + * @param ElggUser $user The user this is being generated for. + * @param string $password Password in clear text + */ + function generate_user_password(ElggUser $user, $password) + { + return md5($password . $user->salt); + } + + /** + * Simple function which ensures that a username contains only valid characters. + * + * This should only permit chars that are valid on the file system as well. + * + * @param string $username + * @throws RegistrationException on invalid + */ + function validate_username($username) { global $CONFIG; - + // Basic, check length if (!isset($CONFIG->minusername)) { $CONFIG->minusername = 4; } - + if (strlen($username) < $CONFIG->minusername) - throw new RegistrationException(elgg_echo('registration:usernametooshort')); - - // Blacklist for bad characters (partially nicked from mediawiki) - - $blacklist = '/[' . - '\x{0080}-\x{009f}' . # iso-8859-1 control chars - '\x{00a0}' . # non-breaking space - '\x{2000}-\x{200f}' . # various whitespace - '\x{2028}-\x{202f}' . # breaks and control chars - '\x{3000}' . # ideographic space - '\x{e000}-\x{f8ff}' . # private use - ']/u'; - - if ( - preg_match($blacklist, $username) - ) + throw new RegistrationException(elgg_echo('registration:usernametooshort')); + + // Blacklist for bad characters (partially nicked from mediawiki) + + $blacklist = '/[' . + '\x{0080}-\x{009f}' . # iso-8859-1 control chars + '\x{00a0}' . # non-breaking space + '\x{2000}-\x{200f}' . # various whitespace + '\x{2028}-\x{202f}' . # breaks and control chars + '\x{3000}' . # ideographic space + '\x{e000}-\x{f8ff}' . # private use + ']/u'; + + if ( + preg_match($blacklist, $username) + ) throw new RegistrationException(elgg_echo('registration:invalidchars')); // Belts and braces TODO: Tidy into main unicode $blacklist2 = '/\\"\'*& ?#%^(){}[]~?<>;|¬`@-+='; for ($n=0; $n < strlen($blacklist2); $n++) if (strpos($username, $blacklist2[$n])!==false) - throw new RegistrationException(elgg_echo('registration:invalidchars')); - - $result = true; - return trigger_plugin_hook('registeruser:validate:username', 'all', array('username' => $username), $result); - } - - /** - * Simple validation of a password. - * - * @param string $password - * @throws RegistrationException on invalid - */ - function validate_password($password) - { - if (strlen($password)<6) throw new RegistrationException(elgg_echo('registration:passwordtooshort')); - - $result = true; - return trigger_plugin_hook('registeruser:validate:password', 'all', array('password' => $password), $result); - } - - /** - * Simple validation of a email. - * - * @param string $address - * @throws RegistrationException on invalid - * @return bool - */ - function validate_email_address($address) - { - if (!is_email_address($address)) throw new RegistrationException(elgg_echo('registration:notemail')); - - // Got here, so lets try a hook (defaulting to ok) - $result = true; - return trigger_plugin_hook('registeruser:validate:email', 'all', array('email' => $address), $result); - } - - /** - * Registers a user, returning false if the username already exists - * - * @param string $username The username of the new user - * @param string $password The password - * @param string $name The user's display name - * @param string $email Their email address - * @param bool $allow_multiple_emails Allow the same email address to be registered multiple times? - * @param int $friend_guid Optionally, GUID of a user this user will friend once fully registered - * @return int|false The new user's GUID; false on failure - */ - function register_user($username, $password, $name, $email, $allow_multiple_emails = false, $friend_guid = 0, $invitecode = '') { - - // Load the configuration - global $CONFIG; - - $username = trim($username); - $password = trim($password); - $name = trim($name); - $email = trim($email); - - // A little sanity checking - if (empty($username) - || empty($password) - || empty($name) - || empty($email)) { - return false; - } - - // See if it exists and is disabled - $access_status = access_get_show_hidden_status(); - access_show_hidden_entities(true); - - // Validate email address - if (!validate_email_address($email)) throw new RegistrationException(elgg_echo('registration:emailnotvalid')); - - // Validate password - if (!validate_password($password)) throw new RegistrationException(elgg_echo('registration:passwordnotvalid')); - - // Validate the username - if (!validate_username($username)) throw new RegistrationException(elgg_echo('registration:usernamenotvalid')); - - // Check to see if $username exists already - if ($user = get_user_by_username($username)) { - //return false; - throw new RegistrationException(elgg_echo('registration:userexists')); - } - - // If we're not allowed multiple emails then see if this address has been used before - if ((!$allow_multiple_emails) && (get_user_by_email($email))) - { - throw new RegistrationException(elgg_echo('registration:dupeemail')); - } - - access_show_hidden_entities($access_status); - - // Check to see if we've registered the first admin yet. - // If not, this is the first admin user! - $admin = datalist_get('admin_registered'); - - // Otherwise ... - $user = new ElggUser(); - $user->username = $username; - $user->email = $email; - $user->name = $name; - $user->access_id = ACCESS_PUBLIC; - $user->salt = generate_random_cleartext_password(); // Note salt generated before password! + throw new RegistrationException(elgg_echo('registration:invalidchars')); + + $result = true; + return trigger_plugin_hook('registeruser:validate:username', 'all', array('username' => $username), $result); + } + + /** + * Simple validation of a password. + * + * @param string $password + * @throws RegistrationException on invalid + */ + function validate_password($password) + { + if (strlen($password)<6) throw new RegistrationException(elgg_echo('registration:passwordtooshort')); + + $result = true; + return trigger_plugin_hook('registeruser:validate:password', 'all', array('password' => $password), $result); + } + + /** + * Simple validation of a email. + * + * @param string $address + * @throws RegistrationException on invalid + * @return bool + */ + function validate_email_address($address) + { + if (!is_email_address($address)) throw new RegistrationException(elgg_echo('registration:notemail')); + + // Got here, so lets try a hook (defaulting to ok) + $result = true; + return trigger_plugin_hook('registeruser:validate:email', 'all', array('email' => $address), $result); + } + + /** + * Registers a user, returning false if the username already exists + * + * @param string $username The username of the new user + * @param string $password The password + * @param string $name The user's display name + * @param string $email Their email address + * @param bool $allow_multiple_emails Allow the same email address to be registered multiple times? + * @param int $friend_guid Optionally, GUID of a user this user will friend once fully registered + * @return int|false The new user's GUID; false on failure + */ + function register_user($username, $password, $name, $email, $allow_multiple_emails = false, $friend_guid = 0, $invitecode = '') { + + // Load the configuration + global $CONFIG; + + $username = trim($username); + $password = trim($password); + $name = trim($name); + $email = trim($email); + + // A little sanity checking + if (empty($username) + || empty($password) + || empty($name) + || empty($email)) { + return false; + } + + // See if it exists and is disabled + $access_status = access_get_show_hidden_status(); + access_show_hidden_entities(true); + + // Validate email address + if (!validate_email_address($email)) throw new RegistrationException(elgg_echo('registration:emailnotvalid')); + + // Validate password + if (!validate_password($password)) throw new RegistrationException(elgg_echo('registration:passwordnotvalid')); + + // Validate the username + if (!validate_username($username)) throw new RegistrationException(elgg_echo('registration:usernamenotvalid')); + + // Check to see if $username exists already + if ($user = get_user_by_username($username)) { + //return false; + throw new RegistrationException(elgg_echo('registration:userexists')); + } + + // If we're not allowed multiple emails then see if this address has been used before + if ((!$allow_multiple_emails) && (get_user_by_email($email))) + { + throw new RegistrationException(elgg_echo('registration:dupeemail')); + } + + access_show_hidden_entities($access_status); + + // Check to see if we've registered the first admin yet. + // If not, this is the first admin user! + $admin = datalist_get('admin_registered'); + + // Otherwise ... + $user = new ElggUser(); + $user->username = $username; + $user->email = $email; + $user->name = $name; + $user->access_id = ACCESS_PUBLIC; + $user->salt = generate_random_cleartext_password(); // Note salt generated before password! $user->password = generate_user_password($user, $password); $user->owner_guid = 0; // Users aren't owned by anyone, even if they are admin created. - $user->container_guid = 0; // Users aren't contained by anyone, even if they are admin created. - $user->save(); - - // If $friend_guid has been set, make mutual friends - if ($friend_guid) { - if ($friend_user = get_user($friend_guid)) { - if ($invitecode == generate_invite_code($friend_user->username)) { - $user->addFriend($friend_guid); - $friend_user->addFriend($user->guid); - } - } - } - - global $registering_admin; - if (!$admin) { - $user->admin = true; - datalist_set('admin_registered',1); - $registering_admin = true; - } else { - $registering_admin = false; - } - - // Turn on email notifications by default - set_user_notification_setting($user->getGUID(), 'email', true); - - return $user->getGUID(); - } - - /** - * Generates a unique invite code for a user - * - * @param string $username The username of the user sending the invitation - * @return string Invite code - */ - function generate_invite_code($username) { - - $secret = datalist_get('__site_secret__'); - return md5($username . $secret); - - } - - /** - * Adds collection submenu items - * - */ - function collections_submenu_items() { - global $CONFIG; - $user = get_loggedin_user(); - add_submenu_item(elgg_echo('friends:collections'), $CONFIG->wwwroot . "pg/collections/" . $user->username); - add_submenu_item(elgg_echo('friends:collections:add'),$CONFIG->wwwroot."pg/collections/add"); - } - - /** - * Page handler for friends - * - */ - function friends_page_handler($page_elements) { - - if (isset($page_elements[0]) && $user = get_user_by_username($page_elements[0])) { - set_page_owner($user->getGUID()); - } - if ($_SESSION['guid'] == page_owner()) { - collections_submenu_items(); - } - require_once(dirname(dirname(dirname(__FILE__))) . "/friends/index.php"); - - } - - /** - * Page handler for friends of - * - */ - function friends_of_page_handler($page_elements) { - - if (isset($page_elements[0]) && $user = get_user_by_username($page_elements[0])) { - set_page_owner($user->getGUID()); - } - if ($_SESSION['guid'] == page_owner()) { - collections_submenu_items(); - } - require_once(dirname(dirname(dirname(__FILE__))) . "/friends/of.php"); - - } - - /** - * Page handler for friends of - * - */ - function collections_page_handler($page_elements) { - - if (isset($page_elements[0])) { - if ($page_elements[0] == "add") { - set_page_owner($_SESSION['guid']); - collections_submenu_items(); - require_once(dirname(dirname(dirname(__FILE__))) . "/friends/add.php"); - } else { - if ($user = get_user_by_username($page_elements[0])) { - set_page_owner($user->getGUID()); - if ($_SESSION['guid'] == page_owner()) { - collections_submenu_items(); - } - require_once(dirname(dirname(dirname(__FILE__))) . "/friends/collections.php"); - } - } - } - - } - - /** - * Page handler for dashboard - */ - function dashboard_page_handler($page_elements) { - @require_once(dirname(dirname(dirname(__FILE__))) . "/dashboard/index.php"); - } - - /** - * Sets the last action time of the given user to right now. - * - * @param int $user_guid The user GUID - */ - function set_last_action($user_guid) { - - $user_guid = (int) $user_guid; - global $CONFIG; - $time = time(); - - execute_delayed_write_query("UPDATE {$CONFIG->dbprefix}users_entity set prev_last_action = last_action, last_action = {$time} where guid = {$user_guid}"); - - } - - /** - * Sets the last logon time of the given user to right now. - * - * @param int $user_guid The user GUID - */ - function set_last_login($user_guid) { - - $user_guid = (int) $user_guid; - global $CONFIG; - $time = time(); - - execute_delayed_write_query("UPDATE {$CONFIG->dbprefix}users_entity set prev_last_login = last_login, last_login = {$time} where guid = {$user_guid}"); - - } - - /** - * A permissions plugin hook that grants access to users if they are newly created - allows - * for email activation. - * - * TODO: Do this in a better way! - * - * @param unknown_type $hook - * @param unknown_type $entity_type - * @param unknown_type $returnvalue - * @param unknown_type $params - */ - function new_user_enable_permissions_check($hook, $entity_type, $returnvalue, $params) - { - $entity = $params['entity']; - $user = $params['user']; - if (($entity) && ($entity instanceof ElggUser)) - { - if ( - (($entity->disable_reason == 'new_user') || ( - // if this isn't set at all they're a "new user" - !$entity->validated - )) - && (!isloggedin())) - return true; - - } - - return $returnvalue; - } - - /** - * Sets up user-related menu items - * - */ - function users_pagesetup() { - - // Load config - global $CONFIG; - - //add submenu options - if (get_context() == "friends" || - get_context() == "friendsof" || - get_context() == "collections") { - add_submenu_item(elgg_echo('friends'),$CONFIG->wwwroot."pg/friends/" . page_owner_entity()->username); - add_submenu_item(elgg_echo('friends:of'),$CONFIG->wwwroot."pg/friendsof/" . page_owner_entity()->username); - } - - } - - /** - * Users initialisation function, which establishes the page handler - * - */ - function users_init() { - - // Load config - global $CONFIG; - - // Set up menu for logged in users - if (isloggedin()) { - $user = get_loggedin_user(); - add_menu(elgg_echo('friends'), $CONFIG->wwwroot . "pg/friends/" . $user->username); - } - - register_page_handler('friends','friends_page_handler'); - register_page_handler('friendsof','friends_of_page_handler'); - register_page_handler('collections','collections_page_handler'); - register_page_handler('dashboard','dashboard_page_handler'); - register_action("register",true); - register_action("useradd",true); - register_action("friends/add"); - register_action("friends/remove"); - register_action('friends/addcollection'); - register_action('friends/deletecollection'); - register_action('friends/editcollection'); - register_action("user/spotlight"); - - register_action("usersettings/save"); - - register_action("user/passwordreset"); - register_action("user/requestnewpassword"); - - // User name change - extend_elgg_settings_page('user/settings/name', 'usersettings/user', 1); - //register_action("user/name"); - - // User password change - extend_elgg_settings_page('user/settings/password', 'usersettings/user', 1); - //register_action("user/password"); - - // Add email settings - extend_elgg_settings_page('user/settings/email', 'usersettings/user', 1); - //register_action("email/save"); - - // Add language settings - extend_elgg_settings_page('user/settings/language', 'usersettings/user', 1); - - // Add default access settings - extend_elgg_settings_page('user/settings/default_access', 'usersettings/user', 1); - - //register_action("user/language"); - - // Register the user type - register_entity_type('user',''); - - register_plugin_hook('usersettings:save','user','users_settings_save'); - register_plugin_hook('search','all','search_list_users_by_name'); - - - // Handle a special case for newly created users when the user is not logged in - // TODO: handle this better! - register_plugin_hook('permissions_check','all','new_user_enable_permissions_check'); - } - - /** - * Returns a formatted list of users suitable for injecting into search. - * - */ - function search_list_users_by_name($hook, $user, $returnvalue, $tag) { - - // Change this to set the number of users that display on the search page - $threshold = 4; - - $object = get_input('object'); - - if (!get_input('offset') && (empty($object) || $object == 'user')) - if ($users = search_for_user($tag,$threshold)) { - - $countusers = search_for_user($tag,0,0,"",true); - - $return = elgg_view('user/search/startblurb',array('count' => $countusers, 'tag' => $tag)); - foreach($users as $user) { - $return .= elgg_view_entity($user); - } - $return .= elgg_view('user/search/finishblurb',array('count' => $countusers, 'threshold' => $threshold, 'tag' => $tag)); - return $return; - - } - - } - - function users_settings_save() { - - global $CONFIG; - @include($CONFIG->path . "actions/user/name.php"); - @include($CONFIG->path . "actions/user/password.php"); - @include($CONFIG->path . "actions/email/save.php"); - @include($CONFIG->path . "actions/user/language.php"); - @include($CONFIG->path . "actions/user/default_access.php"); - - } - - //register actions ************************************************************* - - register_elgg_event_handler('init','system','users_init',0); - register_elgg_event_handler('pagesetup','system','users_pagesetup',0); - + $user->container_guid = 0; // Users aren't contained by anyone, even if they are admin created. + $user->save(); + + // If $friend_guid has been set, make mutual friends + if ($friend_guid) { + if ($friend_user = get_user($friend_guid)) { + if ($invitecode == generate_invite_code($friend_user->username)) { + $user->addFriend($friend_guid); + $friend_user->addFriend($user->guid); + } + } + } + + global $registering_admin; + if (!$admin) { + $user->admin = true; + datalist_set('admin_registered',1); + $registering_admin = true; + } else { + $registering_admin = false; + } + + // Turn on email notifications by default + set_user_notification_setting($user->getGUID(), 'email', true); + + return $user->getGUID(); + } + + /** + * Generates a unique invite code for a user + * + * @param string $username The username of the user sending the invitation + * @return string Invite code + */ + function generate_invite_code($username) { + + $secret = datalist_get('__site_secret__'); + return md5($username . $secret); + + } + + /** + * Adds collection submenu items + * + */ + function collections_submenu_items() { + global $CONFIG; + $user = get_loggedin_user(); + add_submenu_item(elgg_echo('friends:collections'), $CONFIG->wwwroot . "pg/collections/" . $user->username); + add_submenu_item(elgg_echo('friends:collections:add'),$CONFIG->wwwroot."pg/collections/add"); + } + + /** + * Page handler for friends + * + */ + function friends_page_handler($page_elements) { + + if (isset($page_elements[0]) && $user = get_user_by_username($page_elements[0])) { + set_page_owner($user->getGUID()); + } + if ($_SESSION['guid'] == page_owner()) { + collections_submenu_items(); + } + require_once(dirname(dirname(dirname(__FILE__))) . "/friends/index.php"); + + } + + /** + * Page handler for friends of + * + */ + function friends_of_page_handler($page_elements) { + + if (isset($page_elements[0]) && $user = get_user_by_username($page_elements[0])) { + set_page_owner($user->getGUID()); + } + if ($_SESSION['guid'] == page_owner()) { + collections_submenu_items(); + } + require_once(dirname(dirname(dirname(__FILE__))) . "/friends/of.php"); + + } + + /** + * Page handler for friends of + * + */ + function collections_page_handler($page_elements) { + + if (isset($page_elements[0])) { + if ($page_elements[0] == "add") { + set_page_owner($_SESSION['guid']); + collections_submenu_items(); + require_once(dirname(dirname(dirname(__FILE__))) . "/friends/add.php"); + } else { + if ($user = get_user_by_username($page_elements[0])) { + set_page_owner($user->getGUID()); + if ($_SESSION['guid'] == page_owner()) { + collections_submenu_items(); + } + require_once(dirname(dirname(dirname(__FILE__))) . "/friends/collections.php"); + } + } + } + + } + + /** + * Page handler for dashboard + */ + function dashboard_page_handler($page_elements) { + @require_once(dirname(dirname(dirname(__FILE__))) . "/dashboard/index.php"); + } + + /** + * Sets the last action time of the given user to right now. + * + * @param int $user_guid The user GUID + */ + function set_last_action($user_guid) { + + $user_guid = (int) $user_guid; + global $CONFIG; + $time = time(); + + execute_delayed_write_query("UPDATE {$CONFIG->dbprefix}users_entity set prev_last_action = last_action, last_action = {$time} where guid = {$user_guid}"); + + } + + /** + * Sets the last logon time of the given user to right now. + * + * @param int $user_guid The user GUID + */ + function set_last_login($user_guid) { + + $user_guid = (int) $user_guid; + global $CONFIG; + $time = time(); + + execute_delayed_write_query("UPDATE {$CONFIG->dbprefix}users_entity set prev_last_login = last_login, last_login = {$time} where guid = {$user_guid}"); + + } + + /** + * A permissions plugin hook that grants access to users if they are newly created - allows + * for email activation. + * + * TODO: Do this in a better way! + * + * @param unknown_type $hook + * @param unknown_type $entity_type + * @param unknown_type $returnvalue + * @param unknown_type $params + */ + function new_user_enable_permissions_check($hook, $entity_type, $returnvalue, $params) + { + $entity = $params['entity']; + $user = $params['user']; + if (($entity) && ($entity instanceof ElggUser)) + { + if ( + (($entity->disable_reason == 'new_user') || ( + // if this isn't set at all they're a "new user" + !$entity->validated + )) + && (!isloggedin())) + return true; + + } + + return $returnvalue; + } + + /** + * Sets up user-related menu items + * + */ + function users_pagesetup() { + + // Load config + global $CONFIG; + + //add submenu options + if (get_context() == "friends" || + get_context() == "friendsof" || + get_context() == "collections") { + add_submenu_item(elgg_echo('friends'),$CONFIG->wwwroot."pg/friends/" . page_owner_entity()->username); + add_submenu_item(elgg_echo('friends:of'),$CONFIG->wwwroot."pg/friendsof/" . page_owner_entity()->username); + } + + } + + /** + * Users initialisation function, which establishes the page handler + * + */ + function users_init() { + + // Load config + global $CONFIG; + + // Set up menu for logged in users + if (isloggedin()) { + $user = get_loggedin_user(); + add_menu(elgg_echo('friends'), $CONFIG->wwwroot . "pg/friends/" . $user->username); + } + + register_page_handler('friends','friends_page_handler'); + register_page_handler('friendsof','friends_of_page_handler'); + register_page_handler('collections','collections_page_handler'); + register_page_handler('dashboard','dashboard_page_handler'); + register_action("register",true); + register_action("useradd",true); + register_action("friends/add"); + register_action("friends/remove"); + register_action('friends/addcollection'); + register_action('friends/deletecollection'); + register_action('friends/editcollection'); + register_action("user/spotlight"); + + register_action("usersettings/save"); + + register_action("user/passwordreset"); + register_action("user/requestnewpassword"); + + // User name change + extend_elgg_settings_page('user/settings/name', 'usersettings/user', 1); + //register_action("user/name"); + + // User password change + extend_elgg_settings_page('user/settings/password', 'usersettings/user', 1); + //register_action("user/password"); + + // Add email settings + extend_elgg_settings_page('user/settings/email', 'usersettings/user', 1); + //register_action("email/save"); + + // Add language settings + extend_elgg_settings_page('user/settings/language', 'usersettings/user', 1); + + // Add default access settings + extend_elgg_settings_page('user/settings/default_access', 'usersettings/user', 1); + + //register_action("user/language"); + + // Register the user type + register_entity_type('user',''); + + register_plugin_hook('usersettings:save','user','users_settings_save'); + register_plugin_hook('search','all','search_list_users_by_name'); + + + // Handle a special case for newly created users when the user is not logged in + // TODO: handle this better! + register_plugin_hook('permissions_check','all','new_user_enable_permissions_check'); + } + + /** + * Returns a formatted list of users suitable for injecting into search. + * + */ + function search_list_users_by_name($hook, $user, $returnvalue, $tag) { + + // Change this to set the number of users that display on the search page + $threshold = 4; + + $object = get_input('object'); + + if (!get_input('offset') && (empty($object) || $object == 'user')) + if ($users = search_for_user($tag,$threshold)) { + + $countusers = search_for_user($tag,0,0,"",true); + + $return = elgg_view('user/search/startblurb',array('count' => $countusers, 'tag' => $tag)); + foreach($users as $user) { + $return .= elgg_view_entity($user); + } + $return .= elgg_view('user/search/finishblurb',array('count' => $countusers, 'threshold' => $threshold, 'tag' => $tag)); + return $return; + + } + + } + + function users_settings_save() { + + global $CONFIG; + @include($CONFIG->path . "actions/user/name.php"); + @include($CONFIG->path . "actions/user/password.php"); + @include($CONFIG->path . "actions/email/save.php"); + @include($CONFIG->path . "actions/user/language.php"); + @include($CONFIG->path . "actions/user/default_access.php"); + + } + + //register actions ************************************************************* + + register_elgg_event_handler('init','system','users_init',0); + register_elgg_event_handler('pagesetup','system','users_pagesetup',0); + ?> \ No newline at end of file diff --git a/engine/lib/version.php b/engine/lib/version.php index 47bb36972..2476a0b75 100644 --- a/engine/lib/version.php +++ b/engine/lib/version.php @@ -1,14 +1,14 @@ -path . "version.php")) { - if (!$humanreadable) return $version; - return $release; - } - - return false; - - } - - /** - * Determines whether or not the database needs to be upgraded. - * - * @return true|false Depending on whether or not the db version matches the code version - */ - function version_upgrade_check() { - - $dbversion = (int) datalist_get('version'); - $version = get_version(); - - if ($version > $dbversion) { - return true; - } - return false; - - } - - /** - * Upgrades Elgg - * - */ - function version_upgrade() { - - $dbversion = (int) datalist_get('version'); + } + + /** + * Get the current version information + * + * @param true|false $humanreadable Whether to return a human readable version (default: false) + * @return string|false Depending on success + */ + function get_version($humanreadable = false) { + + global $CONFIG; + if (@include($CONFIG->path . "version.php")) { + if (!$humanreadable) return $version; + return $release; + } + + return false; + + } + + /** + * Determines whether or not the database needs to be upgraded. + * + * @return true|false Depending on whether or not the db version matches the code version + */ + function version_upgrade_check() { + + $dbversion = (int) datalist_get('version'); + $version = get_version(); + + if ($version > $dbversion) { + return true; + } + return false; + + } + + /** + * Upgrades Elgg + * + */ + function version_upgrade() { + + $dbversion = (int) datalist_get('version'); // Upgrade database - db_upgrade($dbversion); + db_upgrade($dbversion); system_message(elgg_echo('upgrade:db')); // Upgrade core @@ -121,8 +121,8 @@ trigger_elgg_event('upgrade', 'upgrade', $upgrade_details); // Update the version - datalist_set('version', get_version()); - - } - + datalist_set('version', get_version()); + + } + ?> \ No newline at end of file diff --git a/engine/lib/widgets.php b/engine/lib/widgets.php index 8793370ef..f6f01f660 100644 --- a/engine/lib/widgets.php +++ b/engine/lib/widgets.php @@ -1,528 +1,528 @@ -attributes['subtype'] = "widget"; + } + + public function __construct($guid = null) { parent::__construct($guid); } + + /** + * Override entity get and sets in order to save data to private data store. + */ + public function get($name) + { + // See if its in our base attribute + if (isset($this->attributes[$name])) { + return $this->attributes[$name]; + } + + // No, so see if its in the private data store. + $meta = get_private_setting($this->guid, $name); + if ($meta) + return $meta; + + // Can't find it, so return null + return null; + } + + /** + * Override entity get and sets in order to save data to private data store. + */ + public function set($name, $value) + { + if (array_key_exists($name, $this->attributes)) + { + // Check that we're not trying to change the guid! + if ((array_key_exists('guid', $this->attributes)) && ($name=='guid')) + return false; + + $this->attributes[$name] = $value; + } + else + return set_private_setting($this->guid, $name, $value); + + return true; + } + } + + /** + * Register a particular context for use with widgets. + * + * @param string $context The context we wish to enable context for + */ + function use_widgets($context) { + + global $CONFIG; + if (!isset($CONFIG->widgets)) + $CONFIG->widgets = new stdClass; + if (!isset($CONFIG->widgets->contexts)) { + $CONFIG->widgets->contexts = array(); + } + if (!empty($context)) { + $CONFIG->widgets->contexts[] = $context; + } + + } + + /** + * Determines whether or not the current context is using widgets + * + * @return true|false Depending on widget status + */ + function using_widgets() { + + global $CONFIG; + $context = get_context(); + if (isset($CONFIG->widgets->contexts) && is_array($CONFIG->widgets->contexts)) { + if (in_array($context, $CONFIG->widgets->contexts)) return true; + } + + return false; + + } + + /** + * When given a widget entity and a new requested location, saves the new location + * and also provides a sensible ordering for all widgets in that column + * + * @param ElggObject $widget The widget entity + * @param int $order The order within the column + * @param int $column The column (1, 2 or 3) + * @return true|false Depending on success + */ + function save_widget_location(ElggObject $widget, $order, $column) { + + if ($widget instanceof ElggObject) { + if ($widget->subtype == "widget") { + + // If you can't move the widget, don't save a new location + if (!$widget->draggable) + return false; + + // Sanitise the column value + if ($column != 1 || $column != 2 || $column != 3) + $column = 1; + + $widget->column = (int) $column; + + $ordertmp = array(); + + if ($entities = get_entities_from_metadata_multi(array( + 'context' => $widget->context, + 'column' => $column, + ),'object','widget')) { + foreach($entities as $entity) { + $entityorder = $entity->order; + if ($entityorder < $order) { + $ordertmp[$entityorder] = $entity; + } + if ($entityorder >= $order) { + $ordertmp[$entityorder + 10000] = $entity; + } + } + } + + $ordertmp[$order] = $widget; + ksort($ordertmp); + + $orderticker = 10; + foreach($ordertmp as $orderval => $entity) { + $entity->order = $orderticker; + $orderticker += 10; + } + + return true; + + } else { + register_error($widget->subtype); + } + + } + + return false; + + } + + /** + * Get widgets for a particular context and column, in order of display + * + * @param int $user_guid The owner user GUID + * @param string $context The context (profile, dashboard etc) + * @param int $column The column (1 or 2) + * @return array|false An array of widget ElggObjects, or false + */ + function get_widgets($user_guid, $context, $column) { + + if ($widgets = get_entities_from_private_setting_multi(array( + 'column' => $column, + 'context' => $context), "object", "widget", $user_guid, "", 10000)) + /*if ($widgets = get_user_objects_by_metadata($user_guid, "widget", array( + 'column' => $column, + 'context' => $context, + ), 10000)) { + */ + { + + $widgetorder = array(); + foreach($widgets as $widget) { + $order = $widget->order; + while(isset($widgetorder[$order])) { + $order++; + } + $widgetorder[$order] = $widget; + } + + ksort($widgetorder); + + return $widgetorder; + + } + + return false; + + } + + /** + * Displays a particular widget + * + * @param ElggObject $widget The widget to display + * @return string The HTML for the widget, including JavaScript wrapper + */ + function display_widget(ElggObject $widget) { + + return elgg_view_entity($widget); + + } + + /** + * Add a new widget + * + * @param int $user_guid User GUID to associate this widget with + * @param string $handler The handler for this widget + * @param string $context The page context for this widget + * @param int $order The order to display this widget in + * @param int $column The column to display this widget in (1, 2 or 3) + * @param int $access_id If not specified, it is set to the default access level + * @return true|false Depending on success + */ + function add_widget($user_guid, $handler, $context, $order = 0, $column = 1, $access_id = null) { + + if (empty($user_guid) || empty($context) || empty($handler) || !widget_type_exists($handler)) + return false; + + if ($user = get_user($user_guid)) { + + $widget = new ElggWidget; + $widget->owner_guid = $user_guid; + $widget->container_guid = $user_guid; + if (isset($access_id)) { + $widget->access_id = $access_id; + } else { + $widget->access_id = get_default_access(); + } + + if (!$widget->save()) + return false; + + $widget->handler = $handler; + $widget->context = $context; + $widget->column = $column; + $widget->order = $order; + + // save_widget_location($widget, $order, $column); + return true; + + } + + return false; + + } + + /** + * Define a new widget type + * + * @param string $handler The identifier for the widget handler + * @param string $name The name of the widget type + * @param string $description A description for the widget type + * @param string $context A comma-separated list of contexts where this widget is allowed (default: 'all') + * @param true|false $multiple Whether or not multiple instances of this widget are allowed on a single dashboard (default: false) + * @param string $position A comma-separated list of positions on the page (side or main) where this widget is allowed (default: "side,main") + * @return true|false Depending on success + */ + + function add_widget_type($handler, $name, $description, $context = "all", $multiple = false, $positions = "side,main") { + + if (!empty($handler) && !empty($name)) { + + global $CONFIG; + + if (!isset($CONFIG->widgets)) + $CONFIG->widgets = new stdClass; + + if (!isset($CONFIG->widgets->handlers)) + $CONFIG->widgets->handlers = array(); + + $handlerobj = new stdClass; + $handlerobj->name = $name; + $handlerobj->description = $description; + $handlerobj->context = explode(",",$context); + $handlerobj->multiple = $multiple; + $handlerobj->positions = explode(",",$positions); + + $CONFIG->widgets->handlers[$handler] = $handlerobj; + + return true; + + } + + return false; + + } + + /** + * Determines whether or not widgets with the specified handler have been defined + * + * @param string $handler The widget handler identifying string + * @return true|false Whether or not those widgets exist + */ + function widget_type_exists($handler) { + + global $CONFIG; + if (!empty($CONFIG->widgets) + && !empty($CONFIG->widgets->handlers) + && is_array($CONFIG->widgets->handlers) + && array_key_exists($handler, $CONFIG->widgets->handlers)) + return true; + + return false; + + } + + /** + * Returns an array of stdClass objects representing the defined widget types + * + * @return array A list of types defined (if any) + */ + function get_widget_types() { + + global $CONFIG; + if (!empty($CONFIG->widgets) + && !empty($CONFIG->widgets->handlers) + && is_array($CONFIG->widgets->handlers)) { + + $context = get_context(); + + foreach($CONFIG->widgets->handlers as $key => $handler) { + if (!in_array('all',$handler->context) && + !in_array($context,$handler->context)) { + unset($CONFIG->widgets->handlers[$key]); + } + } + + return $CONFIG->widgets->handlers; + + } + + return array(); + + } + + /** + * Saves a widget's settings (by passing an array of (name => value) pairs to save_{$handler}_widget) + * + * @param int $widget_guid The GUID of the widget we're saving to + * @param array $params An array of name => value parameters + */ + function save_widget_info($widget_guid, $params) { + + if ($widget = get_entity($widget_guid)) { + + $subtype = $widget->getSubtype(); + + if ($subtype != "widget") return false; + $handler = $widget->handler; + if (empty($handler) || !widget_type_exists($handler)) return false; + + if (!$widget->canEdit()) return false; + + // Save the params to the widget + if (is_array($params) && sizeof($params) > 0) { + foreach($params as $name => $value) { + + if (!empty($name) && !in_array($name,array( + 'guid','owner_guid','site_guid' + ))) { + if (is_array($value)) + { + // TODO: Handle arrays securely + $widget->setMetaData($name, $value, "", true); + }else + $widget->$name = $value; + } + } + $widget->save(); + } + + $function = "save_{$handler}_widget"; + if (is_callable($function)) { + return $function($params); + } + + return true; + + } + + return false; + + } + + function reorder_widgets_from_panel($panelstring1, $panelstring2, $panelstring3, $context, $owner) { + + $return = true; + + $mainwidgets = explode('::',$panelstring1); + $sidewidgets = explode('::',$panelstring2); + $rightwidgets = explode('::',$panelstring3); + + $handlers = array(); + $guids = array(); + + if (is_array($mainwidgets) && sizeof($mainwidgets) > 0) { + foreach($mainwidgets as $widget) { + + $guid = (int) $widget; + + if ("{$guid}" == "{$widget}") { + $guids[1][] = $widget; + } else { + $handlers[1][] = $widget; + } + + } + } + if (is_array($sidewidgets) && sizeof($sidewidgets) > 0) { + foreach($sidewidgets as $widget) { + + $guid = (int) $widget; + + if ("{$guid}" == "{$widget}") { + $guids[2][] = $widget; + } else { + $handlers[2][] = $widget; + } + + } + } + if (is_array($rightwidgets) && sizeof($rightwidgets) > 0) { + foreach($rightwidgets as $widget) { + + $guid = (int) $widget; + + if ("{$guid}" == "{$widget}") { + $guids[3][] = $widget; + } else { + $handlers[3][] = $widget; + } + + } + } + + // Reorder existing widgets or delete ones that have vanished + foreach (array(1,2,3) as $column) { + if ($dbwidgets = get_widgets($owner,$context,$column)) { + + foreach($dbwidgets as $dbwidget) { + if (in_array($dbwidget->getGUID(),$guids[1]) || in_array($dbwidget->getGUID(),$guids[2]) || in_array($dbwidget->getGUID(),$guids[3])) { + if (in_array($dbwidget->getGUID(),$guids[1])) { + $pos = array_search($dbwidget->getGUID(),$guids[1]); + $col = 1; + } else if (in_array($dbwidget->getGUID(),$guids[2])) { + $pos = array_search($dbwidget->getGUID(),$guids[2]); + $col = 2; + } else { + $pos = array_search($dbwidget->getGUID(),$guids[3]); + $col = 3; + } + $pos = ($pos + 1) * 10; + $dbwidget->column = $col; + $dbwidget->order = $pos; + } else { + $dbguid = $dbwidget->getGUID(); + if (!$dbwidget->delete()) { + $return = false; + } else { + // Remove state cookie + setcookie('widget' + $dbguid, null); + } + } + } + + } + // Add new ones + if (sizeof($guids[$column]) > 0) { + foreach($guids[$column] as $key => $guid) { + if ($guid == 0) { + $pos = ($key + 1) * 10; + $handler = $handlers[$column][$key]; + if (!add_widget($owner,$handler,$context,$pos,$column)) + $return = false; + } + } + } + } + + return $return; + + } + + /** + * Run some things once. + * + */ + function widget_run_once() + { + // Register a class + add_subtype("object", "widget", "ElggWidget"); + } + + /** + * Function to initialise widgets functionality on Elgg init + * + */ + function widgets_init() { + + register_action('widgets/reorder'); + register_action('widgets/save'); + register_action('widgets/add'); + + // Now run this stuff, but only once + run_function_once("widget_run_once"); + } + + // Register event + register_elgg_event_handler('init','system','widgets_init'); + + // Use widgets on the dashboard + use_widgets('dashboard'); - * @link http://elgg.org/ - */ - - /** - * Override ElggObject in order to store widget data in ultra-private stores. - */ - class ElggWidget extends ElggObject - { - protected function initialise_attributes() - { - parent::initialise_attributes(); - - $this->attributes['subtype'] = "widget"; - } - - public function __construct($guid = null) { parent::__construct($guid); } - - /** - * Override entity get and sets in order to save data to private data store. - */ - public function get($name) - { - // See if its in our base attribute - if (isset($this->attributes[$name])) { - return $this->attributes[$name]; - } - - // No, so see if its in the private data store. - $meta = get_private_setting($this->guid, $name); - if ($meta) - return $meta; - - // Can't find it, so return null - return null; - } - - /** - * Override entity get and sets in order to save data to private data store. - */ - public function set($name, $value) - { - if (array_key_exists($name, $this->attributes)) - { - // Check that we're not trying to change the guid! - if ((array_key_exists('guid', $this->attributes)) && ($name=='guid')) - return false; - - $this->attributes[$name] = $value; - } - else - return set_private_setting($this->guid, $name, $value); - - return true; - } - } - - /** - * Register a particular context for use with widgets. - * - * @param string $context The context we wish to enable context for - */ - function use_widgets($context) { - - global $CONFIG; - if (!isset($CONFIG->widgets)) - $CONFIG->widgets = new stdClass; - if (!isset($CONFIG->widgets->contexts)) { - $CONFIG->widgets->contexts = array(); - } - if (!empty($context)) { - $CONFIG->widgets->contexts[] = $context; - } - - } - - /** - * Determines whether or not the current context is using widgets - * - * @return true|false Depending on widget status - */ - function using_widgets() { - - global $CONFIG; - $context = get_context(); - if (isset($CONFIG->widgets->contexts) && is_array($CONFIG->widgets->contexts)) { - if (in_array($context, $CONFIG->widgets->contexts)) return true; - } - - return false; - - } - - /** - * When given a widget entity and a new requested location, saves the new location - * and also provides a sensible ordering for all widgets in that column - * - * @param ElggObject $widget The widget entity - * @param int $order The order within the column - * @param int $column The column (1, 2 or 3) - * @return true|false Depending on success - */ - function save_widget_location(ElggObject $widget, $order, $column) { - - if ($widget instanceof ElggObject) { - if ($widget->subtype == "widget") { - - // If you can't move the widget, don't save a new location - if (!$widget->draggable) - return false; - - // Sanitise the column value - if ($column != 1 || $column != 2 || $column != 3) - $column = 1; - - $widget->column = (int) $column; - - $ordertmp = array(); - - if ($entities = get_entities_from_metadata_multi(array( - 'context' => $widget->context, - 'column' => $column, - ),'object','widget')) { - foreach($entities as $entity) { - $entityorder = $entity->order; - if ($entityorder < $order) { - $ordertmp[$entityorder] = $entity; - } - if ($entityorder >= $order) { - $ordertmp[$entityorder + 10000] = $entity; - } - } - } - - $ordertmp[$order] = $widget; - ksort($ordertmp); - - $orderticker = 10; - foreach($ordertmp as $orderval => $entity) { - $entity->order = $orderticker; - $orderticker += 10; - } - - return true; - - } else { - register_error($widget->subtype); - } - - } - - return false; - - } - - /** - * Get widgets for a particular context and column, in order of display - * - * @param int $user_guid The owner user GUID - * @param string $context The context (profile, dashboard etc) - * @param int $column The column (1 or 2) - * @return array|false An array of widget ElggObjects, or false - */ - function get_widgets($user_guid, $context, $column) { - - if ($widgets = get_entities_from_private_setting_multi(array( - 'column' => $column, - 'context' => $context), "object", "widget", $user_guid, "", 10000)) - /*if ($widgets = get_user_objects_by_metadata($user_guid, "widget", array( - 'column' => $column, - 'context' => $context, - ), 10000)) { - */ - { - - $widgetorder = array(); - foreach($widgets as $widget) { - $order = $widget->order; - while(isset($widgetorder[$order])) { - $order++; - } - $widgetorder[$order] = $widget; - } - - ksort($widgetorder); - - return $widgetorder; - - } - - return false; - - } - - /** - * Displays a particular widget - * - * @param ElggObject $widget The widget to display - * @return string The HTML for the widget, including JavaScript wrapper - */ - function display_widget(ElggObject $widget) { - - return elgg_view_entity($widget); - - } - - /** - * Add a new widget - * - * @param int $user_guid User GUID to associate this widget with - * @param string $handler The handler for this widget - * @param string $context The page context for this widget - * @param int $order The order to display this widget in - * @param int $column The column to display this widget in (1, 2 or 3) - * @param int $access_id If not specified, it is set to the default access level - * @return true|false Depending on success - */ - function add_widget($user_guid, $handler, $context, $order = 0, $column = 1, $access_id = null) { - - if (empty($user_guid) || empty($context) || empty($handler) || !widget_type_exists($handler)) - return false; - - if ($user = get_user($user_guid)) { - - $widget = new ElggWidget; - $widget->owner_guid = $user_guid; - $widget->container_guid = $user_guid; - if (isset($access_id)) { - $widget->access_id = $access_id; - } else { - $widget->access_id = get_default_access(); - } - - if (!$widget->save()) - return false; - - $widget->handler = $handler; - $widget->context = $context; - $widget->column = $column; - $widget->order = $order; - - // save_widget_location($widget, $order, $column); - return true; - - } - - return false; - - } - - /** - * Define a new widget type - * - * @param string $handler The identifier for the widget handler - * @param string $name The name of the widget type - * @param string $description A description for the widget type - * @param string $context A comma-separated list of contexts where this widget is allowed (default: 'all') - * @param true|false $multiple Whether or not multiple instances of this widget are allowed on a single dashboard (default: false) - * @param string $position A comma-separated list of positions on the page (side or main) where this widget is allowed (default: "side,main") - * @return true|false Depending on success - */ - - function add_widget_type($handler, $name, $description, $context = "all", $multiple = false, $positions = "side,main") { - - if (!empty($handler) && !empty($name)) { - - global $CONFIG; - - if (!isset($CONFIG->widgets)) - $CONFIG->widgets = new stdClass; - - if (!isset($CONFIG->widgets->handlers)) - $CONFIG->widgets->handlers = array(); - - $handlerobj = new stdClass; - $handlerobj->name = $name; - $handlerobj->description = $description; - $handlerobj->context = explode(",",$context); - $handlerobj->multiple = $multiple; - $handlerobj->positions = explode(",",$positions); - - $CONFIG->widgets->handlers[$handler] = $handlerobj; - - return true; - - } - - return false; - - } - - /** - * Determines whether or not widgets with the specified handler have been defined - * - * @param string $handler The widget handler identifying string - * @return true|false Whether or not those widgets exist - */ - function widget_type_exists($handler) { - - global $CONFIG; - if (!empty($CONFIG->widgets) - && !empty($CONFIG->widgets->handlers) - && is_array($CONFIG->widgets->handlers) - && array_key_exists($handler, $CONFIG->widgets->handlers)) - return true; - - return false; - - } - - /** - * Returns an array of stdClass objects representing the defined widget types - * - * @return array A list of types defined (if any) - */ - function get_widget_types() { - - global $CONFIG; - if (!empty($CONFIG->widgets) - && !empty($CONFIG->widgets->handlers) - && is_array($CONFIG->widgets->handlers)) { - - $context = get_context(); - - foreach($CONFIG->widgets->handlers as $key => $handler) { - if (!in_array('all',$handler->context) && - !in_array($context,$handler->context)) { - unset($CONFIG->widgets->handlers[$key]); - } - } - - return $CONFIG->widgets->handlers; - - } - - return array(); - - } - - /** - * Saves a widget's settings (by passing an array of (name => value) pairs to save_{$handler}_widget) - * - * @param int $widget_guid The GUID of the widget we're saving to - * @param array $params An array of name => value parameters - */ - function save_widget_info($widget_guid, $params) { - - if ($widget = get_entity($widget_guid)) { - - $subtype = $widget->getSubtype(); - - if ($subtype != "widget") return false; - $handler = $widget->handler; - if (empty($handler) || !widget_type_exists($handler)) return false; - - if (!$widget->canEdit()) return false; - - // Save the params to the widget - if (is_array($params) && sizeof($params) > 0) { - foreach($params as $name => $value) { - - if (!empty($name) && !in_array($name,array( - 'guid','owner_guid','site_guid' - ))) { - if (is_array($value)) - { - // TODO: Handle arrays securely - $widget->setMetaData($name, $value, "", true); - }else - $widget->$name = $value; - } - } - $widget->save(); - } - - $function = "save_{$handler}_widget"; - if (is_callable($function)) { - return $function($params); - } - - return true; - - } - - return false; - - } - - function reorder_widgets_from_panel($panelstring1, $panelstring2, $panelstring3, $context, $owner) { - - $return = true; - - $mainwidgets = explode('::',$panelstring1); - $sidewidgets = explode('::',$panelstring2); - $rightwidgets = explode('::',$panelstring3); - - $handlers = array(); - $guids = array(); - - if (is_array($mainwidgets) && sizeof($mainwidgets) > 0) { - foreach($mainwidgets as $widget) { - - $guid = (int) $widget; - - if ("{$guid}" == "{$widget}") { - $guids[1][] = $widget; - } else { - $handlers[1][] = $widget; - } - - } - } - if (is_array($sidewidgets) && sizeof($sidewidgets) > 0) { - foreach($sidewidgets as $widget) { - - $guid = (int) $widget; - - if ("{$guid}" == "{$widget}") { - $guids[2][] = $widget; - } else { - $handlers[2][] = $widget; - } - - } - } - if (is_array($rightwidgets) && sizeof($rightwidgets) > 0) { - foreach($rightwidgets as $widget) { - - $guid = (int) $widget; - - if ("{$guid}" == "{$widget}") { - $guids[3][] = $widget; - } else { - $handlers[3][] = $widget; - } - - } - } - - // Reorder existing widgets or delete ones that have vanished - foreach (array(1,2,3) as $column) { - if ($dbwidgets = get_widgets($owner,$context,$column)) { - - foreach($dbwidgets as $dbwidget) { - if (in_array($dbwidget->getGUID(),$guids[1]) || in_array($dbwidget->getGUID(),$guids[2]) || in_array($dbwidget->getGUID(),$guids[3])) { - if (in_array($dbwidget->getGUID(),$guids[1])) { - $pos = array_search($dbwidget->getGUID(),$guids[1]); - $col = 1; - } else if (in_array($dbwidget->getGUID(),$guids[2])) { - $pos = array_search($dbwidget->getGUID(),$guids[2]); - $col = 2; - } else { - $pos = array_search($dbwidget->getGUID(),$guids[3]); - $col = 3; - } - $pos = ($pos + 1) * 10; - $dbwidget->column = $col; - $dbwidget->order = $pos; - } else { - $dbguid = $dbwidget->getGUID(); - if (!$dbwidget->delete()) { - $return = false; - } else { - // Remove state cookie - setcookie('widget' + $dbguid, null); - } - } - } - - } - // Add new ones - if (sizeof($guids[$column]) > 0) { - foreach($guids[$column] as $key => $guid) { - if ($guid == 0) { - $pos = ($key + 1) * 10; - $handler = $handlers[$column][$key]; - if (!add_widget($owner,$handler,$context,$pos,$column)) - $return = false; - } - } - } - } - - return $return; - - } - - /** - * Run some things once. - * - */ - function widget_run_once() - { - // Register a class - add_subtype("object", "widget", "ElggWidget"); - } - - /** - * Function to initialise widgets functionality on Elgg init - * - */ - function widgets_init() { - - register_action('widgets/reorder'); - register_action('widgets/save'); - register_action('widgets/add'); - - // Now run this stuff, but only once - run_function_once("widget_run_once"); - } - - // Register event - register_elgg_event_handler('init','system','widgets_init'); - - // Use widgets on the dashboard - use_widgets('dashboard'); - - ?> \ No newline at end of file diff --git a/engine/settings.example.php b/engine/settings.example.php index 50af236e4..4fbc716a3 100644 --- a/engine/settings.example.php +++ b/engine/settings.example.php @@ -1,98 +1,98 @@ -dbuser = '{{CONFIG_DBUSER}}'; - - // Database password - $CONFIG->dbpass = '{{CONFIG_DBPASS}}'; - - // Database name - $CONFIG->dbname = '{{CONFIG_DBNAME}}'; - - // Database server - // (For most configurations, you can leave this as 'localhost') - $CONFIG->dbhost = '{{CONFIG_DBHOST}}'; - - // Database table prefix - // If you're sharing a database with other applications, you will want to use this - // to differentiate Elgg's tables. - $CONFIG->dbprefix = '{{CONFIG_DBPREFIX}}'; - - /* - * Multiple database connections - * - * Here you can set up multiple connections for reads and writes. To do this, uncomment out - * the lines below. - */ - - /* - - // Yes! We want to split reads and writes - $CONFIG->db->split = true; - - // READS - // Database username - $CONFIG->db['read']->dbuser = ""; - - // Database password - $CONFIG->db['read']->dbpass = ""; - - // Database name - $CONFIG->db['read']->dbname = ""; - - // Database server - // (For most configurations, you can leave this as 'localhost') - $CONFIG->db['read']->dbhost = "localhost"; - - // WRITES - // Database username - $CONFIG->db['write']->dbuser = ""; - - // Database password - $CONFIG->db['write']->dbpass = ""; - - // Database name - $CONFIG->db['write']->dbname = ""; - - // Database server - // (For most configurations, you can leave this as 'localhost') - $CONFIG->db['write']->dbhost = "localhost"; - - - */ - - /* - * For extra connections for both reads and writes, you can turn both - * $CONFIG->db['read'] and $CONFIG->db['write'] into an array, eg: - * - * $CONFIG->db['read'][0]->dbhost = "localhost"; - * - * Note that the array keys must be numeric and consecutive, i.e., they start - * at 0, the next one must be at 1, etc. - */ +dbuser = '{{CONFIG_DBUSER}}'; + + // Database password + $CONFIG->dbpass = '{{CONFIG_DBPASS}}'; + + // Database name + $CONFIG->dbname = '{{CONFIG_DBNAME}}'; + + // Database server + // (For most configurations, you can leave this as 'localhost') + $CONFIG->dbhost = '{{CONFIG_DBHOST}}'; + + // Database table prefix + // If you're sharing a database with other applications, you will want to use this + // to differentiate Elgg's tables. + $CONFIG->dbprefix = '{{CONFIG_DBPREFIX}}'; + + /* + * Multiple database connections + * + * Here you can set up multiple connections for reads and writes. To do this, uncomment out + * the lines below. + */ + + /* + + // Yes! We want to split reads and writes + $CONFIG->db->split = true; + + // READS + // Database username + $CONFIG->db['read']->dbuser = ""; + + // Database password + $CONFIG->db['read']->dbpass = ""; + + // Database name + $CONFIG->db['read']->dbname = ""; + + // Database server + // (For most configurations, you can leave this as 'localhost') + $CONFIG->db['read']->dbhost = "localhost"; + + // WRITES + // Database username + $CONFIG->db['write']->dbuser = ""; + + // Database password + $CONFIG->db['write']->dbpass = ""; + + // Database name + $CONFIG->db['write']->dbname = ""; + + // Database server + // (For most configurations, you can leave this as 'localhost') + $CONFIG->db['write']->dbhost = "localhost"; + + + */ + + /* + * For extra connections for both reads and writes, you can turn both + * $CONFIG->db['read'] and $CONFIG->db['write'] into an array, eg: + * + * $CONFIG->db['read'][0]->dbhost = "localhost"; + * + * Note that the array keys must be numeric and consecutive, i.e., they start + * at 0, the next one must be at 1, etc. + */ /** @@ -110,7 +110,7 @@ //$CONFIG->memcache_servers = array ( // array('server1', 11211), // array('server2', 11211) - //); + //); /** * Some work-around flags. @@ -118,12 +118,12 @@ // Try uncommenting the below if your notification emails are not being sent // $CONFIG->broken_mta = true; - - /** - * Url - I am not sure if this will be here ? - **/ - - // URL - $CONFIG->url = ""; - + + /** + * Url - I am not sure if this will be here ? + **/ + + // URL + $CONFIG->url = ""; + ?> \ No newline at end of file diff --git a/engine/start.php b/engine/start.php index c387e2fce..23a04cb60 100644 --- a/engine/start.php +++ b/engine/start.php @@ -1,219 +1,219 @@ -debug) && $CONFIG->debug) error_log("Loading $file..."); - if (!include_once($file)) - throw new InstallationException("Could not load {$file}"); - } - - } else { // End portion for sanitised installs only - - throw new InstallationException(elgg_echo('installation:error:configuration')); - - } - - // Autodetect some default configuration settings - set_default_config(); - - // Trigger events - trigger_elgg_event('boot', 'system'); - - // Load plugins - - $installed = is_installed(); - $db_installed = is_db_installed(); - - // Determine light mode - $lm = strtolower(get_input('lightmode')); - if ($lm == 'true') $lightmode = true; - - // Load plugins, if we're not in light mode - if (($installed) && ($db_installed) && ($sanitised) && (!$lightmode)) { - load_plugins(); - - trigger_elgg_event('plugins_boot', 'system'); - } - - // Forward if we haven't been installed - if ((!$installed || !$db_installed) && !substr_count($_SERVER["PHP_SELF"],"install.php") && !substr_count($_SERVER["PHP_SELF"],"css.php") && !substr_count($_SERVER["PHP_SELF"],"action_handler.php")) { - header("Location: install.php"); - exit; - } - - // Trigger events - if (!substr_count($_SERVER["PHP_SELF"],"install.php") && - !substr_count($_SERVER["PHP_SELF"],"setup.php") && - !$lightmode - && !(defined('upgrading') && upgrading == 'upgrading')) { - // If default settings haven't been installed, forward to the default settings page - trigger_elgg_event('init', 'system'); - //if (!datalist_get('default_settings')) { - //forward("setup.php"); - //} - } - - // System booted, return to normal view - set_input('view', $oldview); - if (empty($oldview)) { - if (empty($CONFIG->view)) - $oldview = 'default'; - else - $oldview = $CONFIG->view; - } - - if (($installed) && ($db_installed)) - { - $lastupdate = datalist_get('simplecache_lastupdate'); - $lastcached = datalist_get('simplecache_'.$oldview); - if ($lastupdate == 0 || $lastcached < $lastupdate) { - elgg_view_regenerate_simplecache(); - $lastcached = time(); - datalist_set('simplecache_lastupdate',$lastcached); - datalist_set('simplecache_'.$oldview,$lastcached); - } - $CONFIG->lastcache = $lastcached; - } + * @author Curverider Ltd + + * @link http://elgg.org/ + */ + + /* + * Basic profiling + */ + global $START_MICROTIME; + $START_MICROTIME = microtime(true); + + /** + * Load important prerequisites + */ + + if (!include_once(dirname(__FILE__) . "/lib/exceptions.php")) { // Exceptions + echo "Error in installation: could not load the Exceptions library."; + exit; + } + + if (!include_once(dirname(__FILE__) . "/lib/elgglib.php")) { // Main Elgg library + echo "Elgg could not load its main library."; + exit; + } + + if (!include_once(dirname(__FILE__) . "/lib/access.php")) { // Access library + echo "Error in installation: could not load the Access library."; + exit; + } + + if (!include_once(dirname(__FILE__) . "/lib/system_log.php")) { // Logging library + echo "Error in installation: could not load the System Log library."; + exit; + } + + if (!include_once(dirname(__FILE__) . "/lib/export.php")) { // Export library + echo "Error in installation: could not load the Export library."; + exit; + } + + if (!include_once(dirname(__FILE__) . "/lib/sessions.php")) { + echo ("Error in installation: Elgg could not load the Sessions library"); + exit; + } + + if (!include_once(dirname(__FILE__) . "/lib/languages.php")) { // Languages library + echo "Error in installation: could not load the languages library."; + exit; + } + + if (!include_once(dirname(__FILE__) . "/lib/input.php")) { // Input library + echo "Error in installation: could not load the input library."; + exit; + } + + if (!include_once(dirname(__FILE__) . "/lib/install.php")) { // Installation library + echo "Error in installation: could not load the installation library."; + exit; + } + + if (!include_once(dirname(__FILE__) . "/lib/cache.php")) { // Installation library + echo "Error in installation: could not load the cache library."; + exit; + } + + + + // Use fallback view until sanitised + $oldview = get_input('view'); + set_input('view', 'failsafe'); + + /** + * Set light mode default + */ + $lightmode = false; + + /** + * Establish handlers + */ + + // Register the error handler + set_error_handler('__elgg_php_error_handler'); + set_exception_handler('__elgg_php_exception_handler'); + + /** + * If there are basic issues with the way the installation is formed, don't bother trying + * to load any more files + */ + + if ($sanitised = sanitised()) { // Begin portion for sanitised installs only + + /** + * Load the system settings + */ + + if (!include_once(dirname(__FILE__) . "/settings.php")) // Global settings + throw new InstallationException("Elgg could not load the settings file."); + + /** + * Load and initialise the database + */ + + if (!include_once(dirname(__FILE__) . "/lib/database.php")) // Database connection + throw new InstallationException("Elgg could not load the main Elgg database library."); + + /** + * Load the remaining libraries from /lib/ in alphabetical order, + * except for a few exceptions + */ + + if (!include_once(dirname(__FILE__) . "/lib/actions.php")) { + throw new InstallationException("Elgg could not load the Actions library"); + } + + + + // We don't want to load or reload these files + + $file_exceptions = array( + '.','..', + '.DS_Store', + 'Thumbs.db', + '.svn', + 'CVS','cvs', + 'settings.php','settings.example.php','languages.php','exceptions.php','elgglib.php','access.php','database.php','actions.php','sessions.php' + ); + + // Get the list of files to include, and alphabetically sort them + + $files = get_library_files(dirname(__FILE__) . "/lib",$file_exceptions); + asort($files); + + // Get config + global $CONFIG; + + // Include them + foreach($files as $file) { + if (isset($CONFIG->debug) && $CONFIG->debug) error_log("Loading $file..."); + if (!include_once($file)) + throw new InstallationException("Could not load {$file}"); + } + + } else { // End portion for sanitised installs only + + throw new InstallationException(elgg_echo('installation:error:configuration')); + + } + + // Autodetect some default configuration settings + set_default_config(); + + // Trigger events + trigger_elgg_event('boot', 'system'); + + // Load plugins + + $installed = is_installed(); + $db_installed = is_db_installed(); + + // Determine light mode + $lm = strtolower(get_input('lightmode')); + if ($lm == 'true') $lightmode = true; + + // Load plugins, if we're not in light mode + if (($installed) && ($db_installed) && ($sanitised) && (!$lightmode)) { + load_plugins(); + + trigger_elgg_event('plugins_boot', 'system'); + } + + // Forward if we haven't been installed + if ((!$installed || !$db_installed) && !substr_count($_SERVER["PHP_SELF"],"install.php") && !substr_count($_SERVER["PHP_SELF"],"css.php") && !substr_count($_SERVER["PHP_SELF"],"action_handler.php")) { + header("Location: install.php"); + exit; + } + + // Trigger events + if (!substr_count($_SERVER["PHP_SELF"],"install.php") && + !substr_count($_SERVER["PHP_SELF"],"setup.php") && + !$lightmode + && !(defined('upgrading') && upgrading == 'upgrading')) { + // If default settings haven't been installed, forward to the default settings page + trigger_elgg_event('init', 'system'); + //if (!datalist_get('default_settings')) { + //forward("setup.php"); + //} + } + + // System booted, return to normal view + set_input('view', $oldview); + if (empty($oldview)) { + if (empty($CONFIG->view)) + $oldview = 'default'; + else + $oldview = $CONFIG->view; + } + + if (($installed) && ($db_installed)) + { + $lastupdate = datalist_get('simplecache_lastupdate'); + $lastcached = datalist_get('simplecache_'.$oldview); + if ($lastupdate == 0 || $lastcached < $lastupdate) { + elgg_view_regenerate_simplecache(); + $lastcached = time(); + datalist_set('simplecache_lastupdate',$lastcached); + datalist_set('simplecache_'.$oldview,$lastcached); + } + $CONFIG->lastcache = $lastcached; + } ?> \ No newline at end of file diff --git a/entities/index.php b/entities/index.php index 5b6b104b6..85395b78d 100644 --- a/entities/index.php +++ b/entities/index.php @@ -1,68 +1,68 @@ -container_guid) { + set_page_owner($entity->container_guid); + } else { + set_page_owner($entity->owner_guid); + } + + // Set the body to be the full view of the entity, and the title to be its title + if ($entity instanceof ElggObject) { + $title = $entity->title; + } else if ($entity instanceof ElggEntity) { + $title = $entity->name; + } + $area2 = elgg_view_entity($entity,true); + if ($shell) { + $body = elgg_view_layout('two_column_left_sidebar', '', $area1 . $area2); + } else { + $body = $area2; + } + + // Otherwise? + } else { + + $body = elgg_echo('notfound'); + + } + + // Display the page + if ($shell) { + page_draw($title, $body); + } else { + header("Content-type: text/html; charset=UTF-8"); + echo $title; + echo $body; + } - * @link http://elgg.org/ - */ - - // Load Elgg engine - require_once(dirname(dirname(__FILE__)) . "/engine/start.php"); - - // Get the GUID of the entity we want to view - $guid = (int) get_input('guid'); - $shell = get_input('shell'); - if ($shell == "no") { - $shell = false; - } else { - $shell = true; - } - - $context = get_input('context'); - if ($context) set_context($context); - - // Get the entity, if possible - if ($entity = get_entity($guid)) { - - if ($entity->container_guid) { - set_page_owner($entity->container_guid); - } else { - set_page_owner($entity->owner_guid); - } - - // Set the body to be the full view of the entity, and the title to be its title - if ($entity instanceof ElggObject) { - $title = $entity->title; - } else if ($entity instanceof ElggEntity) { - $title = $entity->name; - } - $area2 = elgg_view_entity($entity,true); - if ($shell) { - $body = elgg_view_layout('two_column_left_sidebar', '', $area1 . $area2); - } else { - $body = $area2; - } - - // Otherwise? - } else { - - $body = elgg_echo('notfound'); - - } - - // Display the page - if ($shell) { - page_draw($title, $body); - } else { - header("Content-type: text/html; charset=UTF-8"); - echo $title; - echo $body; - } - ?> \ No newline at end of file diff --git a/entities/list.php b/entities/list.php index e6505a6e9..3b02efc15 100644 --- a/entities/list.php +++ b/entities/list.php @@ -1,21 +1,21 @@ - \ No newline at end of file diff --git a/friends/add.php b/friends/add.php index edca9d96e..60cbd28db 100644 --- a/friends/add.php +++ b/friends/add.php @@ -1,28 +1,28 @@ - get_user_friends($_SESSION['user']->getGUID(),"",9999))); + + // Format page + $body = elgg_view_layout('two_column_left_sidebar','', elgg_view_title(elgg_echo('friends:collections:add')) . $area2); + + // Draw it + page_draw(elgg_echo('friends:collections:add'),$body); - * @link http://elgg.org/ - */ - - // Start engine - require_once(dirname(dirname((__FILE__))) . "/engine/start.php"); - - // You need to be logged in for this one - gatekeeper(); - - $area2 = elgg_view('friends/forms/edit', array('friends' => get_user_friends($_SESSION['user']->getGUID(),"",9999))); - - // Format page - $body = elgg_view_layout('two_column_left_sidebar','', elgg_view_title(elgg_echo('friends:collections:add')) . $area2); - - // Draw it - page_draw(elgg_echo('friends:collections:add'),$body); - ?> \ No newline at end of file diff --git a/friends/collections.php b/friends/collections.php index f507654e4..6c023f005 100644 --- a/friends/collections.php +++ b/friends/collections.php @@ -1,28 +1,28 @@ -getGUID()); + + // Format page + $body = elgg_view_layout('two_column_left_sidebar', '', elgg_view_title(elgg_echo('friends:collections')) . $area2); + + // Draw it + page_draw(elgg_echo('friends:collections'),$body); - * @link http://elgg.org/ - */ - - // Start engine - require_once(dirname(dirname((__FILE__))) . "/engine/start.php"); - - // You need to be logged in for this one - gatekeeper(); - - $area2 = elgg_view_access_collections($_SESSION['user']->getGUID()); - - // Format page - $body = elgg_view_layout('two_column_left_sidebar', '', elgg_view_title(elgg_echo('friends:collections')) . $area2); - - // Draw it - page_draw(elgg_echo('friends:collections'),$body); - ?> \ No newline at end of file diff --git a/friends/edit.php b/friends/edit.php index 5ece2596a..cd9f37b95 100644 --- a/friends/edit.php +++ b/friends/edit.php @@ -1,39 +1,39 @@ - $collection, 'collection_members' => $collection_members)); + + // Format page + $body = elgg_view_layout('two_column_left_sidebar',$area1. $area2); + + // Draw it + page_draw(elgg_echo('friends:add'),$body); - * @link http://elgg.org/ - */ - - // Start engine - require_once(dirname(dirname((__FILE__))) . "/engine/start.php"); - - // You need to be logged in for this one - gatekeeper(); - - //set the title - $area1 = elgg_view_title(elgg_echo('friends:collectionedit'), false); - - //grab the collection id passed to the edit form - $collection_id = get_input('collection'); - - //get the full collection - $collection = get_access_collection($collection_id); - //get all members of the collection - $collection_members = get_members_of_access_collection($collection_id); - - $area2 = elgg_view('friends/forms/edit', array('collection' => $collection, 'collection_members' => $collection_members)); - - // Format page - $body = elgg_view_layout('two_column_left_sidebar',$area1. $area2); - - // Draw it - page_draw(elgg_echo('friends:add'),$body); - ?> \ No newline at end of file diff --git a/friends/index.php b/friends/index.php index 1c85cdc6f..e9e4f7374 100644 --- a/friends/index.php +++ b/friends/index.php @@ -1,26 +1,26 @@ -getGUID()); + $owner = $_SESSION['user']; + } + + $area1 = elgg_view_title(elgg_echo('friends')); + $area2 = list_entities_from_relationship('friend',$owner->getGUID(),false,'user','',0,10,false); + $body = elgg_view_layout('two_column_left_sidebar', '', $area1 . $area2); + + page_draw(sprintf(elgg_echo("friends:owned"),$owner->name),$body); - * @link http://elgg.org/ - */ - - if (!$owner = page_owner_entity()) { - gatekeeper(); - set_page_owner($_SESSION['user']->getGUID()); - $owner = $_SESSION['user']; - } - - $area1 = elgg_view_title(elgg_echo('friends')); - $area2 = list_entities_from_relationship('friend',$owner->getGUID(),false,'user','',0,10,false); - $body = elgg_view_layout('two_column_left_sidebar', '', $area1 . $area2); - - page_draw(sprintf(elgg_echo("friends:owned"),$owner->name),$body); - ?> \ No newline at end of file diff --git a/friends/of.php b/friends/of.php index 4ae20dc7d..f1231750c 100644 --- a/friends/of.php +++ b/friends/of.php @@ -1,26 +1,26 @@ -getGUID()); + $owner = $_SESSION['user']; + } + + $area1 = elgg_view_title(elgg_echo('friends:of')); + $area2 = list_entities_from_relationship('friend',$owner->getGUID(),true,'user','',0,10,false); + $body = elgg_view_layout('two_column_left_sidebar', '', $area1 . $area2); + + page_draw(sprintf(elgg_echo("friends:of:owned"),$owner->name),$body); - * @link http://elgg.org/ - */ - - if (!$owner = page_owner_entity()) { - gatekeeper(); - set_page_owner($_SESSION['user']->getGUID()); - $owner = $_SESSION['user']; - } - - $area1 = elgg_view_title(elgg_echo('friends:of')); - $area2 = list_entities_from_relationship('friend',$owner->getGUID(),true,'user','',0,10,false); - $body = elgg_view_layout('two_column_left_sidebar', '', $area1 . $area2); - - page_draw(sprintf(elgg_echo("friends:of:owned"),$owner->name),$body); - ?> \ No newline at end of file diff --git a/friends/pickercallback.php b/friends/pickercallback.php index 2cbe82506..57406b94d 100644 --- a/friends/pickercallback.php +++ b/friends/pickercallback.php @@ -1,61 +1,61 @@ - $friendspicker, 'count' => sizeof($members))); - $content = elgg_view('friends/tablelist',array('entities' => $members, 'content' => $js_segment)); - break; - default: $friends = $pageowner->getFriends('',9999); - $content = elgg_view('friends/picker',array( - 'entities' => $friends, - 'value' => $members, - 'callback' => true, - 'friendspicker' => $friendspicker, - 'formcontents' => elgg_view('friends/forms/collectionfields',array('collection' => get_access_collection($collection))), - 'formtarget' => $CONFIG->wwwroot . 'action/friends/editcollection', - )); - break; - - } - - // Output the content - echo $content; - + * @author Curverider Ltd + + * @link http://elgg.org/ + */ + + // Load Elgg engine + require_once(dirname(dirname(__FILE__)) . "/engine/start.php"); + global $CONFIG; + + // Get callback type (list or picker) + $type = get_input('type','picker'); + + // Get list of members if applicable + /*$members = get_input('members',''); + if (!empty($members)) { + $members = explode(',',$members); + } else { + $members = array(); + }*/ + $collection = (int) get_input('collection',0); + $members = get_members_of_access_collection($collection, true); + if (!$members) $members = array(); + + $friendspicker = (int) get_input('friendspicker',0); + + // Get page owner (bomb out if there isn't one) + $pageowner = page_owner_entity(); + if (!$pageowner) { forward(); exit; } + + // Depending on the view type, launch a different view + switch($type) { + + case 'list': + $js_segment = elgg_view('friends/tablelistcountupdate',array('friendspicker' => $friendspicker, 'count' => sizeof($members))); + $content = elgg_view('friends/tablelist',array('entities' => $members, 'content' => $js_segment)); + break; + default: $friends = $pageowner->getFriends('',9999); + $content = elgg_view('friends/picker',array( + 'entities' => $friends, + 'value' => $members, + 'callback' => true, + 'friendspicker' => $friendspicker, + 'formcontents' => elgg_view('friends/forms/collectionfields',array('collection' => get_access_collection($collection))), + 'formtarget' => $CONFIG->wwwroot . 'action/friends/editcollection', + )); + break; + + } + + // Output the content + echo $content; + ?> \ No newline at end of file diff --git a/index.php b/index.php index 8da033bd9..effdac99d 100644 --- a/index.php +++ b/index.php @@ -1,44 +1,44 @@ - \ No newline at end of file diff --git a/install.php b/install.php index 50447941a..48290fdf0 100644 --- a/install.php +++ b/install.php @@ -1,42 +1,42 @@ - \ No newline at end of file diff --git a/languages/en.php b/languages/en.php index 5bd856fb8..8878fa0d9 100644 --- a/languages/en.php +++ b/languages/en.php @@ -1,1079 +1,1079 @@ - 'Sites', - - /** - * Sessions - */ - - 'login' => "Log in", - 'loginok' => "You have been logged in.", - 'loginerror' => "We couldn't log you in. This may be because you haven't validated your account yet, the details you supplied were incorrect, or you have made too many incorrect login attempts. Make sure your details are correct and please try again.", - - 'logout' => "Log out", - 'logoutok' => "You have been logged out.", - 'logouterror' => "We couldn't log you out. Please try again.", - - /** - * Errors - */ - 'exception:title' => "Welcome to Elgg.", - - 'InstallationException:CantCreateSite' => "Unable to create a default ElggSite with credentials Name:%s, Url: %s", - - 'actionundefined' => "The requested action (%s) was not defined in the system.", - 'actionloggedout' => "Sorry, you cannot perform this action while logged out.", - - 'notfound' => "The requested resource could not be found, or you do not have access to it.", - - 'SecurityException:Codeblock' => "Denied access to execute privileged code block", - 'DatabaseException:WrongCredentials' => "Elgg couldn't connect to the database using the given credentials.", - 'DatabaseException:NoConnect' => "Elgg couldn't select the database '%s', please check that the database is created and you have access to it.", - 'SecurityException:FunctionDenied' => "Access to privileged function '%s' is denied.", - 'DatabaseException:DBSetupIssues' => "There were a number of issues: ", - 'DatabaseException:ScriptNotFound' => "Elgg couldn't find the requested database script at %s.", - - 'IOException:FailedToLoadGUID' => "Failed to load new %s from GUID:%d", - 'InvalidParameterException:NonElggObject' => "Passing a non-ElggObject to an ElggObject constructor!", - 'InvalidParameterException:UnrecognisedValue' => "Unrecognised value passed to constuctor.", - - 'InvalidClassException:NotValidElggStar' => "GUID:%d is not a valid %s", - - 'PluginException:MisconfiguredPlugin' => "%s is a misconfigured plugin.", - - 'InvalidParameterException:NonElggUser' => "Passing a non-ElggUser to an ElggUser constructor!", - - 'InvalidParameterException:NonElggSite' => "Passing a non-ElggSite to an ElggSite constructor!", - - 'InvalidParameterException:NonElggGroup' => "Passing a non-ElggGroup to an ElggGroup constructor!", - - 'IOException:UnableToSaveNew' => "Unable to save new %s", - - 'InvalidParameterException:GUIDNotForExport' => "GUID has not been specified during export, this should never happen.", - 'InvalidParameterException:NonArrayReturnValue' => "Entity serialisation function passed a non-array returnvalue parameter", - - 'ConfigurationException:NoCachePath' => "Cache path set to nothing!", - 'IOException:NotDirectory' => "%s is not a directory.", - - 'IOException:BaseEntitySaveFailed' => "Unable to save new object's base entity information!", - 'InvalidParameterException:UnexpectedODDClass' => "import() passed an unexpected ODD class", - 'InvalidParameterException:EntityTypeNotSet' => "Entity type must be set.", - - 'ClassException:ClassnameNotClass' => "%s is not a %s.", - 'ClassNotFoundException:MissingClass' => "Class '%s' was not found, missing plugin?", - 'InstallationException:TypeNotSupported' => "Type %s is not supported. This indicates an error in your installation, most likely caused by an incomplete upgrade.", - - 'ImportException:ImportFailed' => "Could not import element %d", - 'ImportException:ProblemSaving' => "There was a problem saving %s", - 'ImportException:NoGUID' => "New entity created but has no GUID, this should not happen.", - - 'ImportException:GUIDNotFound' => "Entity '%d' could not be found.", - 'ImportException:ProblemUpdatingMeta' => "There was a problem updating '%s' on entity '%d'", - - 'ExportException:NoSuchEntity' => "No such entity GUID:%d", - - 'ImportException:NoODDElements' => "No OpenDD elements found in import data, import failed.", - 'ImportException:NotAllImported' => "Not all elements were imported.", - - 'InvalidParameterException:UnrecognisedFileMode' => "Unrecognised file mode '%s'", - 'InvalidParameterException:MissingOwner' => "File %s (%d) is missing an owner!", - 'IOException:CouldNotMake' => "Could not make %s", - 'IOException:MissingFileName' => "You must specify a name before opening a file.", - 'ClassNotFoundException:NotFoundNotSavedWithFile' => "Filestore not found or class not saved with file!", - 'NotificationException:NoNotificationMethod' => "No notification method specified.", - 'NotificationException:NoHandlerFound' => "No handler found for '%s' or it was not callable.", - 'NotificationException:ErrorNotifyingGuid' => "There was an error while notifying %d", - 'NotificationException:NoEmailAddress' => "Could not get the email address for GUID:%d", - 'NotificationException:MissingParameter' => "Missing a required parameter, '%s'", - - 'DatabaseException:WhereSetNonQuery' => "Where set contains non WhereQueryComponent", - 'DatabaseException:SelectFieldsMissing' => "Fields missing on a select style query", - 'DatabaseException:UnspecifiedQueryType' => "Unrecognised or unspecified query type.", - 'DatabaseException:NoTablesSpecified' => "No tables specified for query.", - 'DatabaseException:NoACL' => "No access control was provided on query", - - 'InvalidParameterException:NoEntityFound' => "No entity found, it either doesn't exist or you don't have access to it.", - - 'InvalidParameterException:GUIDNotFound' => "GUID:%s could not be found, or you can not access it.", - 'InvalidParameterException:IdNotExistForGUID' => "Sorry, '%s' does not exist for guid:%d", - 'InvalidParameterException:CanNotExportType' => "Sorry, I don't know how to export '%s'", - 'InvalidParameterException:NoDataFound' => "Could not find any data.", - 'InvalidParameterException:DoesNotBelong' => "Does not belong to entity.", - 'InvalidParameterException:DoesNotBelongOrRefer' => "Does not belong to entity or refer to entity.", - 'InvalidParameterException:MissingParameter' => "Missing parameter, you need to provide a GUID.", - - 'SecurityException:APIAccessDenied' => "Sorry, API access has been disabled by the administrator.", - 'SecurityException:NoAuthMethods' => "No authentication methods were found that could authenticate this API request.", - 'APIException:ApiResultUnknown' => "API Result is of an unknown type, this should never happen.", - - 'ConfigurationException:NoSiteID' => "No site ID has been specified.", - 'InvalidParameterException:UnrecognisedMethod' => "Unrecognised call method '%s'", - 'APIException:MissingParameterInMethod' => "Missing parameter %s in method %s", - 'APIException:ParameterNotArray' => "%s does not appear to be an array.", - 'APIException:UnrecognisedTypeCast' => "Unrecognised type in cast %s for variable '%s' in method '%s'", - 'APIException:InvalidParameter' => "Invalid parameter found for '%s' in method '%s'.", - 'APIException:FunctionParseError' => "%s(%s) has a parsing error.", - 'APIException:FunctionNoReturn' => "%s(%s) returned no value.", - 'SecurityException:AuthTokenExpired' => "Authentication token either missing, invalid or expired.", - 'CallException:InvalidCallMethod' => "%s must be called using '%s'", - 'APIException:MethodCallNotImplemented' => "Method call '%s' has not been implemented.", - 'APIException:AlgorithmNotSupported' => "Algorithm '%s' is not supported or has been disabled.", - 'ConfigurationException:CacheDirNotSet' => "Cache directory 'cache_path' not set.", - 'APIException:NotGetOrPost' => "Request method must be GET or POST", - 'APIException:MissingAPIKey' => "Missing X-Elgg-apikey HTTP header", - 'APIException:MissingHmac' => "Missing X-Elgg-hmac header", - 'APIException:MissingHmacAlgo' => "Missing X-Elgg-hmac-algo header", - 'APIException:MissingTime' => "Missing X-Elgg-time header", - 'APIException:TemporalDrift' => "X-Elgg-time is too far in the past or future. Epoch fail.", - 'APIException:NoQueryString' => "No data on the query string", - 'APIException:MissingPOSTHash' => "Missing X-Elgg-posthash header", - 'APIException:MissingPOSTAlgo' => "Missing X-Elgg-posthash_algo header", - 'APIException:MissingContentType' => "Missing content type for post data", - 'SecurityException:InvalidPostHash' => "POST data hash is invalid - Expected %s but got %s.", - 'SecurityException:DupePacket' => "Packet signature already seen.", - 'SecurityException:InvalidAPIKey' => "Invalid or missing API Key.", - 'NotImplementedException:CallMethodNotImplemented' => "Call method '%s' is currently not supported.", - - 'NotImplementedException:XMLRPCMethodNotImplemented' => "XML-RPC method call '%s' not implemented.", - 'InvalidParameterException:UnexpectedReturnFormat' => "Call to method '%s' returned an unexpected result.", - 'CallException:NotRPCCall' => "Call does not appear to be a valid XML-RPC call", - - 'PluginException:NoPluginName' => "The plugin name could not be found", - - 'ConfigurationException:BadDatabaseVersion' => "The database backend you have installed doesn't meet the basic requirements to run Elgg. Please consult your documentation.", - 'ConfigurationException:BadPHPVersion' => "You need at least PHP version 5.2 to run Elgg.", - 'configurationwarning:phpversion' => "Elgg requires at least PHP version 5.2, you can install it on 5.1.6 but some features may not work. Use at your own risk.", - - - 'InstallationException:DatarootNotWritable' => "Your data directory %s is not writable.", - 'InstallationException:DatarootUnderPath' => "Your data directory %s must be outside of your install path.", - 'InstallationException:DatarootBlank' => "You have not specified a data directory.", - - 'SecurityException:authenticationfailed' => "User could not be authenticated", - - 'CronException:unknownperiod' => '%s is not a recognised period.', - - 'SecurityException:deletedisablecurrentsite' => 'You can not delete or disable the site you are currently viewing!', - - 'memcache:notinstalled' => 'PHP memcache module not installed, you must install php5-memcache', - 'memcache:noservers' => 'No memcache servers defined, please populate the $CONFIG->memcache_servers variable', - 'memcache:versiontoolow' => 'Memcache needs at least version %s to run, you are running %s', - 'memcache:noaddserver' => 'Multiple server support disabled, you may need to upgrade your PECL memcache library', - - 'deprecatedfunction' => 'Warning: This code uses the deprecated function \'%s\' and is not compatible with this version of Elgg', - - 'pageownerunavailable' => 'Warning: The page owner %d is not accessible!', - /** - * API - */ - 'system.api.list' => "List all available API calls on the system.", - 'auth.gettoken' => "This API call lets a user log in, returning an authentication token which can be used in leu of a username and password for authenticating further calls.", - - /** - * User details - */ - - 'name' => "Display name", - 'email' => "Email address", - 'username' => "Username", - 'password' => "Password", - 'passwordagain' => "Password (again for verification)", - 'admin_option' => "Make this user an admin?", - - /** - * Access - */ - - 'PRIVATE' => "Private", - 'LOGGED_IN' => "Logged in users", - 'PUBLIC' => "Public", - 'access:friends:label' => "Friends", - 'access' => "Access", - - /** - * Dashboard and widgets - */ - - 'dashboard' => "Dashboard", - 'dashboard:configure' => "Edit page", - 'dashboard:nowidgets' => "Your dashboard is your gateway into the site. Click 'Edit page' to add widgets to keep track of content and your life within the system.", - - 'widgets:add' => 'Add widgets to your page', - 'widgets:add:description' => "Choose the features you want to add to your page by dragging them from the Widget gallery on the right, to any of the three widget areas below, and position them where you would like them to appear. - -To remove a widget drag it back to the Widget gallery.", - 'widgets:position:fixed' => '(Fixed position on page)', - - 'widgets' => "Widgets", - 'widget' => "Widget", - 'item:object:widget' => "Widgets", - 'layout:customise' => "Customise layout", - 'widgets:gallery' => "Widget gallery", - 'widgets:leftcolumn' => "Left widgets", - 'widgets:fixed' => "Fixed position", - 'widgets:middlecolumn' => "Middle widgets", - 'widgets:rightcolumn' => "Right widgets", - 'widgets:profilebox' => "Profile box", - 'widgets:panel:save:success' => "Your widgets were successfully saved.", - 'widgets:panel:save:failure' => "There was a problem saving your widgets. Please try again.", - 'widgets:save:success' => "The widget was successfully saved.", - 'widgets:save:failure' => "We could not save your widget. Please try again.", - 'widgets:handlernotfound' => 'This widget is either broken or has been disabled by the site administrator.', - - /** - * Groups - */ - - 'group' => "Group", - 'item:group' => "Groups", - - /** - * Profile - */ - - 'profile' => "Profile", + 'Sites', + + /** + * Sessions + */ + + 'login' => "Log in", + 'loginok' => "You have been logged in.", + 'loginerror' => "We couldn't log you in. This may be because you haven't validated your account yet, the details you supplied were incorrect, or you have made too many incorrect login attempts. Make sure your details are correct and please try again.", + + 'logout' => "Log out", + 'logoutok' => "You have been logged out.", + 'logouterror' => "We couldn't log you out. Please try again.", + + /** + * Errors + */ + 'exception:title' => "Welcome to Elgg.", + + 'InstallationException:CantCreateSite' => "Unable to create a default ElggSite with credentials Name:%s, Url: %s", + + 'actionundefined' => "The requested action (%s) was not defined in the system.", + 'actionloggedout' => "Sorry, you cannot perform this action while logged out.", + + 'notfound' => "The requested resource could not be found, or you do not have access to it.", + + 'SecurityException:Codeblock' => "Denied access to execute privileged code block", + 'DatabaseException:WrongCredentials' => "Elgg couldn't connect to the database using the given credentials.", + 'DatabaseException:NoConnect' => "Elgg couldn't select the database '%s', please check that the database is created and you have access to it.", + 'SecurityException:FunctionDenied' => "Access to privileged function '%s' is denied.", + 'DatabaseException:DBSetupIssues' => "There were a number of issues: ", + 'DatabaseException:ScriptNotFound' => "Elgg couldn't find the requested database script at %s.", + + 'IOException:FailedToLoadGUID' => "Failed to load new %s from GUID:%d", + 'InvalidParameterException:NonElggObject' => "Passing a non-ElggObject to an ElggObject constructor!", + 'InvalidParameterException:UnrecognisedValue' => "Unrecognised value passed to constuctor.", + + 'InvalidClassException:NotValidElggStar' => "GUID:%d is not a valid %s", + + 'PluginException:MisconfiguredPlugin' => "%s is a misconfigured plugin.", + + 'InvalidParameterException:NonElggUser' => "Passing a non-ElggUser to an ElggUser constructor!", + + 'InvalidParameterException:NonElggSite' => "Passing a non-ElggSite to an ElggSite constructor!", + + 'InvalidParameterException:NonElggGroup' => "Passing a non-ElggGroup to an ElggGroup constructor!", + + 'IOException:UnableToSaveNew' => "Unable to save new %s", + + 'InvalidParameterException:GUIDNotForExport' => "GUID has not been specified during export, this should never happen.", + 'InvalidParameterException:NonArrayReturnValue' => "Entity serialisation function passed a non-array returnvalue parameter", + + 'ConfigurationException:NoCachePath' => "Cache path set to nothing!", + 'IOException:NotDirectory' => "%s is not a directory.", + + 'IOException:BaseEntitySaveFailed' => "Unable to save new object's base entity information!", + 'InvalidParameterException:UnexpectedODDClass' => "import() passed an unexpected ODD class", + 'InvalidParameterException:EntityTypeNotSet' => "Entity type must be set.", + + 'ClassException:ClassnameNotClass' => "%s is not a %s.", + 'ClassNotFoundException:MissingClass' => "Class '%s' was not found, missing plugin?", + 'InstallationException:TypeNotSupported' => "Type %s is not supported. This indicates an error in your installation, most likely caused by an incomplete upgrade.", + + 'ImportException:ImportFailed' => "Could not import element %d", + 'ImportException:ProblemSaving' => "There was a problem saving %s", + 'ImportException:NoGUID' => "New entity created but has no GUID, this should not happen.", + + 'ImportException:GUIDNotFound' => "Entity '%d' could not be found.", + 'ImportException:ProblemUpdatingMeta' => "There was a problem updating '%s' on entity '%d'", + + 'ExportException:NoSuchEntity' => "No such entity GUID:%d", + + 'ImportException:NoODDElements' => "No OpenDD elements found in import data, import failed.", + 'ImportException:NotAllImported' => "Not all elements were imported.", + + 'InvalidParameterException:UnrecognisedFileMode' => "Unrecognised file mode '%s'", + 'InvalidParameterException:MissingOwner' => "File %s (%d) is missing an owner!", + 'IOException:CouldNotMake' => "Could not make %s", + 'IOException:MissingFileName' => "You must specify a name before opening a file.", + 'ClassNotFoundException:NotFoundNotSavedWithFile' => "Filestore not found or class not saved with file!", + 'NotificationException:NoNotificationMethod' => "No notification method specified.", + 'NotificationException:NoHandlerFound' => "No handler found for '%s' or it was not callable.", + 'NotificationException:ErrorNotifyingGuid' => "There was an error while notifying %d", + 'NotificationException:NoEmailAddress' => "Could not get the email address for GUID:%d", + 'NotificationException:MissingParameter' => "Missing a required parameter, '%s'", + + 'DatabaseException:WhereSetNonQuery' => "Where set contains non WhereQueryComponent", + 'DatabaseException:SelectFieldsMissing' => "Fields missing on a select style query", + 'DatabaseException:UnspecifiedQueryType' => "Unrecognised or unspecified query type.", + 'DatabaseException:NoTablesSpecified' => "No tables specified for query.", + 'DatabaseException:NoACL' => "No access control was provided on query", + + 'InvalidParameterException:NoEntityFound' => "No entity found, it either doesn't exist or you don't have access to it.", + + 'InvalidParameterException:GUIDNotFound' => "GUID:%s could not be found, or you can not access it.", + 'InvalidParameterException:IdNotExistForGUID' => "Sorry, '%s' does not exist for guid:%d", + 'InvalidParameterException:CanNotExportType' => "Sorry, I don't know how to export '%s'", + 'InvalidParameterException:NoDataFound' => "Could not find any data.", + 'InvalidParameterException:DoesNotBelong' => "Does not belong to entity.", + 'InvalidParameterException:DoesNotBelongOrRefer' => "Does not belong to entity or refer to entity.", + 'InvalidParameterException:MissingParameter' => "Missing parameter, you need to provide a GUID.", + + 'SecurityException:APIAccessDenied' => "Sorry, API access has been disabled by the administrator.", + 'SecurityException:NoAuthMethods' => "No authentication methods were found that could authenticate this API request.", + 'APIException:ApiResultUnknown' => "API Result is of an unknown type, this should never happen.", + + 'ConfigurationException:NoSiteID' => "No site ID has been specified.", + 'InvalidParameterException:UnrecognisedMethod' => "Unrecognised call method '%s'", + 'APIException:MissingParameterInMethod' => "Missing parameter %s in method %s", + 'APIException:ParameterNotArray' => "%s does not appear to be an array.", + 'APIException:UnrecognisedTypeCast' => "Unrecognised type in cast %s for variable '%s' in method '%s'", + 'APIException:InvalidParameter' => "Invalid parameter found for '%s' in method '%s'.", + 'APIException:FunctionParseError' => "%s(%s) has a parsing error.", + 'APIException:FunctionNoReturn' => "%s(%s) returned no value.", + 'SecurityException:AuthTokenExpired' => "Authentication token either missing, invalid or expired.", + 'CallException:InvalidCallMethod' => "%s must be called using '%s'", + 'APIException:MethodCallNotImplemented' => "Method call '%s' has not been implemented.", + 'APIException:AlgorithmNotSupported' => "Algorithm '%s' is not supported or has been disabled.", + 'ConfigurationException:CacheDirNotSet' => "Cache directory 'cache_path' not set.", + 'APIException:NotGetOrPost' => "Request method must be GET or POST", + 'APIException:MissingAPIKey' => "Missing X-Elgg-apikey HTTP header", + 'APIException:MissingHmac' => "Missing X-Elgg-hmac header", + 'APIException:MissingHmacAlgo' => "Missing X-Elgg-hmac-algo header", + 'APIException:MissingTime' => "Missing X-Elgg-time header", + 'APIException:TemporalDrift' => "X-Elgg-time is too far in the past or future. Epoch fail.", + 'APIException:NoQueryString' => "No data on the query string", + 'APIException:MissingPOSTHash' => "Missing X-Elgg-posthash header", + 'APIException:MissingPOSTAlgo' => "Missing X-Elgg-posthash_algo header", + 'APIException:MissingContentType' => "Missing content type for post data", + 'SecurityException:InvalidPostHash' => "POST data hash is invalid - Expected %s but got %s.", + 'SecurityException:DupePacket' => "Packet signature already seen.", + 'SecurityException:InvalidAPIKey' => "Invalid or missing API Key.", + 'NotImplementedException:CallMethodNotImplemented' => "Call method '%s' is currently not supported.", + + 'NotImplementedException:XMLRPCMethodNotImplemented' => "XML-RPC method call '%s' not implemented.", + 'InvalidParameterException:UnexpectedReturnFormat' => "Call to method '%s' returned an unexpected result.", + 'CallException:NotRPCCall' => "Call does not appear to be a valid XML-RPC call", + + 'PluginException:NoPluginName' => "The plugin name could not be found", + + 'ConfigurationException:BadDatabaseVersion' => "The database backend you have installed doesn't meet the basic requirements to run Elgg. Please consult your documentation.", + 'ConfigurationException:BadPHPVersion' => "You need at least PHP version 5.2 to run Elgg.", + 'configurationwarning:phpversion' => "Elgg requires at least PHP version 5.2, you can install it on 5.1.6 but some features may not work. Use at your own risk.", + + + 'InstallationException:DatarootNotWritable' => "Your data directory %s is not writable.", + 'InstallationException:DatarootUnderPath' => "Your data directory %s must be outside of your install path.", + 'InstallationException:DatarootBlank' => "You have not specified a data directory.", + + 'SecurityException:authenticationfailed' => "User could not be authenticated", + + 'CronException:unknownperiod' => '%s is not a recognised period.', + + 'SecurityException:deletedisablecurrentsite' => 'You can not delete or disable the site you are currently viewing!', + + 'memcache:notinstalled' => 'PHP memcache module not installed, you must install php5-memcache', + 'memcache:noservers' => 'No memcache servers defined, please populate the $CONFIG->memcache_servers variable', + 'memcache:versiontoolow' => 'Memcache needs at least version %s to run, you are running %s', + 'memcache:noaddserver' => 'Multiple server support disabled, you may need to upgrade your PECL memcache library', + + 'deprecatedfunction' => 'Warning: This code uses the deprecated function \'%s\' and is not compatible with this version of Elgg', + + 'pageownerunavailable' => 'Warning: The page owner %d is not accessible!', + /** + * API + */ + 'system.api.list' => "List all available API calls on the system.", + 'auth.gettoken' => "This API call lets a user log in, returning an authentication token which can be used in leu of a username and password for authenticating further calls.", + + /** + * User details + */ + + 'name' => "Display name", + 'email' => "Email address", + 'username' => "Username", + 'password' => "Password", + 'passwordagain' => "Password (again for verification)", + 'admin_option' => "Make this user an admin?", + + /** + * Access + */ + + 'PRIVATE' => "Private", + 'LOGGED_IN' => "Logged in users", + 'PUBLIC' => "Public", + 'access:friends:label' => "Friends", + 'access' => "Access", + + /** + * Dashboard and widgets + */ + + 'dashboard' => "Dashboard", + 'dashboard:configure' => "Edit page", + 'dashboard:nowidgets' => "Your dashboard is your gateway into the site. Click 'Edit page' to add widgets to keep track of content and your life within the system.", + + 'widgets:add' => 'Add widgets to your page', + 'widgets:add:description' => "Choose the features you want to add to your page by dragging them from the Widget gallery on the right, to any of the three widget areas below, and position them where you would like them to appear. + +To remove a widget drag it back to the Widget gallery.", + 'widgets:position:fixed' => '(Fixed position on page)', + + 'widgets' => "Widgets", + 'widget' => "Widget", + 'item:object:widget' => "Widgets", + 'layout:customise' => "Customise layout", + 'widgets:gallery' => "Widget gallery", + 'widgets:leftcolumn' => "Left widgets", + 'widgets:fixed' => "Fixed position", + 'widgets:middlecolumn' => "Middle widgets", + 'widgets:rightcolumn' => "Right widgets", + 'widgets:profilebox' => "Profile box", + 'widgets:panel:save:success' => "Your widgets were successfully saved.", + 'widgets:panel:save:failure' => "There was a problem saving your widgets. Please try again.", + 'widgets:save:success' => "The widget was successfully saved.", + 'widgets:save:failure' => "We could not save your widget. Please try again.", + 'widgets:handlernotfound' => 'This widget is either broken or has been disabled by the site administrator.', + + /** + * Groups + */ + + 'group' => "Group", + 'item:group' => "Groups", + + /** + * Profile + */ + + 'profile' => "Profile", 'profile:edit:default' => 'Replace profile fields', - 'profile:preview' => 'Preview', - 'user' => "User", - 'item:user' => "Users", - 'riveritem:single:user' => 'a user', + 'profile:preview' => 'Preview', + 'user' => "User", + 'item:user' => "Users", + 'riveritem:single:user' => 'a user', 'riveritem:plural:user' => 'some users', - - - - /** - * Profile menu items and titles - */ - - 'profile:yours' => "Your profile", - 'profile:user' => "%s's profile", - - 'profile:edit' => "Edit profile", - 'profile:profilepictureinstructions' => "The profile picture is the image that's displayed on your profile page.
You can change it as often as you'd like. (File formats accepted: GIF, JPG or PNG)", - 'profile:icon' => "Profile picture", - 'profile:createicon' => "Create your avatar", - 'profile:currentavatar' => "Current avatar", - 'profile:createicon:header' => "Profile picture", - 'profile:profilepicturecroppingtool' => "Profile picture cropping tool", - 'profile:createicon:instructions' => "Click and drag a square below to match how you want your picture cropped. A preview of your cropped picture will appear in the box on the right. When you are happy with the preview, click 'Create your avatar'. This cropped image will be used throughout the site as your avatar. ", - - 'profile:editdetails' => "Edit details", - 'profile:editicon' => "Edit profile icon", - - 'profile:aboutme' => "About me", - 'profile:description' => "About me", - 'profile:briefdescription' => "Brief description", - 'profile:location' => "Location", - 'profile:skills' => "Skills", - 'profile:interests' => "Interests", - 'profile:contactemail' => "Contact email", - 'profile:phone' => "Telephone", - 'profile:mobile' => "Mobile phone", - 'profile:website' => "Website", - - 'profile:banned' => 'This user account has been suspended.', - 'profile:deleteduser' => 'Deleted user', - - 'profile:river:update' => "%s updated their profile", - 'profile:river:iconupdate' => "%s updated their profile icon", - - 'profile:label' => "Profile label", - 'profile:type' => "Profile type", - - 'profile:editdefault:fail' => 'Default profile could not be saved', - 'profile:editdefault:success' => 'Item successfully added to default profile', - - - 'profile:editdefault:delete:fail' => 'Removed default profile item field failed', - 'profile:editdefault:delete:success' => 'Default profile item deleted!', - - 'profile:defaultprofile:reset' => 'Default system profile reset', - - 'profile:resetdefault' => 'Reset default profile', - 'profile:explainchangefields' => 'You can replace the existing profile fields with your own using the form below. First you give the new profile field a label, for example, \'Favourite team\'. Next you need to select the field type, for example, tags, url, text and so on. At any time you can revert back to the default profile set up.', - - - - /** - * Profile status messages - */ - - 'profile:saved' => "Your profile was successfully saved.", - 'profile:icon:uploaded' => "Your profile picture was successfully uploaded.", - - /** - * Profile error messages - */ - - 'profile:noaccess' => "You do not have permission to edit this profile.", - 'profile:notfound' => "Sorry; we could not find the specified profile.", - 'profile:cantedit' => "Sorry; you do not have permission to edit this profile.", - 'profile:icon:notfound' => "Sorry; there was a problem uploading your profile picture.", - - /** - * Friends - */ - - 'friends' => "Friends", - 'friends:yours' => "Your friends", - 'friends:owned' => "%s's friends", - 'friend:add' => "Add friend", - 'friend:remove' => "Remove friend", - - 'friends:add:successful' => "You have successfully added %s as a friend.", - 'friends:add:failure' => "We couldn't add %s as a friend. Please try again.", - - 'friends:remove:successful' => "You have successfully removed %s from your friends.", - 'friends:remove:failure' => "We couldn't remove %s from your friends. Please try again.", - - 'friends:none' => "This user hasn't added anyone as a friend yet.", - 'friends:none:you' => "You haven't added anyone as a friend! Search for your interests to begin finding people to follow.", - - 'friends:none:found' => "No friends were found.", - - 'friends:of:none' => "Nobody has added this user as a friend yet.", - 'friends:of:none:you' => "Nobody has added you as a friend yet. Start adding content and fill in your profile to let people find you!", - - 'friends:of:owned' => "People who have made %s a friend", - - 'friends:num_display' => "Number of friends to display", - 'friends:icon_size' => "Icon size", - 'friends:tiny' => "tiny", - 'friends:small' => "small", - 'friends:of' => "Friends of", - 'friends:collections' => "Collections of friends", - 'friends:collections:add' => "New friends collection", - 'friends:addfriends' => "Add friends", - 'friends:collectionname' => "Collection name", - 'friends:collectionfriends' => "Friends in collection", - 'friends:collectionedit' => "Edit this collection", - 'friends:nocollections' => "You do not yet have any collections.", - 'friends:collectiondeleted' => "Your collection has been deleted.", - 'friends:collectiondeletefailed' => "We were unable to delete the collection. Either you don't have permission, or some other problem has occurred.", - 'friends:collectionadded' => "Your collection was successfuly created", - 'friends:nocollectionname' => "You need to give your collection a name before it can be created.", - 'friends:collections:members' => "Collection members", - 'friends:collections:edit' => "Edit collection", - - 'friends:river:created' => "%s added the friends widget.", - 'friends:river:updated' => "%s updated their friends widget.", - 'friends:river:delete' => "%s removed their friends widget.", - 'friends:river:add' => "%s is now a friend with", - - 'friendspicker:chararray' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', - - /** - * Feeds - */ - 'feed:rss' => 'Subscribe to feed', - 'feed:odd' => 'Syndicate OpenDD', - - /** - * links - **/ - - 'link:view' => 'view link', - - - /** - * River - */ - 'river' => "River", - 'river:relationship:friend' => 'is now friends with', - 'river:noaccess' => 'You do not have permission to view this item.', - 'river:posted:generic' => '%s posted', - - /** - * Plugins - */ - 'plugins:settings:save:ok' => "Settings for the %s plugin were saved successfully.", - 'plugins:settings:save:fail' => "There was a problem saving settings for the %s plugin.", - 'plugins:usersettings:save:ok' => "User settings for the %s plugin were saved successfully.", - 'plugins:usersettings:save:fail' => "There was a problem saving user settings for the %s plugin.", - 'admin:plugins:label:version' => "Version", - 'item:object:plugin' => 'Plugin configuration settings', - - /** - * Notifications - */ - 'notifications:usersettings' => "Notification settings", - 'notifications:methods' => "Please specify which methods you want to permit.", - - 'notifications:usersettings:save:ok' => "Your notification settings were successfully saved.", - 'notifications:usersettings:save:fail' => "There was a problem saving your notification settings.", - - 'user.notification.get' => 'Return the notification settings for a given user.', - 'user.notification.set' => 'Set the notification settings for a given user.', - /** - * Search - */ - - 'search' => "Search", - 'searchtitle' => "Search: %s", - 'users:searchtitle' => "Searching for users: %s", - 'groups:searchtitle' => "Searching for groups: %s", - 'advancedsearchtitle' => "%s with results matching %s", - 'notfound' => "No results found.", - 'next' => "Next", - 'previous' => "Previous", - - 'viewtype:change' => "Change listing type", - 'viewtype:list' => "List view", - 'viewtype:gallery' => "Gallery", - - 'tag:search:startblurb' => "Items with tags matching '%s':", - - 'user:search:startblurb' => "Users matching '%s':", - 'user:search:finishblurb' => "To view more, click here.", - - 'group:search:startblurb' => "Groups matching '%s':", - 'group:search:finishblurb' => "To view more, click here.", - 'search:go' => 'Go', - - /** - * Account - */ - - 'account' => "Account", - 'settings' => "Settings", - 'tools' => "Tools", - 'tools:yours' => "Your tools", - - 'register' => "Register", - 'registerok' => "You have successfully registered for %s.", - 'registerbad' => "Your registration was unsuccessful. The username may already exist, your passwords might not match, or your username or password may be too short.", - 'registerdisabled' => "Registration has been disabled by the system administrator", - - 'firstadminlogininstructions' => 'Your new Elgg site has been successfully installed and your administrator account created. You can now configure your site further by enabling various installed plugin tools.', - - 'registration:notemail' => 'The email address you provided does not appear to be a valid email address.', - 'registration:userexists' => 'That username already exists', - 'registration:usernametooshort' => 'Your username must be a minimum of 4 characters long.', - 'registration:passwordtooshort' => 'The password must be a minimum of 6 characters long.', - 'registration:dupeemail' => 'This email address has already been registered.', - 'registration:invalidchars' => 'Sorry, your username contains invalid characters.', - 'registration:emailnotvalid' => 'Sorry, the email address you entered is invalid on this system', - 'registration:passwordnotvalid' => 'Sorry, the password you entered is invalid on this system', - 'registration:usernamenotvalid' => 'Sorry, the username you entered is invalid on this system', - - 'adduser' => "Add User", - 'adduser:ok' => "You have successfully added a new user.", - 'adduser:bad' => "The new user could not be created.", - - 'item:object:reported_content' => "Reported items", - - 'user:set:name' => "Account name settings", - 'user:name:label' => "Your name", - 'user:name:success' => "Successfully changed your name on the system.", - 'user:name:fail' => "Could not change your name on the system.", - - 'user:set:password' => "Account password", - 'user:password:label' => "Your new password", - 'user:password2:label' => "Your new password again", - 'user:password:success' => "Password changed", - 'user:password:fail' => "Could not change your password on the system.", - 'user:password:fail:notsame' => "The two passwords are not the same!", - 'user:password:fail:tooshort' => "Password is too short!", - - 'user:set:language' => "Language settings", - 'user:language:label' => "Your language", - 'user:language:success' => "Your language settings have been updated.", - 'user:language:fail' => "Your language settings could not be saved.", - - 'user:username:notfound' => 'Username %s not found.', - - 'user:password:lost' => 'Lost password', - 'user:password:resetreq:success' => 'Successfully requested a new password, email sent', - 'user:password:resetreq:fail' => 'Could not request a new password.', - - 'user:password:text' => 'To generate a new password, enter your username below. We will send the address of a unique verification page to you via email click on the link in the body of the message and a new password will be sent to you.', - - 'user:persistent' => 'Remember me', - /** - * Administration - */ - - 'admin:configuration:success' => "Your settings have been saved.", - 'admin:configuration:fail' => "Your settings could not be saved.", - - 'admin' => "Administration", - 'admin:description' => "The admin panel allows you to control all aspects of the system, from user management to how plugins behave. Choose an option below to get started.", - - 'admin:user' => "User Administration", - 'admin:user:description' => "This admin panel allows you to control user settings for your site. Choose an option below to get started.", - 'admin:user:adduser:label' => "Click here to add a new user...", - 'admin:user:opt:linktext' => "Configure users...", - 'admin:user:opt:description' => "Configure users and account information. ", - - 'admin:site' => "Site Administration", - 'admin:site:description' => "This admin panel allows you to control global settings for your site. Choose an option below to get started.", - 'admin:site:opt:linktext' => "Configure site...", - 'admin:site:opt:description' => "Configure the site technical and non-technical settings. ", - 'admin:site:access:warning' => "Changing the access setting only affects the permissions on content created in the future.", - - 'admin:plugins' => "Tool Administration", - 'admin:plugins:description' => "This admin panel allows you to control and configure tools installed on your site.", - 'admin:plugins:opt:linktext' => "Configure tools...", - 'admin:plugins:opt:description' => "Configure the tools installed on the site. ", - 'admin:plugins:label:author' => "Author", - 'admin:plugins:label:copyright' => "Copyright", - 'admin:plugins:label:licence' => "Licence", - 'admin:plugins:label:website' => "URL", - 'admin:plugins:label:moreinfo' => 'more info', - 'admin:plugins:label:version' => 'Version', - 'admin:plugins:warning:elggversionunknown' => 'Warning: This plugin does not specify a compatible Elgg version.', - 'admin:plugins:warning:elggtoolow' => 'Warning: This plugin requires a later version of Elgg!', - 'admin:plugins:reorder:yes' => "Plugin %s was reordered successfully.", - 'admin:plugins:reorder:no' => "Plugin %s could not be reordered.", - 'admin:plugins:disable:yes' => "Plugin %s was disabled successfully.", - 'admin:plugins:disable:no' => "Plugin %s could not be disabled.", - 'admin:plugins:enable:yes' => "Plugin %s was enabled successfully.", - 'admin:plugins:enable:no' => "Plugin %s could not be enabled.", - - 'admin:statistics' => "Statistics", - 'admin:statistics:description' => "This is an overview of statistics on your site. If you need more detailed statistics, a professional administration feature is available.", - 'admin:statistics:opt:description' => "View statistical information about users and objects on your site.", - 'admin:statistics:opt:linktext' => "View statistics...", - 'admin:statistics:label:basic' => "Basic site statistics", - 'admin:statistics:label:numentities' => "Entities on site", - 'admin:statistics:label:numusers' => "Number of users", - 'admin:statistics:label:numonline' => "Number of users online", - 'admin:statistics:label:onlineusers' => "Users online now", - 'admin:statistics:label:version' => "Elgg version", - 'admin:statistics:label:version:release' => "Release", - 'admin:statistics:label:version:version' => "Version", - - 'admin:user:label:search' => "Find users:", - 'admin:user:label:seachbutton' => "Search", - - 'admin:user:ban:no' => "Can not ban user", - 'admin:user:ban:yes' => "User banned.", - 'admin:user:unban:no' => "Can not unban user", - 'admin:user:unban:yes' => "User un-banned.", - 'admin:user:delete:no' => "Can not delete user", - 'admin:user:delete:yes' => "User deleted", - - 'admin:user:resetpassword:yes' => "Password reset, user notified.", - 'admin:user:resetpassword:no' => "Password could not be reset.", - - 'admin:user:makeadmin:yes' => "User is now an admin.", - 'admin:user:makeadmin:no' => "We could not make this user an admin.", - - 'admin:user:removeadmin:yes' => "User is no longer an admin.", - 'admin:user:removeadmin:no' => "We could not remove administrator privileges from this user.", - - /** - * User settings - */ - 'usersettings:description' => "The user settings panel allows you to control all your personal settings, from user management to how plugins behave. Choose an option below to get started.", - - 'usersettings:statistics' => "Your statistics", - 'usersettings:statistics:opt:description' => "View statistical information about users and objects on your site.", - 'usersettings:statistics:opt:linktext' => "Account statistics", - - 'usersettings:user' => "Your settings", - 'usersettings:user:opt:description' => "This allows you to control user settings.", - 'usersettings:user:opt:linktext' => "Change your settings", - - 'usersettings:plugins' => "Tools", - 'usersettings:plugins:opt:description' => "Configure settings (if any) for your active tools.", - 'usersettings:plugins:opt:linktext' => "Configure your tools", - - 'usersettings:plugins:description' => "This panel allows you to control and configure the personal settings for the tools installed by your system administrator.", - 'usersettings:statistics:label:numentities' => "Your entities", - - 'usersettings:statistics:yourdetails' => "Your details", - 'usersettings:statistics:label:name' => "Full name", - 'usersettings:statistics:label:email' => "Email", - 'usersettings:statistics:label:membersince' => "Member since", - 'usersettings:statistics:label:lastlogin' => "Last logged in", - - - - /** - * Generic action words - */ - - 'save' => "Save", - 'publish' => "Publish", - 'cancel' => "Cancel", - 'saving' => "Saving ...", - 'update' => "Update", - 'edit' => "Edit", - 'delete' => "Delete", - 'accept' => "Accept", - 'load' => "Load", - 'upload' => "Upload", - 'ban' => "Ban", - 'unban' => "Unban", - 'enable' => "Enable", - 'disable' => "Disable", - 'request' => "Request", - 'complete' => "Complete", - 'open' => 'Open', - 'close' => 'Close', - 'reply' => "Reply", - 'more' => 'More', - 'comments' => 'Comments', - 'import' => 'Import', - 'export' => 'Export', - - 'up' => 'Up', - 'down' => 'Down', - 'top' => 'Top', - 'bottom' => 'Bottom', - - 'invite' => "Invite", - - 'resetpassword' => "Reset password", - 'makeadmin' => "Make admin", - 'removeadmin' => "Remove admin", - - 'option:yes' => "Yes", - 'option:no' => "No", - - 'unknown' => 'Unknown', - - 'active' => 'Active', - 'total' => 'Total', - - 'learnmore' => "Click here to learn more.", - - 'content' => "content", - 'content:latest' => 'Latest activity', - 'content:latest:blurb' => 'Alternatively, click here to view the latest content from across the site.', - - 'link:text' => 'view link', - - 'enableall' => 'Enable All', - 'disableall' => 'Disable All', - - /** - * Generic questions - */ - - 'question:areyousure' => 'Are you sure?', - - /** - * Generic data words - */ - - 'title' => "Title", - 'description' => "Description", - 'tags' => "Tags", - 'spotlight' => "Spotlight", - 'all' => "All", - - 'by' => 'by', - - 'annotations' => "Annotations", - 'relationships' => "Relationships", - 'metadata' => "Metadata", - - /** - * Input / output strings - */ - - 'deleteconfirm' => "Are you sure you want to delete this item?", - 'fileexists' => "A file has already been uploaded. To replace it, select it below:", - - /** - * User add - */ - - 'useradd:subject' => 'User account created', - 'useradd:body' => ' -%s, - -A user account has been created for you at %s. To log in, visit: - - %s - -And log in with these user credentials: - - Username: %s - Password: %s - -Once you have logged in, we highly recommend that you change your password. -', - - /** - * System messages - **/ - - 'systemmessages:dismiss' => "click to dismiss", - - - /** - * Import / export - */ - 'importsuccess' => "Import of data was successful", - 'importfail' => "OpenDD import of data failed.", - - /** - * Time - */ - - 'friendlytime:justnow' => "just now", - 'friendlytime:minutes' => "%s minutes ago", - 'friendlytime:minutes:singular' => "a minute ago", - 'friendlytime:hours' => "%s hours ago", - 'friendlytime:hours:singular' => "an hour ago", - 'friendlytime:days' => "%s days ago", - 'friendlytime:days:singular' => "yesterday", - - 'date:month:01' => 'January %s', - 'date:month:02' => 'February %s', - 'date:month:03' => 'March %s', - 'date:month:04' => 'April %s', - 'date:month:05' => 'May %s', - 'date:month:06' => 'June %s', - 'date:month:07' => 'July %s', - 'date:month:08' => 'August %s', - 'date:month:09' => 'September %s', - 'date:month:10' => 'October %s', - 'date:month:11' => 'November %s', - 'date:month:12' => 'December %s', - - - /** - * Installation and system settings - */ - - 'installation:error:htaccess' => "Elgg requires a file called .htaccess to be set in the root directory of its installation. We tried to create it for you, but Elgg doesn't have permission to write to that directory. - -Creating this is easy. Copy the contents of the textbox below into a text editor and save it as .htaccess - -", - 'installation:error:settings' => "Elgg couldn't find its settings file. Most of Elgg's settings will be handled for you, but we need you to supply your database details. To do this: - -1. Rename engine/settings.example.php to settings.php in your Elgg installation. - -2. Open it with a text editor and enter your MySQL database details. If you don't know these, ask your system administrator or technical support for help. - -Alternatively, you can enter your database settings below and we will try and do this for you...", - - 'installation:error:configuration' => "Once you've corrected any configuration issues, press reload to try again.", - - 'installation' => "Installation", - 'installation:success' => "Elgg's database was installed successfully.", - 'installation:configuration:success' => "Your initial configuration settings have been saved. Now register your initial user; this will be your first system administrator.", - - 'installation:settings' => "System settings", - 'installation:settings:description' => "Now that the Elgg database has been successfully installed, you need to enter a couple of pieces of information to get your site fully up and running. We've tried to guess where we could, but you should check these details.", - - 'installation:settings:dbwizard:prompt' => "Enter your database settings below and hit save:", - 'installation:settings:dbwizard:label:user' => "Database user", - 'installation:settings:dbwizard:label:pass' => "Database password", - 'installation:settings:dbwizard:label:dbname' => "Elgg database", - 'installation:settings:dbwizard:label:host' => "Database hostname (usually 'localhost')", - 'installation:settings:dbwizard:label:prefix' => "Database table prefix (usually 'elgg')", - - 'installation:settings:dbwizard:savefail' => "We were unable to save the new settings.php. Please save the following file as engine/settings.php using a text editor.", - - 'installation:sitename' => "The name of your site (eg \"My social networking site\"):", - 'installation:sitedescription' => "Short description of your site (optional)", - 'installation:wwwroot' => "The site URL, followed by a trailing slash:", - 'installation:path' => "The full path to your site root on your disk, followed by a trailing slash:", - 'installation:dataroot' => "The full path to the directory where uploaded files will be stored, followed by a trailing slash:", - 'installation:dataroot:warning' => "You must create this directory manually. It should sit in a different directory to your Elgg installation.", - 'installation:sitepermissions' => "The default access permissions:", - 'installation:language' => "The default language for your site:", - 'installation:debug' => "Debug mode provides extra information which can be used to diagnose faults, however it can slow your system down so should only be used if you are having problems:", - 'installation:debug:label' => "Turn on debug mode", - 'installation:httpslogin' => "Enable this to have user logins performed over HTTPS. You will need to have https enabled on your server for this to work.", - 'installation:httpslogin:label' => "Enable HTTPS logins", - 'installation:usage' => "This option lets Elgg send anonymous usage statistics back to Curverider.", - 'installation:usage:label' => "Send anonymous usage statistics", - 'installation:view' => "Enter the view which will be used as the default for your site or leave this blank for the default view (if in doubt, leave as default):", - - 'installation:siteemail' => "Site email address (used when sending system emails)", - - 'installation:disableapi' => "The RESTful API is a flexible and extensible interface that enables applications to use certain Elgg features remotely.", - 'installation:disableapi:label' => "Enable the RESTful API", - - 'installation:allow_user_default_access:description' => "If checked, individual users will be allowed to set their own default access level that can over-ride the system default access level.", - 'installation:allow_user_default_access:label' => "Allow user default access", - - 'installation:simplecache:description' => "The simple cache increases performance by caching static content including some CSS and JavaScript files. Normally you will want this on.", - 'installation:simplecache:label' => "Use simple cache (recommended)", - - 'installation:viewpathcache:description' => "The view filepath cache decreases the loading times of plugins by caching the location of their views.", - 'installation:viewpathcache:label' => "Use view filepath cache (recommended)", - - 'upgrading' => 'Upgrading', - 'upgrade:db' => 'Your database was upgraded.', - 'upgrade:core' => 'Your elgg installation was upgraded', - - /** - * Welcome - */ - - 'welcome' => "Welcome", - 'welcome:user' => 'Welcome %s', - 'welcome_message' => "Welcome to this Elgg installation.", - - /** - * Emails - */ - 'email:settings' => "Email settings", - 'email:address:label' => "Your email address", - - 'email:save:success' => "New email address saved, verification requested.", - 'email:save:fail' => "Your new email address could not be saved.", - - 'friend:newfriend:subject' => "%s has made you a friend!", - 'friend:newfriend:body' => "%s has made you a friend! - -To view their profile, click here: - - %s - -You cannot reply to this email.", - - - - 'email:resetpassword:subject' => "Password reset!", - 'email:resetpassword:body' => "Hi %s, - -Your password has been reset to: %s", - - - 'email:resetreq:subject' => "Request for new password.", - 'email:resetreq:body' => "Hi %s, - -Somebody (from the IP address %s) has requested a new password for their account. - -If you requested this click on the link below, otherwise ignore this email. - -%s -", - - /** - * user default access - */ - - 'default_access:settings' => "Your default access level", - 'default_access:label' => "Default access", - 'user:default_access:success' => "Your new default access level was saved.", - 'user:default_access:failure' => "Your new default access level could not be saved.", - - /** - * XML-RPC - */ - 'xmlrpc:noinputdata' => "Input data missing", - - /** - * Comments - */ - - 'comments:count' => "%s comments", - - 'riveraction:annotation:generic_comment' => '%s commented on %s', - - 'generic_comments:add' => "Add a comment", - 'generic_comments:text' => "Comment", - 'generic_comment:posted' => "Your comment was successfully posted.", - 'generic_comment:deleted' => "Your comment was successfully deleted.", - 'generic_comment:blank' => "Sorry; you need to actually put something in your comment before we can save it.", - 'generic_comment:notfound' => "Sorry; we could not find the specified item.", - 'generic_comment:notdeleted' => "Sorry; we could not delete this comment.", - 'generic_comment:failure' => "An unexpected error occurred when adding your comment. Please try again.", - - 'generic_comment:email:subject' => 'You have a new comment!', - 'generic_comment:email:body' => "You have a new comment on your item \"%s\" from %s. It reads: - - -%s - - -To reply or view the original item, click here: - - %s - -To view %s's profile, click here: - - %s - -You cannot reply to this email.", - - /** - * Entities - */ - 'entity:default:strapline' => 'Created %s by %s', - 'entity:default:missingsupport:popup' => 'This entity cannot be displayed correctly. This may be because it requires support provided by a plugin that is no longer installed.', - - 'entity:delete:success' => 'Entity %s has been deleted', - 'entity:delete:fail' => 'Entity %s could not be deleted', - - - /** - * Action gatekeeper - */ - 'actiongatekeeper:missingfields' => 'Form is missing __token or __ts fields', - 'actiongatekeeper:tokeninvalid' => "We encountered an error (token mismatch). This probably means that the page you were using expired. Please try again.", - 'actiongatekeeper:timeerror' => 'The page you were using has expired. Please refresh and try again.', - 'actiongatekeeper:pluginprevents' => 'A extension has prevented this form from being submitted.', - - /** - * Word blacklists - */ - 'word:blacklist' => 'and, the, then, but, she, his, her, him, one, not, also, about, now, hence, however, still, likewise, otherwise, therefore, conversely, rather, consequently, furthermore, nevertheless, instead, meanwhile, accordingly, this, seems, what, whom, whose, whoever, whomever', - - /** - * Languages according to ISO 639-1 - */ - "aa" => "Afar", - "ab" => "Abkhazian", - "af" => "Afrikaans", - "am" => "Amharic", - "ar" => "Arabic", - "as" => "Assamese", - "ay" => "Aymara", - "az" => "Azerbaijani", - "ba" => "Bashkir", - "be" => "Byelorussian", - "bg" => "Bulgarian", - "bh" => "Bihari", - "bi" => "Bislama", - "bn" => "Bengali; Bangla", - "bo" => "Tibetan", - "br" => "Breton", - "ca" => "Catalan", - "co" => "Corsican", - "cs" => "Czech", - "cy" => "Welsh", - "da" => "Danish", - "de" => "German", - "dz" => "Bhutani", - "el" => "Greek", - "en" => "English", - "eo" => "Esperanto", - "es" => "Spanish", - "et" => "Estonian", - "eu" => "Basque", - "fa" => "Persian", - "fi" => "Finnish", - "fj" => "Fiji", - "fo" => "Faeroese", - "fr" => "French", - "fy" => "Frisian", - "ga" => "Irish", - "gd" => "Scots / Gaelic", - "gl" => "Galician", - "gn" => "Guarani", - "gu" => "Gujarati", - "he" => "Hebrew", - "ha" => "Hausa", - "hi" => "Hindi", - "hr" => "Croatian", - "hu" => "Hungarian", - "hy" => "Armenian", - "ia" => "Interlingua", - "id" => "Indonesian", - "ie" => "Interlingue", - "ik" => "Inupiak", - //"in" => "Indonesian", - "is" => "Icelandic", - "it" => "Italian", - "iu" => "Inuktitut", - "iw" => "Hebrew (obsolete)", - "ja" => "Japanese", - "ji" => "Yiddish (obsolete)", - "jw" => "Javanese", - "ka" => "Georgian", - "kk" => "Kazakh", - "kl" => "Greenlandic", - "km" => "Cambodian", - "kn" => "Kannada", - "ko" => "Korean", - "ks" => "Kashmiri", - "ku" => "Kurdish", - "ky" => "Kirghiz", - "la" => "Latin", - "ln" => "Lingala", - "lo" => "Laothian", - "lt" => "Lithuanian", - "lv" => "Latvian/Lettish", - "mg" => "Malagasy", - "mi" => "Maori", - "mk" => "Macedonian", - "ml" => "Malayalam", - "mn" => "Mongolian", - "mo" => "Moldavian", - "mr" => "Marathi", - "ms" => "Malay", - "mt" => "Maltese", - "my" => "Burmese", - "na" => "Nauru", - "ne" => "Nepali", - "nl" => "Dutch", - "no" => "Norwegian", - "oc" => "Occitan", - "om" => "(Afan) Oromo", - "or" => "Oriya", - "pa" => "Punjabi", - "pl" => "Polish", - "ps" => "Pashto / Pushto", - "pt" => "Portuguese", - "qu" => "Quechua", - "rm" => "Rhaeto-Romance", - "rn" => "Kirundi", - "ro" => "Romanian", - "ru" => "Russian", - "rw" => "Kinyarwanda", - "sa" => "Sanskrit", - "sd" => "Sindhi", - "sg" => "Sangro", - "sh" => "Serbo-Croatian", - "si" => "Singhalese", - "sk" => "Slovak", - "sl" => "Slovenian", - "sm" => "Samoan", - "sn" => "Shona", - "so" => "Somali", - "sq" => "Albanian", - "sr" => "Serbian", - "ss" => "Siswati", - "st" => "Sesotho", - "su" => "Sundanese", - "sv" => "Swedish", - "sw" => "Swahili", - "ta" => "Tamil", - "te" => "Tegulu", - "tg" => "Tajik", - "th" => "Thai", - "ti" => "Tigrinya", - "tk" => "Turkmen", - "tl" => "Tagalog", - "tn" => "Setswana", - "to" => "Tonga", - "tr" => "Turkish", - "ts" => "Tsonga", - "tt" => "Tatar", - "tw" => "Twi", - "ug" => "Uigur", - "uk" => "Ukrainian", - "ur" => "Urdu", - "uz" => "Uzbek", - "vi" => "Vietnamese", - "vo" => "Volapuk", - "wo" => "Wolof", - "xh" => "Xhosa", - //"y" => "Yiddish", - "yi" => "Yiddish", - "yo" => "Yoruba", - "za" => "Zuang", - "zh" => "Chinese", - "zu" => "Zulu", - ); - - add_translation("en",$english); - -?> + + + + /** + * Profile menu items and titles + */ + + 'profile:yours' => "Your profile", + 'profile:user' => "%s's profile", + + 'profile:edit' => "Edit profile", + 'profile:profilepictureinstructions' => "The profile picture is the image that's displayed on your profile page.
You can change it as often as you'd like. (File formats accepted: GIF, JPG or PNG)", + 'profile:icon' => "Profile picture", + 'profile:createicon' => "Create your avatar", + 'profile:currentavatar' => "Current avatar", + 'profile:createicon:header' => "Profile picture", + 'profile:profilepicturecroppingtool' => "Profile picture cropping tool", + 'profile:createicon:instructions' => "Click and drag a square below to match how you want your picture cropped. A preview of your cropped picture will appear in the box on the right. When you are happy with the preview, click 'Create your avatar'. This cropped image will be used throughout the site as your avatar. ", + + 'profile:editdetails' => "Edit details", + 'profile:editicon' => "Edit profile icon", + + 'profile:aboutme' => "About me", + 'profile:description' => "About me", + 'profile:briefdescription' => "Brief description", + 'profile:location' => "Location", + 'profile:skills' => "Skills", + 'profile:interests' => "Interests", + 'profile:contactemail' => "Contact email", + 'profile:phone' => "Telephone", + 'profile:mobile' => "Mobile phone", + 'profile:website' => "Website", + + 'profile:banned' => 'This user account has been suspended.', + 'profile:deleteduser' => 'Deleted user', + + 'profile:river:update' => "%s updated their profile", + 'profile:river:iconupdate' => "%s updated their profile icon", + + 'profile:label' => "Profile label", + 'profile:type' => "Profile type", + + 'profile:editdefault:fail' => 'Default profile could not be saved', + 'profile:editdefault:success' => 'Item successfully added to default profile', + + + 'profile:editdefault:delete:fail' => 'Removed default profile item field failed', + 'profile:editdefault:delete:success' => 'Default profile item deleted!', + + 'profile:defaultprofile:reset' => 'Default system profile reset', + + 'profile:resetdefault' => 'Reset default profile', + 'profile:explainchangefields' => 'You can replace the existing profile fields with your own using the form below. First you give the new profile field a label, for example, \'Favourite team\'. Next you need to select the field type, for example, tags, url, text and so on. At any time you can revert back to the default profile set up.', + + + + /** + * Profile status messages + */ + + 'profile:saved' => "Your profile was successfully saved.", + 'profile:icon:uploaded' => "Your profile picture was successfully uploaded.", + + /** + * Profile error messages + */ + + 'profile:noaccess' => "You do not have permission to edit this profile.", + 'profile:notfound' => "Sorry; we could not find the specified profile.", + 'profile:cantedit' => "Sorry; you do not have permission to edit this profile.", + 'profile:icon:notfound' => "Sorry; there was a problem uploading your profile picture.", + + /** + * Friends + */ + + 'friends' => "Friends", + 'friends:yours' => "Your friends", + 'friends:owned' => "%s's friends", + 'friend:add' => "Add friend", + 'friend:remove' => "Remove friend", + + 'friends:add:successful' => "You have successfully added %s as a friend.", + 'friends:add:failure' => "We couldn't add %s as a friend. Please try again.", + + 'friends:remove:successful' => "You have successfully removed %s from your friends.", + 'friends:remove:failure' => "We couldn't remove %s from your friends. Please try again.", + + 'friends:none' => "This user hasn't added anyone as a friend yet.", + 'friends:none:you' => "You haven't added anyone as a friend! Search for your interests to begin finding people to follow.", + + 'friends:none:found' => "No friends were found.", + + 'friends:of:none' => "Nobody has added this user as a friend yet.", + 'friends:of:none:you' => "Nobody has added you as a friend yet. Start adding content and fill in your profile to let people find you!", + + 'friends:of:owned' => "People who have made %s a friend", + + 'friends:num_display' => "Number of friends to display", + 'friends:icon_size' => "Icon size", + 'friends:tiny' => "tiny", + 'friends:small' => "small", + 'friends:of' => "Friends of", + 'friends:collections' => "Collections of friends", + 'friends:collections:add' => "New friends collection", + 'friends:addfriends' => "Add friends", + 'friends:collectionname' => "Collection name", + 'friends:collectionfriends' => "Friends in collection", + 'friends:collectionedit' => "Edit this collection", + 'friends:nocollections' => "You do not yet have any collections.", + 'friends:collectiondeleted' => "Your collection has been deleted.", + 'friends:collectiondeletefailed' => "We were unable to delete the collection. Either you don't have permission, or some other problem has occurred.", + 'friends:collectionadded' => "Your collection was successfuly created", + 'friends:nocollectionname' => "You need to give your collection a name before it can be created.", + 'friends:collections:members' => "Collection members", + 'friends:collections:edit' => "Edit collection", + + 'friends:river:created' => "%s added the friends widget.", + 'friends:river:updated' => "%s updated their friends widget.", + 'friends:river:delete' => "%s removed their friends widget.", + 'friends:river:add' => "%s is now a friend with", + + 'friendspicker:chararray' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + + /** + * Feeds + */ + 'feed:rss' => 'Subscribe to feed', + 'feed:odd' => 'Syndicate OpenDD', + + /** + * links + **/ + + 'link:view' => 'view link', + + + /** + * River + */ + 'river' => "River", + 'river:relationship:friend' => 'is now friends with', + 'river:noaccess' => 'You do not have permission to view this item.', + 'river:posted:generic' => '%s posted', + + /** + * Plugins + */ + 'plugins:settings:save:ok' => "Settings for the %s plugin were saved successfully.", + 'plugins:settings:save:fail' => "There was a problem saving settings for the %s plugin.", + 'plugins:usersettings:save:ok' => "User settings for the %s plugin were saved successfully.", + 'plugins:usersettings:save:fail' => "There was a problem saving user settings for the %s plugin.", + 'admin:plugins:label:version' => "Version", + 'item:object:plugin' => 'Plugin configuration settings', + + /** + * Notifications + */ + 'notifications:usersettings' => "Notification settings", + 'notifications:methods' => "Please specify which methods you want to permit.", + + 'notifications:usersettings:save:ok' => "Your notification settings were successfully saved.", + 'notifications:usersettings:save:fail' => "There was a problem saving your notification settings.", + + 'user.notification.get' => 'Return the notification settings for a given user.', + 'user.notification.set' => 'Set the notification settings for a given user.', + /** + * Search + */ + + 'search' => "Search", + 'searchtitle' => "Search: %s", + 'users:searchtitle' => "Searching for users: %s", + 'groups:searchtitle' => "Searching for groups: %s", + 'advancedsearchtitle' => "%s with results matching %s", + 'notfound' => "No results found.", + 'next' => "Next", + 'previous' => "Previous", + + 'viewtype:change' => "Change listing type", + 'viewtype:list' => "List view", + 'viewtype:gallery' => "Gallery", + + 'tag:search:startblurb' => "Items with tags matching '%s':", + + 'user:search:startblurb' => "Users matching '%s':", + 'user:search:finishblurb' => "To view more, click here.", + + 'group:search:startblurb' => "Groups matching '%s':", + 'group:search:finishblurb' => "To view more, click here.", + 'search:go' => 'Go', + + /** + * Account + */ + + 'account' => "Account", + 'settings' => "Settings", + 'tools' => "Tools", + 'tools:yours' => "Your tools", + + 'register' => "Register", + 'registerok' => "You have successfully registered for %s.", + 'registerbad' => "Your registration was unsuccessful. The username may already exist, your passwords might not match, or your username or password may be too short.", + 'registerdisabled' => "Registration has been disabled by the system administrator", + + 'firstadminlogininstructions' => 'Your new Elgg site has been successfully installed and your administrator account created. You can now configure your site further by enabling various installed plugin tools.', + + 'registration:notemail' => 'The email address you provided does not appear to be a valid email address.', + 'registration:userexists' => 'That username already exists', + 'registration:usernametooshort' => 'Your username must be a minimum of 4 characters long.', + 'registration:passwordtooshort' => 'The password must be a minimum of 6 characters long.', + 'registration:dupeemail' => 'This email address has already been registered.', + 'registration:invalidchars' => 'Sorry, your username contains invalid characters.', + 'registration:emailnotvalid' => 'Sorry, the email address you entered is invalid on this system', + 'registration:passwordnotvalid' => 'Sorry, the password you entered is invalid on this system', + 'registration:usernamenotvalid' => 'Sorry, the username you entered is invalid on this system', + + 'adduser' => "Add User", + 'adduser:ok' => "You have successfully added a new user.", + 'adduser:bad' => "The new user could not be created.", + + 'item:object:reported_content' => "Reported items", + + 'user:set:name' => "Account name settings", + 'user:name:label' => "Your name", + 'user:name:success' => "Successfully changed your name on the system.", + 'user:name:fail' => "Could not change your name on the system.", + + 'user:set:password' => "Account password", + 'user:password:label' => "Your new password", + 'user:password2:label' => "Your new password again", + 'user:password:success' => "Password changed", + 'user:password:fail' => "Could not change your password on the system.", + 'user:password:fail:notsame' => "The two passwords are not the same!", + 'user:password:fail:tooshort' => "Password is too short!", + + 'user:set:language' => "Language settings", + 'user:language:label' => "Your language", + 'user:language:success' => "Your language settings have been updated.", + 'user:language:fail' => "Your language settings could not be saved.", + + 'user:username:notfound' => 'Username %s not found.', + + 'user:password:lost' => 'Lost password', + 'user:password:resetreq:success' => 'Successfully requested a new password, email sent', + 'user:password:resetreq:fail' => 'Could not request a new password.', + + 'user:password:text' => 'To generate a new password, enter your username below. We will send the address of a unique verification page to you via email click on the link in the body of the message and a new password will be sent to you.', + + 'user:persistent' => 'Remember me', + /** + * Administration + */ + + 'admin:configuration:success' => "Your settings have been saved.", + 'admin:configuration:fail' => "Your settings could not be saved.", + + 'admin' => "Administration", + 'admin:description' => "The admin panel allows you to control all aspects of the system, from user management to how plugins behave. Choose an option below to get started.", + + 'admin:user' => "User Administration", + 'admin:user:description' => "This admin panel allows you to control user settings for your site. Choose an option below to get started.", + 'admin:user:adduser:label' => "Click here to add a new user...", + 'admin:user:opt:linktext' => "Configure users...", + 'admin:user:opt:description' => "Configure users and account information. ", + + 'admin:site' => "Site Administration", + 'admin:site:description' => "This admin panel allows you to control global settings for your site. Choose an option below to get started.", + 'admin:site:opt:linktext' => "Configure site...", + 'admin:site:opt:description' => "Configure the site technical and non-technical settings. ", + 'admin:site:access:warning' => "Changing the access setting only affects the permissions on content created in the future.", + + 'admin:plugins' => "Tool Administration", + 'admin:plugins:description' => "This admin panel allows you to control and configure tools installed on your site.", + 'admin:plugins:opt:linktext' => "Configure tools...", + 'admin:plugins:opt:description' => "Configure the tools installed on the site. ", + 'admin:plugins:label:author' => "Author", + 'admin:plugins:label:copyright' => "Copyright", + 'admin:plugins:label:licence' => "Licence", + 'admin:plugins:label:website' => "URL", + 'admin:plugins:label:moreinfo' => 'more info', + 'admin:plugins:label:version' => 'Version', + 'admin:plugins:warning:elggversionunknown' => 'Warning: This plugin does not specify a compatible Elgg version.', + 'admin:plugins:warning:elggtoolow' => 'Warning: This plugin requires a later version of Elgg!', + 'admin:plugins:reorder:yes' => "Plugin %s was reordered successfully.", + 'admin:plugins:reorder:no' => "Plugin %s could not be reordered.", + 'admin:plugins:disable:yes' => "Plugin %s was disabled successfully.", + 'admin:plugins:disable:no' => "Plugin %s could not be disabled.", + 'admin:plugins:enable:yes' => "Plugin %s was enabled successfully.", + 'admin:plugins:enable:no' => "Plugin %s could not be enabled.", + + 'admin:statistics' => "Statistics", + 'admin:statistics:description' => "This is an overview of statistics on your site. If you need more detailed statistics, a professional administration feature is available.", + 'admin:statistics:opt:description' => "View statistical information about users and objects on your site.", + 'admin:statistics:opt:linktext' => "View statistics...", + 'admin:statistics:label:basic' => "Basic site statistics", + 'admin:statistics:label:numentities' => "Entities on site", + 'admin:statistics:label:numusers' => "Number of users", + 'admin:statistics:label:numonline' => "Number of users online", + 'admin:statistics:label:onlineusers' => "Users online now", + 'admin:statistics:label:version' => "Elgg version", + 'admin:statistics:label:version:release' => "Release", + 'admin:statistics:label:version:version' => "Version", + + 'admin:user:label:search' => "Find users:", + 'admin:user:label:seachbutton' => "Search", + + 'admin:user:ban:no' => "Can not ban user", + 'admin:user:ban:yes' => "User banned.", + 'admin:user:unban:no' => "Can not unban user", + 'admin:user:unban:yes' => "User un-banned.", + 'admin:user:delete:no' => "Can not delete user", + 'admin:user:delete:yes' => "User deleted", + + 'admin:user:resetpassword:yes' => "Password reset, user notified.", + 'admin:user:resetpassword:no' => "Password could not be reset.", + + 'admin:user:makeadmin:yes' => "User is now an admin.", + 'admin:user:makeadmin:no' => "We could not make this user an admin.", + + 'admin:user:removeadmin:yes' => "User is no longer an admin.", + 'admin:user:removeadmin:no' => "We could not remove administrator privileges from this user.", + + /** + * User settings + */ + 'usersettings:description' => "The user settings panel allows you to control all your personal settings, from user management to how plugins behave. Choose an option below to get started.", + + 'usersettings:statistics' => "Your statistics", + 'usersettings:statistics:opt:description' => "View statistical information about users and objects on your site.", + 'usersettings:statistics:opt:linktext' => "Account statistics", + + 'usersettings:user' => "Your settings", + 'usersettings:user:opt:description' => "This allows you to control user settings.", + 'usersettings:user:opt:linktext' => "Change your settings", + + 'usersettings:plugins' => "Tools", + 'usersettings:plugins:opt:description' => "Configure settings (if any) for your active tools.", + 'usersettings:plugins:opt:linktext' => "Configure your tools", + + 'usersettings:plugins:description' => "This panel allows you to control and configure the personal settings for the tools installed by your system administrator.", + 'usersettings:statistics:label:numentities' => "Your entities", + + 'usersettings:statistics:yourdetails' => "Your details", + 'usersettings:statistics:label:name' => "Full name", + 'usersettings:statistics:label:email' => "Email", + 'usersettings:statistics:label:membersince' => "Member since", + 'usersettings:statistics:label:lastlogin' => "Last logged in", + + + + /** + * Generic action words + */ + + 'save' => "Save", + 'publish' => "Publish", + 'cancel' => "Cancel", + 'saving' => "Saving ...", + 'update' => "Update", + 'edit' => "Edit", + 'delete' => "Delete", + 'accept' => "Accept", + 'load' => "Load", + 'upload' => "Upload", + 'ban' => "Ban", + 'unban' => "Unban", + 'enable' => "Enable", + 'disable' => "Disable", + 'request' => "Request", + 'complete' => "Complete", + 'open' => 'Open', + 'close' => 'Close', + 'reply' => "Reply", + 'more' => 'More', + 'comments' => 'Comments', + 'import' => 'Import', + 'export' => 'Export', + + 'up' => 'Up', + 'down' => 'Down', + 'top' => 'Top', + 'bottom' => 'Bottom', + + 'invite' => "Invite", + + 'resetpassword' => "Reset password", + 'makeadmin' => "Make admin", + 'removeadmin' => "Remove admin", + + 'option:yes' => "Yes", + 'option:no' => "No", + + 'unknown' => 'Unknown', + + 'active' => 'Active', + 'total' => 'Total', + + 'learnmore' => "Click here to learn more.", + + 'content' => "content", + 'content:latest' => 'Latest activity', + 'content:latest:blurb' => 'Alternatively, click here to view the latest content from across the site.', + + 'link:text' => 'view link', + + 'enableall' => 'Enable All', + 'disableall' => 'Disable All', + + /** + * Generic questions + */ + + 'question:areyousure' => 'Are you sure?', + + /** + * Generic data words + */ + + 'title' => "Title", + 'description' => "Description", + 'tags' => "Tags", + 'spotlight' => "Spotlight", + 'all' => "All", + + 'by' => 'by', + + 'annotations' => "Annotations", + 'relationships' => "Relationships", + 'metadata' => "Metadata", + + /** + * Input / output strings + */ + + 'deleteconfirm' => "Are you sure you want to delete this item?", + 'fileexists' => "A file has already been uploaded. To replace it, select it below:", + + /** + * User add + */ + + 'useradd:subject' => 'User account created', + 'useradd:body' => ' +%s, + +A user account has been created for you at %s. To log in, visit: + + %s + +And log in with these user credentials: + + Username: %s + Password: %s + +Once you have logged in, we highly recommend that you change your password. +', + + /** + * System messages + **/ + + 'systemmessages:dismiss' => "click to dismiss", + + + /** + * Import / export + */ + 'importsuccess' => "Import of data was successful", + 'importfail' => "OpenDD import of data failed.", + + /** + * Time + */ + + 'friendlytime:justnow' => "just now", + 'friendlytime:minutes' => "%s minutes ago", + 'friendlytime:minutes:singular' => "a minute ago", + 'friendlytime:hours' => "%s hours ago", + 'friendlytime:hours:singular' => "an hour ago", + 'friendlytime:days' => "%s days ago", + 'friendlytime:days:singular' => "yesterday", + + 'date:month:01' => 'January %s', + 'date:month:02' => 'February %s', + 'date:month:03' => 'March %s', + 'date:month:04' => 'April %s', + 'date:month:05' => 'May %s', + 'date:month:06' => 'June %s', + 'date:month:07' => 'July %s', + 'date:month:08' => 'August %s', + 'date:month:09' => 'September %s', + 'date:month:10' => 'October %s', + 'date:month:11' => 'November %s', + 'date:month:12' => 'December %s', + + + /** + * Installation and system settings + */ + + 'installation:error:htaccess' => "Elgg requires a file called .htaccess to be set in the root directory of its installation. We tried to create it for you, but Elgg doesn't have permission to write to that directory. + +Creating this is easy. Copy the contents of the textbox below into a text editor and save it as .htaccess + +", + 'installation:error:settings' => "Elgg couldn't find its settings file. Most of Elgg's settings will be handled for you, but we need you to supply your database details. To do this: + +1. Rename engine/settings.example.php to settings.php in your Elgg installation. + +2. Open it with a text editor and enter your MySQL database details. If you don't know these, ask your system administrator or technical support for help. + +Alternatively, you can enter your database settings below and we will try and do this for you...", + + 'installation:error:configuration' => "Once you've corrected any configuration issues, press reload to try again.", + + 'installation' => "Installation", + 'installation:success' => "Elgg's database was installed successfully.", + 'installation:configuration:success' => "Your initial configuration settings have been saved. Now register your initial user; this will be your first system administrator.", + + 'installation:settings' => "System settings", + 'installation:settings:description' => "Now that the Elgg database has been successfully installed, you need to enter a couple of pieces of information to get your site fully up and running. We've tried to guess where we could, but you should check these details.", + + 'installation:settings:dbwizard:prompt' => "Enter your database settings below and hit save:", + 'installation:settings:dbwizard:label:user' => "Database user", + 'installation:settings:dbwizard:label:pass' => "Database password", + 'installation:settings:dbwizard:label:dbname' => "Elgg database", + 'installation:settings:dbwizard:label:host' => "Database hostname (usually 'localhost')", + 'installation:settings:dbwizard:label:prefix' => "Database table prefix (usually 'elgg')", + + 'installation:settings:dbwizard:savefail' => "We were unable to save the new settings.php. Please save the following file as engine/settings.php using a text editor.", + + 'installation:sitename' => "The name of your site (eg \"My social networking site\"):", + 'installation:sitedescription' => "Short description of your site (optional)", + 'installation:wwwroot' => "The site URL, followed by a trailing slash:", + 'installation:path' => "The full path to your site root on your disk, followed by a trailing slash:", + 'installation:dataroot' => "The full path to the directory where uploaded files will be stored, followed by a trailing slash:", + 'installation:dataroot:warning' => "You must create this directory manually. It should sit in a different directory to your Elgg installation.", + 'installation:sitepermissions' => "The default access permissions:", + 'installation:language' => "The default language for your site:", + 'installation:debug' => "Debug mode provides extra information which can be used to diagnose faults, however it can slow your system down so should only be used if you are having problems:", + 'installation:debug:label' => "Turn on debug mode", + 'installation:httpslogin' => "Enable this to have user logins performed over HTTPS. You will need to have https enabled on your server for this to work.", + 'installation:httpslogin:label' => "Enable HTTPS logins", + 'installation:usage' => "This option lets Elgg send anonymous usage statistics back to Curverider.", + 'installation:usage:label' => "Send anonymous usage statistics", + 'installation:view' => "Enter the view which will be used as the default for your site or leave this blank for the default view (if in doubt, leave as default):", + + 'installation:siteemail' => "Site email address (used when sending system emails)", + + 'installation:disableapi' => "The RESTful API is a flexible and extensible interface that enables applications to use certain Elgg features remotely.", + 'installation:disableapi:label' => "Enable the RESTful API", + + 'installation:allow_user_default_access:description' => "If checked, individual users will be allowed to set their own default access level that can over-ride the system default access level.", + 'installation:allow_user_default_access:label' => "Allow user default access", + + 'installation:simplecache:description' => "The simple cache increases performance by caching static content including some CSS and JavaScript files. Normally you will want this on.", + 'installation:simplecache:label' => "Use simple cache (recommended)", + + 'installation:viewpathcache:description' => "The view filepath cache decreases the loading times of plugins by caching the location of their views.", + 'installation:viewpathcache:label' => "Use view filepath cache (recommended)", + + 'upgrading' => 'Upgrading', + 'upgrade:db' => 'Your database was upgraded.', + 'upgrade:core' => 'Your elgg installation was upgraded', + + /** + * Welcome + */ + + 'welcome' => "Welcome", + 'welcome:user' => 'Welcome %s', + 'welcome_message' => "Welcome to this Elgg installation.", + + /** + * Emails + */ + 'email:settings' => "Email settings", + 'email:address:label' => "Your email address", + + 'email:save:success' => "New email address saved, verification requested.", + 'email:save:fail' => "Your new email address could not be saved.", + + 'friend:newfriend:subject' => "%s has made you a friend!", + 'friend:newfriend:body' => "%s has made you a friend! + +To view their profile, click here: + + %s + +You cannot reply to this email.", + + + + 'email:resetpassword:subject' => "Password reset!", + 'email:resetpassword:body' => "Hi %s, + +Your password has been reset to: %s", + + + 'email:resetreq:subject' => "Request for new password.", + 'email:resetreq:body' => "Hi %s, + +Somebody (from the IP address %s) has requested a new password for their account. + +If you requested this click on the link below, otherwise ignore this email. + +%s +", + + /** + * user default access + */ + + 'default_access:settings' => "Your default access level", + 'default_access:label' => "Default access", + 'user:default_access:success' => "Your new default access level was saved.", + 'user:default_access:failure' => "Your new default access level could not be saved.", + + /** + * XML-RPC + */ + 'xmlrpc:noinputdata' => "Input data missing", + + /** + * Comments + */ + + 'comments:count' => "%s comments", + + 'riveraction:annotation:generic_comment' => '%s commented on %s', + + 'generic_comments:add' => "Add a comment", + 'generic_comments:text' => "Comment", + 'generic_comment:posted' => "Your comment was successfully posted.", + 'generic_comment:deleted' => "Your comment was successfully deleted.", + 'generic_comment:blank' => "Sorry; you need to actually put something in your comment before we can save it.", + 'generic_comment:notfound' => "Sorry; we could not find the specified item.", + 'generic_comment:notdeleted' => "Sorry; we could not delete this comment.", + 'generic_comment:failure' => "An unexpected error occurred when adding your comment. Please try again.", + + 'generic_comment:email:subject' => 'You have a new comment!', + 'generic_comment:email:body' => "You have a new comment on your item \"%s\" from %s. It reads: + + +%s + + +To reply or view the original item, click here: + + %s + +To view %s's profile, click here: + + %s + +You cannot reply to this email.", + + /** + * Entities + */ + 'entity:default:strapline' => 'Created %s by %s', + 'entity:default:missingsupport:popup' => 'This entity cannot be displayed correctly. This may be because it requires support provided by a plugin that is no longer installed.', + + 'entity:delete:success' => 'Entity %s has been deleted', + 'entity:delete:fail' => 'Entity %s could not be deleted', + + + /** + * Action gatekeeper + */ + 'actiongatekeeper:missingfields' => 'Form is missing __token or __ts fields', + 'actiongatekeeper:tokeninvalid' => "We encountered an error (token mismatch). This probably means that the page you were using expired. Please try again.", + 'actiongatekeeper:timeerror' => 'The page you were using has expired. Please refresh and try again.', + 'actiongatekeeper:pluginprevents' => 'A extension has prevented this form from being submitted.', + + /** + * Word blacklists + */ + 'word:blacklist' => 'and, the, then, but, she, his, her, him, one, not, also, about, now, hence, however, still, likewise, otherwise, therefore, conversely, rather, consequently, furthermore, nevertheless, instead, meanwhile, accordingly, this, seems, what, whom, whose, whoever, whomever', + + /** + * Languages according to ISO 639-1 + */ + "aa" => "Afar", + "ab" => "Abkhazian", + "af" => "Afrikaans", + "am" => "Amharic", + "ar" => "Arabic", + "as" => "Assamese", + "ay" => "Aymara", + "az" => "Azerbaijani", + "ba" => "Bashkir", + "be" => "Byelorussian", + "bg" => "Bulgarian", + "bh" => "Bihari", + "bi" => "Bislama", + "bn" => "Bengali; Bangla", + "bo" => "Tibetan", + "br" => "Breton", + "ca" => "Catalan", + "co" => "Corsican", + "cs" => "Czech", + "cy" => "Welsh", + "da" => "Danish", + "de" => "German", + "dz" => "Bhutani", + "el" => "Greek", + "en" => "English", + "eo" => "Esperanto", + "es" => "Spanish", + "et" => "Estonian", + "eu" => "Basque", + "fa" => "Persian", + "fi" => "Finnish", + "fj" => "Fiji", + "fo" => "Faeroese", + "fr" => "French", + "fy" => "Frisian", + "ga" => "Irish", + "gd" => "Scots / Gaelic", + "gl" => "Galician", + "gn" => "Guarani", + "gu" => "Gujarati", + "he" => "Hebrew", + "ha" => "Hausa", + "hi" => "Hindi", + "hr" => "Croatian", + "hu" => "Hungarian", + "hy" => "Armenian", + "ia" => "Interlingua", + "id" => "Indonesian", + "ie" => "Interlingue", + "ik" => "Inupiak", + //"in" => "Indonesian", + "is" => "Icelandic", + "it" => "Italian", + "iu" => "Inuktitut", + "iw" => "Hebrew (obsolete)", + "ja" => "Japanese", + "ji" => "Yiddish (obsolete)", + "jw" => "Javanese", + "ka" => "Georgian", + "kk" => "Kazakh", + "kl" => "Greenlandic", + "km" => "Cambodian", + "kn" => "Kannada", + "ko" => "Korean", + "ks" => "Kashmiri", + "ku" => "Kurdish", + "ky" => "Kirghiz", + "la" => "Latin", + "ln" => "Lingala", + "lo" => "Laothian", + "lt" => "Lithuanian", + "lv" => "Latvian/Lettish", + "mg" => "Malagasy", + "mi" => "Maori", + "mk" => "Macedonian", + "ml" => "Malayalam", + "mn" => "Mongolian", + "mo" => "Moldavian", + "mr" => "Marathi", + "ms" => "Malay", + "mt" => "Maltese", + "my" => "Burmese", + "na" => "Nauru", + "ne" => "Nepali", + "nl" => "Dutch", + "no" => "Norwegian", + "oc" => "Occitan", + "om" => "(Afan) Oromo", + "or" => "Oriya", + "pa" => "Punjabi", + "pl" => "Polish", + "ps" => "Pashto / Pushto", + "pt" => "Portuguese", + "qu" => "Quechua", + "rm" => "Rhaeto-Romance", + "rn" => "Kirundi", + "ro" => "Romanian", + "ru" => "Russian", + "rw" => "Kinyarwanda", + "sa" => "Sanskrit", + "sd" => "Sindhi", + "sg" => "Sangro", + "sh" => "Serbo-Croatian", + "si" => "Singhalese", + "sk" => "Slovak", + "sl" => "Slovenian", + "sm" => "Samoan", + "sn" => "Shona", + "so" => "Somali", + "sq" => "Albanian", + "sr" => "Serbian", + "ss" => "Siswati", + "st" => "Sesotho", + "su" => "Sundanese", + "sv" => "Swedish", + "sw" => "Swahili", + "ta" => "Tamil", + "te" => "Tegulu", + "tg" => "Tajik", + "th" => "Thai", + "ti" => "Tigrinya", + "tk" => "Turkmen", + "tl" => "Tagalog", + "tn" => "Setswana", + "to" => "Tonga", + "tr" => "Turkish", + "ts" => "Tsonga", + "tt" => "Tatar", + "tw" => "Twi", + "ug" => "Uigur", + "uk" => "Ukrainian", + "ur" => "Urdu", + "uz" => "Uzbek", + "vi" => "Vietnamese", + "vo" => "Volapuk", + "wo" => "Wolof", + "xh" => "Xhosa", + //"y" => "Yiddish", + "yi" => "Yiddish", + "yo" => "Yoruba", + "za" => "Zuang", + "zh" => "Chinese", + "zu" => "Zulu", + ); + + add_translation("en",$english); + +?> diff --git a/mod/garbagecollector/languages/en.php b/mod/garbagecollector/languages/en.php index bfc56bdaa..480ec0042 100644 --- a/mod/garbagecollector/languages/en.php +++ b/mod/garbagecollector/languages/en.php @@ -17,7 +17,7 @@ 'garbagecollector:weekly' => 'Once a week', 'garbagecollector:monthly' => 'Once a month', - 'garbagecollector:yearly' => 'Once a year', + 'garbagecollector:yearly' => 'Once a year', 'garbagecollector' => "GARBAGE COLLECTOR\n", 'garbagecollector:done' => "DONE\n", diff --git a/mod/logbrowser/index.php b/mod/logbrowser/index.php index 975173700..18a15bfa4 100644 --- a/mod/logbrowser/index.php +++ b/mod/logbrowser/index.php @@ -1,66 +1,66 @@ -guid; + } + } else { + $user_guid = get_input('user_guid',0); + if ($user_guid) { + $user = (int) $user_guid; + } else { + $user = ""; + } + } + + $timelower = get_input('timelower'); + if ($timelower) $timelower = strtotime($timelower); + $timeupper = get_input('timeupper'); + if ($timeupper) $timeupper = strtotime($timeupper); + + $title = elgg_view_title(elgg_echo('logbrowser')); + + // Get log entries + $log = get_system_log($user, "", "", "","", $limit, $offset, false, $timeupper, $timelower); + $count = get_system_log($user, "", "", "","", $limit, $offset, true, $timeupper, $timelower); + $log_entries = array(); + + foreach ($log as $l) + { + $tmp = new ElggObject(); + $tmp->subtype = 'logwrapper'; + $tmp->entry = $l; + $log_entries[] = $tmp; + } + + $form = elgg_view('logbrowser/form',array('user_guid' => $user, 'timeupper' => $timeupper, 'timelower' => $timelower)); + + set_context('search'); + $result = elgg_view_entity_list($log_entries, $count, $offset, $limit, false, false); + set_context('admin'); + +// Display main admin menu + page_draw(elgg_echo('logbrowser'),elgg_view_layout("two_column_left_sidebar", '', $title . $form . $result)); - * @link http://elgg.com/ - */ - - require_once(dirname(dirname(dirname(__FILE__))) . "/engine/start.php"); - - admin_gatekeeper(); - set_context('admin'); - // Set admin user for user block - set_page_owner($_SESSION['guid']); - - - $limit = get_input('limit', 40); - $offset = get_input('offset'); - - $search_username = get_input('search_username'); - if ($search_username) { - if ($user = get_user_by_username($search_username)) { - $user = $user->guid; - } - } else { - $user_guid = get_input('user_guid',0); - if ($user_guid) { - $user = (int) $user_guid; - } else { - $user = ""; - } - } - - $timelower = get_input('timelower'); - if ($timelower) $timelower = strtotime($timelower); - $timeupper = get_input('timeupper'); - if ($timeupper) $timeupper = strtotime($timeupper); - - $title = elgg_view_title(elgg_echo('logbrowser')); - - // Get log entries - $log = get_system_log($user, "", "", "","", $limit, $offset, false, $timeupper, $timelower); - $count = get_system_log($user, "", "", "","", $limit, $offset, true, $timeupper, $timelower); - $log_entries = array(); - - foreach ($log as $l) - { - $tmp = new ElggObject(); - $tmp->subtype = 'logwrapper'; - $tmp->entry = $l; - $log_entries[] = $tmp; - } - - $form = elgg_view('logbrowser/form',array('user_guid' => $user, 'timeupper' => $timeupper, 'timelower' => $timelower)); - - set_context('search'); - $result = elgg_view_entity_list($log_entries, $count, $offset, $limit, false, false); - set_context('admin'); - -// Display main admin menu - page_draw(elgg_echo('logbrowser'),elgg_view_layout("two_column_left_sidebar", '', $title . $form . $result)); - ?> \ No newline at end of file diff --git a/mod/logbrowser/languages/en.php b/mod/logbrowser/languages/en.php index a100e7ff7..aa06edd9a 100644 --- a/mod/logbrowser/languages/en.php +++ b/mod/logbrowser/languages/en.php @@ -14,13 +14,13 @@ */ 'logbrowser' => 'Log browser', - 'logbrowser:browse' => 'Browse system log', - 'logbrowser:search' => 'Refine results', - 'logbrowser:user' => 'Username to search by', - 'logbrowser:starttime' => 'Beginning time (for example "last monday", "1 hour ago")', - 'logbrowser:endtime' => 'End time', - - 'logbrowser:explore' => 'Explore log', + 'logbrowser:browse' => 'Browse system log', + 'logbrowser:search' => 'Refine results', + 'logbrowser:user' => 'Username to search by', + 'logbrowser:starttime' => 'Beginning time (for example "last monday", "1 hour ago")', + 'logbrowser:endtime' => 'End time', + + 'logbrowser:explore' => 'Explore log', ); diff --git a/mod/logbrowser/start.php b/mod/logbrowser/start.php index 52e1f8617..47a78c243 100644 --- a/mod/logbrowser/start.php +++ b/mod/logbrowser/start.php @@ -16,28 +16,28 @@ global $CONFIG; // Register a page handler, so we can have nice URLs - register_page_handler('logbrowser','logbrowser_page_handler'); - - // Extend CSS - extend_view('css','logbrowser/css'); - - // Extend context menu with admin logbrowsre link - if (isadminloggedin()) - { - extend_view('profile/menu/adminlinks','logbrowser/adminlinks',10000); + register_page_handler('logbrowser','logbrowser_page_handler'); + + // Extend CSS + extend_view('css','logbrowser/css'); + + // Extend context menu with admin logbrowsre link + if (isadminloggedin()) + { + extend_view('profile/menu/adminlinks','logbrowser/adminlinks',10000); } - } - - /** - * Adding the log browser to the admin menu - * - */ - function logbrowser_pagesetup() - { - if (get_context() == 'admin' && isadminloggedin()) { - global $CONFIG; - add_submenu_item(elgg_echo('logbrowser'), $CONFIG->wwwroot . 'pg/logbrowser/'); - } + } + + /** + * Adding the log browser to the admin menu + * + */ + function logbrowser_pagesetup() + { + if (get_context() == 'admin' && isadminloggedin()) { + global $CONFIG; + add_submenu_item(elgg_echo('logbrowser'), $CONFIG->wwwroot . 'pg/logbrowser/'); + } } /** @@ -56,6 +56,6 @@ // Initialise log browser - register_elgg_event_handler('init','system','logbrowser_init'); + register_elgg_event_handler('init','system','logbrowser_init'); register_elgg_event_handler('pagesetup','system','logbrowser_pagesetup'); ?> \ No newline at end of file diff --git a/mod/logbrowser/views/default/logbrowser/adminlinks.php b/mod/logbrowser/views/default/logbrowser/adminlinks.php index abe83707d..e84e385ed 100644 --- a/mod/logbrowser/views/default/logbrowser/adminlinks.php +++ b/mod/logbrowser/views/default/logbrowser/adminlinks.php @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/mod/logbrowser/views/default/logbrowser/form.php b/mod/logbrowser/views/default/logbrowser/form.php index 2b0c78720..4a1e40d6a 100644 --- a/mod/logbrowser/views/default/logbrowser/form.php +++ b/mod/logbrowser/views/default/logbrowser/form.php @@ -1,66 +1,66 @@ - -
-username; - } else { - $userval = ""; - } - - - $form = ""; - - $form .= "

" . elgg_echo('logbrowser:user'); - $form .= elgg_view('input/text',array( - 'internalname' => 'search_username', - 'value' => $userval - )) . "

"; - - $form .= "

" . elgg_echo('logbrowser:starttime'); - $form .= elgg_view('input/text',array( - 'internalname' => 'timelower', - 'value' => $lowerval - )) . "

"; - - $form .= "

" . elgg_echo('logbrowser:endtime'); - $form .= elgg_view('input/text',array( - 'internalname' => 'timeupper', - 'value' => $upperval - )) . "

"; - $form .= elgg_view('input/submit',array( - 'value' => elgg_echo('search') - )); - - $wrappedform = elgg_view('input/form',array( - 'body' => $form, - 'method' => 'get', - 'action' => $vars['url'] . "mod/logbrowser/" - )); - - if ($upperval || $lowerval || $userval) { - $hidden = ""; - } else { - $hidden = "style=\"display:none\""; - } - -?> - -
>
-

- -

+ +
+username; + } else { + $userval = ""; + } + + + $form = ""; + + $form .= "

" . elgg_echo('logbrowser:user'); + $form .= elgg_view('input/text',array( + 'internalname' => 'search_username', + 'value' => $userval + )) . "

"; + + $form .= "

" . elgg_echo('logbrowser:starttime'); + $form .= elgg_view('input/text',array( + 'internalname' => 'timelower', + 'value' => $lowerval + )) . "

"; + + $form .= "

" . elgg_echo('logbrowser:endtime'); + $form .= elgg_view('input/text',array( + 'internalname' => 'timeupper', + 'value' => $upperval + )) . "

"; + $form .= elgg_view('input/submit',array( + 'value' => elgg_echo('search') + )); + + $wrappedform = elgg_view('input/form',array( + 'body' => $form, + 'method' => 'get', + 'action' => $vars['url'] . "mod/logbrowser/" + )); + + if ($upperval || $lowerval || $userval) { + $hidden = ""; + } else { + $hidden = "style=\"display:none\""; + } + +?> + +
>
+

+ +

\ No newline at end of file diff --git a/mod/logbrowser/views/default/object/logwrapper.php b/mod/logbrowser/views/default/object/logwrapper.php index bae5d4240..923ce7c52 100644 --- a/mod/logbrowser/views/default/object/logwrapper.php +++ b/mod/logbrowser/views/default/object/logwrapper.php @@ -1,50 +1,50 @@ -entry; - - $by = get_entity($entry->performed_by_guid); - $object = get_object_from_log_entry($entry->id); - - if (is_callable(array($object, 'getURL'))) - $obj_url = $object->getURL(); - - //echo elgg_view_listing($icon, $info); -?> - - - - - - -
- time_created ); ?> - - getURL()."\">{$by->name}"; - echo " guid}\">" . $by->guid . ""; - } - else echo " "; ?> - - - "; - echo "{$entry->object_class}"; - if ($obj_url) echo ""; - echo " " . $entry->object_id; - - ?> - -
- event); ?> -
-
+ * @link http://elgg.com/ + */ + + $entry = $vars['entity']->entry; + + $by = get_entity($entry->performed_by_guid); + $object = get_object_from_log_entry($entry->id); + + if (is_callable(array($object, 'getURL'))) + $obj_url = $object->getURL(); + + //echo elgg_view_listing($icon, $info); +?> + + + + + + +
+ time_created ); ?> + + getURL()."\">{$by->name}"; + echo " guid}\">" . $by->guid . ""; + } + else echo " "; ?> + + + "; + echo "{$entry->object_class}"; + if ($obj_url) echo ""; + echo " " . $entry->object_id; + + ?> + +
+ event); ?> +
+
\ No newline at end of file diff --git a/mod/uservalidationbyemail/start.php b/mod/uservalidationbyemail/start.php index fc6f5cc14..583415a5d 100644 --- a/mod/uservalidationbyemail/start.php +++ b/mod/uservalidationbyemail/start.php @@ -27,8 +27,8 @@ if (($object) && ($object instanceof ElggUser)) { uservalidationbyemail_request_validation($object->guid); - } - + } + return true; } diff --git a/settings/index.php b/settings/index.php index 7bf02273a..736dfe4c7 100644 --- a/settings/index.php +++ b/settings/index.php @@ -9,17 +9,17 @@ */ // Get the Elgg framework - require_once(dirname(dirname(__FILE__)) . "/engine/start.php"); - - if (!page_owner()) - set_page_owner($_SESSION['guid']); - - // Make sure we don't open a security hole ... - if ((!page_owner_entity()) || (!page_owner_entity()->canEdit())) { - set_page_owner($_SESSION['guid']); - } - + require_once(dirname(dirname(__FILE__)) . "/engine/start.php"); + + if (!page_owner()) + set_page_owner($_SESSION['guid']); + + // Make sure we don't open a security hole ... + if ((!page_owner_entity()) || (!page_owner_entity()->canEdit())) { + set_page_owner($_SESSION['guid']); + } + // Forward to the user settings - forward('pg/settings/user/' . page_owner_entity()->username . "/"); + forward('pg/settings/user/' . page_owner_entity()->username . "/"); ?> \ No newline at end of file diff --git a/simplecache/view.php b/simplecache/view.php index bb5eb2e03..0913ddb3e 100644 --- a/simplecache/view.php +++ b/simplecache/view.php @@ -1,71 +1,71 @@ -dbhost,$CONFIG->dbuser,$CONFIG->dbpass, true)) { - - $view = $viewinput['view']; - $viewtype = $viewinput['viewtype']; - if (empty($viewtype)) $viewtype = 'default'; - - if (@mysql_select_db($CONFIG->dbname,$mysql_dblink)) { - // get dataroot and simplecache_enabled in one select for efficiency - $simplecache_enabled = true; - if (!isset($dataroot)) { - if ($result = mysql_query("select name, value from {$CONFIG->dbprefix}datalists where name in ('dataroot','simplecache_enabled')",$mysql_dblink)) { - $row = mysql_fetch_object($result); - - while ($row) { - if ($row->name == 'dataroot') { - $dataroot = $row->value; - } else if ($row->name == 'simplecache_enabled') { - $simplecache_enabled = $row->value; - } - $row = mysql_fetch_object($result); - } - } - } - - if ($simplecache_enabled || $override) { - $filename = $dataroot . 'views_simplecache/' . md5($viewtype . $view); - if (file_exists($filename)) { - $contents = file_get_contents($filename); - header("Content-Length: " . strlen($contents)); +dbhost,$CONFIG->dbuser,$CONFIG->dbpass, true)) { + + $view = $viewinput['view']; + $viewtype = $viewinput['viewtype']; + if (empty($viewtype)) $viewtype = 'default'; + + if (@mysql_select_db($CONFIG->dbname,$mysql_dblink)) { + // get dataroot and simplecache_enabled in one select for efficiency + $simplecache_enabled = true; + if (!isset($dataroot)) { + if ($result = mysql_query("select name, value from {$CONFIG->dbprefix}datalists where name in ('dataroot','simplecache_enabled')",$mysql_dblink)) { + $row = mysql_fetch_object($result); + + while ($row) { + if ($row->name == 'dataroot') { + $dataroot = $row->value; + } else if ($row->name == 'simplecache_enabled') { + $simplecache_enabled = $row->value; + } + $row = mysql_fetch_object($result); + } + } + } + + if ($simplecache_enabled || $override) { + $filename = $dataroot . 'views_simplecache/' . md5($viewtype . $view); + if (file_exists($filename)) { + $contents = file_get_contents($filename); + header("Content-Length: " . strlen($contents)); } else { mysql_query("INSERT into {$CONFIG->dbprefix}datalists set name = 'simplecache_lastupdate', value = '0' ON DUPLICATE KEY UPDATE value='0'"); - - echo ''; exit; - } - } else { - mysql_close($mysql_dblink); - require_once(dirname(dirname(__FILE__)) . "/engine/start.php"); - $contents = elgg_view($view); - header("Content-Length: " . strlen($contents)); - } - } + + echo ''; exit; + } + } else { + mysql_close($mysql_dblink); + require_once(dirname(dirname(__FILE__)) . "/engine/start.php"); + $contents = elgg_view($view); + header("Content-Length: " . strlen($contents)); + } + } } $split_output = str_split($contents, 1024); foreach($split_output as $chunk) - echo $chunk; + echo $chunk; + - ?> diff --git a/upgrade.php b/upgrade.php index e1b297d83..8de74ad54 100644 --- a/upgrade.php +++ b/upgrade.php @@ -11,22 +11,22 @@ * @link http://elgg.org/ */ - // Include elgg engine - define('upgrading','upgrading'); + // Include elgg engine + define('upgrading','upgrading'); define('externalpage',true); - require_once(dirname(__FILE__) . "/engine/start.php"); - + require_once(dirname(__FILE__) . "/engine/start.php"); + if (get_input('upgrade') == 'upgrade') { if (version_upgrade_check()) { version_upgrade(); - } + } datalist_set('simplecache_lastupdate',0); - elgg_filepath_cache_reset(); - } else { - global $CONFIG; - echo elgg_view('settings/upgrading'); - exit; + elgg_filepath_cache_reset(); + } else { + global $CONFIG; + echo elgg_view('settings/upgrading'); + exit; } forward(); diff --git a/vendors/calendarpopup/CalendarPopup.js b/vendors/calendarpopup/CalendarPopup.js index 2eb92ec17..664c3c066 100644 --- a/vendors/calendarpopup/CalendarPopup.js +++ b/vendors/calendarpopup/CalendarPopup.js @@ -1,1462 +1,1462 @@ -// =================================================================== -// Author: Matt Kruse -// WWW: http://www.mattkruse.com/ -// -// NOTICE: You may use this code for any purpose, commercial or -// private, without any further permission from the author. You may -// remove this notice from your final code if you wish, however it is -// appreciated by the author if at least my web site address is kept. -// -// You may *NOT* re-distribute this code in any way except through its -// use. That means, you can include it in your product, or your web -// site, or any other form where the code is actually being used. You -// may not put the plain javascript up on your site for download or -// include it in your javascript libraries for download. -// If you wish to share this code with others, please just point them -// to the URL instead. -// Please DO NOT link directly to my .js files from your site. Copy -// the files to your server and use them there. Thank you. -// =================================================================== - - -/* SOURCE FILE: AnchorPosition.js */ - -/* -AnchorPosition.js -Author: Matt Kruse -Last modified: 10/11/02 - -DESCRIPTION: These functions find the position of an tag in a document, -so other elements can be positioned relative to it. - -COMPATABILITY: Netscape 4.x,6.x,Mozilla, IE 5.x,6.x on Windows. Some small -positioning errors - usually with Window positioning - occur on the -Macintosh platform. - -FUNCTIONS: -getAnchorPosition(anchorname) - Returns an Object() having .x and .y properties of the pixel coordinates - of the upper-left corner of the anchor. Position is relative to the PAGE. - -getAnchorWindowPosition(anchorname) - Returns an Object() having .x and .y properties of the pixel coordinates - of the upper-left corner of the anchor, relative to the WHOLE SCREEN. - -NOTES: - -1) For popping up separate browser windows, use getAnchorWindowPosition. - Otherwise, use getAnchorPosition - -2) Your anchor tag MUST contain both NAME and ID attributes which are the - same. For example: - - -3) There must be at least a space between for IE5.5 to see the - anchor tag correctly. Do not do with no space. -*/ - -// getAnchorPosition(anchorname) -// This function returns an object having .x and .y properties which are the coordinates -// of the named anchor, relative to the page. -function getAnchorPosition(anchorname) { - // This function will return an Object with x and y properties - var useWindow=false; - var coordinates=new Object(); - var x=0,y=0; - // Browser capability sniffing - var use_gebi=false, use_css=false, use_layers=false; - if (document.getElementById) { use_gebi=true; } - else if (document.all) { use_css=true; } - else if (document.layers) { use_layers=true; } - // Logic to find position - if (use_gebi && document.all) { - x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]); - y=AnchorPosition_getPageOffsetTop(document.all[anchorname]); - } - else if (use_gebi) { - var o=document.getElementById(anchorname); - x=AnchorPosition_getPageOffsetLeft(o); - y=AnchorPosition_getPageOffsetTop(o); - } - else if (use_css) { - x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]); - y=AnchorPosition_getPageOffsetTop(document.all[anchorname]); - } - else if (use_layers) { - var found=0; - for (var i=0; i9?"":"0")+x} - -// ------------------------------------------------------------------ -// isDate ( date_string, format_string ) -// Returns true if date string matches format of format string and -// is a valid date. Else returns false. -// It is recommended that you trim whitespace around the value before -// passing it to this function, as whitespace is NOT ignored! -// ------------------------------------------------------------------ -function isDate(val,format) { - var date=getDateFromFormat(val,format); - if (date==0) { return false; } - return true; - } - -// ------------------------------------------------------------------- -// compareDates(date1,date1format,date2,date2format) -// Compare two date strings to see which is greater. -// Returns: -// 1 if date1 is greater than date2 -// 0 if date2 is greater than date1 of if they are the same -// -1 if either of the dates is in an invalid format -// ------------------------------------------------------------------- -function compareDates(date1,dateformat1,date2,dateformat2) { - var d1=getDateFromFormat(date1,dateformat1); - var d2=getDateFromFormat(date2,dateformat2); - if (d1==0 || d2==0) { - return -1; - } - else if (d1 > d2) { - return 1; - } - return 0; - } - -// ------------------------------------------------------------------ -// formatDate (date_object, format) -// Returns a date in the output format specified. -// The format string uses the same abbreviations as in getDateFromFormat() -// ------------------------------------------------------------------ -function formatDate(date,format) { - format=format+""; - var result=""; - var i_format=0; - var c=""; - var token=""; - var y=date.getYear()+""; - var M=date.getMonth()+1; - var d=date.getDate(); - var E=date.getDay(); - var H=date.getHours(); - var m=date.getMinutes(); - var s=date.getSeconds(); - var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k; - // Convert real date parts into formatted versions - var value=new Object(); - if (y.length < 4) {y=""+(y-0+1900);} - value["y"]=""+y; - value["yyyy"]=y; - value["yy"]=y.substring(2,4); - value["M"]=M; - value["MM"]=LZ(M); - value["MMM"]=MONTH_NAMES[M-1]; - value["NNN"]=MONTH_NAMES[M+11]; - value["d"]=d; - value["dd"]=LZ(d); - value["E"]=DAY_NAMES[E+7]; - value["EE"]=DAY_NAMES[E]; - value["H"]=H; - value["HH"]=LZ(H); - if (H==0){value["h"]=12;} - else if (H>12){value["h"]=H-12;} - else {value["h"]=H;} - value["hh"]=LZ(value["h"]); - if (H>11){value["K"]=H-12;} else {value["K"]=H;} - value["k"]=H+1; - value["KK"]=LZ(value["K"]); - value["kk"]=LZ(value["k"]); - if (H > 11) { value["a"]="PM"; } - else { value["a"]="AM"; } - value["m"]=m; - value["mm"]=LZ(m); - value["s"]=s; - value["ss"]=LZ(s); - while (i_format < format.length) { - c=format.charAt(i_format); - token=""; - while ((format.charAt(i_format)==c) && (i_format < format.length)) { - token += format.charAt(i_format++); - } - if (value[token] != null) { result=result + value[token]; } - else { result=result + token; } - } - return result; - } - -// ------------------------------------------------------------------ -// Utility functions for parsing in getDateFromFormat() -// ------------------------------------------------------------------ -function _isInteger(val) { - var digits="1234567890"; - for (var i=0; i < val.length; i++) { - if (digits.indexOf(val.charAt(i))==-1) { return false; } - } - return true; - } -function _getInt(str,i,minlength,maxlength) { - for (var x=maxlength; x>=minlength; x--) { - var token=str.substring(i,i+x); - if (token.length < minlength) { return null; } - if (_isInteger(token)) { return token; } - } - return null; - } - -// ------------------------------------------------------------------ -// getDateFromFormat( date_string , format_string ) -// -// This function takes a date string and a format string. It matches -// If the date string matches the format string, it returns the -// getTime() of the date. If it does not match, it returns 0. -// ------------------------------------------------------------------ -function getDateFromFormat(val,format) { - val=val+""; - format=format+""; - var i_val=0; - var i_format=0; - var c=""; - var token=""; - var token2=""; - var x,y; - var now=new Date(); - var year=now.getYear(); - var month=now.getMonth()+1; - var date=1; - var hh=now.getHours(); - var mm=now.getMinutes(); - var ss=now.getSeconds(); - var ampm=""; - - while (i_format < format.length) { - // Get next token from format string - c=format.charAt(i_format); - token=""; - while ((format.charAt(i_format)==c) && (i_format < format.length)) { - token += format.charAt(i_format++); - } - // Extract contents of value based on format token - if (token=="yyyy" || token=="yy" || token=="y") { - if (token=="yyyy") { x=4;y=4; } - if (token=="yy") { x=2;y=2; } - if (token=="y") { x=2;y=4; } - year=_getInt(val,i_val,x,y); - if (year==null) { return 0; } - i_val += year.length; - if (year.length==2) { - if (year > 70) { year=1900+(year-0); } - else { year=2000+(year-0); } - } - } - else if (token=="MMM"||token=="NNN"){ - month=0; - for (var i=0; i11)) { - month=i+1; - if (month>12) { month -= 12; } - i_val += month_name.length; - break; - } - } - } - if ((month < 1)||(month>12)){return 0;} - } - else if (token=="EE"||token=="E"){ - for (var i=0; i12)){return 0;} - i_val+=month.length;} - else if (token=="dd"||token=="d") { - date=_getInt(val,i_val,token.length,2); - if(date==null||(date<1)||(date>31)){return 0;} - i_val+=date.length;} - else if (token=="hh"||token=="h") { - hh=_getInt(val,i_val,token.length,2); - if(hh==null||(hh<1)||(hh>12)){return 0;} - i_val+=hh.length;} - else if (token=="HH"||token=="H") { - hh=_getInt(val,i_val,token.length,2); - if(hh==null||(hh<0)||(hh>23)){return 0;} - i_val+=hh.length;} - else if (token=="KK"||token=="K") { - hh=_getInt(val,i_val,token.length,2); - if(hh==null||(hh<0)||(hh>11)){return 0;} - i_val+=hh.length;} - else if (token=="kk"||token=="k") { - hh=_getInt(val,i_val,token.length,2); - if(hh==null||(hh<1)||(hh>24)){return 0;} - i_val+=hh.length;hh--;} - else if (token=="mm"||token=="m") { - mm=_getInt(val,i_val,token.length,2); - if(mm==null||(mm<0)||(mm>59)){return 0;} - i_val+=mm.length;} - else if (token=="ss"||token=="s") { - ss=_getInt(val,i_val,token.length,2); - if(ss==null||(ss<0)||(ss>59)){return 0;} - i_val+=ss.length;} - else if (token=="a") { - if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";} - else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";} - else {return 0;} - i_val+=2;} - else { - if (val.substring(i_val,i_val+token.length)!=token) {return 0;} - else {i_val+=token.length;} - } - } - // If there are any trailing characters left in the value, it doesn't match - if (i_val != val.length) { return 0; } - // Is date valid for month? - if (month==2) { - // Check for leap year - if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year - if (date > 29){ return 0; } - } - else { if (date > 28) { return 0; } } - } - if ((month==4)||(month==6)||(month==9)||(month==11)) { - if (date > 30) { return 0; } - } - // Correct hours value - if (hh<12 && ampm=="PM") { hh=hh-0+12; } - else if (hh>11 && ampm=="AM") { hh-=12; } - var newdate=new Date(year,month-1,date,hh,mm,ss); - return newdate.getTime(); - } - -// ------------------------------------------------------------------ -// parseDate( date_string [, prefer_euro_format] ) -// -// This function takes a date string and tries to match it to a -// number of possible date formats to get the value. It will try to -// match against the following international formats, in this order: -// y-M-d MMM d, y MMM d,y y-MMM-d d-MMM-y MMM d -// M/d/y M-d-y M.d.y MMM-d M/d M-d -// d/M/y d-M-y d.M.y d-MMM d/M d-M -// A second argument may be passed to instruct the method to search -// for formats like d/M/y (european format) before M/d/y (American). -// Returns a Date object or null if no patterns match. -// ------------------------------------------------------------------ -function parseDate(val) { - var preferEuro=(arguments.length==2)?arguments[1]:false; - generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d'); - monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d'); - dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M'); - var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst'); - var d=null; - for (var i=0; i tags may cause errors. - -USAGE: -// Create an object for a WINDOW popup -var win = new PopupWindow(); - -// Create an object for a DIV window using the DIV named 'mydiv' -var win = new PopupWindow('mydiv'); - -// Set the window to automatically hide itself when the user clicks -// anywhere else on the page except the popup -win.autoHide(); - -// Show the window relative to the anchor name passed in -win.showPopup(anchorname); - -// Hide the popup -win.hidePopup(); - -// Set the size of the popup window (only applies to WINDOW popups -win.setSize(width,height); - -// Populate the contents of the popup window that will be shown. If you -// change the contents while it is displayed, you will need to refresh() -win.populate(string); - -// set the URL of the window, rather than populating its contents -// manually -win.setUrl("http://www.site.com/"); - -// Refresh the contents of the popup -win.refresh(); - -// Specify how many pixels to the right of the anchor the popup will appear -win.offsetX = 50; - -// Specify how many pixels below the anchor the popup will appear -win.offsetY = 100; - -NOTES: -1) Requires the functions in AnchorPosition.js - -2) Your anchor tag MUST contain both NAME and ID attributes which are the - same. For example: - - -3) There must be at least a space between for IE5.5 to see the - anchor tag correctly. Do not do with no space. - -4) When a PopupWindow object is created, a handler for 'onmouseup' is - attached to any event handler you may have already defined. Do NOT define - an event handler for 'onmouseup' after you define a PopupWindow object or - the autoHide() will not work correctly. -*/ - -// Set the position of the popup window based on the anchor -function PopupWindow_getXYPosition(anchorname) { - var coordinates; - if (this.type == "WINDOW") { - coordinates = getAnchorWindowPosition(anchorname); - } - else { - coordinates = getAnchorPosition(anchorname); - } - this.x = coordinates.x; - this.y = coordinates.y; - } -// Set width/height of DIV/popup window -function PopupWindow_setSize(width,height) { - this.width = width; - this.height = height; - } -// Fill the window with contents -function PopupWindow_populate(contents) { - this.contents = contents; - this.populated = false; - } -// Set the URL to go to -function PopupWindow_setUrl(url) { - this.url = url; - } -// Set the window popup properties -function PopupWindow_setWindowProperties(props) { - this.windowProperties = props; - } -// Refresh the displayed contents of the popup -function PopupWindow_refresh() { - if (this.divName != null) { - // refresh the DIV object - if (this.use_gebi) { - document.getElementById(this.divName).innerHTML = this.contents; - } - else if (this.use_css) { - document.all[this.divName].innerHTML = this.contents; - } - else if (this.use_layers) { - var d = document.layers[this.divName]; - d.document.open(); - d.document.writeln(this.contents); - d.document.close(); - } - } - else { - if (this.popupWindow != null && !this.popupWindow.closed) { - if (this.url!="") { - this.popupWindow.location.href=this.url; - } - else { - this.popupWindow.document.open(); - this.popupWindow.document.writeln(this.contents); - this.popupWindow.document.close(); - } - this.popupWindow.focus(); - } - } - } -// Position and show the popup, relative to an anchor object -function PopupWindow_showPopup(anchorname) { - this.getXYPosition(anchorname); - this.x += this.offsetX; - this.y += this.offsetY; - if (!this.populated && (this.contents != "")) { - this.populated = true; - this.refresh(); - } - if (this.divName != null) { - // Show the DIV object - if (this.use_gebi) { - document.getElementById(this.divName).style.left = this.x + "px"; - document.getElementById(this.divName).style.top = this.y + "px"; - document.getElementById(this.divName).style.visibility = "visible"; - } - else if (this.use_css) { - document.all[this.divName].style.left = this.x; - document.all[this.divName].style.top = this.y; - document.all[this.divName].style.visibility = "visible"; - } - else if (this.use_layers) { - document.layers[this.divName].left = this.x; - document.layers[this.divName].top = this.y; - document.layers[this.divName].visibility = "visible"; - } - } - else { - if (this.popupWindow == null || this.popupWindow.closed) { - // If the popup window will go off-screen, move it so it doesn't - if (this.x<0) { this.x=0; } - if (this.y<0) { this.y=0; } - if (screen && screen.availHeight) { - if ((this.y + this.height) > screen.availHeight) { - this.y = screen.availHeight - this.height; - } - } - if (screen && screen.availWidth) { - if ((this.x + this.width) > screen.availWidth) { - this.x = screen.availWidth - this.width; - } - } - var avoidAboutBlank = window.opera || ( document.layers && !navigator.mimeTypes['*'] ) || navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled ); - this.popupWindow = window.open(avoidAboutBlank?"":"about:blank","window_"+anchorname,this.windowProperties+",width="+this.width+",height="+this.height+",screenX="+this.x+",left="+this.x+",screenY="+this.y+",top="+this.y+""); - } - this.refresh(); - } - } -// Hide the popup -function PopupWindow_hidePopup() { - if (this.divName != null) { - if (this.use_gebi) { - document.getElementById(this.divName).style.visibility = "hidden"; - } - else if (this.use_css) { - document.all[this.divName].style.visibility = "hidden"; - } - else if (this.use_layers) { - document.layers[this.divName].visibility = "hidden"; - } - } - else { - if (this.popupWindow && !this.popupWindow.closed) { - this.popupWindow.close(); - this.popupWindow = null; - } - } - } -// Pass an event and return whether or not it was the popup DIV that was clicked -function PopupWindow_isClicked(e) { - if (this.divName != null) { - if (this.use_layers) { - var clickX = e.pageX; - var clickY = e.pageY; - var t = document.layers[this.divName]; - if ((clickX > t.left) && (clickX < t.left+t.clip.width) && (clickY > t.top) && (clickY < t.top+t.clip.height)) { - return true; - } - else { return false; } - } - else if (document.all) { // Need to hard-code this to trap IE for error-handling - var t = window.event.srcElement; - while (t.parentElement != null) { - if (t.id==this.divName) { - return true; - } - t = t.parentElement; - } - return false; - } - else if (this.use_gebi && e) { - var t = e.originalTarget; - while (t.parentNode != null) { - if (t.id==this.divName) { - return true; - } - t = t.parentNode; - } - return false; - } - return false; - } - return false; - } - -// Check an onMouseDown event to see if we should hide -function PopupWindow_hideIfNotClicked(e) { - if (this.autoHideEnabled && !this.isClicked(e)) { - this.hidePopup(); - } - } -// Call this to make the DIV disable automatically when mouse is clicked outside it -function PopupWindow_autoHide() { - this.autoHideEnabled = true; - } -// This global function checks all PopupWindow objects onmouseup to see if they should be hidden -function PopupWindow_hidePopupWindows(e) { - for (var i=0; i0) { - this.type="DIV"; - this.divName = arguments[0]; - } - else { - this.type="WINDOW"; - } - this.use_gebi = false; - this.use_css = false; - this.use_layers = false; - if (document.getElementById) { this.use_gebi = true; } - else if (document.all) { this.use_css = true; } - else if (document.layers) { this.use_layers = true; } - else { this.type = "WINDOW"; } - this.offsetX = 0; - this.offsetY = 0; - // Method mappings - this.getXYPosition = PopupWindow_getXYPosition; - this.populate = PopupWindow_populate; - this.setUrl = PopupWindow_setUrl; - this.setWindowProperties = PopupWindow_setWindowProperties; - this.refresh = PopupWindow_refresh; - this.showPopup = PopupWindow_showPopup; - this.hidePopup = PopupWindow_hidePopup; - this.setSize = PopupWindow_setSize; - this.isClicked = PopupWindow_isClicked; - this.autoHide = PopupWindow_autoHide; - this.hideIfNotClicked = PopupWindow_hideIfNotClicked; - } - -/* SOURCE FILE: CalendarPopup.js */ - -// HISTORY -// ------------------------------------------------------------------ -// Feb 7, 2005: Fixed a CSS styles to use px unit -// March 29, 2004: Added check in select() method for the form field -// being disabled. If it is, just return and don't do anything. -// March 24, 2004: Fixed bug - when month name and abbreviations were -// changed, date format still used original values. -// January 26, 2004: Added support for drop-down month and year -// navigation (Thanks to Chris Reid for the idea) -// September 22, 2003: Fixed a minor problem in YEAR calendar with -// CSS prefix. -// August 19, 2003: Renamed the function to get styles, and made it -// work correctly without an object reference -// August 18, 2003: Changed showYearNavigation and -// showYearNavigationInput to optionally take an argument of -// true or false -// July 31, 2003: Added text input option for year navigation. -// Added a per-calendar CSS prefix option to optionally use -// different styles for different calendars. -// July 29, 2003: Fixed bug causing the Today link to be clickable -// even though today falls in a disabled date range. -// Changed formatting to use pure CSS, allowing greater control -// over look-and-feel options. -// June 11, 2003: Fixed bug causing the Today link to be unselectable -// under certain cases when some days of week are disabled -// March 14, 2003: Added ability to disable individual dates or date -// ranges, display as light gray and strike-through -// March 14, 2003: Removed dependency on graypixel.gif and instead -/// use table border coloring -// March 12, 2003: Modified showCalendar() function to allow optional -// start-date parameter -// March 11, 2003: Modified select() function to allow optional -// start-date parameter -/* -DESCRIPTION: This object implements a popup calendar to allow the user to -select a date, month, quarter, or year. - -COMPATABILITY: Works with Netscape 4.x, 6.x, IE 5.x on Windows. Some small -positioning errors - usually with Window positioning - occur on the -Macintosh platform. -The calendar can be modified to work for any location in the world by -changing which weekday is displayed as the first column, changing the month -names, and changing the column headers for each day. - -USAGE: -// Create a new CalendarPopup object of type WINDOW -var cal = new CalendarPopup(); - -// Create a new CalendarPopup object of type DIV using the DIV named 'mydiv' -var cal = new CalendarPopup('mydiv'); - -// Easy method to link the popup calendar with an input box. -cal.select(inputObject, anchorname, dateFormat); -// Same method, but passing a default date other than the field's current value -cal.select(inputObject, anchorname, dateFormat, '01/02/2000'); -// This is an example call to the popup calendar from a link to populate an -// input box. Note that to use this, date.js must also be included!! -Select - -// Set the type of date select to be used. By default it is 'date'. -cal.setDisplayType(type); - -// When a date, month, quarter, or year is clicked, a function is called and -// passed the details. You must write this function, and tell the calendar -// popup what the function name is. -// Function to be called for 'date' select receives y, m, d -cal.setReturnFunction(functionname); -// Function to be called for 'month' select receives y, m -cal.setReturnMonthFunction(functionname); -// Function to be called for 'quarter' select receives y, q -cal.setReturnQuarterFunction(functionname); -// Function to be called for 'year' select receives y -cal.setReturnYearFunction(functionname); - -// Show the calendar relative to a given anchor -cal.showCalendar(anchorname); - -// Hide the calendar. The calendar is set to autoHide automatically -cal.hideCalendar(); - -// Set the month names to be used. Default are English month names -cal.setMonthNames("January","February","March",...); - -// Set the month abbreviations to be used. Default are English month abbreviations -cal.setMonthAbbreviations("Jan","Feb","Mar",...); - -// Show navigation for changing by the year, not just one month at a time -cal.showYearNavigation(); - -// Show month and year dropdowns, for quicker selection of month of dates -cal.showNavigationDropdowns(); - -// Set the text to be used above each day column. The days start with -// sunday regardless of the value of WeekStartDay -cal.setDayHeaders("S","M","T",...); - -// Set the day for the first column in the calendar grid. By default this -// is Sunday (0) but it may be changed to fit the conventions of other -// countries. -cal.setWeekStartDay(1); // week is Monday - Sunday - -// Set the weekdays which should be disabled in the 'date' select popup. You can -// then allow someone to only select week end dates, or Tuedays, for example -cal.setDisabledWeekDays(0,1); // To disable selecting the 1st or 2nd days of the week - -// Selectively disable individual days or date ranges. Disabled days will not -// be clickable, and show as strike-through text on current browsers. -// Date format is any format recognized by parseDate() in date.js -// Pass a single date to disable: -cal.addDisabledDates("2003-01-01"); -// Pass null as the first parameter to mean "anything up to and including" the -// passed date: -cal.addDisabledDates(null, "01/02/03"); -// Pass null as the second parameter to mean "including the passed date and -// anything after it: -cal.addDisabledDates("Jan 01, 2003", null); -// Pass two dates to disable all dates inbetween and including the two -cal.addDisabledDates("January 01, 2003", "Dec 31, 2003"); - -// When the 'year' select is displayed, set the number of years back from the -// current year to start listing years. Default is 2. -// This is also used for year drop-down, to decide how many years +/- to display -cal.setYearSelectStartOffset(2); - -// Text for the word "Today" appearing on the calendar -cal.setTodayText("Today"); - -// The calendar uses CSS classes for formatting. If you want your calendar to -// have unique styles, you can set the prefix that will be added to all the -// classes in the output. -// For example, normal output may have this: -// Today -// But if you set the prefix like this: -cal.setCssPrefix("Test"); -// The output will then look like: -// Today -// And you can define that style somewhere in your page. - -// When using Year navigation, you can make the year be an input box, so -// the user can manually change it and jump to any year -cal.showYearNavigationInput(); - -// Set the calendar offset to be different than the default. By default it -// will appear just below and to the right of the anchorname. So if you have -// a text box where the date will go and and anchor immediately after the -// text box, the calendar will display immediately under the text box. -cal.offsetX = 20; -cal.offsetY = 20; - -NOTES: -1) Requires the functions in AnchorPosition.js and PopupWindow.js - -2) Your anchor tag MUST contain both NAME and ID attributes which are the - same. For example: - - -3) There must be at least a space between for IE5.5 to see the - anchor tag correctly. Do not do with no space. - -4) When a CalendarPopup object is created, a handler for 'onmouseup' is - attached to any event handler you may have already defined. Do NOT define - an event handler for 'onmouseup' after you define a CalendarPopup object - or the autoHide() will not work correctly. - -5) The calendar popup display uses style sheets to make it look nice. - -*/ - -// CONSTRUCTOR for the CalendarPopup Object -function CalendarPopup() { - var c; - if (arguments.length>0) { - c = new PopupWindow(arguments[0]); - } - else { - c = new PopupWindow(); - c.setSize(150,175); - } - c.offsetX = -152; - c.offsetY = 25; - c.autoHide(); - // Calendar-specific properties - c.monthNames = new Array("January","February","March","April","May","June","July","August","September","October","November","December"); - c.monthAbbreviations = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"); - c.dayHeaders = new Array("S","M","T","W","T","F","S"); - c.returnFunction = "CP_tmpReturnFunction"; - c.returnMonthFunction = "CP_tmpReturnMonthFunction"; - c.returnQuarterFunction = "CP_tmpReturnQuarterFunction"; - c.returnYearFunction = "CP_tmpReturnYearFunction"; - c.weekStartDay = 0; - c.isShowYearNavigation = false; - c.displayType = "date"; - c.disabledWeekDays = new Object(); - c.disabledDatesExpression = ""; - c.yearSelectStartOffset = 2; - c.currentDate = null; - c.todayText="Today"; - c.cssPrefix=""; - c.isShowNavigationDropdowns=false; - c.isShowYearNavigationInput=false; - window.CP_calendarObject = null; - window.CP_targetInput = null; - window.CP_dateFormat = "MM/dd/yyyy"; - // Method mappings - c.copyMonthNamesToWindow = CP_copyMonthNamesToWindow; - c.setReturnFunction = CP_setReturnFunction; - c.setReturnMonthFunction = CP_setReturnMonthFunction; - c.setReturnQuarterFunction = CP_setReturnQuarterFunction; - c.setReturnYearFunction = CP_setReturnYearFunction; - c.setMonthNames = CP_setMonthNames; - c.setMonthAbbreviations = CP_setMonthAbbreviations; - c.setDayHeaders = CP_setDayHeaders; - c.setWeekStartDay = CP_setWeekStartDay; - c.setDisplayType = CP_setDisplayType; - c.setDisabledWeekDays = CP_setDisabledWeekDays; - c.addDisabledDates = CP_addDisabledDates; - c.setYearSelectStartOffset = CP_setYearSelectStartOffset; - c.setTodayText = CP_setTodayText; - c.showYearNavigation = CP_showYearNavigation; - c.showCalendar = CP_showCalendar; - c.hideCalendar = CP_hideCalendar; - c.getStyles = getCalendarStyles; - c.refreshCalendar = CP_refreshCalendar; - c.getCalendar = CP_getCalendar; - c.select = CP_select; - c.setCssPrefix = CP_setCssPrefix; - c.showNavigationDropdowns = CP_showNavigationDropdowns; - c.showYearNavigationInput = CP_showYearNavigationInput; - c.copyMonthNamesToWindow(); - // Return the object - return c; - } -function CP_copyMonthNamesToWindow() { - // Copy these values over to the date.js - if (typeof(window.MONTH_NAMES)!="undefined" && window.MONTH_NAMES!=null) { - window.MONTH_NAMES = new Array(); - for (var i=0; i\n"; - result += '
\n'; - } - else { - result += '
\n'; - result += '
\n'; - result += '
\n'; - } - // Code for DATE display (default) - // ------------------------------- - if (this.displayType=="date" || this.displayType=="week-end") { - if (this.currentDate==null) { this.currentDate = now; } - if (arguments.length > 0) { var month = arguments[0]; } - else { var month = this.currentDate.getMonth()+1; } - if (arguments.length > 1 && arguments[1]>0 && arguments[1]-0==arguments[1]) { var year = arguments[1]; } - else { var year = this.currentDate.getFullYear(); } - var daysinmonth= new Array(0,31,28,31,30,31,30,31,31,30,31,30,31); - if ( ( (year%4 == 0)&&(year%100 != 0) ) || (year%400 == 0) ) { - daysinmonth[2] = 29; - } - var current_month = new Date(year,month-1,1); - var display_year = year; - var display_month = month; - var display_date = 1; - var weekday= current_month.getDay(); - var offset = 0; - - offset = (weekday >= this.weekStartDay) ? weekday-this.weekStartDay : 7-this.weekStartDay+weekday ; - if (offset > 0) { - display_month--; - if (display_month < 1) { display_month = 12; display_year--; } - display_date = daysinmonth[display_month]-offset+1; - } - var next_month = month+1; - var next_month_year = year; - if (next_month > 12) { next_month=1; next_month_year++; } - var last_month = month-1; - var last_month_year = year; - if (last_month < 1) { last_month=12; last_month_year--; } - var date_class; - if (this.type!="WINDOW") { - result += ""; - } - result += '\n'; - var refresh = windowref+'CP_refreshCalendar'; - var refreshLink = 'javascript:' + refresh; - if (this.isShowNavigationDropdowns) { - result += ''; - result += ''; - - result += ''; - } - else { - if (this.isShowYearNavigation) { - result += ''; - result += ''; - result += ''; - result += ''; - - result += ''; - if (this.isShowYearNavigationInput) { - result += ''; - } - else { - result += ''; - } - result += ''; - } - else { - result += '\n'; - result += '\n'; - result += '\n'; - } - } - result += '
 <'+this.monthNames[month-1]+'> <'+year+'><<'+this.monthNames[month-1]+' '+year+'>>
\n'; - result += '\n'; - result += '\n'; - for (var j=0; j<7; j++) { - - result += '\n'; - } - result += '\n'; - for (var row=1; row<=6; row++) { - result += '\n'; - for (var col=1; col<=7; col++) { - var disabled=false; - if (this.disabledDatesExpression!="") { - var ds=""+display_year+LZ(display_month)+LZ(display_date); - eval("disabled=("+this.disabledDatesExpression+")"); - } - var dateClass = ""; - if ((display_month == this.currentDate.getMonth()+1) && (display_date==this.currentDate.getDate()) && (display_year==this.currentDate.getFullYear())) { - dateClass = "cpCurrentDate"; - } - else if (display_month == month) { - dateClass = "cpCurrentMonthDate"; - } - else { - dateClass = "cpOtherMonthDate"; - } - if (disabled || this.disabledWeekDays[col-1]) { - result += ' \n'; - } - else { - var selected_date = display_date; - var selected_month = display_month; - var selected_year = display_year; - if (this.displayType=="week-end") { - var d = new Date(selected_year,selected_month-1,selected_date,0,0,0,0); - d.setDate(d.getDate() + (7-col)); - selected_year = d.getYear(); - if (selected_year < 1000) { selected_year += 1900; } - selected_month = d.getMonth()+1; - selected_date = d.getDate(); - } - result += ' \n'; - } - display_date++; - if (display_date > daysinmonth[display_month]) { - display_date=1; - display_month++; - } - if (display_month > 12) { - display_month=1; - display_year++; - } - } - result += ''; - } - var current_weekday = now.getDay() - this.weekStartDay; - if (current_weekday < 0) { - current_weekday += 7; - } - result += '\n'; - result += '
'+this.dayHeaders[(this.weekStartDay+j)%7]+'
'+display_date+''+display_date+'
\n'; - if (this.disabledDatesExpression!="") { - var ds=""+now.getFullYear()+LZ(now.getMonth()+1)+LZ(now.getDate()); - eval("disabled=("+this.disabledDatesExpression+")"); - } - if (disabled || this.disabledWeekDays[current_weekday+1]) { - result += ' '+this.todayText+'\n'; - } - else { - result += ' '+this.todayText+'\n'; - } - result += '
\n'; - result += '
\n'; - } - - // Code common for MONTH, QUARTER, YEAR - // ------------------------------------ - if (this.displayType=="month" || this.displayType=="quarter" || this.displayType=="year") { - if (arguments.length > 0) { var year = arguments[0]; } - else { - if (this.displayType=="year") { var year = now.getFullYear()-this.yearSelectStartOffset; } - else { var year = now.getFullYear(); } - } - if (this.displayType!="year" && this.isShowYearNavigation) { - result += ""; - result += '\n'; - result += ' \n'; - result += ' \n'; - result += ' \n'; - result += '
<<'+year+'>>
\n'; - } - } - - // Code for MONTH display - // ---------------------- - if (this.displayType=="month") { - // If POPUP, write entire HTML document - result += '\n'; - for (var i=0; i<4; i++) { - result += ''; - for (var j=0; j<3; j++) { - var monthindex = ((i*3)+j); - result += ''; - } - result += ''; - } - result += '
'+this.monthAbbreviations[monthindex]+'
\n'; - } - - // Code for QUARTER display - // ------------------------ - if (this.displayType=="quarter") { - result += '
\n'; - for (var i=0; i<2; i++) { - result += ''; - for (var j=0; j<2; j++) { - var quarter = ((i*2)+j+1); - result += ''; - } - result += ''; - } - result += '

Q'+quarter+'

\n'; - } - - // Code for YEAR display - // --------------------- - if (this.displayType=="year") { - var yearColumnSize = 4; - result += ""; - result += '\n'; - result += ' \n'; - result += ' \n'; - result += '
<<>>
\n'; - result += '\n'; - for (var i=0; i'+currentyear+''; - } - result += ''; - } - result += '
\n'; - } - // Common - if (this.type == "WINDOW") { - result += "\n"; - } - return result; - } +// =================================================================== +// Author: Matt Kruse +// WWW: http://www.mattkruse.com/ +// +// NOTICE: You may use this code for any purpose, commercial or +// private, without any further permission from the author. You may +// remove this notice from your final code if you wish, however it is +// appreciated by the author if at least my web site address is kept. +// +// You may *NOT* re-distribute this code in any way except through its +// use. That means, you can include it in your product, or your web +// site, or any other form where the code is actually being used. You +// may not put the plain javascript up on your site for download or +// include it in your javascript libraries for download. +// If you wish to share this code with others, please just point them +// to the URL instead. +// Please DO NOT link directly to my .js files from your site. Copy +// the files to your server and use them there. Thank you. +// =================================================================== + + +/* SOURCE FILE: AnchorPosition.js */ + +/* +AnchorPosition.js +Author: Matt Kruse +Last modified: 10/11/02 + +DESCRIPTION: These functions find the position of an tag in a document, +so other elements can be positioned relative to it. + +COMPATABILITY: Netscape 4.x,6.x,Mozilla, IE 5.x,6.x on Windows. Some small +positioning errors - usually with Window positioning - occur on the +Macintosh platform. + +FUNCTIONS: +getAnchorPosition(anchorname) + Returns an Object() having .x and .y properties of the pixel coordinates + of the upper-left corner of the anchor. Position is relative to the PAGE. + +getAnchorWindowPosition(anchorname) + Returns an Object() having .x and .y properties of the pixel coordinates + of the upper-left corner of the anchor, relative to the WHOLE SCREEN. + +NOTES: + +1) For popping up separate browser windows, use getAnchorWindowPosition. + Otherwise, use getAnchorPosition + +2) Your anchor tag MUST contain both NAME and ID attributes which are the + same. For example: + + +3) There must be at least a space between for IE5.5 to see the + anchor tag correctly. Do not do with no space. +*/ + +// getAnchorPosition(anchorname) +// This function returns an object having .x and .y properties which are the coordinates +// of the named anchor, relative to the page. +function getAnchorPosition(anchorname) { + // This function will return an Object with x and y properties + var useWindow=false; + var coordinates=new Object(); + var x=0,y=0; + // Browser capability sniffing + var use_gebi=false, use_css=false, use_layers=false; + if (document.getElementById) { use_gebi=true; } + else if (document.all) { use_css=true; } + else if (document.layers) { use_layers=true; } + // Logic to find position + if (use_gebi && document.all) { + x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]); + y=AnchorPosition_getPageOffsetTop(document.all[anchorname]); + } + else if (use_gebi) { + var o=document.getElementById(anchorname); + x=AnchorPosition_getPageOffsetLeft(o); + y=AnchorPosition_getPageOffsetTop(o); + } + else if (use_css) { + x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]); + y=AnchorPosition_getPageOffsetTop(document.all[anchorname]); + } + else if (use_layers) { + var found=0; + for (var i=0; i9?"":"0")+x} + +// ------------------------------------------------------------------ +// isDate ( date_string, format_string ) +// Returns true if date string matches format of format string and +// is a valid date. Else returns false. +// It is recommended that you trim whitespace around the value before +// passing it to this function, as whitespace is NOT ignored! +// ------------------------------------------------------------------ +function isDate(val,format) { + var date=getDateFromFormat(val,format); + if (date==0) { return false; } + return true; + } + +// ------------------------------------------------------------------- +// compareDates(date1,date1format,date2,date2format) +// Compare two date strings to see which is greater. +// Returns: +// 1 if date1 is greater than date2 +// 0 if date2 is greater than date1 of if they are the same +// -1 if either of the dates is in an invalid format +// ------------------------------------------------------------------- +function compareDates(date1,dateformat1,date2,dateformat2) { + var d1=getDateFromFormat(date1,dateformat1); + var d2=getDateFromFormat(date2,dateformat2); + if (d1==0 || d2==0) { + return -1; + } + else if (d1 > d2) { + return 1; + } + return 0; + } + +// ------------------------------------------------------------------ +// formatDate (date_object, format) +// Returns a date in the output format specified. +// The format string uses the same abbreviations as in getDateFromFormat() +// ------------------------------------------------------------------ +function formatDate(date,format) { + format=format+""; + var result=""; + var i_format=0; + var c=""; + var token=""; + var y=date.getYear()+""; + var M=date.getMonth()+1; + var d=date.getDate(); + var E=date.getDay(); + var H=date.getHours(); + var m=date.getMinutes(); + var s=date.getSeconds(); + var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k; + // Convert real date parts into formatted versions + var value=new Object(); + if (y.length < 4) {y=""+(y-0+1900);} + value["y"]=""+y; + value["yyyy"]=y; + value["yy"]=y.substring(2,4); + value["M"]=M; + value["MM"]=LZ(M); + value["MMM"]=MONTH_NAMES[M-1]; + value["NNN"]=MONTH_NAMES[M+11]; + value["d"]=d; + value["dd"]=LZ(d); + value["E"]=DAY_NAMES[E+7]; + value["EE"]=DAY_NAMES[E]; + value["H"]=H; + value["HH"]=LZ(H); + if (H==0){value["h"]=12;} + else if (H>12){value["h"]=H-12;} + else {value["h"]=H;} + value["hh"]=LZ(value["h"]); + if (H>11){value["K"]=H-12;} else {value["K"]=H;} + value["k"]=H+1; + value["KK"]=LZ(value["K"]); + value["kk"]=LZ(value["k"]); + if (H > 11) { value["a"]="PM"; } + else { value["a"]="AM"; } + value["m"]=m; + value["mm"]=LZ(m); + value["s"]=s; + value["ss"]=LZ(s); + while (i_format < format.length) { + c=format.charAt(i_format); + token=""; + while ((format.charAt(i_format)==c) && (i_format < format.length)) { + token += format.charAt(i_format++); + } + if (value[token] != null) { result=result + value[token]; } + else { result=result + token; } + } + return result; + } + +// ------------------------------------------------------------------ +// Utility functions for parsing in getDateFromFormat() +// ------------------------------------------------------------------ +function _isInteger(val) { + var digits="1234567890"; + for (var i=0; i < val.length; i++) { + if (digits.indexOf(val.charAt(i))==-1) { return false; } + } + return true; + } +function _getInt(str,i,minlength,maxlength) { + for (var x=maxlength; x>=minlength; x--) { + var token=str.substring(i,i+x); + if (token.length < minlength) { return null; } + if (_isInteger(token)) { return token; } + } + return null; + } + +// ------------------------------------------------------------------ +// getDateFromFormat( date_string , format_string ) +// +// This function takes a date string and a format string. It matches +// If the date string matches the format string, it returns the +// getTime() of the date. If it does not match, it returns 0. +// ------------------------------------------------------------------ +function getDateFromFormat(val,format) { + val=val+""; + format=format+""; + var i_val=0; + var i_format=0; + var c=""; + var token=""; + var token2=""; + var x,y; + var now=new Date(); + var year=now.getYear(); + var month=now.getMonth()+1; + var date=1; + var hh=now.getHours(); + var mm=now.getMinutes(); + var ss=now.getSeconds(); + var ampm=""; + + while (i_format < format.length) { + // Get next token from format string + c=format.charAt(i_format); + token=""; + while ((format.charAt(i_format)==c) && (i_format < format.length)) { + token += format.charAt(i_format++); + } + // Extract contents of value based on format token + if (token=="yyyy" || token=="yy" || token=="y") { + if (token=="yyyy") { x=4;y=4; } + if (token=="yy") { x=2;y=2; } + if (token=="y") { x=2;y=4; } + year=_getInt(val,i_val,x,y); + if (year==null) { return 0; } + i_val += year.length; + if (year.length==2) { + if (year > 70) { year=1900+(year-0); } + else { year=2000+(year-0); } + } + } + else if (token=="MMM"||token=="NNN"){ + month=0; + for (var i=0; i11)) { + month=i+1; + if (month>12) { month -= 12; } + i_val += month_name.length; + break; + } + } + } + if ((month < 1)||(month>12)){return 0;} + } + else if (token=="EE"||token=="E"){ + for (var i=0; i12)){return 0;} + i_val+=month.length;} + else if (token=="dd"||token=="d") { + date=_getInt(val,i_val,token.length,2); + if(date==null||(date<1)||(date>31)){return 0;} + i_val+=date.length;} + else if (token=="hh"||token=="h") { + hh=_getInt(val,i_val,token.length,2); + if(hh==null||(hh<1)||(hh>12)){return 0;} + i_val+=hh.length;} + else if (token=="HH"||token=="H") { + hh=_getInt(val,i_val,token.length,2); + if(hh==null||(hh<0)||(hh>23)){return 0;} + i_val+=hh.length;} + else if (token=="KK"||token=="K") { + hh=_getInt(val,i_val,token.length,2); + if(hh==null||(hh<0)||(hh>11)){return 0;} + i_val+=hh.length;} + else if (token=="kk"||token=="k") { + hh=_getInt(val,i_val,token.length,2); + if(hh==null||(hh<1)||(hh>24)){return 0;} + i_val+=hh.length;hh--;} + else if (token=="mm"||token=="m") { + mm=_getInt(val,i_val,token.length,2); + if(mm==null||(mm<0)||(mm>59)){return 0;} + i_val+=mm.length;} + else if (token=="ss"||token=="s") { + ss=_getInt(val,i_val,token.length,2); + if(ss==null||(ss<0)||(ss>59)){return 0;} + i_val+=ss.length;} + else if (token=="a") { + if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";} + else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";} + else {return 0;} + i_val+=2;} + else { + if (val.substring(i_val,i_val+token.length)!=token) {return 0;} + else {i_val+=token.length;} + } + } + // If there are any trailing characters left in the value, it doesn't match + if (i_val != val.length) { return 0; } + // Is date valid for month? + if (month==2) { + // Check for leap year + if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year + if (date > 29){ return 0; } + } + else { if (date > 28) { return 0; } } + } + if ((month==4)||(month==6)||(month==9)||(month==11)) { + if (date > 30) { return 0; } + } + // Correct hours value + if (hh<12 && ampm=="PM") { hh=hh-0+12; } + else if (hh>11 && ampm=="AM") { hh-=12; } + var newdate=new Date(year,month-1,date,hh,mm,ss); + return newdate.getTime(); + } + +// ------------------------------------------------------------------ +// parseDate( date_string [, prefer_euro_format] ) +// +// This function takes a date string and tries to match it to a +// number of possible date formats to get the value. It will try to +// match against the following international formats, in this order: +// y-M-d MMM d, y MMM d,y y-MMM-d d-MMM-y MMM d +// M/d/y M-d-y M.d.y MMM-d M/d M-d +// d/M/y d-M-y d.M.y d-MMM d/M d-M +// A second argument may be passed to instruct the method to search +// for formats like d/M/y (european format) before M/d/y (American). +// Returns a Date object or null if no patterns match. +// ------------------------------------------------------------------ +function parseDate(val) { + var preferEuro=(arguments.length==2)?arguments[1]:false; + generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d'); + monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d'); + dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M'); + var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst'); + var d=null; + for (var i=0; i tags may cause errors. + +USAGE: +// Create an object for a WINDOW popup +var win = new PopupWindow(); + +// Create an object for a DIV window using the DIV named 'mydiv' +var win = new PopupWindow('mydiv'); + +// Set the window to automatically hide itself when the user clicks +// anywhere else on the page except the popup +win.autoHide(); + +// Show the window relative to the anchor name passed in +win.showPopup(anchorname); + +// Hide the popup +win.hidePopup(); + +// Set the size of the popup window (only applies to WINDOW popups +win.setSize(width,height); + +// Populate the contents of the popup window that will be shown. If you +// change the contents while it is displayed, you will need to refresh() +win.populate(string); + +// set the URL of the window, rather than populating its contents +// manually +win.setUrl("http://www.site.com/"); + +// Refresh the contents of the popup +win.refresh(); + +// Specify how many pixels to the right of the anchor the popup will appear +win.offsetX = 50; + +// Specify how many pixels below the anchor the popup will appear +win.offsetY = 100; + +NOTES: +1) Requires the functions in AnchorPosition.js + +2) Your anchor tag MUST contain both NAME and ID attributes which are the + same. For example: + + +3) There must be at least a space between for IE5.5 to see the + anchor tag correctly. Do not do with no space. + +4) When a PopupWindow object is created, a handler for 'onmouseup' is + attached to any event handler you may have already defined. Do NOT define + an event handler for 'onmouseup' after you define a PopupWindow object or + the autoHide() will not work correctly. +*/ + +// Set the position of the popup window based on the anchor +function PopupWindow_getXYPosition(anchorname) { + var coordinates; + if (this.type == "WINDOW") { + coordinates = getAnchorWindowPosition(anchorname); + } + else { + coordinates = getAnchorPosition(anchorname); + } + this.x = coordinates.x; + this.y = coordinates.y; + } +// Set width/height of DIV/popup window +function PopupWindow_setSize(width,height) { + this.width = width; + this.height = height; + } +// Fill the window with contents +function PopupWindow_populate(contents) { + this.contents = contents; + this.populated = false; + } +// Set the URL to go to +function PopupWindow_setUrl(url) { + this.url = url; + } +// Set the window popup properties +function PopupWindow_setWindowProperties(props) { + this.windowProperties = props; + } +// Refresh the displayed contents of the popup +function PopupWindow_refresh() { + if (this.divName != null) { + // refresh the DIV object + if (this.use_gebi) { + document.getElementById(this.divName).innerHTML = this.contents; + } + else if (this.use_css) { + document.all[this.divName].innerHTML = this.contents; + } + else if (this.use_layers) { + var d = document.layers[this.divName]; + d.document.open(); + d.document.writeln(this.contents); + d.document.close(); + } + } + else { + if (this.popupWindow != null && !this.popupWindow.closed) { + if (this.url!="") { + this.popupWindow.location.href=this.url; + } + else { + this.popupWindow.document.open(); + this.popupWindow.document.writeln(this.contents); + this.popupWindow.document.close(); + } + this.popupWindow.focus(); + } + } + } +// Position and show the popup, relative to an anchor object +function PopupWindow_showPopup(anchorname) { + this.getXYPosition(anchorname); + this.x += this.offsetX; + this.y += this.offsetY; + if (!this.populated && (this.contents != "")) { + this.populated = true; + this.refresh(); + } + if (this.divName != null) { + // Show the DIV object + if (this.use_gebi) { + document.getElementById(this.divName).style.left = this.x + "px"; + document.getElementById(this.divName).style.top = this.y + "px"; + document.getElementById(this.divName).style.visibility = "visible"; + } + else if (this.use_css) { + document.all[this.divName].style.left = this.x; + document.all[this.divName].style.top = this.y; + document.all[this.divName].style.visibility = "visible"; + } + else if (this.use_layers) { + document.layers[this.divName].left = this.x; + document.layers[this.divName].top = this.y; + document.layers[this.divName].visibility = "visible"; + } + } + else { + if (this.popupWindow == null || this.popupWindow.closed) { + // If the popup window will go off-screen, move it so it doesn't + if (this.x<0) { this.x=0; } + if (this.y<0) { this.y=0; } + if (screen && screen.availHeight) { + if ((this.y + this.height) > screen.availHeight) { + this.y = screen.availHeight - this.height; + } + } + if (screen && screen.availWidth) { + if ((this.x + this.width) > screen.availWidth) { + this.x = screen.availWidth - this.width; + } + } + var avoidAboutBlank = window.opera || ( document.layers && !navigator.mimeTypes['*'] ) || navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled ); + this.popupWindow = window.open(avoidAboutBlank?"":"about:blank","window_"+anchorname,this.windowProperties+",width="+this.width+",height="+this.height+",screenX="+this.x+",left="+this.x+",screenY="+this.y+",top="+this.y+""); + } + this.refresh(); + } + } +// Hide the popup +function PopupWindow_hidePopup() { + if (this.divName != null) { + if (this.use_gebi) { + document.getElementById(this.divName).style.visibility = "hidden"; + } + else if (this.use_css) { + document.all[this.divName].style.visibility = "hidden"; + } + else if (this.use_layers) { + document.layers[this.divName].visibility = "hidden"; + } + } + else { + if (this.popupWindow && !this.popupWindow.closed) { + this.popupWindow.close(); + this.popupWindow = null; + } + } + } +// Pass an event and return whether or not it was the popup DIV that was clicked +function PopupWindow_isClicked(e) { + if (this.divName != null) { + if (this.use_layers) { + var clickX = e.pageX; + var clickY = e.pageY; + var t = document.layers[this.divName]; + if ((clickX > t.left) && (clickX < t.left+t.clip.width) && (clickY > t.top) && (clickY < t.top+t.clip.height)) { + return true; + } + else { return false; } + } + else if (document.all) { // Need to hard-code this to trap IE for error-handling + var t = window.event.srcElement; + while (t.parentElement != null) { + if (t.id==this.divName) { + return true; + } + t = t.parentElement; + } + return false; + } + else if (this.use_gebi && e) { + var t = e.originalTarget; + while (t.parentNode != null) { + if (t.id==this.divName) { + return true; + } + t = t.parentNode; + } + return false; + } + return false; + } + return false; + } + +// Check an onMouseDown event to see if we should hide +function PopupWindow_hideIfNotClicked(e) { + if (this.autoHideEnabled && !this.isClicked(e)) { + this.hidePopup(); + } + } +// Call this to make the DIV disable automatically when mouse is clicked outside it +function PopupWindow_autoHide() { + this.autoHideEnabled = true; + } +// This global function checks all PopupWindow objects onmouseup to see if they should be hidden +function PopupWindow_hidePopupWindows(e) { + for (var i=0; i0) { + this.type="DIV"; + this.divName = arguments[0]; + } + else { + this.type="WINDOW"; + } + this.use_gebi = false; + this.use_css = false; + this.use_layers = false; + if (document.getElementById) { this.use_gebi = true; } + else if (document.all) { this.use_css = true; } + else if (document.layers) { this.use_layers = true; } + else { this.type = "WINDOW"; } + this.offsetX = 0; + this.offsetY = 0; + // Method mappings + this.getXYPosition = PopupWindow_getXYPosition; + this.populate = PopupWindow_populate; + this.setUrl = PopupWindow_setUrl; + this.setWindowProperties = PopupWindow_setWindowProperties; + this.refresh = PopupWindow_refresh; + this.showPopup = PopupWindow_showPopup; + this.hidePopup = PopupWindow_hidePopup; + this.setSize = PopupWindow_setSize; + this.isClicked = PopupWindow_isClicked; + this.autoHide = PopupWindow_autoHide; + this.hideIfNotClicked = PopupWindow_hideIfNotClicked; + } + +/* SOURCE FILE: CalendarPopup.js */ + +// HISTORY +// ------------------------------------------------------------------ +// Feb 7, 2005: Fixed a CSS styles to use px unit +// March 29, 2004: Added check in select() method for the form field +// being disabled. If it is, just return and don't do anything. +// March 24, 2004: Fixed bug - when month name and abbreviations were +// changed, date format still used original values. +// January 26, 2004: Added support for drop-down month and year +// navigation (Thanks to Chris Reid for the idea) +// September 22, 2003: Fixed a minor problem in YEAR calendar with +// CSS prefix. +// August 19, 2003: Renamed the function to get styles, and made it +// work correctly without an object reference +// August 18, 2003: Changed showYearNavigation and +// showYearNavigationInput to optionally take an argument of +// true or false +// July 31, 2003: Added text input option for year navigation. +// Added a per-calendar CSS prefix option to optionally use +// different styles for different calendars. +// July 29, 2003: Fixed bug causing the Today link to be clickable +// even though today falls in a disabled date range. +// Changed formatting to use pure CSS, allowing greater control +// over look-and-feel options. +// June 11, 2003: Fixed bug causing the Today link to be unselectable +// under certain cases when some days of week are disabled +// March 14, 2003: Added ability to disable individual dates or date +// ranges, display as light gray and strike-through +// March 14, 2003: Removed dependency on graypixel.gif and instead +/// use table border coloring +// March 12, 2003: Modified showCalendar() function to allow optional +// start-date parameter +// March 11, 2003: Modified select() function to allow optional +// start-date parameter +/* +DESCRIPTION: This object implements a popup calendar to allow the user to +select a date, month, quarter, or year. + +COMPATABILITY: Works with Netscape 4.x, 6.x, IE 5.x on Windows. Some small +positioning errors - usually with Window positioning - occur on the +Macintosh platform. +The calendar can be modified to work for any location in the world by +changing which weekday is displayed as the first column, changing the month +names, and changing the column headers for each day. + +USAGE: +// Create a new CalendarPopup object of type WINDOW +var cal = new CalendarPopup(); + +// Create a new CalendarPopup object of type DIV using the DIV named 'mydiv' +var cal = new CalendarPopup('mydiv'); + +// Easy method to link the popup calendar with an input box. +cal.select(inputObject, anchorname, dateFormat); +// Same method, but passing a default date other than the field's current value +cal.select(inputObject, anchorname, dateFormat, '01/02/2000'); +// This is an example call to the popup calendar from a link to populate an +// input box. Note that to use this, date.js must also be included!! +Select + +// Set the type of date select to be used. By default it is 'date'. +cal.setDisplayType(type); + +// When a date, month, quarter, or year is clicked, a function is called and +// passed the details. You must write this function, and tell the calendar +// popup what the function name is. +// Function to be called for 'date' select receives y, m, d +cal.setReturnFunction(functionname); +// Function to be called for 'month' select receives y, m +cal.setReturnMonthFunction(functionname); +// Function to be called for 'quarter' select receives y, q +cal.setReturnQuarterFunction(functionname); +// Function to be called for 'year' select receives y +cal.setReturnYearFunction(functionname); + +// Show the calendar relative to a given anchor +cal.showCalendar(anchorname); + +// Hide the calendar. The calendar is set to autoHide automatically +cal.hideCalendar(); + +// Set the month names to be used. Default are English month names +cal.setMonthNames("January","February","March",...); + +// Set the month abbreviations to be used. Default are English month abbreviations +cal.setMonthAbbreviations("Jan","Feb","Mar",...); + +// Show navigation for changing by the year, not just one month at a time +cal.showYearNavigation(); + +// Show month and year dropdowns, for quicker selection of month of dates +cal.showNavigationDropdowns(); + +// Set the text to be used above each day column. The days start with +// sunday regardless of the value of WeekStartDay +cal.setDayHeaders("S","M","T",...); + +// Set the day for the first column in the calendar grid. By default this +// is Sunday (0) but it may be changed to fit the conventions of other +// countries. +cal.setWeekStartDay(1); // week is Monday - Sunday + +// Set the weekdays which should be disabled in the 'date' select popup. You can +// then allow someone to only select week end dates, or Tuedays, for example +cal.setDisabledWeekDays(0,1); // To disable selecting the 1st or 2nd days of the week + +// Selectively disable individual days or date ranges. Disabled days will not +// be clickable, and show as strike-through text on current browsers. +// Date format is any format recognized by parseDate() in date.js +// Pass a single date to disable: +cal.addDisabledDates("2003-01-01"); +// Pass null as the first parameter to mean "anything up to and including" the +// passed date: +cal.addDisabledDates(null, "01/02/03"); +// Pass null as the second parameter to mean "including the passed date and +// anything after it: +cal.addDisabledDates("Jan 01, 2003", null); +// Pass two dates to disable all dates inbetween and including the two +cal.addDisabledDates("January 01, 2003", "Dec 31, 2003"); + +// When the 'year' select is displayed, set the number of years back from the +// current year to start listing years. Default is 2. +// This is also used for year drop-down, to decide how many years +/- to display +cal.setYearSelectStartOffset(2); + +// Text for the word "Today" appearing on the calendar +cal.setTodayText("Today"); + +// The calendar uses CSS classes for formatting. If you want your calendar to +// have unique styles, you can set the prefix that will be added to all the +// classes in the output. +// For example, normal output may have this: +// Today +// But if you set the prefix like this: +cal.setCssPrefix("Test"); +// The output will then look like: +// Today +// And you can define that style somewhere in your page. + +// When using Year navigation, you can make the year be an input box, so +// the user can manually change it and jump to any year +cal.showYearNavigationInput(); + +// Set the calendar offset to be different than the default. By default it +// will appear just below and to the right of the anchorname. So if you have +// a text box where the date will go and and anchor immediately after the +// text box, the calendar will display immediately under the text box. +cal.offsetX = 20; +cal.offsetY = 20; + +NOTES: +1) Requires the functions in AnchorPosition.js and PopupWindow.js + +2) Your anchor tag MUST contain both NAME and ID attributes which are the + same. For example: + + +3) There must be at least a space between for IE5.5 to see the + anchor tag correctly. Do not do with no space. + +4) When a CalendarPopup object is created, a handler for 'onmouseup' is + attached to any event handler you may have already defined. Do NOT define + an event handler for 'onmouseup' after you define a CalendarPopup object + or the autoHide() will not work correctly. + +5) The calendar popup display uses style sheets to make it look nice. + +*/ + +// CONSTRUCTOR for the CalendarPopup Object +function CalendarPopup() { + var c; + if (arguments.length>0) { + c = new PopupWindow(arguments[0]); + } + else { + c = new PopupWindow(); + c.setSize(150,175); + } + c.offsetX = -152; + c.offsetY = 25; + c.autoHide(); + // Calendar-specific properties + c.monthNames = new Array("January","February","March","April","May","June","July","August","September","October","November","December"); + c.monthAbbreviations = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"); + c.dayHeaders = new Array("S","M","T","W","T","F","S"); + c.returnFunction = "CP_tmpReturnFunction"; + c.returnMonthFunction = "CP_tmpReturnMonthFunction"; + c.returnQuarterFunction = "CP_tmpReturnQuarterFunction"; + c.returnYearFunction = "CP_tmpReturnYearFunction"; + c.weekStartDay = 0; + c.isShowYearNavigation = false; + c.displayType = "date"; + c.disabledWeekDays = new Object(); + c.disabledDatesExpression = ""; + c.yearSelectStartOffset = 2; + c.currentDate = null; + c.todayText="Today"; + c.cssPrefix=""; + c.isShowNavigationDropdowns=false; + c.isShowYearNavigationInput=false; + window.CP_calendarObject = null; + window.CP_targetInput = null; + window.CP_dateFormat = "MM/dd/yyyy"; + // Method mappings + c.copyMonthNamesToWindow = CP_copyMonthNamesToWindow; + c.setReturnFunction = CP_setReturnFunction; + c.setReturnMonthFunction = CP_setReturnMonthFunction; + c.setReturnQuarterFunction = CP_setReturnQuarterFunction; + c.setReturnYearFunction = CP_setReturnYearFunction; + c.setMonthNames = CP_setMonthNames; + c.setMonthAbbreviations = CP_setMonthAbbreviations; + c.setDayHeaders = CP_setDayHeaders; + c.setWeekStartDay = CP_setWeekStartDay; + c.setDisplayType = CP_setDisplayType; + c.setDisabledWeekDays = CP_setDisabledWeekDays; + c.addDisabledDates = CP_addDisabledDates; + c.setYearSelectStartOffset = CP_setYearSelectStartOffset; + c.setTodayText = CP_setTodayText; + c.showYearNavigation = CP_showYearNavigation; + c.showCalendar = CP_showCalendar; + c.hideCalendar = CP_hideCalendar; + c.getStyles = getCalendarStyles; + c.refreshCalendar = CP_refreshCalendar; + c.getCalendar = CP_getCalendar; + c.select = CP_select; + c.setCssPrefix = CP_setCssPrefix; + c.showNavigationDropdowns = CP_showNavigationDropdowns; + c.showYearNavigationInput = CP_showYearNavigationInput; + c.copyMonthNamesToWindow(); + // Return the object + return c; + } +function CP_copyMonthNamesToWindow() { + // Copy these values over to the date.js + if (typeof(window.MONTH_NAMES)!="undefined" && window.MONTH_NAMES!=null) { + window.MONTH_NAMES = new Array(); + for (var i=0; i\n"; + result += '
\n'; + } + else { + result += '
\n'; + result += '
\n'; + result += '
\n'; + } + // Code for DATE display (default) + // ------------------------------- + if (this.displayType=="date" || this.displayType=="week-end") { + if (this.currentDate==null) { this.currentDate = now; } + if (arguments.length > 0) { var month = arguments[0]; } + else { var month = this.currentDate.getMonth()+1; } + if (arguments.length > 1 && arguments[1]>0 && arguments[1]-0==arguments[1]) { var year = arguments[1]; } + else { var year = this.currentDate.getFullYear(); } + var daysinmonth= new Array(0,31,28,31,30,31,30,31,31,30,31,30,31); + if ( ( (year%4 == 0)&&(year%100 != 0) ) || (year%400 == 0) ) { + daysinmonth[2] = 29; + } + var current_month = new Date(year,month-1,1); + var display_year = year; + var display_month = month; + var display_date = 1; + var weekday= current_month.getDay(); + var offset = 0; + + offset = (weekday >= this.weekStartDay) ? weekday-this.weekStartDay : 7-this.weekStartDay+weekday ; + if (offset > 0) { + display_month--; + if (display_month < 1) { display_month = 12; display_year--; } + display_date = daysinmonth[display_month]-offset+1; + } + var next_month = month+1; + var next_month_year = year; + if (next_month > 12) { next_month=1; next_month_year++; } + var last_month = month-1; + var last_month_year = year; + if (last_month < 1) { last_month=12; last_month_year--; } + var date_class; + if (this.type!="WINDOW") { + result += ""; + } + result += '\n'; + var refresh = windowref+'CP_refreshCalendar'; + var refreshLink = 'javascript:' + refresh; + if (this.isShowNavigationDropdowns) { + result += ''; + result += ''; + + result += ''; + } + else { + if (this.isShowYearNavigation) { + result += ''; + result += ''; + result += ''; + result += ''; + + result += ''; + if (this.isShowYearNavigationInput) { + result += ''; + } + else { + result += ''; + } + result += ''; + } + else { + result += '\n'; + result += '\n'; + result += '\n'; + } + } + result += '
 <'+this.monthNames[month-1]+'> <'+year+'><<'+this.monthNames[month-1]+' '+year+'>>
\n'; + result += '\n'; + result += '\n'; + for (var j=0; j<7; j++) { + + result += '\n'; + } + result += '\n'; + for (var row=1; row<=6; row++) { + result += '\n'; + for (var col=1; col<=7; col++) { + var disabled=false; + if (this.disabledDatesExpression!="") { + var ds=""+display_year+LZ(display_month)+LZ(display_date); + eval("disabled=("+this.disabledDatesExpression+")"); + } + var dateClass = ""; + if ((display_month == this.currentDate.getMonth()+1) && (display_date==this.currentDate.getDate()) && (display_year==this.currentDate.getFullYear())) { + dateClass = "cpCurrentDate"; + } + else if (display_month == month) { + dateClass = "cpCurrentMonthDate"; + } + else { + dateClass = "cpOtherMonthDate"; + } + if (disabled || this.disabledWeekDays[col-1]) { + result += ' \n'; + } + else { + var selected_date = display_date; + var selected_month = display_month; + var selected_year = display_year; + if (this.displayType=="week-end") { + var d = new Date(selected_year,selected_month-1,selected_date,0,0,0,0); + d.setDate(d.getDate() + (7-col)); + selected_year = d.getYear(); + if (selected_year < 1000) { selected_year += 1900; } + selected_month = d.getMonth()+1; + selected_date = d.getDate(); + } + result += ' \n'; + } + display_date++; + if (display_date > daysinmonth[display_month]) { + display_date=1; + display_month++; + } + if (display_month > 12) { + display_month=1; + display_year++; + } + } + result += ''; + } + var current_weekday = now.getDay() - this.weekStartDay; + if (current_weekday < 0) { + current_weekday += 7; + } + result += '\n'; + result += '
'+this.dayHeaders[(this.weekStartDay+j)%7]+'
'+display_date+''+display_date+'
\n'; + if (this.disabledDatesExpression!="") { + var ds=""+now.getFullYear()+LZ(now.getMonth()+1)+LZ(now.getDate()); + eval("disabled=("+this.disabledDatesExpression+")"); + } + if (disabled || this.disabledWeekDays[current_weekday+1]) { + result += ' '+this.todayText+'\n'; + } + else { + result += ' '+this.todayText+'\n'; + } + result += '
\n'; + result += '
\n'; + } + + // Code common for MONTH, QUARTER, YEAR + // ------------------------------------ + if (this.displayType=="month" || this.displayType=="quarter" || this.displayType=="year") { + if (arguments.length > 0) { var year = arguments[0]; } + else { + if (this.displayType=="year") { var year = now.getFullYear()-this.yearSelectStartOffset; } + else { var year = now.getFullYear(); } + } + if (this.displayType!="year" && this.isShowYearNavigation) { + result += ""; + result += '\n'; + result += ' \n'; + result += ' \n'; + result += ' \n'; + result += '
<<'+year+'>>
\n'; + } + } + + // Code for MONTH display + // ---------------------- + if (this.displayType=="month") { + // If POPUP, write entire HTML document + result += '\n'; + for (var i=0; i<4; i++) { + result += ''; + for (var j=0; j<3; j++) { + var monthindex = ((i*3)+j); + result += ''; + } + result += ''; + } + result += '
'+this.monthAbbreviations[monthindex]+'
\n'; + } + + // Code for QUARTER display + // ------------------------ + if (this.displayType=="quarter") { + result += '
\n'; + for (var i=0; i<2; i++) { + result += ''; + for (var j=0; j<2; j++) { + var quarter = ((i*2)+j+1); + result += ''; + } + result += ''; + } + result += '

Q'+quarter+'

\n'; + } + + // Code for YEAR display + // --------------------- + if (this.displayType=="year") { + var yearColumnSize = 4; + result += ""; + result += '\n'; + result += ' \n'; + result += ' \n'; + result += '
<<>>
\n'; + result += '\n'; + for (var i=0; i'+currentyear+''; + } + result += ''; + } + result += '
\n'; + } + // Common + if (this.type == "WINDOW") { + result += "\n"; + } + return result; + } diff --git a/vendors/jquery/jquery.form.js b/vendors/jquery/jquery.form.js index f46ff55d0..c027f19c0 100644 --- a/vendors/jquery/jquery.form.js +++ b/vendors/jquery/jquery.form.js @@ -1,643 +1,643 @@ -/* - * jQuery Form Plugin - * version: 2.28 (10-MAY-2009) - * @requires jQuery v1.2.2 or later - * - * Examples and documentation at: http://malsup.com/jquery/form/ - * Dual licensed under the MIT and GPL licenses: - * http://www.opensource.org/licenses/mit-license.php - * http://www.gnu.org/licenses/gpl.html - */ -;(function($) { - -/* - Usage Note: - ----------- - Do not use both ajaxSubmit and ajaxForm on the same form. These - functions are intended to be exclusive. Use ajaxSubmit if you want - to bind your own submit handler to the form. For example, - - $(document).ready(function() { - $('#myForm').bind('submit', function() { - $(this).ajaxSubmit({ - target: '#output' - }); - return false; // <-- important! - }); - }); - - Use ajaxForm when you want the plugin to manage all the event binding - for you. For example, - - $(document).ready(function() { - $('#myForm').ajaxForm({ - target: '#output' - }); - }); - - When using ajaxForm, the ajaxSubmit function will be invoked for you - at the appropriate time. -*/ - -/** - * ajaxSubmit() provides a mechanism for immediately submitting - * an HTML form using AJAX. - */ -$.fn.ajaxSubmit = function(options) { - // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) - if (!this.length) { - log('ajaxSubmit: skipping submit process - no element selected'); - return this; - } - - if (typeof options == 'function') - options = { success: options }; - - var url = $.trim(this.attr('action')); - if (url) { - // clean url (don't include hash vaue) - url = (url.match(/^([^#]+)/)||[])[1]; - } - url = url || window.location.href || '' - - options = $.extend({ - url: url, - type: this.attr('method') || 'GET' - }, options || {}); - - // hook for manipulating the form data before it is extracted; - // convenient for use with rich editors like tinyMCE or FCKEditor - var veto = {}; - this.trigger('form-pre-serialize', [this, options, veto]); - if (veto.veto) { - log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); - return this; - } - - // provide opportunity to alter form data before it is serialized - if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { - log('ajaxSubmit: submit aborted via beforeSerialize callback'); - return this; - } - - var a = this.formToArray(options.semantic); - if (options.data) { - options.extraData = options.data; - for (var n in options.data) { - if(options.data[n] instanceof Array) { - for (var k in options.data[n]) - a.push( { name: n, value: options.data[n][k] } ); - } - else - a.push( { name: n, value: options.data[n] } ); - } - } - - // give pre-submit callback an opportunity to abort the submit - if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { - log('ajaxSubmit: submit aborted via beforeSubmit callback'); - return this; - } - - // fire vetoable 'validate' event - this.trigger('form-submit-validate', [a, this, options, veto]); - if (veto.veto) { - log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); - return this; - } - - var q = $.param(a); - - if (options.type.toUpperCase() == 'GET') { - options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; - options.data = null; // data is null for 'get' - } - else - options.data = q; // data is the query string for 'post' - - var $form = this, callbacks = []; - if (options.resetForm) callbacks.push(function() { $form.resetForm(); }); - if (options.clearForm) callbacks.push(function() { $form.clearForm(); }); - - // perform a load on the target only if dataType is not provided - if (!options.dataType && options.target) { - var oldSuccess = options.success || function(){}; - callbacks.push(function(data) { - $(options.target).html(data).each(oldSuccess, arguments); - }); - } - else if (options.success) - callbacks.push(options.success); - - options.success = function(data, status) { - for (var i=0, max=callbacks.length; i < max; i++) - callbacks[i].apply(options, [data, status, $form]); - }; - - // are there files to upload? - var files = $('input:file', this).fieldValue(); - var found = false; - for (var j=0; j < files.length; j++) - if (files[j]) - found = true; - - var multipart = false; -// var mp = 'multipart/form-data'; -// multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); - - // options.iframe allows user to force iframe mode - if (options.iframe || found || multipart) { - // hack to fix Safari hang (thanks to Tim Molendijk for this) - // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d - if (options.closeKeepAlive) - $.get(options.closeKeepAlive, fileUpload); - else - fileUpload(); - } - else - $.ajax(options); - - // fire 'notify' event - this.trigger('form-submit-notify', [this, options]); - return this; - - - // private function for handling file uploads (hat tip to YAHOO!) - function fileUpload() { - var form = $form[0]; - - if ($(':input[name=submit]', form).length) { - alert('Error: Form elements must not be named "submit".'); - return; - } - - var opts = $.extend({}, $.ajaxSettings, options); - var s = $.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts); - - var id = 'jqFormIO' + (new Date().getTime()); - var $io = $('