diff --git a/application/configs/application.ini b/application/configs/application.ini index 3400a0bc4..95835d341 100644 --- a/application/configs/application.ini +++ b/application/configs/application.ini @@ -1,446 +1,477 @@ [production] version = "v1.94" ;phpSettings.date.timezone = "UTC" phpSettings.display_startup_errors = 0 phpSettings.display_errors = 0 resources.frontController.params.displayExceptions = 0 includePaths.library = APPLICATION_PATH "/../library" autoloaderNamespaces[] = "Local_" autoloaderNamespaces[] = "Ppload_" autoloaderNamespaces[] = "Crontab_" autoloaderNamespaces[] = "Cgsmith" bootstrap.path = APPLICATION_PATH "/modules/default/Bootstrap.php" bootstrap.class = "Bootstrap" resources.frontController.moduleDirectory = APPLICATION_PATH "/modules" resources.frontController.defaultModule = "default" resources.frontController.baseurl = "/" resources.modules[] = resources.layout.layout = "flat_ui_template" resources.layout.layoutPath = APPLICATION_PATH "/modules/default/views/layout" resources.view[] = resources.view.encoding = "UTF-8" resources.view.doctype = "XHTML5" resources.view.contentType = "text/html;charset=utf-8" resources.locale.default = "en_US" resources.locale.force = false resources.locale.registry_key = "Zend_Locale" resources.db.adapter = "pdo_mysql" resources.db.params.host = "host" resources.db.params.username = "uname" resources.db.params.password = "pass" resources.db.params.dbname = "dbname" resources.db.params.charset = "utf8" resources.db.params.type = "pdo_mysql" resources.db.params.driver_options.1002 = "SET NAMES utf8" resources.db.isDefaultTableAdapter = true resources.mail.transport.type = Zend_Mail_Transport_Smtp resources.mail.transport.host = "email-host" resources.mail.transport.port = 587 resources.mail.transport.auth = "login" resources.mail.transport.username = "uname" resources.mail.transport.password = "pass" resources.mail.transport.ssl = "tls" resources.mail.defaultFrom.email = from@ocs-webserver.org resources.mail.defaultFrom.name = "ocs-webserver.org" resources.mail.defaultReplyTo.email = contact@ocs-webserver.org resources.mail.defaultReplyTo.name = "ocs-webserver.org" resources.translate.registry_key = "Zend_Translate" resources.translate.adapter = array resources.translate.options.scan = "directory" resources.translate.locale = "en_US" resources.translate.data.de_DE = APPLICATION_DATA "/locales/de_DE.php" resources.translate.data.en_US = APPLICATION_DATA "/locales/en_US.php" resources.translate.data.zh_CN = APPLICATION_DATA "/locales/zh_CN.php" resources.log.stream.writerName = "Stream" resources.log.stream.writerParams.stream = APPLICATION_PATH "/../data/logs/application.log" resources.log.stream.writerParams.mode = "a" ;resources.log.stream.filterName = "Priority" ;resources.log.stream.filterParams.priority = 8 queue.validate.name = "website_validate" queue.validate.dbAdapter = "Local_Queue_Adapter_Db" queue.validate.messageAdapter = "Local_Queue_Adapter_Db_Message" queue.validate.maxMessages = 1 images.upload.path = APPLICATION_PATH "/../httpdocs/img/data/" images.media.server = "http://cn.any_server.org" images.media.upload = "http://cn.any_server.org/any_path" videos.upload.path = APPLICATION_PATH "/../httpdocs/video/data/" videos.media.server = "http://video.any_server.org" videos.media.upload = "http://video.any_server.org/any_path" videos.media.cdnserver = "http://cdn.any_server.org/" torrent.media.server = "http://torrent.any_server.org" torrent.media.createurl = "http://torrent.any_server.org/any_path" torrent.media.deleteurl = "http://torrent.any_server.org/any_path" torrent.media.downloadurl = "http://torrent.any_server.org/any_path" torrent.media.min_filesize = 104857600 comics.media.server = "http://comic.any_server.org" comics.media.extracturl = "http://comic.any_server.org/any_path" comics.media.tocurl = "http://comic.any_server.org/any_path" comics.media.pageurl = "http://comic.any_server.org/any_path" third_party.paypal.sandbox.active = 0 third_party.paypal.security.userid = "ppuid" third_party.paypal.security.password = "pppass" third_party.paypal.security.signature = "ppsig" third_party.paypal.facilitator_fee_receiver = "receiver@mail.com" third_party.paypal.facilitator_fee = 0 third_party.paypal.application.id = "APP-ID" third_party.paypal.api.endpoint = "https://svcs.paypal.com" third_party.paypal.form.endpoint = "https://ic.paypal.com" third_party.paypal.ipn.endpoint = "https://www.paypal.com" third_party.paypal.masspay.endpoint = "https://api-3t.paypal.com/nvp" third_party.paypal.masspay.ipn.endpoint = "https://ipnpb.paypal.com/cgi-bin" third_party.paypal.service.version = "1.2.0" third_party.paypal.request.data.format = "NV" third_party.paypal.response.data.format = "NV" third_party.paypal.client.auth = "Nocert" third_party.paypal.client.application_id = "app" third_party.paypal.client.partner_name = "partner" third_party.paypal.merchantid = 0 third_party.github.client_id = "" third_party.github.client_secret = "" third_party.github.client_callback = $_SERVER['HTTP_HOST'] "/oauth/github" ; deprecated ;third_party.ocs.client_id = "" ;third_party.ocs.client_secret = "" ;third_party.ocs.client_callback = $_SERVER['HTTP_HOST'] "/oauth/ocs" admin.email = "contact@ocs-webserver.org" website.tracking.chartbeat = "/js/tracking/chartbeat.js" website.tracking.google = "/js/tracking/goggle.js" ; Application settings.cache.path = APPLICATION_CACHE settings.log.path = APPLICATION_DATA "/logs/" settings.search.path = APPLICATION_DATA "/indexes/" +settings.spam_filter.active = true +settings.double_opt_in.active = true +; set it 1 to prevent that the LESS files are processed and dont forget to kill the cache. otherwise 0 to process less files. +settings.noLESScompile = 1 +; in some server environment we don't want to store the page views. In this case set this value to 0. +settings.savePageView = 1 settings.store.template.path = APPLICATION_DATA "/stores/templates/" settings.store.template.default = "default" -phpSettings.session.name = "OcsWebserverId" -phpSettings.session.save_path = APPLICATION_DATA "/sessions" -phpSettings.session.cookie_httponly = true -phpSettings.session.cookie_lifetime = 31536000 -phpSettings.session.gc_maxlifetime = 7776000 +; job queue +settings.queue.general.name = "ocs_jobs" +; timeout in microseconds +settings.queue.general.timeout = 600000 +settings.queue.general.message_count = 1 -settings.spam_filter.active = true -settings.double_opt_in.active = true +; Session config +; -------------- +; deprecated +;phpSettings.session.name = "OcsWebserverId" +;phpSettings.session.save_path = APPLICATION_DATA "/sessions" +;phpSettings.session.cookie_httponly = true +;phpSettings.session.cookie_lifetime = 31536000 +;phpSettings.session.gc_maxlifetime = 7776000 settings.session.remember_me.name = "OcsWebserverRememberMe" settings.session.remember_me.cookie_lifetime = 31536000 settings.session.remember_me.cookie_httponly = true + settings.session.auth.name = "OcsWebserverSession" -settings.session.auth.cookie_lifetime = 31536000 -settings.session.auth.cookie_path = "/" -settings.session.auth.cookie_httponly = true +;deprecated +;settings.session.auth.cookie_lifetime = 31536000 +;settings.session.auth.cookie_path = "/" +;settings.session.auth.cookie_httponly = true + settings.session.filter_browse_original = 'FilterBrowseOriginalSession' settings.session.auth.anonymous = 'user_anonyous' -settings.session.saveHandler.replace.enabled = true -settings.session.saveHandler.cache.type = "Libmemcached" -settings.session.saveHandler.class = "Local_Session_Handler_Memcache" -settings.session.saveHandler.options.servers.0.host = "memcachehost" -settings.session.saveHandler.options.servers.0.port = 11211 -settings.session.saveHandler.options.servers.0.persistent = true -settings.session.saveHandler.options.servers.0.status = true -settings.session.saveHandler.options.compression = true - +; deprecated +;settings.session.saveHandler.replace.enabled = true +;settings.session.saveHandler.cache.type = "Libmemcached" +;settings.session.saveHandler.class = "Local_Session_Handler_Memcache" +;settings.session.saveHandler.options.servers.0.host = "memcachehost" +;settings.session.saveHandler.options.servers.0.port = 11211 +;settings.session.saveHandler.options.servers.0.persistent = true +;settings.session.saveHandler.options.servers.0.status = true +;settings.session.saveHandler.options.compression = true + +; Session config +resources.session.save_path = APPLICATION_DATA "/sessions" +resources.session.name = 'ocs-session' +resources.session.cookie_httponly = true +resources.session.cookie_secure = true +resources.session.cookie_lifetime = 2592000 +resources.session.remember_me_seconds = 31536000 +; comment out all following lines with savehandler to use original php session management +resources.session.saveHandler.class = "Local_Session_Handler_Memcache" +resources.session.saveHandler.options.cache.type = "Libmemcached" +; #ZF-3490 : For the memcached backend, there is a lifetime limit of 30 days (2592000 seconds) +resources.session.saveHandler.options.cache.maxlifetime = 2592000 +resources.session.saveHandler.options.servers.0.host = "memcachehost" +resources.session.saveHandler.options.servers.0.port = 11211 +resources.session.saveHandler.options.servers.0.persistent = true +resources.session.saveHandler.options.servers.0.status = true +resources.session.saveHandler.options.compression = true + +; Application cache settings.cache.enabled = true settings.cache.frontend.type = Core settings.cache.frontend.options.lifetime = 600 settings.cache.frontend.options.automatic_serialization = true settings.cache.frontend.options.cache_id_prefix = "front_" settings.cache.frontend.options.cache = true settings.cache.backend.type = "Libmemcached" settings.cache.backend.options.servers.0.host = "memcachehost" settings.cache.backend.options.servers.0.port = 11211 settings.cache.backend.options.servers.0.persistent = true settings.cache.backend.options.servers.0.weight = 1 settings.cache.backend.options.servers.0.timeout = 5 settings.cache.backend.options.servers.0.retry_interval = 15 ; alternative backend file cache, if no memcache installed (only for development environments) ;settings.cache.backend.type = "File" ;settings.cache.backend.options.cache_dir = APPLICATION_CACHE ;settings.cache.backend.options.file_locking = true ;settings.cache.backend.options.read_control = true ;settings.cache.backend.options.read_control_type = 'crc32' ;settings.cache.backend.options.hashed_directory_level = 1 ;settings.cache.backend.options.hashed_directory_perm = 0700 ;settings.cache.backend.options.file_name_prefix = 'ocs' ;settings.cache.backend.options.cache_file_perm = 0700 +; search settings.search.host = 'localhost' settings.search.port = '8983' settings.search.http_path = '/solr/any_core/' settings.client.default.name = 'default' ; deprecated ;settings.client.config.path = APPLICATION_PATH "/configs/" settings.client.default.baseurl = 'any-host.org' settings.client.default.baseurl_store = 'www.any-host.com' settings.client.default.baseurl_meta = 'any-host.org' settings.client.default.baseurl_member = 'any-host.org' settings.client.default.baseurl_product = 'any-host.org' settings.client.default.baselogo = 'images/system/storeLogo.png' settings.client.default.url_forum = "" settings.client.default.url_blog = "" settings.client.default.url_gitlab = "" settings.client.default.url_myopendesktop = "" settings.client.default.url_cloudopendesktop = "" settings.client.default.url_musicopendesktop = "" settings.client.default.url_docsopendesktop = "" settings.client.default.url_mastodon = "" settings.client.default.url_riot = "" -settings.client.default.riot_access_token="" +settings.client.default.riot_access_token = "" settings.client.default.collection_cat_id = '' settings.client.default.ranking_cat_id = '' settings.client.default.tag_group_collection_type_id = '' settings.client.default.tag_collection_type_collection_id = '' settings.client.default.tag_collection_type_ranking_id = '' settings.client.default.tag_group_original_id = '' settings.client.default.tag_original_id = '' settings.client.default.tag_modification_id = '' ;ebook tag config settings.client.default.tag_group_ebook = '' settings.client.default.tag_group_ebook_author = '' settings.client.default.tag_group_ebook_editor = '' settings.client.default.tag_group_ebook_illustrator = '' settings.client.default.tag_group_ebook_translator = '' settings.client.default.tag_group_ebook_subject = '' settings.client.default.tag_group_ebook_shelf = '' settings.client.default.tag_group_ebook_language = '' settings.client.default.tag_group_ebook_type = '' settings.client.default.tag_is_ebook = '' ;os-user tag config settings.client.default.tag_group_osuser = '' settings.client.default.tag_type_osuser = '' ;dangerous tag config settings.client.default.tag_group_dangerous_id = '' settings.client.default.tag_dangerous_id = '' settings.static.include_path = APPLICATION_PATH "/../httpdocs/partials/" settings.static.include.contact = "contact.phtml" settings.static.include.privacy = "privacy.phtml" settings.static.include.imprint = "imprint.phtml" settings.static.include.terms = "terms.phtml" settings.static.include.terms-general = "terms-general.phtml" settings.static.include.terms-publishing = "terms-publishing.phtml" settings.static.include.terms-payout = "terms-payout.phtml" settings.static.include.terms-dmca = "terms-dmca.phtml" settings.static.include.terms-cookies = "terms-cookies.phtml" settings.static.include.faq = "faq.phtml" settings.static.include.gitfaq = "gitfaq.phtml" settings.static.include.faqold = "faqold.phtml" settings.static.include.about = "about.phtml" settings.static.include.ocsapi = "ocsapi.phtml" -settings.queue.general.name = "ocs_jobs" -; timeout in microseconds -settings.queue.general.timeout = 600000 -settings.queue.general.message_count = 1 - -settings.noLESScompile = 1 ; set it 1 to prevent that the LESS files are processed and dont forget to kill the cache. otherwise 0 to process less files. -settings.savePageView = 1 ; in some server environment we don't want to store the page views. I this case set this value to 0. - settings.dwh.db.adapter = "pdo_mysql" settings.dwh.db.params.host = "host" settings.dwh.db.params.username = "uname" settings.dwh.db.params.password = "pass" settings.dwh.db.params.dbname = "dbname" settings.dwh.db.params.charset = "utf8" settings.dwh.db.params.type = "pdo_mysql" settings.dwh.db.params.driver_options.1002 = "SET NAMES utf8" settings.dwh.db.isDefaultTableAdapter = false ; ppload ; deprecated third_party.ppload.server = "https://www.ocs-fileserver.org" third_party.ppload.api_uri = "https://www.ocs-fileserver.org/api/" third_party.ppload.client_id = "clientid" third_party.ppload.secret = "sec" third_party.ppload.download_secret = "sec" ; new fileserver config settings.server.files.host = "" settings.server.files.download_secret = "" settings.server.files.api.uri = "" settings.server.files.api.client_id = "" -settings.server.files.api.client_secret= "" +settings.server.files.api.client_secret = "" settings.server.oauth.host = "" settings.server.oauth.authorize_url = "" settings.server.oauth.token_url = "" settings.server.oauth.callback = $_SERVER['HTTP_HOST'] "/oauth/ocs" settings.server.oauth.client_id = "" settings.server.oauth.client_secret = "" settings.server.oauth.create_user_url = "" settings.server.oauth.profile_user_url = "" settings.server.opencode.host = "" settings.server.opencode.user_logfilename = "opencode" settings.server.opencode.user_sudo = "" settings.server.opencode.user_agent = "OCS Opendesktop" settings.server.opencode.private_token = "" settings.server.opencode.provider_name = "oauth_opendesktop" settings.server.ldap.host = "" settings.server.ldap.port = "389" settings.server.ldap.username = "" settings.server.ldap.password = "" settings.server.ldap.bindRequiresDn = true settings.server.ldap.accountDomainName = "" settings.server.ldap.baseDn = "" settings.server.ldap.accountFilterFormat = "(objectClass=account)" settings.server.ldap.tryUsernameSplit = false settings.server.ldap_group.baseDn = "" settings.server.ldap_ext.rootDn = "" settings.server.forum.host = "" settings.server.forum.user_logfilename = "forum" settings.server.forum.user_sudo = "" settings.server.forum.user_agent = "" settings.server.forum.private_token = "" settings.server.chat.host = "" settings.server.chat.user_logfilename = "chat" settings.server.chat.sudo_user = "" settings.server.chat.sudo_user_pw = "" settings.server.chat.home_server = "" settings.server.chat.user_agent = "" +settings.server.ip.api.v4 = "" +settings.server.ip.api.v6 = "" + settings.ocs_server.apiUri = "http://ocs-server.org" settings.jwt.secret = "" settings.jwt.expire.accessToken = "2 hours" settings.jwt.expire.refreshToken = "180 days" settings.jwt.expire.cookie = "30 days" settings.jwt.expire.authorizationCode = "10 minutes" settings.jwt.expire.resetCode = "2 hours" settings.jwt.issuer_ident = "http://localhost:80" settings.domain.base.host = "www.example.com" settings.domain.forum.host = "forum.example.com" settings.domain.forum.cookie_name = "_t" settings.domain.openid.host = "id.example.com" settings.domain.openid.cookie_name = "ltat" settings.domain.opencode.host = "git.example.com" settings.domain.opencode.cookie_name = "_example.com_session" settings.domain.mastodon.host = "mastodon.example.com" [development : production] phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1 resources.frontController.params.displayExceptions = 1 resources.db.adapter = "pdo_mysql" resources.db.params.host = "dev-host" resources.db.params.username = "uname" resources.db.params.password = "pass" resources.db.params.dbname = "db" resources.db.params.charset = "utf8" resources.db.isDefaultTableAdapter = true ;resources.db.params.profiler.enabled = "true" ;resources.db.params.profiler.class = "Zend_Db_Profiler_Firebug" third_party.paypal.security.userid = "pp.sandbox.uid" third_party.paypal.security.password = "pppass" third_party.paypal.security.signature = "ppsig" third_party.paypal.sandbox.email = "sanbaox@mail.com" third_party.paypal.facilitator_fee_receiver = "sandbox@mail.com" third_party.paypal.facilitator_fee = 0 third_party.paypal.application.id = "SANDBOX-APP-ID" third_party.paypal.api.endpoint = "https://svcs.sandbox.paypal.com" third_party.paypal.form.endpoint = "https://www.sandbox.paypal.com" third_party.paypal.ipn.endpoint = "https://www.sandbox.paypal.com" [testing : development] [cronjob : production] resources.frontController.moduleDirectory = APPLICATION_PATH "/modules" resources.frontController.defaultControllerName = "cron" resources.frontController.defaultAction = "run" resources.modules[] = resources.frontController.params.displayExceptions = 1 phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1 third_party.paypal.sandbox.active = 0 third_party.paypal.security.userid = "ppuid" third_party.paypal.security.password = "pppass" third_party.paypal.security.signature = "ppsig" third_party.paypal.facilitator_fee_receiver = "receiver@mail.com" third_party.paypal.facilitator_fee = 0 third_party.paypal.application.id = "APP-ID" third_party.paypal.api.endpoint = "https://svcs.paypal.com" third_party.paypal.form.endpoint = "https://ic.paypal.com" third_party.paypal.ipn.endpoint = "https://www.paypal.com" third_party.paypal.masspay.endpoint = "https://api-3t.paypal.com/nvp" third_party.paypal.service.version = "1.2.0" third_party.paypal.request.data.format = "NV" third_party.paypal.response.data.format = "NV" third_party.paypal.client.auth = "Nocert" third_party.paypal.client.application_id = "app" third_party.paypal.client.partner_name = "partner" third_party.paypal.test = Live settings.cache.enabled = true settings.cache.frontend.type = Core settings.cache.frontend.options.lifetime = 600 settings.cache.frontend.options.automatic_serialization = true settings.cache.frontend.options.cache_id_prefix = "cron_" settings.cache.frontend.options.cache = true settings.cache.backend.type = File settings.cache.backend.options.cache_dir = APPLICATION_CACHE settings.cache.backend.options.file_locking = true settings.cache.backend.options.read_control = true settings.cache.backend.options.read_control_type = 'crc32' settings.cache.backend.options.hashed_directory_level = 1 settings.cache.backend.options.hashed_directory_perm = 0700 settings.cache.backend.options.file_name_prefix = 'cron_' settings.cache.backend.options.cache_file_perm = 0700 [searchbotenv : production] resources.frontController.params.displayExceptions = 0 phpSettings.display_startup_errors = 0 phpSettings.display_errors = 0 diff --git a/application/modules/backend/views/scripts/categories/index.phtml b/application/modules/backend/views/scripts/categories/index.phtml index 7defc2cc7..e390ee41a 100644 --- a/application/modules/backend/views/scripts/categories/index.phtml +++ b/application/modules/backend/views/scripts/categories/index.phtml @@ -1,690 +1,530 @@ . **/ ?>
getCurrentMessages() as $message) : ?>

escape($message); ?>

hide deleted records:
-
-

Form fields with * are required.

- -
-
-
Title*
-
- -
-
-
-
XDG-Type
-
- -
-
-
-
Legacy Name
-
- -
-
-
-
Download Factor
-
- -
-
-
-
Mediaview Factor
-
- -
-
-
-
Show Description*
-
- -
-
-
-
Source Required*
-
- -
-
-
-
Status*
-
- -
-
-
-
-
\ No newline at end of file diff --git a/application/modules/default/Bootstrap.php b/application/modules/default/Bootstrap.php index d7af81202..43abb5645 100644 --- a/application/modules/default/Bootstrap.php +++ b/application/modules/default/Bootstrap.php @@ -1,1116 +1,1100 @@ . **/ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { /** * @return Zend_Application_Module_Autoloader * @throws Zend_Loader_Exception */ protected function _initAutoload() { $autoloader = new Zend_Application_Module_Autoloader(array( 'namespace' => 'Default', 'basePath' => realpath(dirname(__FILE__)), )); $autoloader->addResourceType('formelements', 'forms/elements', 'Form_Element'); $autoloader->addResourceType('formvalidators', 'forms/validators', 'Form_Validator'); return $autoloader; } /** * @throws Zend_Exception * @throws Zend_Session_Exception */ protected function _initSessionManagement() { + $session = $this->bootstrap('session'); + Zend_Session::start(); $config = $this->getOption('settings')['session']; - - $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false; - - if ($config['saveHandler']['replace']['enabled']) { - $cacheClass = 'Zend_Cache_Backend_' . $config['saveHandler']['cache']['type']; - $_cache = new $cacheClass($config['saveHandler']['options']); - Zend_Loader::loadClass($config['saveHandler']['class']); - Zend_Session::setSaveHandler(new $config['saveHandler']['class']($_cache)); - Zend_Session::setOptions(array( - 'cookie_domain' => $domain, - 'cookie_path' => $config['auth']['cookie_path'], - 'cookie_lifetime' => $config['auth']['cookie_lifetime'], - 'cookie_httponly' => $config['auth']['cookie_httponly'] - )); - Zend_Session::start(); - } - $session_namespace = new Zend_Session_Namespace($config['auth']['name']); - $session_namespace->setExpirationSeconds($config['auth']['cookie_lifetime']); - Zend_Auth::getInstance()->setStorage(new Zend_Auth_Storage_Session($session_namespace->getNamespace())); } protected function _initConfig() { /** $config Zend_Config */ $config = $this->getApplication()->getApplicationConfig(); Zend_Registry::set('config', $config); return $config; } /** * @return mixed|null|Zend_Cache_Core|Zend_Cache_Frontend * @throws Zend_Cache_Exception * @throws Zend_Exception */ protected function _initCache() { if (Zend_Registry::isRegistered('cache')) { return Zend_Registry::get('cache'); } $cache = null; $options = $this->getOption('settings'); if (true == $options['cache']['enabled']) { $cache = Zend_Cache::factory($options['cache']['frontend']['type'], $options['cache']['backend']['type'], $options['cache']['frontend']['options'], $options['cache']['backend']['options']); } else { // Fallback settings for some (maybe development) environments which have no cache management installed. if (false === is_writeable(APPLICATION_CACHE)) { error_log('directory for cache files does not exists or not writable: ' . APPLICATION_CACHE); throw new Zend_Application_Bootstrap_Exception('directory for cache files does not exists or not writable: ' . APPLICATION_CACHE); } $frontendOptions = array( 'lifetime' => 600, 'automatic_serialization' => true, 'cache_id_prefix' => $options['cache']['frontend']['options']['cache_id_prefix'], 'cache' => true ); $backendOptions = array( 'cache_dir' => APPLICATION_CACHE, 'file_locking' => true, 'read_control' => true, 'read_control_type' => 'crc32', 'hashed_directory_level' => 1, 'hashed_directory_perm' => 0700, 'file_name_prefix' => $options['cache']['frontend']['options']['cache_id_prefix'], 'cache_file_perm' => 0700 ); $cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions); } Zend_Registry::set('cache', $cache); Zend_Locale::setCache($cache); Zend_Locale_Data::setCache($cache); Zend_Currency::setCache($cache); Zend_Translate::setCache($cache); Zend_Translate_Adapter::setCache($cache); Zend_Db_Table_Abstract::setDefaultMetadataCache($cache); Zend_Paginator::setCache($cache); return $cache; } /** * @throws Zend_Application_Bootstrap_Exception */ protected function _initViewConfig() { $view = $this->bootstrap('view')->getResource('view'); $view->addHelperPath(APPLICATION_PATH . '/modules/default/views/helpers', 'Default_View_Helper_'); $view->addHelperPath(APPLICATION_LIB . '/Zend/View/Helper', 'Zend_View_Helper_'); $options = $this->getOptions(); $docType = $options['resources']['view']['doctype'] ? $options['resources']['view']['doctype'] : 'XHTML1_TRANSITIONAL'; $view->doctype($docType); } /** * @throws Zend_Locale_Exception */ protected function _initLocale() { $configResources = $this->getOption('resources'); Zend_Locale::setDefault($configResources['locale']['default']); Zend_Registry::set($configResources['locale']['registry_key'], $configResources['locale']['default']); } /** * @return Zend_Translate * @throws Zend_Application_Resource_Exception * @throws Zend_Form_Exception * @throws Zend_Session_Exception * @throws Zend_Translate_Exception * @throws Zend_Validate_Exception */ protected function _initTranslate() { $options = $this->getOption('resources'); $options = $options['translate']; if (!isset($options['data'])) { throw new Zend_Application_Resource_Exception('not found the file'); } $adapter = isset($options['adapter']) ? $options['adapter'] : Zend_Translate::AN_ARRAY; $session = new Zend_Session_Namespace('aa'); if ($session->locale) { $locale = $session->locale; } else { $locale = isset($options['locale']) ? $options['locale'] : null; } $data = ''; if (isset($options['data'][$locale])) { $data = $options['data'][$locale]; } $translateOptions = isset($options['options']) ? $options['options'] : array(); $translate = new Zend_Translate($adapter, $data, $locale, $translateOptions); Zend_Form::setDefaultTranslator($translate); Zend_Validate_Abstract::setDefaultTranslator($translate); Zend_Registry::set('Zend_Translate', $translate); return $translate; } /** * @throws Zend_Application_Bootstrap_Exception */ protected function _initDbAdapter() { $db = $this->bootstrap('db')->getResource('db'); Zend_Registry::set('db', $db); Zend_Db_Table::setDefaultAdapter($db); Zend_Db_Table_Abstract::setDefaultAdapter($db); } /** * @throws Zend_Application_Bootstrap_Exception */ protected function _initLogger() { /** @var Zend_Log $logger */ $logger = $this->getPluginResource('log')->getLog(); $logger->registerErrorHandler(); Zend_Registry::set('logger', $logger); } protected function _initGlobals() { Zend_Paginator::setDefaultScrollingStyle('Elastic'); Zend_View_Helper_PaginationControl::setDefaultViewPartial('paginationControl.phtml'); Zend_Filter::addDefaultNamespaces('Local_Filter'); $version = $this->getOption('version'); defined('APPLICATION_VERSION') || define('APPLICATION_VERSION', $version); } /** * @return Default_Plugin_AclRules|false|mixed * @throws Zend_Cache_Exception */ protected function _initAclRules() { /** @var Zend_Cache_Core $appCache */ $appCache = $this->getResource('cache'); if (false == ($aclRules = $appCache->load('AclRules'))) { $aclRules = new Default_Plugin_AclRules(); Zend_Registry::set('acl', $aclRules); $appCache->save($aclRules, 'AclRules', array('AclRules'), 14400); } return $aclRules; } /** * @throws Zend_Application_Bootstrap_Exception * @throws Zend_Loader_PluginLoader_Exception */ protected function _initPlugins() { /** @var $front Zend_Controller_Front */ $front = $this->bootstrap('frontController')->getResource('frontController'); $aclRules = $this->bootstrap('aclRules')->getResource('aclRules'); $front->unregisterPlugin('Zend_Controller_Plugin_ErrorHandler'); $front->registerPlugin(new Default_Plugin_ErrorHandler()); + $front->registerPlugin(new Default_Plugin_Stats()); $front->registerPlugin(new Default_Plugin_RememberMe(Zend_Auth::getInstance())); $front->registerPlugin(new Default_Plugin_SignOn(Zend_Auth::getInstance())); $front->registerPlugin(new Default_Plugin_Acl(Zend_Auth::getInstance(), $aclRules)); $loader = new Zend_Loader_PluginLoader(); $loader->addPrefixPath('Zend_View_Helper', APPLICATION_LIB . '/Zend/View/Helper/') ->addPrefixPath('Zend_Form_Element', APPLICATION_LIB . '/Zend/Form/Element') ->addPrefixPath('Default_View_Helper', APPLICATION_PATH . '/modules/default/views/helpers') ->addPrefixPath('Default_Form_Helper', APPLICATION_PATH . '/modules/default/forms/helpers') ->addPrefixPath('Default_Form_Element', APPLICATION_PATH . '/modules/default/forms/elements') ->addPrefixPath('Default_Form_Decorator', APPLICATION_PATH . '/modules/default/forms/decorators') ->addPrefixPath('Default_Form_Validator', APPLICATION_PATH . '/modules/default/forms/validators'); } protected function _initThirdParty() { $appConfig = $this->getResource('config'); $imageConfig = $appConfig->images; defined('IMAGES_UPLOAD_PATH') || define('IMAGES_UPLOAD_PATH', $imageConfig->upload->path); defined('IMAGES_MEDIA_SERVER') || define('IMAGES_MEDIA_SERVER', $imageConfig->media->server); $videoConfig = $appConfig->videos; defined('VIDEOS_UPLOAD_PATH') || define('VIDEOS_UPLOAD_PATH', $videoConfig->upload->path); defined('VIDEOS_MEDIA_SERVER') || define('VIDEOS_MEDIA_SERVER', $videoConfig->media->server); $comicConfig = $appConfig->comics; defined('COMICS_MEDIA_SERVER') || define('COMICS_MEDIA_SERVER', $comicConfig->media->server); // fileserver $configFileserver = $appConfig->settings->server->files; defined('PPLOAD_API_URI') || define('PPLOAD_API_URI', $configFileserver->api->uri); defined('PPLOAD_CLIENT_ID') || define('PPLOAD_CLIENT_ID', $configFileserver->api->client_id); defined('PPLOAD_SECRET') || define('PPLOAD_SECRET', $configFileserver->api->client_secret); defined('PPLOAD_HOST') || define('PPLOAD_HOST', $configFileserver->host); defined('PPLOAD_DOWNLOAD_SECRET') || define('PPLOAD_DOWNLOAD_SECRET', $configFileserver->download_secret); } /** * @return false|mixed|Zend_Controller_Router_Rewrite * @throws Zend_Application_Bootstrap_Exception * @throws Zend_Cache_Exception * @throws Zend_Controller_Exception * @throws Zend_Exception */ protected function _initRouter() { $this->bootstrap('frontController'); /** @var $front Zend_Controller_Front */ $front = $this->getResource('frontController'); /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); if (($router = $cache->load('ProjectRouter'))) { $front->setRouter($router); return $router; } /** @var $router Zend_Controller_Router_Rewrite */ $router = $front->getRouter(); /** RSS Feed */ $router->addRoute('rdf_store', new Zend_Controller_Router_Route('/content.rdf', array( 'module' => 'default', 'controller' => 'rss', 'action' => 'rdf' ))); $router->addRoute('rdf_events_hive', new Zend_Controller_Router_Route_Regex('.*-events.rss', array( 'module' => 'default', 'controller' => 'rss', 'action' => 'rss' ))); $router->addRoute('rdf_store_hive', new Zend_Controller_Router_Route_Regex('.*-content.rdf', array( 'module' => 'default', 'controller' => 'rss', 'action' => 'rdf' ))); $router->addRoute('rdf_store_hive_rss', new Zend_Controller_Router_Route_Regex('rss/.*-content.rdf', array( 'module' => 'default', 'controller' => 'rss', 'action' => 'rdf' ))); /** new store dependent routing rules */ //$router->addRoute('store_general', new Zend_Controller_Router_Route('/s/:domain_store_id/:controller/:action/*', array( // 'module' => 'default', // 'controller' => 'explore', // 'action' => 'index' //))); $router->addRoute('store_home', new Zend_Controller_Router_Route('/s/:domain_store_id/', array( 'module' => 'default', 'controller' => 'home', 'action' => 'index' ))); $router->addRoute('store_browse', new Zend_Controller_Router_Route('/s/:domain_store_id/browse/*', array( 'module' => 'default', 'controller' => 'explore', 'action' => 'index' ))); $router->addRoute('store_product_add', new Zend_Controller_Router_Route('/s/:domain_store_id/product/add', array( 'module' => 'default', 'controller' => 'product', 'action' => 'add' ))); $router->addRoute('store_settings', new Zend_Controller_Router_Route('/s/:domain_store_id/settings', array( 'module' => 'default', 'controller' => 'settings', 'action' => 'index' ))); $router->addRoute('store_pling_box_show', new Zend_Controller_Router_Route('/s/:domain_store_id/supporterbox/:memberid', array( 'module' => 'default', 'controller' => 'plingbox', 'action' => 'index' ))); $router->addRoute('store_pling_box_show', new Zend_Controller_Router_Route('/s/:domain_store_id/productcomment/addreply/*', array( 'module' => 'default', 'controller' => 'productcomment', 'action' => 'addreply' ))); $router->addRoute('store_product', new Zend_Controller_Router_Route('/s/:domain_store_id/p/:project_id/:action/*', array( 'module' => 'default', 'controller' => 'product', 'action' => 'show' ))); $router->addRoute('store_collection', new Zend_Controller_Router_Route('/s/:domain_store_id/c/:project_id/:action/*', array( 'module' => 'default', 'controller' => 'collection', 'action' => 'show' ))); /* $router->addRoute('store_product', new Zend_Controller_Router_Route('/s/:domain_store_id/c/:project_id/:action/*', array( 'module' => 'default', 'controller' => 'collection', 'action' => 'show' ))); */ $router->addRoute('store_user', new Zend_Controller_Router_Route('/s/:domain_store_id/member/:member_id/:action/*', array( 'module' => 'default', 'controller' => 'user', 'action' => 'index' ))); $router->addRoute('store_user_name', new Zend_Controller_Router_Route('/s/:domain_store_id/u/:user_name/:action/*', array( 'module' => 'default', 'controller' => 'user', 'action' => 'index' ))); $router->addRoute('store_login', new Zend_Controller_Router_Route('/s/:domain_store_id/login/*', array( 'module' => 'default', 'controller' => 'authorization', 'action' => 'login' ))); $router->addRoute('store_register', new Zend_Controller_Router_Route('/s/:domain_store_id/register', array( 'module' => 'default', 'controller' => 'authorization', 'action' => 'register' ))); /** general routing rules */ $router->addRoute('home', new Zend_Controller_Router_Route('/', array( 'module' => 'default', 'controller' => 'home', 'action' => 'index' ))); $router->addRoute('home_home', new Zend_Controller_Router_Route('/home', array( 'module' => 'default', 'controller' => 'home', 'action' => 'index' ))); $router->addRoute('home_start', new Zend_Controller_Router_Route('/start', array( 'module' => 'default', 'controller' => 'home', 'action' => 'start' ))); $router->addRoute('home_ajax', new Zend_Controller_Router_Route('/showfeatureajax/*', array( 'module' => 'default', 'controller' => 'home', 'action' => 'showfeatureajax' ))); $router->addRoute('backend', new Zend_Controller_Router_Route('/backend/:controller/:action/*', array( 'module' => 'backend', 'controller' => 'index', 'action' => 'index' ))); $router->addRoute('backend_statistics', new Zend_Controller_Router_Route('/statistics/:action/*', array( 'module' => 'backend', 'controller' => 'statistics', 'action' => 'index' ))); $router->addRoute('browse', new Zend_Controller_Router_Route('/browse/*', array( 'module' => 'default', 'controller' => 'explore', 'action' => 'index' ))); $router->addRoute('browse_favourites', new Zend_Controller_Router_Route('/my-favourites/*', array( 'module' => 'default', 'controller' => 'explore', 'action' => 'index', 'fav' => '1' ))); $router->addRoute('button_render', new Zend_Controller_Router_Route('/button/:project_id/:size/', array( 'module' => 'default', 'controller' => 'button', 'action' => 'render', 'size' => 'large' ))); $router->addRoute('button_action', new Zend_Controller_Router_Route('/button/a/:action/', array( 'module' => 'default', 'controller' => 'button', 'action' => 'index' ))); $router->addRoute('pling_box_show', new Zend_Controller_Router_Route('/supporterbox/:memberid/', array( 'module' => 'default', 'controller' => 'plingbox', 'action' => 'index' ))); $router->addRoute('external_donation_list', new Zend_Controller_Router_Route('/donationlist/:project_id/', array( 'module' => 'default', 'controller' => 'donationlist', 'action' => 'render' ))); $router->addRoute('external_widget', new Zend_Controller_Router_Route('/widget/:project_id/', array( 'module' => 'default', 'controller' => 'widget', 'action' => 'render' ))); $router->addRoute('external_widget_save', new Zend_Controller_Router_Route('/widget/save/*', array( 'module' => 'default', 'controller' => 'widget', 'action' => 'save' ))); $router->addRoute('external_widget_save', new Zend_Controller_Router_Route('/widget/config/:project_id/', array( 'module' => 'default', 'controller' => 'widget', 'action' => 'config' ))); $router->addRoute('external_widget_save_default', new Zend_Controller_Router_Route('/widget/savedefault/*', array( 'module' => 'default', 'controller' => 'widget', 'action' => 'savedefault' ))); $router->addRoute('support_old', new Zend_Controller_Router_Route('/support-old', array( 'module' => 'default', 'controller' => 'support', 'action' => 'index' ))); $router->addRoute('support_old_pay', new Zend_Controller_Router_Route('/support-old/pay', array( 'module' => 'default', 'controller' => 'support', 'action' => 'pay' ))); $router->addRoute('support_old_paymentok', new Zend_Controller_Router_Route('/support-old/paymentok', array( 'module' => 'default', 'controller' => 'support', 'action' => 'paymentok' ))); $router->addRoute('support_old_paymentcancel', new Zend_Controller_Router_Route('/support-old/paymentcancel', array( 'module' => 'default', 'controller' => 'support', 'action' => 'paymentcancel' ))); $router->addRoute('samepaypal', new Zend_Controller_Router_Route('/samepaypal', array( 'module' => 'default', 'controller' => 'spam', 'action' => 'paypal' ))); $router->addRoute('support_new', new Zend_Controller_Router_Route('/supportold2', array( 'module' => 'default', 'controller' => 'subscription', 'action' => 'index' ))); $router->addRoute('support_predefined', new Zend_Controller_Router_Route('/support-predefined', array( 'module' => 'default', 'controller' => 'subscription', 'action' => 'supportpredefinded' ))); $router->addRoute('support_pay_predefined', new Zend_Controller_Router_Route('/support/paypredefined', array( 'module' => 'default', 'controller' => 'subscription', 'action' => 'paypredefined' ))); $router->addRoute('support_new2', new Zend_Controller_Router_Route('/support', array( 'module' => 'default', 'controller' => 'subscription', 'action' => 'support2' ))); $router->addRoute('support_new_pay2', new Zend_Controller_Router_Route('/support/pay', array( 'module' => 'default', 'controller' => 'subscription', 'action' => 'pay2' ))); $router->addRoute('support_new_pay', new Zend_Controller_Router_Route('/support/payold2', array( 'module' => 'default', 'controller' => 'subscription', 'action' => 'pay' ))); $router->addRoute('support_new_paymentok', new Zend_Controller_Router_Route('/support/paymentok', array( 'module' => 'default', 'controller' => 'subscription', 'action' => 'paymentok' ))); $router->addRoute('support_new_paymentcancel', new Zend_Controller_Router_Route('/support/paymentcancel', array( 'module' => 'default', 'controller' => 'subscription', 'action' => 'paymentcancel' ))); /** * Project/Product */ $router->addRoute('product_short_url', new Zend_Controller_Router_Route('/p/:project_id/:action/*', array( 'module' => 'default', 'controller' => 'product', 'action' => 'show' ))); $router->addRoute('product_referrer_url', new Zend_Controller_Router_Route('/p/:project_id/er/:er/*', array( 'module' => 'default', 'controller' => 'product', 'action' => 'show' ))); $router->addRoute('product_collectionid_url', new Zend_Controller_Router_Route('/co/:collection_id', array( 'module' => 'default', 'controller' => 'product', 'action' => 'show' ))); $router->addRoute('product_add', new Zend_Controller_Router_Route('/product/add', array( 'module' => 'default', 'controller' => 'product', 'action' => 'add' ))); $router->addRoute('product_add_extend', new Zend_Controller_Router_Route('/product/add/:catId', array( 'module' => 'default', 'controller' => 'product', 'action' => 'add' ))); $router->addRoute('search', new Zend_Controller_Router_Route('/search/*', array( 'module' => 'default', 'controller' => 'product', 'action' => 'search' ))); $router->addRoute('search_domain', new Zend_Controller_Router_Route('/s/:domain_store_id/search/*', array( 'module' => 'default', 'controller' => 'product', 'action' => 'search' ))); $router->addRoute('product_save', new Zend_Controller_Router_Route('/p/save/*', array( 'module' => 'default', 'controller' => 'product', 'action' => 'saveproduct' ))); /** * Collection */ $router->addRoute('collection_short_url', new Zend_Controller_Router_Route('/c/:project_id/', array( 'module' => 'default', 'controller' => 'collection', 'action' => 'index' ))); $router->addRoute('collection_short_url', new Zend_Controller_Router_Route('/c/:project_id/:action/*', array( 'module' => 'default', 'controller' => 'collection', 'action' => 'index' ))); $router->addRoute('collection_referrer_url', new Zend_Controller_Router_Route('/c/:project_id/er/:er/*', array( 'module' => 'default', 'controller' => 'collection', 'action' => 'index' ))); $router->addRoute('collection_add', new Zend_Controller_Router_Route('/collection/add', array( 'module' => 'default', 'controller' => 'collection', 'action' => 'add' ))); /** * $router->addRoute('search', new Zend_Controller_Router_Route('/search/*', array( * 'module' => 'default', * 'controller' => 'collection', * 'action' => 'search' * ))); * * $router->addRoute('search_domain',new Zend_Controller_Router_Route('/s/:domain_store_id/search/*', * array( * 'module' => 'default', * 'controller' => 'product', * 'action' => 'search' * ))); */ $router->addRoute('collection_save', new Zend_Controller_Router_Route('/c/save/*', array( 'module' => 'default', 'controller' => 'collection', 'action' => 'saveproduct' ))); /** * Member */ $router->addRoute('member_settings_old', new Zend_Controller_Router_Route('/settings/:action/*', array( 'module' => 'default', 'controller' => 'settings', 'action' => 'index' ))); $router->addRoute('user_show', new Zend_Controller_Router_Route('/member/:member_id/:action/*', array( 'module' => 'default', 'controller' => 'user', 'action' => 'index' ))); $router->addRoute('user_avatar', new Zend_Controller_Router_Route('/member/avatar/:emailhash/:size', array( 'module' => 'default', 'controller' => 'user', 'action' => 'avatar' ))); $router->addRoute('user_show_with_name', new Zend_Controller_Router_Route('/u/:user_name/:action/*', array( 'module' => 'default', 'controller' => 'user', 'action' => 'index' ))); $router->addRoute('user_recification', new Zend_Controller_Router_Route('/r/:action/*', array( 'module' => 'default', 'controller' => 'rectification', 'action' => 'index' ))); $router->addRoute('user_show_short', new Zend_Controller_Router_Route('/me/:member_id/:action/*', array( 'module' => 'default', 'controller' => 'user', 'action' => 'index' ))); $router->addRoute('register', new Zend_Controller_Router_Route_Static('/register', array( 'module' => 'default', 'controller' => 'authorization', 'action' => 'register' ))); $router->addRoute('register_validate', new Zend_Controller_Router_Route_Static('/register/validate', array( 'module' => 'default', 'controller' => 'authorization', 'action' => 'validate' ))); $router->addRoute('verification', new Zend_Controller_Router_Route('/verification/:vid', array( 'module' => 'default', 'controller' => 'authorization', 'action' => 'verification' ))); $router->addRoute('logout', new Zend_Controller_Router_Route_Static('/logout', array( 'module' => 'default', 'controller' => 'logout', 'action' => 'logout' ))); $router->addRoute('propagatelogout', new Zend_Controller_Router_Route_Static('/logout/propagate', array( 'module' => 'default', 'controller' => 'authorization', 'action' => 'propagatelogout' ))); $router->addRoute('checkuser', new Zend_Controller_Router_Route_Static('/checkuser', array( 'module' => 'default', 'controller' => 'authorization', 'action' => 'checkuser' ))); $router->addRoute('login', new Zend_Controller_Router_Route('/login', array( 'module' => 'default', 'controller' => 'authorization', 'action' => 'login' ))); $router->addRoute('login', new Zend_Controller_Router_Route('/login/:action/*', array( 'module' => 'default', 'controller' => 'authorization', 'action' => 'login' ))); $router->addRoute('LoginController', new Zend_Controller_Router_Route('/l/:action/*', array( 'module' => 'default', 'controller' => 'login', 'action' => 'login' ))); $router->addRoute('content', new Zend_Controller_Router_Route('/content/:page', array( 'module' => 'default', 'controller' => 'content', 'action' => 'index' ))); $router->addRoute('categories_about', new Zend_Controller_Router_Route('/cat/:page/about', array( 'module' => 'default', 'controller' => 'categories', 'action' => 'about' ))); // **** static routes $router->addRoute('static_faq_old', new Zend_Controller_Router_Route_Static('/faq-old', array( 'module' => 'default', 'controller' => 'content', 'action' => 'index', 'page' => 'faqold' ))); $router->addRoute('static_faq', new Zend_Controller_Router_Route_Static('/faq-pling', array( 'module' => 'default', 'controller' => 'content', 'action' => 'index', 'page' => 'faq' ))); $router->addRoute('static_gitfaq', new Zend_Controller_Router_Route_Static('/faq-opencode', array( 'module' => 'default', 'controller' => 'content', 'action' => 'index', 'page' => 'gitfaq' ))); $router->addRoute('static_ocsapi', new Zend_Controller_Router_Route_Static('/ocs-api', array( 'module' => 'default', 'controller' => 'content', 'action' => 'index', 'page' => 'ocsapi' ))); $router->addRoute('static_plings', new Zend_Controller_Router_Route_Static('/about', array( 'module' => 'default', 'controller' => 'content', 'action' => 'index', 'page' => 'about' ))); $router->addRoute('static_terms', new Zend_Controller_Router_Route_Static('/terms', array( 'module' => 'default', 'controller' => 'content', 'action' => 'index', 'page' => 'terms' ))); $router->addRoute('static_terms_general', new Zend_Controller_Router_Route_Static('/terms/general', array( 'module' => 'default', 'controller' => 'content', 'action' => 'index', 'page' => 'terms-general' ))); $router->addRoute('static_terms_publish', new Zend_Controller_Router_Route_Static('/terms/publishing', array( 'module' => 'default', 'controller' => 'content', 'action' => 'index', 'page' => 'terms-publishing' ))); $router->addRoute('static_terms_dmca', new Zend_Controller_Router_Route_Static('/terms/dmca', array( 'module' => 'default', 'controller' => 'content', 'action' => 'index', 'page' => 'terms-dmca' ))); $router->addRoute('static_terms_payout', new Zend_Controller_Router_Route_Static('/terms/payout', array( 'module' => 'default', 'controller' => 'content', 'action' => 'index', 'page' => 'terms-payout' ))); $router->addRoute('static_terms_cookies', new Zend_Controller_Router_Route_Static('/terms/cookies', array( 'module' => 'default', 'controller' => 'content', 'action' => 'index', 'page' => 'terms-cookies' ))); $router->addRoute('static_privacy', new Zend_Controller_Router_Route_Static('/privacy', array( 'module' => 'default', 'controller' => 'content', 'action' => 'index', 'page' => 'privacy' ))); $router->addRoute('static_imprint', new Zend_Controller_Router_Route_Static('/imprint', array( 'module' => 'default', 'controller' => 'content', 'action' => 'index', 'page' => 'imprint' ))); $router->addRoute('static_contact', new Zend_Controller_Router_Route_Static('/contact', array( 'module' => 'default', 'controller' => 'content', 'action' => 'index', 'page' => 'contact' ))); // **** ppload $router->addRoute('pploadlogin', new Zend_Controller_Router_Route('/pploadlogin/*', array( 'module' => 'default', 'controller' => 'authorization', 'action' => 'pploadlogin' ))); // OCS API //20191120 OCS-API is disabled for webservers, only api.pling.com or api.kde-look.org allowed, see ticket #1494 //20191125 erst mal wieder drin $router->addRoute('ocs_providers_xml', new Zend_Controller_Router_Route('/ocs/providers.xml', array( 'module' => 'default', 'controller' => 'ocsv1', 'action' => 'providers' ))); $router->addRoute('ocs_v1_config', new Zend_Controller_Router_Route('/ocs/v1/config', array( 'module' => 'default', 'controller' => 'ocsv1', 'action' => 'config' ))); $router->addRoute('ocs_v1_person_check', new Zend_Controller_Router_Route('/ocs/v1/person/check', array( 'module' => 'default', 'controller' => 'ocsv1', 'action' => 'personcheck' ))); $router->addRoute('ocs_v1_person_data', new Zend_Controller_Router_Route('/ocs/v1/person/data', array( 'module' => 'default', 'controller' => 'ocsv1', 'action' => 'persondata' ))); $router->addRoute('ocs_v1_person_data_personid', new Zend_Controller_Router_Route('/ocs/v1/person/data/:personid', array( 'module' => 'default', 'controller' => 'ocsv1', 'action' => 'persondata' ))); $router->addRoute('ocs_v1_person_self', new Zend_Controller_Router_Route('/ocs/v1/person/self', array( 'module' => 'default', 'controller' => 'ocsv1', 'action' => 'personself' ))); $router->addRoute('ocs_v1_content_categories', new Zend_Controller_Router_Route('/ocs/v1/content/categories', array( 'module' => 'default', 'controller' => 'ocsv1', 'action' => 'contentcategories' ))); $router->addRoute('ocs_v1_content_data_contentid', new Zend_Controller_Router_Route('/ocs/v1/content/data/:contentid', array( 'module' => 'default', 'controller' => 'ocsv1', 'action' => 'contentdata', 'contentid' => null ))); $router->addRoute('ocs_v1_content_download_contentid_itemid', new Zend_Controller_Router_Route('/ocs/v1/content/download/:contentid/:itemid', array( 'module' => 'default', 'controller' => 'ocsv1', 'action' => 'contentdownload' ))); $router->addRoute('ocs_v1_content_previewpic_contentid', new Zend_Controller_Router_Route('/ocs/v1/content/previewpic/:contentid', array( 'module' => 'default', 'controller' => 'ocsv1', 'action' => 'contentpreviewpic' ))); $router->addRoute('ocs_v1_comments', new Zend_Controller_Router_Route('/ocs/v1/comments/data/:comment_type/:content_id/:second_id', array( 'module' => 'default', 'controller' => 'ocsv1', 'action' => 'comments', 'comment_type' => -1, 'content_id' => null, 'second_id' => null ))); $router->addRoute('ocs_v1_voting', new Zend_Controller_Router_Route('/ocs/v1/content/vote/:contentid', array( 'module' => 'default', 'controller' => 'ocsv1', 'action' => 'vote' ))); // embed $router->addRoute('embed_v1_member_projects', new Zend_Controller_Router_Route('/embed/v1/member/:memberid', array( 'module' => 'default', 'controller' => 'embedv1', 'action' => 'memberprojects' ))); $router->addRoute('embed_v1_member_projects_files', new Zend_Controller_Router_Route('/embed/v1/ppload/:ppload_collection_id', array( 'module' => 'default', 'controller' => 'embedv1', 'action' => 'ppload' ))); $router->addRoute('embed_v1_member_projectscomments', new Zend_Controller_Router_Route('/embed/v1/comments/:id', array( 'module' => 'default', 'controller' => 'embedv1', 'action' => 'comments' ))); $router->addRoute('embed_v1_member_projectdetail', new Zend_Controller_Router_Route('/embed/v1/project/:projectid', array( 'module' => 'default', 'controller' => 'embedv1', 'action' => 'projectdetail' ))); $router->addRoute('clones', new Zend_Controller_Router_Route('/clones/*', array( 'module' => 'default', 'controller' => 'credits', 'action' => 'index' ))); $router->addRoute('mods', new Zend_Controller_Router_Route('/mods/*', array( 'module' => 'default', 'controller' => 'credits', 'action' => 'mods' ))); $cache->save($router, 'ProjectRouter', array('router'), 14400); return $router; } /** * @throws Zend_Cache_Exception * @throws Zend_Exception * @throws exception */ protected function _initCss() { if (APPLICATION_ENV != "development" && APPLICATION_ENV != "staging") { return; } $appConfig = $this->getResource('config'); if ((boolean)$appConfig->settings->noLESScompile === true) { return; } $sLess = realpath(APPLICATION_PATH . '/../httpdocs/theme/flatui/less/stylesheet.less'); $sCss = realpath(APPLICATION_PATH . '/../httpdocs/theme/flatui/css/stylesheet.css'); /** * @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); if (md5_file($sLess) !== $cache->load('md5Less')) { require_once APPLICATION_PATH . "/../library/lessphp/lessc.inc.php"; $oLessc = new lessc($sLess); $oLessc->setFormatter('compressed'); file_put_contents($sCss, $oLessc->parse()); $cache->save(md5_file($sLess), 'md5Less'); } } protected function _initGlobalApplicationVars() { $modelDomainConfig = new Default_Model_DbTable_ConfigStore(); Zend_Registry::set('application_store_category_list', $modelDomainConfig->fetchAllStoresAndCategories()); Zend_Registry::set('application_store_config_list', $modelDomainConfig->fetchAllStoresConfigArray()); Zend_Registry::set('application_store_config_id_list', $modelDomainConfig->fetchAllStoresConfigByIdArray()); } /** * @throws Zend_Application_Bootstrap_Exception */ protected function _initStoreDependentVars() { /** @var $front Zend_Controller_Front */ $front = $this->bootstrap('frontController')->getResource('frontController'); $front->registerPlugin(new Default_Plugin_InitGlobalStoreVars()); } } diff --git a/application/modules/default/controllers/AuthorizationController.php b/application/modules/default/controllers/AuthorizationController.php index 45ef34e45..00a6799c5 100644 --- a/application/modules/default/controllers/AuthorizationController.php +++ b/application/modules/default/controllers/AuthorizationController.php @@ -1,1024 +1,1025 @@ . **/ class AuthorizationController extends Local_Controller_Action_DomainSwitch { const DEFAULT_ROLE_ID = 300; const PROFILE_IMG_SRC_LOCAL = 'local'; public function githubAction() { require_once APPLICATION_LIB . '/Local/CrawlerDetect.php'; if (crawlerDetect($_SERVER['HTTP_USER_AGENT'])) { $this->getResponse()->setHttpResponseCode(404); $this->forward('index', 'explore'); return; } $this->forward('login', 'oauth', 'default', array('provider' => 'github', 'redirect' => $this->getParam('redirect'))); } public function ocsAction() { require_once APPLICATION_LIB . '/Local/CrawlerDetect.php'; if (crawlerDetect($_SERVER['HTTP_USER_AGENT'])) { $this->getResponse()->setHttpResponseCode(404); $this->forward('index', 'explore'); return; } $this->forward('login', 'oauth', 'default', array('provider' => 'ocs', 'redirect' => $this->getParam('redirect'))); } public function redirectAction() { $param = null; if (preg_match("/redirect\/(.*?)$/i", $this->getRequest()->getRequestUri(), $result)) { $param = array('redirect' => $result[1]); } $this->forward('login', null, null, $param); } /** * login from cookie * * @throws Zend_Auth_Storage_Exception * @throws Zend_Form_Exception * @throws Zend_Session_Exception * @throws exception */ public function lfcAction() { $this->view->success = 0; $this->view->noPopup = true; //TODO: check redirect for a local valid url. $this->view->redirect = $this->getParam('redirect'); $formLogin = new Default_Form_Login(); $formLogin->setAction('/login/lfc/'); $formLogin->getElement('remember_me')->setValue(true); if ($this->_request->isGet()) { // not a POST request $this->view->form = $formLogin->populate(array('redirect' => $this->view->redirect)); $this->view->error = 0; return; } Zend_Registry::get('logger')->info(__METHOD__ . PHP_EOL . ' - authentication attempt on host: ' . Zend_Registry::get('store_host') . PHP_EOL . ' - param redirect: ' . $this->getParam('redirect') . PHP_EOL . ' - from ip: ' . $this->_request->getClientIp() ); if (false === $formLogin->isValid($_POST)) { // form not valid Zend_Registry::get('logger')->info(__METHOD__ . PHP_EOL . ' - ip: ' . $this->_request->getClientIp() . PHP_EOL . ' - form not valid:' . PHP_EOL . print_r($formLogin->getMessages(), true)); $this->view->form = $formLogin; $this->view->errorText = 'index.login.error.auth'; $this->view->error = 1; return; } $values = $formLogin->getValues(); $authModel = new Default_Model_Authorization(); $authResult = $authModel->authenticateUser($values['mail'], $values['password'], $values['remember_me']); if (false == $authResult->isValid()) { // authentication fail Zend_Registry::get('logger')->info(__METHOD__ . PHP_EOL . ' - ip: ' . $this->_request->getClientIp() . PHP_EOL . ' - authentication fail: ' . PHP_EOL . print_r($authResult->getMessages(), true) ); $this->view->errorText = 'index.login.error.auth'; $this->view->form = $formLogin; $this->view->error = 1; $this->_helper->viewRenderer('login'); return; } $auth = Zend_Auth::getInstance(); $userId = $auth->getStorage()->read()->member_id; // handle redirect if (false === empty($this->view->redirect)) { $redirect = $this->decodeString($this->view->redirect); if (false !== strpos('/register', $redirect)) { $redirect = '/member/' . $userId . '/activities/'; } $this->redirect($redirect); } else { $this->redirect('/member/' . $userId . '/activities/'); } } /** * @param string $string * * @return string */ protected function decodeString($string) { $decodeFilter = new Local_Filter_Url_Decrypt(); return $decodeFilter->filter($string); } /** * @throws Zend_Auth_Storage_Exception * @throws Zend_Exception * @throws Zend_Session_Exception * @throws exception */ public function propagateAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); if (Zend_Auth::getInstance()->hasIdentity()) { $this->_helper->json(array('status' => 'ok', 'message' => 'Already logged in.')); } Zend_Registry::get('logger')->info(__METHOD__ . PHP_EOL . ' - token: ' . $this->getParam('token') . PHP_EOL . ' - host: ' . Zend_Registry::get('store_host') . PHP_EOL . ' - ip: ' . $this->_request->getClientIp() ); $modelAuthToken = new Default_Model_SingleSignOnToken(); $token_data = $modelAuthToken->getData($this->getParam('token')); if (false === $token_data) { Zend_Registry::get('logger')->warn(__METHOD__ . PHP_EOL . ' - Login failed: no token exists' . PHP_EOL . ' - host: ' . Zend_Registry::get('store_host') . PHP_EOL . ' - ip: ' . $this->_request->getClientIp() ); $this->_helper->json(array('status' => 'fail', 'message' => 'Login failed.')); } $remember_me = isset($token_data['remember_me']) ? (boolean)$token_data['remember_me'] : false; $member_id = isset($token_data['member_id']) ? (int)$token_data['member_id'] : null; $modelAuth = new Default_Model_Authorization(); $authResult = $modelAuth->authenticateUser($member_id, null, $remember_me, Local_Auth_AdapterFactory::LOGIN_SSO); if ($authResult->isValid()) { Zend_Registry::get('logger')->info(__METHOD__ . PHP_EOL . ' - authentication successful: ' . PHP_EOL . ' - host: ' . Zend_Registry::get('store_host') . PHP_EOL . ' - ip: ' . $this->_request->getClientIp() ); $this->getResponse()->setHeader('Access-Control-Allow-Origin', $this->getParam('origin')) ->setHeader('Access-Control-Allow-Credentials', 'true') ->setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept'); $this->_helper->json(array('status' => 'ok', 'message' => 'Login successful.')); } else { Zend_Registry::get('logger')->info(__METHOD__ . PHP_EOL . ' - authentication fail: ' . PHP_EOL . ' - host: ' . Zend_Registry::get('store_host') . PHP_EOL . ' - ip: ' . $this->_request->getClientIp() . PHP_EOL . print_r($authResult->getMessages(), true) ); $this->_helper->json(array('status' => 'fail', 'message' => 'Login failed.')); } } public function checkuserAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $this->getResponse()->setHeader('Access-Control-Allow-Origin', 'https://gitlab.pling.cc') ->setHeader('Access-Control-Allow-Credentials', 'true')->setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept'); $formLogin = new Default_Form_Login(); if (false === $formLogin->isValid($_GET)) { // form not valid $this->_helper->json(array('status' => 'error', 'message' => 'not valid')); return; } $values = $formLogin->getValues(); $authModel = new Default_Model_Authorization(); $authResult = $authModel->authenticateUser($values['mail'], $values['password'], $values['remember_me']); if (false == $authResult->isValid()) { // authentication fail $this->_helper->json(array('status' => 'error', 'message' => 'not valid')); return; } $auth = Zend_Auth::getInstance(); $userId = $auth->getStorage()->read()->member_id; //Send user to LDAP try { $ldap_server = new Default_Model_Ocs_Ldap(); $ldap_server->createUser($userId); Zend_Registry::get('logger')->debug(__METHOD__ . ' - ldap : ' . implode(PHP_EOL . " - ", $ldap_server->getMessages())); } catch (Exception $e) { Zend_Registry::get('logger')->err($e->getMessage() . PHP_EOL . $e->getTraceAsString()); } //If the user is a hive user, we have to update his password $this->changePasswordIfNeeded($userId, $values['password']); $this->_helper->json(array('status' => 'ok', 'message' => 'User is OK.')); } /** * @param int $member_id * @param string $password * @throws Zend_Db_Statement_Exception * @throws Zend_Exception */ private function changePasswordIfNeeded($member_id, $password) { $userTabel = new Default_Model_Member(); $showMember = $userTabel->fetchMember($member_id); $memberSettings = $showMember; //User with OCS Password if ($showMember->password_type == Default_Model_Member::PASSWORD_TYPE_OCS) { return; } //Hive User if ($memberSettings->password_type == Default_Model_Member::PASSWORD_TYPE_HIVE) { //Save old data $memberSettings->password_old = $memberSettings->password; $memberSettings->password_type_old = Default_Model_Member::PASSWORD_TYPE_HIVE; //Change type and password $memberSettings->password_type = Default_Model_Member::PASSWORD_TYPE_OCS; $memberSettings->password = Local_Auth_Adapter_Ocs::getEncryptedPassword($password, Default_Model_Member::PASSWORD_TYPE_OCS); $memberSettings->save(); //Update Auth-Services try { $id_server = new Default_Model_Ocs_OAuth(); $id_server->updatePasswordForUser($memberSettings->member_id); $messages = $id_server->getMessages(); if (false == empty($messages)) { Zend_Registry::get('logger')->info(json_encode($messages)); } } catch (Exception $e) { Zend_Registry::get('logger')->err($e->getMessage() . PHP_EOL . $e->getTraceAsString()); } try { $ldap_server = new Default_Model_Ocs_Ldap(); $ldap_server->updatePassword($memberSettings->member_id,$password); $messages = $ldap_server->getMessages(); if (false == empty($messages)) { Zend_Registry::get('logger')->info(json_encode($messages)); } } catch (Exception $e) { Zend_Registry::get('logger')->err($e->getMessage() . PHP_EOL . $e->getTraceAsString()); } } return; } /** * @throws Zend_Auth_Storage_Exception * @throws Zend_Exception * @throws Zend_Form_Exception * @throws Zend_Session_Exception * @throws exception */ public function loginAction() { $this->view->noheader = true; //TODO: check redirect for a local valid url. $this->view->redirect = $this->getParam('redirect'); // if the user is still logged in, we do not show the login page. They should log out first. if (Zend_Auth::getInstance()->hasIdentity()) { $this->_helper->flashMessenger->addMessage('

You are still logged in. Please click here to log out first.

'); $this->handleRedirect(Zend_Auth::getInstance()->getIdentity()->member_id); } $formLogin = new Default_Form_Login(); if ($this->_request->isGet()) { // not a POST request $this->view->formLogin = $formLogin->populate(array('redirect' => $this->view->redirect)); $this->view->error = 0; return; } Zend_Registry::get('logger')->info(__METHOD__ . PHP_EOL . ' - authentication attempt on host: ' . Zend_Registry::get('store_host') . PHP_EOL . ' - param redirect: ' . $this->getParam('redirect') . PHP_EOL . ' - from ip: ' . $this->_request->getClientIp() . PHP_EOL . ' - http method: ' . $this->_request->getMethod() . PHP_EOL . ' - csrf string: ' . (isset($_POST['login_csrf']) ? $_POST['login_csrf'] : '') ); if (false === Default_Model_CsrfProtection::validateCsrfToken($_POST['login_csrf'])) { Zend_Registry::get('logger')->info(__METHOD__ . PHP_EOL . ' - ip: ' . $this->_request->getClientIp() . PHP_EOL . ' - validate CSRF token failed:' . PHP_EOL . ' - received token: ' . $_POST['login_csrf'] . PHP_EOL . ' - stored token: ' . Default_Model_CsrfProtection::getCsrfToken() ); $this->view->error = 0; $this->view->formLogin = $formLogin; if ($this->_request->isXmlHttpRequest()) { $viewLoginForm = $this->view->render('authorization/partials/loginForm.phtml'); $this->_helper->json(array('status' => 'ok', 'message' => $viewLoginForm)); } return; } if (false === $formLogin->isValid($_POST)) { // form not valid Zend_Registry::get('logger')->info(__METHOD__ . PHP_EOL . ' - ip: ' . $this->_request->getClientIp() . PHP_EOL . ' - form not valid:' . PHP_EOL . print_r($formLogin->getMessages(), true) ); $this->view->formLogin = $formLogin; $this->view->errorText = 'index.login.error.auth'; $this->view->error = 1; if ($this->_request->isXmlHttpRequest()) { $viewLoginForm = $this->view->render('authorization/partials/loginForm.phtml'); $this->_helper->json(array('status' => 'ok', 'message' => $viewLoginForm)); } return; } $values = $formLogin->getValues(); $authModel = new Default_Model_Authorization(); $authResult = $authModel->authenticateUser($values['mail'], $values['password'], $values['remember_me']); if (false == $authResult->isValid()) { // authentication fail Zend_Registry::get('logger')->info(__METHOD__ . PHP_EOL . ' - authentication fail.' . PHP_EOL . ' - user: ' . $values['mail'] . PHP_EOL . ' - remember_me: ' . $values['remember_me'] . PHP_EOL . ' - ip: ' . $this->_request->getClientIp() . PHP_EOL . print_r($authResult->getMessages(), true) ); if ($authResult->getCode() == Local_Auth_Result::MAIL_ADDRESS_NOT_VALIDATED) { $session = new Zend_Session_Namespace(); $session->mail_verify_member_id = $authResult->getIdentity(); if ($this->_request->isXmlHttpRequest()) { $viewMessage = $this->view->render('verify/resend.phtml'); $this->_helper->json(array('status' => 'ok', 'message' => $viewMessage)); } } $this->view->errorText = 'index.login.error.auth'; $this->view->formLogin = $formLogin; $this->view->error = 1; if ($this->_request->isXmlHttpRequest()) { $viewLoginForm = $this->view->render('authorization/partials/loginForm.phtml'); $this->_helper->json(array('status' => 'ok', 'message' => $viewLoginForm)); } return; } Zend_Registry::get('logger')->info(__METHOD__ . PHP_EOL . ' - authentication successful.' . PHP_EOL . ' - user: ' . $values['mail'] . PHP_EOL . ' - user_id: ' . isset(Zend_Auth::getInstance()->getStorage()->read()->member_id) ? Zend_Auth::getInstance()->getStorage()->read()->member_id : '' . PHP_EOL . ' - remember_me: ' . $values['remember_me'] . PHP_EOL . ' - ip: ' . $this->_request->getClientIp() ); $filter = new Local_Filter_Url_Encrypt(); $p = $filter->filter($values['password']); $sess = new Zend_Session_Namespace('ocs_meta'); $sess->phash = $p; $auth = Zend_Auth::getInstance(); $userId = $auth->getStorage()->read()->member_id; $jwt = Default_Model_Jwt::encode($userId); $sess->openid = $jwt; //If the user is a hive user, we have to update his password $this->changePasswordIfNeeded($userId, $values['password']); //log login try { $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']) : $_SERVER['REMOTE_ADDR']; if (is_array($ip)) { $ip = $ip[0]; } $agent = null; if ( isset( $_SERVER ) ) { $agent = $_SERVER['HTTP_USER_AGENT']; } $fingerprint = null; $session = new Zend_Session_Namespace(); $fp = $session->client_fp; if (!empty($fp)) { $fingerprint = $fp; } $ipv4 = null; $ipv6 = null; if($this->hasParam('ipv4')) { $ipv4 = $this->getParam('ipv4'); } if($this->hasParam('ipv6')) { $ipv6 = $this->getParam('ipv6'); } $loginHistory = new Default_Model_LoginHistory(); $loginHistory->log($userId, $ip, $ipv4, $ipv6, $agent, $fingerprint); } catch (Exception $exc) { } //$modelToken = new Default_Model_SingleSignOnToken(); //$data = array( // 'remember_me' => $values['remember_me'], // //'redirect' => $this->getParam('redirect'), // 'redirect' => $this->view->redirect, // 'action' => Default_Model_SingleSignOnToken::ACTION_LOGIN, // 'member_id' => $userId //); //$token_id = $modelToken->createToken($data); //setcookie(Default_Model_SingleSignOnToken::ACTION_LOGIN, $token_id, time() + 120, '/', // Local_Tools_ParseDomain::get_domain($this->getRequest()->getHttpHost()), null, true); //user has to correct his data? $modelReviewProfile = new Default_Model_ReviewProfileData(); if (false === $modelReviewProfile->hasValidProfile($auth->getStorage()->read())) { Zend_Registry::get('logger')->info(__METHOD__ . PHP_EOL . ' - User has to change user data!' . PHP_EOL . ' - error code: ' . print_r($modelReviewProfile->getErrorCode(), true) ); if ($this->_request->isXmlHttpRequest()) { $redirect = $this->getParam('redirect') ? '/redirect/' . $this->getParam('redirect') : ''; $this->_helper->json(array( 'status' => 'ok', 'redirect' => '/r/change/e/' . $modelReviewProfile->getErrorCode() . $redirect )); } else { $this->getRequest()->setParam('member_id', $userId); $this->redirect("/r/change/e/" . $modelReviewProfile->getErrorCode(), $this->getAllParams()); } return; } // handle redirect $this->view->loginok = true; $this->handleRedirect($userId); } /** * @param int $userId * * @throws Zend_Exception * @throws Zend_Filter_Exception */ protected function handleRedirect($userId) { if (empty($this->view->redirect)) { Zend_Registry::get('logger')->info(__METHOD__ . PHP_EOL . ' - user_id: ' . $userId . PHP_EOL . ' - redirect: empty'); if ($this->_request->isXmlHttpRequest()) { $redirect_url = $this->encodeString('/member/' . $userId . '/activities/'); $redirect = '/home/redirectme?redirect=' . $redirect_url; $this->_helper->json(array('status' => 'ok', 'redirect' => $redirect)); return; } $this->getRequest()->setParam('member_id', $userId); $redirect_url = $this->encodeString('/member/' . $userId . '/activities/'); $redirect = '/home/redirectme?redirect=' . $redirect_url; $this->redirect($redirect, $this->getAllParams()); return; } $redirect = $this->decodeString($this->view->redirect); Zend_Registry::get('logger')->info(__METHOD__ . PHP_EOL . ' - user_id: ' . $userId . PHP_EOL . ' - redirect: ' . $redirect); if (false !== strpos('/register', $redirect)) { $redirect = '/member/' . $userId . '/activities/'; } $redirect = '/home/redirectme?redirect=' . $this->encodeString($redirect); if ($this->_request->isXmlHttpRequest()) { $this->_helper->json(array('status' => 'ok', 'redirect' => $redirect)); return; } $this->redirect($redirect); return; } /** * @param string $string * * @return string * @throws Zend_Filter_Exception */ protected function encodeString($string) { $encodeFilter = new Local_Filter_Url_Encrypt(); return $encodeFilter->filter($string); } /** * @throws Exception * @throws Zend_Exception * @throws Zend_Form_Exception */ public function registerAction() { $this->view->redirect = $this->getParam('redirect'); $this->view->headScript()->appendFile('//www.google.com/recaptcha/api.js'); $this->view->addHelperPath(APPLICATION_LIB . '/Cgsmith/View/Helper', 'Cgsmith\\View\\Helper\\'); $formRegister = new Default_Form_Register(); if ($this->_request->isGet()) { $this->view->formRegister = $formRegister->populate(array('redirect' => urlencode($this->view->redirect))); $this->view->error = 0; return; } if (false === $formRegister->isValid($_POST)) { $this->view->formRegister = $formRegister; $this->view->error = 1; if ($this->_request->isXmlHttpRequest()) { $viewRegisterForm = $this->view->render('authorization/partials/registerForm.phtml'); $this->_helper->json(array('status' => 'ok', 'message' => $viewRegisterForm)); } return; } $formRegisterValues = $formRegister->getValues(); unset($formRegisterValues['g-recaptcha-response']); $formRegisterValues['password'] = $formRegisterValues['password1']; $formRegisterValues['username'] = Default_Model_HtmlPurify::purify($formRegisterValues['username']); $formRegisterValues['mail'] = strtolower($formRegisterValues['mail']); $doubleOptIn = (boolean)Zend_Registry::get('config')->settings->double_opt_in->active; $newUserData = $this->createNewUser($formRegisterValues, $doubleOptIn); Default_Model_ActivityLog::logActivity($newUserData['main_project_id'], null, $newUserData['member_id'], Default_Model_ActivityLog::MEMBER_JOINED, array()); if ($doubleOptIn) { $this->sendConfirmationMail($formRegisterValues, $newUserData['verificationVal']); } Zend_Registry::get('logger')->debug(__METHOD__ . ' - member_id: ' . $newUserData['member_id'] . ' - Link for verification: ' . 'http://' . $this->getServerName() . '/verification/' . $newUserData['verificationVal']); //log login try { $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']) : $_SERVER['REMOTE_ADDR']; if (is_array($ip)) { $ip = $ip[0]; } $agent = null; if ( isset( $_SERVER ) ) { $agent = $_SERVER['HTTP_USER_AGENT']; } $fingerprint = null; $session = new Zend_Session_Namespace(); $fp = $session->client_fp; if (!empty($fp)) { $fingerprint = $fp; } $ipv4 = null; $ipv6 = null; if($this->hasParam('ipv4')) { $ipv4 = $this->getParam('ipv4'); } if($this->hasParam('ipv6')) { $ipv6 = $this->getParam('ipv6'); } $loginHistory = new Default_Model_LoginHistory(); $loginHistory->log($newUserData['member_id'], $ip, $ipv4, $ipv6, $agent, $fingerprint); } catch (Exception $exc) { } if ($this->_request->isXmlHttpRequest()) { $viewRegisterForm = $this->view->render('authorization/partials/registerSuccess.phtml'); $this->_helper->json(array('status' => 'ok', 'message' => $viewRegisterForm)); } else { $this->view->overlay = $this->view->render('authorization/registerSuccess.phtml'); $this->forward('index', 'explore', 'default'); } } /** * @param array $userData * * @return array * @throws Exception */ protected function createNewUser($userData, $doubleOptIn = true) { if (false === $doubleOptIn) { $userData['mail_checked'] = 1; $userData['is_active'] = 1; $userData['is_deleted'] = 0; } $userTable = new Default_Model_Member(); $userData = $userTable->createNewUser($userData); return $userData; } /** * @param array $val * @param string $verificationVal */ protected function sendConfirmationMail($val, $verificationVal) { $confirmMail = new Default_Plugin_SendMail('tpl_verify_user'); $confirmMail->setTemplateVar('servername', $this->getServerName()); $confirmMail->setTemplateVar('username', $val['username']); $confirmMail->setTemplateVar('verificationlinktext', 'Click here to verify your email address'); $confirmMail->setTemplateVar('verificationlink', 'https://' . $this->getServerName() . '/verification/' . $verificationVal . ''); $confirmMail->setTemplateVar('verificationurl', 'https://' . $this->getServerName() . '/verification/' . $verificationVal); $confirmMail->setReceiverMail($val['mail']); $confirmMail->setFromMail('registration@opendesktop.org'); $confirmMail->send(); } /** * @return mixed */ protected function getServerName() { /** @var Zend_Controller_Request_Http $request */ $request = $this->getRequest(); return $request->getHttpHost(); } /** * @throws Zend_Controller_Action_Exception * @throws Zend_Exception * @throws Zend_Session_Exception */ public function propagatelogoutAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); if (false == Zend_Auth::getInstance()->hasIdentity()) { $this->_helper->json(array('status' => 'ok', 'message' => 'Already logged out.')); } $modelAuth = new Default_Model_Authorization(); $modelAuth->logout(); $this->_helper->json(array('status' => 'ok', 'message' => 'Logout successful.')); } /** * @throws Zend_Cache_Exception * @throws Zend_Controller_Action_Exception * @throws Zend_Exception * @throws Zend_Session_Exception + * @deprecated */ public function logoutAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); if (Zend_Auth::getInstance()->hasIdentity()) { $modelAuth = new Default_Model_Authorization(); $modelAuth->logout(); $modelToken = new Default_Model_SingleSignOnToken(); $data = array( 'remember_me' => false, 'redirect' => $this->getParam('redirect'), 'action' => Default_Model_SingleSignOnToken::ACTION_LOGOUT ); $token_id = $modelToken->createToken($data); setcookie(Default_Model_SingleSignOnToken::ACTION_LOGOUT, $token_id, time() + 120, '/', Local_Tools_ParseDomain::get_domain($this->getRequest()->getHttpHost()), null, true); } if ($this->_request->isXmlHttpRequest()) { $this->_helper->json(array('status' => 'ok', 'message' => 'Logout successful.')); } else { $this->redirect('/'); } } public function init() { parent::init(); // TODO: Change the autogenerated stub $this->getResponse()->clearHeaders(array('Expires', 'Pragma', 'Cache-Control'))->setHeader('Pragma', 'no-cache', true) ->setHeader('Cache-Control', 'private, no-cache, must-revalidate', true); } /** * @throws Zend_Auth_Storage_Exception * @throws Zend_Controller_Action_Exception * @throws Zend_Exception * @throws exception */ public function verificationAction() { $filterInput = new Zend_Filter_Input(array('*' => 'StringTrim', 'vid' => 'Alnum'), array('vid' => array('Alnum', 'presence' => 'required')), $this->getAllParams()); $_vId = $filterInput->getEscaped('vid'); if (!$_vId) { $this->redirect('/'); } $translate = Zend_Registry::get('Zend_Translate'); $this->view->title = $translate->_('member.email.verification.title'); $authModel = new Default_Model_Authorization(); $authUser = $authModel->getAuthUserDataFromUnverified($_vId); if (empty($authUser)) { throw new Zend_Controller_Action_Exception('This member account could not activated. verification id:' . print_r($this->getParam('vid'), true)); } if ($authUser AND (false == empty($authUser->email_checked))) { $this->view->headScript()->appendFile('//www.google.com/recaptcha/api.js'); $this->view->addHelperPath(APPLICATION_LIB . '/Cgsmith/View/Helper', 'Cgsmith\\View\\Helper\\'); $this->view->formRegister = new Default_Form_Register(); $this->view->registerErrMsg = "

Your account has already been activated.

Log in or try to generate a new password for your account.

"; $this->view->overlay = $this->view->render('authorization/registerError.phtml'); $this->_helper->viewRenderer('register'); return; } Zend_Registry::get('logger')->info(__METHOD__ . ' - activate user from email link. (member_id, username): (' . print_r($authUser->member_id, true) . ', ' . print_r($authUser->username, true) . ')'); $modelMember = new Default_Model_Member(); $result = $modelMember->activateMemberFromVerification($authUser->member_id, $_vId); if (false == $result) { throw new Zend_Controller_Action_Exception('Your member account could not activated.'); } Zend_Registry::get('logger')->info(__METHOD__ . ' - user activated. member_id: ' . print_r($authUser->member_id, true)); $modelMember = new Default_Model_Member(); $record = $modelMember->fetchMemberData($authUser->member_id, false); try { $oauth = new Default_Model_Ocs_OAuth(); $oauth->createUserFromArray($record->toArray()); Zend_Registry::get('logger')->debug(__METHOD__ . ' - oauth : ' . implode(PHP_EOL . " - ", $oauth->getMessages())); } catch (Exception $e) { Zend_Registry::get('logger')->err($e->getMessage() . PHP_EOL . $e->getTraceAsString()); } try { $ldap = new Default_Model_Ocs_Ldap(); $ldap->addUserFromArray($record->toArray()); Zend_Registry::get('logger')->debug(__METHOD__ . ' - ldap : ' . implode(PHP_EOL . " - ", $ldap->getMessages())); } catch (Exception $e) { Zend_Registry::get('logger')->err($e->getMessage() . PHP_EOL . $e->getTraceAsString()); } try { $openCode = new Default_Model_Ocs_Gitlab(); $openCode->createUserFromArray($record->toArray()); Zend_Registry::get('logger')->debug(__METHOD__ . ' - opencode : ' . implode(PHP_EOL . " - ", $openCode->getMessages())); } catch (Exception $e) { Zend_Registry::get('logger')->err($e->getMessage() . PHP_EOL . $e->getTraceAsString()); } try { $forum = new Default_Model_Ocs_Forum(); $forum->createUserFromArray($record->toArray()); Zend_Registry::get('logger')->debug(__METHOD__ . ' - forum : ' . implode(PHP_EOL . " - ", $forum->getMessages())); } catch (Exception $e) { Zend_Registry::get('logger')->err($e->getMessage() . PHP_EOL . $e->getTraceAsString()); } Default_Model_ActivityLog::logActivity($authUser->member_id, null, $authUser->member_id, Default_Model_ActivityLog::MEMBER_EMAIL_CONFIRMED, array()); $this->view->member = $authUser; $this->view->username = $authUser->username; $this->view->headScript()->appendFile('//www.google.com/recaptcha/api.js'); $this->view->addHelperPath(APPLICATION_LIB . '/Cgsmith/View/Helper', 'Cgsmith\\View\\Helper\\'); $this->view->form = new Default_Form_Register(); $this->view->overlay = $this->view->render('authorization/registerWelcome.phtml'); $this->storeAuthSessionData($authUser->member_id); $tableProduct = new Default_Model_Project(); $this->view->products = $tableProduct->fetchAllProjectsForMember($authUser->member_id); $this->forward('index', 'settings', 'default', array('member_id' => $authUser->member_id)); } /** * @param string|int $identity * * @throws Zend_Auth_Storage_Exception * @throws exception */ protected function storeAuthSessionData($identity) { $authDataModel = new Default_Model_Authorization(); $authDataModel->storeAuthSessionDataByIdentity($identity); } /** * ppload */ public function pploadloginAction() { $this->_helper->layout()->disableLayout(); // Init identity and credential $identity = null; $credential = null; if (!empty($_REQUEST['identity'])) { $identity = $_REQUEST['identity']; } else { if (!empty($_SERVER['PHP_AUTH_USER'])) { $identity = $_SERVER['PHP_AUTH_USER']; } } if (!empty($_REQUEST['credential'])) { $credential = $_REQUEST['credential']; } else { if (!empty($_SERVER['PHP_AUTH_PW'])) { $credential = $_SERVER['PHP_AUTH_PW']; } } // Authenticate and get user data $response = array('status' => 'error'); if ($identity && $credential) { $authModel = new Default_Model_Authorization(); $authData = $authModel->getAuthDataFromApi($identity, $credential); if (!empty($authData->member_id)) { $response = array( 'status' => 'ok', 'member_id' => $authData->member_id ); } } $this->_helper->json($response); } public function htmlloginAction() { $this->_helper->layout()->disableLayout(); //$this->_helper->viewRenderer->setNoRender(true); } public function validateAction() { $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $this->view->headScript()->appendFile('//www.google.com/recaptcha/api.js'); $this->view->addHelperPath(APPLICATION_LIB . '/Cgsmith/View/Helper', 'Cgsmith\\View\\Helper\\'); $formRegister = new Default_Form_Register(); $name = $this->getParam('name'); $value = $this->getParam('value'); $result = $formRegister->getElement($name)->isValid($value); $this->_helper->json(array('status' => $result, $name => $formRegister->getElement($name)->getMessages())); } /** * @param array $val * * @throws Zend_Exception */ protected function sendAdminNotificationMail($val) { $config = Zend_Registry::get('config'); $receiver = $config->admin->email; $oNotificationMail = new Default_Plugin_SendMail('tpl_newuser_notification'); $oNotificationMail->setReceiverMail($receiver); $oNotificationMail->setTemplateVar('username', $val['username']); $oNotificationMail->send(); } /** * @param array $userData * * @return int */ protected function storeNewUser($userData) { $userTable = new Default_Model_Member(); $userData = $userTable->storeNewUser($userData); return $userData->member_id; } /** * @param int $identity */ protected function updateUsersLastOnline($identity) { $authModel = new Default_Model_Authorization(); $authModel->updateUserLastOnline('member_id', $identity); } private function logLogin() { } } \ No newline at end of file diff --git a/application/modules/default/controllers/HomeController.php b/application/modules/default/controllers/HomeController.php index bd561628a..b27b82bc6 100644 --- a/application/modules/default/controllers/HomeController.php +++ b/application/modules/default/controllers/HomeController.php @@ -1,677 +1,661 @@ . **/ class HomeController extends Local_Controller_Action_DomainSwitch { public function indexAction() { - /** @var Default_Model_ConfigStore $storeConfig */ $storeConfig = Zend_Registry::isRegistered('store_config') ? Zend_Registry::get('store_config') : null; - + if ($storeConfig) { - $this->view->tag_filter = Zend_Registry::isRegistered('config_store_tags') ? Zend_Registry::get('config_store_tags') : null; - - - if($storeConfig->isShowHomepage()) - { - $index = $this->getParam('index'); - if($index) - { - if((int)$index==1){ - $this->_helper->viewRenderer('index-' . $storeConfig->config_id_name.'-test'); - }else{ - $this->_helper->viewRenderer('index-' . $storeConfig->config_id_name.'-test'.$index); + $this->view->tag_filter = Zend_Registry::isRegistered('config_store_tags') ? Zend_Registry::get('config_store_tags') : null; + + if ($storeConfig->isShowHomepage()) { + $index = $this->getParam('index'); + if ($index) { + if ((int)$index == 1) { + $this->_helper->viewRenderer('index-' . $storeConfig->config_id_name . '-test'); + } else { + $this->_helper->viewRenderer('index-' . $storeConfig->config_id_name . '-test' . $index); } - - $this->view->index=$index; - }else{ - $this->_helper->viewRenderer('index-' . $storeConfig->config_id_name); - } - return; - } + $this->view->index = $index; + } else { + $this->_helper->viewRenderer('index-' . $storeConfig->config_id_name); + } + + return; + } } $params = array('ord' => 'latest'); if ($this->hasParam('domain_store_id')) { $params['domain_store_id'] = $this->getParam('domain_store_id'); } - $this->forward('index', 'explore', 'default', $params); + $this->forward('index', 'explore', 'default', $params); } public function startAction() { /** @var Default_Model_ConfigStore $storeConfig */ $storeConfig = Zend_Registry::isRegistered('store_config') ? Zend_Registry::get('store_config') : null; - + if ($storeConfig) { - $this->view->tag_filter = Zend_Registry::isRegistered('config_store_tags') ? Zend_Registry::get('config_store_tags') : null; - if($storeConfig->isShowHomepage()) - { + $this->view->tag_filter = Zend_Registry::isRegistered('config_store_tags') ? Zend_Registry::get('config_store_tags') : null; + if ($storeConfig->isShowHomepage()) { //index-opendesktop-start.phtml view - $this->_helper->viewRenderer('index-' . $storeConfig->config_id_name.'-start'); + $this->_helper->viewRenderer('index-' . $storeConfig->config_id_name . '-start'); + return; } } $params = array('ord' => 'latest'); if ($this->hasParam('domain_store_id')) { $params['domain_store_id'] = $this->getParam('domain_store_id'); } - $this->forward('index', 'explore', 'default', $params); + $this->forward('index', 'explore', 'default', $params); } - public function showfeatureajaxAction() + public function showfeatureajaxAction() { $this->_helper->layout->disableLayout(); $modelInfo = new Default_Model_Info(); - $page = (int)$this->getParam('page'); - $type=''; - if($page==0){ - $featureProducts = $modelInfo->getRandProduct(); - $type=''; - - }elseif($page==1){ - $featureProducts = $modelInfo->getRandFeaturedProduct(); - $type='Featured'; - - } - elseif($page==2){ - $featureProducts = $modelInfo->getRandPlingedProduct(); - $type='Plinged'; + $page = (int)$this->getParam('page'); + $type = ''; + if ($page == 0) { + $featureProducts = $modelInfo->getRandProduct(); + $type = ''; + + } elseif ($page == 1) { + $featureProducts = $modelInfo->getRandFeaturedProduct(); + $type = 'Featured'; + + } elseif ($page == 2) { + $featureProducts = $modelInfo->getRandPlingedProduct(); + $type = 'Plinged'; + + } - } - $this->view->featureProducts = $featureProducts; - $this->view->type=$type; - $this->_helper->viewRenderer('/partials/featuredProducts'); + $this->view->type = $type; + $this->_helper->viewRenderer('/partials/featuredProducts'); } - + public function showlastproductsjsonAction() { $this->_helper->layout->disableLayout(); $modelInfo = new Default_Model_Info(); - $offset = (int)$this->getParam('offset',0); - $limit = (int)$this->getParam('limit',5); + $offset = (int)$this->getParam('offset', 0); + $limit = (int)$this->getParam('limit', 5); $catIds = $this->getParam('catIDs'); $tags = $this->getParam('ptype'); $isOriginal = $this->getParam('isoriginal'); - $response = $modelInfo->getJsonLastProductsForHostStores($limit,$catIds, $tags,$isOriginal,$offset); - $this->_helper->json(Zend_Json::decode($response)); + $response = $modelInfo->getJsonLastProductsForHostStores($limit, $catIds, $tags, $isOriginal, $offset); + $this->_helper->json(Zend_Json::decode($response)); } public function getnewactiveplingedproductjsonAction() { $this->_helper->layout->disableLayout(); $modelInfo = new Default_Model_Info(); - $offset = (int)$this->getParam('offset',0); - $limit = (int)$this->getParam('limit',5); - $response = $modelInfo->getJsonNewActivePlingProduct($limit,$offset); - $this->_helper->json(Zend_Json::decode($response)); + $offset = (int)$this->getParam('offset', 0); + $limit = (int)$this->getParam('limit', 5); + $response = $modelInfo->getJsonNewActivePlingProduct($limit, $offset); + $this->_helper->json(Zend_Json::decode($response)); } public function showfeaturejsonAction() { - - $this->_helper->layout->disableLayout(); + + $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $modelInfo = new Default_Model_Info(); $page = (int)$this->getParam('page'); - if($page==0){ - $featureProducts = $modelInfo->getRandProduct(); + if ($page == 0) { + $featureProducts = $modelInfo->getRandProduct(); + $featureProducts->setItemCountPerPage(1); + $featureProducts->setCurrentPageNumber(1); + } else { + $featureProducts = $modelInfo->getFeaturedProductsForHostStores(100); + if ($featureProducts->getTotalItemCount() > 0) { + $offset = (int)$this->getParam('page'); + $irandom = rand(1, $featureProducts->getTotalItemCount()); $featureProducts->setItemCountPerPage(1); - $featureProducts->setCurrentPageNumber(1); - }else{ - $featureProducts = $modelInfo->getFeaturedProductsForHostStores(100); - if($featureProducts->getTotalItemCount() > 0){ - $offset = (int)$this->getParam('page'); - $irandom = rand(1,$featureProducts->getTotalItemCount()); - $featureProducts->setItemCountPerPage(1); - $featureProducts->setCurrentPageNumber($irandom); - } + $featureProducts->setCurrentPageNumber($irandom); } + } - $item; + $item = null; foreach ($featureProducts as $i) { - $item = $i; - break; - } + $item = $i; + break; + } $helpCategories = new Default_View_Helper_FetchCategoriesForProductAsString(); $response = array( - 'project_id' => $item['project_id'], - 'member_id' => $item['member_id'], - 'username' => $item['username'], - 'profile_image_url' => $item['profile_image_url'], - 'featured' => $item['featured'], - 'description' => $item['description'], - 'title' => $item['title'], - 'category' => $helpCategories->fetchCategoriesForProductAsString($item['project_id']), - 'image_small' => $item['image_small'], - 'laplace_score' => $item['laplace_score'], - 'count_likes' => $item['count_likes'], - 'count_dislikes' => $item['count_dislikes'], - 'changed_at' => $item['changed_at'], - 'created_at' => $item['created_at'], - 'count_comments' => $item['count_comments'] + 'project_id' => $item['project_id'], + 'member_id' => $item['member_id'], + 'username' => $item['username'], + 'profile_image_url' => $item['profile_image_url'], + 'featured' => $item['featured'], + 'description' => $item['description'], + 'title' => $item['title'], + 'category' => $helpCategories->fetchCategoriesForProductAsString($item['project_id']), + 'image_small' => $item['image_small'], + 'laplace_score' => $item['laplace_score'], + 'count_likes' => $item['count_likes'], + 'count_dislikes' => $item['count_dislikes'], + 'changed_at' => $item['changed_at'], + 'created_at' => $item['created_at'], + 'count_comments' => $item['count_comments'] ); - $this->_helper->json($response); + $this->_helper->json($response); } - + public function showspotlightjsonAction() { - - $this->_helper->layout->disableLayout(); + + $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $modelInfo = new Default_Model_Info(); $page = (int)$this->getParam('page'); - $mostplingedcreateor = $modelInfo->getMostPlingedCreators(1,$page); + $mostplingedcreateor = $modelInfo->getMostPlingedCreators(1, $page); $creator = array_pop($mostplingedcreateor); - $helperImage = new Default_View_Helper_Image(); - $creator['profile_image_url'] = $helperImage->Image($creator['profile_image_url'], array('width' => 200, 'height' => 200)); - $products = $modelInfo->getMostPlingedProductsForUser($creator['member_id'],5,0); + $helperImage = new Default_View_Helper_Image(); + $creator['profile_image_url'] = $helperImage->Image($creator['profile_image_url'], + array('width' => 200, 'height' => 200)); + $products = $modelInfo->getMostPlingedProductsForUser($creator['member_id'], 5, 0); foreach ($products as &$p) { - $p['image_small'] = $helperImage->Image($p['image_small'], array('width' => 200, 'height' => 200)); + $p['image_small'] = $helperImage->Image($p['image_small'], array('width' => 200, 'height' => 200)); } - $creator['products'] = $products; - $this->_helper->json($creator); + $creator['products'] = $products; + $this->_helper->json($creator); } public function metamenujsAction() { $this->_helper->layout()->disableLayout(); - - header('Access-Control-Allow-Origin: *'); - + + header('Access-Control-Allow-Origin: *'); + $this->getResponse() ->setHeader('Access-Control-Allow-Origin', '*') ->setHeader('Access-Control-Allow-Credentials', 'true') ->setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') - ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept') - ; - + ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept'); + } public function metamenubundlejsAction() { - $this->_helper->layout()->disableLayout(); + $this->_helper->layout()->disableLayout(); } public function searchmemberAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $username = $this->getParam('username'); $results = null; - if(strlen(trim($username))>2) - { + if (strlen(trim($username)) > 2) { $model = new Default_Model_Member(); $results = $model->findActiveMemberByName($username); $helperImage = new Default_View_Helper_Image(); foreach ($results as &$value) { - $avatar = $helperImage->image($value['profile_image_url'],array('width' => 100, 'height' => 100, 'crop' => 2)); + $avatar = $helperImage->image($value['profile_image_url'], + array('width' => 100, 'height' => 100, 'crop' => 2)); $value['profile_image_url'] = $avatar; } } $this->_helper->json($results); } public function memberjsonAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $member_id = $this->getParam('member_id'); $results = null; - if($member_id){ + if ($member_id) { $info = new Default_Model_Info(); $commentsOpendeskop = $info->getDiscussionOpendeskop($member_id); - $results=array('commentsOpendeskop' => $commentsOpendeskop); + $results = array('commentsOpendeskop' => $commentsOpendeskop); } $this->_helper->json($results); } - - + + public function baseurlajaxAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); - - header('Access-Control-Allow-Origin: *'); - + + header('Access-Control-Allow-Origin: *'); + $this->getResponse() ->setHeader('Access-Control-Allow-Origin', '*') ->setHeader('Access-Control-Allow-Credentials', 'true') ->setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') - ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept') - ; - + ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept'); + $resultArray = array(); - + $baseurl = Zend_Registry::get('config')->settings->client->default->baseurl; $resultArray['base_url'] = $baseurl; - + $resultAll = array(); $resultAll['status'] = "success"; $resultAll['data'] = $resultArray; - + $this->_helper->json($resultAll); } - + public function forumurlajaxAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); - - header('Access-Control-Allow-Origin: *'); - + + header('Access-Control-Allow-Origin: *'); + $this->getResponse() ->setHeader('Access-Control-Allow-Origin', '*') ->setHeader('Access-Control-Allow-Credentials', 'true') ->setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') - ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept') - ; - - + ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept'); + + $resultArray = array(); - + $url_forum = Zend_Registry::get('config')->settings->client->default->url_forum; $resultArray['url_forum'] = $url_forum; - + $resultAll = array(); $resultAll['status'] = "success"; $resultAll['data'] = $resultArray; - + $this->_helper->json($resultAll); } - + public function blogurlajaxAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); - - header('Access-Control-Allow-Origin: *'); - + + header('Access-Control-Allow-Origin: *'); + $this->getResponse() ->setHeader('Access-Control-Allow-Origin', '*') ->setHeader('Access-Control-Allow-Credentials', 'true') ->setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') - ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept') - ; - + ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept'); + $resultArray = array(); - + $url_blog = Zend_Registry::get('config')->settings->client->default->url_blog; $resultArray['url_blog'] = $url_blog; - + $resultAll = array(); $resultAll['status'] = "success"; $resultAll['data'] = $resultArray; - + $this->_helper->json($resultAll); } - - + + public function storenameajaxAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); - - header('Access-Control-Allow-Origin: *'); - + + header('Access-Control-Allow-Origin: *'); + $this->getResponse() ->setHeader('Access-Control-Allow-Origin', '*') ->setHeader('Access-Control-Allow-Credentials', 'true') ->setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') - ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept') - ; - + ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept'); + $resultArray = array(); - - $sname = Zend_Registry::get('store_host'); + + $sname = Zend_Registry::get('store_host'); $resultArray['store_name'] = $sname; - + $resultAll = array(); $resultAll['status'] = "success"; $resultAll['data'] = $resultArray; - + $this->_helper->json($resultAll); } - - + + public function loginurlajaxAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); - - header('Access-Control-Allow-Origin: *'); - + + header('Access-Control-Allow-Origin: *'); + $this->getResponse() ->setHeader('Access-Control-Allow-Origin', '*') ->setHeader('Access-Control-Allow-Credentials', 'true') ->setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') - ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept') - ; - + ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept'); + $resultArray = array(); - + $url = $this->getParam('url'); $filterRedirect = new Local_Filter_Url_Encrypt(); - + $loginUrl = '/login?redirect=' . $filterRedirect->filter($url); - + $resultArray['login_url'] = $loginUrl; - + $resultAll = array(); $resultAll['status'] = "success"; $resultAll['data'] = $resultArray; - + $this->_helper->json($resultAll); } - - - + + public function domainsajaxAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); - - header('Access-Control-Allow-Origin: *'); - + + header('Access-Control-Allow-Origin: *'); + $this->getResponse() ->setHeader('Access-Control-Allow-Origin', '*') ->setHeader('Access-Control-Allow-Credentials', 'true') ->setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') - ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept') - ; - - + ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept'); + + $resultArray = array(); - - + + $domainobjects = $this->fetchMetaheaderMenuJson(); $resultArray['domains'] = $domainobjects; - + $storeobjects = $this->fetchStoresForCatTreeJson(); $resultArray['storefortree'] = $storeobjects; - - + + $resultAll = array(); $resultAll['status'] = "success"; $resultAll['data'] = $resultArray; - + $this->_helper->json($resultAll); } - - protected function setLayout() - { - $storeConfig = Zend_Registry::isRegistered('store_config') ? Zend_Registry::get('store_config') : null; - if($storeConfig && $storeConfig->layout_home) - { - $this->_helper->layout()->setLayout($storeConfig->layout_home); - }else{ - $this->_helper->layout()->setLayout('home_template'); - } - } - - private function fetchMetaheaderMenuJson() - { + { - $sname = Zend_Registry::get('store_host'); + $sname = Zend_Registry::get('store_host'); /** @var Zend_Cache_Core $cache */ - $cache = Zend_Registry::get('cache'); - $cacheName = __FUNCTION__ . md5($sname); + $cache = Zend_Registry::get('cache'); + $cacheName = __FUNCTION__ . md5($sname); if (false == ($domainobjects = $cache->load($cacheName))) { $tbl = new Default_Model_DbTable_ConfigStore(); $result = $tbl->fetchDomainObjects(); - // sort Desktop manuelly to the front + // sort Desktop manuelly to the front $arrayDesktop = array(); - $arrayRest = array(); - + $arrayRest = array(); + foreach ($result as $obj) { - $o = $obj['order']; - $curOrder = floor($obj['order']/1000); - if($curOrder<10 or $curOrder>50) continue; - $obj['calcOrder'] = $curOrder; + $o = $obj['order']; + $curOrder = floor($obj['order'] / 1000); + if ($curOrder < 10 or $curOrder > 50) { + continue; + } + $obj['calcOrder'] = $curOrder; $tmp = array(); $tmp['order'] = $obj['order']; $tmp['calcOrder'] = $obj['calcOrder']; $tmp['host'] = $obj['host']; - $tmp['name'] = $obj['name']; - $tmp['is_show_in_menu'] = $obj['is_show_in_menu']; - $tmp['is_show_real_domain_as_url'] = $obj['is_show_real_domain_as_url']; + $tmp['name'] = $obj['name']; + $tmp['is_show_in_menu'] = $obj['is_show_in_menu']; + $tmp['is_show_real_domain_as_url'] = $obj['is_show_real_domain_as_url']; - if($curOrder==30) { - // Desktop set calcOrder = 9 manuelly put desktop in front + if ($curOrder == 30) { + // Desktop set calcOrder = 9 manuelly put desktop in front $tmp['calcOrder'] = 9; - $arrayDesktop[] = $tmp; - }else{ - $arrayRest[] = $tmp; - } + $arrayDesktop[] = $tmp; + } else { + $arrayRest[] = $tmp; + } } $domainobjects = array_merge($arrayDesktop, $arrayRest); - + $baseurl = Zend_Registry::get('config')->settings->client->default->baseurl; // set group name manully foreach ($domainobjects as &$obj) { - if($sname == $obj['host']){ - $obj['menuactive'] = 1; - }else{ - $obj['menuactive'] = 0; - } + if ($sname == $obj['host']) { + $obj['menuactive'] = 1; + } else { + $obj['menuactive'] = 0; + } - $order = $obj['order']; - //OLD: z.b 150001 ende ==1 go real link otherwise /s/$name - /*$last_char_check = substr($order, -1); - if($last_char_check=='1') - { - $obj['menuhref'] = $obj['host']; - }else{ - $obj['menuhref'] = $baseurl.'/s/'.$obj['name']; - } - * - */ - $domainAsUrl = $obj['is_show_real_domain_as_url']; - if($domainAsUrl) - { - $obj['menuhref'] = $obj['host']; - }else{ - $obj['menuhref'] = $baseurl.'/s/'.$obj['name']; - } + $order = $obj['order']; + //OLD: z.b 150001 ende ==1 go real link otherwise /s/$name + /*$last_char_check = substr($order, -1); + if($last_char_check=='1') + { + $obj['menuhref'] = $obj['host']; + }else{ + $obj['menuhref'] = $baseurl.'/s/'.$obj['name']; + } + * + */ + $domainAsUrl = $obj['is_show_real_domain_as_url']; + if ($domainAsUrl) { + $obj['menuhref'] = $obj['host']; + } else { + $obj['menuhref'] = $baseurl . '/s/' . $obj['name']; + } - switch ($obj['calcOrder']) { - case 9: - $obj['menugroup']='Desktops'; - break; - case 10: - $obj['menugroup']='Applications'; - break; - case 20: - $obj['menugroup']='Addons'; - break; - case 40: - $obj['menugroup']='Artwork'; - break; - case 50: - $obj['menugroup']='Other'; + switch ($obj['calcOrder']) { + case 9: + $obj['menugroup'] = 'Desktops'; break; - } - + case 10: + $obj['menugroup'] = 'Applications'; + break; + case 20: + $obj['menugroup'] = 'Addons'; + break; + case 40: + $obj['menugroup'] = 'Artwork'; + break; + case 50: + $obj['menugroup'] = 'Other'; + break; + } + } $cache->save($domainobjects, $cacheName, array(), 28800); } - return Zend_Json::encode($domainobjects); + + return Zend_Json::encode($domainobjects); } - - - private function fetchStoresForCatTreeJson() - { - $sname = Zend_Registry::get('store_host'); + private function fetchStoresForCatTreeJson() + { + $sname = Zend_Registry::get('store_host'); /** @var Zend_Cache_Core $cache */ - $cache = Zend_Registry::get('cache'); - $cacheName = __FUNCTION__ . md5($sname); + $cache = Zend_Registry::get('cache'); + $cacheName = __FUNCTION__ . md5($sname); - if (false == ($domainobjects = $cache->load($cacheName))) { + if (false == ($domain_objects = $cache->load($cacheName))) { $tbl = new Default_Model_DbTable_ConfigStore(); $result = $tbl->fetchDomainObjects(); - // sort Desktop manuelly to the front + // sort Desktop manually to the front $arrayDesktop = array(); - $arrayRest = array(); - + $arrayRest = array(); + foreach ($result as $obj) { $tmp = array(); $tmp['order'] = $obj['order']; $tmp['calcOrder'] = $obj['calcOrder']; $tmp['host'] = $obj['host']; - $tmp['name'] = $obj['name']; - $tmp['is_show_in_menu'] = $obj['is_show_in_menu']; - $tmp['is_show_real_domain_as_url'] = $obj['is_show_real_domain_as_url']; + $tmp['name'] = $obj['name']; + $tmp['is_show_in_menu'] = $obj['is_show_in_menu']; + $tmp['is_show_real_domain_as_url'] = $obj['is_show_real_domain_as_url']; - $arrayRest[] = $tmp; + $arrayRest[] = $tmp; } - $domainobjects = array_merge($arrayDesktop, $arrayRest); + $domain_objects = array_merge($arrayDesktop, $arrayRest); + - $baseurl = Zend_Registry::get('config')->settings->client->default->baseurl; // set group name manully - foreach ($domainobjects as &$obj) { + foreach ($domain_objects as &$obj) { - if($sname == $obj['host']){ - $obj['menuactive'] = 1; - }else{ - $obj['menuactive'] = 0; - } + if ($sname == $obj['host']) { + $obj['menuactive'] = 1; + } else { + $obj['menuactive'] = 0; + } - $order = $obj['order']; - //OLD: z.b 150001 ende ==1 go real link otherwise /s/$name - /*$last_char_check = substr($order, -1); - if($last_char_check=='1') - { - $obj['menuhref'] = $obj['host']; - }else{ - $obj['menuhref'] = $baseurl.'/s/'.$obj['name']; - } - * - */ - $domainAsUrl = $obj['is_show_real_domain_as_url']; - if($domainAsUrl) - { - $obj['menuhref'] = $obj['host']; - }else{ - $obj['menuhref'] = $baseurl.'/s/'.$obj['name']; - } + $order = $obj['order']; + //OLD: z.b 150001 ende ==1 go real link otherwise /s/$name + /*$last_char_check = substr($order, -1); + if($last_char_check=='1') + { + $obj['menuhref'] = $obj['host']; + }else{ + $obj['menuhref'] = $baseurl.'/s/'.$obj['name']; + } + * + */ + $domainAsUrl = $obj['is_show_real_domain_as_url']; + if ($domainAsUrl) { + $obj['menuhref'] = $obj['host']; + } else { + $obj['menuhref'] = $baseurl . '/s/' . $obj['name']; + } } - $cache->save($domainobjects, $cacheName, array(), 28800); + $cache->save($domain_objects, $cacheName, array(), 28800); } - return Zend_Json::encode($domainobjects); + + return Zend_Json::encode($domain_objects); } - - + /** * @throws Exception * @throws Zend_Exception * @throws Zend_Form_Exception */ public function redirectmeAction() { $this->_helper->layout()->disableLayout(); //$this->_helper->viewRenderer->setNoRender(true); - + $redir = "/"; - if(isset($_GET['redirect'])) { + if (isset($_GET['redirect'])) { $redir = $_GET['redirect']; $filter = new Local_Filter_Url_Decrypt(); $redir = $filter->filter($redir); - + } $this->view->redirect = $redir; } - + public function fetchforgitAction() { $this->_helper->layout()->disableLayout(); - + $tableProject = new Default_Model_Project(); $params = $this->getAllParams(); $action = 'fetch-products-for-git-project-id'; - if($this->hasParam('target')) { + if ($this->hasParam('target')) { $action = $params['target']; } - - if($action == 'fetch-products-for-git-project-id') { - - + + if ($action == 'fetch-products-for-git-project-id') { + + $gitProjectId = $params['project_id']; $this->view->products = null; - if(isset($gitProjectId)) { + if (isset($gitProjectId)) { $products = $tableProject->fetchAll('status = 100 AND type_id = 1 AND is_gitlab_project = 1 AND gitlab_project_id = ' . $gitProjectId); $helperImage = new Default_View_Helper_Image(); $viewArray = array(); $viewProjectArray = array(); foreach ($products as $product) { $viewProjectArray = array(); $viewProjectArray['project_id'] = $product['project_id']; $viewProjectArray['title'] = $product['title']; $viewProjectArray['version'] = $product['version']; $viewProjectArray['member_id'] = $product['member_id']; - $viewProjectArray['avatar'] = $helperImage->Image($product['image_small'], array('width' => 100, 'height' => 100)); + $viewProjectArray['avatar'] = $helperImage->Image($product['image_small'], + array('width' => 100, 'height' => 100)); $viewArray[] = $viewProjectArray; } $this->view->viewdata = $viewArray; } } else { $this->view->viewdata = array(); } - - - + + + } + + protected function setLayout() + { + $storeConfig = Zend_Registry::isRegistered('store_config') ? Zend_Registry::get('store_config') : null; + if ($storeConfig && $storeConfig->layout_home) { + $this->_helper->layout()->setLayout($storeConfig->layout_home); + } else { + $this->_helper->layout()->setLayout('home_template'); + } } } diff --git a/application/modules/default/controllers/LoginController.php b/application/modules/default/controllers/LoginController.php index 3575811bf..6d911baec 100644 --- a/application/modules/default/controllers/LoginController.php +++ b/application/modules/default/controllers/LoginController.php @@ -1,50 +1,75 @@ . * * Created: 30.11.2018 */ class LoginController extends Local_Controller_Action_DomainSwitch { public function setthemeAction() { $this->_helper->layout()->disableLayout(); //$this->_helper->viewRenderer->setNoRender(true); } + public function setAction() + { + $this->_helper->layout()->disableLayout(); + //$this->_helper->viewRenderer->setNoRender(true); + + } + public function fpAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); - $fingerprint = stripslashes(trim($this->getParam('fp'))); + $fp = stripslashes(trim($this->getParam('fp'))); + $ip4 = filter_var(stripslashes(trim($this->getParam('ipv4'))), FILTER_VALIDATE_IP); + $ip6 = filter_var(stripslashes(trim($this->getParam('ipv6'))), FILTER_VALIDATE_IP); + $hash = sha1($fp.$ip4.$ip6); + $request_ip = $this->getRequest()->getClientIp(); + $namespace = new Zend_Session_Namespace(); - Zend_Registry::set('client_fp', $fingerprint); + if ($namespace->stat_hash === $hash) { + $this->_helper->json(array('status' => 'ok')); - $namespace = new Zend_Session_Namespace(); - $namespace->client_fp = $fingerprint; + return; + } + + $namespace->client_fp = $fp; + $namespace->stat_fp = $fp; + $namespace->stat_ipv4 = $ip4 ? $ip4 : null; + $namespace->stat_ipv6 = $ip6 ? $ip6 : null; + $namespace->stat_hash = $hash; + $namespace->stat_request_ip = $request_ip; + $namespace->stat_valid = true; + + foreach ($namespace->getIterator()->getArrayCopy() as $key=>$item) { + Zend_Registry::get('logger')->debug(print_r($key, true).' => '.print_r($item,true)); + }; $this->_helper->json(array('status' => 'ok')); } } \ No newline at end of file diff --git a/application/modules/default/controllers/LogoutController.php b/application/modules/default/controllers/LogoutController.php index 1893968b6..b952e0478 100644 --- a/application/modules/default/controllers/LogoutController.php +++ b/application/modules/default/controllers/LogoutController.php @@ -1,68 +1,64 @@ . * * Created: 10.10.2018 */ class LogoutController extends Local_Controller_Action_DomainSwitch { public function logoutAction() { $this->_helper->layout()->disableLayout(); //$this->_helper->viewRenderer->setNoRender(true); $redir = "/"; if (isset($_GET['redirect'])) { $redir = $_GET['redirect']; $filter = new Local_Filter_Url_Decrypt(); $redir = $filter->filter($redir); } $this->view->redirect = $redir; if (Zend_Auth::getInstance()->hasIdentity()) { $user_id = Zend_Auth::getInstance()->getStorage()->read()->member_id; $modelAuth = new Default_Model_Authorization(); $modelAuth->logout(); - //$modelToken = new Default_Model_SingleSignOnToken(); - //$data = array( - // 'remember_me' => false, - // 'redirect' => $this->getParam('redirect'), - // 'action' => Default_Model_SingleSignOnToken::ACTION_LOGOUT - //); - //$token_id = $modelToken->createToken($data); - //setcookie(Default_Model_SingleSignOnToken::ACTION_LOGOUT, $token_id, time() + 120, '/', - // Local_Tools_ParseDomain::get_domain($this->getRequest()->getHttpHost()), null, true); - - $config = Zend_Registry::get('config')->settings->domain; - - $jwt = Default_Model_Jwt::encode($user_id); - setcookie($config->openid->cookie_name, $jwt, time() - 120, '/', $config->openid->host, null, true); - - setcookie($config->forum->cookie_name, $jwt, time() - 120, '/', $config->forum->host, null, true); - - setcookie($config->opencode->cookie_name, $jwt, time() - 120, '/', $config->opencode->host, null, true); +// $config = Zend_Registry::get('config')->settings->domain; +// +// $jwt = Default_Model_Jwt::encode($user_id); +// setcookie($config->openid->cookie_name, $jwt, time() - 120, '/', $config->openid->host, null, true); +// +// setcookie($config->forum->cookie_name, $jwt, time() - 120, '/', $config->forum->host, null, true); +// +// setcookie($config->opencode->cookie_name, $jwt, time() - 120, '/', $config->opencode->host, null, true); } } + public function setAction() + { + $this->_helper->layout()->disableLayout(); + //$this->_helper->viewRenderer->setNoRender(true); + } + } \ No newline at end of file diff --git a/application/modules/default/controllers/ProductController.php b/application/modules/default/controllers/ProductController.php index 78c669c99..65d4bb901 100644 --- a/application/modules/default/controllers/ProductController.php +++ b/application/modules/default/controllers/ProductController.php @@ -1,3366 +1,3431 @@ . **/ class ProductController extends Local_Controller_Action_DomainSwitch { const IMAGE_SMALL_UPLOAD = 'image_small_upload'; const IMAGE_BIG_UPLOAD = 'image_big_upload'; /** * Zend_Controller_Request_Abstract object wrapping the request environment * * @var Zend_Controller_Request_Http */ protected $_request = null; /** @var int */ protected $_projectId; /** @var int */ protected $_collectionId; /** @var Zend_Auth */ protected $_auth; /** @var string */ protected $_browserTitlePrepend; public function init() { parent::init(); $this->_projectId = (int)$this->getParam('project_id'); $this->_collectionId = (int)$this->getParam('collection_id'); $this->_auth = Zend_Auth::getInstance(); $this->_browserTitlePrepend = $this->templateConfigData['head']['browser_title_prepend']; $action = $this->getRequest()->getActionName(); - $title = $action; - if($action =='add') - { - $title = 'add product'; - }else - { - $title = $action; + $title = $action; + if ($action == 'add') { + $title = 'add product'; + } else { + $title = $action; } $this->view->headTitle($title . ' - ' . $this->getHeadTitle(), 'SET'); } public function ratingAction() { $this->_helper->layout()->disableLayout(); if (array_key_exists($this->_projectId, $this->_authMember->projects)) { return; } $userRating = (int)$this->getParam('rate', 0); $modelRating = new Default_Model_DbTable_ProjectRating(); $modelRating->rateForProject($this->_projectId, $this->_authMember->member_id, $userRating); } public function pploadAction() { $this->_helper->layout->disableLayout(); $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductInfo($this->_projectId); //create ppload download hash: secret + collection_id + expire-timestamp $salt = PPLOAD_DOWNLOAD_SECRET; $collectionID = $productInfo->ppload_collection_id; $timestamp = time() + 3600; // one hour valid //20181009 ronald: change hash from MD5 to SHA512 //$hash = md5($salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying $hash = hash('sha512',$salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying $this->view->download_hash = $hash; $this->view->download_timestamp = $timestamp; $this->view->product = $productInfo; $this->_helper->viewRenderer('/partials/pploadajax'); } - - public function gettaggroupsforcatajaxAction() { + + public function gettaggroupsforcatajaxAction() + { $this->_helper->layout()->disableLayout(); - + $catId = null; $fileId = null; - - if($this->hasParam('file_id')) { + + if ($this->hasParam('file_id')) { $fileId = $this->getParam('file_id'); } - - if($this->hasParam('project_cat_id')) { + + if ($this->hasParam('project_cat_id')) { $catId = $this->getParam('project_cat_id'); - $catTagModel = new Default_Model_Tags(); - $catTagGropuModel = new Default_Model_TagGroup(); + $catTagModel = new Default_Model_Tags(); + $catTagGropuModel = new Default_Model_TagGroup(); $tagGroups = $catTagGropuModel->fetchTagGroupsForCategory($catId); - + $tableTags = new Default_Model_DbTable_Tags(); - + $result = array(); $resultGroup = array(); - + foreach ($tagGroups as $group) { - $tags = $tableTags->fetchForGroupForSelect($group['tag_group_id']); + $tags = $tableTags->fetchForGroupForSelect($group['tag_group_id']); $selectedTags = null; - if(!empty($fileId)) { - $selectedTags = $catTagModel->getTagsArray($fileId, Default_Model_DbTable_Tags::TAG_TYPE_FILE,$group['tag_group_id']); + if (!empty($fileId)) { + $selectedTags = $catTagModel->getTagsArray($fileId, Default_Model_DbTable_Tags::TAG_TYPE_FILE, $group['tag_group_id']); } - + $group['tag_list'] = $tags; $group['selected_tags'] = $selectedTags; $result[] = $group; } - + $this->_helper->json(array('status' => 'ok', 'ResultSize' => count($tagGroups), 'tag_groups' => $result)); return; } $this->_helper->json(array('status' => 'error')); } - - private function getTagGroupsForCat($fileId) { - $modelProduct = new Default_Model_Project(); - $productInfo = $modelProduct->fetchProductInfo($this->_projectId); - $catId = $productInfo->project_category_id; - - if(!empty($catId)) { - $catTagModel = new Default_Model_Tags(); - $catTagGropuModel = new Default_Model_TagGroup(); - $tagGroups = $catTagGropuModel->fetchTagGroupsForCategory($catId); - - $tableTags = new Default_Model_DbTable_Tags(); - - $result = array(); - - foreach ($tagGroups as $group) { - $tags = $tableTags->fetchForGroupForSelect($group['tag_group_id']); - $selectedTags = null; - if(!empty($fileId)) { - $selectedTags = $catTagModel->getTagsArray($fileId, Default_Model_DbTable_Tags::TAG_TYPE_FILE,$group['tag_group_id']); - } - - $group['tag_list'] = $tags; - $group['selected_tags'] = $selectedTags; - $result[] = $group; - } - - return $result; - } - - return null; - } - - - private function getFileDownloadCount($collection_id, $fileId) { - $modelFiles = new Default_Model_DbTable_PploadFiles(); - - $countAll = $modelFiles->fetchCountDownloadsForFileAllTime($collection_id, $fileId); - $countToday = $modelFiles->fetchCountDownloadsForFileToday($collection_id, $fileId); - - $count = (int)$countAll+ (int)$countToday; - return $count; - } - + public function listsamesourceurlAction() - { + { $this->_helper->layout()->disableLayout(); - $this->_helper->viewRenderer->setNoRender(true); - $modelProduct = new Default_Model_Project(); - $productInfo = $modelProduct->fetchProductInfo($this->_projectId); + $this->_helper->viewRenderer->setNoRender(true); + $modelProduct = new Default_Model_Project(); + $productInfo = $modelProduct->fetchProductInfo($this->_projectId); $result = $modelProduct->getSourceUrlProjects($productInfo->source_url); $r = '
'; foreach ($result as $value) { - $r=$r.'
' - .'
'.$value['title'].'
' - .'' - .'
'.$value['created_at'].'
' - .'
'.$value['changed_at'].'
' - .'
'; + $r = $r . '
' + . '
' . $value['title'] . '
' + . '' + . '
' . $value['created_at'] . '
' + . '
' . $value['changed_at'] . '
' + . '
'; } - $r = $r.'
'; - - + $r = $r . ''; + + /*$response='';*/ echo $r; - } - - - - public function getfilesajaxAction() { + } + + public function getfilesajaxAction() + { $this->_helper->layout()->disableLayout(); - + $collection_id = null; $file_status = null; $ignore_status_code = null; - + $helperUserRole = new Backend_View_Helper_UserRole(); $userRoleName = $helperUserRole->userRole(); - - if($this->hasParam('status')) { + + if ($this->hasParam('status')) { $file_status = $this->getParam('status'); } - if($this->hasParam('ignore_status_code')) { + if ($this->hasParam('ignore_status_code')) { $ignore_status_code = $this->getParam('ignore_status_code'); } - + $filesTable = new Default_Model_DbTable_PploadFiles(); - - if($this->hasParam('collection_id')) { + + if ($this->hasParam('collection_id')) { $collection_id = $this->getParam('collection_id'); $result = array(); $isForAdmin = false; if ($userRoleName == Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN) { $isForAdmin = true; } - + //Load files from DB - if($ignore_status_code == 0 && $file_status == 'active') { + if ($ignore_status_code == 0 && $file_status == 'active') { $files = $filesTable->fetchAllActiveFilesForProject($collection_id, $isForAdmin); } else { $files = $filesTable->fetchAllFilesForProject($collection_id, $isForAdmin); } - + //Check, if the project category has tag-grous $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductInfo($this->_projectId); - $catTagGropuModel = new Default_Model_TagGroup(); + $catTagGropuModel = new Default_Model_TagGroup(); $tagGroups = $catTagGropuModel->fetchTagGroupsForCategory($productInfo->project_category_id); foreach ($files as $file) { //add tag grous, if needed - if(!empty($tagGroups)) { + if (!empty($tagGroups)) { $groups = $this->getTagGroupsForCat($file['id']); $file['tag_groups'] = $groups; } - + //Download Counter - + //new counter IP based $counterUkAll = $file['count_dl_all_uk']; $counterNoUkAll = $file['count_dl_all_nouk']; $counterUkToday = $file['count_dl_uk_today']; $counterNew = 0; - if(!empty($counterUkAll)) { + if (!empty($counterUkAll)) { $counterNew = $counterNew + $counterUkAll; } - if(!empty($counterUkToday)) { + if (!empty($counterUkToday)) { $counterNew = $counterNew + $counterUkToday; } - if(!empty($counterNoUkAll)) { + if (!empty($counterNoUkAll)) { $counterNew = $counterNew + $counterNoUkAll; } $file['downloaded_count_uk'] = $counterNew; if ($userRoleName == Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN) { //$file['downloaded_count_live'] = $this->getFileDownloadCount($collection_id, $file['id']); $counterToday = $file['count_dl_today']; $counterAll = $file['count_dl_all']; $counter = 0; - if(!empty($counterToday)) { + if (!empty($counterToday)) { $counter = $counterToday; } - if(!empty($counterAll)) { + if (!empty($counterAll)) { $counter = $counter + $counterAll; } $file['downloaded_count_live'] = $counter; } else { unset($file['count_dl_all']); unset($file['count_dl_all_nouk']); unset($file['count_dl_all_uk']); unset($file['count_dl_uk_today']); unset($file['count_dl_today']); unset($file['downloaded_count']); } $result[] = $file; } - - $this->_helper->json(array('status' => 'success', 'ResultSize' => count($result), 'files' => $result)); - - return; - } - $this->_helper->json(array('status' => 'error')); - } - - - public function getfiletagsajaxAction() { - $this->_helper->layout()->disableLayout(); - - $fileId = null; - - if($this->hasParam('file_id')) { - $fileId = $this->getParam('file_id'); - - $tagModel = new Default_Model_Tags(); - $fileTags = $tagModel->getFileTags($fileId); - - $this->_helper->json(array('status' => 'ok', 'ResultSize' => count($fileTags), 'file_tags' => $fileTags)); + $this->_helper->json(array('status' => 'success', 'ResultSize' => count($result), 'files' => $result)); return; } $this->_helper->json(array('status' => 'error')); } - + private function getTagGroupsForCat($fileId) + { + $modelProduct = new Default_Model_Project(); + $productInfo = $modelProduct->fetchProductInfo($this->_projectId); + $catId = $productInfo->project_category_id; - public function initJsonForReact(){ - $modelProduct = new Default_Model_Project(); - $productInfo = $modelProduct->fetchProductInfo($this->_projectId); - $this->view->product = $productInfo; - if (empty($this->view->product)) { - throw new Zend_Controller_Action_Exception('This page does not exist', 404); - } + if (!empty($catId)) { + $catTagModel = new Default_Model_Tags(); + $catTagGropuModel = new Default_Model_TagGroup(); + $tagGroups = $catTagGropuModel->fetchTagGroupsForCategory($catId); - if(null != $this->_authMember) { - $this->view->authMemberJson = Zend_Json::encode( Default_Model_Member::cleanAuthMemberForJson($this->_authMember) ); - } + $tableTags = new Default_Model_DbTable_Tags(); - $helpAddDefaultScheme = new Default_View_Helper_AddDefaultScheme(); - $this->view->product->title = Default_Model_HtmlPurify::purify($this->view->product->title); - $this->view->product->description = Default_Model_BBCode::renderHtml(Default_Model_HtmlPurify::purify($this->view->product->description)); - $this->view->product->version = Default_Model_HtmlPurify::purify($this->view->product->version); - $this->view->product->link_1 = Default_Model_HtmlPurify::purify($helpAddDefaultScheme->addDefaultScheme($this->view->product->link_1),Default_Model_HtmlPurify::ALLOW_URL); - $this->view->product->source_url = Default_Model_HtmlPurify::purify($this->view->product->source_url,Default_Model_HtmlPurify::ALLOW_URL); - $this->view->product->facebook_code = Default_Model_HtmlPurify::purify($this->view->product->facebook_code,Default_Model_HtmlPurify::ALLOW_URL); - $this->view->product->twitter_code = Default_Model_HtmlPurify::purify($this->view->product->twitter_code,Default_Model_HtmlPurify::ALLOW_URL); - $this->view->product->google_code = Default_Model_HtmlPurify::purify($this->view->product->google_code,Default_Model_HtmlPurify::ALLOW_URL); - $this->view->productJson = Zend_Json::encode(Default_Model_Collection::cleanProductInfoForJson($this->view->product) ); - - $fmodel =new Default_Model_DbTable_PploadFiles(); - $files = $fmodel->fetchFilesForProject($this->view->product->ppload_collection_id); + $result = array(); - $salt = PPLOAD_DOWNLOAD_SECRET; - - $filesList = array(); - - foreach ($files as $file) { - $timestamp = time() + 3600; // one hour valid - $hash = hash('sha512',$salt . $file['collection_id'] . $timestamp); // order isn't important at all... just do the same when verifying - $url = PPLOAD_API_URI . 'files/download/id/' . $file['id'] . '/s/' . $hash . '/t/' . $timestamp; - if(null != $this->_authMember) { - $url .= '/u/' . $this->_authMember->member_id; + foreach ($tagGroups as $group) { + $tags = $tableTags->fetchForGroupForSelect($group['tag_group_id']); + $selectedTags = null; + if (!empty($fileId)) { + $selectedTags = $catTagModel->getTagsArray($fileId, Default_Model_DbTable_Tags::TAG_TYPE_FILE, + $group['tag_group_id']); } - $url .= '/lt/filepreview/' . $file['name']; - $file['url'] = urlencode($url); - $filesList[] = $file; - } - - $this->view->filesJson = Zend_Json::encode($filesList); - $this->view->filesCntJson = Zend_Json::encode($fmodel->fetchFilesCntForProject($this->view->product->ppload_collection_id)); - - $tableProjectUpdates = new Default_Model_ProjectUpdates(); - $this->view->updatesJson = Zend_Json::encode($tableProjectUpdates->fetchProjectUpdates($this->_projectId)); - $tableProjectRatings = new Default_Model_DbTable_ProjectRating(); - $ratings = $tableProjectRatings->fetchRating($this->_projectId); - $cntRatingsActive = 0; - foreach ($ratings as $p) { - if($p['rating_active']==1) $cntRatingsActive =$cntRatingsActive+1; - } - $this->view->ratingsJson = Zend_Json::encode($ratings); - $this->view->cntRatingsActiveJson = Zend_Json::encode($cntRatingsActive); - - $identity = Zend_Auth::getInstance()->getStorage()->read(); - if (Zend_Auth::getInstance()->hasIdentity()){ - $ratingOfUserJson = $tableProjectRatings->getProjectRateForUser($this->_projectId,$identity->member_id); - $this->view->ratingOfUserJson = Zend_Json::encode($ratingOfUserJson); - }else{ - $this->view->ratingOfUserJson = Zend_Json::encode(null); + + $group['tag_list'] = $tags; + $group['selected_tags'] = $selectedTags; + $result[] = $group; } - $tableProjectFollower = new Default_Model_DbTable_ProjectFollower(); - $likes = $tableProjectFollower->fetchLikesForProject($this->_projectId); - $this->view->likeJson = Zend_Json::encode($likes); - $projectplings = new Default_Model_ProjectPlings(); - $plings = $projectplings->fetchPlingsForProject($this->_projectId); - $this->view->projectplingsJson = Zend_Json::encode($plings); + return $result; + } - $tableProject = new Default_Model_Project(); - $galleryPictures = $tableProject->getGalleryPictureSources($this->_projectId); - $this->view->galleryPicturesJson = Zend_Json::encode($galleryPictures); + return null; + } - $tagmodel = new Default_Model_Tags(); - $tagsuser = $tagmodel->getTagsUser($this->_projectId, Default_Model_Tags::TAG_TYPE_PROJECT); - $tagssystem = $tagmodel->getTagsSystemList($this->_projectId); - $this->view->tagsuserJson = Zend_Json::encode($tagsuser); - $this->view->tagssystemJson = Zend_Json::encode($tagssystem); + public function getfiletagsajaxAction() + { + $this->_helper->layout()->disableLayout(); - $modelComments = new Default_Model_ProjectComments(); - $offset = 0; - $testComments = $modelComments->getCommentTreeForProjectList($this->_projectId); - $this->view->commentsJson = Zend_Json::encode($testComments); + $fileId = null; - $modelClone = new Default_Model_ProjectClone(); - $origins = $modelClone->fetchOrigins($this->_projectId); - $this->view->originsJson = Zend_Json::encode($origins); - $related = $modelClone->fetchRelatedProducts($this->_projectId); - $this->view->relatedJson = Zend_Json::encode($related); + if ($this->hasParam('file_id')) { + $fileId = $this->getParam('file_id'); - $moreProducts = $tableProject->fetchMoreProjects($this->view->product, 8); - $this->view->moreProductsJson = Zend_Json::encode($moreProducts); + $tagModel = new Default_Model_Tags(); + $fileTags = $tagModel->getFileTags($fileId); - $moreProducts = $tableProject->fetchMoreProjectsOfOtherUsr($this->view->product, 8); - $this->view->moreProductsOfOtherUsrJson = Zend_Json::encode($moreProducts); + $this->_helper->json(array('status' => 'ok', 'ResultSize' => count($fileTags), 'file_tags' => $fileTags)); + return; + } + $this->_helper->json(array('status' => 'error')); + } + public function showAction() + { + $this->view->authMember = $this->_authMember; + $this->_helper->viewRenderer('index'); + $this->indexAction(); } public function indexAction() - { + { if (!empty($this->_collectionId)) { $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductForCollectionId($this->_collectionId); $this->_projectId = $productInfo->project_id; } if (empty($this->_projectId)) { $this->redirect('/explore'); } $this->view->paramPageId = (int)$this->getParam('page'); $this->view->member_id = null; - if(null != $this->_authMember && null != $this->_authMember->member_id) { + if (null != $this->_authMember && null != $this->_authMember->member_id) { $this->view->member_id = $this->_authMember->member_id; } - // $this->fetchDataForIndexView(); - + // $this->fetchDataForIndexView(); + $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductInfo($this->_projectId); if (empty($productInfo)) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } - + //Check if this is a collection - if($productInfo->type_id == $modelProduct::PROJECT_TYPE_COLLECTION) { - $this->redirect('/c/'.$this->_projectId); + if ($productInfo->type_id == $modelProduct::PROJECT_TYPE_COLLECTION) { + $this->redirect('/c/' . $this->_projectId); } - + $this->view->product = $productInfo; $this->view->headTitle($productInfo->title . ' - ' . $this->getHeadTitle(), 'SET'); $this->view->cat_id = $this->view->product->project_category_id; - $tagGroupFilter = Zend_Registry::isRegistered('config_store_taggroups') ? Zend_Registry::get('config_store_taggroups') : null; - if(!empty($tagGroupFilter)) { + $tagGroupFilter = Zend_Registry::isRegistered('config_store_taggroups') ? Zend_Registry::get('config_store_taggroups') : null; + if (!empty($tagGroupFilter)) { $filterArray = array(); foreach ($tagGroupFilter as $tagGroupId) { $inputFilter = $this->getFilterTagFromCookie($tagGroupId); $filterArray[$tagGroupId] = $inputFilter; } $this->view->tag_group_filter = $filterArray; } - + //create ppload download hash: secret + collection_id + expire-timestamp $salt = PPLOAD_DOWNLOAD_SECRET; $collectionID = $this->view->product->ppload_collection_id; $timestamp = time() + 3600; // one hour valid //20181009 ronald: change hash from MD5 to SHA512 //$hash = md5($salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying - $hash = hash('sha512',$salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying + $hash = hash('sha512', + $salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying $this->view->download_hash = $hash; $this->view->download_timestamp = $timestamp; - - + $helperUserRole = new Backend_View_Helper_UserRole(); $userRoleName = $helperUserRole->userRole(); $isAdmin = false; if (Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN == $userRoleName) { $isAdmin = true; } - $helperUserIsOwner = new Default_View_Helper_UserIsOwner(); $helperIsProjectActive = new Default_View_Helper_IsProjectActive(); if (!$isAdmin AND (false === $helperIsProjectActive->isProjectActive($this->view->product->project_status)) - AND (false === $helperUserIsOwner->UserIsOwner($this->view->product->member_id)) + AND (false === $helperUserIsOwner->UserIsOwner($this->view->product->member_id)) ) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } if (APPLICATION_ENV != 'searchbotenv') { + Default_Model_Views::saveViewProduct($this->_projectId); + $tablePageViews = new Default_Model_DbTable_StatPageViews(); $tablePageViews->savePageView($this->_projectId, $this->getRequest()->getClientIp(), $this->_authMember->member_id); } - - $fmodel =new Default_Model_DbTable_PploadFiles(); - + + $fmodel = new Default_Model_DbTable_PploadFiles(); + $filesList = array(); - - if(isset($this->view->product->ppload_collection_id)) { + + if (isset($this->view->product->ppload_collection_id)) { $files = $fmodel->fetchFilesForProject($this->view->product->ppload_collection_id); - if(!empty($files)) { + if (!empty($files)) { foreach ($files as $file) { $timestamp = time() + 3600; // one hour valid - $hash = hash('sha512',$salt . $file['collection_id'] . $timestamp); // order isn't important at all... just do the same when verifying + $hash = hash('sha512', + $salt . $file['collection_id'] . $timestamp); // order isn't important at all... just do the same when verifying $url = PPLOAD_API_URI . 'files/download/id/' . $file['id'] . '/s/' . $hash . '/t/' . $timestamp; - if(null != $this->_authMember) { + if (null != $this->_authMember) { $url .= '/u/' . $this->_authMember->member_id; } $url .= '/lt/filepreview/' . $file['name']; $file['url'] = urlencode($url); - + //If this file is a video, we have to convert it for preview - if(!empty($file['type']) && in_array($file['type'], Backend_Commands_ConvertVideo::$VIDEO_FILE_TYPES) && empty($file['ppload_file_preview_id'])) { + if (!empty($file['type']) && in_array($file['type'], + Backend_Commands_ConvertVideo::$VIDEO_FILE_TYPES) && empty($file['ppload_file_preview_id'])) { $queue = Local_Queue_Factory::getQueue(); - $command = new Backend_Commands_ConvertVideo($file['collection_id'], $file['id'], $file['type']); + $command = new Backend_Commands_ConvertVideo($file['collection_id'], $file['id'], + $file['type']); $queue->send(serialize($command)); } - - if(!empty($file['url_preview'])) { + + if (!empty($file['url_preview'])) { $file['url_preview'] = urlencode($file['url_preview']); } - if(!empty($file['url_thumb'])) { + if (!empty($file['url_thumb'])) { $file['url_thumb'] = urlencode($file['url_thumb']); } - + $filesList[] = $file; } } } $this->view->filesJson = Zend_Json::encode($filesList); - + //gitlab - if($this->view->product->is_gitlab_project) { + if ($this->view->product->is_gitlab_project) { $gitProject = $this->fetchGitlabProject($this->view->product->gitlab_project_id); - if(null == $gitProject) { + if (null == $gitProject) { $this->view->product->is_gitlab_project = 0; $this->view->product->show_gitlab_project_issues = 0; $this->view->product->use_gitlab_project_readme = 0; $this->view->product->gitlab_project_id = null; } else { $this->view->gitlab_project = $gitProject; //show issues? - if($this->view->product->show_gitlab_project_issues) { + if ($this->view->product->show_gitlab_project_issues) { $issues = $this->fetchGitlabProjectIssues($this->view->product->gitlab_project_id); $this->view->gitlab_project_issues = $issues; $this->view->gitlab_project_issues_url = $this->view->gitlab_project['web_url'] . '/issues/'; } //show readme.md? - if($this->view->product->use_gitlab_project_readme && null != $this->view->gitlab_project['readme_url']) { + if ($this->view->product->use_gitlab_project_readme && null != $this->view->gitlab_project['readme_url']) { $config = Zend_Registry::get('config')->settings->server->opencode; - $readme = $this->view->gitlab_project['web_url'].'/raw/master/README.md?inline=false'; + $readme = $this->view->gitlab_project['web_url'] . '/raw/master/README.md?inline=false'; $httpClient = new Zend_Http_Client($readme, array('keepalive' => true, 'strictredirects' => true)); $httpClient->resetParameters(); $httpClient->setUri($readme); $httpClient->setHeaders('Private-Token', $config->private_token); $httpClient->setHeaders('Sudo', $config->user_sudo); $httpClient->setHeaders('User-Agent', $config->user_agent); $httpClient->setMethod(Zend_Http_Client::GET); $response = $httpClient->request(); $body = $response->getRawBody(); if (count($body) == 0) { return array(); } include_once('Parsedown.php'); $Parsedown = new Parsedown(); $this->view->readme = $Parsedown->text($body); } else { $this->view->readme = null; } } } - + // products related $pc = new Default_Model_ProjectClone(); - $cntRelatedProducts=0; + $cntRelatedProducts = 0; $ancesters = $pc->fetchAncestersIds($this->_projectId); //$siblings = $pc->fetchSiblings($this->_projectId); //$parents = $pc->fetchParentIds($this->_projectId); - if($ancesters && strlen($ancesters)>0){ + if ($ancesters && strlen($ancesters) > 0) { $parents = $pc->fetchParentLevelRelatives($this->_projectId); - }else{ + } else { $parents = $pc->fetchParentIds($this->_projectId); } - if($parents && strlen($parents)>0) - { - $siblings = $pc->fetchSiblingsLevelRelatives($parents, $this->_projectId); - }else - { + if ($parents && strlen($parents) > 0) { + $siblings = $pc->fetchSiblingsLevelRelatives($parents, $this->_projectId); + } else { $siblings = null; - } - $childrens = $pc->fetchChildrensIds($this->_projectId); + } + $childrens = $pc->fetchChildrensIds($this->_projectId); $childrens2 = null; $childrens3 = null; - if(strlen($childrens)>0) - { + if (strlen($childrens) > 0) { $childrens2 = $pc->fetchChildrensChildrenIds($childrens); - if(strlen($childrens2)>0) - { + if (strlen($childrens2) > 0) { $childrens3 = $pc->fetchChildrensChildrenIds($childrens2); } } $this->view->related_ancesters = null; $this->view->related_siblings = null; $this->view->related_parents = null; $this->view->related_children = null; $this->view->related_children2 = null; $this->view->related_children3 = null; - if($ancesters && strlen($ancesters)>0){ + if ($ancesters && strlen($ancesters) > 0) { $pts = $modelProduct->fetchProjects($ancesters); - $this->view->related_ancesters = sizeof($pts)==0?null:$pts; - $cntRelatedProducts+= sizeof($pts); + $this->view->related_ancesters = sizeof($pts) == 0 ? null : $pts; + $cntRelatedProducts += sizeof($pts); } - if($siblings && strlen($siblings)>0){ + if ($siblings && strlen($siblings) > 0) { $pts = $modelProduct->fetchProjects($siblings); - $this->view->related_siblings = sizeof($pts)==0?null:$pts; - $cntRelatedProducts+= sizeof($pts); + $this->view->related_siblings = sizeof($pts) == 0 ? null : $pts; + $cntRelatedProducts += sizeof($pts); } - if($parents && strlen($parents)>0){ + if ($parents && strlen($parents) > 0) { $pts = $modelProduct->fetchProjects($parents); - $this->view->related_parents = sizeof($pts)==0?null:$pts; - $cntRelatedProducts+= sizeof($pts); + $this->view->related_parents = sizeof($pts) == 0 ? null : $pts; + $cntRelatedProducts += sizeof($pts); } - if($childrens && strlen($childrens)>0){ + if ($childrens && strlen($childrens) > 0) { $pts = $modelProduct->fetchProjects($childrens); - $this->view->related_children = sizeof($pts)==0?null:$pts; - $cntRelatedProducts+= sizeof($pts); + $this->view->related_children = sizeof($pts) == 0 ? null : $pts; + $cntRelatedProducts += sizeof($pts); } - if($childrens2 && strlen($childrens2)>0){ + if ($childrens2 && strlen($childrens2) > 0) { $pts = $modelProduct->fetchProjects($childrens2); - $this->view->related_children2 = sizeof($pts)==0?null:$pts; - $cntRelatedProducts+= sizeof($pts); + $this->view->related_children2 = sizeof($pts) == 0 ? null : $pts; + $cntRelatedProducts += sizeof($pts); } - if($childrens3 && strlen($childrens3)>0){ + if ($childrens3 && strlen($childrens3) > 0) { $pts = $modelProduct->fetchProjects($childrens3); - $this->view->related_children3 = sizeof($pts)==0?null:$pts; - $cntRelatedProducts+= sizeof($pts); + $this->view->related_children3 = sizeof($pts) == 0 ? null : $pts; + $cntRelatedProducts += sizeof($pts); } $this->view->cntRelatedProducts = $cntRelatedProducts; - - $storeConfig = Zend_Registry::isRegistered('store_config') ? Zend_Registry::get('store_config') : null; - if($storeConfig->layout_pagedetail && $storeConfig->isRenderReact()){ - $this->initJsonForReact(); - $this->_helper->viewRenderer('index-react'); + + $storeConfig = Zend_Registry::isRegistered('store_config') ? Zend_Registry::get('store_config') : null; + if ($storeConfig->layout_pagedetail && $storeConfig->isRenderReact()) { + $this->initJsonForReact(); + $this->_helper->viewRenderer('index-react'); } } - public function showAction() + private function getFilterTagFromCookie($group) { - $this->view->authMember = $this->_authMember; - $this->_helper->viewRenderer('index'); - $this->indexAction(); + $config = Zend_Registry::get('config'); + $cookieName = $config->settings->session->filter_browse_original . $group; + + $storedInCookie = isset($_COOKIE[$cookieName]) ? $_COOKIE[$cookieName] : null; + + return $storedInCookie; + } + + private function fetchGitlabProject($gitProjectId) + { + $gitlab = new Default_Model_Ocs_Gitlab(); + + try { + $gitProject = $gitlab->getProject($gitProjectId); + } catch (Exception $exc) { + //Project is gone + $modelProject = new Default_Model_Project(); + $modelProject->updateProject($this->_projectId, array( + 'is_gitlab_project' => 0, + 'gitlab_project_id' => null, + 'show_gitlab_project_issues' => 0, + 'use_gitlab_project_readme' => 0 + )); + $gitProject = null; + } + + return $gitProject; + } + + private function fetchGitlabProjectIssues($gitProjectId) + { + $gitlab = new Default_Model_Ocs_Gitlab(); + + try { + $gitProjectIssues = $gitlab->getProjectIssues($gitProjectId); + } catch (Exception $exc) { + //Project is gone + $modelProject = new Default_Model_Project(); + $modelProject->updateProject($this->_projectId, array( + 'is_gitlab_project' => 0, + 'gitlab_project_id' => null, + 'show_gitlab_project_issues' => 0, + 'use_gitlab_project_readme' => 0 + )); + + $gitProjectIssues = null; + } + + + return $gitProjectIssues; } + public function initJsonForReact() + { + $modelProduct = new Default_Model_Project(); + $productInfo = $modelProduct->fetchProductInfo($this->_projectId); + $this->view->product = $productInfo; + if (empty($this->view->product)) { + throw new Zend_Controller_Action_Exception('This page does not exist', 404); + } + + if (null != $this->_authMember) { + $this->view->authMemberJson = Zend_Json::encode(Default_Model_Member::cleanAuthMemberForJson($this->_authMember)); + } + + $helpAddDefaultScheme = new Default_View_Helper_AddDefaultScheme(); + $this->view->product->title = Default_Model_HtmlPurify::purify($this->view->product->title); + $this->view->product->description = Default_Model_BBCode::renderHtml(Default_Model_HtmlPurify::purify($this->view->product->description)); + $this->view->product->version = Default_Model_HtmlPurify::purify($this->view->product->version); + $this->view->product->link_1 = Default_Model_HtmlPurify::purify($helpAddDefaultScheme->addDefaultScheme($this->view->product->link_1), + Default_Model_HtmlPurify::ALLOW_URL); + $this->view->product->source_url = Default_Model_HtmlPurify::purify($this->view->product->source_url, + Default_Model_HtmlPurify::ALLOW_URL); + $this->view->product->facebook_code = Default_Model_HtmlPurify::purify($this->view->product->facebook_code, + Default_Model_HtmlPurify::ALLOW_URL); + $this->view->product->twitter_code = Default_Model_HtmlPurify::purify($this->view->product->twitter_code, + Default_Model_HtmlPurify::ALLOW_URL); + $this->view->product->google_code = Default_Model_HtmlPurify::purify($this->view->product->google_code, + Default_Model_HtmlPurify::ALLOW_URL); + $this->view->productJson = Zend_Json::encode(Default_Model_Collection::cleanProductInfoForJson($this->view->product)); + + $fmodel = new Default_Model_DbTable_PploadFiles(); + $files = $fmodel->fetchFilesForProject($this->view->product->ppload_collection_id); + + $salt = PPLOAD_DOWNLOAD_SECRET; + + $filesList = array(); + + foreach ($files as $file) { + $timestamp = time() + 3600; // one hour valid + $hash = hash('sha512', + $salt . $file['collection_id'] . $timestamp); // order isn't important at all... just do the same when verifying + $url = PPLOAD_API_URI . 'files/download/id/' . $file['id'] . '/s/' . $hash . '/t/' . $timestamp; + if (null != $this->_authMember) { + $url .= '/u/' . $this->_authMember->member_id; + } + $url .= '/lt/filepreview/' . $file['name']; + $file['url'] = urlencode($url); + $filesList[] = $file; + } + + $this->view->filesJson = Zend_Json::encode($filesList); + $this->view->filesCntJson = Zend_Json::encode($fmodel->fetchFilesCntForProject($this->view->product->ppload_collection_id)); + + $tableProjectUpdates = new Default_Model_ProjectUpdates(); + $this->view->updatesJson = Zend_Json::encode($tableProjectUpdates->fetchProjectUpdates($this->_projectId)); + $tableProjectRatings = new Default_Model_DbTable_ProjectRating(); + $ratings = $tableProjectRatings->fetchRating($this->_projectId); + $cntRatingsActive = 0; + foreach ($ratings as $p) { + if ($p['rating_active'] == 1) { + $cntRatingsActive = $cntRatingsActive + 1; + } + } + $this->view->ratingsJson = Zend_Json::encode($ratings); + $this->view->cntRatingsActiveJson = Zend_Json::encode($cntRatingsActive); + + $identity = Zend_Auth::getInstance()->getStorage()->read(); + if (Zend_Auth::getInstance()->hasIdentity()) { + $ratingOfUserJson = $tableProjectRatings->getProjectRateForUser($this->_projectId, $identity->member_id); + $this->view->ratingOfUserJson = Zend_Json::encode($ratingOfUserJson); + } else { + $this->view->ratingOfUserJson = Zend_Json::encode(null); + } + $tableProjectFollower = new Default_Model_DbTable_ProjectFollower(); + $likes = $tableProjectFollower->fetchLikesForProject($this->_projectId); + $this->view->likeJson = Zend_Json::encode($likes); + + $projectplings = new Default_Model_ProjectPlings(); + $plings = $projectplings->fetchPlingsForProject($this->_projectId); + $this->view->projectplingsJson = Zend_Json::encode($plings); + + $tableProject = new Default_Model_Project(); + $galleryPictures = $tableProject->getGalleryPictureSources($this->_projectId); + $this->view->galleryPicturesJson = Zend_Json::encode($galleryPictures); + + $tagmodel = new Default_Model_Tags(); + $tagsuser = $tagmodel->getTagsUser($this->_projectId, Default_Model_Tags::TAG_TYPE_PROJECT); + $tagssystem = $tagmodel->getTagsSystemList($this->_projectId); + $this->view->tagsuserJson = Zend_Json::encode($tagsuser); + $this->view->tagssystemJson = Zend_Json::encode($tagssystem); + + $modelComments = new Default_Model_ProjectComments(); + $offset = 0; + $testComments = $modelComments->getCommentTreeForProjectList($this->_projectId); + $this->view->commentsJson = Zend_Json::encode($testComments); + + $modelClone = new Default_Model_ProjectClone(); + $origins = $modelClone->fetchOrigins($this->_projectId); + $this->view->originsJson = Zend_Json::encode($origins); + $related = $modelClone->fetchRelatedProducts($this->_projectId); + $this->view->relatedJson = Zend_Json::encode($related); + + $moreProducts = $tableProject->fetchMoreProjects($this->view->product, 8); + $this->view->moreProductsJson = Zend_Json::encode($moreProducts); + $moreProducts = $tableProject->fetchMoreProjectsOfOtherUsr($this->view->product, 8); + $this->view->moreProductsOfOtherUsrJson = Zend_Json::encode($moreProducts); + + + } public function addAction() { $this->view->member = $this->_authMember; $this->view->mode = 'add'; - - if($this->getParam('catId')){ + + if ($this->getParam('catId')) { $this->view->catId = $this->getParam('catId'); } $form = new Default_Form_Product(array('member_id' => $this->view->member->member_id)); $this->view->form = $form; - + if ($this->_request->isGet()) { return; } - + $helperUserRole = new Backend_View_Helper_UserRole(); $userRoleName = $helperUserRole->userRole(); $isAdmin = false; if (Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN == $userRoleName) { $isAdmin = true; } - + if (isset($_POST['cancel'])) { // user cancel function $this->redirect('/member/' . $this->_authMember->member_id . '/news/'); } if (false === $form->isValid($_POST)) { // form not valid $this->view->form = $form; $this->view->error = 1; return; } $values = $form->getValues(); $imageModel = new Default_Model_DbTable_Image(); try { $values['image_small'] = $imageModel->saveImage($form->getElement(self::IMAGE_SMALL_UPLOAD)); } catch (Exception $e) { Zend_Registry::get('logger')->err(__METHOD__ . ' - ERROR upload productPicture - ' . print_r($e, true)); } // form was valid, so we can set status to active $values['status'] = Default_Model_DbTable_Project::PROJECT_ACTIVE; // save new project $modelProject = new Default_Model_Project(); Zend_Registry::get('logger')->info(__METHOD__ . ' - $post: ' . print_r($_POST, true)); Zend_Registry::get('logger')->info(__METHOD__ . ' - $files: ' . print_r($_FILES, true)); Zend_Registry::get('logger')->info(__METHOD__ . ' - input values: ' . print_r($values, true)); $newProject = null; try { if (isset($values['project_id'])) { $newProject = $modelProject->updateProject($values['project_id'], $values); } else { - $newProject = $modelProject->createProject($this->_authMember->member_id, $values, $this->_authMember->username); + $newProject = $modelProject->createProject($this->_authMember->member_id, $values, + $this->_authMember->username); //$this->createSystemPlingForNewProject($newProject->project_id); } } catch (Exception $exc) { Zend_Registry::get('logger')->warn(__METHOD__ . ' - traceString: ' . $exc->getTraceAsString()); } if (!$newProject) { $this->_helper->flashMessenger->addMessage('

You did not choose a Category in the last level.

'); $this->forward('add'); return; } //update the gallery pics $mediaServerUrls = $this->saveGalleryPics($form->gallery->upload->upload_picture); $modelProject->updateGalleryPictures($newProject->project_id, $mediaServerUrls); //If there is no Logo, we take the 1. gallery pic if (!isset($values['image_small']) || $values['image_small'] == '') { $values['image_small'] = $mediaServerUrls[0]; $newProject = $modelProject->updateProject($newProject->project_id, $values); } //New Project in Session, for AuthValidation (owner) $this->_auth->getIdentity()->projects[$newProject->project_id] = array('project_id' => $newProject->project_id); $modelTags = new Default_Model_Tags(); if ($values['tagsuser']) { - $modelTags->processTagsUser($newProject->project_id, implode(',', $values['tagsuser']),Default_Model_Tags::TAG_TYPE_PROJECT); + $modelTags->processTagsUser($newProject->project_id, implode(',', $values['tagsuser']), + Default_Model_Tags::TAG_TYPE_PROJECT); } else { $modelTags->processTagsUser($newProject->project_id, null, Default_Model_Tags::TAG_TYPE_PROJECT); } - - $modelTags->processTagProductOriginalOrModification($newProject->project_id,$values['is_original_or_modification'][0]); + + $modelTags->processTagProductOriginalOrModification($newProject->project_id, + $values['is_original_or_modification'][0]); //set license, if needed $licenseTag = $form->getElement('license_tag_id')->getValue(); //only set/update license tags if something was changed if ($licenseTag && count($licenseTag) > 0) { $modelTags->saveLicenseTagForProject($newProject->project_id, $licenseTag); $activityLog = new Default_Model_ActivityLog(); - $activityLog->logActivity($newProject->project_id, $newProject->project_id, $this->_authMember->member_id,Default_Model_ActivityLog::PROJECT_LICENSE_CHANGED, array('title' => 'Set new License Tag', 'description' => 'New TagId: ' . $licenseTag)); + $activityLog->logActivity($newProject->project_id, $newProject->project_id, $this->_authMember->member_id, + Default_Model_ActivityLog::PROJECT_LICENSE_CHANGED, + array('title' => 'Set new License Tag', 'description' => 'New TagId: ' . $licenseTag)); } $isGitlabProject = $form->getElement('is_gitlab_project')->getValue(); $gitlabProjectId = $form->getElement('gitlab_project_id')->getValue(); if ($isGitlabProject && $gitlabProjectId == 0) { $values['gitlab_project_id'] = null; } $activityLog = new Default_Model_ActivityLog(); - $activityLog->writeActivityLog($newProject->project_id, $newProject->member_id, Default_Model_ActivityLog::PROJECT_CREATED, $newProject->toArray()); + $activityLog->writeActivityLog($newProject->project_id, $newProject->member_id, + Default_Model_ActivityLog::PROJECT_CREATED, $newProject->toArray()); // ppload $this->processPploadId($newProject); try { if (100 < $this->_authMember->roleId) { if (Default_Model_Spam::hasSpamMarkers($newProject->toArray())) { $tableReportComments = new Default_Model_DbTable_ReportProducts(); - $tableReportComments->save(array('project_id' => $newProject->project_id, 'reported_by' => 24, 'text' => "System: automatic spam detection")); + $tableReportComments->save(array( + 'project_id' => $newProject->project_id, + 'reported_by' => 24, + 'text' => "System: automatic spam detection" + )); } Default_Model_DbTable_SuspicionLog::logProject($newProject, $this->_authMember, $this->getRequest()); } } catch (Zend_Exception $e) { Zend_Registry::get('logger')->err($e->getMessage()); } $this->redirect('/member/' . $newProject->member_id . '/products/'); } private function saveGalleryPics($form_element) { $imageModel = new Default_Model_DbTable_Image(); return $imageModel->saveImages($form_element); } - - /** - * @param $projectData - * - * @throws Zend_Exception - * @throws Zend_Queue_Exception - */ - protected function createTaskWebsiteOwnerVerification($projectData) - { - if (empty($projectData->link_1)) { - return; - } - $checkAuthCode = new Local_Verification_WebsiteProject(); - $authCode = $checkAuthCode->generateAuthCode(stripslashes($projectData->link_1)); - $queue = Local_Queue_Factory::getQueue(); - $command = new Backend_Commands_CheckProjectWebsite($projectData->project_id, $projectData->link_1, $authCode); - $queue->send(serialize($command)); - } - /** * @param $projectData */ protected function processPploadId($projectData) { if ($projectData->ppload_collection_id) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); // Update collection information $collectionCategory = $projectData->project_category_id; if (Default_Model_Project::PROJECT_ACTIVE == $projectData->status) { $collectionCategory .= '-published'; } $collectionRequest = array( 'title' => $projectData->title, 'description' => $projectData->description, 'category' => $collectionCategory, 'content_id' => $projectData->project_id ); $collectionResponse = $pploadApi->putCollection($projectData->ppload_collection_id, $collectionRequest); // Store product image as collection thumbnail $this->_updatePploadMediaCollectionthumbnail($projectData); } } /** * ppload */ protected function _updatePploadMediaCollectionthumbnail($projectData) { if (empty($projectData->ppload_collection_id) || empty($projectData->image_small) ) { return false; } $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); $filename = sys_get_temp_dir() . '/' . $projectData->image_small; if (false === file_exists(dirname($filename))) { mkdir(dirname($filename), 0777, true); } $viewHelperImage = new Default_View_Helper_Image(); $uri = $viewHelperImage->Image($projectData->image_small, array( - 'width' => 600, - 'height' => 600 - )); + 'width' => 600, + 'height' => 600 + )); file_put_contents($filename, file_get_contents($uri)); $mediaCollectionthumbnailResponse = $pploadApi->postMediaCollectionthumbnail($projectData->ppload_collection_id, array('file' => $filename)); unlink($filename); if (isset($mediaCollectionthumbnailResponse->status) && $mediaCollectionthumbnailResponse->status == 'success' ) { return true; } return false; } public function editAction() { if (empty($this->_projectId)) { $this->redirect($this->_helper->url('add')); return; } $this->_helper->viewRenderer('add'); // we use the same view as you can see at add a product $this->view->mode = 'edit'; $projectTable = new Default_Model_DbTable_Project(); $projectModel = new Default_Model_Project(); $modelTags = new Default_Model_Tags(); $tagTable = new Default_Model_DbTable_Tags(); //check if product with given id exists $projectData = $projectTable->find($this->_projectId)->current(); if (empty($projectData)) { $this->redirect($this->_helper->url('add')); return; } $member = null; if (isset($this->_authMember) AND (false === empty($this->_authMember->member_id))) { $member = $this->_authMember; } else { throw new Zend_Controller_Action_Exception('no authorization found'); } if (("admin" == $this->_authMember->roleName)) { $modelMember = new Default_Model_Member(); $member = $modelMember->fetchMember($projectData->member_id, false); } - + $helperUserRole = new Backend_View_Helper_UserRole(); $userRoleName = $helperUserRole->userRole(); $isAdmin = false; if (Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN == $userRoleName) { $isAdmin = true; } //set ppload-collection-id in view $this->view->ppload_collection_id = $projectData->ppload_collection_id; $this->view->project_id = $projectData->project_id; $this->view->product = $projectData; //create ppload download hash: secret + collection_id + expire-timestamp $salt = PPLOAD_DOWNLOAD_SECRET; $collectionID = $projectData->ppload_collection_id; $timestamp = time() + 3600; // one hour valid //20181009 ronald: change hash from MD5 to SHA512 //$hash = md5($salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying - $hash = hash('sha512',$salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying + $hash = hash('sha512', + $salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying $this->view->download_hash = $hash; $this->view->download_timestamp = $timestamp; $this->view->member_id = $member->member_id; $this->view->member = $member; //read the already existing gallery pics and add them to the form $sources = $projectModel->getGalleryPictureSources($this->_projectId); - + //get the gitlab projects for this user //setup form $form = new Default_Form_Product(array('pictures' => $sources, 'member_id' => $this->view->member_id)); if (false === empty($projectData->image_small)) { $form->getElement('image_small_upload')->setRequired(false); } $form->getElement('preview')->setLabel('Save'); $form->removeElement('project_id'); // we don't need this field in edit mode if ($this->_request->isGet()) { $form->populate($projectData->toArray()); - // $form->populate(array('tags' => $modelTags->getTags($projectData->project_id, Default_Model_Tags::TAG_TYPE_PROJECT))); - $form->populate(array('tagsuser' => $modelTags->getTagsUser($projectData->project_id, Default_Model_Tags::TAG_TYPE_PROJECT))); + // $form->populate(array('tags' => $modelTags->getTags($projectData->project_id, Default_Model_Tags::TAG_TYPE_PROJECT))); + $form->populate(array( + 'tagsuser' => $modelTags->getTagsUser($projectData->project_id, Default_Model_Tags::TAG_TYPE_PROJECT) + )); $form->getElement('image_small')->setValue($projectData->image_small); //Bilder voreinstellen $form->getElement(self::IMAGE_SMALL_UPLOAD)->setValue($projectData->image_small); $licenseTags = $tagTable->fetchLicenseTagsForProject($this->_projectId); $licenseTag = null; - if($licenseTags) { + if ($licenseTags) { $licenseTag = $licenseTags[0]['tag_id']; } $form->getElement('license_tag_id')->setValue($licenseTag); $is_original = $modelTags->isProductOriginal($projectData->project_id); $is_modification = $modelTags->isProductModification($projectData->project_id); - if($is_original){ - $form->getElement('is_original_or_modification')->setValue(1); - } else if($is_modification){ - $form->getElement('is_original_or_modification')->setValue(2); + if ($is_original) { + $form->getElement('is_original_or_modification')->setValue(1); + } else { + if ($is_modification) { + $form->getElement('is_original_or_modification')->setValue(2); + } } - + $this->view->form = $form; return; } if (isset($_POST['cancel'])) { // user cancel function $this->redirect('/member/' . $member->member_id . '/news/'); } if (false === $form->isValid($_POST, $this->_projectId)) { // form not valid $this->view->form = $form; $this->view->error = 1; return; } $values = $form->getValues(); //set license, if needed - $tagList = $modelTags->getTagsArray($this->_projectId, $modelTags::TAG_TYPE_PROJECT, $modelTags::TAG_LICENSE_GROUPID); + $tagList = $modelTags->getTagsArray($this->_projectId, $modelTags::TAG_TYPE_PROJECT, + $modelTags::TAG_LICENSE_GROUPID); $oldLicenseTagId = null; - if($tagList && count($tagList) == 1) { + if ($tagList && count($tagList) == 1) { $oldLicenseTagId = $tagList[0]['tag_id']; } $licenseTag = $form->getElement('license_tag_id')->getValue(); //only set/update license tags if something was changed - if($licenseTag <> $oldLicenseTagId) { + if ($licenseTag <> $oldLicenseTagId) { $modelTags->saveLicenseTagForProject($this->_projectId, $licenseTag); $activityLog = new Default_Model_ActivityLog(); - $activityLog->logActivity($this->_projectId, $this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_LICENSE_CHANGED, array('title' => 'License Tag', 'description' => 'Old TagId: '.$oldLicenseTagId.' - New TagId: '.$licenseTag)); + $activityLog->logActivity($this->_projectId, $this->_projectId, $this->_authMember->member_id, + Default_Model_ActivityLog::PROJECT_LICENSE_CHANGED, array( + 'title' => 'License Tag', + 'description' => 'Old TagId: ' . $oldLicenseTagId . ' - New TagId: ' . $licenseTag + )); } - + //gitlab project $isGitlabProject = $form->getElement('is_gitlab_project')->getValue(); $gitlabProjectId = $form->getElement('gitlab_project_id')->getValue(); - if($isGitlabProject && $gitlabProjectId == 0) { + if ($isGitlabProject && $gitlabProjectId == 0) { $values['gitlab_project_id'] = null; } - $imageModel = new Default_Model_DbTable_Image(); try { $uploadedSmallImage = $imageModel->saveImage($form->getElement(self::IMAGE_SMALL_UPLOAD)); $values['image_small'] = $uploadedSmallImage ? $uploadedSmallImage : $values['image_small']; } catch (Exception $e) { Zend_Registry::get('logger')->err(__METHOD__ . ' - ERROR upload productPicture - ' . print_r($e, true)); } // save changes $projectModel->updateProject($this->_projectId, $values); //update the gallery pics $pictureSources = array_merge($values['gallery']['online_picture'], $this->saveGalleryPics($form->gallery->upload->upload_picture)); $projectModel->updateGalleryPictures($this->_projectId, $pictureSources); //If there is no Logo, we take the 1. gallery pic if (!isset($projectData->image_small) || $projectData->image_small == '') { $projectData->image_small = $pictureSources[0]; } //20180219 ronald: we set the changed_at only by new files or new updates //$projectData->changed_at = new Zend_Db_Expr('NOW()'); $projectData->save(); - - $modelTags->processTagProductOriginalOrModification($this->_projectId,$values['is_original_or_modification'][0]); - if($values['tagsuser']) { - $modelTags->processTagsUser($this->_projectId,implode(',',$values['tagsuser']), Default_Model_Tags::TAG_TYPE_PROJECT); - }else - { - $modelTags->processTagsUser($this->_projectId,null, Default_Model_Tags::TAG_TYPE_PROJECT); - } + $modelTags->processTagProductOriginalOrModification($this->_projectId, + $values['is_original_or_modification'][0]); - $activityLog = new Default_Model_ActivityLog(); - $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_EDITED, $projectData->toArray()); + if ($values['tagsuser']) { + $modelTags->processTagsUser($this->_projectId, implode(',', $values['tagsuser']), + Default_Model_Tags::TAG_TYPE_PROJECT); + } else { + $modelTags->processTagsUser($this->_projectId, null, Default_Model_Tags::TAG_TYPE_PROJECT); + } + + $activityLog = new Default_Model_ActivityLog(); + $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, + Default_Model_ActivityLog::PROJECT_EDITED, $projectData->toArray()); // ppload $this->processPploadId($projectData); try { if (100 < $this->_authMember->roleId) { if (Default_Model_Spam::hasSpamMarkers($projectData->toArray())) { $tableReportComments = new Default_Model_DbTable_ReportProducts(); - $tableReportComments->save(array('project_id' => $projectData->project_id, 'reported_by' => 24, 'text' => "System: automatic spam detection on product edit")); + $tableReportComments->save(array( + 'project_id' => $projectData->project_id, + 'reported_by' => 24, + 'text' => "System: automatic spam detection on product edit" + )); } Default_Model_DbTable_SuspicionLog::logProject($projectData, $this->_authMember, $this->getRequest()); } } catch (Zend_Exception $e) { Zend_Registry::get('logger')->err($e->getMessage()); } $helperBuildMemberUrl = new Default_View_Helper_BuildMemberUrl(); $this->redirect($helperBuildMemberUrl->buildMemberUrl($member->username, 'products')); } public function getupdatesajaxAction() { $this->view->authMember = $this->_authMember; $tableProject = new Default_Model_ProjectUpdates(); $updates = $tableProject->fetchProjectUpdates($this->_projectId); foreach ($updates as $key => $update) { $updates[$key]['title'] = Default_Model_HtmlPurify::purify($update['title']); - $updates[$key]['text'] = Default_Model_BBCode::renderHtml(Default_Model_HtmlPurify::purify(htmlentities($update['text'], ENT_QUOTES | ENT_IGNORE))); + $updates[$key]['text'] = Default_Model_BBCode::renderHtml(Default_Model_HtmlPurify::purify(htmlentities($update['text'], + ENT_QUOTES | ENT_IGNORE))); $updates[$key]['raw_title'] = $update['title']; $updates[$key]['raw_text'] = $update['text']; } $result['status'] = 'success'; $result['ResultSize'] = count($updates); $result['updates'] = $updates; $this->_helper->json($result); } public function saveupdateajaxAction() { $filter = - new Zend_Filter_Input( - array( - '*' => 'StringTrim' - ), - array( - '*' => array(), - 'title' => array( - new Zend_Validate_StringLength(array('min' => 3, 'max' => 200)), - 'presence' => 'required', - 'allowEmpty' => false - ), - 'text' => array( - new Zend_Validate_StringLength(array('min' => 3, 'max' => 16383)), - 'presence' => 'required', - 'allowEmpty' => false + new Zend_Filter_Input( + array( + '*' => 'StringTrim' ), - 'update_id' => array('digits', 'allowEmpty' => true) - ), $this->getAllParams(), array('allowEmpty' => true)); + array( + '*' => array(), + 'title' => array( + new Zend_Validate_StringLength(array('min' => 3, 'max' => 200)), + 'presence' => 'required', + 'allowEmpty' => false + ), + 'text' => array( + new Zend_Validate_StringLength(array('min' => 3, 'max' => 16383)), + 'presence' => 'required', + 'allowEmpty' => false + ), + 'update_id' => array('digits', 'allowEmpty' => true) + ), $this->getAllParams(), array('allowEmpty' => true)); if ($filter->hasInvalid() OR $filter->hasMissing() OR $filter->hasUnknown()) { $result['status'] = 'error'; $result['messages'] = $filter->getMessages(); $result['update_id'] = null; $this->_helper->json($result); } $update_id = $filter->getEscaped('update_id'); $tableProjectUpdates = new Default_Model_ProjectUpdates(); //Save update if (!empty($update_id)) { //Update old update $updateArray = array(); $updateArray['title'] = $filter->getUnescaped('title'); $updateArray['text'] = $filter->getUnescaped('text'); $updateArray['changed_at'] = new Zend_Db_Expr('Now()'); $countUpdated = $tableProjectUpdates->update($updateArray, 'project_update_id = ' . $update_id); } else { //Add new update $updateArray = array(); $updateArray['title'] = $filter->getUnescaped('title'); $updateArray['text'] = $filter->getUnescaped('text'); $updateArray['public'] = 1; $updateArray['project_id'] = $this->_projectId; $updateArray['member_id'] = $this->_authMember->member_id; $updateArray['created_at'] = new Zend_Db_Expr('Now()'); $updateArray['changed_at'] = new Zend_Db_Expr('Now()'); $rowset = $tableProjectUpdates->save($updateArray); $update_id = $rowset->project_update_id; //20180219 ronald: we set the changed_at only by new files or new updates $projectTable = new Default_Model_Project(); $projectUpdateRow = $projectTable->find($this->_projectId)->current(); if (count($projectUpdateRow) == 1) { $projectUpdateRow->changed_at = new Zend_Db_Expr('NOW()'); $projectUpdateRow->save(); } } $result['status'] = 'success'; $result['update_id'] = $update_id; $this->_helper->json($result); } public function deleteupdateajaxAction() { $this->view->authMember = $this->_authMember; $tableProject = new Default_Model_ProjectUpdates(); $params = $this->getAllParams(); $project_update_id = $params['update_id']; $updateArray = array(); $updateArray['public'] = 0; $updateArray['changed_at'] = new Zend_Db_Expr('Now()'); $tableProject->update($updateArray, 'project_update_id = ' . $project_update_id); $result['status'] = 'success'; $result['update_id'] = $project_update_id; $this->_helper->json($result); } public function updatesAction() { $this->view->authMember = $this->_authMember; $tableProject = new Default_Model_Project(); $this->view->product = $tableProject->fetchProductInfo($this->_projectId); if (false === isset($this->view->product)) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } $this->view->relatedProducts = $tableProject->fetchSimilarProjects($this->view->product, 6); $this->view->supporter = $tableProject->fetchProjectSupporter($this->_projectId); $this->view->product_views = $tableProject->fetchProjectViews($this->_projectId); $modelPlings = new Default_Model_DbTable_Plings(); $this->view->comments = $modelPlings->getCommentsForProject($this->_projectId, 10); $tableMember = new Default_Model_Member(); $this->view->member = $tableMember->fetchMemberData($this->view->product->member_id); $this->view->updates = $tableProject->fetchProjectUpdates($this->_projectId); $tablePageViews = new Default_Model_DbTable_StatPageViews(); $tablePageViews->savePageView($this->_projectId, $this->getRequest()->getClientIp(), $this->_authMember->member_id); } public function updateAction() { $this->_helper->layout()->setLayout('flat_ui'); $this->view->headScript()->setFile(''); $this->view->headLink()->setStylesheet(''); $this->_helper->viewRenderer('add'); $form = new Default_Form_ProjectUpdate(); $projectTable = new Default_Model_Project(); $projectData = null; $projectUpdateId = (int)$this->getParam('upid'); $this->view->member = $this->_authMember; $this->view->title = 'Add an update for your product'; $activityLogType = Default_Model_ActivityLog::PROJECT_ITEM_CREATED; if (false === empty($projectUpdateId)) { $this->view->title = 'Edit an product update'; $projectData = $projectTable->find($projectUpdateId)->current(); $form->populate($projectData->toArray()); $form->getElement('upid')->setValue($projectUpdateId); $activityLogType = Default_Model_ActivityLog::PROJECT_ITEM_EDITED; } $this->view->form = $form; if ($this->_request->isGet()) { return; } if (isset($_POST['cancel'])) { // user cancel function $this->_redirect('/member/' . $this->_authMember->member_id . '/news/'); } if (false === $form->isValid($_POST)) { // form not valid $this->view->form = $form; $this->view->error = 1; return; } $values = $form->getValues(); $projectUpdateRow = $projectTable->find($values['upid'])->current(); if (count($projectUpdateRow) == 0) { $projectUpdateRow = $projectTable->createRow($values); $projectUpdateRow->project_id = $values['upid']; $projectUpdateRow->created_at = new Zend_Db_Expr('NOW()'); $projectUpdateRow->start_date = new Zend_Db_Expr('NOW()'); $projectUpdateRow->member_id = $this->_authMember->member_id; $projectUpdateRow->creator_id = $this->_authMember->member_id; $projectUpdateRow->status = Default_Model_Project::PROJECT_ACTIVE; $projectUpdateRow->type_id = 2; $projectUpdateRow->pid = $this->_projectId; } else { $projectUpdateRow->setFromArray($values); //20180219 ronald: we set the changed_at only by new files or new updates //$projectUpdateRow->changed_at = new Zend_Db_Expr('NOW()'); } $lastId = $projectUpdateRow->save(); //New Project in Session, for AuthValidation (owner) $this->_auth->getIdentity()->projects[$lastId] = array('project_id' => $lastId); $tableProduct = new Default_Model_Project(); $product = $tableProduct->find($this->_projectId)->current(); $activityLogValues = $projectUpdateRow->toArray(); $activityLogValues['image_small'] = $product->image_small; $activityLog = new Default_Model_ActivityLog(); //$activityLog->writeActivityLog($lastId, $projectUpdateRow->member_id, $activityLogType, $activityLogValues); $activityLog->writeActivityLog($lastId, $this->_authMember->member_id, $activityLogType, $activityLogValues); $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); $urlProjectShow = $helperBuildProductUrl->buildProductUrl($this->_projectId); $this->redirect($urlProjectShow); } public function previewAction() { $this->view->authMember = $this->_authMember; $form = new Default_Form_ProjectConfirm(); if ($this->_request->isGet()) { $form->populate(get_object_vars($this->_authMember)); $this->view->form = $form; $this->fetchDataForIndexView(); $this->view->preview = $this->view->render('product/index.phtml'); return; } if (isset($_POST['save'])) { $projectTable = new Default_Model_Project(); $projectTable->setStatus(Default_Model_Project::PROJECT_INACTIVE, $this->_projectId); //todo: maybe we have to delete the project data from database otherwise we produce many zombies $this->redirect('/member/' . $this->_authMember->member_id . '/products/'); } if (isset($_POST['back'])) { $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); $this->redirect($helperBuildProductUrl->buildProductUrl($this->_projectId, 'edit')); } if (false === $form->isValid($_POST)) { // form not valid $this->view->form = $form; $this->fetchDataForIndexView(); $this->view->preview = $this->view->render('product/index.phtml'); $this->view->error = 1; return; } $projectTable = new Default_Model_Project(); $projectTable->setStatus(Default_Model_Project::PROJECT_ACTIVE, $this->_projectId); // add to search index $modelProject = new Default_Model_Project(); $productInfo = $modelProject->fetchProductInfo($this->_projectId); $modelSearch = new Default_Model_Search_Lucene(); $modelSearch->addDocument($productInfo->toArray()); $this->redirect('/member/' . $this->_authMember->member_id . '/products/'); } protected function fetchDataForIndexView() { $tableProject = new Default_Model_Project(); $this->view->product = $tableProject->fetchProductInfo($this->_projectId); if (false === isset($this->view->product)) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } $desc = $this->view->product->description; $newDesc = $this->bbcode2html($desc); $this->view->product->description = $newDesc; // switch off temporally 02.05.2017 //$this->view->supporting = $tableProject->fetchProjectSupporterWithPlings($this->_projectId); //$orgUpdates = $tableProjectUpdates->fetchLastProjectUpdate($this->_projectId); $tableProjectUpdates = new Default_Model_ProjectUpdates(); $orgUpdates = $tableProjectUpdates->fetchProjectUpdates($this->_projectId); $newUpdates = array(); foreach ($orgUpdates as $update) { $desc = $update['text']; $newDesc = $this->bbcode2html($desc); $update['text'] = $newDesc; $newUpdates[] = $update; } $this->view->updates = $newUpdates; // switch off temporally 02.05.2017 //$this->view->supporter = $tableProject->fetchProjectSupporter($this->_projectId); $this->view->galleryPictures = $tableProject->getGalleryPictureSources($this->_projectId); $this->view->product_views = $tableProject->fetchProjectViews($this->_projectId); $helperFetchCategory = new Default_View_Helper_CatTitle(); $helperFetchCatParent = new Default_View_Helper_CatParent(); $this->view->catId = $this->view->product->project_category_id; $this->view->catTitle = $helperFetchCategory->catTitle($this->view->product->project_category_id); $this->view->catParentId = $helperFetchCatParent->getCatParentId(array('project_category_id' => $this->view->product->project_category_id)); if ($this->view->catParentId) { $this->view->catParentTitle = $helperFetchCategory->catTitle($this->view->catParentId); } $AuthCodeExist = new Local_Verification_WebsiteProject(); $this->view->websiteAuthCode = $AuthCodeExist->generateAuthCode(stripslashes($this->view->product->link_1)); // switch off temporally 02.05.2017 //$modelPlings = new Default_Model_DbTable_Plings(); //$this->view->plings = $modelPlings->getDonationsForProject($this->_projectId, 10); $tableMember = new Default_Model_Member(); $this->view->member = $tableMember->fetchMemberData($this->view->product->member_id); $this->view->more_products = $tableProject->fetchMoreProjects($this->view->product, 8); $this->view->more_products_otheruser = $tableProject->fetchMoreProjectsOfOtherUsr($this->view->product, 8); $widgetDefaultModel = new Default_Model_DbTable_ProjectWidgetDefault(); $widgetDefault = $widgetDefaultModel->fetchConfig($this->_projectId); $widgetDefault->text->headline = $this->view->product->title; //$widgetDefault->amounts->current = $this->view->product->amount_received; $widgetDefault->amounts->goal = $this->view->product->amount; $widgetDefault->project = $this->_projectId; $this->view->widgetConfig = $widgetDefault; $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); $this->view->permaLink = $helperBuildProductUrl->buildProductUrl($this->_projectId, null, null, true); $this->view->urlPay = $helperBuildProductUrl->buildProductUrl($this->_projectId, 'pay'); $referrerUrl = $this->readExploreUrlFromReferrer(); if (false === empty($referrerUrl)) { $this->view->referrerUrl = $referrerUrl; } } /** * transforms a string with bbcode markup into html * * @param string $txt * @param bool $nl2br * * @return string */ private function bbcode2html($txt, $nl2br = true, $forcecolor = '') { if (!empty($forcecolor)) { $fc = ' style="color:' . $forcecolor . ';"'; } else { $fc = ''; } $newtxt = htmlspecialchars($txt); if ($nl2br) { $newtxt = nl2br($newtxt); } $patterns = array( '`\[b\](.+?)\[/b\]`is', '`\[i\](.+?)\[/i\]`is', '`\[u\](.+?)\[/u\]`is', '`\[li\](.+?)\[/li\]`is', '`\[strike\](.+?)\[/strike\]`is', '`\[url\]([a-z0-9]+?://){1}([\w\-]+\.([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^ \"\n\r\t<]*)?)\[/url\]`si', '`\[quote\](.+?)\[/quote\]`is', '`\[indent](.+?)\[/indent\]`is' ); $replaces = array( '\\1', '\\1', '\\1', '\\1', '\\1', '\1\2', 'Quote:
\1
', '\\1' ); $newtxt = preg_replace($patterns, $replaces, $newtxt); return ($newtxt); } protected function readExploreUrlFromReferrer() { $helperBuildExploreUrl = new Default_View_Helper_BuildExploreUrl(); $referrerExplore = $helperBuildExploreUrl->buildExploreUrl(null, null, null, null, true); /** @var Zend_Controller_Request_Http $request */ $request = $this->getRequest(); if (strpos($request->getHeader('referer'), $referrerExplore) !== false) { return $request->getHeader('referer'); } } public function plingAction() { if (empty($this->_projectId)) { $this->redirect('/explore'); } $this->view->authMember = $this->_authMember; $this->fetchDataForIndexView(); $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); $this->view->urlPay = $helperBuildProductUrl->buildProductUrl($this->_projectId, 'pay'); $this->view->amount = (float)$this->getParam('amount', 1); $this->view->comment = html_entity_decode(strip_tags($this->getParam('comment'), null), ENT_QUOTES, 'utf-8'); $this->view->provider = mb_strtolower(html_entity_decode(strip_tags($this->getParam('provider'), null), ENT_QUOTES, 'utf-8'), 'utf-8'); $this->view->headTitle($this->_browserTitlePrepend . $this->view->product->title, 'SET'); $helperUserIsOwner = new Default_View_Helper_UserIsOwner(); $helperIsProjectActive = new Default_View_Helper_IsProjectActive(); if ((false === $helperIsProjectActive->isProjectActive($this->view->product->project_status)) AND (false - === $helperUserIsOwner->UserIsOwner($this->view->product->member_id)) + === $helperUserIsOwner->UserIsOwner($this->view->product->member_id)) ) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } $tableProject = new Default_Model_Project(); $this->view->supporting = $tableProject->fetchProjectSupporterWithPlings($this->_projectId); } - - public function payAction() { $this->_helper->layout()->disableLayout(); $tableProject = new Default_Model_Project(); $project = $tableProject->fetchProductInfo($this->_projectId); //get parameter $amount = (float)$this->getParam('amount', 1); $comment = Default_Model_HtmlPurify::purify($this->getParam('comment')); $paymentProvider = mb_strtolower(html_entity_decode(strip_tags($this->getParam('provider'), null), ENT_QUOTES, 'utf-8'), 'utf-8'); $hideIdentity = (int)$this->getParam('hideId', 0); $paymentGateway = $this->createPaymentGateway($paymentProvider); $paymentGateway->getUserDataStore()->generateFromArray($project->toArray()); $requestMessage = 'Thank you for supporting: ' . $paymentGateway->getUserDataStore()->getProductTitle(); $response = null; try { $response = $paymentGateway->requestPayment($amount, $requestMessage); $this->view->checkoutEndpoint = $paymentGateway->getCheckoutEndpoint(); $this->view->paymentKey = $response->getPaymentId(); $this->_helper->viewRenderer->setRender('pay_' . $paymentProvider); } catch (Exception $e) { throw new Zend_Controller_Action_Exception('payment error', 500, $e); } if (false === $response->isSuccessful()) { throw new Zend_Controller_Action_Exception('payment failure', 500); } if (empty($this->_authMember->member_id) or ($hideIdentity == 1)) { $memberId = 1; } else { $memberId = $this->_authMember->member_id; } //Add pling $modelPlings = new Default_Model_DbTable_Plings(); $plingId = $modelPlings->createNewPlingFromResponse($response, $memberId, $project->project_id, $amount); if (false == empty($comment)) { $modelComments = new Default_Model_ProjectComments(); $dataComment = array( 'comment_type' => Default_Model_DbTable_Comments::COMMENT_TYPE_PLING, 'comment_target_id' => $project->project_id, 'comment_member_id' => $memberId, 'comment_pling_id' => $plingId, 'comment_text' => $comment ); $modelComments->save($dataComment); } $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $memberId, Default_Model_ActivityLog::PROJECT_PLINGED, $project->toArray()); } /** * @param string $paymentProvider * * @return Local_Payment_GatewayInterface * @throws Exception * @throws Local_Payment_Exception * @throws Zend_Controller_Exception * @throws Zend_Exception */ protected function createPaymentGateway($paymentProvider) { $httpHost = $this->getRequest()->getHttpHost(); /** @var Zend_Config $config */ $config = Zend_Registry::get('config'); $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); switch ($paymentProvider) { case 'paypal': $paymentGateway = new Default_Model_PayPal_Gateway($config->third_party->paypal); $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/paypal'); // $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/paypal?XDEBUG_SESSION_START=1'); $paymentGateway->setCancelUrl($helperBuildProductUrl->buildProductUrl($this->_projectId, 'paymentcancel', null, true)); $paymentGateway->setReturnUrl($helperBuildProductUrl->buildProductUrl($this->_projectId, 'paymentok', null, true)); break; case 'dwolla': $paymentGateway = new Default_Model_Dwolla_Gateway($config->third_party->dwolla); $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/dwolla'); // $paymentGateway->setIpnNotificationUrl('http://' . $_SERVER ['HTTP_HOST'] . '/gateway/dwolla?XDEBUG_SESSION_START=1'); $paymentGateway->setReturnUrl($helperBuildProductUrl->buildProductUrl($this->_projectId, 'dwolla', null, true)); break; case 'amazon': $paymentGateway = new Default_Model_Amazon_Gateway($config->third_party->amazon); $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/amazon'); // $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/amazon?XDEBUG_SESSION_START=1'); $paymentGateway->setCancelUrl($helperBuildProductUrl->buildProductUrl($this->_projectId, 'paymentcancel', null, true)); $paymentGateway->setReturnUrl($helperBuildProductUrl->buildProductUrl($this->_projectId, 'paymentok', null, true)); break; default: throw new Zend_Controller_Exception('No known payment provider found in parameters.'); break; } return $paymentGateway; } public function dwollaAction() { $modelPling = new Default_Model_DbTable_Plings(); $plingData = $modelPling->fetchRow(array('payment_reference_key = ?' => $this->getParam('checkoutId'))); $plingData->payment_transaction_id = (int)$this->getParam('transaction'); $plingData->save(); if ($this->_getParam('status') == 'Completed') { $this->_helper->viewRenderer('paymentok'); $this->paymentokAction(); } else { $this->_helper->viewRenderer('paymentcancel'); $this->paymentcancelAction(); } } public function paymentokAction() { $this->_helper->layout()->disableLayout(); $this->view->paymentStatus = 'success'; $this->view->paymentMessage = 'Payment successful.'; $this->fetchDataForIndexView(); } public function paymentcancelAction() { $this->_helper->layout()->disableLayout(); $this->view->paymentStatus = 'danger'; $this->view->paymentMessage = 'Payment cancelled.'; $this->fetchDataForIndexView(); } public function deleteAction() { $this->_helper->layout()->setLayout('flat_ui'); $memberId = (int)$this->getParam('m'); if ((empty($this->_authMember->member_id)) OR (empty($memberId)) OR ($this->_authMember->member_id - != $memberId) + != $memberId) ) { $this->forward('products', 'user', 'default'); return; } $tableProduct = new Default_Model_Project(); - $tableProduct->setDeleted($this->_authMember->member_id,$this->_projectId); + $tableProduct->setDeleted($this->_authMember->member_id, $this->_projectId); $product = $tableProduct->find($this->_projectId)->current(); // delete product from search index $modelSearch = new Default_Model_Search_Lucene(); $modelSearch->deleteDocument($product->toArray()); // $command = new Backend_Commands_DeleteProductExtended($product); // $command->doCommand(); // $queue = Local_Queue_Factory::getQueue('search'); // $command = new Backend_Commands_DeleteProductFromIndex($product->project_id, $product->project_category_id); // $msg = $queue->send(serialize($command)); // ppload // Delete collection if ($product->ppload_collection_id) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); $collectionResponse = $pploadApi->deleteCollection($product->ppload_collection_id); } $activityLog = new Default_Model_ActivityLog(); - $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_DELETED, + $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, + Default_Model_ActivityLog::PROJECT_DELETED, $product->toArray()); $this->forward('products', 'user', 'default'); } public function unpublishAction() { $this->_helper->layout()->setLayout('flat_ui'); $memberId = (int)$this->getParam('m'); if ( (empty($this->_authMember->member_id)) OR (empty($memberId)) OR ($this->_authMember->member_id != $memberId) ) { return; } $tableProduct = new Default_Model_Project(); $tableProduct->setInActive($this->_projectId, $memberId); $product = $tableProduct->find($this->_projectId)->current(); if (isset($product->type_id) && $product->type_id == Default_Model_Project::PROJECT_TYPE_UPDATE) { $parentProduct = $tableProduct->find($product->pid)->current(); $product->image_small = $parentProduct->image_small; } $activityLog = new Default_Model_ActivityLog(); - $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_UNPUBLISHED, + $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, + Default_Model_ActivityLog::PROJECT_UNPUBLISHED, $product->toArray()); // remove unpublished project from search index $modelSearch = new Default_Model_Search_Lucene(); $modelSearch->deleteDocument($product); // ppload if ($product->ppload_collection_id) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); // Update collection information $collectionRequest = array( 'category' => $product->project_category_id ); $collectionResponse = $pploadApi->putCollection($product->ppload_collection_id, $collectionRequest); } $this->forward('products', 'user', 'default', array('member_id' => $memberId)); //$this->redirect('/member/'.$memberId.'/products'); } public function publishAction() { $memberId = (int)$this->getParam('m'); if ((empty($this->_authMember->member_id)) OR (empty($memberId)) OR ($this->_authMember->member_id - != $memberId) + != $memberId) ) { return; } $tableProduct = new Default_Model_Project(); - $tableProduct->setActive($this->_authMember->member_id,$this->_projectId); + $tableProduct->setActive($this->_authMember->member_id, $this->_projectId); $product = $tableProduct->find($this->_projectId)->current(); if (isset($product->type_id) && $product->type_id == Default_Model_Project::PROJECT_TYPE_UPDATE) { $parentProduct = $tableProduct->find($product->pid)->current(); $product->image_small = $parentProduct->image_small; } $activityLog = new Default_Model_ActivityLog(); - $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_PUBLISHED, + $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, + Default_Model_ActivityLog::PROJECT_PUBLISHED, $product->toArray()); // add published project to search index // $productInfo = $tableProduct->fetchProductInfo($this->_projectId); // $modelSearch = new Default_Model_Search_Lucene(); // $modelSearch->addDocument($productInfo); // ppload if ($product->ppload_collection_id) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); // Update collection information $collectionRequest = array( 'category' => $product->project_category_id . '-published' ); $collectionResponse = $pploadApi->putCollection($product->ppload_collection_id, $collectionRequest); } $this->forward('products', 'user', 'default', array('member_id' => $memberId)); //$this->redirect('/member/'.$memberId.'/products'); } - public function loadratingsAction() - { + public function loadratingsAction() + { $this->_helper->layout->disableLayout(); - $tableProjectRatings = new Default_Model_DbTable_ProjectRating(); + $tableProjectRatings = new Default_Model_DbTable_ProjectRating(); $ratings = $tableProjectRatings->fetchRating($this->_projectId); $this->_helper->json($ratings); } public function loadtagratingAction() { - $this->_helper->layout->disableLayout(); - //$tableProjectRatings = new Default_Model_DbTable_ProjectRating(); - //$ratings = $tableProjectRatings->fetchTagRating($this->_projectId); - $category_id= $this->getParam('gid'); - $model = new Default_Model_ProjectTagRatings(); - $ratingsLabel = $model->getCategoryTagRatings($category_id); - $ratingsValue=null; - if($ratingsLabel!=null && sizeof($ratingsLabel)>0) - { - $ratingsValue = $model->getProjectTagRatings($this->_projectId); - } - - $this->_helper->json(array( + $this->_helper->layout->disableLayout(); + //$tableProjectRatings = new Default_Model_DbTable_ProjectRating(); + //$ratings = $tableProjectRatings->fetchTagRating($this->_projectId); + $category_id = $this->getParam('gid'); + $model = new Default_Model_ProjectTagRatings(); + $ratingsLabel = $model->getCategoryTagRatings($category_id); + $ratingsValue = null; + if ($ratingsLabel != null && sizeof($ratingsLabel) > 0) { + $ratingsValue = $model->getProjectTagRatings($this->_projectId); + } + + $this->_helper->json(array( 'status' => 'ok', - 'labels' =>$ratingsLabel, - 'values' =>$ratingsValue - )); + 'labels' => $ratingsLabel, + 'values' => $ratingsValue + )); } + public function votetagratingAction() { $this->_helper->layout->disableLayout(); - $vote= $this->getParam('vote'); - $tag_id= $this->getParam('tid'); + $vote = $this->getParam('vote'); + $tag_id = $this->getParam('tid'); + $msg = $this->getParam('msg'); + if (strlen($msg) < 1) { + $this->_helper->json(array( + 'status' => 'error', + 'msg' => 'Please add a comment.' + )); + + return; + }; + $model = new Default_Model_ProjectTagRatings(); - if($this->_authMember->member_id) - { - $checkVote = $model->checkIfVote($this->_authMember->member_id,$this->_projectId,$tag_id); - if(!$checkVote) - { - $model->doVote($this->_authMember->member_id,$this->_projectId,$tag_id,$vote); - }else{ - if($checkVote['vote']== $vote) - { + if ($this->_authMember->member_id) { + $checkVote = $model->checkIfVote($this->_authMember->member_id, $this->_projectId, $tag_id); + if (!$checkVote) { + $model->doVote($this->_authMember->member_id, $this->_projectId, $tag_id, $vote, $msg); + } else { + if ($checkVote['vote'] == $vote) { $model->removeVote($checkVote['tag_rating_id']); - }else{ + } else { $model->removeVote($checkVote['tag_rating_id']); - $model->doVote($this->_authMember->member_id,$this->_projectId,$tag_id,$vote); - } + $model->doVote($this->_authMember->member_id, $this->_projectId, $tag_id, $vote, $msg); + } } - + $this->_helper->json(array( - 'status' => 'ok' - )); - }else{ + 'status' => 'ok' + )); + } else { $this->_helper->json(array( 'status' => 'error', - 'msg' =>'Login please' - )); + 'msg' => 'Login please' + )); } } - + public function loadfilesjsonAction() { $this->_helper->layout->disableLayout(); // $project_id = $this->getParam('pid'); $modelProject = new Default_Model_Project(); $files = $modelProject->fetchFilesForProject($this->_projectId); $salt = PPLOAD_DOWNLOAD_SECRET; foreach ($files as &$file) { $timestamp = time() + 3600; // one hour valid - $hash = hash('sha512',$salt . $file['collection_id'] . $timestamp); // order isn't important at all... just do the same when verifying + $hash = hash('sha512', + $salt . $file['collection_id'] . $timestamp); // order isn't important at all... just do the same when verifying $url = PPLOAD_API_URI . 'files/download/id/' . $file['id'] . '/s/' . $hash . '/t/' . $timestamp; - if(null != $this->_authMember) { + if (null != $this->_authMember) { $url .= '/u/' . $this->_authMember->member_id; } $url .= '/lt/filepreview/' . $file['name']; - $file['url'] = urlencode($url); - } + $file['url'] = urlencode($url); + } $this->_helper->json($files); } - + public function loadfirstfilejsonAction() { $this->_helper->layout->disableLayout(); // $project_id = $this->getParam('pid'); $modelProject = new Default_Model_Project(); $files = $modelProject->fetchFilesForProject($this->_projectId); $salt = PPLOAD_DOWNLOAD_SECRET; $file = $files[0]; - + $timestamp = time() + 3600; // one hour valid - $hash = hash('sha512',$salt . $file['collection_id'] . $timestamp); // order isn't important at all... just do the same when verifying + $hash = hash('sha512', + $salt . $file['collection_id'] . $timestamp); // order isn't important at all... just do the same when verifying $url = PPLOAD_API_URI . 'files/download/id/' . $file['id'] . '/s/' . $hash . '/t/' . $timestamp; - if(null != $this->_authMember) { + if (null != $this->_authMember) { $url .= '/u/' . $this->_authMember->member_id; } $url .= '/lt/filepreview/' . $file['name']; - $file['url'] = urlencode($url); + $file['url'] = urlencode($url); $this->_helper->json($file); } - + public function loadinstallinstructionAction() { $this->_helper->layout->disableLayout(); $infomodel = new Default_Model_Info(); - $text = $infomodel->getOCSInstallInstruction(); - + $text = $infomodel->getOCSInstallInstruction(); + $this->_helper->json(array( - 'status' => 'ok', - 'data' => $text + 'status' => 'ok', + 'data' => $text )); } public function followAction() { $this->_helper->layout()->disableLayout(); // $this->_helper->viewRenderer->setNoRender(true); $this->view->project_id = $this->_projectId; $this->view->authMember = $this->_authMember; if (array_key_exists($this->_projectId, $this->_authMember->projects)) { return; } $projectFollowTable = new Default_Model_DbTable_ProjectFollower(); $newVals = array('project_id' => $this->_projectId, 'member_id' => $this->_authMember->member_id); $where = $projectFollowTable->select()->where('member_id = ?', $this->_authMember->member_id) - ->where('project_id = ?', $this->_projectId, 'INTEGER') - ; + ->where('project_id = ?', $this->_projectId, 'INTEGER'); $result = $projectFollowTable->fetchRow($where); if (null === $result) { $projectFollowTable->createRow($newVals)->save(); $tableProduct = new Default_Model_Project(); $product = $tableProduct->find($this->_projectId)->current(); $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_FOLLOWED, $product->toArray()); } // ppload //Add collection to favorite // $projectTable = new Default_Model_DbTable_Project(); // $projectData = $projectTable->find($this->_projectId)->current(); // if ($projectData->ppload_collection_id) { // $pploadApi = new Ppload_Api(array( // 'apiUri' => PPLOAD_API_URI, // 'clientId' => PPLOAD_CLIENT_ID, // 'secret' => PPLOAD_SECRET // )); // // $favoriteRequest = array( // 'user_id' => $this->_authMember->member_id, // 'collection_id' => $projectData->ppload_collection_id // ); // // $favoriteResponse = $pploadApi->postFavorite($favoriteRequest); // } } public function unfollowAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer('follow'); $this->view->project_id = $this->_projectId; $this->view->authMember = $this->_authMember; $projectFollowTable = new Default_Model_DbTable_ProjectFollower(); $projectFollowTable->delete('member_id=' . $this->_authMember->member_id . ' AND project_id=' - . $this->_projectId); + . $this->_projectId); $tableProduct = new Default_Model_Project(); $product = $tableProduct->find($this->_projectId)->current(); $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_UNFOLLOWED, $product->toArray()); // ppload // Delete collection from favorite // $projectTable = new Default_Model_DbTable_Project(); // $projectData = $projectTable->find($this->_projectId)->current(); // if ($projectData->ppload_collection_id) { // $pploadApi = new Ppload_Api(array( // 'apiUri' => PPLOAD_API_URI, // 'clientId' => PPLOAD_CLIENT_ID, // 'secret' => PPLOAD_SECRET // )); // // $favoriteRequest = array( // 'user_id' => $this->_authMember->member_id, // 'collection_id' => $projectData->ppload_collection_id // ); // // $favoriteResponse = // $pploadApi->postFavorite($favoriteRequest); // This post call will retrieve existing favorite info // if (!empty($favoriteResponse->favorite->id)) { // $favoriteResponse = $pploadApi->deleteFavorite($favoriteResponse->favorite->id); // } // } } public function followpAction() { $this->_helper->layout()->disableLayout(); // $this->_helper->viewRenderer->setNoRender(true); $this->view->project_id = $this->_projectId; $this->view->authMember = $this->_authMember; if (array_key_exists($this->_projectId, $this->_authMember->projects)) { return; } $projectFollowTable = new Default_Model_DbTable_ProjectFollower(); $newVals = array('project_id' => $this->_projectId, 'member_id' => $this->_authMember->member_id); $where = $projectFollowTable->select()->where('member_id = ?', $this->_authMember->member_id) - ->where('project_id = ?', $this->_projectId, 'INTEGER') - ; + ->where('project_id = ?', $this->_projectId, 'INTEGER'); $result = $projectFollowTable->fetchRow($where); if (null === $result) { - $projectFollowTable->createRow($newVals)->save(); + $projectFollowTable->createRow($newVals)->save(); $tableProduct = new Default_Model_Project(); $product = $tableProduct->find($this->_projectId)->current(); $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_FOLLOWED, $product->toArray()); } } public function unfollowpAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer('followp'); $this->view->project_id = $this->_projectId; $this->view->authMember = $this->_authMember; $projectFollowTable = new Default_Model_DbTable_ProjectFollower(); $projectFollowTable->delete('member_id=' . $this->_authMember->member_id . ' AND project_id=' - . $this->_projectId); + . $this->_projectId); $tableProduct = new Default_Model_Project(); $product = $tableProduct->find($this->_projectId)->current(); $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_UNFOLLOWED, $product->toArray()); } - protected function logActivity($logId) - { - $tableProduct = new Default_Model_Project(); - $product = $tableProduct->find($this->_projectId)->current(); - $activityLog = new Default_Model_ActivityLog(); - $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, - $logId, $product->toArray()); - } - - public function followprojectAction() { $this->_helper->layout()->disableLayout(); $this->view->project_id = $this->_projectId; $this->view->authMember = $this->_authMember; // not allow to pling himself - if (array_key_exists($this->_projectId, $this->_authMember->projects)) - { - $this->_helper->json(array( - 'status' => 'error', - 'msg' => 'not allowed' - )); + if (array_key_exists($this->_projectId, $this->_authMember->projects)) { + $this->_helper->json(array( + 'status' => 'error', + 'msg' => 'not allowed' + )); + return; } $projectFollowTable = new Default_Model_DbTable_ProjectFollower(); $newVals = array('project_id' => $this->_projectId, 'member_id' => $this->_authMember->member_id); $where = $projectFollowTable->select()->where('member_id = ?', $this->_authMember->member_id) - ->where('project_id = ?', $this->_projectId, 'INTEGER') ; + ->where('project_id = ?', $this->_projectId, 'INTEGER'); $result = $projectFollowTable->fetchRow($where); if (null === $result) { $projectFollowTable->createRow($newVals)->save(); $this->logActivity(Default_Model_ActivityLog::PROJECT_FOLLOWED); $cnt = $projectFollowTable->countForProject($this->_projectId); - $this->_helper->json(array( - 'status' => 'ok', - 'msg' => 'Success.', - 'cnt' => $cnt, - 'action' =>'insert' - )); - }else{ + $this->_helper->json(array( + 'status' => 'ok', + 'msg' => 'Success.', + 'cnt' => $cnt, + 'action' => 'insert' + )); + } else { $projectFollowTable->delete('member_id=' . $this->_authMember->member_id . ' AND project_id=' - . $this->_projectId); + . $this->_projectId); $this->logActivity(Default_Model_ActivityLog::PROJECT_UNFOLLOWED); $cnt = $projectFollowTable->countForProject($this->_projectId); $this->_helper->json(array( - 'status' => 'ok', - 'msg' => 'Success.', - 'cnt' => $cnt, - 'action' => 'delete' - )); + 'status' => 'ok', + 'msg' => 'Success.', + 'cnt' => $cnt, + 'action' => 'delete' + )); } } + protected function logActivity($logId) + { + $tableProduct = new Default_Model_Project(); + $product = $tableProduct->find($this->_projectId)->current(); + $activityLog = new Default_Model_ActivityLog(); + $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, + $logId, $product->toArray()); + } public function plingprojectAction() { $this->_helper->layout()->disableLayout(); $this->view->project_id = $this->_projectId; $this->view->authMember = $this->_authMember; // not allow to pling himself - if (array_key_exists($this->_projectId, $this->_authMember->projects)) - { - $this->_helper->json(array( - 'status' => 'error', - 'msg' => 'not allowed' - )); + if (array_key_exists($this->_projectId, $this->_authMember->projects)) { + $this->_helper->json(array( + 'status' => 'error', + 'msg' => 'not allowed' + )); + return; } // not allow to pling if not supporter $helperIsSupporter = new Default_View_Helper_IsSupporter(); - if(!$helperIsSupporter->isSupporter($this->_authMember->member_id)) - { - $this->_helper->json(array( - 'status' => 'error', - 'msg' => 'become a supporter first please. ' - )); + if (!$helperIsSupporter->isSupporter($this->_authMember->member_id)) { + $this->_helper->json(array( + 'status' => 'error', + 'msg' => 'become a supporter first please. ' + )); + return; } $projectplings = new Default_Model_ProjectPlings(); $newVals = array('project_id' => $this->_projectId, 'member_id' => $this->_authMember->member_id); $sql = $projectplings->select() - ->where('member_id = ?', $this->_authMember->member_id) - ->where('is_deleted = ?',0) - ->where('project_id = ?', $this->_projectId, 'INTEGER') - ; + ->where('member_id = ?', $this->_authMember->member_id) + ->where('is_deleted = ?', 0) + ->where('project_id = ?', $this->_projectId, 'INTEGER'); $result = $projectplings->fetchRow($sql); if (null === $result) { - $projectplings->createRow($newVals)->save(); - //$this->logActivity(Default_Model_ActivityLog::PROJECT_PLINGED_2); + $projectplings->createRow($newVals)->save(); + //$this->logActivity(Default_Model_ActivityLog::PROJECT_PLINGED_2); - $cnt = $projectplings->getPlingsAmount($this->_projectId); - $this->_helper->json(array( - 'status' => 'ok', - 'msg' => 'Success.', - 'cnt' => $cnt, - 'action' =>'insert' - )); - }else{ + $cnt = $projectplings->getPlingsAmount($this->_projectId); + $this->_helper->json(array( + 'status' => 'ok', + 'msg' => 'Success.', + 'cnt' => $cnt, + 'action' => 'insert' + )); + } else { // delete pling $projectplings->setDelete($result->project_plings_id); //$this->logActivity(Default_Model_ActivityLog::PROJECT_DISPLINGED_2); - $cnt = $projectplings->getPlingsAmount($this->_projectId); + $cnt = $projectplings->getPlingsAmount($this->_projectId); $this->_helper->json(array( - 'status' => 'ok', - 'msg' => 'Success.', - 'cnt' => $cnt, - 'action' => 'delete' - )); + 'status' => 'ok', + 'msg' => 'Success.', + 'cnt' => $cnt, + 'action' => 'delete' + )); } } -/** - - public function unplingprojectAction() - { - $this->_helper->layout()->disableLayout(); - - $projectplings = new Default_Model_ProjectPlings(); - $pling = $projectplings->getPling($this->_projectId,$this->_authMember->member_id); - - if($pling) - { - $projectplings->setDelete($pling->project_plings_id); - $cnt = count($projectplings->getPlings($this->_projectId)); - $this->_helper->json(array( - 'status' => 'ok', - 'deleted' => $pling->project_plings_id, - 'msg' => 'Success. ', - 'cnt' => $cnt - )); - - $tableProduct = new Default_Model_Project(); - $product = $tableProduct->find($this->_projectId)->current(); - - $activityLog = new Default_Model_ActivityLog(); - $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, - Default_Model_ActivityLog::PROJECT_DISPLINGED_2, $product->toArray()); - }else{ - $this->_helper->json(array( - 'status' => 'error', - 'msg' => 'not existing.' - )); - } - - - } -**/ + /** + * + * public function unplingprojectAction() + * { + * $this->_helper->layout()->disableLayout(); + * + * $projectplings = new Default_Model_ProjectPlings(); + * $pling = $projectplings->getPling($this->_projectId,$this->_authMember->member_id); + * + * if($pling) + * { + * $projectplings->setDelete($pling->project_plings_id); + * $cnt = count($projectplings->getPlings($this->_projectId)); + * $this->_helper->json(array( + * 'status' => 'ok', + * 'deleted' => $pling->project_plings_id, + * 'msg' => 'Success. ', + * 'cnt' => $cnt + * )); + * + * $tableProduct = new Default_Model_Project(); + * $product = $tableProduct->find($this->_projectId)->current(); + * + * $activityLog = new Default_Model_ActivityLog(); + * $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, + * Default_Model_ActivityLog::PROJECT_DISPLINGED_2, $product->toArray()); + * }else{ + * $this->_helper->json(array( + * 'status' => 'error', + * 'msg' => 'not existing.' + * )); + * } + * + * + * } + **/ public function followsAction() { $projectFollowTable = new Default_Model_Member(); $memberId = $this->_authMember->member_id; $this->view->productList = $projectFollowTable->fetchFollowedProjects($memberId); $projectArray = $this->generateFollowedProjectsViewData($this->view->productList); $this->view->productArray['followedProjects'] = $projectArray; } /** * @param $list * * @return array */ protected function generateFollowedProjectsViewData($list) { $viewArray = array(); if (count($list) == 0) { return $viewArray; } $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); foreach ($list as $element) { $arr = array(); $arr['id'] = $element->project_id; $arr['name'] = $element->title; $arr['image'] = $element->image_small; $arr['url'] = $helperBuildProductUrl->buildProductUrl($element->project_id); $arr['urlUnFollow'] = $helperBuildProductUrl->buildProductUrl($element->project_id, 'unfollow'); #$arr['showUrlUnFollow'] = $this->view->isMember; $viewArray[] = $arr; } return $viewArray; } public function verifycodeAction() { $this->_helper->layout()->disableLayout(); if ($this->_request->isXmlHttpRequest()) { $tabProject = new Default_Model_DbTable_Project(); $dataProject = $tabProject->find($this->_projectId)->current(); $this->createTaskWebsiteOwnerVerification($dataProject); $this->view->message = 'Your product page is stored for validation.'; return; } $this->view->message = 'This service is not available at the moment. Please try again later.'; } + /** + * @param $projectData + * + * @throws Zend_Exception + * @throws Zend_Queue_Exception + */ + protected function createTaskWebsiteOwnerVerification($projectData) + { + if (empty($projectData->link_1)) { + return; + } + $checkAuthCode = new Local_Verification_WebsiteProject(); + $authCode = $checkAuthCode->generateAuthCode(stripslashes($projectData->link_1)); + $queue = Local_Queue_Factory::getQueue(); + $command = new Backend_Commands_CheckProjectWebsite($projectData->project_id, $projectData->link_1, $authCode); + $queue->send(serialize($command)); + } + /** * @throws Zend_Controller_Action_Exception * @deprecated */ public function fetchAction() { $this->_helper->layout()->disableLayout(); if ($this->_request->isXmlHttpRequest()) { $this->view->authMember = $this->_authMember; $this->fetchDataForIndexView(); $tableProject = new Default_Model_Project(); $this->view->supporting = $tableProject->fetchProjectSupporterWithPlings($this->_projectId); if (false === isset($this->view->product)) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } $helperUserIsOwner = new Default_View_Helper_UserIsOwner(); $helperIsProjectActive = new Default_View_Helper_IsProjectActive(); if ((false === $helperIsProjectActive->isProjectActive($this->view->product->project_status)) AND (false - === $helperUserIsOwner->UserIsOwner($this->view->product->member_id)) + === $helperUserIsOwner->UserIsOwner($this->view->product->member_id)) ) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } $tablePageViews = new Default_Model_DbTable_StatPageViews(); $tablePageViews->savePageView($this->_projectId, $this->getRequest()->getClientIp(), $this->_authMember->member_id); } $this->_helper->json(get_object_vars($this->view)); } public function claimAction() { $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductInfo($this->_projectId); if ($productInfo->claimable != Default_Model_Project::PROJECT_CLAIMABLE) { throw new Zend_Controller_Action_Exception('Method not available', 404); } $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); if (empty($productInfo->claimed_by_member)) { $modelProduct->setClaimedByMember($this->_authMember->member_id, $this->_projectId); $claimMail = new Default_Plugin_SendMail('tpl_mail_claim_product'); $claimMail->setTemplateVar('sender', $this->_authMember->mail); $claimMail->setTemplateVar('productid', $productInfo->project_id); $claimMail->setTemplateVar('producttitle', $productInfo->title); $claimMail->setTemplateVar('userid', $this->_authMember->member_id); $claimMail->setTemplateVar('username', $this->_authMember->username); $claimMail->setTemplateVar('usermail', $this->_authMember->mail); $claimMail->setReceiverMail(array('contact@opendesktop.org')); $claimMail->send(); $claimMailConfirm = new Default_Plugin_SendMail('tpl_mail_claim_confirm'); $claimMailConfirm->setTemplateVar('sender', 'contact@opendesktop.org'); $claimMailConfirm->setTemplateVar('producttitle', $productInfo->title); $claimMailConfirm->setTemplateVar('productlink', 'http://' . $this->getRequest()->getHttpHost() - . $helperBuildProductUrl->buildProductUrl($productInfo->project_id)); + . $helperBuildProductUrl->buildProductUrl($productInfo->project_id)); $claimMailConfirm->setTemplateVar('username', $this->_authMember->username); $claimMailConfirm->setReceiverMail($this->_authMember->mail); $claimMailConfirm->send(); } $this->_helper->viewRenderer('index'); $this->indexAction(); } public function makerconfigAction() { $this->_helper->layout()->disableLayout(); $widgetProjectId = (int)$this->getParam('project_id'); if (false == isset($widgetProjectId)) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } $widgetDefaultModel = new Default_Model_DbTable_ProjectWidgetDefault(); $widgetDefault = $widgetDefaultModel->fetchConfig($widgetProjectId); if (!isset($widgetDefault)) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } else { $this->view->widgetConfig = $widgetDefault; $productModel = new Default_Model_Project(); $this->view->product = $productModel->fetchProductDataFromMV($widgetProjectId); $this->view->supporting = $productModel->fetchProjectSupporterWithPlings($widgetProjectId); $plingModel = new Default_Model_DbTable_Plings(); $this->view->comments = $plingModel->getCommentsForProject($widgetProjectId, 10); $websiteOwner = new Local_Verification_WebsiteProject(); $this->view->authCode = ''; + . $websiteOwner->generateAuthCode(stripslashes($this->view->product->link_1)) . '" />'; } } /** * ppload */ public function addpploadfileAction() { $this->_helper->layout()->disableLayout(); $log = Zend_Registry::get('logger'); $log->debug('**********' . __CLASS__ . '::' . __FUNCTION__ . '**********' . "\n"); $projectTable = new Default_Model_DbTable_Project(); $projectData = $projectTable->find($this->_projectId)->current(); $error_text = ''; // Add file to ppload collection if (!empty($_FILES['file_upload']['tmp_name']) && $_FILES['file_upload']['error'] == UPLOAD_ERR_OK ) { $tmpFilename = dirname($_FILES['file_upload']['tmp_name']) . '/' . basename($_FILES['file_upload']['name']); $log->debug(__CLASS__ . '::' . __FUNCTION__ . '::' . print_r($tmpFilename, true) . "\n"); move_uploaded_file($_FILES['file_upload']['tmp_name'], $tmpFilename); $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); $fileRequest = array( 'file' => $tmpFilename, 'owner_id' => $this->_authMember->member_id ); - + //Admins can upload files for users $helperUserRole = new Backend_View_Helper_UserRole(); $userRoleName = $helperUserRole->userRole(); if (Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN == $userRoleName) { $member_id = $projectData->member_id; $fileRequest = array( 'file' => $tmpFilename, 'owner_id' => $member_id ); } - + if ($projectData->ppload_collection_id) { // Append to existing collection $fileRequest['collection_id'] = $projectData->ppload_collection_id; } //if (isset($_POST['file_description'])) { // $fileRequest['description'] = mb_substr($_POST['file_description'], 0, 140); //} $fileResponse = $pploadApi->postFile($fileRequest); $log->debug(__CLASS__ . '::' . __FUNCTION__ . '::' . print_r($fileResponse, true) . "\n"); unlink($tmpFilename); if (!empty($fileResponse->file->collection_id)) { if (!$projectData->ppload_collection_id) { // Save collection ID $projectData->ppload_collection_id = $fileResponse->file->collection_id; //20180219 ronald: we set the changed_at only by new files or new updates - if((int)$this->_authMember->member_id==(int)$projectData->member_id) - { + if ((int)$this->_authMember->member_id == (int)$projectData->member_id) { $projectData->changed_at = new Zend_Db_Expr('NOW()'); } else { - $log->info('********** ' . __CLASS__ . '::' . __FUNCTION__ . ' Project ChangedAt is not set: Auth-Member ('.$this->_authMember->member_id.') != Project-Owner ('.$projectData->member_id.'): **********' . "\n"); - } + $log->info('********** ' . __CLASS__ . '::' . __FUNCTION__ . ' Project ChangedAt is not set: Auth-Member (' . $this->_authMember->member_id . ') != Project-Owner (' . $projectData->member_id . '): **********' . "\n"); + } $projectData->ghns_excluded = 0; $projectData->save(); $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $projectData->member_id, Default_Model_ActivityLog::PROJECT_EDITED, $projectData->toArray()); // Update profile information $memberTable = new Default_Model_DbTable_Member(); $memberSettings = $memberTable->find($this->_authMember->member_id)->current(); $mainproject = $projectTable->find($memberSettings->main_project_id)->current(); $profileName = ''; if ($memberSettings->firstname || $memberSettings->lastname ) { $profileName = trim($memberSettings->firstname . ' ' . $memberSettings->lastname); } else { if ($memberSettings->username) { $profileName = $memberSettings->username; } } $profileRequest = array( 'owner_id' => $this->_authMember->member_id, 'name' => $profileName, 'email' => $memberSettings->mail, 'homepage' => $memberSettings->link_website, 'description' => $mainproject->description ); $profileResponse = $pploadApi->postProfile($profileRequest); // Update collection information $collectionCategory = $projectData->project_category_id; if (Default_Model_Project::PROJECT_ACTIVE == $projectData->status) { $collectionCategory .= '-published'; } $collectionRequest = array( 'title' => $projectData->title, 'description' => $projectData->description, 'category' => $collectionCategory, 'content_id' => $projectData->project_id ); $collectionResponse = $pploadApi->putCollection($projectData->ppload_collection_id, $collectionRequest); // Store product image as collection thumbnail $this->_updatePploadMediaCollectionthumbnail($projectData); } else { //20180219 ronald: we set the changed_at only by new files or new updates - if((int)$this->_authMember->member_id==(int)$projectData->member_id) - { + if ((int)$this->_authMember->member_id == (int)$projectData->member_id) { $projectData->changed_at = new Zend_Db_Expr('NOW()'); } else { - $log->info('********** ' . __CLASS__ . '::' . __FUNCTION__ . ' Project ChangedAt is not set: Auth-Member ('.$this->_authMember->member_id.') != Project-Owner ('.$projectData->member_id.'): **********' . "\n"); - } + $log->info('********** ' . __CLASS__ . '::' . __FUNCTION__ . ' Project ChangedAt is not set: Auth-Member (' . $this->_authMember->member_id . ') != Project-Owner (' . $projectData->member_id . '): **********' . "\n"); + } $projectData->ghns_excluded = 0; - $projectData->save(); + $projectData->save(); } - + //If this file is a video, we have to convert it for preview - if(!empty($fileResponse->file->type) && in_array($fileResponse->file->type, Backend_Commands_ConvertVideo::$VIDEO_FILE_TYPES)) { + if (!empty($fileResponse->file->type) && in_array($fileResponse->file->type, + Backend_Commands_ConvertVideo::$VIDEO_FILE_TYPES)) { $queue = Local_Queue_Factory::getQueue(); - $command = new Backend_Commands_ConvertVideo($projectData->ppload_collection_id, $fileResponse->file->id, $fileResponse->file->type); + $command = new Backend_Commands_ConvertVideo($projectData->ppload_collection_id, + $fileResponse->file->id, $fileResponse->file->type); $queue->send(serialize($command)); } //If this file is bigger than XXX MB (see application.ini), then create a webtorrent file $config = Zend_Registry::get('config'); $minFileSize = $config->torrent->media->min_filesize; - if(!empty($fileResponse->file->size) && $fileResponse->file->size >= $minFileSize) { + if (!empty($fileResponse->file->size) && $fileResponse->file->size >= $minFileSize) { $queue = Local_Queue_Factory::getQueue(); $command = new Backend_Commands_CreateTorrent($fileResponse->file); $queue->send(serialize($command)); } - + //If this is a cbr or cbz comic archive, then start an extracting job - if($this->endsWith($fileResponse->file->name, '.cbr') || $this->endsWith($fileResponse->file->name, '.cbz')) { + if ($this->endsWith($fileResponse->file->name, '.cbr') || $this->endsWith($fileResponse->file->name, + '.cbz')) { $queue = Local_Queue_Factory::getQueue(); $command = new Backend_Commands_ExtractComic($fileResponse->file); - $queue->send(serialize($command)); + $queue->send(serialize($command)); } $this->_helper->json(array( 'status' => 'ok', 'file' => $fileResponse->file )); return; } } $log->debug('********** END ' . __CLASS__ . '::' . __FUNCTION__ . '**********' . "\n"); $this->_helper->json(array('status' => 'error', 'error_text' => $error_text)); } - + private function endsWith($haystack, $needle) { return $needle === "" || substr(strtolower($haystack), -strlen($needle)) === strtolower($needle); } /** * ppload */ public function updatepploadfileAction() { $this->_helper->layout()->disableLayout(); $log = Zend_Registry::get('logger'); $log->debug('**********' . __CLASS__ . '::' . __FUNCTION__ . '**********' . "\n"); $projectTable = new Default_Model_DbTable_Project(); $projectData = $projectTable->find($this->_projectId)->current(); $error_text = ''; // Update a file in ppload collection if (!empty($_POST['file_id'])) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); $fileResponse = $pploadApi->getFile($_POST['file_id']); if (isset($fileResponse->file->collection_id) && $fileResponse->file->collection_id == $projectData->ppload_collection_id ) { $fileRequest = array(); $tmpFilename = ''; if (!empty($_FILES['file_upload']['tmp_name']) && $_FILES['file_upload']['error'] == UPLOAD_ERR_OK ) { $tmpFilename = dirname($_FILES['file_upload']['tmp_name']) . '/' . basename($_FILES['file_upload']['name']); $log->debug(__CLASS__ . '::' . __FUNCTION__ . '::' . print_r($tmpFilename, true) . "\n"); move_uploaded_file($_FILES['file_upload']['tmp_name'], $tmpFilename); $fileRequest['file'] = $tmpFilename; - + //20180219 ronald: we set the changed_at only by new files or new updates - if((int)$this->_authMember->member_id==(int)$projectData->member_id) - { + if ((int)$this->_authMember->member_id == (int)$projectData->member_id) { $projectData->changed_at = new Zend_Db_Expr('NOW()'); } else { - $log->info('********** ' . __CLASS__ . '::' . __FUNCTION__ . ' Project ChangedAt is not set: Auth-Member ('.$this->_authMember->member_id.') != Project-Owner ('.$projectData->member_id.'): **********' . "\n"); - } + $log->info('********** ' . __CLASS__ . '::' . __FUNCTION__ . ' Project ChangedAt is not set: Auth-Member (' . $this->_authMember->member_id . ') != Project-Owner (' . $projectData->member_id . '): **********' . "\n"); + } $projectData->ghns_excluded = 0; - $projectData->save(); - + $projectData->save(); + } if (isset($_POST['file_description'])) { $fileRequest['description'] = mb_substr($_POST['file_description'], 0, 140); } if (isset($_POST['file_category'])) { $fileRequest['category'] = $_POST['file_category']; } if (isset($_POST['file_tags'])) { $fileRequest['tags'] = $_POST['file_tags']; } if (isset($_POST['ocs_compatible'])) { $fileRequest['ocs_compatible'] = $_POST['ocs_compatible']; } if (isset($_POST['file_version'])) { $fileRequest['version'] = $_POST['file_version']; } $fileResponse = $pploadApi->putFile($_POST['file_id'], $fileRequest); $log->debug(__CLASS__ . '::' . __FUNCTION__ . '::' . print_r($fileResponse, true) . "\n"); if ($tmpFilename) { unlink($tmpFilename); } if (isset($fileResponse->status) && $fileResponse->status == 'success' ) { //If this file is bigger than XXX MB (see application.ini), then create a webtorrent file $config = Zend_Registry::get('config'); $minFileSize = $config->torrent->media->min_filesize; - if(!empty($fileResponse->file->size) && $fileResponse->file->size >= $minFileSize) { + if (!empty($fileResponse->file->size) && $fileResponse->file->size >= $minFileSize) { $queue = Local_Queue_Factory::getQueue(); $command = new Backend_Commands_CreateTorrent($fileResponse->file); $queue->send(serialize($command)); } $this->_helper->json(array( 'status' => 'ok', 'file' => $fileResponse->file )); return; } else { $error_text .= 'Response: $pploadApi->putFile(): ' . json_encode($fileResponse) - . '; $fileResponse->status: ' . $fileResponse->status; + . '; $fileResponse->status: ' . $fileResponse->status; } } else { $error_text .= 'PPload Response: ' . json_encode($fileResponse) - . '; fileResponse->file->collection_id: ' . $fileResponse->file->collection_id - . ' != $projectData->ppload_collection_id: ' . $projectData->ppload_collection_id; + . '; fileResponse->file->collection_id: ' . $fileResponse->file->collection_id + . ' != $projectData->ppload_collection_id: ' . $projectData->ppload_collection_id; } } else { $error_text .= 'No CollectionId or no FileId. CollectionId: ' . $projectData->ppload_collection_id - . ', FileId: ' . $_POST['file_id']; + . ', FileId: ' . $_POST['file_id']; } $log->debug('********** END ' . __CLASS__ . '::' . __FUNCTION__ . '**********' . "\n"); $this->_helper->json(array('status' => 'error', 'error_text' => $error_text)); } public function updatefiletagAction() { $this->_helper->layout()->disableLayout(); $error_text = ''; // Update a file information in ppload collection if (!empty($_POST['file_id'])) { $tagId = null; if (isset($_POST['tag_id'])) { $tagId = $_POST['tag_id']; } $tagGroupId = null; if (isset($_POST['tag_group_id'])) { $tagGroupId = $_POST['tag_group_id']; } //set architecture $modelTags = new Default_Model_Tags(); $modelTags->saveFileTagForProjectAndTagGroup($this->_projectId, $_POST['file_id'], $tagId, $tagGroupId); $this->_helper->json(array('status' => 'ok')); return; } else { $error_text .= 'No FileId. , FileId: ' . $_POST['file_id']; } $this->_helper->json(array('status' => 'error', 'error_text' => $error_text)); } - + public function deletefiletagAction() { $this->_helper->layout()->disableLayout(); $error_text = ''; // Update a file information in ppload collection if (!empty($_POST['file_id'])) { $tagId = null; if (isset($_POST['tag_id'])) { $tagId = $_POST['tag_id']; } //set architecture $modelTags = new Default_Model_Tags(); $modelTags->deleteFileTagForProject($this->_projectId, $_POST['file_id'], $tagId); $this->_helper->json(array('status' => 'ok')); return; } else { $error_text .= 'No FileId. , FileId: ' . $_POST['file_id']; } $this->_helper->json(array('status' => 'error', 'error_text' => $error_text)); } - public function updatecompatibleAction() { $this->_helper->layout()->disableLayout(); $error_text = ''; // Update a file information in ppload collection if (!empty($_POST['file_id'])) { $typeId = null; if (isset($_POST['is_compatible'])) { $is_compatible = $_POST['is_compatible']; } return; } else { $error_text .= 'No FileId. , FileId: ' . $_POST['file_id']; } $this->_helper->json(array('status' => 'error', 'error_text' => $error_text)); } - public function startdownloadAction() { + public function startdownloadAction() + { $this->_helper->layout()->disableLayout(); /** * Save Download-Data in Member_Download_History */ $file_id = $this->getParam('file_id'); $file_type = $this->getParam('file_type'); $file_name = $this->getParam('file_name'); $file_size = $this->getParam('file_size'); $projectId = $this->_projectId; - - $this->redirect('/dl?file_id='.$file_id.'&file_type='.$file_type.'&file_name='.$file_name.'&file_size='.$file_size.'&project_id='.$projectId); - - -// if ($_SERVER['REQUEST_METHOD'] == 'POST') { -/* if(isset($file_id) && isset($projectId) && isset($memberId)) { - $memberDlHistory = new Default_Model_DbTable_MemberDownloadHistory(); - $data = array('project_id' => $projectId, 'member_id' => $memberId, 'file_id' => $file_id, 'file_type' => $file_type, 'file_name' => $file_name, 'file_size' => $file_size); - $memberDlHistory->createRow($data)->save(); - } - $url = urldecode($urltring); - $this->redirect($url); - * - */ + $this->redirect('/dl?file_id=' . $file_id . '&file_type=' . $file_type . '&file_name=' . $file_name . '&file_size=' . $file_size . '&project_id=' . $projectId); + + +// if ($_SERVER['REQUEST_METHOD'] == 'POST') { + /* if(isset($file_id) && isset($projectId) && isset($memberId)) { + $memberDlHistory = new Default_Model_DbTable_MemberDownloadHistory(); + $data = array('project_id' => $projectId, 'member_id' => $memberId, 'file_id' => $file_id, 'file_type' => $file_type, 'file_name' => $file_name, 'file_size' => $file_size); + $memberDlHistory->createRow($data)->save(); + } + + $url = urldecode($urltring); + $this->redirect($url); + * + */ // } else { // $this->redirect('/ads?file_id='.$file_id); // } } + /** + * ppload + */ + /*public function deletepploadcollectionAction() + { + $this->_helper->layout()->disableLayout(); + + $projectTable = new Default_Model_DbTable_Project(); + $projectData = $projectTable->find($this->_projectId)->current(); + + // Delete ppload collection + if ($projectData->ppload_collection_id) { + $pploadApi = new Ppload_Api(array( + 'apiUri' => PPLOAD_API_URI, + 'clientId' => PPLOAD_CLIENT_ID, + 'secret' => PPLOAD_SECRET + )); + + $collectionResponse = $pploadApi->deleteCollection($projectData->ppload_collection_id); + + if (isset($collectionResponse->status) + && $collectionResponse->status == 'success' + ) { + $projectData->ppload_collection_id = null; + $projectData->changed_at = new Zend_Db_Expr('NOW()'); + $projectData->save(); + + $activityLog = new Default_Model_ActivityLog(); + $activityLog->writeActivityLog( + $this->_projectId, + $projectData->member_id, + Default_Model_ActivityLog::PROJECT_EDITED, + $projectData->toArray() + ); + + $this->_helper->json(array('status' => 'ok')); + return; + } + } + + $this->_helper->json(array('status' => 'error')); + }*/ /** * ppload */ public function deletepploadfileAction() { $this->_helper->layout()->disableLayout(); $projectTable = new Default_Model_DbTable_Project(); $projectData = $projectTable->find($this->_projectId)->current(); $error_text = ''; // Delete file from ppload collection if (!empty($_POST['file_id'])) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); $fileResponse = $pploadApi->getFile($_POST['file_id']); if (isset($fileResponse->file->collection_id) && $fileResponse->file->collection_id == $projectData->ppload_collection_id ) { $fileResponse = $pploadApi->deleteFile($_POST['file_id']); if (isset($fileResponse->status) && $fileResponse->status == 'success' ) { $this->_helper->json(array('status' => 'ok')); return; } else { $error_text .= 'Response: $pploadApi->putFile(): ' . json_encode($fileResponse); } } } $this->_helper->json(array('status' => 'error', 'error_text' => $error_text)); } /** * ppload */ public function deletepploadfilesAction() { $this->_helper->layout()->disableLayout(); $projectTable = new Default_Model_DbTable_Project(); $projectData = $projectTable->find($this->_projectId)->current(); // Delete all files in ppload collection if ($projectData->ppload_collection_id) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); $filesRequest = array( 'collection_id' => $projectData->ppload_collection_id, 'perpage' => 1000 ); $filesResponse = $pploadApi->getFiles($filesRequest); if (isset($filesResponse->status) && $filesResponse->status == 'success' ) { foreach ($filesResponse->files as $file) { $fileResponse = $pploadApi->deleteFile($file->id); if (!isset($fileResponse->status) || $fileResponse->status != 'success' ) { $this->_helper->json(array('status' => 'error')); return; } } } $this->_helper->json(array('status' => 'ok')); return; } $this->_helper->json(array('status' => 'error')); } - /** - * ppload - */ - /*public function deletepploadcollectionAction() - { - $this->_helper->layout()->disableLayout(); - - $projectTable = new Default_Model_DbTable_Project(); - $projectData = $projectTable->find($this->_projectId)->current(); - - // Delete ppload collection - if ($projectData->ppload_collection_id) { - $pploadApi = new Ppload_Api(array( - 'apiUri' => PPLOAD_API_URI, - 'clientId' => PPLOAD_CLIENT_ID, - 'secret' => PPLOAD_SECRET - )); - - $collectionResponse = $pploadApi->deleteCollection($projectData->ppload_collection_id); - - if (isset($collectionResponse->status) - && $collectionResponse->status == 'success' - ) { - $projectData->ppload_collection_id = null; - $projectData->changed_at = new Zend_Db_Expr('NOW()'); - $projectData->save(); - $activityLog = new Default_Model_ActivityLog(); - $activityLog->writeActivityLog( - $this->_projectId, - $projectData->member_id, - Default_Model_ActivityLog::PROJECT_EDITED, - $projectData->toArray() - ); - - $this->_helper->json(array('status' => 'ok')); - return; - } - } - - $this->_helper->json(array('status' => 'error')); - }*/ public function saveproductAction() { $form = new Default_Form_Product(); // we don't need to test a file which doesn't exist in this case. The Framework stumbles if $_FILES is empty. if ($this->_request->isXmlHttpRequest() AND (count($_FILES) == 0)) { $form->removeElement('image_small_upload'); // $form->removeElement('image_big_upload'); $form->removeSubForm('gallery'); $form->removeElement('project_id'); //(workaround: Some Browsers send "0" in some cases.) } if (false === $form->isValid($_POST)) { $errors = $form->getMessages(); $messages = $this->getErrorMessages($errors); $this->_helper->json(array('status' => 'error', 'messages' => $messages)); } $formValues = $form->getValues(); $formValues['status'] = Default_Model_Project::PROJECT_INCOMPLETE; $modelProject = new Default_Model_Project(); $newProject = $modelProject->createProject($this->_authMember->member_id, $formValues, $this->_authMember->username); //$this->createSystemPlingForNewProject($newProject->project_id); //New Project in Session, for AuthValidation (owner) $this->_auth->getIdentity()->projects[$newProject->project_id] = array('project_id' => $newProject->project_id); $this->_helper->json(array('status' => 'ok', 'project_id' => $newProject->project_id)); } - - protected function createPling($member_id,$project_id) - { - $projectplings = new Default_Model_ProjectPlings(); - $newVals = array('project_id' =>$project_id, 'member_id' => $member_id); - $sql = $projectplings->select() - ->where('member_id = ?', $this->_authMember->member_id) - ->where('is_deleted = ?',0) - ->where('project_id = ?', $this->_projectId, 'INTEGER'); - $result = $projectplings->fetchRow($sql); - if (null === $result) { - $projectplings->createRow($newVals)->save(); - } - } - - - /** * @param $errors * * @return array */ protected function getErrorMessages($errors) { $messages = array(); foreach ($errors as $element => $row) { if (!empty($row) && $element != 'submit') { foreach ($row as $validator => $message) { $messages[$element][] = $message; } } } return $messages; } public function searchAction() - { + { // Filter-Parameter $params = $this->getAllParams(); $filterInput = new Zend_Filter_Input( array( - '*' => 'StringTrim', - 'projectSearchText' => array(new Zend_Filter_Callback('stripslashes'),'StripTags'), - 'page' => 'digits', - 'pci' => 'digits', - 'ls' => 'digits', - 't' => array(new Zend_Filter_Callback('stripslashes'),'StripTags'), - 'pkg'=> array(new Zend_Filter_Callback('stripslashes'),'StripTags'), - 'lic'=> array(new Zend_Filter_Callback('stripslashes'),'StripTags'), - 'arch'=> array(new Zend_Filter_Callback('stripslashes'),'StripTags') + '*' => 'StringTrim', + 'projectSearchText' => array(new Zend_Filter_Callback('stripslashes'), 'StripTags'), + 'page' => 'digits', + 'pci' => 'digits', + 'ls' => 'digits', + 't' => array(new Zend_Filter_Callback('stripslashes'), 'StripTags'), + 'pkg' => array(new Zend_Filter_Callback('stripslashes'), 'StripTags'), + 'lic' => array(new Zend_Filter_Callback('stripslashes'), 'StripTags'), + 'arch' => array(new Zend_Filter_Callback('stripslashes'), 'StripTags') ), array( 'projectSearchText' => array( new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)), 'presence' => 'required' ), 'page' => array('digits', 'default' => '1'), 'f' => array( new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)), //new Zend_Validate_InArray(array('f'=>'tags')), 'allowEmpty' => true ), - 'pci' => array('digits', + 'pci' => array( + 'digits', 'allowEmpty' => true ), - 'ls' => array('digits', + 'ls' => array( + 'digits', 'allowEmpty' => true ), - 't' => array(new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)), + 't' => array( + new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)), 'allowEmpty' => true ), - 'pkg' => array(new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)), + 'pkg' => array( + new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)), 'allowEmpty' => true ), - 'lic' => array(new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)), + 'lic' => array( + new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)), 'allowEmpty' => true ), - 'arch' => array(new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)), - 'allowEmpty' => true) + 'arch' => array( + new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)), + 'allowEmpty' => true + ) ), $params); - - if ($filterInput->hasInvalid()) { $this->_helper->flashMessenger->addMessage('

There was an error. Please check your input and try again.

'); + return; } - $this->view->searchText = $filterInput->getEscaped('projectSearchText'); $this->view->page = $filterInput->getEscaped('page'); $this->view->searchField = $filterInput->getEscaped('f'); $this->view->pci = $filterInput->getEscaped('pci'); $this->view->ls = $filterInput->getEscaped('ls'); $this->view->t = $filterInput->getEscaped('t'); $this->view->pkg = $filterInput->getEscaped('pkg'); $this->view->arch = $filterInput->getEscaped('arch'); $this->view->lic = $filterInput->getEscaped('lic'); $this->view->store = $this->getParam('domain_store_id'); - if(isset($params['isJson'])) - { + if (isset($params['isJson'])) { $this->_helper->layout()->disableLayout(); - $filterScore = $this->view->ls ? 'laplace_score:['.$this->view->ls.' TO '.($this->view->ls+9).']':null; - $filterCat = $this->view->pci ? 'project_category_id:('.$this->view->pci.')' : null; - $filterTags = $this->view->t ? 'tags:('.$this->view->t.')' : null; - $filterPkg = $this->view->pkg ? 'package_names:('.$this->view->pkg.')' : null; - $filterArch = $this->view->arch ? 'arch_names:('.$this->view->arch.')' : null; - $filterLic = $this->view->lic ? 'license_names:('.$this->view->lic.')' : null; + $filterScore = $this->view->ls ? 'laplace_score:[' . $this->view->ls . ' TO ' . ($this->view->ls + 9) . ']' : null; + $filterCat = $this->view->pci ? 'project_category_id:(' . $this->view->pci . ')' : null; + $filterTags = $this->view->t ? 'tags:(' . $this->view->t . ')' : null; + $filterPkg = $this->view->pkg ? 'package_names:(' . $this->view->pkg . ')' : null; + $filterArch = $this->view->arch ? 'arch_names:(' . $this->view->arch . ')' : null; + $filterLic = $this->view->lic ? 'license_names:(' . $this->view->lic . ')' : null; // $param = array('q' => $this->view->searchText ,'store'=>$this->view->store,'page' => $this->view->page // , 'count' => 10, 'qf' => $this->view->searchField, 'fq' => array($filterCat, $filterScore, $filterTags,$filterPkg,$filterArch,$filterLic)); - - $param = array('q' => 'test','store'=>null,'page' => 1 - , 'count' => 10); + + $param = array( + 'q' => 'test', + 'store' => null, + 'page' => 1 + , + 'count' => 10 + ); $viewHelperImage = new Default_View_Helper_Image(); - + $modelSearch = new Default_Model_Solr(); try { $result = $modelSearch->search($param); - $products = $result['hits']; - + $products = $result['hits']; + // var_dump($products); // die; - $ps=array(); + $ps = array(); foreach ($products as $p) { $img = $viewHelperImage->Image($p->image_small, array( 'width' => 50, 'height' => 50 )); - $ps[] =array('description'=>$p->description - ,'title' =>$p->title - ,'project_id' =>$p->project_id - ,'member_id'=>$p->member_id - ,'username' => $p->username - ,'laplace_score' =>$p->laplace_score - ,'score' =>$p->score - ,'image_small' =>$img); + $ps[] = array( + 'description' => $p->description + , + 'title' => $p->title + , + 'project_id' => $p->project_id + , + 'member_id' => $p->member_id + , + 'username' => $p->username + , + 'laplace_score' => $p->laplace_score + , + 'score' => $p->score + , + 'image_small' => $img + ); } - + $this->_helper->json(array( - 'status' => 'ok', + 'status' => 'ok', 'products' => $ps, - 'q' =>$param + 'q' => $param )); } catch (Exception $e) { $this->_helper->json(array( 'status' => 'err', - 'msg' => 'Not Found! Try again.' + 'msg' => 'Not Found! Try again.' )); - } - + } + + } + + + } + + public function startmediaviewajaxAction() + { + return $this->startvideoajaxAction(); + } + + public function startvideoajaxAction() + { + $this->_helper->layout()->disableLayout(); + + $collection_id = null; + $file_id = null; + $memberId = $this->_authMember->member_id; + $media_view_type_id = $this->getParam('type_id'); + if (!$media_view_type_id) { + // default + $media_view_type_id = Default_Model_DbTable_MediaViews::MEDIA_TYPE_VIDEO; + } + + if ($this->hasParam('collection_id') && $this->hasParam('file_id')) { + $collection_id = $this->getParam('collection_id'); + $file_id = $this->getParam('file_id'); + $id = null; + + //Log media view + try { + $mediaviewsTable = new Default_Model_DbTable_MediaViews(); + $id = $mediaviewsTable->getNewId(); + $data = array( + 'media_view_id' => $id, + 'media_view_type_id' => $media_view_type_id, + 'project_id' => $this->_projectId, + 'collection_id' => $collection_id, + 'file_id' => $file_id, + 'start_timestamp' => new Zend_Db_Expr ('Now()'), + 'ip' => $this->getRealIpAddr(), + 'referer' => $this->getReferer() + ); + if (!empty($memberId)) { + $data['member_id'] = $memberId; + } + $data['source'] = 'OCS-Webserver'; + + $mediaviewsTable->createRow($data)->save(); + + } catch (Exception $exc) { + //echo $exc->getTraceAsString(); + $errorLog = Zend_Registry::get('logger'); + $errorLog->err(__METHOD__ . ' - ' . $exc->getMessage() . ' ---------- ' . PHP_EOL); + } + + + $this->_helper->json(array('status' => 'success', 'MediaViewId' => $id)); + + return; + } + + $this->_helper->json(array('status' => 'error')); + } + + function getRealIpAddr() + { + if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet + { + $ip = $_SERVER['HTTP_CLIENT_IP']; + } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy + { + $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; + } else { + $ip = $_SERVER['REMOTE_ADDR']; + } + + return $ip; + } + + function getReferer() + { + $referer = null; + if (!empty($_SERVER['HTTP_REFERER'])) { + $referer = $_SERVER['HTTP_REFERER']; + } + + return $referer; + } + + public function stopmediaviewajaxAction() + { + return $this->stopvideoajaxAction(); + } + + public function stopvideoajaxAction() + { + $this->_helper->layout()->disableLayout(); + + $view_id = null; + + if ($this->hasParam('media_view_id')) { + $view_id = $this->getParam('media_view_id'); + + //Log media view stop + try { + $mediaviewsTable = new Default_Model_DbTable_MediaViews(); + $data = array('stop_timestamp' => new Zend_Db_Expr ('Now()')); + $mediaviewsTable->update($data, 'media_view_id = ' . $view_id); + } catch (Exception $exc) { + //echo $exc->getTraceAsString(); + $errorLog = Zend_Registry::get('logger'); + $errorLog->err(__METHOD__ . ' - ' . $exc->getMessage() . ' ---------- ' . PHP_EOL); + } + $this->_helper->json(array('status' => 'success', 'MediaViewId' => $view_id)); + + return; } - + $this->_helper->json(array('status' => 'error')); + } + + protected function createPling($member_id, $project_id) + { + $projectplings = new Default_Model_ProjectPlings(); + $newVals = array('project_id' => $project_id, 'member_id' => $member_id); + $sql = $projectplings->select() + ->where('member_id = ?', $this->_authMember->member_id) + ->where('is_deleted = ?', 0) + ->where('project_id = ?', $this->_projectId, 'INTEGER'); + $result = $projectplings->fetchRow($sql); + if (null === $result) { + $projectplings->createRow($newVals)->save(); + } } - - /** * @param $memberId * * @throws Zend_Db_Table_Exception */ protected function setViewDataForMyProducts($memberId) { $tableMember = new Default_Model_Member(); $this->view->member = $tableMember->find($memberId)->current(); $tableProduct = new Default_Model_Project(); $this->view->products = $tableProduct->fetchAllProjectsForMember($memberId); } protected function _initResponseHeader() { $duration = 1800; // in seconds $expires = gmdate("D, d M Y H:i:s", time() + $duration) . " GMT"; $this->getResponse()->setHeader('X-FRAME-OPTIONS', 'ALLOWALL', - true)// ->setHeader('Last-Modified', $modifiedTime, true) + true)// ->setHeader('Last-Modified', $modifiedTime, true) ->setHeader('Expires', $expires, true)->setHeader('Pragma', 'no-cache', true) - ->setHeader('Cache-Control', 'private, no-cache, must-revalidate', true) - ; + ->setHeader('Cache-Control', 'private, no-cache, must-revalidate', true); } /** * @param $hits * * @return array */ protected function generateProjectsArrayForView($hits) { $viewArray = array(); $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); /** @var $hit Zend_Search_Lucene_Search_QueryHit */ foreach ($hits as $hit) { $project = $hit->getDocument(); if (null != $project->username) { $isUpdate = ($project->type_id == 2); if ($isUpdate) { $showUrl = $helperBuildProductUrl->buildProductUrl($project->pid) . '#anker_' . $project->project_id; $plingUrl = $helperBuildProductUrl->buildProductUrl($project->pid, 'pling'); } else { $showUrl = $helperBuildProductUrl->buildProductUrl($project->project_id); $plingUrl = $helperBuildProductUrl->buildProductUrl($project->project_id, 'pling'); } $projectArr = array( 'score' => $hit->score, 'id' => $project->project_id, 'type_id' => $project->type_id, 'title' => $project->title, 'description' => $project->description, 'image' => $project->image_small, 'plings' => 0, 'urlGoal' => $showUrl, 'urlPling' => $plingUrl, 'showUrlPling' => ($project->paypal_mail != null), 'member' => array( 'name' => $project->username, 'url' => 'member/' . $project->member_id, 'image' => $project->profile_image_url, 'id' => $project->member_id ) ); $viewArray[] = $projectArr; } } return $viewArray; } - protected function setLayout() { $layoutName = 'flat_ui_template'; - $storeConfig = Zend_Registry::isRegistered('store_config') ? Zend_Registry::get('store_config') : null; - if($storeConfig && $storeConfig->layout_pagedetail) - { - $this->_helper->layout()->setLayout($storeConfig->layout_pagedetail); - }else{ + $storeConfig = Zend_Registry::isRegistered('store_config') ? Zend_Registry::get('store_config') : null; + if ($storeConfig && $storeConfig->layout_pagedetail) { + $this->_helper->layout()->setLayout($storeConfig->layout_pagedetail); + } else { $this->_helper->layout()->setLayout($layoutName); - } - } - - - private function fetchGitlabProject($gitProjectId) - { - $gitlab = new Default_Model_Ocs_Gitlab(); - - try { - $gitProject = $gitlab->getProject($gitProjectId); - } catch (Exception $exc) { - //Project is gone - $modelProject = new Default_Model_Project(); - $modelProject->updateProject($this->_projectId, array('is_gitlab_project' => 0, 'gitlab_project_id' => null, 'show_gitlab_project_issues' => 0, 'use_gitlab_project_readme' => 0)); - $gitProject = null; - } - return $gitProject; - } - - private function fetchGitlabProjectIssues($gitProjectId) - { - $gitlab = new Default_Model_Ocs_Gitlab(); - - try { - $gitProjectIssues = $gitlab->getProjectIssues($gitProjectId); - } catch (Exception $exc) { - //Project is gone - $modelProject = new Default_Model_Project(); - $modelProject->updateProject($this->_projectId, array('is_gitlab_project' => 0, 'gitlab_project_id' => null, 'show_gitlab_project_issues' => 0, 'use_gitlab_project_readme' => 0)); - - $gitProjectIssues = null; - } - - - - return $gitProjectIssues; - } - - public function startmediaviewajaxAction() { - return $this->startvideoajaxAction(); - } - - public function startvideoajaxAction() { - $this->_helper->layout()->disableLayout(); - - $collection_id = null; - $file_id = null; - $memberId = $this->_authMember->member_id; - $media_view_type_id = $this->getParam('type_id'); - if(!$media_view_type_id) - { - // default - $media_view_type_id = Default_Model_DbTable_MediaViews::MEDIA_TYPE_VIDEO; - } - - if($this->hasParam('collection_id') && $this->hasParam('file_id')) { - $collection_id = $this->getParam('collection_id'); - $file_id = $this->getParam('file_id'); - $id = null; - - //Log media view - try { - $mediaviewsTable = new Default_Model_DbTable_MediaViews(); - $id = $mediaviewsTable->getNewId(); - $data = array('media_view_id' => $id, 'media_view_type_id' => $media_view_type_id, 'project_id' => $this->_projectId, 'collection_id' => $collection_id, 'file_id' => $file_id, 'start_timestamp' => new Zend_Db_Expr ('Now()'), 'ip' => $this->getRealIpAddr(), 'referer' => $this->getReferer()); - if(!empty($memberId)) { - $data['member_id'] = $memberId; - } - $data['source'] = 'OCS-Webserver'; - - $mediaviewsTable->createRow($data)->save(); - - } catch (Exception $exc) { - //echo $exc->getTraceAsString(); - $errorLog = Zend_Registry::get('logger'); - $errorLog->err(__METHOD__ . ' - ' . $exc->getMessage() . ' ---------- ' . PHP_EOL); - } - - - $this->_helper->json(array('status' => 'success', 'MediaViewId' => $id)); - - return; } - - $this->_helper->json(array('status' => 'error')); - } - - public function stopmediaviewajaxAction() { - return $this->stopvideoajaxAction(); } - - public function stopvideoajaxAction() { - $this->_helper->layout()->disableLayout(); - - $view_id = null; - - if($this->hasParam('media_view_id')) { - $view_id = $this->getParam('media_view_id'); - - //Log media view stop - try { - $mediaviewsTable = new Default_Model_DbTable_MediaViews(); - $data = array('stop_timestamp' => new Zend_Db_Expr ('Now()')); - $mediaviewsTable->update($data, 'media_view_id = '. $view_id); - } catch (Exception $exc) { - //echo $exc->getTraceAsString(); - $errorLog = Zend_Registry::get('logger'); - $errorLog->err(__METHOD__ . ' - ' . $exc->getMessage() . ' ---------- ' . PHP_EOL); - } - $this->_helper->json(array('status' => 'success', 'MediaViewId' => $view_id)); - - return; - } - - $this->_helper->json(array('status' => 'error')); - } - - function getRealIpAddr() - { - if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet - { - $ip=$_SERVER['HTTP_CLIENT_IP']; - } - elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy - { - $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; - } - else - { - $ip=$_SERVER['REMOTE_ADDR']; - } - return $ip; - } - - function getReferer() + private function getFileDownloadCount($collection_id, $fileId) { - $referer = null; - if (!empty($_SERVER['HTTP_REFERER'])) { - $referer = $_SERVER['HTTP_REFERER']; - } - return $referer; - } - - private function getFilterTagFromCookie($group) - { - $config = Zend_Registry::get('config'); - $cookieName = $config->settings->session->filter_browse_original.$group; + $modelFiles = new Default_Model_DbTable_PploadFiles(); - $storedInCookie = isset($_COOKIE[$cookieName]) ? $_COOKIE[$cookieName] : NULL; + $countAll = $modelFiles->fetchCountDownloadsForFileAllTime($collection_id, $fileId); + $countToday = $modelFiles->fetchCountDownloadsForFileToday($collection_id, $fileId); - return $storedInCookie; + $count = (int)$countAll + (int)$countToday; + + return $count; } } diff --git a/application/modules/default/models/Authorization.php b/application/modules/default/models/Authorization.php index 4f83d6ad7..17e2ce1bd 100644 --- a/application/modules/default/models/Authorization.php +++ b/application/modules/default/models/Authorization.php @@ -1,368 +1,370 @@ . **/ class Default_Model_Authorization { const LOGIN_REMEMBER_ME = 'infinity'; /** @var string */ protected $_dataModelName; /** @var Zend_Db_Table_Abstract */ protected $_dataTable; /** @var string */ protected $_loginMethod; /** @var object */ protected $_authUserData; /** * @param string $_dataModelName */ function __construct($_dataModelName = 'Default_Model_DbTable_Member') { $this->_dataModelName = $_dataModelName; $this->_dataTable = new $this->_dataModelName; } /** * @throws Zend_Session_Exception * @throws Zend_Exception */ public function logout() { $auth = Zend_Auth::getInstance(); $auth->clearIdentity(); $session = new Zend_Session_Namespace(); - $session->unsetAll(); - Zend_Session::forgetMe(); - // Zend_Session::destroy(); + //$session->unsetAll(); + //Zend_Session::forgetMe(); + Zend_Session::rememberUntil(Zend_Registry::get('config')->resources->session->cookie_lifetime); + //Zend_Session::destroy(); $modelRememberMe = new Default_Model_RememberMe(); $modelRememberMe->deleteSession(); } /** * @param string $userId * @param string $userSecret * @param bool $setRememberMe * @param string $loginMethod * * @return Zend_Auth_Result * @throws Zend_Auth_Storage_Exception * @throws Zend_Session_Exception * @throws exception */ public function authenticateUser($userId, $userSecret, $setRememberMe = false, $loginMethod = null) { if (false === empty($loginMethod)) { $this->_loginMethod = $loginMethod; } $authResult = $this->authenticateCredentials($userId, $userSecret, $loginMethod); if ($authResult->isValid()) { $this->updateRememberMe($setRememberMe); Zend_Session::regenerateId(); + Zend_Session::rememberMe(); $this->_storeAuthSessionData(); $this->updateUserLastOnline('member_id', $this->_authUserData->member_id); } return $authResult; } /** * @param $identity * @param $credential * @param null $loginMethod * * @return Zend_Auth_Result * @throws Zend_Auth_Adapter_Exception * @throws Zend_Exception */ protected function authenticateCredentials($identity, $credential, $loginMethod = null) { /** @var Local_Auth_Adapter_Ocs $authAdapter */ $authAdapter = Local_Auth_AdapterFactory::getAuthAdapter($identity, $credential, $loginMethod); $authAdapter->setIdentity($identity); $authAdapter->setCredential($credential); $authResult = $authAdapter->authenticate(); if ($authResult->isValid()) { $this->_authUserData = $authAdapter->getResultRowObject(null, 'password'); } return $authResult; } /** * @param bool $setRememberMe * * @throws Zend_Db_Statement_Exception * @throws Zend_Exception */ public function updateRememberMe($setRememberMe = false) { $modelRememberMe = new Default_Model_RememberMe(); if (false == $setRememberMe) { $modelRememberMe->deleteSession(); return; } if ($modelRememberMe->hasValidCookie()) { $modelRememberMe->updateSession($this->_authUserData->member_id); } else { $modelRememberMe->createSession($this->_authUserData->member_id); } } /** * @throws Zend_Auth_Storage_Exception * @throws exception */ protected function _storeAuthSessionData() { $extendedAuthData = $this->getExtendedAuthUserData($this->_authUserData); $auth = Zend_Auth::getInstance(); $auth->getStorage()->write($extendedAuthData); } /** * @param object $authUserData * * @return object * @throws exception */ protected function getExtendedAuthUserData($authUserData) { $extendedAuthUserData = new stdClass(); if (isset($this->_loginMethod) AND $this->_loginMethod == self::LOGIN_REMEMBER_ME) { $modelMember = new Default_Model_Member(); $memberData = $modelMember->fetchMemberData($authUserData->member_id); $extendedAuthUserData->external_id = $memberData->external_id; $extendedAuthUserData->username = $memberData->username; $extendedAuthUserData->roleId = $memberData->roleId; $extendedAuthUserData->avatar = $memberData->avatar; $extendedAuthUserData->profile_image_url = $memberData->profile_image_url; $extendedAuthUserData->is_active = $memberData->is_active; $extendedAuthUserData->is_deleted = $memberData->is_deleted; $extendedAuthUserData->roleName = $this->getRoleNameForUserRole($memberData->roleId); } else { $extendedAuthUserData->roleName = $this->getRoleNameForUserRole($authUserData->roleId); } $extendedAuthUserData->projects = $this->getProjectIdsForUser($authUserData->member_id); return (object)array_merge((array)$authUserData, (array)$extendedAuthUserData); } /** * @param int $roleId * * @return string * @throws exception */ protected function getRoleNameForUserRole($roleId) { $database = Zend_Db_Table::getDefaultAdapter(); $sql = " SELECT `shortname` FROM `member_role` WHERE `member_role_id` = ?; "; $sql = $database->quoteInto($sql, $roleId, 'INTEGER', 1); $resultSet = $database->query($sql)->fetchAll(); if (count($resultSet) > 0) { return $resultSet[0]['shortname']; } else { throw new Exception('undefined member role'); } } /** * @param int $identifier * * @return array * @throws Zend_Db_Statement_Exception */ protected function getProjectIdsForUser($identifier) { $database = Zend_Db_Table::getDefaultAdapter(); $sql = " SELECT `p`.`project_id` FROM `project` AS `p` WHERE `p`.`member_id` = ?; "; $sql = $database->quoteInto($sql, $identifier, 'INTEGER', 1); $resultSet = $database->query($sql)->fetchAll(); return $this->generateArrayWithKeyProjectId($resultSet); } /** * @param array $inputArray * * @return array */ protected function generateArrayWithKeyProjectId($inputArray) { $arrayWithKeyProjectId = array(); foreach ($inputArray as $element) { $arrayWithKeyProjectId[$element['project_id']] = $element; } return $arrayWithKeyProjectId; } /** * @param string $identifier * @param string|int $identity * * @return int */ public function updateUserLastOnline($identifier, $identity) { /** @var Zend_Db_Table_Abstract $dataTable */ $dataTable = $this->_dataTable; return $dataTable->update(array('last_online' => new Zend_Db_Expr('NOW()')), $dataTable->getAdapter()->quoteIdentifier($identifier, true) . ' = ' . $identity); } /** * @return object */ public function getAuthData() { return $this->_authUserData; } /** * @param int $identity * * @throws Zend_Auth_Storage_Exception * @throws exception */ public function storeAuthSessionDataByIdentity($identity) { $authDataAll = $this->getAllAuthUserData('member_id', $identity); $auth = Zend_Auth::getInstance(); $auth->getStorage()->write($authDataAll); } /** * @param string $identifier * @param string|int $identity * * @return object * @throws exception */ protected function getAllAuthUserData($identifier, $identity) { $this->_authUserData = $this->getAuthUserData($identifier, $identity); return $this->getExtendedAuthUserData($this->_authUserData); } /** * @param string $identifier * @param string|int $identity * * @return object * @throws Zend_Exception */ protected function getAuthUserData($identifier, $identity) { $dataTable = $this->_dataTable; $where = $dataTable->select()->where($dataTable->getAdapter()->quoteIdentifier($identifier, true) . ' = ?', $identity); $resultRow = $dataTable->fetchRow($where)->toArray(); unset($resultRow['password']); return (object)$resultRow; } /** * @param string $identity * * @return null|object * @throws Zend_Exception */ public function getAuthUserDataFromUnverified($identity) { $sql = " SELECT `m`.*, `member_email`.`email_verification_value`, `member_email`.`email_checked`, `mei`.`external_id` FROM `member_email` JOIN `member` AS `m` ON `m`.`member_id` = `member_email`.`email_member_id` LEFT JOIN `member_external_id` AS `mei` ON `mei`.`member_id` = `m`.`member_id` WHERE `member_email`.`email_deleted` = 0 AND `member_email`.`email_verification_value` = :verification AND `m`.`is_deleted` = 0 "; $resultRow = $this->_dataTable->getAdapter()->fetchRow($sql, array('verification' => $identity)); if ($resultRow) { unset($resultRow['password']); return (object)$resultRow; } return null; } /** * ppload and OCS * * @param string $identity * @param string $credential * @param string $loginMethod * * @return mixed * @throws Zend_Auth_Adapter_Exception * @throws Zend_Exception */ public function getAuthDataFromApi($identity, $credential, $loginMethod = null) { $authResult = $this->authenticateCredentials($identity, $credential, $loginMethod); if ($authResult->isValid()) { Zend_Session::regenerateId(); $this->_storeAuthSessionData(); return $this->_authUserData; } return false; } /** * @param string $identifier * @param string|int $identity * * @return int */ public function removeAllCookieInformation($identifier, $identity) { $dataTable = new Default_Model_DbTable_Session(); $where = $dataTable->getAdapter()->quoteInto($dataTable->getAdapter()->quoteIdentifier($identifier, true) . ' = ?', $identity); return $dataTable->delete($where); } } \ No newline at end of file diff --git a/application/modules/default/models/DbTable/StatPageViews.php b/application/modules/default/models/DbTable/StatPageViews.php index 5bc17fd9a..a193da9e8 100644 --- a/application/modules/default/models/DbTable/StatPageViews.php +++ b/application/modules/default/models/DbTable/StatPageViews.php @@ -1,54 +1,54 @@ . **/ class Default_Model_DbTable_StatPageViews extends Zend_Db_Table_Abstract { protected $_name = "stat_page_views"; public function savePageView($project_id, $clientIp, $member_id) { if (SEARCHBOT_DETECTED) { // we don't save a page view when a search bot was detected return; } if (false == Zend_Registry::get('config')->settings->savePageView) { return; } - $this->_db->beginTransaction(); + //$this->_db->beginTransaction(); try { $this->_db->query("INSERT LOW_PRIORITY INTO {$this->_name} (`project_id`, `ip`, `member_id`) VALUES (:param1, :param2, :param3);", array( 'param1' => $project_id, 'param2' => $clientIp, 'param3' => $member_id )); - $this->_db->commit(); +// $this->_db->commit(); } catch (Exception $ex) { - $this->_db->rollBack(); +// $this->_db->rollBack(); Zend_Registry::get('logger')->err(__METHOD__ . ' - ' . $ex->getMessage()); } } } \ No newline at end of file diff --git a/application/modules/default/models/RememberMe.php b/application/modules/default/models/RememberMe.php index 93a745caf..227952f6b 100644 --- a/application/modules/default/models/RememberMe.php +++ b/application/modules/default/models/RememberMe.php @@ -1,282 +1,288 @@ . **/ class Default_Model_RememberMe { protected $salt = 'slkdmclskdaruiowrjasndf224323423rwersdf§$%ZTFG§EWRSGFSD!§RWESFD'; /** @var null|Zend_Controller_Request_Http */ protected $request; /** @var string */ protected $dataTableName; /** @var Default_Model_DbTable_Comments */ protected $dataTable; /** @var string */ protected $cookieName; /** @var int */ protected $cookieTimeout; /** * PHP 5 allows developers to declare constructor methods for classes. * Classes which have a constructor method call this method on each newly-created object, * so it is suitable for any initialization that the object may need before it is used. * * Note: Parent constructors are not called implicitly if the child class defines a constructor. * In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. * * param [ mixed $args [, $... ]] * * @param string $_dataTableName * * @throws Zend_Exception * @link http://php.net/manual/en/language.oop5.decon.php */ public function __construct($_dataTableName = 'Default_Model_DbTable_Session') { $this->request = Zend_Controller_Front::getInstance()->getRequest(); $this->dataTableName = $_dataTableName; $this->dataTable = new $this->dataTableName; $config = Zend_Registry::get('config'); $this->cookieName = $config->settings->session->remember_me->name; $this->cookieTimeout = $config->settings->session->remember_me->cookie_lifetime; } /** * @param $identifier * * @return array|null * @throws Zend_Db_Statement_Exception */ public function updateSession($identifier) { $currentSessionCookie = $this->getCookieData(); if (empty($currentSessionCookie)) { return $this->createSession($identifier); } $newSessionData = $this->createSessionData($identifier); $this->setCookie($newSessionData); $countUpdated = $this->updateSessionData($currentSessionCookie, $newSessionData, $identifier); if (empty($countUpdated)) { $this->saveSessionData($newSessionData); // old session entry not found; we create a new one } return $newSessionData; } /** * @return null|array */ public function getCookieData() { $cookieRememberMe = $this->request->getCookie($this->cookieName, null); if (false === isset($cookieRememberMe)) { return null; } $cookieData = unserialize($cookieRememberMe); if (empty($cookieData)) { return null; } $sessionData = array(); $sessionData['member_id'] = (int)$cookieData['mi']; $sessionData['remember_me_id'] = $cookieData['u']; $sessionData['token'] = isset($cookieData['t']) ? $cookieData['t'] : null; return $sessionData; } /** * @param int $identifier * * @return array return new session data * @throws Exception */ public function createSession($identifier) { $newSessionData = $this->createSessionData($identifier); $this->setCookie($newSessionData); $this->saveSessionData($newSessionData); + $this->storeRememberIdInSession($newSessionData['remember_mem_id']); return $newSessionData; } /** * @param int $identifier * * @return array */ protected function createSessionData($identifier) { $sessionData = array(); $sessionData['member_id'] = (int)$identifier; $sessionData['remember_me_id'] = Local_Tools_UUID::generateUUID(); $sessionData['expiry'] = time() + (int)$this->cookieTimeout; - $sessionData['token'] = - base64_encode(hash('sha256', $sessionData['member_id'] . $sessionData['remember_me_id'] . $this->salt)); + $sessionData['token'] = base64_encode(hash('sha256', $sessionData['member_id'] . $sessionData['remember_me_id'] . $this->salt)); return $sessionData; } /** * @param array $newSessionData * * @return bool */ protected function setCookie($newSessionData) { if (empty($newSessionData)) { return false; } $domain = Local_Tools_ParseDomain::get_domain($this->request->getHttpHost()); $sessionData = array(); $sessionData['mi'] = $newSessionData['member_id']; $sessionData['u'] = $newSessionData['remember_me_id']; $sessionData['t'] = $newSessionData['token']; // delete old cookie with wrong domain //setcookie($this->cookieName, null, time() - $this->cookieTimeout, '/', $this->request->getHttpHost(), null, true); return setcookie($this->cookieName, serialize($sessionData), $newSessionData['expiry'], '/', $domain, null, true); } /** * @param $newSessionData * * @return mixed * @throws Exception */ protected function saveSessionData($newSessionData) { $newSessionData['expiry'] = date('Y-m-d H:i:s', $newSessionData['expiry']); // change to mysql datetime format $this->dataTable->save($newSessionData); return $newSessionData; } /** * @param array $currentSessionData * @param array $newSessionData * @param int $identifier * * @return int count of updated rows * @throws Zend_Db_Statement_Exception */ private function updateSessionData($currentSessionData, $newSessionData, $identifier) { if (false == isset($currentSessionData) OR (count($currentSessionData) == 0)) { return null; } $sql = "UPDATE `session` SET `remember_me_id` = :remember_new, `expiry` = FROM_UNIXTIME(:expiry_new), `changed` = NOW() WHERE `member_id` = :member_id AND `remember_me_id` = :remember_old"; $result = $this->dataTable->getAdapter()->query($sql, array( 'remember_new' => $newSessionData['remember_me_id'], 'expiry_new' => $newSessionData['expiry'], 'member_id' => $identifier, 'remember_old' => $currentSessionData['remember_me_id'] )) ; return $result->rowCount(); } public function hasValidCookie() { $sessionCookieData = $this->getCookieData(); return $this->validateCookieData($sessionCookieData); } protected function validateCookieData($currentCookie) { if (empty($currentCookie)) { return false; } if (empty($currentCookie['token'])) { return false; } if (empty($currentCookie['member_id']) OR (false == is_int($currentCookie['member_id']))) { return false; } if (empty($currentCookie['remember_me_id'])) { return false; } $cookieToken = base64_decode($currentCookie['token']); $validateToken = hash('sha256', $currentCookie['member_id'] . $currentCookie['remember_me_id'] . $this->salt); if ($cookieToken != $validateToken) { return false; } return true; } public function deleteSession() { $currentSessionCookie = $this->getCookieData(); if (empty($currentSessionCookie)) { return; } $this->removeSessionData($currentSessionCookie); $this->deleteCookie(); } /** * @param array $currentSessionCookie * * @return bool * @throws Zend_Db_Statement_Exception */ protected function removeSessionData($currentSessionCookie) { $sql = "DELETE FROM `session` WHERE `member_id` = :member_id AND `remember_me_id` = :uuid"; $result = $this->dataTable->getAdapter()->query($sql, array( 'member_id' => $currentSessionCookie['member_id'], 'uuid' => $currentSessionCookie['remember_me_id'] )) ; if ($result->rowCount() > 0) { return true; } else { return false; } } public function deleteCookie() { $domain = Local_Tools_ParseDomain::get_domain($this->request->getHttpHost()); $cookieExpire = time() - $this->cookieTimeout; setcookie($this->cookieName, false, $cookieExpire, '/', $this->request->getHttpHost(), null, true); setcookie($this->cookieName, false, $cookieExpire, '/', $domain, null, true); } + private function storeRememberIdInSession($remember_mem_id) + { + $session = new Zend_Session_Namespace(); + $session->remember_me_id = $remember_mem_id; + } + } \ No newline at end of file diff --git a/application/modules/default/models/Views.php b/application/modules/default/models/Views.php new file mode 100644 index 000000000..5ed097bb7 --- /dev/null +++ b/application/modules/default/models/Views.php @@ -0,0 +1,77 @@ +. + * + */ +class Default_Model_Views +{ + + const OBJECT_TYPE_PRODUCT = 10; + const OBJECT_TYPE_MEMBERPAGE = 20; + const OBJECT_TYPE_LOGIN = 30; + const OBJECT_TYPE_LOGOUT = 32; + const OBJECT_TYPE_DOWNLOAD = 40; + + public static function saveViewProduct($product_id) + { + self::saveViewObject(self::OBJECT_TYPE_PRODUCT, $product_id); + } + + public static function saveViewObject($object_type, $object_id) + { + $sql = ("INSERT IGNORE INTO `stat_page_impression` (`seen_at`, `ip_inet`, `object_type`, `object_id`, `ipv4`, `ipv6`, `fingerprint`, `user_agent`, `member_id_viewer`) VALUES (:seen, :ip_inet, :object_type, :product_id, :ipv4, :ipv6, :fp, :ua, :member)"); + $session = new Zend_Session_Namespace(); + $view_member_id = Zend_Auth::getInstance()->getIdentity()->member_id ? Zend_Auth::getInstance()->getIdentity()->member_id : null; + $ipClient = Zend_Controller_Front::getInstance()->getRequest()->getClientIp(); + $ipClientv6 = filter_var($ipClient, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ? $ipClient : null; + $ipClientv4 = filter_var($ipClient, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) ? $ipClient : null; + $session_ipv6 = isset($session->stat_ipv6) ? inet_pton($session->stat_ipv6) : null; + $session_ipv4 = isset($session->stat_ipv4) ? inet_pton($session->stat_ipv4) : null; + $ip_inet = isset($session_ipv6) ? $session_ipv6 : (isset($session_ipv4) ? $session_ipv4 : inet_pton($ipClient)); + + try { + Zend_Db_Table::getDefaultAdapter()->query($sql, array( + 'seen' => round(time() / 300), + 'ip_inet' => $ip_inet, + 'object_type' => $object_type, + 'product_id' => $object_id, + 'ipv6' => $session->stat_ipv6 ? $session->stat_ipv6 : $ipClientv6, + 'ipv4' => $session->stat_ipv4 ? $session->stat_ipv4 : $ipClientv4, + 'fp' => $session->stat_fp ? $session->stat_fp : null, + 'ua' => $_SERVER['HTTP_USER_AGENT'] ? $_SERVER['HTTP_USER_AGENT'] : null, + 'member' => $view_member_id + )); + } catch (Exception $e) { + Zend_Registry::get('logger')->err(__METHOD__ . ' - ERROR write - ' . print_r($e, true)); + } + } + + public static function saveViewMemberpage($member_id) + { + self::saveViewObject(self::OBJECT_TYPE_MEMBERPAGE, $member_id); + } + + public static function saveViewDownload($file_id) + { + self::saveViewObject(self::OBJECT_TYPE_DOWNLOAD, $file_id); + } + +} \ No newline at end of file diff --git a/application/modules/default/plugins/AclRules.php b/application/modules/default/plugins/AclRules.php index 6b80cf8d7..54188f4f0 100644 --- a/application/modules/default/plugins/AclRules.php +++ b/application/modules/default/plugins/AclRules.php @@ -1,440 +1,440 @@ . **/ class Default_Plugin_AclRules extends Zend_Acl { const ROLENAME_GUEST = 'guest'; const ROLENAME_COOKIEUSER = 'cookieuser'; const ROLENAME_FEUSER = 'feuser'; const ROLENAME_MODERATOR = 'moderator'; const ROLENAME_STAFF = 'staff'; const ROLENAME_ADMIN = 'admin'; const ROLENAME_SYSUSER = 'sysuser'; function __construct() { $this->addRole(new Zend_Acl_Role (self::ROLENAME_GUEST)); $this->addRole(new Zend_Acl_Role (self::ROLENAME_COOKIEUSER), self::ROLENAME_GUEST); $this->addRole(new Zend_Acl_Role (self::ROLENAME_FEUSER), self::ROLENAME_COOKIEUSER); $this->addRole(new Zend_Acl_Role (self::ROLENAME_MODERATOR), self::ROLENAME_FEUSER); $this->addRole(new Zend_Acl_Role (self::ROLENAME_STAFF), self::ROLENAME_FEUSER); $this->addRole(new Zend_Acl_Role (self::ROLENAME_ADMIN)); $this->addRole(new Zend_Acl_Role (self::ROLENAME_SYSUSER)); - $this->addResource(new Zend_Acl_Resource ('default_logout')); $this->addResource(new Zend_Acl_Resource ('default_oauth')); $this->addResource(new Zend_Acl_Resource ('default_authorization')); $this->addResource(new Zend_Acl_Resource ('default_button')); $this->addResource(new Zend_Acl_Resource ('default_categories')); $this->addResource(new Zend_Acl_Resource ('default_community')); $this->addResource(new Zend_Acl_Resource ('default_content')); $this->addResource(new Zend_Acl_Resource ('default_discovery')); $this->addResource(new Zend_Acl_Resource ('default_donationlist')); $this->addResource(new Zend_Acl_Resource ('default_support')); $this->addResource(new Zend_Acl_Resource ('default_subscription')); $this->addResource(new Zend_Acl_Resource ('default_error')); $this->addResource(new Zend_Acl_Resource ('default_explore')); $this->addResource(new Zend_Acl_Resource ('default_gateway')); $this->addResource(new Zend_Acl_Resource ('default_hive')); $this->addResource(new Zend_Acl_Resource ('default_home')); $this->addResource(new Zend_Acl_Resource ('default_ocsv1')); // OCS API $this->addResource(new Zend_Acl_Resource ('default_embedv1')); // embed API $this->addResource(new Zend_Acl_Resource ('default_membersetting')); $this->addResource(new Zend_Acl_Resource ('default_json')); $this->addResource(new Zend_Acl_Resource ('default_productcategory')); $this->addResource(new Zend_Acl_Resource ('default_productcomment')); $this->addResource(new Zend_Acl_Resource ('default_product')); $this->addResource(new Zend_Acl_Resource ('default_report')); $this->addResource(new Zend_Acl_Resource ('default_rectification')); $this->addResource(new Zend_Acl_Resource ('default_rss')); $this->addResource(new Zend_Acl_Resource ('default_settings')); $this->addResource(new Zend_Acl_Resource ('default_supporterbox')); $this->addResource(new Zend_Acl_Resource ('default_plingbox')); $this->addResource(new Zend_Acl_Resource ('default_user')); $this->addResource(new Zend_Acl_Resource ('default_widget')); $this->addResource(new Zend_Acl_Resource ('default_file')); $this->addResource(new Zend_Acl_Resource ('default_plings')); $this->addResource(new Zend_Acl_Resource ('default_gitfaq')); $this->addResource(new Zend_Acl_Resource ('default_spam')); $this->addResource(new Zend_Acl_Resource ('default_moderation')); $this->addResource(new Zend_Acl_Resource ('default_duplicates')); $this->addResource(new Zend_Acl_Resource ('default_newproducts')); $this->addResource(new Zend_Acl_Resource ('default_misuse')); $this->addResource(new Zend_Acl_Resource ('default_credits')); $this->addResource(new Zend_Acl_Resource ('default_ads')); $this->addResource(new Zend_Acl_Resource ('default_dl')); $this->addResource(new Zend_Acl_Resource ('default_password')); $this->addResource(new Zend_Acl_Resource ('default_verify')); $this->addResource(new Zend_Acl_Resource ('default_login')); + $this->addResource(new Zend_Acl_Resource ('default_logout')); $this->addResource(new Zend_Acl_Resource ('default_collection')); $this->addResource(new Zend_Acl_Resource ('default_funding')); $this->addResource(new Zend_Acl_Resource ('default_stati')); $this->addResource(new Zend_Acl_Resource ('default_tag')); $this->addResource(new Zend_Acl_Resource ('default_section')); $this->addResource(new Zend_Acl_Resource ('default_supporters')); $this->addResource(new Zend_Acl_Resource ('backend_categories')); $this->addResource(new Zend_Acl_Resource ('backend_vcategories')); $this->addResource(new Zend_Acl_Resource ('backend_categorytag')); $this->addResource(new Zend_Acl_Resource ('backend_categorytaggroup')); $this->addResource(new Zend_Acl_Resource ('backend_claim')); $this->addResource(new Zend_Acl_Resource ('backend_comments')); $this->addResource(new Zend_Acl_Resource ('backend_content')); $this->addResource(new Zend_Acl_Resource ('backend_faq')); $this->addResource(new Zend_Acl_Resource ('backend_hive')); $this->addResource(new Zend_Acl_Resource ('backend_hiveuser')); $this->addResource(new Zend_Acl_Resource ('backend_index')); $this->addResource(new Zend_Acl_Resource ('backend_mail')); $this->addResource(new Zend_Acl_Resource ('backend_member')); $this->addResource(new Zend_Acl_Resource ('backend_memberpayout')); $this->addResource(new Zend_Acl_Resource ('backend_memberpaypaladdress')); $this->addResource(new Zend_Acl_Resource ('backend_paypalvalidstatus')); $this->addResource(new Zend_Acl_Resource ('backend_payoutstatus')); $this->addResource(new Zend_Acl_Resource ('backend_operatingsystem')); $this->addResource(new Zend_Acl_Resource ('backend_project')); $this->addResource(new Zend_Acl_Resource ('backend_ranking')); $this->addResource(new Zend_Acl_Resource ('backend_reportcomments')); $this->addResource(new Zend_Acl_Resource ('backend_reportproducts')); $this->addResource(new Zend_Acl_Resource ('backend_search')); $this->addResource(new Zend_Acl_Resource ('backend_storecategories')); $this->addResource(new Zend_Acl_Resource ('backend_vstorecategories')); $this->addResource(new Zend_Acl_Resource ('backend_store')); $this->addResource(new Zend_Acl_Resource ('backend_tag')); $this->addResource(new Zend_Acl_Resource ('backend_user')); $this->addResource(new Zend_Acl_Resource ('backend_tags')); $this->addResource(new Zend_Acl_Resource ('backend_ghnsexcluded')); $this->addResource(new Zend_Acl_Resource ('backend_letteravatar')); $this->addResource(new Zend_Acl_Resource ('backend_group')); $this->addResource(new Zend_Acl_Resource ('backend_spamkeywords')); $this->addResource(new Zend_Acl_Resource ('backend_projectclone')); $this->addResource(new Zend_Acl_Resource ('backend_section')); $this->addResource(new Zend_Acl_Resource ('backend_sectioncategories')); $this->addResource(new Zend_Acl_Resource ('backend_sponsor')); $this->addResource(new Zend_Acl_Resource ('backend_browselisttype')); $this->addResource(new Zend_Acl_Resource ('backend_cdiscourse')); $this->addResource(new Zend_Acl_Resource ('backend_cgitlab')); $this->addResource(new Zend_Acl_Resource ('backend_cldap')); $this->addResource(new Zend_Acl_Resource ('backend_coauth')); $this->addResource(new Zend_Acl_Resource ('backend_cexport')); $this->addResource(new Zend_Acl_Resource ('backend_statistics')); $this->addResource(new Zend_Acl_Resource ('statistics_data')); $this->allow(self::ROLENAME_GUEST, array( 'statistics_data' )); $this->allow(self::ROLENAME_GUEST, array( 'default_logout', 'default_authorization', 'default_button', 'default_categories', 'default_content', 'default_community', 'default_donationlist', 'default_error', 'default_explore', 'default_gateway', 'default_hive', 'default_home', 'default_membersetting', 'default_json', 'default_ocsv1', // OCS API 'default_embedv1', // embed API 'default_productcategory', 'default_rss', 'default_support', 'default_subscription', 'default_supporterbox', 'default_plingbox', 'default_oauth', 'default_plings', 'default_gitfaq', 'default_ads', 'default_dl', 'default_stati', 'default_password', 'default_verify', 'default_login', 'default_supporters', 'default_collection' )); $this->allow(self::ROLENAME_SYSUSER, array( 'default_authorization', 'default_button', 'default_categories', 'default_content', 'default_community', 'default_donationlist', 'default_error', 'default_explore', 'default_gateway', 'default_hive', 'default_home', 'default_ocsv1', // OCS API 'default_embedv1', // embed API 'default_productcategory', 'default_report', 'default_rss', 'default_supporterbox', 'default_plingbox', 'default_oauth', 'default_plings', 'default_ads', 'default_dl', 'default_stati', 'default_password' )); $this->allow(self::ROLENAME_COOKIEUSER, array( 'default_logout', 'default_productcomment', 'default_settings', 'default_tag', 'default_rectification' )); $this->allow(self::ROLENAME_STAFF, array( 'backend_index', 'backend_categories', 'backend_categorytag', 'backend_claim', 'backend_comments', 'backend_content', 'backend_store', 'backend_storecategories', 'backend_operatingsystem', 'backend_reportcomments', 'backend_reportproducts', 'backend_search', 'backend_group' )); $this->allow(self::ROLENAME_ADMIN); // resource access rights in detail $this->allow(self::ROLENAME_GUEST, 'backend_group', array('newgroup')); // resource default_product $this->allow(self::ROLENAME_GUEST, 'default_product', array( 'index', 'show', 'getupdatesajax', 'updates', 'follows', 'fetch', 'search', 'startdownload', 'ppload', 'loadratings', 'loadfilesjson', 'loadinstallinstruction', 'gettaggroupsforcatajax', 'getfilesajax', 'getfiletagsajax', 'startvideoajax', 'stopvideoajax', 'startmediaviewajax', 'stopmediaviewajax', 'loadfirstfilejson', 'loadtagrating' )); // resource default_product $this->allow(self::ROLENAME_GUEST, 'default_collection', array( 'index', 'show', 'getupdatesajax', 'updates', 'follows', 'fetch', 'search', //'startdownload', //'ppload', 'loadratings', //'loadinstallinstruction', //'getfilesajax', 'gettaggroupsforcatajax' )); // resource default_product $this->allow(self::ROLENAME_SYSUSER, 'default_product', array( 'index', 'show', 'getupdatesajax', 'updates', 'follows', 'fetch', 'search', 'startdownload', 'ppload', 'loadratings' )); $this->allow(self::ROLENAME_COOKIEUSER, 'default_product', array( 'add', 'rating', 'follow', 'unfollow', 'plingproject', 'followproject', 'unplingproject', 'add', 'pling', 'pay', 'dwolla', 'paymentok', 'paymentcancel', 'saveproduct', 'claim', 'votetagrating' )); $this->allow(self::ROLENAME_COOKIEUSER, 'default_collection', array( 'add', 'rating', 'follow', 'unfollow', 'plingproject', 'followproject', 'unplingproject', 'pling', 'pay', 'dwolla', 'paymentok', 'paymentcancel', 'saveproduct', 'claim' )); $this->allow(self::ROLENAME_COOKIEUSER, 'default_membersetting', array( 'getsettings','setsettings','notification','searchmember' )); $this->allow(self::ROLENAME_MODERATOR, 'backend_project', array( 'doghnsexclude' )); $this->allow(self::ROLENAME_MODERATOR, 'default_moderation', array( 'index','list' )); $this->allow(self::ROLENAME_MODERATOR, 'default_duplicates', array( 'index' )); $this->allow(self::ROLENAME_MODERATOR, 'default_newproducts', array( 'index' )); $this->allow(self::ROLENAME_COOKIEUSER, 'default_product', array( 'edit', 'saveupdateajax', 'deleteupdateajax', 'update', 'preview', 'delete', 'unpublish', 'publish', 'verifycode', 'makerconfig', 'addpploadfile', 'updatepploadfile', 'deletepploadfile', 'deletepploadfiles', 'updatefiletag', 'getcollectionprojectsajax', 'getprojectsajax' ), new Default_Plugin_Acl_IsProjectOwnerAssertion()); // resource default_support $this->allow(self::ROLENAME_GUEST, 'default_support', array('index')); $this->allow(self::ROLENAME_COOKIEUSER, 'default_support', array('index', 'pay', 'paymentok', 'paymentcancel')); // resource default_subscription $this->allow(self::ROLENAME_GUEST, 'default_subscription', array('index', 'support2')); $this->allow(self::ROLENAME_COOKIEUSER, 'default_subscription', array('index', 'support2', 'pay', 'pay2', 'paymentok', 'paymentcancel')); // resource default_report $this->allow(self::ROLENAME_COOKIEUSER, 'default_report', array('comment', 'product', 'productfraud', 'productclone')); // resource default_widget $this->allow(self::ROLENAME_GUEST, 'default_widget', array('index', 'render')); $this->allow(self::ROLENAME_COOKIEUSER, 'default_widget', array('save', 'savedefault', 'config'), new Default_Plugin_Acl_IsProjectOwnerAssertion()); $this->allow(self::ROLENAME_COOKIEUSER, 'default_file', array( 'gitlink', 'link', ), new Default_Plugin_Acl_IsProjectOwnerAssertion()); // resource default_user $this->allow(self::ROLENAME_GUEST, 'default_home', array('baseurlajax','forumurlajax','blogurlajax','storenameajax','domainsajax', 'userdataajax', 'loginurlajax', 'metamenujs','metamenubundlejs','fetchforgit')); // resource default_user $this->allow(self::ROLENAME_GUEST, 'default_user', array('index', 'aboutme', 'share', 'report', 'about', 'tooltip', 'avatar', 'userdataajax','showoriginal')); $this->allow(self::ROLENAME_COOKIEUSER, 'default_user', array( 'follow', 'unfollow', 'settings', 'products', 'collections', 'news', 'activities', 'payments', 'income', 'payout', 'payouthistory', 'plings', 'plingsold', 'plingsajax', 'plingsmonthajax', 'downloadhistory', 'likes', 'funding', 'sectionsajax', 'sectionsmonthajax', 'sectionplingsmonthajax', 'sectioncreditsmonthajax', 'sectionaffiliatesmonthdetailajax', )); //$this->allow(self::ROLENAME_GUEST, 'default_funding', array( // 'index', // 'plingsajax', // 'plingsmonthajax' //)); $this->allow(self::ROLENAME_COOKIEUSER, 'default_tag', array('filter', 'add', 'del', 'assign', 'remove')); } } diff --git a/application/modules/default/plugins/Stats.php b/application/modules/default/plugins/Stats.php new file mode 100644 index 000000000..dae0264ca --- /dev/null +++ b/application/modules/default/plugins/Stats.php @@ -0,0 +1,33 @@ +getControllerName(), $allowed_controller)) { + return; + } + + $session_stats = new Zend_Session_Namespace(); + foreach ($session_stats->getIterator()->getArrayCopy() as $key => $item) { + Zend_Registry::get('logger')->debug(print_r($key, true).' => '.print_r($item,true)); + }; + $request_ip = $request->getClientIp(); + + if (empty($session_stats->stat_ipv4) AND empty($session_stats->stat_ipv6)) { + $session_stats->stat_valid = false; + + return; + } + + if (($request_ip != $session_stats->stat_ipv4) AND ($request_ip != $session_stats->stat_ipv6)) { + $session_stats->stat_valid = false; + + return; + } + } + +} \ No newline at end of file diff --git a/application/modules/default/views/helpers/ProjectDetailCounts.php b/application/modules/default/views/helpers/ProjectDetailCounts.php index bd7d6f947..f6457255c 100755 --- a/application/modules/default/views/helpers/ProjectDetailCounts.php +++ b/application/modules/default/views/helpers/ProjectDetailCounts.php @@ -1,51 +1,52 @@ . **/ class Default_View_Helper_ProjectDetailCounts extends Zend_View_Helper_Abstract { /* * for project detail show count info: page views today page views total */ - public function projectDetailCounts ($project_id) + public function projectDetailCounts($project_id) { - $sql= " + $sql = " SELECT - count(1) as `count_views` + count(1) AS `count_views` FROM `stat_page_views_48h` WHERE `project_id` = :project_id - AND created_at >= subdate(NOW(), 1) - union + AND `created_at` >= subdate(NOW(), 1) + UNION SELECT - count(1) as `count_views` + count(1) AS `count_views` FROM `stat_page_views` WHERE `project_id` = :project_id "; - + $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql, array('project_id' => $project_id)); + return $resultSet; } } \ No newline at end of file diff --git a/application/modules/default/views/layout/flat_ui_template.phtml b/application/modules/default/views/layout/flat_ui_template.phtml index cfdd2bb89..5ca36fd35 100644 --- a/application/modules/default/views/layout/flat_ui_template.phtml +++ b/application/modules/default/views/layout/flat_ui_template.phtml @@ -1,210 +1,209 @@ . **/ ?> render('partials/htmlheader.phtml'); ?> */?> render('partials/header/metaheader.phtml');?> noheader) echo $this->render('partials/header/header.phtml'); ?> render('partials/flashMessage.phtml'); ?> layout()->content; ?> render('partials/footer/template.phtml'); ?> render('partials/genericModalConfirmation.phtml'); ?> */ ?> render('partials/propagateLogin.phtml'); echo $this->render('partials/propagateLogout.phtml'); ?> inlineScript() ?> google_id; } ?> piwik_id; } ?> render('partials/profiler.phtml') ?> client_fp; -if (empty($fp)) : ?> - - +$apiv4 = Zend_Registry::get("config")->settings->server->ip->api->v4; +$apiv6 = Zend_Registry::get("config")->settings->server->ip->api->v6; +if (false == $session->stat_valid) : ?> + + diff --git a/application/modules/default/views/layout/home_template.phtml b/application/modules/default/views/layout/home_template.phtml index 04d2f87fc..880764124 100644 --- a/application/modules/default/views/layout/home_template.phtml +++ b/application/modules/default/views/layout/home_template.phtml @@ -1,156 +1,154 @@ . **/ ?> render('partials/htmlheader.phtml'); ?> index && $this->index==4) { echo $this->render('partials/header/template_pling_home.phtml'); }else { echo $this->render('partials/header/template.phtml'); } ?> render('partials/flashMessage.phtml'); ?> layout()->content; ?> render('partials/footer/template.phtml'); ?> render('partials/propagateLogin.phtml'); echo $this->render('partials/propagateLogout.phtml'); ?> inlineScript() ?> google_id; } ?> piwik_id; } ?> render('partials/profiler.phtml') ?> - client_fp; -if (empty($fp)) : ?> - - +$apiv4 = Zend_Registry::get("config")->settings->server->ip->api->v4; +$apiv6 = Zend_Registry::get("config")->settings->server->ip->api->v6; +if (false == $session->stat_valid) : ?> + + diff --git a/application/modules/default/views/layout/layout_appimagehub.phtml b/application/modules/default/views/layout/layout_appimagehub.phtml index 9dc447cff..aea800888 100755 --- a/application/modules/default/views/layout/layout_appimagehub.phtml +++ b/application/modules/default/views/layout/layout_appimagehub.phtml @@ -1,193 +1,201 @@ . **/ ?> render('partials/htmlheader.phtml'); ?> */?> render('partials/header/template.phtml'); ?> render('partials/flashMessage.phtml'); ?> layout()->content; ?> render('partials/footer/template.phtml'); ?> render('partials/genericModalConfirmation.phtml'); ?> render('partials/propagateLogin.phtml'); echo $this->render('partials/propagateLogout.phtml'); ?> inlineScript() ?> google_id; } ?> piwik_id; } ?> render('partials/profiler.phtml') ?> +settings->server->ip->api->v4; +$apiv6 = Zend_Registry::get("config")->settings->server->ip->api->v6; +if (false == $session->stat_valid) : ?> + + + diff --git a/application/modules/default/views/layout/layout_appimagehub_home.phtml b/application/modules/default/views/layout/layout_appimagehub_home.phtml index 8678ea44d..d56753c1a 100755 --- a/application/modules/default/views/layout/layout_appimagehub_home.phtml +++ b/application/modules/default/views/layout/layout_appimagehub_home.phtml @@ -1,155 +1,163 @@ . **/ ?> render('partials/htmlheader.phtml'); ?> */?> render('partials/header/template.phtml'); ?> render('partials/flashMessage.phtml'); ?> layout()->content; ?> render('partials/footer/template.phtml'); ?> render('partials/propagateLogin.phtml'); echo $this->render('partials/propagateLogout.phtml'); ?> inlineScript() ?> google_id; } ?> piwik_id; } ?> render('partials/profiler.phtml') ?> +settings->server->ip->api->v4; +$apiv6 = Zend_Registry::get("config")->settings->server->ip->api->v6; +if (false == $session->stat_valid) : ?> + + + diff --git a/application/modules/default/views/layout/layout_pling_home.phtml b/application/modules/default/views/layout/layout_pling_home.phtml index 8e075ae98..c8eade656 100755 --- a/application/modules/default/views/layout/layout_pling_home.phtml +++ b/application/modules/default/views/layout/layout_pling_home.phtml @@ -1,168 +1,167 @@ . **/ ?> render('partials/htmlheader.phtml'); ?> render('partials/header/metaheader.phtml');?> render('partials/flashMessage.phtml'); ?> layout()->content; ?> render('partials/footer/template.phtml'); ?> render('partials/propagateLogin.phtml'); echo $this->render('partials/propagateLogout.phtml'); ?> inlineScript() ?> google_id; } ?> piwik_id; } ?> render('partials/profiler.phtml') ?> client_fp; -if (empty($fp)) : ?> - - +$apiv4 = Zend_Registry::get("config")->settings->server->ip->api->v4; +$apiv6 = Zend_Registry::get("config")->settings->server->ip->api->v6; +if (false == $session->stat_valid) : ?> + + diff --git a/application/modules/default/views/layout/static_content.phtml b/application/modules/default/views/layout/static_content.phtml index a2c59b122..63598129e 100644 --- a/application/modules/default/views/layout/static_content.phtml +++ b/application/modules/default/views/layout/static_content.phtml @@ -1,98 +1,98 @@ . **/ ?> render('partials/htmlheader.phtml'); ?> render('partials/header/template.phtml'); ?>
layout()->content; ?>
render('partials/footer/template.phtml'); ?> google_id; } ?> piwik_id; } ?> client_fp; -if (empty($fp)) : ?> - - +$apiv4 = Zend_Registry::get("config")->settings->server->ip->api->v4; +$apiv6 = Zend_Registry::get("config")->settings->server->ip->api->v6; +if (false == $session->stat_valid) : ?> + + + diff --git a/application/modules/default/views/scripts/home/redirectme.phtml b/application/modules/default/views/scripts/home/redirectme.phtml index b4724b14e..0f10cb4be 100644 --- a/application/modules/default/views/scripts/home/redirectme.phtml +++ b/application/modules/default/views/scripts/home/redirectme.phtml @@ -1,79 +1,83 @@ getRequest(); $http_scheme = $request->getScheme(); $baseurl = Zend_Registry::get('config')->settings->client->default->baseurl; $url_forum = Zend_Registry::get('config')->settings->client->default->url_forum; $url_gitlab = Zend_Registry::get('config')->settings->client->default->url_gitlab; $url_myopendesktop = Zend_Registry::get('config')->settings->client->default->url_myopendesktop; $url_nextcloud = Zend_Registry::get('config')->settings->client->default->url_cloudopendesktop; $config = Zend_Registry::get('config')->settings->domain; $getAuthUser = new Default_View_Helper_GetAuthUser(); $member = $getAuthUser->getAuthUser(); $phash = null; $ltat = ''; if (Zend_Auth::getInstance()->hasIdentity()) { $sess = new Zend_Session_Namespace('ocs_meta'); $phash = $sess->phash; $ltat = $sess->openid; } $info = new Default_Model_Info(); $domains = $info->getActiveStoresForCrossDomainLogin(); ?> - Zend_Registry::get('config')->phpSettings->session->name, 'id' => Zend_Session::getId()); - Zend_Registry::get('cache')->save($data, $id); - $cookie = Local_LoginCookie::createJwt($id, 120); - $url = sprintf('%s://%s/l/settheme?k=%s', $http_scheme, $domain, $cookie); - echo(''.PHP_EOL); - } - ?>

Please Wait...

+settings->session->remember_me->name; + $remember_me = isset($_COOKIE[$cookie_name]) ? unserialize($_COOKIE[$cookie_name]) : null; + $id = crc32($domain.Zend_Session::getId()); + $data = array('domain' => Zend_Registry::get('config')->resources->session->name, 'id' => Zend_Session::getId(), 'remember_me' => $remember_me); + Zend_Registry::get('cache')->save($data, $id); + $cookie = Local_LoginCookie::createJwt($id, 120); +// $url = sprintf('%s://%s/l/settheme?k=%s', $http_scheme, $domain, $cookie); +// echo(''.PHP_EOL); + $url = sprintf('%s://%s/l/set?k=%s', $http_scheme, $domain, $cookie); + echo '' . PHP_EOL; +} +?> \ No newline at end of file diff --git a/application/modules/default/views/scripts/login/set.phtml b/application/modules/default/views/scripts/login/set.phtml new file mode 100644 index 000000000..e33d1189e --- /dev/null +++ b/application/modules/default/views/scripts/login/set.phtml @@ -0,0 +1,26 @@ +resources->session->remember_me_seconds; + /** @var Zend_Cache_Core $cache */ + $cache = Zend_Registry::get('cache'); + if ($data = $cache->load($id)) { + $cookie_params = session_get_cookie_params(); + setcookie($data['domain'], $data['id'], time() + $cookie_lifetime, $cookie_params['path'], '', $cookie_params['secure'], true); + if (false == empty($data['remember_me'])) { + $cookie_name = Zend_Registry::get('config')->settings->session->remember_me->name; + setcookie($cookie_name, serialize($data['remember_me']), time() + $cookie_lifetime, $cookie_params['path'], '', $cookie_params['secure'], true); + } + $cache->remove($id); + } + } +} + +$imagePath = APPLICATION_PATH . "/../httpdocs/img/default.png"; +$image = file_get_contents($imagePath); +echo $image; \ No newline at end of file diff --git a/application/modules/default/views/scripts/login/settheme.phtml b/application/modules/default/views/scripts/login/settheme.phtml index 6562b4db7..5ce234a94 100644 --- a/application/modules/default/views/scripts/login/settheme.phtml +++ b/application/modules/default/views/scripts/login/settheme.phtml @@ -1,18 +1,23 @@ resources->session->remember_me_seconds; /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); if ($data = $cache->load($id)) { $cookie_params = session_get_cookie_params(); - setcookie($data['domain'], $data['id'], time()+31536000, $cookie_params['path'], $_SERVER['HTTP_HOST'], $cookie_params['secure'], true); + setcookie($data['domain'], $data['id'], time() + $cookie_lifetime, $cookie_params['path'], $_SERVER['HTTP_HOST'], $cookie_params['secure'], true); + if (false == empty($data['remember_me'])) { + $cookie_name = Zend_Registry::get('config')->settings->session->remember_me->name; + setcookie($cookie_name, serialize($data['remember_me']), time() + $cookie_lifetime, $cookie_params['path'], $_SERVER['HTTP_HOST'], $cookie_params['secure'], true); + } $cache->remove($id); } } } include APPLICATION_PATH . "/../httpdocs/theme/flatui/css/empty.css"; \ No newline at end of file diff --git a/application/modules/default/views/scripts/logout/logout.phtml b/application/modules/default/views/scripts/logout/logout.phtml index d3696c4ec..19eaef720 100644 --- a/application/modules/default/views/scripts/logout/logout.phtml +++ b/application/modules/default/views/scripts/logout/logout.phtml @@ -1,46 +1,59 @@

Please Wait...

getRequest(); $http_scheme = 'https'; if (APPLICATION_ENV == 'development') { $http_scheme = $request->getScheme(); } $config = Zend_Registry::get('config')->settings->domain; $url_nextcloud = Zend_Registry::get('config')->settings->client->default->url_cloudopendesktop; $info = new Default_Model_Info(); $domains = $info->getActiveStoresForCrossDomainLogin(); foreach ($domains as $domain) { - - echo ''; - + if ($domain == $_SERVER['HTTP_HOST']) { + continue; + } + $cookie_name = Zend_Registry::get('config')->settings->session->remember_me->name; + $remember_me = isset($_COOKIE[$cookie_name]) ? unserialize($_COOKIE[$cookie_name]) : null; + $id = crc32('logout'.$domain . Zend_Session::getId()); + $data = array('domain' => Zend_Registry::get('config')->resources->session->name, + 'id' => Zend_Session::getId(), + 'remember_me' => $remember_me + ); + Zend_Registry::get('cache')->save($data, $id); + $cookie = Local_LoginCookie::createJwt($id, 120); + $url = sprintf('%s://%s/logout/set?k=%s', $http_scheme, $domain, $cookie); + echo '' . PHP_EOL; } - ?> - - -://mastodon->host?>/auth/sign_out" style="display:none;" /> */ ?> +://mastodon->host?>/auth/sign_out" style="display:none;" /> + + */ +?> \ No newline at end of file diff --git a/application/modules/default/views/scripts/logout/set.phtml b/application/modules/default/views/scripts/logout/set.phtml new file mode 100644 index 000000000..e55742aa7 --- /dev/null +++ b/application/modules/default/views/scripts/logout/set.phtml @@ -0,0 +1,33 @@ +resources->session->cookie_lifetime; + /** @var Zend_Cache_Core $cache */ + $cache = Zend_Registry::get('cache'); + if ($data = $cache->load($id)) { + $cookie_params = session_get_cookie_params(); + setcookie($data['domain'], $data['id'], time() + $cookie_lifetime, $cookie_params['path'], $_SERVER['HTTP_HOST'], $cookie_params['secure'], true); + $cache->remove($id); + } + } +} + +$imagePath = APPLICATION_PATH . "/../httpdocs/img/default.png"; +$image = file_get_contents($imagePath); +echo $image; diff --git a/docker-compose.yml b/docker-compose.yml index 3af2e16f7..a4f33a1e8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,41 +1,112 @@ -version: '3' +version: '2.4' services: web: + image: nginx:latest + ports: + - "80:80" + volumes: + - ./.docker/dev/nginx/ocs.conf:/etc/nginx/conf.d/default.conf + - ./httpdocs:/usr/local/src/ocs-webserver/httpdocs + - ./.docker_init/images_sys/store_kde:/usr/local/src/ocs-webserver/httpdocs/images_sys/store_kde + - ./.docker_init/images_sys/superstore:/usr/local/src/ocs-webserver/httpdocs/images_sys/superstore + - ./.docker_init/images_sys/store_pling:/usr/local/src/ocs-webserver/httpdocs/images_sys/store_pling + - ./.docker_init/images_sys/store_opendesktop:/usr/local/src/ocs-webserver/httpdocs/images_sys/store_opendesktop + container_name: 'ocs-web' + depends_on: + - app + networks: + dev: + aliases: + - ocs + - pling + app: build: context: . - args: - BUILD_ENV: development - ports: - - '80:80' + dockerfile: .docker/dev/app/Dockerfile +# args: +# BUILD_ENV: development + environment: + - APPLICATION_ENV=development + - APPLICATION_TIMEZONE=UTC +# - APPLICATION_LOGFILE=/var/log/ocs-webserver/application.log +# - APPLICATION_LOGMODE=a + - APPLICATION_LOGFILE=php://stdout + - APPLICATION_LOGMODE=w + - PHP_IDE_CONFIG=serverName=localhost volumes: - - .:/usr/src/ocs-webserver - - ./.docker_init/configs/application.dev.ini:/usr/src/ocs-webserver/application/configs/application.local.ini - - ./.docker_init/httpdocs/.htaccess:/usr/src/ocs-webserver/httpdocs/.htaccess - - ./.docker_init/httpdocs/images_sys/store_kde:/usr/src/ocs-webserver/httpdocs/images_sys/store_kde - - ./.docker_init/httpdocs/images_sys/store_opendesktop:/usr/src/ocs-webserver/httpdocs/images_sys/store_opendesktop - - ./.docker_init/httpdocs/images_sys/superstore:/usr/src/ocs-webserver/httpdocs/images_sys/superstore -# - ./.docker_init/templates:/usr/src/ocs-webserver/data/stores/templates - expose: - - '80' + - .:/usr/local/src/ocs-webserver + - ./.docker_init/templates:/usr/local/src/ocs-webserver/data/stores/templates + - ./.docker_init/images_sys/store_kde:/usr/local/src/ocs-webserver/httpdocs/images_sys/store_kde + - ./.docker_init/images_sys/superstore:/usr/local/src/ocs-webserver/httpdocs/images_sys/superstore + - ./.docker_init/images_sys/store_pling:/usr/local/src/ocs-webserver/httpdocs/images_sys/store_pling + - ./.docker_init/images_sys/store_opendesktop:/usr/local/src/ocs-webserver/httpdocs/images_sys/store_opendesktop +# - ./.docker/dev/app/application.local.ini:/usr/local/src/ocs-webserver/application/configs/application.local.ini +# - ./.docker_init/httpdocs/.htaccess:/usr/local/src/ocs-webserver/httpdocs/.htaccess + container_name: 'ocs-webserver' depends_on: - sessions - cache - sqldb + - ipify + networks: + - dev + ipify: + build: + context: .docker/dev/ipify + dockerfile: ./Dockerfile + container_name: 'ocs-ipify' + networks: + dev: + aliases: + - ipify4 + - ipify6 + ports: + - "8080:80" sessions: image: 'memcached:1.5' + container_name: 'ocs-sessions' expose: - '11211' + networks: + - dev cache: image: 'memcached:1.5' + container_name: 'ocs-cache' expose: - '11211' + networks: + - dev sqldb: - image: mariadb + image: mysql:5.5.57 + container_name: 'ocs-database' ports: - '3306:3306' expose: - '3306' environment: - MYSQL_ROOT_PASSWORD=${OCS_WS_MYSQL_ROOT_PWD:-root} volumes: - ./.docker_init/seed/:/docker-entrypoint-initdb.d + - ./.docker/dev/sqldb/init:/etc/mysql/conf.d + networks: + - dev + search: + image: 'solr:8.1' + container_name: 'ocs-search' + expose: + - '8983' + ports: + - '127.0.0.1:8983:8983' + volumes: + - ./.docker_init/solr/lib/mysql-connector-java-5.1.41-bin.jar:/opt/solr/contrib/dataimporthandler-extras/lib/mysql-connector-java-5.1.41-bin.jar + - ./.docker_init/solr/config:/ocs-config + entrypoint: + - docker-entrypoint.sh + - solr-precreate + - opendesktop + - /ocs-config + networks: + - dev +networks: + dev: +# enable_ipv6: true \ No newline at end of file diff --git a/httpdocs/theme/flatui/js/script.js b/httpdocs/theme/flatui/js/script.js index c3762d44d..8da4f0483 100644 --- a/httpdocs/theme/flatui/js/script.js +++ b/httpdocs/theme/flatui/js/script.js @@ -1,2689 +1,2745 @@ /** * ocs-webserver * * Copyright 2016 by pling GmbH. * * This file is part of ocs-webserver. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ +var prefix = 'ocs_'; + +var OcsStorage = { + set: function(key, value) { + localStorage[key] = JSON.stringify(value); + }, + get: function(key) { + return localStorage[key] ? JSON.parse(localStorage[key]) : null; + } +}; + +var OcsStats = { + props: {}, + a: 0, + readIp: function(apiv4, apiv6) { + var xhr1 = $.getJSON(apiv4,function(data) { OcsStats.props.ipv4=data.ip;OcsStats.saveProps(1);}); + xhr1.fail(function() { + OcsStats.saveProps(1); + }); + var xhr2 = $.getJSON(apiv6,function(data) { OcsStats.props.ipv6=data.ip;OcsStats.saveProps(2);}); + xhr2.fail(function () { + OcsStats.saveProps(2); + }); + }, + genId: function() { + var options={}; + Fingerprint2.get(options, function (components) { + var values = components.map(function (component) { return component.value }); + OcsStats.props.fp = Fingerprint2.x64hash128(values.join(''), 31); + OcsStats.saveProps(4); + }) + }, + saveProps: function(c) { + OcsStorage.set('ocs',OcsStats.props); + OcsStats.a += c; + if (OcsStats.a == 7) { + OcsStats.postProps(); + } + }, + postProps: function() { + $.post("/l/fp",OcsStats.props); + }, + readStats: function(apiv4, apiv6) { + if (window.requestIdleCallback) { + requestIdleCallback(function () { + OcsStats.genId(); + OcsStats.readIp(apiv4, apiv6); + }) + } else { + setTimeout(function () { + OcsStats.genId(); + OcsStats.readIp(apiv4, apiv6); + }, 500) + } + } +}; var newProductPage = (function () { return { setup: function () { function adjustScrollableContentHeight() { var pling_box_height = $('#pling-it-box').height(); $('.scrollable-content').height(pling_box_height); $('.scrollable-content').jScrollPane({ mouseWheelSpeed: 30 }); } function adjustSupportersHeight() { var comments_height = $('#donations-panel').find('#comments').height(); var supporters_height = $('#donations-panel').find('#supporters').height(); if (comments_height > supporters_height) { $('#donations-panel').find('#supporters').height(comments_height); } } $(document).ready(function () { adjustScrollableContentHeight(); adjustSupportersHeight(); $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { adjustSupportersHeight(); }); }); } } })(); // only instantiate when needed to instantiate: var ImagePreview = { hasError: false, setup: function () { this.initProductPicture(); this.initTitlePicture(); this.initProfilePicture(); this.initProfilePictureBackground(); }, previewImage: function (input, img_id) { if (input.files && input.files[0]) { var reader = new FileReader(); var image = new Image(); var file = input.files[0]; reader.readAsDataURL(input.files[0]); reader.onload = function (_image) { var image_element = $('#' + img_id); image.src = _image.target.result; // url.createObjectURL(file); image.onload = function () { var w = this.width, h = this.height, t = file.type, // ext only: // file.type.split('/')[1], n = file.name, s = ~~(file.size / 1024); // + 'KB' ImagePreview.hasError = false; image_element.parent().parent().find('div.bg-danger').remove(); if (w > 2000 || w < 20 || h > 2000 || h < 20) { //image_element.attr('src', '').hide().parent().append('
Wrong image dimensions
'); image_element.parent().parent().append('
Wrong image dimensions
'); //input.val(null); //$(input).replaceWith(input = $(input).clone(true)); $($(input).closest('form')[0]).trigger('reset'); ImagePreview.hasError = true; } if (s > 2000) { //image_element.attr('src', '').hide().parent().append('
File too large
'); image_element.parent().parent().append('
File too large
'); //input.val(null); //$(input).replaceWith(input = $(input).clone(true)); $($(input).closest('form')[0]).trigger('reset'); ImagePreview.hasError = true; } var allowedExtensions = /(jpg|jpeg|png|gif)$/i; if(!allowedExtensions.exec(t)) { image_element.parent().parent().append('
Invalid file type: ' + file.type + '
'); //input.val(null); //$(input).replaceWith(input = $(input).clone(true)); $($(input).closest('form')[0]).trigger('reset'); ImagePreview.hasError = true; } if (false == ImagePreview.hasError) { ImagePreview.hasError = false; image_element.attr('src', _image.target.result); image_element.show(); } }; image.onerror = function () { image_element.parent().parent().find('div.bg-danger').remove(); image_element.parent().parent().append('
Invalid file type: ' + file.type + '
'); }; //image_element.attr('src', _image.target.result); //image_element.show(); if (img_id == 'product-picture-preview') { $('button#add-product-picture').text('CHANGE LOGO'); } else if (img_id == 'title-picture-preview') { $('button#add-title-picture').text('CHANGE BANNER'); } else if (img_id == 'profile-picture-preview') { $('button#add-profile-picture').text('CHANGE PICTURE'); $('input#profile_img_src').val('local'); } else if (img_id == 'profile-picture-bg-preview') { $('button#add-profile-picture-background').text('CHANGE PICTURE'); } }; } }, previewImageMember: function (input, img_id) { if (input.files && input.files[0]) { var reader = new FileReader(); var image = new Image(); var file = input.files[0]; reader.readAsDataURL(input.files[0]); reader.onload = function (_image) { var image_element = $('#' + img_id); image.src = _image.target.result; // url.createObjectURL(file); image.onload = function () { ImagePreview.hasError = false; image_element.parent().find('.image-error').remove(); if (false == ImagePreview.hasError) { image_element.attr('src', _image.target.result); image_element.show(); } }; image.onerror = function () { image_element.parent().append('
Invalid file type
'); }; if (img_id == 'profile-picture-background-preview') { $('button#add-profile-picture-background').text('CHANGE PICTURE'); } }; } }, readImage: function (file) { var reader = new FileReader(); var image = new Image(); reader.readAsDataURL(file); reader.onload = function (_file) { image.src = _file.target.result; // url.createObjectURL(file); image.onload = function () { var w = this.width, h = this.height, t = file.type, // ext only: // file.type.split('/')[1], n = file.name, s = ~~(file.size / 1024) + 'KB'; $('#uploadPreview').append(' ' + w + 'x' + h + ' ' + s + ' ' + t + ' ' + n + '
'); }; image.onerror = function () { alert('Invalid file type: ' + file.type); }; }; }, initProductPicture: function () { if ($('#image_small').length == 0) { return; } if ($('#image_small').attr('value').length == 0) { return; } var imageTarget = $('#image_small').data('target'); $(imageTarget).attr('src', 'https://cn.opendesktop.org/cache/200x200-2/img/' + $('#image_small').attr('value')); $(imageTarget).show(); $('button#add-product-picture').text('CHANGE LOGO'); }, initTitlePicture: function () { if ($('#image_big').length == 0) { return; } if ($('#image_big').attr('value').length == 0) { return; } var imageTarget = $('#image_big').data('target'); $(imageTarget).attr('src', 'https://cn.opendesktop.org/cache/200x200-2/img/' + $('#image_big').attr('value')); $(imageTarget).show(); $('button#add-title-picture').text('CHANGE BANNER'); }, initProfilePicture: function () { if ($('#profile_image_url').length == 0) { return; } if ($('#profile_image_url').attr('value').length == 0) { return; } var imageTarget = $('#profile_image_url').data('target'); $(imageTarget).attr('src', $('#profile_image_url').attr('value')); $('#profile-picture').attr('src', $('#profile_image_url').attr('value')); $(imageTarget).show(); $('button#add-profile-picture').text('CHANGE PICTURE'); }, initProfilePictureBackground: function () { if ($('#profile_image_url_bg').length == 0) { return; } if ($('#profile_image_url_bg').attr('value').length == 0) { return; } var imageTarget = $('#profile_image_url_bg').data('target'); $(imageTarget).attr('src', $('#profile_image_url_bg').attr('value')); $('#profile-picture-background-preview').attr('src', $('#profile_image_url_bg').attr('value')); $(imageTarget).show(); $('button#add-profile-picture-background').text('CHANGE PICTURE'); } }; var MenuHover = (function () { return { setup: function () { $('body').on('click', 'a#login-dropdown', function (event) { event.stopPropagation(); $('.header-login-container').toggleClass('active'); }).on('click', '.header-login-container', function (event) { event.stopPropagation(); }).on('click', 'a.menu-trigger', function (event) { event.stopPropagation(); var html_menu_element = '.' + $(this).attr('rel'); $(html_menu_element).toggleClass('active'); }).on('mouseup', function (event) { var container = $('ul.profile-menu'); var trigger = $('li.profile-menu-container a.menu-trigger'); if (trigger.is(event.target)) { return; } if (!container.is(event.target) // if the target of the click isn't the container... && container.has(event.target).length === 0) // ... nor a descendant of the container { container.removeClass('active'); } }).on('mouseup', function (event) { container = $('div.header-login-container'); trigger = $('a#login-dropdown'); if (trigger.is(event.target)) { return; } if (!container.is(event.target) // if the target of the click isn't the container... && container.has(event.target).length === 0) // ... nor a descendant of the container { container.removeClass('active'); } }).click(function () { $('.header-login-container.active').removeClass('active'); $('.profile-menu.active').removeClass('active'); }); } }; })(); var ButtonCode = (function () { return { setup: function () { $('#button-code-heading').click(function () { if ($(this).hasClass('button-code-active')) { $(this).removeClass('button-code-active'); $(this).parent().find('.button-code').slideUp('fast'); $(this).parent().find('.button-code').css('border-bottom', 'none'); $(this).find('.icon-expand-code').css('background-image', 'url(img/icon-expand.png)'); } else { $(this).addClass('button-code-active'); $(this).parent().find('.button-code').css('border-bottom', '1px solid #bdc3c7'); $(this).parent().find('.button-code').slideDown('fast'); $(this).find('.icon-expand-code').css('background-image', 'url(img/icon-contract.png)'); } }) }, setupClipboardCopy: function (containerId) { $(containerId).on('mouseover', function () { $(this).off('mouseover'); $(this).find('[data-clipboard-target]').each(function () { var clipboardTarget = $($(this).attr('data-clipboard-target')); $(this).zclip({ path: '/theme/flatui/js/lib/ZeroClipboard.swf', copy: $.trim($(clipboardTarget).text()) }); }); }); } }; })(); var ProductPage = (function () { return { setup: function () { $(".dropdown-toggle").dropdown(); $('.scroll-pane').jScrollPane({ mouseWheelSpeed: 30, animateScroll: true }); $('.love-it').on('click', function () { this_img_src = $(this).find('img').attr('src'); if (!$(this).hasClass('no-login') && this_img_src != '/theme/flatui/img/icon-like-color.png') { $(this).prev('.share-it').trigger('click'); } }); $('.payment-options').find('.options').find('span.option').on('click', function () { var this_number = $(this).attr('title'); var number_input = $('.payment-options').find('input[type="number"]'); number_input.attr('value', this_number).val(this_number); number_input.focus(); $('.options').find('.selected').removeClass('selected'); $(this).addClass('selected'); }); }, setupPlingButton: function () { $('#pling-amount').on('focus', function () { $('#pling-amount').popover('destroy'); }); $('#pling-start').on('click', function (event) { validateElement = $('#pling-amount'); validateValue = validateElement.val(); if (validateValue == '' || (isNaN(parseFloat(validateValue)) || !isFinite(validateValue))) { event.preventDefault(); $('#pling-amount').popover({ placement: 'bottom', html: 'true', content: '
Donation must be a numeric value.
' }).popover('show'); return false; } minValue = validateElement.attr('min'); if (parseFloat(validateValue) < parseFloat(minValue)) { event.preventDefault(); $('#pling-amount').popover({ placement: 'bottom', html: 'true', content: '
Donation must be equal or greater than ' + minValue + '.
' }).popover('show'); return false; } maxValue = validateElement.attr('max'); if (parseFloat(validateValue) > parseFloat(maxValue)) { event.preventDefault(); $('#pling-amount').popover({ placement: 'bottom', html: 'true', content: '
Donation must be smaller or equal than ' + maxValue + '.
' }).popover('show'); return false; } }); function minmax(value, min, max) { if (parseInt(value) < 0 || isNaN(value)) return 0; else if (parseInt(value) > 100) return 100; else return value; } } } })(); var SlideShowRender = (function () { return { setup: function () { // add the active class to the first image $('#slideshow-container').find('img:first').addClass('active'); $('#slideshow-container').find('#navigation').find('a:first').addClass('active'); // trigger slideshow //SlideShow.setup(); } } })(); var ProductSlideShow = (function () { return { setup: function () { // arrows function $('#slideshow-container').find('#arrows').find('a').on('click', function (e) { var this_id = $(this).attr('id'); var slides = $('#slideshow-container #slides'); var current_img = slides.find('img.active'); var current_img_rel = current_img.attr('rel'); var current_nav_link = $('#slideshow-container').find('#navigation').find('a.active'); if (this_id == 'prev') { var prev_img_rel = parseInt(current_img_rel) - parseInt(1); var next_active_img = $('#slideshow-container').find('img[rel="' + prev_img_rel + '"]'); var next_active_nav_link = $('#slideshow-container').find('#navigation').find('a[rel="' + prev_img_rel + '"]'); if (!next_active_img.size() == 1) { var next_active_img = slides.find('img:last'); var next_active_nav_link = $('#slideshow-container').find('#navigation').find('a:last'); } } else if (this_id == 'next') { var next_img_rel = parseInt(current_img_rel) + parseInt(1); var next_active_img = $('#slideshow-container').find('img[rel="' + next_img_rel + '"]'); var next_active_nav_link = $('#slideshow-container').find('#navigation').find('a[rel="' + next_img_rel + '"]'); if (!next_active_img.size() == 1) { var next_active_img = slides.find('img:first'); var next_active_nav_link = $('#slideshow-container').find('#navigation').find('a:first'); } } current_img.removeClass('active'); current_nav_link.removeClass('active'); next_active_img.addClass('active'); next_active_nav_link.addClass('active'); //clearTimeout(slideShowInterval); //SlideShow.setup(); }); // navigation function $('#slideshow-container').find('#navigation').find('a').on('click', function () { var this_rel = $(this).attr('rel'); var this_image = $('#slideshow-container').find('img[rel="' + this_rel + '"]'); $('#slideshow-container').find('img.active').removeClass('active'); this_image.addClass('active'); $('#slideshow-container').find('#navigation').find('a.active').removeClass('active'); $(this).addClass('active'); }); } } })(); var SlideShow = (function () { return { setup: function () { slideShowInterval = setTimeout(function () { var current_img = $('#slideshow-container').find('img.active'); var current_img_rel = current_img.attr('rel'); var next_img_rel = parseInt(current_img_rel) + parseInt(1); var next_img = $('#slideshow-container').find('img[rel="' + next_img_rel + '"]'); var current_nav_link = $('#slideshow-container').find('#navigation').find('a.active'); current_img.removeClass('active'); current_nav_link.removeClass('active'); if (next_img.size() == 1) { next_img.addClass('active'); $('#slideshow-container').find('#navigation').find('a[rel="' + next_img_rel + '"]').addClass('active'); } else { $('#slideshow-container').find('img:first').addClass('active'); $('#slideshow-container').find('#navigation').find('a:first').addClass('active'); } //SlideShow.setup(); }, 4000); } } })(); var Popuppanel = (function () { return { setup: function () { $('body').on('click', 'a.popuppanel', function (event) { if ($(this).attr('target') === "_blank"){ console.log('dont prevent default'); } else { event.preventDefault(); var hf = $(this).attr('href'); $.fancybox({ 'hideOnContentClick': true, 'autoScale': true, 'cyclic': 'true', 'transitionIn': 'elastic', 'transitionOut': 'elastic', 'type': 'iframe', 'scrolling': 'auto', helpers: { overlay: { locked: false } }, autoSize: true, href: hf, type: 'ajax' }); } }); } } })(); var PlingsRedirect = (function () { return { setup: function () { if(window.location.hash) { $link = $(window.location.hash); $link.trigger("click"); } else if (document.location.hash) { $link = $(document.location.hash); $link.trigger("click"); } } } })(); var ShowPopups = (function () { return { setup: function () { if(window.location.hash) { alert('Hash'); $('a[href="' + document.location.hash + '"]').trigger("click"); } if (document.location.hash) { alert('Hash'); $('a[href="' + document.location.hash + '"]').trigger("click"); } } } })(); /** PRODUCT PAGE **/ // tool tips $('body').on('mouseenter', '.supporter-thumbnail', function () { $(this).popover('show'); }); $('body').on('mouseleave', '.supporter-thumbnail', function () { $(this).popover('hide'); }); var Partials = (function () { return { setup: function () { $('body').on('click', 'a.partial', function (event) { event.preventDefault(); var url = this.href; var target = $(this).attr("data-target"); var toggle = $(this).data('toggle'); var pageFragment = $(this).attr("data-fragment"); $(target).load(url + ' ' + pageFragment, function (response, status, xhr) { if (status == "error") { if (xhr.status == 401) { if (response) { var data = jQuery.parseJSON(response); var redirect = data.login_url; if (redirect) { window.location = redirect; } else { window.location = "/login"; } } } else { $(target).empty().html('Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.'); } } if (toggle) { $(toggle).modal('show'); } }); return false; }); } } })(); var Opendownloadfile= (function () { return { setup: function () { $('body').on('click', 'a.opendownloadfile', function (event) { event.preventDefault(); var file_id = $(this).attr("data-file_id"); var file_type = $(this).attr('data-file_type'); var file_name = $(this).attr('data-file_name'); var file_size = $(this).attr('data-file_size'); var project_id = $(this).attr('data-project_id'); var link_type = $(this).attr('data-link_type'); var is_external = $(this).attr('data-is-external-link'); var has_torrent = $(this).attr('data-has_torrent'); var external_link = null; var popupHeight = '450'; if(is_external == 'true') { external_link = $(this).attr('data-external_link'); popupHeight = '500'; } $.fancybox({ 'hideOnContentClick': true, 'autoScale': false, 'scrolling' : 'no', 'cyclic': 'true', 'transitionIn': 'elastic', 'transitionOut': 'elastic', 'type': 'iframe', 'width':'600', 'height':popupHeight, 'iframe': {'scrolling': 'no'}, 'fitToView' : false, 'autoSize' : false, 'id': 'opendownloadfilepopup', helpers: { overlay: { locked: false } }, href:'/dl?file_id='+file_id+'&file_type='+file_type+'&file_name='+file_name+'&file_size='+file_size+'&has_torrent='+has_torrent+'&project_id='+project_id+'&link_type='+link_type+'&is_external='+is_external+'&external_link='+external_link }); return false; }); } } })(); var PartialsButton = (function () { return { setup: function () { $('body').on('click', 'Button.partialbutton', function (event) { event.preventDefault(); var url = $(this).attr("data-href"); var target = $(this).attr("data-target"); var toggle = $(this).data('toggle'); var pageFragment = $(this).attr("data-fragment"); var spin = $(''); $(target).append(spin); $(target).load(url + ' ' + pageFragment, function (response, status, xhr) { if (status == "error") { if (xhr.status == 401) { if (response) { var data = jQuery.parseJSON(response); var redirect = data.login_url; if (redirect) { window.location = redirect; } else { window.location = "/login"; } } } else { $(target).empty().html('Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.'); } } if (toggle) { $(toggle).modal('show'); } }); return false; }); } } })(); var PartialsButtonHeartDetail = (function () { return { setup: function () { $('body').on('click', '.partialbuttonfollowproject', function (event) { event.preventDefault(); var url = $(this).attr("data-href"); var target = $(this).attr("data-target"); var auth = $(this).attr("data-auth"); var toggle = $(this).data('toggle'); var pageFragment = $(this).attr("data-fragment"); if (!auth) { $('#like-product-modal').modal('show'); return; } // product owner not allow to heart copy from voting.... var loginuser = $('#like-product-modal').find('#loginuser').val(); var productcreator = $('#like-product-modal').find('#productcreator').val(); if (loginuser == productcreator) { // ignore $('#like-product-modal').find('#votelabel').text('Project owner not allowed'); $('#like-product-modal').find('.modal-body').empty(); $('#like-product-modal').modal('show'); return; } var spin = $(''); $(target).prepend(spin); $.ajax({ url: url, cache: false }) .done(function( response ) { $(target).find('.spinning').remove(); if(response.status =='error'){ $(target).html( response.msg ); }else{ if(response.action=='delete'){ //$(target).find('.likelabel').html(response.cnt +' Likes'); $(target).find('.plingtext').html(response.cnt); $(target).find('.plingtext').addClass('heartnumberpurple'); $(target).find('.plingheart').removeClass('heartproject').addClass('heartgrey'); $(target).find('.plingheart').removeClass('fa-heart').addClass('fa-heart-o'); }else{ //$(target).find('.likelabel').html(response.cnt +' Likes'); $(target).find('.plingtext').html(response.cnt); //$(target).find('.plingtext').html(response.cnt+' Fans'); $(target).find('.plingtext').removeClass('heartnumberpurple'); $(target).find('.plingheart').removeClass('heartgrey').addClass('heartproject'); $(target).find('.plingheart').removeClass('fa-heart-o').addClass('fa-heart'); } } }); return false; }); } } })(); var PartialsButtonPlingProject = (function () { return { setup: function () { $('#plingbtn').hover(function(){ $(this).attr('src','/images/system/pling-btn-hover.png'); }, function(){ $(this).attr('src',$(this).attr('data-src')); }); $('body').on('click', '.partialbuttonplingproject', function (event) { event.preventDefault(); var url = $(this).attr("data-href"); var target = $(this).attr("data-target"); var auth = $(this).attr("data-auth"); var issupporter = $(this).attr("data-issupporter"); var toggle = $(this).data('toggle'); var pageFragment = $(this).attr("data-fragment"); if (!auth) { $('#like-product-modal').modal('show'); return; } // product owner not allow to heart copy from voting.... var loginuser = $('#like-product-modal').find('#loginuser').val(); var productcreator = $('#like-product-modal').find('#productcreator').val(); if (loginuser == productcreator) { // ignore $('#like-product-modal').find('#votelabel').text('Project owner not allowed'); $('#like-product-modal').find('.modal-body').empty(); $('#like-product-modal').modal('show'); return; } if (!issupporter) { // ignore $('#like-product-modal').find('#votelabel').html('
To pling a product and help the artist please consider becoming a supporter. Thanks!

Become a supporter
'); $('#like-product-modal').modal('show'); return; } $(target).find('.plingnum').html(''); $.ajax({ url: url, cache: false }) .done(function( response ) { //$(target).find('.spinning').remove(); if(response.status =='error'){ $(target).html( response.msg ); }else{ if(response.action=='delete'){ //pling deleted if(response.cnt==0) { $(target).find('.plingnum').html('Pling me'); }else { $(target).find('.plingnum').html(response.cnt+ ' Plings'); } $(target).find('#plingbtn').attr('src','/images/system/pling-btn-normal.png'); $(target).find('#plingbtn').attr('data-src','/images/system/pling-btn-normal.png'); }else{ //pling inserted $(target).find('.plingnum').html(response.cnt+ ' Plings'); $(target).find('#plingbtn').attr('src','/images/system/pling-btn-active.png'); $(target).find('#plingbtn').attr('data-src','/images/system/pling-btn-active.png'); } } }); return false; }); } } })(); var PartialsReview = (function () { return { setup: function () { $('body').on('click', 'a.partialreview', function (event) { event.preventDefault(); var url = this.href; var target = $(this).attr("data-target"); var toggle = $(this).data('toggle'); var pageFragment = $(this).attr("data-fragment"); // product owner not allow to vote var loginuser = $('#review-product-modal').find('#loginuser').val(); var productcreator = $('#review-product-modal').find('#productcreator').val(); if (loginuser == productcreator) { // ignore $('#review-product-modal').find('#votelabel').text('Project owner not allowed'); $('#review-product-modal').find('.modal-body').empty(); $('#review-product-modal').modal('show'); return; } var userrate = $('#review-product-modal').find('#userrate').val(); // -1 = no rate yet. 0= dislike 1=like if ($(this).hasClass("voteup")) { if (userrate == 1) { $('#review-product-modal').find('#votelabel').empty() .append(' is given already with comment:'); $('#review-product-modal').find('#commenttext').val($('#review-product-modal').find('#otxt').val()); //$('#review-product-modal').find(':submit').attr("disabled", "disabled").css("display", "none"); //$('#review-product-modal').find('#commenttext').attr("disabled", "disabled"); $('#review-product-modal').find(':submit').text("Remove Rating"); } else { $('#review-product-modal').find('input#voteup').val(1); $('#review-product-modal').find('#votelabel').empty() .append(' Add Comment (min. 1 char):'); $('#review-product-modal').find('#commenttext').val('+'); $('#review-product-modal').find(':submit').text("Rate Now"); $('#review-product-modal').find('#commenttext').removeAttr("disabled"); $('#review-product-modal').find(':submit').css("display", "block").removeAttr("disabled"); } } else { // vote down if (userrate == 0) { $('#review-product-modal').find('#votelabel').empty() .append(' is given already with comment: '); $('#review-product-modal').find('#commenttext').val($('#review-product-modal').find('#otxt').val()); // $('#review-product-modal').find('#commenttext').attr("disabled", "disabled"); // $('#review-product-modal').find(':submit').attr("disabled", "disabled").css("display", "none"); $('#review-product-modal').find(':submit').text("Remove Rating"); } else { $('#review-product-modal').find('input#voteup').val(2); $('#review-product-modal').find('#votelabel').empty() .append(' Add Comment (min. 5 char) Please explain the reason for downvote to help the creator to make it better '); $('#review-product-modal').find('#commenttext').val('-'); $('#review-product-modal').find('#commenttext').removeAttr("disabled"); $('#review-product-modal').find(':submit').removeAttr("disabled").css("display", "block"); $('#review-product-modal').find(':submit').text("Rate Now"); } } $('#review-product-modal').modal('show'); if ($('#review-product-modal').hasClass('noid')) { setTimeout(function () { $('#review-product-modal').modal('hide'); }, 2000); } return false; }); } } })(); var PartialsReviewDownloadHistory = (function () { return { setup: function () { $('body').on('click', 'button.partialReviewDownloadHistory', function (event) { event.preventDefault(); var userrate = $(this).attr("data-userrate"); // -1 = no rate yet. 0= dislike 1=like $('#review-product-modal').find('#commenttext').val($(this).attr("data-comment")); $('#review-product-modal').find('#form_p').val($(this).attr("data-project")); if ($(this).hasClass("voteup")) { if (userrate == 1) { $('#review-product-modal').find('#votelabel').empty() .append(' is given already with comment:'); $('#review-product-modal').find(':submit').attr("disabled", "disabled").css("display", "none"); $('#review-product-modal').find('#commenttext').attr("disabled", "disabled"); } else { $('#review-product-modal').find('input#voteup').val(1); $('#review-product-modal').find('#votelabel').empty() .append(' Add Comment (min. 1 char):'); $('#review-product-modal').find('#commenttext').val('+'); $('#review-product-modal').find('#commenttext').removeAttr("disabled"); $('#review-product-modal').find(':submit').css("display", "block").removeAttr("disabled"); } } else { // vote down if (userrate == 0) { $('#review-product-modal').find('#votelabel').empty() .append(' is given already with comment: '); $('#review-product-modal').find('#commenttext').attr("disabled", "disabled"); $('#review-product-modal').find(':submit').attr("disabled", "disabled").css("display", "none"); } else { $('#review-product-modal').find('input#voteup').val(2); $('#review-product-modal').find('#votelabel').empty() .append(' Add Comment (min. 5 chars): '); $('#review-product-modal').find('#commenttext').val('-'); $('#review-product-modal').find('#commenttext').removeAttr("disabled"); $('#review-product-modal').find(':submit').removeAttr("disabled").css("display", "block"); } } $('#review-product-modal').modal('show'); if ($('#review-product-modal').hasClass('noid')) { setTimeout(function () { $('#review-product-modal').modal('hide'); }, 2000); } return false; }); } } })(); //PartialsReviewDownloadHistoryNew var CreateScoreRatingPopup = (function () { return { setup: function () { var preRatingSelected=0; var currentSelect; $( "select.rating-select" ).focus(function() { currentSelect = $(this); preRatingSelected = $(this).val(); }).change(function() { var optionSelected = $(this).find("option:selected"); var valueSelected = optionSelected.val(); var textSelected = optionSelected.text(); var userscore = $(this).attr("data-userrate"); var oldcomment =$(this).attr("data-comment"); var productcreator = $(this).attr("data-creator"); var loginuser = $('#score-product-modal').find('#loginuser').val(); /*if(userscore>0) { $('#score-product-modal').find('#votelabel').empty() .append('Score '+userscore+' is given already with comment:'+oldcomment); }*/ if(!loginuser) { $('#score-product-modal').modal('show'); return; } if (loginuser == productcreator) { // ignore $('#score-product-modal').find('#votelabel').text('Project owner not allowed'); $('#score-product-modal').find('.modal-body').empty(); $('#score-product-modal').find('#modal-btn-onsubmit').remove(); $('#score-product-modal').modal('show'); return; } if(valueSelected==-1) { $('#score-product-modal').find('#votelabel').empty() .append('Remove Rating '); } else if(valueSelected<=5) { $('#score-product-modal').find('#votelabel').empty() .append('Add a review to your rating "'+textSelected +'" (min. 5 chars) Please explain the reason for downvote to help the creator to make it better '); $('#score-product-modal').find('#voteup').val(2); } else { $('#score-product-modal').find('#votelabel').empty() .append('Add a review to your rating "'+textSelected+'" (min. 1 char):'); $('#score-product-modal').find('#voteup').val(1); } $('#score-product-modal').find('#form_p').val($(this).attr("data-project")); $('#score-product-modal').find(':submit').css("display", "block").removeAttr("disabled"); $('#score-product-modal').find('#commenttext').removeAttr("disabled"); if(valueSelected>=1 && valueSelected<=3) { $('#score-product-modal').find('#commenttext').val(''); }else { $('#score-product-modal').find('#commenttext').val(textSelected); } $('#score-product-modal').find('#userscorevalue').val(valueSelected); if(valueSelected=='-1') { $('#score-product-modal').find(':submit').text("Remove Rating"); }else { $('#score-product-modal').find(':submit').text("Rate Now"); } $('#score-product-modal').modal('show'); }); $("#modal-btn-cancel").on("click", function(){ $(currentSelect).find("option[value="+preRatingSelected+"]").prop('selected', true); $("#score-product-modal").modal('hide'); }); var bOnsubmit = false; $('#modal-btn-onsubmit').on("click",function(){ bOnsubmit = true; }); $('#score-product-modal').on('hidden.bs.modal', function () { if(!bOnsubmit) { $(currentSelect).find("option[value="+preRatingSelected+"]").prop('selected', true); } }); } } })(); var PartialForms = (function () { return { setup: function () { $('body').on("submit", 'form.partial', function (event) { event.preventDefault(); event.stopImmediatePropagation(); $(this).find(':submit').attr("disabled", "disabled"); $(this).find(':submit').css("white-space", "normal"); var spin = $(''); $(this).find(':submit').append(spin); var target = $(this).attr("data-target"); var trigger = $(this).attr("data-trigger"); console.log(this); jQuery.ajax({ data: $(this).serialize(), url: this.action, type: this.method, error: function () { $(target).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
"); return false; }, success: function (results) { $(target).empty().html(results); $(target).find(trigger).trigger('click'); return false; } }); return false; }); } } })(); var PartialJsonClone = (function () { return { setup: function () { $('body').on("submit", 'form.partialjsonclone', function (event) { event.preventDefault(); event.stopImmediatePropagation(); var target = $(this).attr("data-target"); var trigger = $(this).attr("data-trigger"); var projectid = $(this).attr("data-projectid"); jQuery.ajax({ data: $(this).serialize(), url: this.action, type: this.method, dataType: "json", error: function () { $(target).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
"); }, success: function (data, textStatus) { $('form#product-report-clone').find('#clonePId').val(''); $('form#product-report-clone').find('#report-text').val('') $('#report-product-clone-'+projectid).modal('hide'); var msgBox = $('#generic-dialog'); msgBox.find('.modal-header-text').empty(); msgBox.find('.modal-body').empty().append(data.message); setTimeout(function () { msgBox.modal('show'); }, 900); } }); return false; }); } } })(); var PartialJson = (function () { return { setup: function () { $('body').on("submit", 'form.partialjson', function (event) { event.preventDefault(); event.stopImmediatePropagation(); var target = $(this).attr("data-target"); var trigger = $(this).attr("data-trigger"); jQuery.ajax({ data: $(this).serialize(), url: this.action, type: this.method, dataType: "json", error: function () { $(target).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
"); }, success: function (data, textStatus) { if (data.redirect) { // data.redirect contains the string URL to redirect to window.location = data.redirect; return; } if (target) { // data.message contains the HTML for the replacement form $(target).empty().html(data.message); } if (trigger) { $(target).find(trigger).trigger('click'); } } }); return false; }); } } })(); var PartialJsonFraud = (function () { return { setup: function () { $('body').on("submit", 'form.partialjsonfraud', function (event) { event.preventDefault(); event.stopImmediatePropagation(); var target = $(this).attr("data-target"); var trigger = $(this).attr("data-trigger"); var text = $('form.partialjsonfraud').find('#report-text').val(); if(text.length<5) { $('form.partialjsonfraud').find('p.warning').remove(); $('form.partialjsonfraud').find('#report-text').parent().append('

at least 5 chars

'); return false; } jQuery.ajax({ data: $(this).serialize(), url: this.action, type: this.method, dataType: "json", error: function () { $(target).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
"); }, success: function (data, textStatus) { if (data.redirect) { // data.redirect contains the string URL to redirect to window.location = data.redirect; return; } if (target) { // data.message contains the HTML for the replacement form $(target).empty().html(data.message); } if (trigger) { $(target).find(trigger).trigger('click'); } } }); return false; }); } } })(); var PartialPayPal = (function () { return { setup: function () { this.initPayPalForm(); this.initPayPalFee(); }, initPayPalForm: function () { $('body').on("submit", 'form.partialpaypal', function (event) { event.preventDefault(); event.stopImmediatePropagation(); var target = $(this).attr("data-target"); var trigger = $(this).attr("data-trigger"); jQuery.ajax({ data: $(this).serialize(), url: this.action, type: this.method, error: function (jqXHR, textStatus, errorThrown) { $('#modal-dialog').modal('hide'); var msgBox = $(''); msgBox.html($(jqXHR.responseText).filter('.page-container').children()); msgBox.append(''); setTimeout(function () { msgBox.modal('show'); }, 900); }, success: function (results) { $(target).empty().html(results); $(target).find(trigger).trigger('click'); $('#modal-dialog').modal('hide'); } }); return false; }); }, initPayPalFee: function () { $('body').on("change", '#amount_plings', function (event) { PartialPayPal.changeFee(); }); }, changeFee: function () { var e = document.getElementById('amount_plings'); var value = parseFloat(e.value); var pling_fee = this.round((value) * 0.05, 2); var pling_sum = (pling_fee) + (value); var paypal_fee = (pling_sum + 0.3) * 0.03 + 0.3; paypal_fee = this.round(paypal_fee, 2); var sum = value + pling_fee + paypal_fee; document.getElementById('pling_fee').value = this.round(pling_fee, 2).toFixed(2); document.getElementById('paypal_fee').value = this.round(paypal_fee, 2).toFixed(2); document.getElementById('sum').value = this.round(sum, 2); }, round: function (x, n) { var a = Math.pow(10, n); return (Math.round(x * a) / a); } } })(); var PartialCommentReviewForm = (function () { return { setup: function () { this.initForm(); }, initForm: function () { $('body').on("submit", 'form.product-add-comment-review', function (event) { event.preventDefault(); event.stopImmediatePropagation(); var c = $.trim($('#commenttext').val()); var v = $('#voteup').val(); if(v==2) { // votedown if(c.length<5) { if($('#review-product-modal').find('#votelabel').find('.warning').length==0) { $('#review-product-modal').find('#votelabel').append("
Please give a comment, thanks!"); } return; } } if(c.length<1) { if($('#review-product-modal').find('#votelabel').find('.warning').length==0) { $('#review-product-modal').find('#votelabel').append("
Please give a comment, thanks!"); } return; } $(this).find(':submit').attr("disabled", "disabled"); $(this).find(':submit').css("white-space", "normal"); var spin = $(''); $(this).find(':submit').append(spin); jQuery.ajax({ data: $(this).serialize(), url: this.action, type: this.method, error: function (jqXHR, textStatus, errorThrown) { $('#review-product-modal').modal('hide'); var msgBox = $('#generic-dialog'); msgBox.modal('hide'); msgBox.find('.modal-header-text').empty().append('Please try later.'); msgBox.find('.modal-body').empty().append("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
"); setTimeout(function () { msgBox.modal('show'); }, 900); }, success: function (results) { $('#review-product-modal').modal('hide'); location.reload(); } }); return false; }); } } })(); var PartialCommentReviewFormNew = (function () { return { setup: function () { this.initForm(); }, initForm: function () { $('body').on("submit", 'form.product-add-comment-review-new', function (event) { event.preventDefault(); event.stopImmediatePropagation(); var c = $.trim($('#score-product-modal').find('#commenttext').val()); var v = $('#score-product-modal').find('#voteup').val(); if(v==2) { // votedown if(c.length<5) { if($('#score-product-modal').find('#votelabel').find('.warning').length==0) { $('#score-product-modal').find('#votelabel').append("
Please give a comment, thanks!"); } return; } } if(c.length<1) { if($('#score-product-modal').find('#votelabel').find('.warning').length==0) { $('#score-product-modal').find('#votelabel').append("
Please give a comment, thanks!"); } return; } $(this).find(':submit').attr("disabled", "disabled"); $(this).find(':submit').css("white-space", "normal"); var spin = $(''); $(this).find(':submit').append(spin); jQuery.ajax({ data: $(this).serialize(), url: this.action, type: this.method, error: function (jqXHR, textStatus, errorThrown) { $('#score-product-modal').modal('hide'); var msgBox = $('#generic-dialog'); msgBox.modal('hide'); msgBox.find('.modal-header-text').empty().append('Please try later.'); msgBox.find('.modal-body').empty().append("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
"); setTimeout(function () { msgBox.modal('show'); }, 900); }, success: function (results) { $('#score-product-modal').modal('hide'); location.reload(); } }); return false; }); } } })(); var PartialFormsAjax = (function () { return { setup: function () { var form = $('form.partialajax'); var target = form.attr("data-target"); var trigger = form.attr("data-trigger"); $(form).find(':submit').on('click', function (e) { e.preventDefault(); $(form).find(':submit').attr("disabled", "disabled"); $(form).find(':submit').css("white-space", "normal"); var spin = $(''); $(form).find(':submit').append(spin); $(form).submit(); }); form.ajaxForm({ error: function () { $(target).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
"); }, success: function (results) { $(target).empty().html(results); $(target).find(trigger).trigger('click'); } }); } } })(); var AjaxFormWithProgress = (function () { return { setup: function (idForm) { var form = $(idForm); var target = form.attr("data-target"); var trigger = form.attr("data-trigger"); var bar = form.find('.progress-bar'); var percent = form.find('.progress-percent'); $(form).find(':submit').on('click', function (e) { e.preventDefault(); $(form).find(':submit').attr("disabled", "disabled"); $(form).find(':submit').css("white-space", "normal"); var spin = $(''); $(form).find(':submit').append(spin); $(form).submit(); }); form.ajaxForm({ beforeSend: function() { var percentVal = '0%'; bar.parent().removeClass('hidden'); bar.width(percentVal); percent.html(percentVal); }, uploadProgress: function(event, position, total, percentComplete) { var percentVal = percentComplete + '%'; bar.width(percentVal); percent.html(percentVal); }, error: function () { $(target).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
"); }, success: function (results) { var percentVal = '100%'; bar.width(percentVal); percent.html(percentVal); $(target).empty().html(results); $(target).find(trigger).trigger('click'); } }); } } })(); var PartialFormsAjaxMemberBg = (function () { return { setup: function () { var form = $('form.partialajaxbg'); var target = form.attr("data-target"); var trigger = form.attr("data-trigger"); $(form).find(':submit').on('click', function (e) { e.preventDefault(); $(form).find(':submit').attr("disabled", "disabled"); $(form).find(':submit').css("white-space", "normal"); var spin = $(''); $(form).find(':submit').append(spin); $(form).submit(); }); form.ajaxForm({ error: function () { $(target).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
"); }, success: function (results) { $(target).empty().html(results); $(target).find(trigger).trigger('click'); } }); } } })(); var AjaxForm = (function () { return { setup: function (elForm, idTargetElement) { var target = $(idTargetElement); $('body').on("submit", elForm, function (event) { event.preventDefault(); event.stopImmediatePropagation(); $(this).find('button').attr("disabled", "disabled"); $(this).find('.glyphicon.glyphicon-send').removeClass('glyphicon-send').addClass('glyphicon-refresh spinning'); jQuery.ajax({ data: $(this).serialize(), url: this.action, type: this.method, dataType: "json", error: function (jqXHR, textStatus, errorThrown) { var results = JSON && JSON.parse(jqXHR.responseText) || $.parseJSON(jqXHR.responseText); var msgBox = $('#generic-dialog'); msgBox.modal('hide'); msgBox.find('.modal-header-text').empty().append(results.title); msgBox.find('.modal-body').empty().append(results.message); setTimeout(function () { msgBox.modal('show'); }, 900); }, success: function (results) { if (results.status == 'ok') { $(target).empty().html(results.data); } if (results.status == 'error') { if (results.message != '') { alert(results.message); } else { alert('Service is temporarily unavailable.'); } } } }); return false; }); } } })(); var WidgetModalAjax = (function () { return { setup: function () { $('.my-product-item').find('a.widget-button').on('click', function () { var this_rel = $(this).attr('rel'); var this_product_id = this_rel.split('product')[1]; var target = $('.modal-body#widget-code-' + this_rel); $.ajax({ url: '/widget/config/' + this_product_id, type: 'html', success: function (results) { target.prepend(results); angular.bootstrap(target, ['widgetApp']); } }); }); } } })(); var LoginContainer = (function () { return { update: function () { if (!Date.now) { Date.now = function () { return new Date().getTime(); } } var timestamp = Date.now() / 1000 | 0; var target = '#login_container'; var url = '/authorization/htmllogin?' + timestamp; $(target).load(url, function (response, status, xhr) { // nothing to do }); } } })(); var RssNews = (function () { return { setup: function () { var json_url = "https://blog.opendesktop.org/?json=1&callback=?"; $.getJSON(json_url, function (res) { var crss = ''; $.each(res.posts, function (i, item) { if (i >= 3) { return false; } var m = moment(item.date); crss += '
' + item.title + '
' + '' + m.format('MMM DD YYYY') + ''+ item.comments.length +' Comment'+(item.comments.length>1?'s':'') +'
'; }); $("#rss-feeds").html(crss); }); } } })(); var BlogJson = (function () { return { setup: function () { var urlforum = 'https://forum.opendesktop.org/'; var json_url = '/json/forum'; $.ajax(json_url).then(function (result) { var topics = result.topic_list.topics; var crss = ''; var count =3; topics.sort(function(a,b){ return new Date(b.last_posted_at) - new Date(a.last_posted_at); }); $.each(topics, function (i, item) { if(!item.pinned){ var m = item.timeago; var r = 'Reply'; var t = item.posts_count -1; if(t==0){ r = 'Replies'; }else if(t==1){ r = 'Reply'; }else{ r = 'Replies'; } crss += '
' + item.title + '
' + '' + m + ''+ t +' '+ r +'
'; count--; } if(count==0) return false; }); $("#blogJson").html(crss); }); } } })(); var GitlabNewProjectsJson = (function () { return { setup: function (url_git) { var json_url = '/json/gitlabnewprojects'; $.ajax(json_url).then(function (result) { var topics = result; var crss = ''; $.each(topics, function (i, item) { var m = item.timeago; crss += ''; }); $("#lastgitprojects").html(crss); }); } } })(); function showGitUserAvatar(url_git,username, projectid) { var json_url = url_git+'/api/v4/users?username=' + username; $.ajax(json_url).then(function (result) { var usr_list = result; $.each(usr_list, function (i,usr) { $img = $('#avatar_' + username + '_' + projectid); //alert(usr); //alert($img.attr('src')); $img.attr('src',usr.avatar_url); //alert($img.attr('src')); }); }); } var ProductDetailCarousel = (function () { return { setup: function () { $('.carousel-inner img').each(function (index) { $(this).on("click", function () { if ($("#product-main-img-container").hasClass("imgfull")) { $('#product-main-img-container').prependTo($('#product-main')); } else { $('#product-main-img-container').prependTo($('#product-page-content')); } $("#product-main-img-container").toggleClass("imgfull"); $("#product-main-img-container").toggleClass("imgsmall"); }); }); } } })(); var AppimagequestionOnClick = (function () { return { setup: function (projectid) { $('body').on('click', 'i.appimagequestion', function (event) { var msgBox = $('#generic-dialog'); msgBox.modal('show'); msgBox.find('.modal-header-text').empty().append('AppImage Info'); msgBox.find('.modal-body').empty().append(""); }); } } })(); var ProductDetailBtnGetItClick = (function () { return { setup: function (projectid) { $('body').on('click', 'button#project_btn_download', function (event) { $.fancybox({ 'hideOnContentClick': true, 'autoScale': true, 'cyclic': 'true', 'transitionIn': 'elastic', 'transitionOut': 'elastic', 'type': 'ajax', helpers: { overlay: { locked: false } }, autoSize: true, href:'/p/'+projectid+'/ppload' }); }); } } })(); var GhnsExcludedClick = (function () { return { setup: function (projectid) { $('body').on('click', '#ghns_excluded-this-checkbox', function (event) { event.stopPropagation(); var status = 1; var title = ''; var btntxt = ''; if (this.checked) { status = 1; title = 'Please specify why this product should be excluded (min 5 chars) :'; btntxt=' ghns exclude'; } else { status = 0; title = 'Please specify why this product should be included (min 5 chars) :'; btntxt=' ghns include'; } var msgBox = $('#generic-dialog'); msgBox.modal('show'); msgBox.find('.modal-header-text').empty().append('GHNS '); msgBox.find('.modal-body').empty().append(title+ '

'); $('body').on("click", "#btn-ghns-excluded", function(){ var txt = $('#ghns-excluded-text').val(); if(txt.length<5) { alert('min 5 chars'); return false; } var project_id = $(this).attr('data-projectid'); var status = $(this).attr('data-status'); var target = "/backend/project/doghnsexclude"; $.ajax({ url: target, method:'POST', data:{'project_id':project_id,'ghns_excluded':status,'msg':txt}, success: function (results) { var msgBox = $('#generic-dialog'); if (status == 0) { msgBox.find('.modal-body').empty().append('Project is successfully included into GHNS'); $('#ghns_excluded-this-checkbox').prop("checked", false); } else { msgBox.find('.modal-body').empty().append('Project is successfully excluded into GHNS'); $('#ghns_excluded-this-checkbox').prop("checked", true); } setTimeout(function () { msgBox.modal('hide'); }, 1000); }, error: function () { alert('Service is temporarily unavailable.'); } }); }); return false; }); } } })(); var AboutMeMyProjectsPaging = (function () { return { setup: function () { $(window).scroll(function() { var end = $("footer").offset().top; var viewEnd = $(window).scrollTop() + $(window).height(); var distance = end - viewEnd; if (distance < 300){ // } // if($(window).scrollTop() == $(document).height() - $(window).height()) { if(!$('button#btnshowmoreproducts').length) return; let indicator = ''; let nextpage = $('button#btnshowmoreproducts').attr('data-page'); $('button#btnshowmoreproducts').remove(); $url = window.location.href; target = $('.about-me-details').find('li.active').find('a').attr('href'); if(target=='#user-original-products'){ $url = $url+'showoriginal' } //target = '#my-products-list'; let container = $('

').append(indicator).load($url,{projectpage:nextpage},function (response, status, xhr) { if (status == "error") { if (xhr.status == 401) { if (response) { var data = jQuery.parseJSON(response); var redirect = data.login_url; if (redirect) { window.location = redirect; } else { window.location = "/login"; } } } else { $(target).empty().html('Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.'); } } }); $(target).append(container); } }); } } })(); var AboutMeMyProjectsPagingButton = (function () { return { setup: function () { let indicator = ''; $('body').on('click', 'button#btnshowmoreproducts', function (event) { let nextpage = $(this).attr('data-page'); $(this).remove(); $url = window.location.href; //target = '#my-products-list'; target = $('.about-me-details').find('li.active').find('a').attr('href'); if(target=='#user-original-products'){ $url = $url+'showoriginal' } let container = $('
').append(indicator).load($url,{projectpage:nextpage},function (response, status, xhr) { if (status == "error") { if (xhr.status == 401) { if (response) { var data = jQuery.parseJSON(response); var redirect = data.login_url; if (redirect) { window.location = redirect; } else { window.location = "/login"; } } } else { $(target).empty().html('Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.'); } } }); $(target).append(container); }); } } })(); var ProductDetailCommentTooltip = (function () { return { setup: function () { TooltipUser.setup('tooltipuser','right'); } } })(); function generateTooltipster(elements,tooltipSide) { $(elements).each(function() { $(this).tooltipster( { side: tooltipSide, theme: ['tooltipster-light', 'tooltipster-light-customized'], contentCloning: true, contentAsHTML: true, interactive: true, functionBefore: function (instance, helper) { var origin = $(helper.origin); var userid = origin.attr('data-user'); if (origin.data('loaded') !== true) { $.get('/member/' + userid + '/tooltip/', function (data) { var d = data.data; var tmp = '
' + d.username + ' ' + d.countrycity + '
' + '
' + '
' + d.cntProjects + ' products
' + '
' + d.totalComments + ' comments
' + '
Likes ' + d.cntLikesGave + ' products
' + '
Got ' + d.cntLikesGot + ' Likes
' + '
Last time active : ' + d.lastactive_at + '
' + '
Member since : ' + d.created_at + '
' + '
'; tmp = tmp + '
'; instance.content(tmp); origin.data('loaded', true); }); } } } ); }); } var TooltipUser = (function () { return { setup: function (tooltipCls, tooltipSide) { $('.'+tooltipCls).tooltipster( { side: tooltipSide, theme: ['tooltipster-light', 'tooltipster-light-customized'], contentCloning: true, contentAsHTML: true, interactive: true, functionBefore: function (instance, helper) { var origin = $(helper.origin); var userid = origin.attr('data-user'); if (origin.data('loaded') !== true) { $.get('/member/' + userid + '/tooltip/', function (data) { var d = data.data; var tmp = '
' + d.username + ' ' + d.countrycity + '
' + '
' + '
' + d.cntProjects + ' products
' + '
' + d.totalComments + ' comments
' + '
Likes ' + d.cntLikesGave + ' products
' + '
Got ' + d.cntLikesGot + ' Likes
' + '
Last time active : ' + d.lastactive_at + '
' + '
Member since : ' + d.created_at + '
' + '
'; tmp = tmp + '
'; instance.content(tmp); origin.data('loaded', true); }); } } } ); } } })(); function generateTooltipUserPlings(elements,tooltipSide) { $(elements).each(function() { $(this).tooltipster( { side: tooltipSide, theme: ['tooltipster-light', 'tooltipster-light-customized'], contentCloning: true, contentAsHTML: true, interactive: true, functionBefore: function (instance, helper) { var origin = $(helper.origin); var userid = origin.attr('data-user'); if (origin.data('loaded') !== true) { $.get('/plings/tooltip/id/'+userid, function (data) { var tmp = '
'; $.each(data.data, function( index, value ) { if(index>10) return false; if(value.profile_image_url.indexOf('http')<0) { value.profile_image_url = "https://cn.opendesktop.org/cache/40x40-2/img/"+value.profile_image_url ; } if(value.profile_image_url.indexOf('.gif')>0) { value.profile_image_url = "https://cn.opendesktop.org/img/"+value.profile_image_url ; } tmp = tmp+'
'+value.username+'
'; }); tmp = tmp + '
'; instance.content(tmp); origin.data('loaded', true); }); } } } ); }); } var TooltipUserPlings = (function () { return { setup: function (tooltipCls, tooltipSide) { $('.'+tooltipCls).tooltipster( { side: tooltipSide, theme: ['tooltipster-light', 'tooltipster-light-customized'], contentCloning: true, contentAsHTML: true, interactive: true, functionBefore: function (instance, helper) { var origin = $(helper.origin); var userid = origin.attr('data-user'); if (origin.data('loaded') !== true) { $.get('/plings/tooltip/id/'+userid, function (data) { var tmp = '
'; $.each(data.data, function( index, value ) { if(index>10) return false; if(value.profile_image_url.indexOf('http')<0) { value.profile_image_url = "https://cn.opendesktop.org/cache/40x40-2/img/"+value.profile_image_url ; } if(value.profile_image_url.indexOf('.gif')>0) { value.profile_image_url = "https://cn.opendesktop.org/img/"+value.profile_image_url ; } tmp = tmp+'
'+value.username+'
'; }); tmp = tmp + '
'; instance.content(tmp); origin.data('loaded', true); }); } } } ); } } })(); var AboutMePage = (function () { return { setup: function (username) { var t = $(document).prop('title'); var tnew = username + "'s Profile " + t; $(document).prop('title', tnew); } } })(); var InitActiveHashTab = (function () { return { setup: function () { var activeTab = document.location.hash; if($('a[href="'+ activeTab +'"]')) { $('a[href="'+ activeTab +'"]').tab('show'); } } } })(); var AboutmeTab= (function () { return { setup: function () { var indicator = ''; $('body').on('click', 'a.aboutmetab', function (event) { event.preventDefault(); var el = $(this).attr('href'); var url = $(this).attr('data-href'); if($(el).find('.product').length==0) { // only load once $(el).append(indicator).load(url,function (){ }); } }); } } })(); var CommunityTabToplistMemberScrollPaging= (function () { return { setup: function (paramEl,paramUrl) { $(window).scroll(function() { var end = $("footer").offset().top; var viewEnd = $(window).scrollTop() + $(window).height(); var distance = end - viewEnd; if (distance < 300){ if(!$('button#toplistmemberscrollshowmore').length) return; var indicator = ''; var nextpage = $('button#toplistmemberscrollshowmore').attr('data-page'); $('button#toplistmemberscrollshowmore').remove(); var pagingurl = paramUrl+"/nopage/1/page/"+nextpage; var $newdiv = $('
'); $(paramEl).find('.product-list').append($newdiv); $($newdiv).load(pagingurl,function (){ generateTooltipster($($newdiv).find('.tooltipuser'),"right"); }) } }); } } })(); var CommunityTab= (function () { return { setup: function () { var indicator = ''; $('body').on('click', 'a.communitytab', function (event) { event.preventDefault(); var el = $(this).attr('href'); var url = $(this).attr('data-href'); if($(el).find('.list').find('.user').length==0) { // only load once $(el).find('.list').append(indicator).load(url,function (){ generateTooltipster($(el).find('.tooltipuser'),"right"); if($(el).find('.tooltipuserplings').length>0) { generateTooltipUserPlings($(el).find('.tooltipuserplings'),"right"); } if(el=='#toplistMemberPanel') { CommunityTabToplistMemberScrollPaging.setup(el,url); } // paging let spans = $(el).find('.opendesktopwidgetpager span'); spans.each(function(index) { $(this).on("click", function(){ $(this).parent().addClass('active').siblings().removeClass('active'); var pagingurl = url+"/nopage/1/page/"+$(this).html(); $(el).find('.product-list').html(''); $(el).find('.product-list').load(pagingurl,function (){ generateTooltipster($(el).find('.tooltipuser'),"right"); if($(el).find('.tooltipuserplings').length>0) { generateTooltipUserPlings($(el).find('.tooltipuserplings'),"right"); }}) }); }); //end paging }); } }); var activeTab = document.location.hash; if($('a[href="'+ activeTab +'"]').length>0) { $('a[href="'+ activeTab +'"]').tab('show'); $('a[href="'+ activeTab +'"]').trigger( "click" ); }else { activeTab = "#supportersPanel"; $('a[href="'+ activeTab +'"]').trigger( "click" ); } $('body').on('mouseenter', '.product-thumbnail-startpage', function () { $(this).popover('show'); }); $('body').on('mouseleave', '.product-thumbnail-startpage', function () { $(this).popover('hide'); }); } } })(); var TagingProduct = (function () { return { setup: function () { $('input[name=tagsuser]') .tagify({ whitelist: ['good', 'great'], autocomplete:true }) .on('remove', function(e, tagName){ console.log('removed', tagName) }) .on('add', function(e, tagName){ console.log('added', tagName) }); } } })(); var TagingProductSelect2 = (function () { return { setup: function () { $.fn.select2.amd.require(['select2/selection/search'], function (Search) { Search.prototype.searchRemoveChoice = function (decorated, item) { this.trigger('unselect', { data: item }); this.$search.val(''); this.handleSearch(); }; }, null, true); var t = $(".taggingSelect2").select2({ placeholder: "Add Tags here ...", //placeholder tags: true, tokenSeparators: [",", " "], minimumInputLength: 3, maximumSelectionLength: 5, width: 'resolve', ajax: { url: '/tag/filter', dataType: 'json', type: "GET", delay: 500, // wait 250 milliseconds before triggering the request processResults: function (data) { return { results : data.data.tags }; } } }); // Bind an event t.on('select2:select', function (e) { var data = e.params.data; var projectid = $("#tagsuserselect").attr('data-pid'); var lis = t.parent().find('ul.select2-selection__rendered').find('li.select2-selection__choice').length; if(lis>5){ t.find("option[value='"+data.id+"']").remove(); return; } var regexp=new RegExp("^[0-9A-Za-z_.-]+$"); if(!(regexp.test(data.text))){ t.find("option[value='"+data.id+"']").remove(); alert('Must be letter or number and can include hyphens'); } if(data.text.length>10){ t.find("option[value='"+data.id+"']").remove(); alert('Max. length 45 chars'); } }); } } })(); var TagingProductDetail = (function () { return { setup: function () { TagingProductDetailSelect2.setup(); $('body').on('click', 'button.topic-tags-btn', function (event) { $(this).toggleClass('Done'); $('.product_category').find('.usertagslabel').remove(); $('.tagsuserselectpanel').toggle(); if($(this).text() == 'Done'){ $(this).text('Manage tags'); var newhtml = ''; var lis = $('li.select2-selection__choice'); $.each(lis, function( index, value ) { newhtml=newhtml+''+value.title+''; }); $('.product_category').find('.topicslink').html(newhtml); }else{ $(this).text('Done'); } }); } } })(); var TagingProductDetailSelect2 = (function () { return { setup: function () { $.fn.select2.amd.require(['select2/selection/search'], function (Search) { Search.prototype.searchRemoveChoice = function (decorated, item) { this.trigger('unselect', { data: item }); this.$search.val(''); this.handleSearch(); }; }, null, true); var t = $("#tagsuserselect").select2({ placeholder: "Input tags please...", //placeholder tags: true, minimumInputLength: 3, closeOnSelect:true, maximumSelectionLength: 5, tokenSeparators: [",", " "], ajax: { url: '/tag/filter', dataType: 'json', type: "GET", delay: 500, // wait 250 milliseconds before triggering the request processResults: function (data) { return { results : data.data.tags }; } } }); // Bind an event t.on('select2:select', function (e) { var data = e.params.data; var projectid = $("#tagsuserselect").attr('data-pid'); $.post( "/tag/add", { p: projectid, t: data.id }) .done(function( data ) { if(data.status=='error'){ $('span.topic-tags-saved').css({ color: "red" }).html(data.message).show().delay(2000).fadeOut(); t.find("option[value='"+data.data.tag+"']").last().remove(); //t.find("option[value="+data.data.tag+"]").last().remove(); } else { $('span.topic-tags-saved').css({ color: "green" }).html(' Saved').show().delay(1000).fadeOut(); } }); }); // Unbind the event t.on('select2:unselect', function(e){ var data = e.params.data; var projectid = $("#tagsuserselect").attr('data-pid'); $.post( "/tag/del", { p: projectid, t: data.id }) .done(function( data ) { console.log(data); $('span.topic-tags-saved').css({ color: "green" }).html(''+data.message).show().delay(1000).fadeOut(); //$('span.topic-tags-saved').show().delay(1000).fadeOut(); }); }); } } })(); var TagingLoopMyProducts = (function () { return { setup: function () { TagingLoopMyProductsSelect2.setup(); $('body').on('click', 'button.topic-tags-btn', function (event) { $(this).toggleClass('Done'); $(this).parent().find('.topicsuser').html(''); $(this).parent().find('.tagsuserselectpanel').toggle(); if($(this).text() == 'Done'){ $(this).text('Manage tags'); var newhtml = ''; var lis = $(this).parent().find('li.select2-selection__choice'); $.each(lis, function( index, value ) { newhtml=newhtml+''+value.title+''; }); $(this).parent().find('.topicsuser').html(newhtml); }else{ $(this).text('Done'); } }); } } })(); var TagingLoopMyProductsSelect2 = (function () { return { setup: function () { $.fn.select2.amd.require(['select2/selection/search'], function (Search) { Search.prototype.searchRemoveChoice = function (decorated, item) { this.trigger('unselect', { data: item }); this.$search.val(''); this.handleSearch(); }; }, null, true); //var t = $("#tagsuserselect").select2({ var t = $(".taggingSelect2").select2({ placeholder: "Input tags please...", //placeholder tags: true, minimumInputLength: 3, closeOnSelect:true, maximumSelectionLength: 5, tokenSeparators: [",", " "], ajax: { url: '/tag/filter', dataType: 'json', type: "GET", delay: 500, // wait 250 milliseconds before triggering the request processResults: function (data) { return { results : data.data.tags }; } } }); // Bind an event t.on('select2:select', function (e) { var data = e.params.data; var projectid = $(this).attr('id').replace('tagsuserselect',''); //var projectid = $("#tagsuserselect").attr('data-pid'); $.post( "/tag/add", { p: projectid, t: data.id }) .done(function( data ) { if(data.status=='error'){ $('#topic-tags-saved'+projectid).css({ color: "red" }).html(data.message).show().delay(2000).fadeOut(); t.find("option[value='"+data.data.tag+"']").last().remove(); }else if(data.status=='existing'){ $('#topic-tags-saved'+projectid).css({ color: "red" }).html(data.message).show().delay(2000).fadeOut(); } else { $('#topic-tags-saved'+projectid).css({ color: "green" }).html(' Saved').show().delay(1000).fadeOut(); } }); }); // Unbind the event t.on('select2:unselect', function(e){ var data = e.params.data; //var projectid = $("#tagsuserselect").attr('data-pid'); var projectid = $(this).attr('id').replace('tagsuserselect',''); $.post( "/tag/del", { p: projectid, t: data.id }) .done(function( data ) { $('#topic-tags-saved'+projectid).css({ color: "green" }).html(''+data.message).show().delay(1000).fadeOut(); }); }); } } })(); var productRatingToggle = (function () { return { setup: function () { $('#showRatingAll').on('click', function () { $('#ratings-panel').find('.spinning').show(); setTimeout(function () { $('#ratings-panel').find('.spinning').hide(); }, 500); $('.btnRateFilter').removeClass('activeRating'); $(this).addClass('activeRating'); $('.productRating-rows').show(); $('.productRating-rows-inactive').show(); }); $('#showRatingActive').on('click', function () { $('#ratings-panel').find('.spinning').show(); setTimeout(function () { $('#ratings-panel').find('.spinning').hide(); }, 500); $('.btnRateFilter').removeClass('activeRating'); $(this).addClass('activeRating'); $('.productRating-rows').show(); $('.productRating-rows-inactive').hide(); }); $('#showRatingUpvotes').on('click', function () { $('#ratings-panel').find('.spinning').show(); setTimeout(function () { $('#ratings-panel').find('.spinning').hide(); }, 500); $('.btnRateFilter').removeClass('activeRating'); $(this).addClass('activeRating'); $('.productRating-rows').show(); $('.clsDownvotes').hide(); $('.productRating-rows-inactive').hide(); }); $('#showRatingDownvotes').on('click', function () { $('#ratings-panel').find('.spinning').show(); setTimeout(function () { $('#ratings-panel').find('.spinning').hide(); }, 500); $('.btnRateFilter').removeClass('activeRating'); $(this).addClass('activeRating'); $('.productRating-rows').show(); $('.productRating-rows-inactive').hide(); $('.clsUpvotes').hide(); }); } } })(); var FilterBrowseOriginalFn= (function () { return { setup: function () { $('body').on('click', 'input#filter_browse_original', function (event) { var checked = $(this).is( ":checked" ); var url = window.location.href; if(url.indexOf("browse")<0) { url = url+'/browse/'; } if(url.indexOf("filteroriginal")>0) { url = url.substring(0,url.indexOf("filteroriginal")); } if(checked){ window.location.href = url+'filteroriginal/1'; }else{ window.location.href = url+'filteroriginal/0'; } }); } } })(); var FilterBrowseTagGroupFn= (function () { return { setup: function () { $('body').on('change', 'select.filter_browse_tag_group', function (event) { var filterVal = $(this).val(); var groupId = $(this).attr('data_group_id'); $.ajax({ url: '/explore/savetaggroupfilter?group_id='+groupId+'&tag_id='+filterVal, cache: false }) .done(function( response ) { var url = window.location.href; window.location.href = url; }); }); } } })(); diff --git a/httpdocs/theme/flatui/js/script.min.js b/httpdocs/theme/flatui/js/script.min.js index 4e7a93fe1..d2c8c36c7 100644 --- a/httpdocs/theme/flatui/js/script.min.js +++ b/httpdocs/theme/flatui/js/script.min.js @@ -1 +1 @@ -var newProductPage={setup:function(){function t(){var t=$("#donations-panel").find("#comments").height();t>$("#donations-panel").find("#supporters").height()&&$("#donations-panel").find("#supporters").height(t)}$(document).ready((function(){var e;e=$("#pling-it-box").height(),$(".scrollable-content").height(e),$(".scrollable-content").jScrollPane({mouseWheelSpeed:30}),t(),$('a[data-toggle="tab"]').on("shown.bs.tab",(function(e){t()}))}))}},ImagePreview={hasError:!1,setup:function(){this.initProductPicture(),this.initTitlePicture(),this.initProfilePicture(),this.initProfilePictureBackground()},previewImage:function(t,e){if(t.files&&t.files[0]){var a=new FileReader,i=new Image,n=t.files[0];a.readAsDataURL(t.files[0]),a.onload=function(a){var o=$("#"+e);i.src=a.target.result,i.onload=function(){var e=this.width,i=this.height,r=n.type,s=(n.name,~~(n.size/1024));ImagePreview.hasError=!1,o.parent().parent().find("div.bg-danger").remove(),(e>2e3||e<20||i>2e3||i<20)&&(o.parent().parent().append('
Wrong image dimensions
'),$($(t).closest("form")[0]).trigger("reset"),ImagePreview.hasError=!0),s>2e3&&(o.parent().parent().append('
File too large
'),$($(t).closest("form")[0]).trigger("reset"),ImagePreview.hasError=!0);/(jpg|jpeg|png|gif)$/i.exec(r)||(o.parent().parent().append('
Invalid file type: '+n.type+"
"),$($(t).closest("form")[0]).trigger("reset"),ImagePreview.hasError=!0),0==ImagePreview.hasError&&(ImagePreview.hasError=!1,o.attr("src",a.target.result),o.show())},i.onerror=function(){o.parent().parent().find("div.bg-danger").remove(),o.parent().parent().append('
Invalid file type: '+n.type+"
")},"product-picture-preview"==e?$("button#add-product-picture").text("CHANGE LOGO"):"title-picture-preview"==e?$("button#add-title-picture").text("CHANGE BANNER"):"profile-picture-preview"==e?($("button#add-profile-picture").text("CHANGE PICTURE"),$("input#profile_img_src").val("local")):"profile-picture-bg-preview"==e&&$("button#add-profile-picture-background").text("CHANGE PICTURE")}}},previewImageMember:function(t,e){if(t.files&&t.files[0]){var a=new FileReader,i=new Image;t.files[0];a.readAsDataURL(t.files[0]),a.onload=function(t){var a=$("#"+e);i.src=t.target.result,i.onload=function(){ImagePreview.hasError=!1,a.parent().find(".image-error").remove(),0==ImagePreview.hasError&&(a.attr("src",t.target.result),a.show())},i.onerror=function(){a.parent().append('
Invalid file type
')},"profile-picture-background-preview"==e&&$("button#add-profile-picture-background").text("CHANGE PICTURE")}}},readImage:function(t){var e=new FileReader,a=new Image;e.readAsDataURL(t),e.onload=function(e){a.src=e.target.result,a.onload=function(){var e=this.width,a=this.height,i=t.type,n=t.name,o=~~(t.size/1024)+"KB";$("#uploadPreview").append(' '+e+"x"+a+" "+o+" "+i+" "+n+"
")},a.onerror=function(){alert("Invalid file type: "+t.type)}}},initProductPicture:function(){if(0!=$("#image_small").length&&0!=$("#image_small").attr("value").length){var t=$("#image_small").data("target");$(t).attr("src","https://cn.opendesktop.org/cache/200x200-2/img/"+$("#image_small").attr("value")),$(t).show(),$("button#add-product-picture").text("CHANGE LOGO")}},initTitlePicture:function(){if(0!=$("#image_big").length&&0!=$("#image_big").attr("value").length){var t=$("#image_big").data("target");$(t).attr("src","https://cn.opendesktop.org/cache/200x200-2/img/"+$("#image_big").attr("value")),$(t).show(),$("button#add-title-picture").text("CHANGE BANNER")}},initProfilePicture:function(){if(0!=$("#profile_image_url").length&&0!=$("#profile_image_url").attr("value").length){var t=$("#profile_image_url").data("target");$(t).attr("src",$("#profile_image_url").attr("value")),$("#profile-picture").attr("src",$("#profile_image_url").attr("value")),$(t).show(),$("button#add-profile-picture").text("CHANGE PICTURE")}},initProfilePictureBackground:function(){if(0!=$("#profile_image_url_bg").length&&0!=$("#profile_image_url_bg").attr("value").length){var t=$("#profile_image_url_bg").data("target");$(t).attr("src",$("#profile_image_url_bg").attr("value")),$("#profile-picture-background-preview").attr("src",$("#profile_image_url_bg").attr("value")),$(t).show(),$("button#add-profile-picture-background").text("CHANGE PICTURE")}}},MenuHover={setup:function(){$("body").on("click","a#login-dropdown",(function(t){t.stopPropagation(),$(".header-login-container").toggleClass("active")})).on("click",".header-login-container",(function(t){t.stopPropagation()})).on("click","a.menu-trigger",(function(t){t.stopPropagation();var e="."+$(this).attr("rel");$(e).toggleClass("active")})).on("mouseup",(function(t){var e=$("ul.profile-menu");$("li.profile-menu-container a.menu-trigger").is(t.target)||e.is(t.target)||0!==e.has(t.target).length||e.removeClass("active")})).on("mouseup",(function(t){container=$("div.header-login-container"),trigger=$("a#login-dropdown"),trigger.is(t.target)||container.is(t.target)||0!==container.has(t.target).length||container.removeClass("active")})).click((function(){$(".header-login-container.active").removeClass("active"),$(".profile-menu.active").removeClass("active")}))}},ButtonCode={setup:function(){$("#button-code-heading").click((function(){$(this).hasClass("button-code-active")?($(this).removeClass("button-code-active"),$(this).parent().find(".button-code").slideUp("fast"),$(this).parent().find(".button-code").css("border-bottom","none"),$(this).find(".icon-expand-code").css("background-image","url(img/icon-expand.png)")):($(this).addClass("button-code-active"),$(this).parent().find(".button-code").css("border-bottom","1px solid #bdc3c7"),$(this).parent().find(".button-code").slideDown("fast"),$(this).find(".icon-expand-code").css("background-image","url(img/icon-contract.png)"))}))},setupClipboardCopy:function(t){$(t).on("mouseover",(function(){$(this).off("mouseover"),$(this).find("[data-clipboard-target]").each((function(){var t=$($(this).attr("data-clipboard-target"));$(this).zclip({path:"/theme/flatui/js/lib/ZeroClipboard.swf",copy:$.trim($(t).text())})}))}))}},ProductPage={setup:function(){$(".dropdown-toggle").dropdown(),$(".scroll-pane").jScrollPane({mouseWheelSpeed:30,animateScroll:!0}),$(".love-it").on("click",(function(){this_img_src=$(this).find("img").attr("src"),$(this).hasClass("no-login")||"/theme/flatui/img/icon-like-color.png"==this_img_src||$(this).prev(".share-it").trigger("click")})),$(".payment-options").find(".options").find("span.option").on("click",(function(){var t=$(this).attr("title"),e=$(".payment-options").find('input[type="number"]');e.attr("value",t).val(t),e.focus(),$(".options").find(".selected").removeClass("selected"),$(this).addClass("selected")}))},setupPlingButton:function(){$("#pling-amount").on("focus",(function(){$("#pling-amount").popover("destroy")})),$("#pling-start").on("click",(function(t){return validateElement=$("#pling-amount"),validateValue=validateElement.val(),""==validateValue||isNaN(parseFloat(validateValue))||!isFinite(validateValue)?(t.preventDefault(),$("#pling-amount").popover({placement:"bottom",html:"true",content:'
Donation must be a numeric value.
'}).popover("show"),!1):(minValue=validateElement.attr("min"),parseFloat(validateValue)×
Donation must be equal or greater than '+minValue+".
"}).popover("show"),!1):(maxValue=validateElement.attr("max"),parseFloat(validateValue)>parseFloat(maxValue)?(t.preventDefault(),$("#pling-amount").popover({placement:"bottom",html:"true",content:'
Donation must be smaller or equal than '+maxValue+".
"}).popover("show"),!1):void 0))}))}},SlideShowRender={setup:function(){$("#slideshow-container").find("img:first").addClass("active"),$("#slideshow-container").find("#navigation").find("a:first").addClass("active")}},ProductSlideShow={setup:function(){$("#slideshow-container").find("#arrows").find("a").on("click",(function(t){var e=$(this).attr("id"),a=$("#slideshow-container #slides"),i=a.find("img.active"),n=i.attr("rel"),o=$("#slideshow-container").find("#navigation").find("a.active");if("prev"==e){var r=parseInt(n)-parseInt(1),s=$("#slideshow-container").find('img[rel="'+r+'"]'),l=$("#slideshow-container").find("#navigation").find('a[rel="'+r+'"]');1==!s.size()&&(s=a.find("img:last"),l=$("#slideshow-container").find("#navigation").find("a:last"))}else if("next"==e){var d=parseInt(n)+parseInt(1);s=$("#slideshow-container").find('img[rel="'+d+'"]'),l=$("#slideshow-container").find("#navigation").find('a[rel="'+d+'"]'),1==!s.size()&&(s=a.find("img:first"),l=$("#slideshow-container").find("#navigation").find("a:first"))}i.removeClass("active"),o.removeClass("active"),s.addClass("active"),l.addClass("active")})),$("#slideshow-container").find("#navigation").find("a").on("click",(function(){var t=$(this).attr("rel"),e=$("#slideshow-container").find('img[rel="'+t+'"]');$("#slideshow-container").find("img.active").removeClass("active"),e.addClass("active"),$("#slideshow-container").find("#navigation").find("a.active").removeClass("active"),$(this).addClass("active")}))}},SlideShow={setup:function(){slideShowInterval=setTimeout((function(){var t=$("#slideshow-container").find("img.active"),e=t.attr("rel"),a=parseInt(e)+parseInt(1),i=$("#slideshow-container").find('img[rel="'+a+'"]'),n=$("#slideshow-container").find("#navigation").find("a.active");t.removeClass("active"),n.removeClass("active"),1==i.size()?(i.addClass("active"),$("#slideshow-container").find("#navigation").find('a[rel="'+a+'"]').addClass("active")):($("#slideshow-container").find("img:first").addClass("active"),$("#slideshow-container").find("#navigation").find("a:first").addClass("active"))}),4e3)}},Popuppanel={setup:function(){$("body").on("click","a.popuppanel",(function(t){if("_blank"===$(this).attr("target"))console.log("dont prevent default");else{t.preventDefault();var e=$(this).attr("href");$.fancybox({hideOnContentClick:!0,autoScale:!0,cyclic:"true",transitionIn:"elastic",transitionOut:"elastic",type:"iframe",scrolling:"auto",helpers:{overlay:{locked:!1}},autoSize:!0,href:e,type:"ajax"})}}))}},PlingsRedirect={setup:function(){window.location.hash?($link=$(window.location.hash),$link.trigger("click")):document.location.hash&&($link=$(document.location.hash),$link.trigger("click"))}},ShowPopups={setup:function(){window.location.hash&&(alert("Hash"),$('a[href="'+document.location.hash+'"]').trigger("click")),document.location.hash&&(alert("Hash"),$('a[href="'+document.location.hash+'"]').trigger("click"))}};$("body").on("mouseenter",".supporter-thumbnail",(function(){$(this).popover("show")})),$("body").on("mouseleave",".supporter-thumbnail",(function(){$(this).popover("hide")}));var Partials={setup:function(){$("body").on("click","a.partial",(function(t){t.preventDefault();var e=this.href,a=$(this).attr("data-target"),i=$(this).data("toggle"),n=$(this).attr("data-fragment");return $(a).load(e+" "+n,(function(t,e,n){if("error"==e)if(401==n.status){if(t){var o=jQuery.parseJSON(t).login_url;window.location=o||"/login"}}else $(a).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.");i&&$(i).modal("show")})),!1}))}},Opendownloadfile={setup:function(){$("body").on("click","a.opendownloadfile",(function(t){t.preventDefault();var e=$(this).attr("data-file_id"),a=$(this).attr("data-file_type"),i=$(this).attr("data-file_name"),n=$(this).attr("data-file_size"),o=$(this).attr("data-project_id"),r=$(this).attr("data-link_type"),s=$(this).attr("data-is-external-link"),l=$(this).attr("data-has_torrent"),d=null,c="450";return"true"==s&&(d=$(this).attr("data-external_link"),c="500"),$.fancybox({hideOnContentClick:!0,autoScale:!1,scrolling:"no",cyclic:"true",transitionIn:"elastic",transitionOut:"elastic",type:"iframe",width:"600",height:c,iframe:{scrolling:"no"},fitToView:!1,autoSize:!1,id:"opendownloadfilepopup",helpers:{overlay:{locked:!1}},href:"/dl?file_id="+e+"&file_type="+a+"&file_name="+i+"&file_size="+n+"&has_torrent="+l+"&project_id="+o+"&link_type="+r+"&is_external="+s+"&external_link="+d}),!1}))}},PartialsButton={setup:function(){$("body").on("click","Button.partialbutton",(function(t){t.preventDefault();var e=$(this).attr("data-href"),a=$(this).attr("data-target"),i=$(this).data("toggle"),n=$(this).attr("data-fragment"),o=$('');return $(a).append(o),$(a).load(e+" "+n,(function(t,e,n){if("error"==e)if(401==n.status){if(t){var o=jQuery.parseJSON(t).login_url;window.location=o||"/login"}}else $(a).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.");i&&$(i).modal("show")})),!1}))}},PartialsButtonHeartDetail={setup:function(){$("body").on("click",".partialbuttonfollowproject",(function(t){t.preventDefault();var e=$(this).attr("data-href"),a=$(this).attr("data-target"),i=$(this).attr("data-auth");if($(this).data("toggle"),$(this).attr("data-fragment"),i){if($("#like-product-modal").find("#loginuser").val()==$("#like-product-modal").find("#productcreator").val())return $("#like-product-modal").find("#votelabel").text("Project owner not allowed"),$("#like-product-modal").find(".modal-body").empty(),void $("#like-product-modal").modal("show");var n=$('');return $(a).prepend(n),$.ajax({url:e,cache:!1}).done((function(t){$(a).find(".spinning").remove(),"error"==t.status?$(a).html(t.msg):"delete"==t.action?($(a).find(".plingtext").html(t.cnt),$(a).find(".plingtext").addClass("heartnumberpurple"),$(a).find(".plingheart").removeClass("heartproject").addClass("heartgrey"),$(a).find(".plingheart").removeClass("fa-heart").addClass("fa-heart-o")):($(a).find(".plingtext").html(t.cnt),$(a).find(".plingtext").removeClass("heartnumberpurple"),$(a).find(".plingheart").removeClass("heartgrey").addClass("heartproject"),$(a).find(".plingheart").removeClass("fa-heart-o").addClass("fa-heart"))})),!1}$("#like-product-modal").modal("show")}))}},PartialsButtonPlingProject={setup:function(){$("#plingbtn").hover((function(){$(this).attr("src","/images/system/pling-btn-hover.png")}),(function(){$(this).attr("src",$(this).attr("data-src"))})),$("body").on("click",".partialbuttonplingproject",(function(t){t.preventDefault();var e=$(this).attr("data-href"),a=$(this).attr("data-target"),i=$(this).attr("data-auth"),n=$(this).attr("data-issupporter");if($(this).data("toggle"),$(this).attr("data-fragment"),i)return $("#like-product-modal").find("#loginuser").val()==$("#like-product-modal").find("#productcreator").val()?($("#like-product-modal").find("#votelabel").text("Project owner not allowed"),$("#like-product-modal").find(".modal-body").empty(),void $("#like-product-modal").modal("show")):n?($(a).find(".plingnum").html(''),$.ajax({url:e,cache:!1}).done((function(t){"error"==t.status?$(a).html(t.msg):"delete"==t.action?(0==t.cnt?$(a).find(".plingnum").html("Pling me"):$(a).find(".plingnum").html(t.cnt+" Plings"),$(a).find("#plingbtn").attr("src","/images/system/pling-btn-normal.png"),$(a).find("#plingbtn").attr("data-src","/images/system/pling-btn-normal.png")):($(a).find(".plingnum").html(t.cnt+" Plings"),$(a).find("#plingbtn").attr("src","/images/system/pling-btn-active.png"),$(a).find("#plingbtn").attr("data-src","/images/system/pling-btn-active.png"))})),!1):($("#like-product-modal").find("#votelabel").html('
To pling a product and help the artist please consider becoming a supporter. Thanks!

Become a supporter
'),void $("#like-product-modal").modal("show"));$("#like-product-modal").modal("show")}))}},PartialsReview={setup:function(){$("body").on("click","a.partialreview",(function(t){if(t.preventDefault(),this.href,$(this).attr("data-target"),$(this).data("toggle"),$(this).attr("data-fragment"),$("#review-product-modal").find("#loginuser").val()==$("#review-product-modal").find("#productcreator").val())return $("#review-product-modal").find("#votelabel").text("Project owner not allowed"),$("#review-product-modal").find(".modal-body").empty(),void $("#review-product-modal").modal("show");var e=$("#review-product-modal").find("#userrate").val();return $(this).hasClass("voteup")?1==e?($("#review-product-modal").find("#votelabel").empty().append(' is given already with comment:'),$("#review-product-modal").find("#commenttext").val($("#review-product-modal").find("#otxt").val()),$("#review-product-modal").find(":submit").text("Remove Rating")):($("#review-product-modal").find("input#voteup").val(1),$("#review-product-modal").find("#votelabel").empty().append(' Add Comment (min. 1 char):'),$("#review-product-modal").find("#commenttext").val("+"),$("#review-product-modal").find(":submit").text("Rate Now"),$("#review-product-modal").find("#commenttext").removeAttr("disabled"),$("#review-product-modal").find(":submit").css("display","block").removeAttr("disabled")):0==e?($("#review-product-modal").find("#votelabel").empty().append(' is given already with comment: '),$("#review-product-modal").find("#commenttext").val($("#review-product-modal").find("#otxt").val()),$("#review-product-modal").find(":submit").text("Remove Rating")):($("#review-product-modal").find("input#voteup").val(2),$("#review-product-modal").find("#votelabel").empty().append(' Add Comment (min. 5 char) Please explain the reason for downvote to help the creator to make it better '),$("#review-product-modal").find("#commenttext").val("-"),$("#review-product-modal").find("#commenttext").removeAttr("disabled"),$("#review-product-modal").find(":submit").removeAttr("disabled").css("display","block"),$("#review-product-modal").find(":submit").text("Rate Now")),$("#review-product-modal").modal("show"),$("#review-product-modal").hasClass("noid")&&setTimeout((function(){$("#review-product-modal").modal("hide")}),2e3),!1}))}},PartialsReviewDownloadHistory={setup:function(){$("body").on("click","button.partialReviewDownloadHistory",(function(t){t.preventDefault();var e=$(this).attr("data-userrate");return $("#review-product-modal").find("#commenttext").val($(this).attr("data-comment")),$("#review-product-modal").find("#form_p").val($(this).attr("data-project")),$(this).hasClass("voteup")?1==e?($("#review-product-modal").find("#votelabel").empty().append(' is given already with comment:'),$("#review-product-modal").find(":submit").attr("disabled","disabled").css("display","none"),$("#review-product-modal").find("#commenttext").attr("disabled","disabled")):($("#review-product-modal").find("input#voteup").val(1),$("#review-product-modal").find("#votelabel").empty().append(' Add Comment (min. 1 char):'),$("#review-product-modal").find("#commenttext").val("+"),$("#review-product-modal").find("#commenttext").removeAttr("disabled"),$("#review-product-modal").find(":submit").css("display","block").removeAttr("disabled")):0==e?($("#review-product-modal").find("#votelabel").empty().append(' is given already with comment: '),$("#review-product-modal").find("#commenttext").attr("disabled","disabled"),$("#review-product-modal").find(":submit").attr("disabled","disabled").css("display","none")):($("#review-product-modal").find("input#voteup").val(2),$("#review-product-modal").find("#votelabel").empty().append(' Add Comment (min. 5 chars): '),$("#review-product-modal").find("#commenttext").val("-"),$("#review-product-modal").find("#commenttext").removeAttr("disabled"),$("#review-product-modal").find(":submit").removeAttr("disabled").css("display","block")),$("#review-product-modal").modal("show"),$("#review-product-modal").hasClass("noid")&&setTimeout((function(){$("#review-product-modal").modal("hide")}),2e3),!1}))}},CreateScoreRatingPopup={setup:function(){var t,e=0;$("select.rating-select").focus((function(){t=$(this),e=$(this).val()})).change((function(){var t=$(this).find("option:selected"),e=t.val(),a=t.text(),i=($(this).attr("data-userrate"),$(this).attr("data-comment"),$(this).attr("data-creator")),n=$("#score-product-modal").find("#loginuser").val();if(n){if(n==i)return $("#score-product-modal").find("#votelabel").text("Project owner not allowed"),$("#score-product-modal").find(".modal-body").empty(),$("#score-product-modal").find("#modal-btn-onsubmit").remove(),void $("#score-product-modal").modal("show");-1==e?$("#score-product-modal").find("#votelabel").empty().append("Remove Rating "):e<=5?($("#score-product-modal").find("#votelabel").empty().append('Add a review to your rating "'+a+'" (min. 5 chars) Please explain the reason for downvote to help the creator to make it better '),$("#score-product-modal").find("#voteup").val(2)):($("#score-product-modal").find("#votelabel").empty().append('Add a review to your rating "'+a+'" (min. 1 char):'),$("#score-product-modal").find("#voteup").val(1)),$("#score-product-modal").find("#form_p").val($(this).attr("data-project")),$("#score-product-modal").find(":submit").css("display","block").removeAttr("disabled"),$("#score-product-modal").find("#commenttext").removeAttr("disabled"),e>=1&&e<=3?$("#score-product-modal").find("#commenttext").val(""):$("#score-product-modal").find("#commenttext").val(a),$("#score-product-modal").find("#userscorevalue").val(e),"-1"==e?$("#score-product-modal").find(":submit").text("Remove Rating"):$("#score-product-modal").find(":submit").text("Rate Now"),$("#score-product-modal").modal("show")}else $("#score-product-modal").modal("show")})),$("#modal-btn-cancel").on("click",(function(){$(t).find("option[value="+e+"]").prop("selected",!0),$("#score-product-modal").modal("hide")}));var a=!1;$("#modal-btn-onsubmit").on("click",(function(){a=!0})),$("#score-product-modal").on("hidden.bs.modal",(function(){a||$(t).find("option[value="+e+"]").prop("selected",!0)}))}},PartialForms={setup:function(){$("body").on("submit","form.partial",(function(t){t.preventDefault(),t.stopImmediatePropagation(),$(this).find(":submit").attr("disabled","disabled"),$(this).find(":submit").css("white-space","normal");var e=$('');$(this).find(":submit").append(e);var a=$(this).attr("data-target"),i=$(this).attr("data-trigger");return console.log(this),jQuery.ajax({data:$(this).serialize(),url:this.action,type:this.method,error:function(){return $(a).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
"),!1},success:function(t){return $(a).empty().html(t),$(a).find(i).trigger("click"),!1}}),!1}))}},PartialJsonClone={setup:function(){$("body").on("submit","form.partialjsonclone",(function(t){t.preventDefault(),t.stopImmediatePropagation();var e=$(this).attr("data-target"),a=($(this).attr("data-trigger"),$(this).attr("data-projectid"));return jQuery.ajax({data:$(this).serialize(),url:this.action,type:this.method,dataType:"json",error:function(){$(e).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
")},success:function(t,e){$("form#product-report-clone").find("#clonePId").val(""),$("form#product-report-clone").find("#report-text").val(""),$("#report-product-clone-"+a).modal("hide");var i=$("#generic-dialog");i.find(".modal-header-text").empty(),i.find(".modal-body").empty().append(t.message),setTimeout((function(){i.modal("show")}),900)}}),!1}))}},PartialJson={setup:function(){$("body").on("submit","form.partialjson",(function(t){t.preventDefault(),t.stopImmediatePropagation();var e=$(this).attr("data-target"),a=$(this).attr("data-trigger");return jQuery.ajax({data:$(this).serialize(),url:this.action,type:this.method,dataType:"json",error:function(){$(e).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
")},success:function(t,i){t.redirect?window.location=t.redirect:(e&&$(e).empty().html(t.message),a&&$(e).find(a).trigger("click"))}}),!1}))}},PartialJsonFraud={setup:function(){$("body").on("submit","form.partialjsonfraud",(function(t){t.preventDefault(),t.stopImmediatePropagation();var e=$(this).attr("data-target"),a=$(this).attr("data-trigger");return $("form.partialjsonfraud").find("#report-text").val().length<5?($("form.partialjsonfraud").find("p.warning").remove(),$("form.partialjsonfraud").find("#report-text").parent().append('

at least 5 chars

'),!1):(jQuery.ajax({data:$(this).serialize(),url:this.action,type:this.method,dataType:"json",error:function(){$(e).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
")},success:function(t,i){t.redirect?window.location=t.redirect:(e&&$(e).empty().html(t.message),a&&$(e).find(a).trigger("click"))}}),!1)}))}},PartialPayPal={setup:function(){this.initPayPalForm(),this.initPayPalFee()},initPayPalForm:function(){$("body").on("submit","form.partialpaypal",(function(t){t.preventDefault(),t.stopImmediatePropagation();var e=$(this).attr("data-target"),a=$(this).attr("data-trigger");return jQuery.ajax({data:$(this).serialize(),url:this.action,type:this.method,error:function(t,e,a){$("#modal-dialog").modal("hide");var i=$('');i.html($(t.responseText).filter(".page-container").children()),i.append(''),setTimeout((function(){i.modal("show")}),900)},success:function(t){$(e).empty().html(t),$(e).find(a).trigger("click"),$("#modal-dialog").modal("hide")}}),!1}))},initPayPalFee:function(){$("body").on("change","#amount_plings",(function(t){PartialPayPal.changeFee()}))},changeFee:function(){var t=document.getElementById("amount_plings"),e=parseFloat(t.value),a=this.round(.05*e,2),i=.03*(a+e+.3)+.3,n=e+a+(i=this.round(i,2));document.getElementById("pling_fee").value=this.round(a,2).toFixed(2),document.getElementById("paypal_fee").value=this.round(i,2).toFixed(2),document.getElementById("sum").value=this.round(n,2)},round:function(t,e){var a=Math.pow(10,e);return Math.round(t*a)/a}},PartialCommentReviewForm={setup:function(){this.initForm()},initForm:function(){$("body").on("submit","form.product-add-comment-review",(function(t){t.preventDefault(),t.stopImmediatePropagation();var e=$.trim($("#commenttext").val());if(2==$("#voteup").val()&&e.length<5)0==$("#review-product-modal").find("#votelabel").find(".warning").length&&$("#review-product-modal").find("#votelabel").append("
Please give a comment, thanks!");else{if(!(e.length<1)){$(this).find(":submit").attr("disabled","disabled"),$(this).find(":submit").css("white-space","normal");var a=$('');return $(this).find(":submit").append(a),jQuery.ajax({data:$(this).serialize(),url:this.action,type:this.method,error:function(t,e,a){$("#review-product-modal").modal("hide");var i=$("#generic-dialog");i.modal("hide"),i.find(".modal-header-text").empty().append("Please try later."),i.find(".modal-body").empty().append("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
"),setTimeout((function(){i.modal("show")}),900)},success:function(t){$("#review-product-modal").modal("hide"),location.reload()}}),!1}0==$("#review-product-modal").find("#votelabel").find(".warning").length&&$("#review-product-modal").find("#votelabel").append("
Please give a comment, thanks!")}}))}},PartialCommentReviewFormNew={setup:function(){this.initForm()},initForm:function(){$("body").on("submit","form.product-add-comment-review-new",(function(t){t.preventDefault(),t.stopImmediatePropagation();var e=$.trim($("#score-product-modal").find("#commenttext").val());if(2==$("#score-product-modal").find("#voteup").val()&&e.length<5)0==$("#score-product-modal").find("#votelabel").find(".warning").length&&$("#score-product-modal").find("#votelabel").append("
Please give a comment, thanks!");else{if(!(e.length<1)){$(this).find(":submit").attr("disabled","disabled"),$(this).find(":submit").css("white-space","normal");var a=$('');return $(this).find(":submit").append(a),jQuery.ajax({data:$(this).serialize(),url:this.action,type:this.method,error:function(t,e,a){$("#score-product-modal").modal("hide");var i=$("#generic-dialog");i.modal("hide"),i.find(".modal-header-text").empty().append("Please try later."),i.find(".modal-body").empty().append("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
"),setTimeout((function(){i.modal("show")}),900)},success:function(t){$("#score-product-modal").modal("hide"),location.reload()}}),!1}0==$("#score-product-modal").find("#votelabel").find(".warning").length&&$("#score-product-modal").find("#votelabel").append("
Please give a comment, thanks!")}}))}},PartialFormsAjax={setup:function(){var t=$("form.partialajax"),e=t.attr("data-target"),a=t.attr("data-trigger");$(t).find(":submit").on("click",(function(e){e.preventDefault(),$(t).find(":submit").attr("disabled","disabled"),$(t).find(":submit").css("white-space","normal");var a=$('');$(t).find(":submit").append(a),$(t).submit()})),t.ajaxForm({error:function(){$(e).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
")},success:function(t){$(e).empty().html(t),$(e).find(a).trigger("click")}})}},AjaxFormWithProgress={setup:function(t){var e=$(t),a=e.attr("data-target"),i=e.attr("data-trigger"),n=e.find(".progress-bar"),o=e.find(".progress-percent");$(e).find(":submit").on("click",(function(t){t.preventDefault(),$(e).find(":submit").attr("disabled","disabled"),$(e).find(":submit").css("white-space","normal");var a=$('');$(e).find(":submit").append(a),$(e).submit()})),e.ajaxForm({beforeSend:function(){n.parent().removeClass("hidden"),n.width("0%"),o.html("0%")},uploadProgress:function(t,e,a,i){var r=i+"%";n.width(r),o.html(r)},error:function(){$(a).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
")},success:function(t){n.width("100%"),o.html("100%"),$(a).empty().html(t),$(a).find(i).trigger("click")}})}},PartialFormsAjaxMemberBg={setup:function(){var t=$("form.partialajaxbg"),e=t.attr("data-target"),a=t.attr("data-trigger");$(t).find(":submit").on("click",(function(e){e.preventDefault(),$(t).find(":submit").attr("disabled","disabled"),$(t).find(":submit").css("white-space","normal");var a=$('');$(t).find(":submit").append(a),$(t).submit()})),t.ajaxForm({error:function(){$(e).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
")},success:function(t){$(e).empty().html(t),$(e).find(a).trigger("click")}})}},AjaxForm={setup:function(t,e){var a=$(e);$("body").on("submit",t,(function(t){return t.preventDefault(),t.stopImmediatePropagation(),$(this).find("button").attr("disabled","disabled"),$(this).find(".glyphicon.glyphicon-send").removeClass("glyphicon-send").addClass("glyphicon-refresh spinning"),jQuery.ajax({data:$(this).serialize(),url:this.action,type:this.method,dataType:"json",error:function(t,e,a){var i=JSON&&JSON.parse(t.responseText)||$.parseJSON(t.responseText),n=$("#generic-dialog");n.modal("hide"),n.find(".modal-header-text").empty().append(i.title),n.find(".modal-body").empty().append(i.message),setTimeout((function(){n.modal("show")}),900)},success:function(t){"ok"==t.status&&$(a).empty().html(t.data),"error"==t.status&&(""!=t.message?alert(t.message):alert("Service is temporarily unavailable."))}}),!1}))}},WidgetModalAjax={setup:function(){$(".my-product-item").find("a.widget-button").on("click",(function(){var t=$(this).attr("rel"),e=t.split("product")[1],a=$(".modal-body#widget-code-"+t);$.ajax({url:"/widget/config/"+e,type:"html",success:function(t){a.prepend(t),angular.bootstrap(a,["widgetApp"])}})}))}},LoginContainer={update:function(){Date.now||(Date.now=function(){return(new Date).getTime()});var t="/authorization/htmllogin?"+(Date.now()/1e3|0);$("#login_container").load(t,(function(t,e,a){}))}},RssNews={setup:function(){$.getJSON("https://blog.opendesktop.org/?json=1&callback=?",(function(t){var e="";$.each(t.posts,(function(t,a){if(t>=3)return!1;var i=moment(a.date);e+='
'+a.title+'
'+i.format("MMM DD YYYY")+''+a.comments.length+" Comment"+(a.comments.length>1?"s":"")+"
"})),$("#rss-feeds").html(e)}))}},BlogJson={setup:function(){$.ajax("/json/forum").then((function(t){var e=t.topic_list.topics,a="",i=3;e.sort((function(t,e){return new Date(e.last_posted_at)-new Date(t.last_posted_at)})),$.each(e,(function(t,e){if(!e.pinned){var n=e.timeago,o="Reply",r=e.posts_count-1;o=0==r?"Replies":1==r?"Reply":"Replies",a+='
'+e.title+'
'+n+''+r+" "+o+"
",i--}if(0==i)return!1})),$("#blogJson").html(a)}))}},GitlabNewProjectsJson={setup:function(t){$.ajax("/json/gitlabnewprojects").then((function(e){var a=e,i="";$.each(a,(function(e,a){var n=a.timeago;i+='"})),$("#lastgitprojects").html(i)}))}};function showGitUserAvatar(t,e,a){var i=t+"/api/v4/users?username="+e;$.ajax(i).then((function(t){var i=t;$.each(i,(function(t,i){$img=$("#avatar_"+e+"_"+a),$img.attr("src",i.avatar_url)}))}))}var ProductDetailCarousel={setup:function(){$(".carousel-inner img").each((function(t){$(this).on("click",(function(){$("#product-main-img-container").hasClass("imgfull")?$("#product-main-img-container").prependTo($("#product-main")):$("#product-main-img-container").prependTo($("#product-page-content")),$("#product-main-img-container").toggleClass("imgfull"),$("#product-main-img-container").toggleClass("imgsmall")}))}))}},AppimagequestionOnClick={setup:function(t){$("body").on("click","i.appimagequestion",(function(t){var e=$("#generic-dialog");e.modal("show"),e.find(".modal-header-text").empty().append("AppImage Info"),e.find(".modal-body").empty().append("")}))}},ProductDetailBtnGetItClick={setup:function(t){$("body").on("click","button#project_btn_download",(function(e){$.fancybox({hideOnContentClick:!0,autoScale:!0,cyclic:"true",transitionIn:"elastic",transitionOut:"elastic",type:"ajax",helpers:{overlay:{locked:!1}},autoSize:!0,href:"/p/"+t+"/ppload"})}))}},GhnsExcludedClick={setup:function(t){$("body").on("click","#ghns_excluded-this-checkbox",(function(e){e.stopPropagation();var a=1,i="",n="";this.checked?(a=1,i="Please specify why this product should be excluded (min 5 chars) :",n=" ghns exclude"):(a=0,i="Please specify why this product should be included (min 5 chars) :",n=" ghns include");var o=$("#generic-dialog");return o.modal("show"),o.find(".modal-header-text").empty().append("GHNS "),o.find(".modal-body").empty().append(i+'

"),$("body").on("click","#btn-ghns-excluded",(function(){var t=$("#ghns-excluded-text").val();if(t.length<5)return alert("min 5 chars"),!1;var e=$(this).attr("data-projectid"),a=$(this).attr("data-status");$.ajax({url:"/backend/project/doghnsexclude",method:"POST",data:{project_id:e,ghns_excluded:a,msg:t},success:function(t){var e=$("#generic-dialog");0==a?(e.find(".modal-body").empty().append("Project is successfully included into GHNS"),$("#ghns_excluded-this-checkbox").prop("checked",!1)):(e.find(".modal-body").empty().append("Project is successfully excluded into GHNS"),$("#ghns_excluded-this-checkbox").prop("checked",!0)),setTimeout((function(){e.modal("hide")}),1e3)},error:function(){alert("Service is temporarily unavailable.")}})})),!1}))}},AboutMeMyProjectsPaging={setup:function(){$(window).scroll((function(){if($("footer").offset().top-($(window).scrollTop()+$(window).height())<300){if(!$("button#btnshowmoreproducts").length)return;let t='',e=$("button#btnshowmoreproducts").attr("data-page");$("button#btnshowmoreproducts").remove(),$url=window.location.href,target=$(".about-me-details").find("li.active").find("a").attr("href"),"#user-original-products"==target&&($url+="showoriginal");let a=$("

").append(t).load($url,{projectpage:e},(function(t,e,a){if("error"==e)if(401==a.status){if(t){var i=jQuery.parseJSON(t).login_url;window.location=i||"/login"}}else $(target).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.")}));$(target).append(a)}}))}},AboutMeMyProjectsPagingButton={setup:function(){$("body").on("click","button#btnshowmoreproducts",(function(t){let e=$(this).attr("data-page");$(this).remove(),$url=window.location.href,target=$(".about-me-details").find("li.active").find("a").attr("href"),"#user-original-products"==target&&($url+="showoriginal");let a=$("
").append('').load($url,{projectpage:e},(function(t,e,a){if("error"==e)if(401==a.status){if(t){var i=jQuery.parseJSON(t).login_url;window.location=i||"/login"}}else $(target).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.")}));$(target).append(a)}))}},ProductDetailCommentTooltip={setup:function(){TooltipUser.setup("tooltipuser","right")}};function generateTooltipster(t,e){$(t).each((function(){$(this).tooltipster({side:e,theme:["tooltipster-light","tooltipster-light-customized"],contentCloning:!0,contentAsHTML:!0,interactive:!0,functionBefore:function(t,e){var a=$(e.origin),i=a.attr("data-user");!0!==a.data("loaded")&&$.get("/member/"+i+"/tooltip/",(function(e){var i=e.data,n='
'+i.username+' '+i.countrycity+'
'+i.cntProjects+' products
'+i.totalComments+' comments
Likes '+i.cntLikesGave+' products
Got '+i.cntLikesGot+' Likes
Last time active : '+i.lastactive_at+'
Member since : '+i.created_at+"
";n+="
",t.content(n),a.data("loaded",!0)}))}})}))}var TooltipUser={setup:function(t,e){$("."+t).tooltipster({side:e,theme:["tooltipster-light","tooltipster-light-customized"],contentCloning:!0,contentAsHTML:!0,interactive:!0,functionBefore:function(t,e){var a=$(e.origin),i=a.attr("data-user");!0!==a.data("loaded")&&$.get("/member/"+i+"/tooltip/",(function(e){var i=e.data,n='
'+i.username+' '+i.countrycity+'
'+i.cntProjects+' products
'+i.totalComments+' comments
Likes '+i.cntLikesGave+' products
Got '+i.cntLikesGot+' Likes
Last time active : '+i.lastactive_at+'
Member since : '+i.created_at+"
";n+="
",t.content(n),a.data("loaded",!0)}))}})}};function generateTooltipUserPlings(t,e){$(t).each((function(){$(this).tooltipster({side:e,theme:["tooltipster-light","tooltipster-light-customized"],contentCloning:!0,contentAsHTML:!0,interactive:!0,functionBefore:function(t,e){var a=$(e.origin),i=a.attr("data-user");!0!==a.data("loaded")&&$.get("/plings/tooltip/id/"+i,(function(e){var i='
';$.each(e.data,(function(t,e){if(t>10)return!1;e.profile_image_url.indexOf("http")<0&&(e.profile_image_url="https://cn.opendesktop.org/cache/40x40-2/img/"+e.profile_image_url),e.profile_image_url.indexOf(".gif")>0&&(e.profile_image_url="https://cn.opendesktop.org/img/"+e.profile_image_url),i=i+'
'+e.username+"
"})),i+="
",t.content(i),a.data("loaded",!0)}))}})}))}var TooltipUserPlings={setup:function(t,e){$("."+t).tooltipster({side:e,theme:["tooltipster-light","tooltipster-light-customized"],contentCloning:!0,contentAsHTML:!0,interactive:!0,functionBefore:function(t,e){var a=$(e.origin),i=a.attr("data-user");!0!==a.data("loaded")&&$.get("/plings/tooltip/id/"+i,(function(e){var i='
';$.each(e.data,(function(t,e){if(t>10)return!1;e.profile_image_url.indexOf("http")<0&&(e.profile_image_url="https://cn.opendesktop.org/cache/40x40-2/img/"+e.profile_image_url),e.profile_image_url.indexOf(".gif")>0&&(e.profile_image_url="https://cn.opendesktop.org/img/"+e.profile_image_url),i=i+'
'+e.username+"
"})),i+="
",t.content(i),a.data("loaded",!0)}))}})}},AboutMePage={setup:function(t){var e=t+"'s Profile "+$(document).prop("title");$(document).prop("title",e)}},InitActiveHashTab={setup:function(){var t=document.location.hash;$('a[href="'+t+'"]')&&$('a[href="'+t+'"]').tab("show")}},AboutmeTab={setup:function(){$("body").on("click","a.aboutmetab",(function(t){t.preventDefault();var e=$(this).attr("href"),a=$(this).attr("data-href");0==$(e).find(".product").length&&$(e).append('').load(a,(function(){}))}))}},CommunityTabToplistMemberScrollPaging={setup:function(t,e){$(window).scroll((function(){if($("footer").offset().top-($(window).scrollTop()+$(window).height())<300){if(!$("button#toplistmemberscrollshowmore").length)return;var a=$("button#toplistmemberscrollshowmore").attr("data-page");$("button#toplistmemberscrollshowmore").remove();var i=e+"/nopage/1/page/"+a,n=$('
');$(t).find(".product-list").append(n),$(n).load(i,(function(){generateTooltipster($(n).find(".tooltipuser"),"right")}))}}))}},CommunityTab={setup:function(){$("body").on("click","a.communitytab",(function(t){t.preventDefault();var e=$(this).attr("href"),a=$(this).attr("data-href");0==$(e).find(".list").find(".user").length&&$(e).find(".list").append('').load(a,(function(){generateTooltipster($(e).find(".tooltipuser"),"right"),$(e).find(".tooltipuserplings").length>0&&generateTooltipUserPlings($(e).find(".tooltipuserplings"),"right"),"#toplistMemberPanel"==e&&CommunityTabToplistMemberScrollPaging.setup(e,a),$(e).find(".opendesktopwidgetpager span").each((function(t){$(this).on("click",(function(){$(this).parent().addClass("active").siblings().removeClass("active");var t=a+"/nopage/1/page/"+$(this).html();$(e).find(".product-list").html(""),$(e).find(".product-list").load(t,(function(){generateTooltipster($(e).find(".tooltipuser"),"right"),$(e).find(".tooltipuserplings").length>0&&generateTooltipUserPlings($(e).find(".tooltipuserplings"),"right")}))}))}))}))}));var t=document.location.hash;$('a[href="'+t+'"]').length>0?($('a[href="'+t+'"]').tab("show"),$('a[href="'+t+'"]').trigger("click")):(t="#supportersPanel",$('a[href="'+t+'"]').trigger("click")),$("body").on("mouseenter",".product-thumbnail-startpage",(function(){$(this).popover("show")})),$("body").on("mouseleave",".product-thumbnail-startpage",(function(){$(this).popover("hide")}))}},TagingProduct={setup:function(){$("input[name=tagsuser]").tagify({whitelist:["good","great"],autocomplete:!0}).on("remove",(function(t,e){console.log("removed",e)})).on("add",(function(t,e){console.log("added",e)}))}},TagingProductSelect2={setup:function(){$.fn.select2.amd.require(["select2/selection/search"],(function(t){t.prototype.searchRemoveChoice=function(t,e){this.trigger("unselect",{data:e}),this.$search.val(""),this.handleSearch()}}),null,!0);var t=$(".taggingSelect2").select2({placeholder:"Add Tags here ...",tags:!0,tokenSeparators:[","," "],minimumInputLength:3,maximumSelectionLength:5,width:"resolve",ajax:{url:"/tag/filter",dataType:"json",type:"GET",delay:500,processResults:function(t){return{results:t.data.tags}}}});t.on("select2:select",(function(e){var a=e.params.data;$("#tagsuserselect").attr("data-pid"),t.parent().find("ul.select2-selection__rendered").find("li.select2-selection__choice").length>5?t.find("option[value='"+a.id+"']").remove():(new RegExp("^[0-9A-Za-z_.-]+$").test(a.text)||(t.find("option[value='"+a.id+"']").remove(),alert("Must be letter or number and can include hyphens")),a.text.length>10&&(t.find("option[value='"+a.id+"']").remove(),alert("Max. length 45 chars")))}))}},TagingProductDetail={setup:function(){TagingProductDetailSelect2.setup(),$("body").on("click","button.topic-tags-btn",(function(t){if($(this).toggleClass("Done"),$(".product_category").find(".usertagslabel").remove(),$(".tagsuserselectpanel").toggle(),"Done"==$(this).text()){$(this).text("Manage tags");var e="",a=$("li.select2-selection__choice");$.each(a,(function(t,a){e=e+''+a.title+""})),$(".product_category").find(".topicslink").html(e)}else $(this).text("Done")}))}},TagingProductDetailSelect2={setup:function(){$.fn.select2.amd.require(["select2/selection/search"],(function(t){t.prototype.searchRemoveChoice=function(t,e){this.trigger("unselect",{data:e}),this.$search.val(""),this.handleSearch()}}),null,!0);var t=$("#tagsuserselect").select2({placeholder:"Input tags please...",tags:!0,minimumInputLength:3,closeOnSelect:!0,maximumSelectionLength:5,tokenSeparators:[","," "],ajax:{url:"/tag/filter",dataType:"json",type:"GET",delay:500,processResults:function(t){return{results:t.data.tags}}}});t.on("select2:select",(function(e){var a=e.params.data,i=$("#tagsuserselect").attr("data-pid");$.post("/tag/add",{p:i,t:a.id}).done((function(e){"error"==e.status?($("span.topic-tags-saved").css({color:"red"}).html(e.message).show().delay(2e3).fadeOut(),t.find("option[value='"+e.data.tag+"']").last().remove()):$("span.topic-tags-saved").css({color:"green"}).html(' Saved').show().delay(1e3).fadeOut()}))})),t.on("select2:unselect",(function(t){var e=t.params.data,a=$("#tagsuserselect").attr("data-pid");$.post("/tag/del",{p:a,t:e.id}).done((function(t){console.log(t),$("span.topic-tags-saved").css({color:"green"}).html(''+t.message).show().delay(1e3).fadeOut()}))}))}},TagingLoopMyProducts={setup:function(){TagingLoopMyProductsSelect2.setup(),$("body").on("click","button.topic-tags-btn",(function(t){if($(this).toggleClass("Done"),$(this).parent().find(".topicsuser").html(""),$(this).parent().find(".tagsuserselectpanel").toggle(),"Done"==$(this).text()){$(this).text("Manage tags");var e="",a=$(this).parent().find("li.select2-selection__choice");$.each(a,(function(t,a){e=e+''+a.title+""})),$(this).parent().find(".topicsuser").html(e)}else $(this).text("Done")}))}},TagingLoopMyProductsSelect2={setup:function(){$.fn.select2.amd.require(["select2/selection/search"],(function(t){t.prototype.searchRemoveChoice=function(t,e){this.trigger("unselect",{data:e}),this.$search.val(""),this.handleSearch()}}),null,!0);var t=$(".taggingSelect2").select2({placeholder:"Input tags please...",tags:!0,minimumInputLength:3,closeOnSelect:!0,maximumSelectionLength:5,tokenSeparators:[","," "],ajax:{url:"/tag/filter",dataType:"json",type:"GET",delay:500,processResults:function(t){return{results:t.data.tags}}}});t.on("select2:select",(function(e){var a=e.params.data,i=$(this).attr("id").replace("tagsuserselect","");$.post("/tag/add",{p:i,t:a.id}).done((function(e){"error"==e.status?($("#topic-tags-saved"+i).css({color:"red"}).html(e.message).show().delay(2e3).fadeOut(),t.find("option[value='"+e.data.tag+"']").last().remove()):"existing"==e.status?$("#topic-tags-saved"+i).css({color:"red"}).html(e.message).show().delay(2e3).fadeOut():$("#topic-tags-saved"+i).css({color:"green"}).html(' Saved').show().delay(1e3).fadeOut()}))})),t.on("select2:unselect",(function(t){var e=t.params.data,a=$(this).attr("id").replace("tagsuserselect","");$.post("/tag/del",{p:a,t:e.id}).done((function(t){$("#topic-tags-saved"+a).css({color:"green"}).html(''+t.message).show().delay(1e3).fadeOut()}))}))}},productRatingToggle={setup:function(){$("#showRatingAll").on("click",(function(){$("#ratings-panel").find(".spinning").show(),setTimeout((function(){$("#ratings-panel").find(".spinning").hide()}),500),$(".btnRateFilter").removeClass("activeRating"),$(this).addClass("activeRating"),$(".productRating-rows").show(),$(".productRating-rows-inactive").show()})),$("#showRatingActive").on("click",(function(){$("#ratings-panel").find(".spinning").show(),setTimeout((function(){$("#ratings-panel").find(".spinning").hide()}),500),$(".btnRateFilter").removeClass("activeRating"),$(this).addClass("activeRating"),$(".productRating-rows").show(),$(".productRating-rows-inactive").hide()})),$("#showRatingUpvotes").on("click",(function(){$("#ratings-panel").find(".spinning").show(),setTimeout((function(){$("#ratings-panel").find(".spinning").hide()}),500),$(".btnRateFilter").removeClass("activeRating"),$(this).addClass("activeRating"),$(".productRating-rows").show(),$(".clsDownvotes").hide(),$(".productRating-rows-inactive").hide()})),$("#showRatingDownvotes").on("click",(function(){$("#ratings-panel").find(".spinning").show(),setTimeout((function(){$("#ratings-panel").find(".spinning").hide()}),500),$(".btnRateFilter").removeClass("activeRating"),$(this).addClass("activeRating"),$(".productRating-rows").show(),$(".productRating-rows-inactive").hide(),$(".clsUpvotes").hide()}))}},FilterBrowseOriginalFn={setup:function(){$("body").on("click","input#filter_browse_original",(function(t){var e=$(this).is(":checked"),a=window.location.href;a.indexOf("browse")<0&&(a+="/browse/"),a.indexOf("filteroriginal")>0&&(a=a.substring(0,a.indexOf("filteroriginal"))),window.location.href=e?a+"filteroriginal/1":a+"filteroriginal/0"}))}},FilterBrowseTagGroupFn={setup:function(){$("body").on("change","select.filter_browse_tag_group",(function(t){var e=$(this).val(),a=$(this).attr("data_group_id");$.ajax({url:"/explore/savetaggroupfilter?group_id="+a+"&tag_id="+e,cache:!1}).done((function(t){var e=window.location.href;window.location.href=e}))}))}}; \ No newline at end of file +var prefix="ocs_",OcsStorage={set:function(e,t){localStorage[e]=JSON.stringify(t)},get:function(e){return localStorage[e]?JSON.parse(localStorage[e]):null}},OcsStats={props:{},a:0,readIp:function(e,t){var a=$.getJSON(e,function(e){OcsStats.props.ipv4=e.ip,OcsStats.saveProps(1)});a.fail(function(){OcsStats.saveProps(1)});var i=$.getJSON(t,function(e){OcsStats.props.ipv6=e.ip,OcsStats.saveProps(2)});i.fail(function(){OcsStats.saveProps(2)})},genId:function(){Fingerprint2.get({},function(e){var t=e.map(function(e){return e.value});OcsStats.props.fp=Fingerprint2.x64hash128(t.join(""),31),OcsStats.saveProps(4)})},saveProps:function(e){OcsStorage.set("ocs",OcsStats.props),OcsStats.a+=e,7==OcsStats.a&&OcsStats.postProps()},postProps:function(){$.post("/l/fp",OcsStats.props)},readStats:function(e,t){window.requestIdleCallback?requestIdleCallback(function(){OcsStats.genId(),OcsStats.readIp(e,t)}):setTimeout(function(){OcsStats.genId(),OcsStats.readIp(e,t)},500)}},newProductPage=function(){return{setup:function(){function e(){var e=$("#pling-it-box").height();$(".scrollable-content").height(e),$(".scrollable-content").jScrollPane({mouseWheelSpeed:30})}function t(){var e=$("#donations-panel").find("#comments").height(),t=$("#donations-panel").find("#supporters").height();e>t&&$("#donations-panel").find("#supporters").height(e)}$(document).ready(function(){e(),t(),$("a[data-toggle=\"tab\"]").on("shown.bs.tab",function(){t()})})}}}(),ImagePreview={hasError:!1,setup:function(){this.initProductPicture(),this.initTitlePicture(),this.initProfilePicture(),this.initProfilePictureBackground()},previewImage:function(e,t){if(e.files&&e.files[0]){var a=new FileReader,i=new Image,o=e.files[0];a.readAsDataURL(e.files[0]),a.onload=function(a){var r=$("#"+t);i.src=a.target.result,i.onload=function(){var i=this.width,l=this.height,d=o.type,t=o.name,n=~~(o.size/1024);ImagePreview.hasError=!1,r.parent().parent().find("div.bg-danger").remove(),(2e3i||2e3l)&&(r.parent().parent().append("
Wrong image dimensions
"),$($(e).closest("form")[0]).trigger("reset"),ImagePreview.hasError=!0),2e3File too large"),$($(e).closest("form")[0]).trigger("reset"),ImagePreview.hasError=!0);var s=/(jpg|jpeg|png|gif)$/i;s.exec(d)||(r.parent().parent().append("
Invalid file type: "+o.type+"
"),$($(e).closest("form")[0]).trigger("reset"),ImagePreview.hasError=!0),!1==ImagePreview.hasError&&(ImagePreview.hasError=!1,r.attr("src",a.target.result),r.show())},i.onerror=function(){r.parent().parent().find("div.bg-danger").remove(),r.parent().parent().append("
Invalid file type: "+o.type+"
")},"product-picture-preview"==t?$("button#add-product-picture").text("CHANGE LOGO"):"title-picture-preview"==t?$("button#add-title-picture").text("CHANGE BANNER"):"profile-picture-preview"==t?($("button#add-profile-picture").text("CHANGE PICTURE"),$("input#profile_img_src").val("local")):"profile-picture-bg-preview"==t&&$("button#add-profile-picture-background").text("CHANGE PICTURE")}}},previewImageMember:function(e,t){if(e.files&&e.files[0]){var a=new FileReader,i=new Image,o=e.files[0];a.readAsDataURL(e.files[0]),a.onload=function(e){var a=$("#"+t);i.src=e.target.result,i.onload=function(){ImagePreview.hasError=!1,a.parent().find(".image-error").remove(),!1==ImagePreview.hasError&&(a.attr("src",e.target.result),a.show())},i.onerror=function(){a.parent().append("
Invalid file type
")},"profile-picture-background-preview"==t&&$("button#add-profile-picture-background").text("CHANGE PICTURE")}}},readImage:function(e){var t=new FileReader,a=new Image;t.readAsDataURL(e),t.onload=function(t){a.src=t.target.result,a.onload=function(){var a=this.width,i=this.height,o=e.type,t=e.name,r=~~(e.size/1024)+"KB";$("#uploadPreview").append(" "+a+"x"+i+" "+r+" "+o+" "+t+"
")},a.onerror=function(){alert("Invalid file type: "+e.type)}}},initProductPicture:function(){if(0!=$("#image_small").length&&0!=$("#image_small").attr("value").length){var e=$("#image_small").data("target");$(e).attr("src","https://cn.opendesktop.org/cache/200x200-2/img/"+$("#image_small").attr("value")),$(e).show(),$("button#add-product-picture").text("CHANGE LOGO")}},initTitlePicture:function(){if(0!=$("#image_big").length&&0!=$("#image_big").attr("value").length){var e=$("#image_big").data("target");$(e).attr("src","https://cn.opendesktop.org/cache/200x200-2/img/"+$("#image_big").attr("value")),$(e).show(),$("button#add-title-picture").text("CHANGE BANNER")}},initProfilePicture:function(){if(0!=$("#profile_image_url").length&&0!=$("#profile_image_url").attr("value").length){var e=$("#profile_image_url").data("target");$(e).attr("src",$("#profile_image_url").attr("value")),$("#profile-picture").attr("src",$("#profile_image_url").attr("value")),$(e).show(),$("button#add-profile-picture").text("CHANGE PICTURE")}},initProfilePictureBackground:function(){if(0!=$("#profile_image_url_bg").length&&0!=$("#profile_image_url_bg").attr("value").length){var e=$("#profile_image_url_bg").data("target");$(e).attr("src",$("#profile_image_url_bg").attr("value")),$("#profile-picture-background-preview").attr("src",$("#profile_image_url_bg").attr("value")),$(e).show(),$("button#add-profile-picture-background").text("CHANGE PICTURE")}}},MenuHover=function(){return{setup:function(){$("body").on("click","a#login-dropdown",function(e){e.stopPropagation(),$(".header-login-container").toggleClass("active")}).on("click",".header-login-container",function(e){e.stopPropagation()}).on("click","a.menu-trigger",function(e){e.stopPropagation();var t="."+$(this).attr("rel");$(t).toggleClass("active")}).on("mouseup",function(e){var t=$("ul.profile-menu"),a=$("li.profile-menu-container a.menu-trigger");a.is(e.target)||!t.is(e.target)&&0===t.has(e.target).length&&t.removeClass("active")}).on("mouseup",function(e){container=$("div.header-login-container"),trigger=$("a#login-dropdown");trigger.is(e.target)||!container.is(e.target)&&0===container.has(e.target).length&&container.removeClass("active")}).click(function(){$(".header-login-container.active").removeClass("active"),$(".profile-menu.active").removeClass("active")})}}}(),ButtonCode=function(){return{setup:function(){$("#button-code-heading").click(function(){$(this).hasClass("button-code-active")?($(this).removeClass("button-code-active"),$(this).parent().find(".button-code").slideUp("fast"),$(this).parent().find(".button-code").css("border-bottom","none"),$(this).find(".icon-expand-code").css("background-image","url(img/icon-expand.png)")):($(this).addClass("button-code-active"),$(this).parent().find(".button-code").css("border-bottom","1px solid #bdc3c7"),$(this).parent().find(".button-code").slideDown("fast"),$(this).find(".icon-expand-code").css("background-image","url(img/icon-contract.png)"))})},setupClipboardCopy:function(e){$(e).on("mouseover",function(){$(this).off("mouseover"),$(this).find("[data-clipboard-target]").each(function(){var e=$($(this).attr("data-clipboard-target"));$(this).zclip({path:"/theme/flatui/js/lib/ZeroClipboard.swf",copy:$.trim($(e).text())})})})}}}(),ProductPage=function(){return{setup:function(){$(".dropdown-toggle").dropdown(),$(".scroll-pane").jScrollPane({mouseWheelSpeed:30,animateScroll:!0}),$(".love-it").on("click",function(){this_img_src=$(this).find("img").attr("src"),$(this).hasClass("no-login")||"/theme/flatui/img/icon-like-color.png"==this_img_src||$(this).prev(".share-it").trigger("click")}),$(".payment-options").find(".options").find("span.option").on("click",function(){var e=$(this).attr("title"),t=$(".payment-options").find("input[type=\"number\"]");t.attr("value",e).val(e),t.focus(),$(".options").find(".selected").removeClass("selected"),$(this).addClass("selected")})},setupPlingButton:function(){$("#pling-amount").on("focus",function(){$("#pling-amount").popover("destroy")}),$("#pling-start").on("click",function(e){return(validateElement=$("#pling-amount"),validateValue=validateElement.val(),""==validateValue||isNaN(parseFloat(validateValue))||!isFinite(validateValue))?(e.preventDefault(),$("#pling-amount").popover({placement:"bottom",html:"true",content:"
Donation must be a numeric value.
"}).popover("show"),!1):(minValue=validateElement.attr("min"),parseFloat(validateValue)\xD7
Donation must be equal or greater than "+minValue+".
"}).popover("show"),!1):(maxValue=validateElement.attr("max"),parseFloat(validateValue)>parseFloat(maxValue))?(e.preventDefault(),$("#pling-amount").popover({placement:"bottom",html:"true",content:"
Donation must be smaller or equal than "+maxValue+".
"}).popover("show"),!1):void 0})}}}(),SlideShowRender=function(){return{setup:function(){$("#slideshow-container").find("img:first").addClass("active"),$("#slideshow-container").find("#navigation").find("a:first").addClass("active")}}}(),ProductSlideShow=function(){return{setup:function(){$("#slideshow-container").find("#arrows").find("a").on("click",function(){var e=$(this).attr("id"),t=$("#slideshow-container #slides"),a=t.find("img.active"),i=a.attr("rel"),o=$("#slideshow-container").find("#navigation").find("a.active");if("prev"==e){var r=parseInt(i)-parseInt(1),s=$("#slideshow-container").find("img[rel=\""+r+"\"]"),n=$("#slideshow-container").find("#navigation").find("a[rel=\""+r+"\"]");if(1==!s.size())var s=t.find("img:last"),n=$("#slideshow-container").find("#navigation").find("a:last")}else if("next"==e){var l=parseInt(i)+parseInt(1),s=$("#slideshow-container").find("img[rel=\""+l+"\"]"),n=$("#slideshow-container").find("#navigation").find("a[rel=\""+l+"\"]");if(1==!s.size())var s=t.find("img:first"),n=$("#slideshow-container").find("#navigation").find("a:first")}a.removeClass("active"),o.removeClass("active"),s.addClass("active"),n.addClass("active")}),$("#slideshow-container").find("#navigation").find("a").on("click",function(){var e=$(this).attr("rel"),t=$("#slideshow-container").find("img[rel=\""+e+"\"]");$("#slideshow-container").find("img.active").removeClass("active"),t.addClass("active"),$("#slideshow-container").find("#navigation").find("a.active").removeClass("active"),$(this).addClass("active")})}}}(),SlideShow=function(){return{setup:function(){slideShowInterval=setTimeout(function(){var e=$("#slideshow-container").find("img.active"),t=e.attr("rel"),a=parseInt(t)+parseInt(1),i=$("#slideshow-container").find("img[rel=\""+a+"\"]"),o=$("#slideshow-container").find("#navigation").find("a.active");e.removeClass("active"),o.removeClass("active"),1==i.size()?(i.addClass("active"),$("#slideshow-container").find("#navigation").find("a[rel=\""+a+"\"]").addClass("active")):($("#slideshow-container").find("img:first").addClass("active"),$("#slideshow-container").find("#navigation").find("a:first").addClass("active"))},4e3)}}}(),Popuppanel=function(){return{setup:function(){$("body").on("click","a.popuppanel",function(e){if("_blank"===$(this).attr("target"))console.log("dont prevent default");else{e.preventDefault();var t=$(this).attr("href");$.fancybox({hideOnContentClick:!0,autoScale:!0,cyclic:"true",transitionIn:"elastic",transitionOut:"elastic",type:"iframe",scrolling:"auto",helpers:{overlay:{locked:!1}},autoSize:!0,href:t,type:"ajax"})}})}}}(),PlingsRedirect=function(){return{setup:function(){window.location.hash?($link=$(window.location.hash),$link.trigger("click")):document.location.hash&&($link=$(document.location.hash),$link.trigger("click"))}}}(),ShowPopups=function(){return{setup:function(){window.location.hash&&(alert("Hash"),$("a[href=\""+document.location.hash+"\"]").trigger("click")),document.location.hash&&(alert("Hash"),$("a[href=\""+document.location.hash+"\"]").trigger("click"))}}}();$("body").on("mouseenter",".supporter-thumbnail",function(){$(this).popover("show")}),$("body").on("mouseleave",".supporter-thumbnail",function(){$(this).popover("hide")});var Partials=function(){return{setup:function(){$("body").on("click","a.partial",function(e){e.preventDefault();var t=this.href,a=$(this).attr("data-target"),i=$(this).data("toggle"),o=$(this).attr("data-fragment");return $(a).load(t+" "+o,function(e,t,o){if("error"==t)if(401!=o.status)$(a).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.");else if(e){var r=jQuery.parseJSON(e),s=r.login_url;window.location=s?s:"/login"}i&&$(i).modal("show")}),!1})}}}(),Opendownloadfile=function(){return{setup:function(){$("body").on("click","a.opendownloadfile",function(e){e.preventDefault();var t=$(this).attr("data-file_id"),a=$(this).attr("data-file_type"),i=$(this).attr("data-file_name"),o=$(this).attr("data-file_size"),r=$(this).attr("data-project_id"),s=$(this).attr("data-link_type"),n=$(this).attr("data-is-external-link"),l=$(this).attr("data-has_torrent"),d=null,p="450";return"true"==n&&(d=$(this).attr("data-external_link"),p="500"),$.fancybox({hideOnContentClick:!0,autoScale:!1,scrolling:"no",cyclic:"true",transitionIn:"elastic",transitionOut:"elastic",type:"iframe",width:"600",height:p,iframe:{scrolling:"no"},fitToView:!1,autoSize:!1,id:"opendownloadfilepopup",helpers:{overlay:{locked:!1}},href:"/dl?file_id="+t+"&file_type="+a+"&file_name="+i+"&file_size="+o+"&has_torrent="+l+"&project_id="+r+"&link_type="+s+"&is_external="+n+"&external_link="+d}),!1})}}}(),PartialsButton=function(){return{setup:function(){$("body").on("click","Button.partialbutton",function(e){e.preventDefault();var t=$(this).attr("data-href"),a=$(this).attr("data-target"),i=$(this).data("toggle"),o=$(this).attr("data-fragment"),r=$("");return $(a).append(r),$(a).load(t+" "+o,function(e,t,o){if("error"==t)if(401!=o.status)$(a).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.");else if(e){var r=jQuery.parseJSON(e),s=r.login_url;window.location=s?s:"/login"}i&&$(i).modal("show")}),!1})}}}(),PartialsButtonHeartDetail=function(){return{setup:function(){$("body").on("click",".partialbuttonfollowproject",function(e){e.preventDefault();var t=$(this).attr("data-href"),a=$(this).attr("data-target"),i=$(this).attr("data-auth"),o=$(this).data("toggle"),r=$(this).attr("data-fragment");if(!i)return void $("#like-product-modal").modal("show");var s=$("#like-product-modal").find("#loginuser").val(),n=$("#like-product-modal").find("#productcreator").val();if(s==n)return $("#like-product-modal").find("#votelabel").text("Project owner not allowed"),$("#like-product-modal").find(".modal-body").empty(),void $("#like-product-modal").modal("show");var l=$("");return $(a).prepend(l),$.ajax({url:t,cache:!1}).done(function(e){$(a).find(".spinning").remove(),"error"==e.status?$(a).html(e.msg):"delete"==e.action?($(a).find(".plingtext").html(e.cnt),$(a).find(".plingtext").addClass("heartnumberpurple"),$(a).find(".plingheart").removeClass("heartproject").addClass("heartgrey"),$(a).find(".plingheart").removeClass("fa-heart").addClass("fa-heart-o")):($(a).find(".plingtext").html(e.cnt),$(a).find(".plingtext").removeClass("heartnumberpurple"),$(a).find(".plingheart").removeClass("heartgrey").addClass("heartproject"),$(a).find(".plingheart").removeClass("fa-heart-o").addClass("fa-heart"))}),!1})}}}(),PartialsButtonPlingProject=function(){return{setup:function(){$("#plingbtn").hover(function(){$(this).attr("src","/images/system/pling-btn-hover.png")},function(){$(this).attr("src",$(this).attr("data-src"))}),$("body").on("click",".partialbuttonplingproject",function(e){e.preventDefault();var t=$(this).attr("data-href"),a=$(this).attr("data-target"),i=$(this).attr("data-auth"),o=$(this).attr("data-issupporter"),r=$(this).data("toggle"),s=$(this).attr("data-fragment");if(!i)return void $("#like-product-modal").modal("show");var n=$("#like-product-modal").find("#loginuser").val(),l=$("#like-product-modal").find("#productcreator").val();return n==l?($("#like-product-modal").find("#votelabel").text("Project owner not allowed"),$("#like-product-modal").find(".modal-body").empty(),void $("#like-product-modal").modal("show")):o?($(a).find(".plingnum").html(""),$.ajax({url:t,cache:!1}).done(function(e){"error"==e.status?$(a).html(e.msg):"delete"==e.action?(0==e.cnt?$(a).find(".plingnum").html("Pling me"):$(a).find(".plingnum").html(e.cnt+" Plings"),$(a).find("#plingbtn").attr("src","/images/system/pling-btn-normal.png"),$(a).find("#plingbtn").attr("data-src","/images/system/pling-btn-normal.png")):($(a).find(".plingnum").html(e.cnt+" Plings"),$(a).find("#plingbtn").attr("src","/images/system/pling-btn-active.png"),$(a).find("#plingbtn").attr("data-src","/images/system/pling-btn-active.png"))}),!1):($("#like-product-modal").find("#votelabel").html("
To pling a product and help the artist please consider becoming a supporter. Thanks!

Become a supporter
"),void $("#like-product-modal").modal("show"))})}}}(),PartialsReview=function(){return{setup:function(){$("body").on("click","a.partialreview",function(e){e.preventDefault();var t=this.href,a=$(this).attr("data-target"),i=$(this).data("toggle"),o=$(this).attr("data-fragment"),r=$("#review-product-modal").find("#loginuser").val(),s=$("#review-product-modal").find("#productcreator").val();if(r==s)return $("#review-product-modal").find("#votelabel").text("Project owner not allowed"),$("#review-product-modal").find(".modal-body").empty(),void $("#review-product-modal").modal("show");var n=$("#review-product-modal").find("#userrate").val();return $(this).hasClass("voteup")?1==n?($("#review-product-modal").find("#votelabel").empty().append(" is given already with comment:"),$("#review-product-modal").find("#commenttext").val($("#review-product-modal").find("#otxt").val()),$("#review-product-modal").find(":submit").text("Remove Rating")):($("#review-product-modal").find("input#voteup").val(1),$("#review-product-modal").find("#votelabel").empty().append(" Add Comment (min. 1 char):"),$("#review-product-modal").find("#commenttext").val("+"),$("#review-product-modal").find(":submit").text("Rate Now"),$("#review-product-modal").find("#commenttext").removeAttr("disabled"),$("#review-product-modal").find(":submit").css("display","block").removeAttr("disabled")):0==n?($("#review-product-modal").find("#votelabel").empty().append(" is given already with comment: "),$("#review-product-modal").find("#commenttext").val($("#review-product-modal").find("#otxt").val()),$("#review-product-modal").find(":submit").text("Remove Rating")):($("#review-product-modal").find("input#voteup").val(2),$("#review-product-modal").find("#votelabel").empty().append(" Add Comment (min. 5 char) Please explain the reason for downvote to help the creator to make it better "),$("#review-product-modal").find("#commenttext").val("-"),$("#review-product-modal").find("#commenttext").removeAttr("disabled"),$("#review-product-modal").find(":submit").removeAttr("disabled").css("display","block"),$("#review-product-modal").find(":submit").text("Rate Now")),$("#review-product-modal").modal("show"),$("#review-product-modal").hasClass("noid")&&setTimeout(function(){$("#review-product-modal").modal("hide")},2e3),!1})}}}(),PartialsReviewDownloadHistory=function(){return{setup:function(){$("body").on("click","button.partialReviewDownloadHistory",function(e){e.preventDefault();var t=$(this).attr("data-userrate");return $("#review-product-modal").find("#commenttext").val($(this).attr("data-comment")),$("#review-product-modal").find("#form_p").val($(this).attr("data-project")),$(this).hasClass("voteup")?1==t?($("#review-product-modal").find("#votelabel").empty().append(" is given already with comment:"),$("#review-product-modal").find(":submit").attr("disabled","disabled").css("display","none"),$("#review-product-modal").find("#commenttext").attr("disabled","disabled")):($("#review-product-modal").find("input#voteup").val(1),$("#review-product-modal").find("#votelabel").empty().append(" Add Comment (min. 1 char):"),$("#review-product-modal").find("#commenttext").val("+"),$("#review-product-modal").find("#commenttext").removeAttr("disabled"),$("#review-product-modal").find(":submit").css("display","block").removeAttr("disabled")):0==t?($("#review-product-modal").find("#votelabel").empty().append(" is given already with comment: "),$("#review-product-modal").find("#commenttext").attr("disabled","disabled"),$("#review-product-modal").find(":submit").attr("disabled","disabled").css("display","none")):($("#review-product-modal").find("input#voteup").val(2),$("#review-product-modal").find("#votelabel").empty().append(" Add Comment (min. 5 chars): "),$("#review-product-modal").find("#commenttext").val("-"),$("#review-product-modal").find("#commenttext").removeAttr("disabled"),$("#review-product-modal").find(":submit").removeAttr("disabled").css("display","block")),$("#review-product-modal").modal("show"),$("#review-product-modal").hasClass("noid")&&setTimeout(function(){$("#review-product-modal").modal("hide")},2e3),!1})}}}(),CreateScoreRatingPopup=function(){return{setup:function(){var e,t=0;$("select.rating-select").focus(function(){e=$(this),t=$(this).val()}).change(function(){var e=$(this).find("option:selected"),t=e.val(),a=e.text(),i=$(this).attr("data-userrate"),o=$(this).attr("data-comment"),r=$(this).attr("data-creator"),s=$("#score-product-modal").find("#loginuser").val();return s?s==r?($("#score-product-modal").find("#votelabel").text("Project owner not allowed"),$("#score-product-modal").find(".modal-body").empty(),$("#score-product-modal").find("#modal-btn-onsubmit").remove(),void $("#score-product-modal").modal("show")):void(-1==t?$("#score-product-modal").find("#votelabel").empty().append("Remove Rating "):5>=t?($("#score-product-modal").find("#votelabel").empty().append("Add a review to your rating \""+a+"\" (min. 5 chars) Please explain the reason for downvote to help the creator to make it better "),$("#score-product-modal").find("#voteup").val(2)):($("#score-product-modal").find("#votelabel").empty().append("Add a review to your rating \""+a+"\" (min. 1 char):"),$("#score-product-modal").find("#voteup").val(1)),$("#score-product-modal").find("#form_p").val($(this).attr("data-project")),$("#score-product-modal").find(":submit").css("display","block").removeAttr("disabled"),$("#score-product-modal").find("#commenttext").removeAttr("disabled"),1<=t&&3>=t?$("#score-product-modal").find("#commenttext").val(""):$("#score-product-modal").find("#commenttext").val(a),$("#score-product-modal").find("#userscorevalue").val(t),"-1"==t?$("#score-product-modal").find(":submit").text("Remove Rating"):$("#score-product-modal").find(":submit").text("Rate Now"),$("#score-product-modal").modal("show")):void $("#score-product-modal").modal("show")}),$("#modal-btn-cancel").on("click",function(){$(e).find("option[value="+t+"]").prop("selected",!0),$("#score-product-modal").modal("hide")});var a=!1;$("#modal-btn-onsubmit").on("click",function(){a=!0}),$("#score-product-modal").on("hidden.bs.modal",function(){a||$(e).find("option[value="+t+"]").prop("selected",!0)})}}}(),PartialForms=function(){return{setup:function(){$("body").on("submit","form.partial",function(e){e.preventDefault(),e.stopImmediatePropagation(),$(this).find(":submit").attr("disabled","disabled"),$(this).find(":submit").css("white-space","normal");var t=$("");$(this).find(":submit").append(t);var a=$(this).attr("data-target"),i=$(this).attr("data-trigger");return console.log(this),jQuery.ajax({data:$(this).serialize(),url:this.action,type:this.method,error:function(){return $(a).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
"),!1},success:function(e){return $(a).empty().html(e),$(a).find(i).trigger("click"),!1}}),!1})}}}(),PartialJsonClone=function(){return{setup:function(){$("body").on("submit","form.partialjsonclone",function(e){e.preventDefault(),e.stopImmediatePropagation();var t=$(this).attr("data-target"),a=$(this).attr("data-trigger"),i=$(this).attr("data-projectid");return jQuery.ajax({data:$(this).serialize(),url:this.action,type:this.method,dataType:"json",error:function(){$(t).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
")},success:function(e){$("form#product-report-clone").find("#clonePId").val(""),$("form#product-report-clone").find("#report-text").val(""),$("#report-product-clone-"+i).modal("hide");var t=$("#generic-dialog");t.find(".modal-header-text").empty(),t.find(".modal-body").empty().append(e.message),setTimeout(function(){t.modal("show")},900)}}),!1})}}}(),PartialJson=function(){return{setup:function(){$("body").on("submit","form.partialjson",function(e){e.preventDefault(),e.stopImmediatePropagation();var t=$(this).attr("data-target"),a=$(this).attr("data-trigger");return jQuery.ajax({data:$(this).serialize(),url:this.action,type:this.method,dataType:"json",error:function(){$(t).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
")},success:function(e){return e.redirect?void(window.location=e.redirect):void(t&&$(t).empty().html(e.message),a&&$(t).find(a).trigger("click"))}}),!1})}}}(),PartialJsonFraud=function(){return{setup:function(){$("body").on("submit","form.partialjsonfraud",function(e){e.preventDefault(),e.stopImmediatePropagation();var t=$(this).attr("data-target"),a=$(this).attr("data-trigger"),i=$("form.partialjsonfraud").find("#report-text").val();return 5>i.length?($("form.partialjsonfraud").find("p.warning").remove(),$("form.partialjsonfraud").find("#report-text").parent().append("

at least 5 chars

"),!1):(jQuery.ajax({data:$(this).serialize(),url:this.action,type:this.method,dataType:"json",error:function(){$(t).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
")},success:function(e){return e.redirect?void(window.location=e.redirect):void(t&&$(t).empty().html(e.message),a&&$(t).find(a).trigger("click"))}}),!1)})}}}(),PartialPayPal=function(){return{setup:function(){this.initPayPalForm(),this.initPayPalFee()},initPayPalForm:function(){$("body").on("submit","form.partialpaypal",function(e){e.preventDefault(),e.stopImmediatePropagation();var t=$(this).attr("data-target"),a=$(this).attr("data-trigger");return jQuery.ajax({data:$(this).serialize(),url:this.action,type:this.method,error:function(e){$("#modal-dialog").modal("hide");var t=$("
");t.html($(e.responseText).filter(".page-container").children()),t.append(""),setTimeout(function(){t.modal("show")},900)},success:function(e){$(t).empty().html(e),$(t).find(a).trigger("click"),$("#modal-dialog").modal("hide")}}),!1})},initPayPalFee:function(){$("body").on("change","#amount_plings",function(){PartialPayPal.changeFee()})},changeFee:function(){var t=document.getElementById("amount_plings"),e=parseFloat(t.value),a=this.round(.05*e,2),i=.03*(a+e+.3)+.3;i=this.round(i,2);var o=e+a+i;document.getElementById("pling_fee").value=this.round(a,2).toFixed(2),document.getElementById("paypal_fee").value=this.round(i,2).toFixed(2),document.getElementById("sum").value=this.round(o,2)},round:function(e,t){var i=Math.pow(10,t);return Math.round(e*i)/i}}}(),PartialCommentReviewForm=function(){return{setup:function(){this.initForm()},initForm:function(){$("body").on("submit","form.product-add-comment-review",function(e){e.preventDefault(),e.stopImmediatePropagation();var t=$.trim($("#commenttext").val()),a=$("#voteup").val();if(2==a&&5>t.length)return void(0==$("#review-product-modal").find("#votelabel").find(".warning").length&&$("#review-product-modal").find("#votelabel").append("
Please give a comment, thanks!"));if(1>t.length)return void(0==$("#review-product-modal").find("#votelabel").find(".warning").length&&$("#review-product-modal").find("#votelabel").append("
Please give a comment, thanks!"));$(this).find(":submit").attr("disabled","disabled"),$(this).find(":submit").css("white-space","normal");var i=$("");return $(this).find(":submit").append(i),jQuery.ajax({data:$(this).serialize(),url:this.action,type:this.method,error:function(){$("#review-product-modal").modal("hide");var e=$("#generic-dialog");e.modal("hide"),e.find(".modal-header-text").empty().append("Please try later."),e.find(".modal-body").empty().append("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
"),setTimeout(function(){e.modal("show")},900)},success:function(){$("#review-product-modal").modal("hide"),location.reload()}}),!1})}}}(),PartialCommentReviewFormNew=function(){return{setup:function(){this.initForm()},initForm:function(){$("body").on("submit","form.product-add-comment-review-new",function(e){e.preventDefault(),e.stopImmediatePropagation();var t=$.trim($("#score-product-modal").find("#commenttext").val()),a=$("#score-product-modal").find("#voteup").val();if(2==a&&5>t.length)return void(0==$("#score-product-modal").find("#votelabel").find(".warning").length&&$("#score-product-modal").find("#votelabel").append("
Please give a comment, thanks!"));if(1>t.length)return void(0==$("#score-product-modal").find("#votelabel").find(".warning").length&&$("#score-product-modal").find("#votelabel").append("
Please give a comment, thanks!"));$(this).find(":submit").attr("disabled","disabled"),$(this).find(":submit").css("white-space","normal");var i=$("");return $(this).find(":submit").append(i),jQuery.ajax({data:$(this).serialize(),url:this.action,type:this.method,error:function(){$("#score-product-modal").modal("hide");var e=$("#generic-dialog");e.modal("hide"),e.find(".modal-header-text").empty().append("Please try later."),e.find(".modal-body").empty().append("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
"),setTimeout(function(){e.modal("show")},900)},success:function(){$("#score-product-modal").modal("hide"),location.reload()}}),!1})}}}(),PartialFormsAjax=function(){return{setup:function(){var t=$("form.partialajax"),a=t.attr("data-target"),i=t.attr("data-trigger");$(t).find(":submit").on("click",function(a){a.preventDefault(),$(t).find(":submit").attr("disabled","disabled"),$(t).find(":submit").css("white-space","normal");var e=$("");$(t).find(":submit").append(e),$(t).submit()}),t.ajaxForm({error:function(){$(a).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
")},success:function(e){$(a).empty().html(e),$(a).find(i).trigger("click")}})}}}(),AjaxFormWithProgress=function(){return{setup:function(e){var t=$(e),a=t.attr("data-target"),i=t.attr("data-trigger"),o=t.find(".progress-bar"),r=t.find(".progress-percent");$(t).find(":submit").on("click",function(a){a.preventDefault(),$(t).find(":submit").attr("disabled","disabled"),$(t).find(":submit").css("white-space","normal");var e=$("");$(t).find(":submit").append(e),$(t).submit()}),t.ajaxForm({beforeSend:function(){o.parent().removeClass("hidden"),o.width("0%"),r.html("0%")},uploadProgress:function(e,t,a,i){var s=i+"%";o.width(s),r.html(s)},error:function(){$(a).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
")},success:function(e){o.width("100%"),r.html("100%"),$(a).empty().html(e),$(a).find(i).trigger("click")}})}}}(),PartialFormsAjaxMemberBg=function(){return{setup:function(){var t=$("form.partialajaxbg"),a=t.attr("data-target"),i=t.attr("data-trigger");$(t).find(":submit").on("click",function(a){a.preventDefault(),$(t).find(":submit").attr("disabled","disabled"),$(t).find(":submit").css("white-space","normal");var e=$("");$(t).find(":submit").append(e),$(t).submit()}),t.ajaxForm({error:function(){$(a).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.
")},success:function(e){$(a).empty().html(e),$(a).find(i).trigger("click")}})}}}(),AjaxForm=function(){return{setup:function(e,t){var a=$(t);$("body").on("submit",e,function(e){return e.preventDefault(),e.stopImmediatePropagation(),$(this).find("button").attr("disabled","disabled"),$(this).find(".glyphicon.glyphicon-send").removeClass("glyphicon-send").addClass("glyphicon-refresh spinning"),jQuery.ajax({data:$(this).serialize(),url:this.action,type:this.method,dataType:"json",error:function(e){var t=JSON&&JSON.parse(e.responseText)||$.parseJSON(e.responseText),a=$("#generic-dialog");a.modal("hide"),a.find(".modal-header-text").empty().append(t.title),a.find(".modal-body").empty().append(t.message),setTimeout(function(){a.modal("show")},900)},success:function(e){"ok"==e.status&&$(a).empty().html(e.data),"error"==e.status&&(""==e.message?alert("Service is temporarily unavailable."):alert(e.message))}}),!1})}}}(),WidgetModalAjax=function(){return{setup:function(){$(".my-product-item").find("a.widget-button").on("click",function(){var e=$(this).attr("rel"),t=e.split("product")[1],a=$(".modal-body#widget-code-"+e);$.ajax({url:"/widget/config/"+t,type:"html",success:function(e){a.prepend(e),angular.bootstrap(a,["widgetApp"])}})})}}}(),LoginContainer=function(){return{update:function(){Date.now||(Date.now=function(){return new Date().getTime()});var e=0|Date.now()/1e3;$("#login_container").load("/authorization/htmllogin?"+e,function(){})}}}(),RssNews=function(){return{setup:function(){$.getJSON("https://blog.opendesktop.org/?json=1&callback=?",function(e){var t="";$.each(e.posts,function(e,a){if(3<=e)return!1;var i=moment(a.date);t+="
"+a.title+"
"+i.format("MMM DD YYYY")+""+a.comments.length+" Comment"+(1
"}),$("#rss-feeds").html(t)})}}}(),BlogJson=function(){return{setup:function(){$.ajax("/json/forum").then(function(e){var t=e.topic_list.topics,a="",o=3;t.sort(function(e,t){return new Date(t.last_posted_at)-new Date(e.last_posted_at)}),$.each(t,function(e,i){if(!i.pinned){var s=i.timeago,n="Reply",l=i.posts_count-1;n=0==l?"Replies":1==l?"Reply":"Replies",a+="
"+i.title+"
"+s+""+l+" "+n+"
",o--}return 0!=o&&void 0}),$("#blogJson").html(a)})}}}(),GitlabNewProjectsJson=function(){return{setup:function(e){$.ajax("/json/gitlabnewprojects").then(function(t){var a="";$.each(t,function(t,i){var o=i.timeago;a+=""}),$("#lastgitprojects").html(a)})}}}();function showGitUserAvatar(e,t,a){$.ajax(e+"/api/v4/users?username="+t).then(function(e){$.each(e,function(e,i){$img=$("#avatar_"+t+"_"+a),$img.attr("src",i.avatar_url)})})}var ProductDetailCarousel=function(){return{setup:function(){$(".carousel-inner img").each(function(){$(this).on("click",function(){$("#product-main-img-container").hasClass("imgfull")?$("#product-main-img-container").prependTo($("#product-main")):$("#product-main-img-container").prependTo($("#product-page-content")),$("#product-main-img-container").toggleClass("imgfull"),$("#product-main-img-container").toggleClass("imgsmall")})})}}}(),AppimagequestionOnClick=function(){return{setup:function(){$("body").on("click","i.appimagequestion",function(){var e=$("#generic-dialog");e.modal("show"),e.find(".modal-header-text").empty().append("AppImage Info"),e.find(".modal-body").empty().append("")})}}}(),ProductDetailBtnGetItClick=function(){return{setup:function(e){$("body").on("click","button#project_btn_download",function(){$.fancybox({hideOnContentClick:!0,autoScale:!0,cyclic:"true",transitionIn:"elastic",transitionOut:"elastic",type:"ajax",helpers:{overlay:{locked:!1}},autoSize:!0,href:"/p/"+e+"/ppload"})})}}}(),GhnsExcludedClick=function(){return{setup:function(e){$("body").on("click","#ghns_excluded-this-checkbox",function(t){t.stopPropagation();var a=1,i="",o="";this.checked?(a=1,i="Please specify why this product should be excluded (min 5 chars) :",o=" ghns exclude"):(a=0,i="Please specify why this product should be included (min 5 chars) :",o=" ghns include");var r=$("#generic-dialog");return r.modal("show"),r.find(".modal-header-text").empty().append("GHNS "),r.find(".modal-body").empty().append(i+"

"),$("body").on("click","#btn-ghns-excluded",function(){var e=$("#ghns-excluded-text").val();if(5>e.length)return alert("min 5 chars"),!1;var t=$(this).attr("data-projectid"),a=$(this).attr("data-status");$.ajax({url:"/backend/project/doghnsexclude",method:"POST",data:{project_id:t,ghns_excluded:a,msg:e},success:function(){var e=$("#generic-dialog");0==a?(e.find(".modal-body").empty().append("Project is successfully included into GHNS"),$("#ghns_excluded-this-checkbox").prop("checked",!1)):(e.find(".modal-body").empty().append("Project is successfully excluded into GHNS"),$("#ghns_excluded-this-checkbox").prop("checked",!0)),setTimeout(function(){e.modal("hide")},1e3)},error:function(){alert("Service is temporarily unavailable.")}})}),!1})}}}(),AboutMeMyProjectsPaging=function(){return{setup:function(){$(window).scroll(function(){var e=$("footer").offset().top,t=$(window).scrollTop()+$(window).height();if(300>e-t){if(!$("button#btnshowmoreproducts").length)return;let e=$("button#btnshowmoreproducts").attr("data-page");$("button#btnshowmoreproducts").remove(),$url=window.location.href,target=$(".about-me-details").find("li.active").find("a").attr("href"),"#user-original-products"==target&&($url+="showoriginal");let t=$("

").append("").load($url,{projectpage:e},function(e,t,a){if("error"==t)if(401!=a.status)$(target).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.");else if(e){var i=jQuery.parseJSON(e),o=i.login_url;window.location=o?o:"/login"}});$(target).append(t)}})}}}(),AboutMeMyProjectsPagingButton=function(){return{setup:function(){$("body").on("click","button#btnshowmoreproducts",function(){let e=$(this).attr("data-page");$(this).remove(),$url=window.location.href,target=$(".about-me-details").find("li.active").find("a").attr("href"),"#user-original-products"==target&&($url+="showoriginal");let t=$("
").append("").load($url,{projectpage:e},function(e,t,a){if("error"==t)if(401!=a.status)$(target).empty().html("Service is temporarily unavailable. Our engineers are working quickly to resolve this issue.
Find out why you may have encountered this error.");else if(e){var i=jQuery.parseJSON(e),o=i.login_url;window.location=o?o:"/login"}});$(target).append(t)})}}}(),ProductDetailCommentTooltip=function(){return{setup:function(){TooltipUser.setup("tooltipuser","right")}}}();function generateTooltipster(e,t){$(e).each(function(){$(this).tooltipster({side:t,theme:["tooltipster-light","tooltipster-light-customized"],contentCloning:!0,contentAsHTML:!0,interactive:!0,functionBefore:function(e,t){var a=$(t.origin),i=a.attr("data-user");!0!==a.data("loaded")&&$.get("/member/"+i+"/tooltip/",function(t){var i=t.data,o="
"+i.username+" "+i.countrycity+"
"+i.cntProjects+" products
"+i.totalComments+" comments
Likes "+i.cntLikesGave+" products
Got "+i.cntLikesGot+" Likes
Last time active : "+i.lastactive_at+"
Member since : "+i.created_at+"
";o+="
",e.content(o),a.data("loaded",!0)})}})})}var TooltipUser=function(){return{setup:function(e,t){$("."+e).tooltipster({side:t,theme:["tooltipster-light","tooltipster-light-customized"],contentCloning:!0,contentAsHTML:!0,interactive:!0,functionBefore:function(e,t){var a=$(t.origin),i=a.attr("data-user");!0!==a.data("loaded")&&$.get("/member/"+i+"/tooltip/",function(t){var i=t.data,o="
"+i.username+" "+i.countrycity+"
"+i.cntProjects+" products
"+i.totalComments+" comments
Likes "+i.cntLikesGave+" products
Got "+i.cntLikesGot+" Likes
Last time active : "+i.lastactive_at+"
Member since : "+i.created_at+"
";o+="
",e.content(o),a.data("loaded",!0)})}})}}}();function generateTooltipUserPlings(e,t){$(e).each(function(){$(this).tooltipster({side:t,theme:["tooltipster-light","tooltipster-light-customized"],contentCloning:!0,contentAsHTML:!0,interactive:!0,functionBefore:function(e,t){var a=$(t.origin),i=a.attr("data-user");!0!==a.data("loaded")&&$.get("/plings/tooltip/id/"+i,function(t){var i="
";$.each(t.data,function(e,t){return!(10t.profile_image_url.indexOf("http")&&(t.profile_image_url="https://cn.opendesktop.org/cache/40x40-2/img/"+t.profile_image_url),0"+t.username+"
")}),i+="",e.content(i),a.data("loaded",!0)})}})})}var TooltipUserPlings=function(){return{setup:function(e,t){$("."+e).tooltipster({side:t,theme:["tooltipster-light","tooltipster-light-customized"],contentCloning:!0,contentAsHTML:!0,interactive:!0,functionBefore:function(e,t){var a=$(t.origin),i=a.attr("data-user");!0!==a.data("loaded")&&$.get("/plings/tooltip/id/"+i,function(t){var i="
";$.each(t.data,function(e,t){return!(10t.profile_image_url.indexOf("http")&&(t.profile_image_url="https://cn.opendesktop.org/cache/40x40-2/img/"+t.profile_image_url),0"+t.username+"
")}),i+="",e.content(i),a.data("loaded",!0)})}})}}}(),AboutMePage=function(){return{setup:function(e){var a=$(document).prop("title");$(document).prop("title",e+"'s Profile "+a)}}}(),InitActiveHashTab=function(){return{setup:function(){var e=document.location.hash;$("a[href=\""+e+"\"]")&&$("a[href=\""+e+"\"]").tab("show")}}}(),AboutmeTab=function(){return{setup:function(){$("body").on("click","a.aboutmetab",function(e){e.preventDefault();var t=$(this).attr("href"),a=$(this).attr("data-href");0==$(t).find(".product").length&&$(t).append("").load(a,function(){})})}}}(),CommunityTabToplistMemberScrollPaging=function(){return{setup:function(e,t){$(window).scroll(function(){var a=$("footer").offset().top,i=$(window).scrollTop()+$(window).height();if(300>a-i){if(!$("button#toplistmemberscrollshowmore").length)return;var o=$("button#toplistmemberscrollshowmore").attr("data-page");$("button#toplistmemberscrollshowmore").remove();var r=$("
");$(e).find(".product-list").append(r),$(r).load(t+"/nopage/1/page/"+o,function(){generateTooltipster($(r).find(".tooltipuser"),"right")})}})}}}(),CommunityTab=function(){return{setup:function(){$("body").on("click","a.communitytab",function(e){e.preventDefault();var t=$(this).attr("href"),a=$(this).attr("data-href");0==$(t).find(".list").find(".user").length&&$(t).find(".list").append("").load(a,function(){generateTooltipster($(t).find(".tooltipuser"),"right"),0<$(t).find(".tooltipuserplings").length&&generateTooltipUserPlings($(t).find(".tooltipuserplings"),"right"),"#toplistMemberPanel"==t&&CommunityTabToplistMemberScrollPaging.setup(t,a);let e=$(t).find(".opendesktopwidgetpager span");e.each(function(){$(this).on("click",function(){$(this).parent().addClass("active").siblings().removeClass("active");var e=a+"/nopage/1/page/"+$(this).html();$(t).find(".product-list").html(""),$(t).find(".product-list").load(e,function(){generateTooltipster($(t).find(".tooltipuser"),"right"),0<$(t).find(".tooltipuserplings").length&&generateTooltipUserPlings($(t).find(".tooltipuserplings"),"right")})})})})});var e=document.location.hash;0<$("a[href=\""+e+"\"]").length?($("a[href=\""+e+"\"]").tab("show"),$("a[href=\""+e+"\"]").trigger("click")):(e="#supportersPanel",$("a[href=\""+e+"\"]").trigger("click")),$("body").on("mouseenter",".product-thumbnail-startpage",function(){$(this).popover("show")}),$("body").on("mouseleave",".product-thumbnail-startpage",function(){$(this).popover("hide")})}}}(),TagingProduct=function(){return{setup:function(){$("input[name=tagsuser]").tagify({whitelist:["good","great"],autocomplete:!0}).on("remove",function(t,e){console.log("removed",e)}).on("add",function(t,e){console.log("added",e)})}}}(),TagingProductSelect2=function(){return{setup:function(){$.fn.select2.amd.require(["select2/selection/search"],function(e){e.prototype.searchRemoveChoice=function(e,t){this.trigger("unselect",{data:t}),this.$search.val(""),this.handleSearch()}},null,!0);var a=$(".taggingSelect2").select2({placeholder:"Add Tags here ...",tags:!0,tokenSeparators:[","," "],minimumInputLength:3,maximumSelectionLength:5,width:"resolve",ajax:{url:"/tag/filter",dataType:"json",type:"GET",delay:500,processResults:function(e){return{results:e.data.tags}}}});a.on("select2:select",function(t){var e=t.params.data,i=$("#tagsuserselect").attr("data-pid"),o=a.parent().find("ul.select2-selection__rendered").find("li.select2-selection__choice").length;if(5"+a.title+""}),$(".product_category").find(".topicslink").html(e)}else $(this).text("Done")})}}}(),TagingProductDetailSelect2=function(){return{setup:function(){$.fn.select2.amd.require(["select2/selection/search"],function(e){e.prototype.searchRemoveChoice=function(e,t){this.trigger("unselect",{data:t}),this.$search.val(""),this.handleSearch()}},null,!0);var e=$("#tagsuserselect").select2({placeholder:"Input tags please...",tags:!0,minimumInputLength:3,closeOnSelect:!0,maximumSelectionLength:5,tokenSeparators:[","," "],ajax:{url:"/tag/filter",dataType:"json",type:"GET",delay:500,processResults:function(e){return{results:e.data.tags}}}});e.on("select2:select",function(t){var a=t.params.data,i=$("#tagsuserselect").attr("data-pid");$.post("/tag/add",{p:i,t:a.id}).done(function(t){"error"==t.status?($("span.topic-tags-saved").css({color:"red"}).html(t.message).show().delay(2e3).fadeOut(),e.find("option[value='"+t.data.tag+"']").last().remove()):$("span.topic-tags-saved").css({color:"green"}).html(" Saved").show().delay(1e3).fadeOut()})}),e.on("select2:unselect",function(t){var e=t.params.data,a=$("#tagsuserselect").attr("data-pid");$.post("/tag/del",{p:a,t:e.id}).done(function(e){console.log(e),$("span.topic-tags-saved").css({color:"green"}).html(""+e.message).show().delay(1e3).fadeOut()})})}}}(),TagingLoopMyProducts=function(){return{setup:function(){TagingLoopMyProductsSelect2.setup(),$("body").on("click","button.topic-tags-btn",function(){if($(this).toggleClass("Done"),$(this).parent().find(".topicsuser").html(""),$(this).parent().find(".tagsuserselectpanel").toggle(),"Done"==$(this).text()){$(this).text("Manage tags");var e="",t=$(this).parent().find("li.select2-selection__choice");$.each(t,function(t,a){e=e+""+a.title+""}),$(this).parent().find(".topicsuser").html(e)}else $(this).text("Done")})}}}(),TagingLoopMyProductsSelect2=function(){return{setup:function(){$.fn.select2.amd.require(["select2/selection/search"],function(e){e.prototype.searchRemoveChoice=function(e,t){this.trigger("unselect",{data:t}),this.$search.val(""),this.handleSearch()}},null,!0);var e=$(".taggingSelect2").select2({placeholder:"Input tags please...",tags:!0,minimumInputLength:3,closeOnSelect:!0,maximumSelectionLength:5,tokenSeparators:[","," "],ajax:{url:"/tag/filter",dataType:"json",type:"GET",delay:500,processResults:function(e){return{results:e.data.tags}}}});e.on("select2:select",function(t){var a=t.params.data,i=$(this).attr("id").replace("tagsuserselect","");$.post("/tag/add",{p:i,t:a.id}).done(function(t){"error"==t.status?($("#topic-tags-saved"+i).css({color:"red"}).html(t.message).show().delay(2e3).fadeOut(),e.find("option[value='"+t.data.tag+"']").last().remove()):"existing"==t.status?$("#topic-tags-saved"+i).css({color:"red"}).html(t.message).show().delay(2e3).fadeOut():$("#topic-tags-saved"+i).css({color:"green"}).html(" Saved").show().delay(1e3).fadeOut()})}),e.on("select2:unselect",function(t){var e=t.params.data,a=$(this).attr("id").replace("tagsuserselect","");$.post("/tag/del",{p:a,t:e.id}).done(function(e){$("#topic-tags-saved"+a).css({color:"green"}).html(""+e.message).show().delay(1e3).fadeOut()})})}}}(),productRatingToggle=function(){return{setup:function(){$("#showRatingAll").on("click",function(){$("#ratings-panel").find(".spinning").show(),setTimeout(function(){$("#ratings-panel").find(".spinning").hide()},500),$(".btnRateFilter").removeClass("activeRating"),$(this).addClass("activeRating"),$(".productRating-rows").show(),$(".productRating-rows-inactive").show()}),$("#showRatingActive").on("click",function(){$("#ratings-panel").find(".spinning").show(),setTimeout(function(){$("#ratings-panel").find(".spinning").hide()},500),$(".btnRateFilter").removeClass("activeRating"),$(this).addClass("activeRating"),$(".productRating-rows").show(),$(".productRating-rows-inactive").hide()}),$("#showRatingUpvotes").on("click",function(){$("#ratings-panel").find(".spinning").show(),setTimeout(function(){$("#ratings-panel").find(".spinning").hide()},500),$(".btnRateFilter").removeClass("activeRating"),$(this).addClass("activeRating"),$(".productRating-rows").show(),$(".clsDownvotes").hide(),$(".productRating-rows-inactive").hide()}),$("#showRatingDownvotes").on("click",function(){$("#ratings-panel").find(".spinning").show(),setTimeout(function(){$("#ratings-panel").find(".spinning").hide()},500),$(".btnRateFilter").removeClass("activeRating"),$(this).addClass("activeRating"),$(".productRating-rows").show(),$(".productRating-rows-inactive").hide(),$(".clsUpvotes").hide()})}}}(),FilterBrowseOriginalFn=function(){return{setup:function(){$("body").on("click","input#filter_browse_original",function(){var e=$(this).is(":checked"),t=window.location.href;0>t.indexOf("browse")&&(t+="/browse/"),0. **/ class Local_Session_Handler_Memcache implements Zend_Session_SaveHandler_Interface { /** @var Zend_Cache_Backend_Interface $cache */ public $cache = null; private $maxlifetime = 3600; public function __construct($cacheHandler) { - $this->cache = $cacheHandler; + if ($cacheHandler instanceof Zend_Cache_Backend_Interface) { + $this->cache = $cacheHandler; + + return $this; + } + + $cacheClass = 'Zend_Cache_Backend_' . $cacheHandler['cache']['type']; + $_cache = new $cacheClass($cacheHandler); + $this->cache = $_cache; + + if (isset($cacheHandler['cache']['maxlifetime'])) { + $this->maxlifetime = (int)$cacheHandler['cache']['maxlifetime']; + } + + return $this; } public function open($save_path, $name) { return true; } public function close() { return true; } public function read($id) { if (false === ($data = $this->cache->load($id))) { return ''; } else { return $data; } } public function write($id, $sessionData) { $this->cache->save($sessionData, $id, array(), $this->maxlifetime); return true; } public function destroy($id) { $this->cache->remove($id); return true; } public function gc($notusedformemcache) { return true; } } \ No newline at end of file diff --git a/library/S3.php b/library/S3.php new file mode 100644 index 000000000..60d08ae56 --- /dev/null +++ b/library/S3.php @@ -0,0 +1,2545 @@ + $host, 'type' => $type, 'user' => $user, 'pass' => $pass); + } + + + /** + * Set the error mode to exceptions + * + * @param boolean $enabled Enable exceptions + * @return void + */ + public static function setExceptions($enabled = true) + { + self::$useExceptions = $enabled; + } + + + /** + * Set AWS time correction offset (use carefully) + * + * This can be used when an inaccurate system time is generating + * invalid request signatures. It should only be used as a last + * resort when the system time cannot be changed. + * + * @param string $offset Time offset (set to zero to use AWS server time) + * @return void + */ + public static function setTimeCorrectionOffset($offset = 0) + { + if ($offset == 0) + { + $rest = new S3Request('HEAD'); + $rest = $rest->getResponse(); + $awstime = $rest->headers['date']; + $systime = time(); + $offset = $systime > $awstime ? -($systime - $awstime) : ($awstime - $systime); + } + self::$__timeOffset = $offset; + } + + + /** + * Set signing key + * + * @param string $keyPairId AWS Key Pair ID + * @param string $signingKey Private Key + * @param boolean $isFile Load private key from file, set to false to load string + * @return boolean + */ + public static function setSigningKey($keyPairId, $signingKey, $isFile = true) + { + self::$__signingKeyPairId = $keyPairId; + if ((self::$__signingKeyResource = openssl_pkey_get_private($isFile ? + file_get_contents($signingKey) : $signingKey)) !== false) return true; + self::__triggerError('S3::setSigningKey(): Unable to open load private key: '.$signingKey, __FILE__, __LINE__); + return false; + } + + + + /** + * Free signing key from memory, MUST be called if you are using setSigningKey() + * + * @return void + */ + public static function freeSigningKey() + { + if (self::$__signingKeyResource !== false) + openssl_free_key(self::$__signingKeyResource); + } + + /** + * Set progress function + * + * @param function $func Progress function + * @return void + */ + public static function setProgressFunction($func = null) + { + self::$progressFunction = $func; + } + + + /** + * Internal error handler + * + * @internal Internal error handler + * @param string $message Error message + * @param string $file Filename + * @param integer $line Line number + * @param integer $code Error code + * @return void + */ + private static function __triggerError($message, $file, $line, $code = 0) + { + if (self::$useExceptions) + throw new S3Exception($message, $file, $line, $code); + else + trigger_error($message, E_USER_WARNING); + } + + + /** + * Get a list of buckets + * + * @param boolean $detailed Returns detailed bucket list when true + * @return array | false + */ + public static function listBuckets($detailed = false) + { + $rest = new S3Request('GET', '', '', self::$endpoint); + $rest = $rest->getResponse(); + if ($rest->error === false && $rest->code !== 200) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::listBuckets(): [%s] %s", $rest->error['code'], + $rest->error['message']), __FILE__, __LINE__); + return false; + } + $results = array(); + if (!isset($rest->body->Buckets)) return $results; + + if ($detailed) + { + if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName)) + $results['owner'] = array( + 'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->DisplayName + ); + $results['buckets'] = array(); + foreach ($rest->body->Buckets->Bucket as $b) + $results['buckets'][] = array( + 'name' => (string)$b->Name, 'time' => strtotime((string)$b->CreationDate) + ); + } else + foreach ($rest->body->Buckets->Bucket as $b) $results[] = (string)$b->Name; + + return $results; + } + + + /** + * Get contents for a bucket + * + * If maxKeys is null this method will loop through truncated result sets + * + * @param string $bucket Bucket name + * @param string $prefix Prefix + * @param string $marker Marker (last file listed) + * @param string $maxKeys Max keys (maximum number of keys to return) + * @param string $delimiter Delimiter + * @param boolean $returnCommonPrefixes Set to true to return CommonPrefixes + * @return array | false + */ + public static function getBucket($bucket, $prefix = null, $marker = null, $maxKeys = null, $delimiter = null, $returnCommonPrefixes = false) + { + $rest = new S3Request('GET', $bucket, '', self::$endpoint); + if ($maxKeys == 0) $maxKeys = null; + if ($prefix !== null && $prefix !== '') $rest->setParameter('prefix', $prefix); + if ($marker !== null && $marker !== '') $rest->setParameter('marker', $marker); + if ($maxKeys !== null && $maxKeys !== '') $rest->setParameter('max-keys', $maxKeys); + if ($delimiter !== null && $delimiter !== '') $rest->setParameter('delimiter', $delimiter); + else if (!empty(self::$defDelimiter)) $rest->setParameter('delimiter', self::$defDelimiter); + $response = $rest->getResponse(); + if ($response->error === false && $response->code !== 200) + $response->error = array('code' => $response->code, 'message' => 'Unexpected HTTP status'); + if ($response->error !== false) + { + self::__triggerError(sprintf("S3::getBucket(): [%s] %s", + $response->error['code'], $response->error['message']), __FILE__, __LINE__); + return false; + } + + $results = array(); + + $nextMarker = null; + if (isset($response->body, $response->body->Contents)) + foreach ($response->body->Contents as $c) + { + $results[(string)$c->Key] = array( + 'name' => (string)$c->Key, + 'time' => strtotime((string)$c->LastModified), + 'size' => (int)$c->Size, + 'hash' => substr((string)$c->ETag, 1, -1) + ); + $nextMarker = (string)$c->Key; + } + + if ($returnCommonPrefixes && isset($response->body, $response->body->CommonPrefixes)) + foreach ($response->body->CommonPrefixes as $c) + $results[(string)$c->Prefix] = array('prefix' => (string)$c->Prefix); + + if (isset($response->body, $response->body->IsTruncated) && + (string)$response->body->IsTruncated == 'false') return $results; + + if (isset($response->body, $response->body->NextMarker)) + $nextMarker = (string)$response->body->NextMarker; + + // Loop through truncated results if maxKeys isn't specified + if ($maxKeys == null && $nextMarker !== null && (string)$response->body->IsTruncated == 'true') + do + { + $rest = new S3Request('GET', $bucket, '', self::$endpoint); + if ($prefix !== null && $prefix !== '') $rest->setParameter('prefix', $prefix); + $rest->setParameter('marker', $nextMarker); + if ($delimiter !== null && $delimiter !== '') $rest->setParameter('delimiter', $delimiter); + + if (($response = $rest->getResponse()) == false || $response->code !== 200) break; + + if (isset($response->body, $response->body->Contents)) + foreach ($response->body->Contents as $c) + { + $results[(string)$c->Key] = array( + 'name' => (string)$c->Key, + 'time' => strtotime((string)$c->LastModified), + 'size' => (int)$c->Size, + 'hash' => substr((string)$c->ETag, 1, -1) + ); + $nextMarker = (string)$c->Key; + } + + if ($returnCommonPrefixes && isset($response->body, $response->body->CommonPrefixes)) + foreach ($response->body->CommonPrefixes as $c) + $results[(string)$c->Prefix] = array('prefix' => (string)$c->Prefix); + + if (isset($response->body, $response->body->NextMarker)) + $nextMarker = (string)$response->body->NextMarker; + + } while ($response !== false && (string)$response->body->IsTruncated == 'true'); + + return $results; + } + + + /** + * Put a bucket + * + * @param string $bucket Bucket name + * @param constant $acl ACL flag + * @param string $location Set as "EU" to create buckets hosted in Europe + * @return boolean + */ + public static function putBucket($bucket, $acl = self::ACL_PRIVATE, $location = false) + { + $rest = new S3Request('PUT', $bucket, '', self::$endpoint); + $rest->setAmzHeader('x-amz-acl', $acl); + + if ($location === false) $location = self::getRegion(); + + if ($location !== false && $location !== "us-east-1") + { + $dom = new DOMDocument; + $createBucketConfiguration = $dom->createElement('CreateBucketConfiguration'); + $locationConstraint = $dom->createElement('LocationConstraint', $location); + $createBucketConfiguration->appendChild($locationConstraint); + $dom->appendChild($createBucketConfiguration); + $rest->data = $dom->saveXML(); + $rest->size = strlen($rest->data); + $rest->setHeader('Content-Type', 'application/xml'); + } + $rest = $rest->getResponse(); + + if ($rest->error === false && $rest->code !== 200) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::putBucket({$bucket}, {$acl}, {$location}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); + return false; + } + return true; + } + + + /** + * Delete an empty bucket + * + * @param string $bucket Bucket name + * @return boolean + */ + public static function deleteBucket($bucket) + { + $rest = new S3Request('DELETE', $bucket, '', self::$endpoint); + $rest = $rest->getResponse(); + if ($rest->error === false && $rest->code !== 204) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::deleteBucket({$bucket}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); + return false; + } + return true; + } + + + /** + * Create input info array for putObject() + * + * @param string $file Input file + * @param mixed $md5sum Use MD5 hash (supply a string if you want to use your own) + * @return array | false + */ + public static function inputFile($file, $md5sum = true) + { + if (!file_exists($file) || !is_file($file) || !is_readable($file)) + { + self::__triggerError('S3::inputFile(): Unable to open input file: '.$file, __FILE__, __LINE__); + return false; + } + clearstatcache(false, $file); + return array('file' => $file, 'size' => filesize($file), 'md5sum' => $md5sum !== false ? + (is_string($md5sum) ? $md5sum : base64_encode(md5_file($file, true))) : '', 'sha256sum' => hash_file('sha256', $file)); + } + + + /** + * Create input array info for putObject() with a resource + * + * @param string $resource Input resource to read from + * @param integer $bufferSize Input byte size + * @param string $md5sum MD5 hash to send (optional) + * @return array | false + */ + public static function inputResource(&$resource, $bufferSize = false, $md5sum = '') + { + if (!is_resource($resource) || (int)$bufferSize < 0) + { + self::__triggerError('S3::inputResource(): Invalid resource or buffer size', __FILE__, __LINE__); + return false; + } + + // Try to figure out the bytesize + if ($bufferSize === false) + { + if (fseek($resource, 0, SEEK_END) < 0 || ($bufferSize = ftell($resource)) === false) + { + self::__triggerError('S3::inputResource(): Unable to obtain resource size', __FILE__, __LINE__); + return false; + } + fseek($resource, 0); + } + + $input = array('size' => $bufferSize, 'md5sum' => $md5sum); + $input['fp'] =& $resource; + return $input; + } + + + /** + * Put an object + * + * @param mixed $input Input data + * @param string $bucket Bucket name + * @param string $uri Object URI + * @param constant $acl ACL constant + * @param array $metaHeaders Array of x-amz-meta-* headers + * @param array $requestHeaders Array of request headers or content type as a string + * @param constant $storageClass Storage class constant + * @param constant $serverSideEncryption Server-side encryption + * @return boolean + */ + public static function putObject($input, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $requestHeaders = array(), $storageClass = self::STORAGE_CLASS_STANDARD, $serverSideEncryption = self::SSE_NONE) + { + if ($input === false) return false; + $rest = new S3Request('PUT', $bucket, $uri, self::$endpoint); + + if (!is_array($input)) $input = array( + 'data' => $input, 'size' => strlen($input), + 'md5sum' => base64_encode(md5($input, true)), + 'sha256sum' => hash('sha256', $input) + ); + + // Data + if (isset($input['fp'])) + $rest->fp =& $input['fp']; + elseif (isset($input['file'])) + $rest->fp = @fopen($input['file'], 'rb'); + elseif (isset($input['data'])) + $rest->data = $input['data']; + + // Content-Length (required) + if (isset($input['size']) && $input['size'] >= 0) + $rest->size = $input['size']; + else { + if (isset($input['file'])) { + clearstatcache(false, $input['file']); + $rest->size = filesize($input['file']); + } + elseif (isset($input['data'])) + $rest->size = strlen($input['data']); + } + + // Custom request headers (Content-Type, Content-Disposition, Content-Encoding) + if (is_array($requestHeaders)) + foreach ($requestHeaders as $h => $v) + strpos($h, 'x-amz-') === 0 ? $rest->setAmzHeader($h, $v) : $rest->setHeader($h, $v); + elseif (is_string($requestHeaders)) // Support for legacy contentType parameter + $input['type'] = $requestHeaders; + + // Content-Type + if (!isset($input['type'])) + { + if (isset($requestHeaders['Content-Type'])) + $input['type'] =& $requestHeaders['Content-Type']; + elseif (isset($input['file'])) + $input['type'] = self::__getMIMEType($input['file']); + else + $input['type'] = 'application/octet-stream'; + } + + if ($storageClass !== self::STORAGE_CLASS_STANDARD) // Storage class + $rest->setAmzHeader('x-amz-storage-class', $storageClass); + + if ($serverSideEncryption !== self::SSE_NONE) // Server-side encryption + $rest->setAmzHeader('x-amz-server-side-encryption', $serverSideEncryption); + + // We need to post with Content-Length and Content-Type, MD5 is optional + if ($rest->size >= 0 && ($rest->fp !== false || $rest->data !== false)) + { + $rest->setHeader('Content-Type', $input['type']); + if (isset($input['md5sum'])) $rest->setHeader('Content-MD5', $input['md5sum']); + + if (isset($input['sha256sum'])) $rest->setAmzHeader('x-amz-content-sha256', $input['sha256sum']); + + $rest->setAmzHeader('x-amz-acl', $acl); + foreach ($metaHeaders as $h => $v) $rest->setAmzHeader('x-amz-meta-'.$h, $v); + $rest->getResponse(); + } else + $rest->response->error = array('code' => 0, 'message' => 'Missing input parameters'); + + if ($rest->response->error === false && $rest->response->code !== 200) + $rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status'); + if ($rest->response->error !== false) + { + self::__triggerError(sprintf("S3::putObject(): [%s] %s", + $rest->response->error['code'], $rest->response->error['message']), __FILE__, __LINE__); + return false; + } + return true; + } + + + /** + * Put an object from a file (legacy function) + * + * @param string $file Input file path + * @param string $bucket Bucket name + * @param string $uri Object URI + * @param constant $acl ACL constant + * @param array $metaHeaders Array of x-amz-meta-* headers + * @param string $contentType Content type + * @return boolean + */ + public static function putObjectFile($file, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = null) + { + return self::putObject(self::inputFile($file), $bucket, $uri, $acl, $metaHeaders, $contentType); + } + + + /** + * Put an object from a string (legacy function) + * + * @param string $string Input data + * @param string $bucket Bucket name + * @param string $uri Object URI + * @param constant $acl ACL constant + * @param array $metaHeaders Array of x-amz-meta-* headers + * @param string $contentType Content type + * @return boolean + */ + public static function putObjectString($string, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = 'text/plain') + { + return self::putObject($string, $bucket, $uri, $acl, $metaHeaders, $contentType); + } + + + /** + * Get an object + * + * @param string $bucket Bucket name + * @param string $uri Object URI + * @param mixed $saveTo Filename or resource to write to + * @return mixed + */ + public static function getObject($bucket, $uri, $saveTo = false) + { + $rest = new S3Request('GET', $bucket, $uri, self::$endpoint); + if ($saveTo !== false) + { + if (is_resource($saveTo)) + $rest->fp =& $saveTo; + else + if (($rest->fp = @fopen($saveTo, 'wb')) !== false) + $rest->file = realpath($saveTo); + else + $rest->response->error = array('code' => 0, 'message' => 'Unable to open save file for writing: '.$saveTo); + } + if ($rest->response->error === false) $rest->getResponse(); + + if ($rest->response->error === false && $rest->response->code !== 200) + $rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status'); + if ($rest->response->error !== false) + { + self::__triggerError(sprintf("S3::getObject({$bucket}, {$uri}): [%s] %s", + $rest->response->error['code'], $rest->response->error['message']), __FILE__, __LINE__); + return false; + } + return $rest->response; + } + + + /** + * Get object information + * + * @param string $bucket Bucket name + * @param string $uri Object URI + * @param boolean $returnInfo Return response information + * @return mixed | false + */ + public static function getObjectInfo($bucket, $uri, $returnInfo = true) + { + $rest = new S3Request('HEAD', $bucket, $uri, self::$endpoint); + $rest = $rest->getResponse(); + if ($rest->error === false && ($rest->code !== 200 && $rest->code !== 404)) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::getObjectInfo({$bucket}, {$uri}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); + return false; + } + return $rest->code == 200 ? $returnInfo ? $rest->headers : true : false; + } + + + /** + * Copy an object + * + * @param string $srcBucket Source bucket name + * @param string $srcUri Source object URI + * @param string $bucket Destination bucket name + * @param string $uri Destination object URI + * @param constant $acl ACL constant + * @param array $metaHeaders Optional array of x-amz-meta-* headers + * @param array $requestHeaders Optional array of request headers (content type, disposition, etc.) + * @param constant $storageClass Storage class constant + * @return mixed | false + */ + public static function copyObject($srcBucket, $srcUri, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $requestHeaders = array(), $storageClass = self::STORAGE_CLASS_STANDARD) + { + $rest = new S3Request('PUT', $bucket, $uri, self::$endpoint); + $rest->setHeader('Content-Length', 0); + foreach ($requestHeaders as $h => $v) + strpos($h, 'x-amz-') === 0 ? $rest->setAmzHeader($h, $v) : $rest->setHeader($h, $v); + foreach ($metaHeaders as $h => $v) $rest->setAmzHeader('x-amz-meta-'.$h, $v); + if ($storageClass !== self::STORAGE_CLASS_STANDARD) // Storage class + $rest->setAmzHeader('x-amz-storage-class', $storageClass); + $rest->setAmzHeader('x-amz-acl', $acl); + $rest->setAmzHeader('x-amz-copy-source', sprintf('/%s/%s', $srcBucket, rawurlencode($srcUri))); + if (sizeof($requestHeaders) > 0 || sizeof($metaHeaders) > 0) + $rest->setAmzHeader('x-amz-metadata-directive', 'REPLACE'); + + $rest = $rest->getResponse(); + if ($rest->error === false && $rest->code !== 200) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::copyObject({$srcBucket}, {$srcUri}, {$bucket}, {$uri}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); + return false; + } + return isset($rest->body->LastModified, $rest->body->ETag) ? array( + 'time' => strtotime((string)$rest->body->LastModified), + 'hash' => substr((string)$rest->body->ETag, 1, -1) + ) : false; + } + + + /** + * Set up a bucket redirection + * + * @param string $bucket Bucket name + * @param string $location Target host name + * @return boolean + */ + public static function setBucketRedirect($bucket = NULL, $location = NULL) + { + $rest = new S3Request('PUT', $bucket, '', self::$endpoint); + + if( empty($bucket) || empty($location) ) { + self::__triggerError("S3::setBucketRedirect({$bucket}, {$location}): Empty parameter.", __FILE__, __LINE__); + return false; + } + + $dom = new DOMDocument; + $websiteConfiguration = $dom->createElement('WebsiteConfiguration'); + $redirectAllRequestsTo = $dom->createElement('RedirectAllRequestsTo'); + $hostName = $dom->createElement('HostName', $location); + $redirectAllRequestsTo->appendChild($hostName); + $websiteConfiguration->appendChild($redirectAllRequestsTo); + $dom->appendChild($websiteConfiguration); + $rest->setParameter('website', null); + $rest->data = $dom->saveXML(); + $rest->size = strlen($rest->data); + $rest->setHeader('Content-Type', 'application/xml'); + $rest = $rest->getResponse(); + + if ($rest->error === false && $rest->code !== 200) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::setBucketRedirect({$bucket}, {$location}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); + return false; + } + return true; + } + + + /** + * Set logging for a bucket + * + * @param string $bucket Bucket name + * @param string $targetBucket Target bucket (where logs are stored) + * @param string $targetPrefix Log prefix (e,g; domain.com-) + * @return boolean + */ + public static function setBucketLogging($bucket, $targetBucket, $targetPrefix = null) + { + // The S3 log delivery group has to be added to the target bucket's ACP + if ($targetBucket !== null && ($acp = self::getAccessControlPolicy($targetBucket, '')) !== false) + { + // Only add permissions to the target bucket when they do not exist + $aclWriteSet = false; + $aclReadSet = false; + foreach ($acp['acl'] as $acl) + if ($acl['type'] == 'Group' && $acl['uri'] == 'http://acs.amazonaws.com/groups/s3/LogDelivery') + { + if ($acl['permission'] == 'WRITE') $aclWriteSet = true; + elseif ($acl['permission'] == 'READ_ACP') $aclReadSet = true; + } + if (!$aclWriteSet) $acp['acl'][] = array( + 'type' => 'Group', 'uri' => 'http://acs.amazonaws.com/groups/s3/LogDelivery', 'permission' => 'WRITE' + ); + if (!$aclReadSet) $acp['acl'][] = array( + 'type' => 'Group', 'uri' => 'http://acs.amazonaws.com/groups/s3/LogDelivery', 'permission' => 'READ_ACP' + ); + if (!$aclReadSet || !$aclWriteSet) self::setAccessControlPolicy($targetBucket, '', $acp); + } + + $dom = new DOMDocument; + $bucketLoggingStatus = $dom->createElement('BucketLoggingStatus'); + $bucketLoggingStatus->setAttribute('xmlns', 'http://s3.amazonaws.com/doc/2006-03-01/'); + if ($targetBucket !== null) + { + if ($targetPrefix == null) $targetPrefix = $bucket . '-'; + $loggingEnabled = $dom->createElement('LoggingEnabled'); + $loggingEnabled->appendChild($dom->createElement('TargetBucket', $targetBucket)); + $loggingEnabled->appendChild($dom->createElement('TargetPrefix', $targetPrefix)); + // TODO: Add TargetGrants? + $bucketLoggingStatus->appendChild($loggingEnabled); + } + $dom->appendChild($bucketLoggingStatus); + + $rest = new S3Request('PUT', $bucket, '', self::$endpoint); + $rest->setParameter('logging', null); + $rest->data = $dom->saveXML(); + $rest->size = strlen($rest->data); + $rest->setHeader('Content-Type', 'application/xml'); + $rest = $rest->getResponse(); + if ($rest->error === false && $rest->code !== 200) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::setBucketLogging({$bucket}, {$targetBucket}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); + return false; + } + return true; + } + + + /** + * Get logging status for a bucket + * + * This will return false if logging is not enabled. + * Note: To enable logging, you also need to grant write access to the log group + * + * @param string $bucket Bucket name + * @return array | false + */ + public static function getBucketLogging($bucket) + { + $rest = new S3Request('GET', $bucket, '', self::$endpoint); + $rest->setParameter('logging', null); + $rest = $rest->getResponse(); + if ($rest->error === false && $rest->code !== 200) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::getBucketLogging({$bucket}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); + return false; + } + if (!isset($rest->body->LoggingEnabled)) return false; // No logging + return array( + 'targetBucket' => (string)$rest->body->LoggingEnabled->TargetBucket, + 'targetPrefix' => (string)$rest->body->LoggingEnabled->TargetPrefix, + ); + } + + + /** + * Disable bucket logging + * + * @param string $bucket Bucket name + * @return boolean + */ + public static function disableBucketLogging($bucket) + { + return self::setBucketLogging($bucket, null); + } + + + /** + * Get a bucket's location + * + * @param string $bucket Bucket name + * @return string | false + */ + public static function getBucketLocation($bucket) + { + $rest = new S3Request('GET', $bucket, '', self::$endpoint); + $rest->setParameter('location', null); + $rest = $rest->getResponse(); + if ($rest->error === false && $rest->code !== 200) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::getBucketLocation({$bucket}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); + return false; + } + return (isset($rest->body[0]) && (string)$rest->body[0] !== '') ? (string)$rest->body[0] : 'US'; + } + + + /** + * Set object or bucket Access Control Policy + * + * @param string $bucket Bucket name + * @param string $uri Object URI + * @param array $acp Access Control Policy Data (same as the data returned from getAccessControlPolicy) + * @return boolean + */ + public static function setAccessControlPolicy($bucket, $uri = '', $acp = array()) + { + $dom = new DOMDocument; + $dom->formatOutput = true; + $accessControlPolicy = $dom->createElement('AccessControlPolicy'); + $accessControlList = $dom->createElement('AccessControlList'); + + // It seems the owner has to be passed along too + $owner = $dom->createElement('Owner'); + $owner->appendChild($dom->createElement('ID', $acp['owner']['id'])); + $owner->appendChild($dom->createElement('DisplayName', $acp['owner']['name'])); + $accessControlPolicy->appendChild($owner); + + foreach ($acp['acl'] as $g) + { + $grant = $dom->createElement('Grant'); + $grantee = $dom->createElement('Grantee'); + $grantee->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); + if (isset($g['id'])) + { // CanonicalUser (DisplayName is omitted) + $grantee->setAttribute('xsi:type', 'CanonicalUser'); + $grantee->appendChild($dom->createElement('ID', $g['id'])); + } + elseif (isset($g['email'])) + { // AmazonCustomerByEmail + $grantee->setAttribute('xsi:type', 'AmazonCustomerByEmail'); + $grantee->appendChild($dom->createElement('EmailAddress', $g['email'])); + } + elseif ($g['type'] == 'Group') + { // Group + $grantee->setAttribute('xsi:type', 'Group'); + $grantee->appendChild($dom->createElement('URI', $g['uri'])); + } + $grant->appendChild($grantee); + $grant->appendChild($dom->createElement('Permission', $g['permission'])); + $accessControlList->appendChild($grant); + } + + $accessControlPolicy->appendChild($accessControlList); + $dom->appendChild($accessControlPolicy); + + $rest = new S3Request('PUT', $bucket, $uri, self::$endpoint); + $rest->setParameter('acl', null); + $rest->data = $dom->saveXML(); + $rest->size = strlen($rest->data); + $rest->setHeader('Content-Type', 'application/xml'); + $rest = $rest->getResponse(); + if ($rest->error === false && $rest->code !== 200) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::setAccessControlPolicy({$bucket}, {$uri}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); + return false; + } + return true; + } + + + /** + * Get object or bucket Access Control Policy + * + * @param string $bucket Bucket name + * @param string $uri Object URI + * @return mixed | false + */ + public static function getAccessControlPolicy($bucket, $uri = '') + { + $rest = new S3Request('GET', $bucket, $uri, self::$endpoint); + $rest->setParameter('acl', null); + $rest = $rest->getResponse(); + if ($rest->error === false && $rest->code !== 200) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::getAccessControlPolicy({$bucket}, {$uri}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); + return false; + } + + $acp = array(); + if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName)) + $acp['owner'] = array( + 'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->DisplayName + ); + + if (isset($rest->body->AccessControlList)) + { + $acp['acl'] = array(); + foreach ($rest->body->AccessControlList->Grant as $grant) + { + foreach ($grant->Grantee as $grantee) + { + if (isset($grantee->ID, $grantee->DisplayName)) // CanonicalUser + $acp['acl'][] = array( + 'type' => 'CanonicalUser', + 'id' => (string)$grantee->ID, + 'name' => (string)$grantee->DisplayName, + 'permission' => (string)$grant->Permission + ); + elseif (isset($grantee->EmailAddress)) // AmazonCustomerByEmail + $acp['acl'][] = array( + 'type' => 'AmazonCustomerByEmail', + 'email' => (string)$grantee->EmailAddress, + 'permission' => (string)$grant->Permission + ); + elseif (isset($grantee->URI)) // Group + $acp['acl'][] = array( + 'type' => 'Group', + 'uri' => (string)$grantee->URI, + 'permission' => (string)$grant->Permission + ); + else continue; + } + } + } + return $acp; + } + + + /** + * Delete an object + * + * @param string $bucket Bucket name + * @param string $uri Object URI + * @return boolean + */ + public static function deleteObject($bucket, $uri) + { + $rest = new S3Request('DELETE', $bucket, $uri, self::$endpoint); + $rest = $rest->getResponse(); + if ($rest->error === false && $rest->code !== 204) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::deleteObject(): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); + return false; + } + return true; + } + + + /** + * Get a query string authenticated URL + * + * @param string $bucket Bucket name + * @param string $uri Object URI + * @param integer $lifetime Lifetime in seconds + * @param boolean $hostBucket Use the bucket name as the hostname + * @param boolean $https Use HTTPS ($hostBucket should be false for SSL verification) + * @return string + */ + public static function getAuthenticatedURL($bucket, $uri, $lifetime, $hostBucket = false, $https = false) + { + $expires = self::__getTime() + $lifetime; + $uri = str_replace(array('%2F', '%2B'), array('/', '+'), rawurlencode($uri)); + return sprintf(($https ? 'https' : 'http').'://%s/%s?AWSAccessKeyId=%s&Expires=%u&Signature=%s', + // $hostBucket ? $bucket : $bucket.'.s3.amazonaws.com', $uri, self::$__accessKey, $expires, + $hostBucket ? $bucket : self::$endpoint.'/'.$bucket, $uri, self::$__accessKey, $expires, + urlencode(self::__getHash("GET\n\n\n{$expires}\n/{$bucket}/{$uri}"))); + } + + + /** + * Get a CloudFront signed policy URL + * + * @param array $policy Policy + * @return string + */ + public static function getSignedPolicyURL($policy) + { + $data = json_encode($policy); + $signature = ''; + if (!openssl_sign($data, $signature, self::$__signingKeyResource)) return false; + + $encoded = str_replace(array('+', '='), array('-', '_', '~'), base64_encode($data)); + $signature = str_replace(array('+', '='), array('-', '_', '~'), base64_encode($signature)); + + $url = $policy['Statement'][0]['Resource'] . '?'; + foreach (array('Policy' => $encoded, 'Signature' => $signature, 'Key-Pair-Id' => self::$__signingKeyPairId) as $k => $v) + $url .= $k.'='.str_replace('%2F', '/', rawurlencode($v)).'&'; + return substr($url, 0, -1); + } + + + /** + * Get a CloudFront canned policy URL + * + * @param string $url URL to sign + * @param integer $lifetime URL lifetime + * @return string + */ + public static function getSignedCannedURL($url, $lifetime) + { + return self::getSignedPolicyURL(array( + 'Statement' => array( + array('Resource' => $url, 'Condition' => array( + 'DateLessThan' => array('AWS:EpochTime' => self::__getTime() + $lifetime) + )) + ) + )); + } + + + /** + * Get upload POST parameters for form uploads + * + * @param string $bucket Bucket name + * @param string $uriPrefix Object URI prefix + * @param constant $acl ACL constant + * @param integer $lifetime Lifetime in seconds + * @param integer $maxFileSize Maximum filesize in bytes (default 5MB) + * @param string $successRedirect Redirect URL or 200 / 201 status code + * @param array $amzHeaders Array of x-amz-meta-* headers + * @param array $headers Array of request headers or content type as a string + * @param boolean $flashVars Includes additional "Filename" variable posted by Flash + * @return object + */ + public static function getHttpUploadPostParams($bucket, $uriPrefix = '', $acl = self::ACL_PRIVATE, $lifetime = 3600, + $maxFileSize = 5242880, $successRedirect = "201", $amzHeaders = array(), $headers = array(), $flashVars = false) + { + // Create policy object + $policy = new stdClass; + $policy->expiration = gmdate('Y-m-d\TH:i:s\Z', (self::__getTime() + $lifetime)); + $policy->conditions = array(); + $obj = new stdClass; $obj->bucket = $bucket; array_push($policy->conditions, $obj); + $obj = new stdClass; $obj->acl = $acl; array_push($policy->conditions, $obj); + + $obj = new stdClass; // 200 for non-redirect uploads + if (is_numeric($successRedirect) && in_array((int)$successRedirect, array(200, 201))) + $obj->success_action_status = (string)$successRedirect; + else // URL + $obj->success_action_redirect = $successRedirect; + array_push($policy->conditions, $obj); + + if ($acl !== self::ACL_PUBLIC_READ) + array_push($policy->conditions, array('eq', '$acl', $acl)); + + array_push($policy->conditions, array('starts-with', '$key', $uriPrefix)); + if ($flashVars) array_push($policy->conditions, array('starts-with', '$Filename', '')); + foreach (array_keys($headers) as $headerKey) + array_push($policy->conditions, array('starts-with', '$'.$headerKey, '')); + foreach ($amzHeaders as $headerKey => $headerVal) + { + $obj = new stdClass; + $obj->{$headerKey} = (string)$headerVal; + array_push($policy->conditions, $obj); + } + array_push($policy->conditions, array('content-length-range', 0, $maxFileSize)); + $policy = base64_encode(str_replace('\/', '/', json_encode($policy))); + + // Create parameters + $params = new stdClass; + $params->AWSAccessKeyId = self::$__accessKey; + $params->key = $uriPrefix.'${filename}'; + $params->acl = $acl; + $params->policy = $policy; unset($policy); + $params->signature = self::__getHash($params->policy); + if (is_numeric($successRedirect) && in_array((int)$successRedirect, array(200, 201))) + $params->success_action_status = (string)$successRedirect; + else + $params->success_action_redirect = $successRedirect; + foreach ($headers as $headerKey => $headerVal) $params->{$headerKey} = (string)$headerVal; + foreach ($amzHeaders as $headerKey => $headerVal) $params->{$headerKey} = (string)$headerVal; + return $params; + } + + + /** + * Create a CloudFront distribution + * + * @param string $bucket Bucket name + * @param boolean $enabled Enabled (true/false) + * @param array $cnames Array containing CNAME aliases + * @param string $comment Use the bucket name as the hostname + * @param string $defaultRootObject Default root object + * @param string $originAccessIdentity Origin access identity + * @param array $trustedSigners Array of trusted signers + * @return array | false + */ + public static function createDistribution($bucket, $enabled = true, $cnames = array(), $comment = null, $defaultRootObject = null, $originAccessIdentity = null, $trustedSigners = array()) + { + if (!extension_loaded('openssl')) + { + self::__triggerError(sprintf("S3::createDistribution({$bucket}, ".(int)$enabled.", [], '$comment'): %s", + "CloudFront functionality requires SSL"), __FILE__, __LINE__); + return false; + } + $useSSL = self::$useSSL; + + self::$useSSL = true; // CloudFront requires SSL + $rest = new S3Request('POST', '', '2010-11-01/distribution', 'cloudfront.amazonaws.com'); + $rest->data = self::__getCloudFrontDistributionConfigXML( + $bucket.'.s3.amazonaws.com', + $enabled, + (string)$comment, + (string)microtime(true), + $cnames, + $defaultRootObject, + $originAccessIdentity, + $trustedSigners + ); + + $rest->size = strlen($rest->data); + $rest->setHeader('Content-Type', 'application/xml'); + $rest = self::__getCloudFrontResponse($rest); + + self::$useSSL = $useSSL; + + if ($rest->error === false && $rest->code !== 201) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::createDistribution({$bucket}, ".(int)$enabled.", [], '$comment'): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); + return false; + } elseif ($rest->body instanceof SimpleXMLElement) + return self::__parseCloudFrontDistributionConfig($rest->body); + return false; + } + + + /** + * Get CloudFront distribution info + * + * @param string $distributionId Distribution ID from listDistributions() + * @return array | false + */ + public static function getDistribution($distributionId) + { + if (!extension_loaded('openssl')) + { + self::__triggerError(sprintf("S3::getDistribution($distributionId): %s", + "CloudFront functionality requires SSL"), __FILE__, __LINE__); + return false; + } + $useSSL = self::$useSSL; + + self::$useSSL = true; // CloudFront requires SSL + $rest = new S3Request('GET', '', '2010-11-01/distribution/'.$distributionId, 'cloudfront.amazonaws.com'); + $rest = self::__getCloudFrontResponse($rest); + + self::$useSSL = $useSSL; + + if ($rest->error === false && $rest->code !== 200) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::getDistribution($distributionId): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); + return false; + } + elseif ($rest->body instanceof SimpleXMLElement) + { + $dist = self::__parseCloudFrontDistributionConfig($rest->body); + $dist['hash'] = $rest->headers['hash']; + $dist['id'] = $distributionId; + return $dist; + } + return false; + } + + + /** + * Update a CloudFront distribution + * + * @param array $dist Distribution array info identical to output of getDistribution() + * @return array | false + */ + public static function updateDistribution($dist) + { + if (!extension_loaded('openssl')) + { + self::__triggerError(sprintf("S3::updateDistribution({$dist['id']}): %s", + "CloudFront functionality requires SSL"), __FILE__, __LINE__); + return false; + } + + $useSSL = self::$useSSL; + + self::$useSSL = true; // CloudFront requires SSL + $rest = new S3Request('PUT', '', '2010-11-01/distribution/'.$dist['id'].'/config', 'cloudfront.amazonaws.com'); + $rest->data = self::__getCloudFrontDistributionConfigXML( + $dist['origin'], + $dist['enabled'], + $dist['comment'], + $dist['callerReference'], + $dist['cnames'], + $dist['defaultRootObject'], + $dist['originAccessIdentity'], + $dist['trustedSigners'] + ); + + $rest->size = strlen($rest->data); + $rest->setHeader('If-Match', $dist['hash']); + $rest = self::__getCloudFrontResponse($rest); + + self::$useSSL = $useSSL; + + if ($rest->error === false && $rest->code !== 200) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::updateDistribution({$dist['id']}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); + return false; + } else { + $dist = self::__parseCloudFrontDistributionConfig($rest->body); + $dist['hash'] = $rest->headers['hash']; + return $dist; + } + return false; + } + + + /** + * Delete a CloudFront distribution + * + * @param array $dist Distribution array info identical to output of getDistribution() + * @return boolean + */ + public static function deleteDistribution($dist) + { + if (!extension_loaded('openssl')) + { + self::__triggerError(sprintf("S3::deleteDistribution({$dist['id']}): %s", + "CloudFront functionality requires SSL"), __FILE__, __LINE__); + return false; + } + + $useSSL = self::$useSSL; + + self::$useSSL = true; // CloudFront requires SSL + $rest = new S3Request('DELETE', '', '2008-06-30/distribution/'.$dist['id'], 'cloudfront.amazonaws.com'); + $rest->setHeader('If-Match', $dist['hash']); + $rest = self::__getCloudFrontResponse($rest); + + self::$useSSL = $useSSL; + + if ($rest->error === false && $rest->code !== 204) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::deleteDistribution({$dist['id']}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); + return false; + } + return true; + } + + + /** + * Get a list of CloudFront distributions + * + * @return array + */ + public static function listDistributions() + { + if (!extension_loaded('openssl')) + { + self::__triggerError(sprintf("S3::listDistributions(): [%s] %s", + "CloudFront functionality requires SSL"), __FILE__, __LINE__); + return false; + } + + $useSSL = self::$useSSL; + self::$useSSL = true; // CloudFront requires SSL + $rest = new S3Request('GET', '', '2010-11-01/distribution', 'cloudfront.amazonaws.com'); + $rest = self::__getCloudFrontResponse($rest); + self::$useSSL = $useSSL; + + if ($rest->error === false && $rest->code !== 200) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::listDistributions(): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); + return false; + } + elseif ($rest->body instanceof SimpleXMLElement && isset($rest->body->DistributionSummary)) + { + $list = array(); + if (isset($rest->body->Marker, $rest->body->MaxItems, $rest->body->IsTruncated)) + { + //$info['marker'] = (string)$rest->body->Marker; + //$info['maxItems'] = (int)$rest->body->MaxItems; + //$info['isTruncated'] = (string)$rest->body->IsTruncated == 'true' ? true : false; + } + foreach ($rest->body->DistributionSummary as $summary) + $list[(string)$summary->Id] = self::__parseCloudFrontDistributionConfig($summary); + + return $list; + } + return array(); + } + + /** + * List CloudFront Origin Access Identities + * + * @return array + */ + public static function listOriginAccessIdentities() + { + if (!extension_loaded('openssl')) + { + self::__triggerError(sprintf("S3::listOriginAccessIdentities(): [%s] %s", + "CloudFront functionality requires SSL"), __FILE__, __LINE__); + return false; + } + + self::$useSSL = true; // CloudFront requires SSL + $rest = new S3Request('GET', '', '2010-11-01/origin-access-identity/cloudfront', 'cloudfront.amazonaws.com'); + $rest = self::__getCloudFrontResponse($rest); + $useSSL = self::$useSSL; + + if ($rest->error === false && $rest->code !== 200) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + trigger_error(sprintf("S3::listOriginAccessIdentities(): [%s] %s", + $rest->error['code'], $rest->error['message']), E_USER_WARNING); + return false; + } + + if (isset($rest->body->CloudFrontOriginAccessIdentitySummary)) + { + $identities = array(); + foreach ($rest->body->CloudFrontOriginAccessIdentitySummary as $identity) + if (isset($identity->S3CanonicalUserId)) + $identities[(string)$identity->Id] = array('id' => (string)$identity->Id, 's3CanonicalUserId' => (string)$identity->S3CanonicalUserId); + return $identities; + } + return false; + } + + + /** + * Invalidate objects in a CloudFront distribution + * + * Thanks to Martin Lindkvist for S3::invalidateDistribution() + * + * @param string $distributionId Distribution ID from listDistributions() + * @param array $paths Array of object paths to invalidate + * @return boolean + */ + public static function invalidateDistribution($distributionId, $paths) + { + if (!extension_loaded('openssl')) + { + self::__triggerError(sprintf("S3::invalidateDistribution(): [%s] %s", + "CloudFront functionality requires SSL"), __FILE__, __LINE__); + return false; + } + + $useSSL = self::$useSSL; + self::$useSSL = true; // CloudFront requires SSL + $rest = new S3Request('POST', '', '2010-08-01/distribution/'.$distributionId.'/invalidation', 'cloudfront.amazonaws.com'); + $rest->data = self::__getCloudFrontInvalidationBatchXML($paths, (string)microtime(true)); + $rest->size = strlen($rest->data); + $rest = self::__getCloudFrontResponse($rest); + self::$useSSL = $useSSL; + + if ($rest->error === false && $rest->code !== 201) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + trigger_error(sprintf("S3::invalidate('{$distributionId}',{$paths}): [%s] %s", + $rest->error['code'], $rest->error['message']), E_USER_WARNING); + return false; + } + return true; + } + + + /** + * Get a InvalidationBatch DOMDocument + * + * @internal Used to create XML in invalidateDistribution() + * @param array $paths Paths to objects to invalidateDistribution + * @param int $callerReference + * @return string + */ + private static function __getCloudFrontInvalidationBatchXML($paths, $callerReference = '0') + { + $dom = new DOMDocument('1.0', 'UTF-8'); + $dom->formatOutput = true; + $invalidationBatch = $dom->createElement('InvalidationBatch'); + foreach ($paths as $path) + $invalidationBatch->appendChild($dom->createElement('Path', $path)); + + $invalidationBatch->appendChild($dom->createElement('CallerReference', $callerReference)); + $dom->appendChild($invalidationBatch); + return $dom->saveXML(); + } + + + /** + * List your invalidation batches for invalidateDistribution() in a CloudFront distribution + * + * http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListInvalidation.html + * returned array looks like this: + * Array + * ( + * [I31TWB0CN9V6XD] => InProgress + * [IT3TFE31M0IHZ] => Completed + * [I12HK7MPO1UQDA] => Completed + * [I1IA7R6JKTC3L2] => Completed + * ) + * + * @param string $distributionId Distribution ID from listDistributions() + * @return array + */ + public static function getDistributionInvalidationList($distributionId) + { + if (!extension_loaded('openssl')) + { + self::__triggerError(sprintf("S3::getDistributionInvalidationList(): [%s] %s", + "CloudFront functionality requires SSL"), __FILE__, __LINE__); + return false; + } + + $useSSL = self::$useSSL; + self::$useSSL = true; // CloudFront requires SSL + $rest = new S3Request('GET', '', '2010-11-01/distribution/'.$distributionId.'/invalidation', 'cloudfront.amazonaws.com'); + $rest = self::__getCloudFrontResponse($rest); + self::$useSSL = $useSSL; + + if ($rest->error === false && $rest->code !== 200) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + trigger_error(sprintf("S3::getDistributionInvalidationList('{$distributionId}'): [%s]", + $rest->error['code'], $rest->error['message']), E_USER_WARNING); + return false; + } + elseif ($rest->body instanceof SimpleXMLElement && isset($rest->body->InvalidationSummary)) + { + $list = array(); + foreach ($rest->body->InvalidationSummary as $summary) + $list[(string)$summary->Id] = (string)$summary->Status; + + return $list; + } + return array(); + } + + + /** + * Get a DistributionConfig DOMDocument + * + * http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/index.html?PutConfig.html + * + * @internal Used to create XML in createDistribution() and updateDistribution() + * @param string $bucket S3 Origin bucket + * @param boolean $enabled Enabled (true/false) + * @param string $comment Comment to append + * @param string $callerReference Caller reference + * @param array $cnames Array of CNAME aliases + * @param string $defaultRootObject Default root object + * @param string $originAccessIdentity Origin access identity + * @param array $trustedSigners Array of trusted signers + * @return string + */ + private static function __getCloudFrontDistributionConfigXML($bucket, $enabled, $comment, $callerReference = '0', $cnames = array(), $defaultRootObject = null, $originAccessIdentity = null, $trustedSigners = array()) + { + $dom = new DOMDocument('1.0', 'UTF-8'); + $dom->formatOutput = true; + $distributionConfig = $dom->createElement('DistributionConfig'); + $distributionConfig->setAttribute('xmlns', 'http://cloudfront.amazonaws.com/doc/2010-11-01/'); + + $origin = $dom->createElement('S3Origin'); + $origin->appendChild($dom->createElement('DNSName', $bucket)); + if ($originAccessIdentity !== null) $origin->appendChild($dom->createElement('OriginAccessIdentity', $originAccessIdentity)); + $distributionConfig->appendChild($origin); + + if ($defaultRootObject !== null) $distributionConfig->appendChild($dom->createElement('DefaultRootObject', $defaultRootObject)); + + $distributionConfig->appendChild($dom->createElement('CallerReference', $callerReference)); + foreach ($cnames as $cname) + $distributionConfig->appendChild($dom->createElement('CNAME', $cname)); + if ($comment !== '') $distributionConfig->appendChild($dom->createElement('Comment', $comment)); + $distributionConfig->appendChild($dom->createElement('Enabled', $enabled ? 'true' : 'false')); + + if (!empty($trustedSigners)) + { + $trusted = $dom->createElement('TrustedSigners'); + foreach ($trustedSigners as $id => $type) + $trusted->appendChild($id !== '' ? $dom->createElement($type, $id) : $dom->createElement($type)); + $distributionConfig->appendChild($trusted); + } + $dom->appendChild($distributionConfig); + //var_dump($dom->saveXML()); + return $dom->saveXML(); + } + + + /** + * Parse a CloudFront distribution config + * + * See http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/index.html?GetDistribution.html + * + * @internal Used to parse the CloudFront DistributionConfig node to an array + * @param object &$node DOMNode + * @return array + */ + private static function __parseCloudFrontDistributionConfig(&$node) + { + if (isset($node->DistributionConfig)) + return self::__parseCloudFrontDistributionConfig($node->DistributionConfig); + + $dist = array(); + if (isset($node->Id, $node->Status, $node->LastModifiedTime, $node->DomainName)) + { + $dist['id'] = (string)$node->Id; + $dist['status'] = (string)$node->Status; + $dist['time'] = strtotime((string)$node->LastModifiedTime); + $dist['domain'] = (string)$node->DomainName; + } + + if (isset($node->CallerReference)) + $dist['callerReference'] = (string)$node->CallerReference; + + if (isset($node->Enabled)) + $dist['enabled'] = (string)$node->Enabled == 'true' ? true : false; + + if (isset($node->S3Origin)) + { + if (isset($node->S3Origin->DNSName)) + $dist['origin'] = (string)$node->S3Origin->DNSName; + + $dist['originAccessIdentity'] = isset($node->S3Origin->OriginAccessIdentity) ? + (string)$node->S3Origin->OriginAccessIdentity : null; + } + + $dist['defaultRootObject'] = isset($node->DefaultRootObject) ? (string)$node->DefaultRootObject : null; + + $dist['cnames'] = array(); + if (isset($node->CNAME)) + foreach ($node->CNAME as $cname) + $dist['cnames'][(string)$cname] = (string)$cname; + + $dist['trustedSigners'] = array(); + if (isset($node->TrustedSigners)) + foreach ($node->TrustedSigners as $signer) + { + if (isset($signer->Self)) + $dist['trustedSigners'][''] = 'Self'; + elseif (isset($signer->KeyPairId)) + $dist['trustedSigners'][(string)$signer->KeyPairId] = 'KeyPairId'; + elseif (isset($signer->AwsAccountNumber)) + $dist['trustedSigners'][(string)$signer->AwsAccountNumber] = 'AwsAccountNumber'; + } + + $dist['comment'] = isset($node->Comment) ? (string)$node->Comment : null; + return $dist; + } + + + /** + * Grab CloudFront response + * + * @internal Used to parse the CloudFront S3Request::getResponse() output + * @param object &$rest S3Request instance + * @return object + */ + private static function __getCloudFrontResponse(&$rest) + { + $rest->getResponse(); + if ($rest->response->error === false && isset($rest->response->body) && + is_string($rest->response->body) && substr($rest->response->body, 0, 5) == 'response->body = simplexml_load_string($rest->response->body); + // Grab CloudFront errors + if (isset($rest->response->body->Error, $rest->response->body->Error->Code, + $rest->response->body->Error->Message)) + { + $rest->response->error = array( + 'code' => (string)$rest->response->body->Error->Code, + 'message' => (string)$rest->response->body->Error->Message + ); + unset($rest->response->body); + } + } + return $rest->response; + } + + + /** + * Get MIME type for file + * + * To override the putObject() Content-Type, add it to $requestHeaders + * + * To use fileinfo, ensure the MAGIC environment variable is set + * + * @internal Used to get mime types + * @param string &$file File path + * @return string + */ + private static function __getMIMEType(&$file) + { + static $exts = array( + 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif', + 'png' => 'image/png', 'ico' => 'image/x-icon', 'pdf' => 'application/pdf', + 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'svg' => 'image/svg+xml', + 'svgz' => 'image/svg+xml', 'swf' => 'application/x-shockwave-flash', + 'zip' => 'application/zip', 'gz' => 'application/x-gzip', + 'tar' => 'application/x-tar', 'bz' => 'application/x-bzip', + 'bz2' => 'application/x-bzip2', 'rar' => 'application/x-rar-compressed', + 'exe' => 'application/x-msdownload', 'msi' => 'application/x-msdownload', + 'cab' => 'application/vnd.ms-cab-compressed', 'txt' => 'text/plain', + 'asc' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html', + 'css' => 'text/css', 'js' => 'text/javascript', + 'xml' => 'text/xml', 'xsl' => 'application/xsl+xml', + 'ogg' => 'application/ogg', 'mp3' => 'audio/mpeg', 'wav' => 'audio/x-wav', + 'avi' => 'video/x-msvideo', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg', + 'mov' => 'video/quicktime', 'flv' => 'video/x-flv', 'php' => 'text/x-php' + ); + + $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION)); + if (isset($exts[$ext])) return $exts[$ext]; + + // Use fileinfo if available + if (extension_loaded('fileinfo') && isset($_ENV['MAGIC']) && + ($finfo = finfo_open(FILEINFO_MIME, $_ENV['MAGIC'])) !== false) + { + if (($type = finfo_file($finfo, $file)) !== false) + { + // Remove the charset and grab the last content-type + $type = explode(' ', str_replace('; charset=', ';charset=', $type)); + $type = array_pop($type); + $type = explode(';', $type); + $type = trim(array_shift($type)); + } + finfo_close($finfo); + if ($type !== false && strlen($type) > 0) return $type; + } + + return 'application/octet-stream'; + } + + + /** + * Get the current time + * + * @internal Used to apply offsets to sytem time + * @return integer + */ + public static function __getTime() + { + return time() + self::$__timeOffset; + } + + + /** + * Generate the auth string: "AWS AccessKey:Signature" + * + * @internal Used by S3Request::getResponse() + * @param string $string String to sign + * @return string + */ + public static function __getSignature($string) + { + return 'AWS '.self::$__accessKey.':'.self::__getHash($string); + } + + + /** + * Creates a HMAC-SHA1 hash + * + * This uses the hash extension if loaded + * + * @internal Used by __getSignature() + * @param string $string String to sign + * @return string + */ + private static function __getHash($string) + { + return base64_encode(extension_loaded('hash') ? + hash_hmac('sha1', $string, self::$__secretKey, true) : pack('H*', sha1( + (str_pad(self::$__secretKey, 64, chr(0x00)) ^ (str_repeat(chr(0x5c), 64))) . + pack('H*', sha1((str_pad(self::$__secretKey, 64, chr(0x00)) ^ + (str_repeat(chr(0x36), 64))) . $string))))); + } + + + /** + * Generate the headers for AWS Signature V4 + * + * @internal Used by S3Request::getResponse() + * @param array $amzHeaders + * @param array $headers + * @param string $method + * @param string $uri + * @param array $parameters + * @return array + */ + public static function __getSignatureV4($amzHeaders, $headers, $method, $uri, $parameters) + { + $service = 's3'; + $region = S3::getRegion(); + + $algorithm = 'AWS4-HMAC-SHA256'; + $combinedHeaders = array(); + + $amzDateStamp = substr($amzHeaders['x-amz-date'], 0, 8); + + // CanonicalHeaders + foreach ($headers as $k => $v) + $combinedHeaders[strtolower($k)] = trim($v); + foreach ($amzHeaders as $k => $v) + $combinedHeaders[strtolower($k)] = trim($v); + uksort($combinedHeaders, array('self', '__sortMetaHeadersCmp')); + + // Convert null query string parameters to strings and sort + $parameters = array_map('strval', $parameters); + uksort($parameters, array('self', '__sortMetaHeadersCmp')); + $queryString = http_build_query($parameters, null, '&', PHP_QUERY_RFC3986); + + // Payload + $amzPayload = array($method); + + $qsPos = strpos($uri, '?'); + $amzPayload[] = ($qsPos === false ? $uri : substr($uri, 0, $qsPos)); + + $amzPayload[] = $queryString; + // add header as string to requests + foreach ($combinedHeaders as $k => $v ) + { + $amzPayload[] = $k . ':' . $v; + } + // add a blank entry so we end up with an extra line break + $amzPayload[] = ''; + // SignedHeaders + $amzPayload[] = implode(';', array_keys($combinedHeaders)); + // payload hash + $amzPayload[] = $amzHeaders['x-amz-content-sha256']; + // request as string + $amzPayloadStr = implode("\n", $amzPayload); + + // CredentialScope + $credentialScope = array($amzDateStamp, $region, $service, 'aws4_request'); + + // stringToSign + $stringToSignStr = implode("\n", array($algorithm, $amzHeaders['x-amz-date'], + implode('/', $credentialScope), hash('sha256', $amzPayloadStr))); + + // Make Signature + $kSecret = 'AWS4' . self::$__secretKey; + $kDate = hash_hmac('sha256', $amzDateStamp, $kSecret, true); + $kRegion = hash_hmac('sha256', $region, $kDate, true); + $kService = hash_hmac('sha256', $service, $kRegion, true); + $kSigning = hash_hmac('sha256', 'aws4_request', $kService, true); + + $signature = hash_hmac('sha256', $stringToSignStr, $kSigning); + + return $algorithm . ' ' . implode(',', array( + 'Credential=' . self::$__accessKey . '/' . implode('/', $credentialScope), + 'SignedHeaders=' . implode(';', array_keys($combinedHeaders)), + 'Signature=' . $signature, + )); + } + + + /** + * Sort compare for meta headers + * + * @internal Used to sort x-amz meta headers + * @param string $a String A + * @param string $b String B + * @return integer + */ + private static function __sortMetaHeadersCmp($a, $b) + { + $lenA = strlen($a); + $lenB = strlen($b); + $minLen = min($lenA, $lenB); + $ncmp = strncmp($a, $b, $minLen); + if ($lenA == $lenB) return $ncmp; + if (0 == $ncmp) return $lenA < $lenB ? -1 : 1; + return $ncmp; + } +} + +/** + * S3 Request class + * + * @link http://undesigned.org.za/2007/10/22/amazon-s3-php-class + * @version 0.5.0-dev + */ +final class S3Request +{ + /** + * AWS URI + * + * @var string + * @access private + */ + private $endpoint; + + /** + * Verb + * + * @var string + * @access private + */ + private $verb; + + /** + * S3 bucket name + * + * @var string + * @access private + */ + private $bucket; + + /** + * Object URI + * + * @var string + * @access private + */ + private $uri; + + /** + * Final object URI + * + * @var string + * @access private + */ + private $resource = ''; + + /** + * Additional request parameters + * + * @var array + * @access private + */ + private $parameters = array(); + + /** + * Amazon specific request headers + * + * @var array + * @access private + */ + private $amzHeaders = array(); + + /** + * HTTP request headers + * + * @var array + * @access private + */ + private $headers = array( + 'Host' => '', 'Date' => '', 'Content-MD5' => '', 'Content-Type' => '' + ); + + /** + * Use HTTP PUT? + * + * @var bool + * @access public + */ + public $fp = false; + + /** + * PUT file size + * + * @var int + * @access public + */ + public $size = 0; + + /** + * PUT post fields + * + * @var array + * @access public + */ + public $data = false; + + /** + * S3 request respone + * + * @var object + * @access public + */ + public $response; + + + /** + * Constructor + * + * @param string $verb Verb + * @param string $bucket Bucket name + * @param string $uri Object URI + * @param string $endpoint AWS endpoint URI + * @return mixed + */ + function __construct($verb, $bucket = '', $uri = '', $endpoint = 's3.amazonaws.com') + { + $this->endpoint = $endpoint; + $this->verb = $verb; + $this->bucket = $bucket; + $this->uri = $uri !== '' ? '/'.str_replace('%2F', '/', rawurlencode($uri)) : '/'; + + if ($this->bucket !== '') + { + if ($this->__dnsBucketName($this->bucket)) + { + $this->headers['Host'] = $this->bucket.'.'.$this->endpoint; + $this->resource = '/'.$this->bucket.$this->uri; + } + else + { + // Old format, deprecated by AWS - removal scheduled for September 30th, 2020 + $this->headers['Host'] = $this->endpoint; + $this->uri = $this->uri; + if ($this->bucket !== '') $this->uri = '/'.$this->bucket.$this->uri; + $this->bucket = ''; + $this->resource = $this->uri; + } + } + else + { + $this->headers['Host'] = $this->endpoint; + $this->resource = $this->uri; + } + + + $this->headers['Date'] = gmdate('D, d M Y H:i:s T'); + $this->response = new STDClass; + $this->response->error = false; + $this->response->body = null; + $this->response->headers = array(); + } + + + /** + * Set request parameter + * + * @param string $key Key + * @param string $value Value + * @return void + */ + public function setParameter($key, $value) + { + $this->parameters[$key] = $value; + } + + + /** + * Set request header + * + * @param string $key Key + * @param string $value Value + * @return void + */ + public function setHeader($key, $value) + { + $this->headers[$key] = $value; + } + + + /** + * Set x-amz-meta-* header + * + * @param string $key Key + * @param string $value Value + * @return void + */ + public function setAmzHeader($key, $value) + { + $this->amzHeaders[$key] = $value; + } + + + /** + * Get the S3 response + * + * @return object | false + */ + public function getResponse() + { + $query = ''; + if (sizeof($this->parameters) > 0) + { + $query = substr($this->uri, -1) !== '?' ? '?' : '&'; + foreach ($this->parameters as $var => $value) + if ($value == null || $value == '') $query .= $var.'&'; + else $query .= $var.'='.rawurlencode($value).'&'; + $query = substr($query, 0, -1); + $this->uri .= $query; + + if (array_key_exists('acl', $this->parameters) || + array_key_exists('location', $this->parameters) || + array_key_exists('torrent', $this->parameters) || + array_key_exists('website', $this->parameters) || + array_key_exists('logging', $this->parameters)) + $this->resource .= $query; + } + $url = (S3::$useSSL ? 'https://' : 'http://') . ($this->headers['Host'] !== '' ? $this->headers['Host'] : $this->endpoint) . $this->uri; + + // Basic setup + $curl = curl_init(); + curl_setopt($curl, CURLOPT_USERAGENT, 'S3/php'); + + if (S3::$useSSL) + { + // Set protocol version + curl_setopt($curl, CURLOPT_SSLVERSION, S3::$useSSLVersion); + + // SSL Validation can now be optional for those with broken OpenSSL installations + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, S3::$useSSLValidation ? 2 : 0); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, S3::$useSSLValidation ? 1 : 0); + + if (S3::$sslKey !== null) curl_setopt($curl, CURLOPT_SSLKEY, S3::$sslKey); + if (S3::$sslCert !== null) curl_setopt($curl, CURLOPT_SSLCERT, S3::$sslCert); + if (S3::$sslCACert !== null) curl_setopt($curl, CURLOPT_CAINFO, S3::$sslCACert); + } + + curl_setopt($curl, CURLOPT_URL, $url); + + if (S3::$proxy != null && isset(S3::$proxy['host'])) + { + curl_setopt($curl, CURLOPT_PROXY, S3::$proxy['host']); + curl_setopt($curl, CURLOPT_PROXYTYPE, S3::$proxy['type']); + if (isset(S3::$proxy['user'], S3::$proxy['pass']) && S3::$proxy['user'] != null && S3::$proxy['pass'] != null) + curl_setopt($curl, CURLOPT_PROXYUSERPWD, sprintf('%s:%s', S3::$proxy['user'], S3::$proxy['pass'])); + } + + // Headers + $httpHeaders = array(); + if (S3::hasAuth()) + { + // Authorization string (CloudFront stringToSign should only contain a date) + if ($this->headers['Host'] == 'cloudfront.amazonaws.com') + { + # TODO: Update CloudFront authentication + foreach ($this->amzHeaders as $header => $value) + if (strlen($value) > 0) $httpHeaders[] = $header.': '.$value; + + foreach ($this->headers as $header => $value) + if (strlen($value) > 0) $httpHeaders[] = $header.': '.$value; + + $httpHeaders[] = 'Authorization: ' . S3::__getSignature($this->headers['Date']); + } + else + { + $this->amzHeaders['x-amz-date'] = gmdate('Ymd\THis\Z'); + + if (!isset($this->amzHeaders['x-amz-content-sha256'])) + $this->amzHeaders['x-amz-content-sha256'] = hash('sha256', $this->data); + + foreach ($this->amzHeaders as $header => $value) + if (strlen($value) > 0) $httpHeaders[] = $header.': '.$value; + + foreach ($this->headers as $header => $value) + if (strlen($value) > 0) $httpHeaders[] = $header.': '.$value; + + $httpHeaders[] = 'Authorization: ' . S3::__getSignatureV4( + $this->amzHeaders, + $this->headers, + $this->verb, + $this->uri, + $this->parameters + ); + + } + } + + curl_setopt($curl, CURLOPT_HTTPHEADER, $httpHeaders); + curl_setopt($curl, CURLOPT_HEADER, false); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, false); + curl_setopt($curl, CURLOPT_WRITEFUNCTION, array(&$this, '__responseWriteCallback')); + curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this, '__responseHeaderCallback')); + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); + + // Request types + switch ($this->verb) + { + case 'GET': break; + case 'PUT': case 'POST': // POST only used for CloudFront + if ($this->fp !== false) + { + curl_setopt($curl, CURLOPT_PUT, true); + curl_setopt($curl, CURLOPT_INFILE, $this->fp); + if ($this->size >= 0) + curl_setopt($curl, CURLOPT_INFILESIZE, $this->size); + } + elseif ($this->data !== false) + { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->verb); + curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data); + } + else + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->verb); + break; + case 'HEAD': + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD'); + curl_setopt($curl, CURLOPT_NOBODY, true); + break; + case 'DELETE': + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); + break; + default: break; + } + + // set curl progress function callback + if (S3::$progressFunction) { + curl_setopt($curl, CURLOPT_NOPROGRESS, false); + curl_setopt($curl, CURLOPT_PROGRESSFUNCTION, S3::$progressFunction); + } + + // Execute, grab errors + if (curl_exec($curl)) + $this->response->code = curl_getinfo($curl, CURLINFO_HTTP_CODE); + else + $this->response->error = array( + 'code' => curl_errno($curl), + 'message' => curl_error($curl), + 'resource' => $this->resource + ); + + @curl_close($curl); + + // Parse body into XML + if ($this->response->error === false && isset($this->response->headers['type']) && + $this->response->headers['type'] == 'application/xml' && isset($this->response->body)) + { + $this->response->body = simplexml_load_string($this->response->body); + + // Grab S3 errors + if (!in_array($this->response->code, array(200, 204, 206)) && + isset($this->response->body->Code, $this->response->body->Message)) + { + $this->response->error = array( + 'code' => (string)$this->response->body->Code, + 'message' => (string)$this->response->body->Message + ); + if (isset($this->response->body->Resource)) + $this->response->error['resource'] = (string)$this->response->body->Resource; + unset($this->response->body); + } + } + + // Clean up file resources + if ($this->fp !== false && is_resource($this->fp)) fclose($this->fp); + + return $this->response; + } + + + /** + * CURL write callback + * + * @param resource &$curl CURL resource + * @param string &$data Data + * @return integer + */ + private function __responseWriteCallback(&$curl, &$data) + { + if (in_array($this->response->code, array(200, 206)) && $this->fp !== false) + return fwrite($this->fp, $data); + else + $this->response->body .= $data; + return strlen($data); + } + + + /** + * Check DNS conformity + * + * @param string $bucket Bucket name + * @return boolean + */ + private function __dnsBucketName($bucket) + { + if (strlen($bucket) > 63 || preg_match("/[^a-z0-9\.-]/", $bucket) > 0) return false; + if (S3::$useSSL && strstr($bucket, '.') !== false) return false; + if (strstr($bucket, '-.') !== false) return false; + if (strstr($bucket, '..') !== false) return false; + if (!preg_match("/^[0-9a-z]/", $bucket)) return false; + if (!preg_match("/[0-9a-z]$/", $bucket)) return false; + return true; + } + + + /** + * CURL header callback + * + * @param resource $curl CURL resource + * @param string $data Data + * @return integer + */ + private function __responseHeaderCallback($curl, $data) + { + if (($strlen = strlen($data)) <= 2) return $strlen; + if (substr($data, 0, 4) == 'HTTP') + $this->response->code = (int)substr($data, 9, 3); + else + { + $data = trim($data); + if (strpos($data, ': ') === false) return $strlen; + list($header, $value) = explode(': ', $data, 2); + $header = strtolower($header); + if ($header == 'last-modified') + $this->response->headers['time'] = strtotime($value); + elseif ($header == 'date') + $this->response->headers['date'] = strtotime($value); + elseif ($header == 'content-length') + $this->response->headers['size'] = (int)$value; + elseif ($header == 'content-type') + $this->response->headers['type'] = $value; + elseif ($header == 'etag') + $this->response->headers['hash'] = $value{0} == '"' ? substr($value, 1, -1) : $value; + elseif (preg_match('/^x-amz-meta-.*$/', $header)) + $this->response->headers[$header] = $value; + } + return $strlen; + } + +} + +/** + * S3 exception class + * + * @link http://undesigned.org.za/2007/10/22/amazon-s3-php-class + * @version 0.5.0-dev + */ + +class S3Exception extends Exception { + /** + * Class constructor + * + * @param string $message Exception message + * @param string $file File in which exception was created + * @param string $line Line number on which exception was created + * @param int $code Exception code + */ + function __construct($message, $file, $line, $code = 0) + { + parent::__construct($message, $code); + $this->file = $file; + $this->line = $line; + } +} diff --git a/sql_code/20191121_updated_stat_page_views.sql b/sql_code/20191121_updated_stat_page_views.sql new file mode 100644 index 000000000..d767470c3 --- /dev/null +++ b/sql_code/20191121_updated_stat_page_views.sql @@ -0,0 +1,44 @@ +USE `pling`; + +CREATE TABLE IF NOT EXISTS `stat_page_impression` +( + `object_id` int(11) NOT NULL, + `object_type` int(11) NOT NULL, + `seen_at` int(11) NOT NULL, + `ip_inet` varbinary(16) NOT NULL, + `member_id_viewer` int(11) DEFAULT NULL, + `ipv6` varchar(50) DEFAULT NULL, + `ipv4` varchar(50) DEFAULT NULL, + `fingerprint` varchar(50) DEFAULT NULL, + `user_agent` varchar(255) DEFAULT NULL, + `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`object_id`, `object_type`, `seen_at`, `ip_inet`) +) ENGINE = InnoDB + DEFAULT CHARSET = `latin1`; + + + +# #insert/update page views into table stat_page_views_mv +# USE `pling`; +# +# #Update mechanism +# START TRANSACTION; +# +# DROP TABLE IF EXISTS `stat_page_views_mv_new`; +# CREATE TABLE `stat_page_views_mv_new` LIKE `stat_page_views_mv`; +# +# INSERT INTO `stat_page_views_mv_new` +# SELECT `stat_page_views`.`project_id` AS `project_id`, +# COUNT(1) AS `count_views`, +# COUNT(DISTINCT `stat_page_views`.`ip`) AS `count_visitor`, +# MAX(`stat_page_views`.`created_at`) AS `last_view` +# FROM `stat_page_views` +# WHERE `stat_page_views`.`created_at` >= CONCAT(CURDATE(), ' 00:00:00') +# GROUP BY `stat_page_views`.`project_id`; +# +# RENAME TABLE `stat_page_views_mv` TO `stat_page_views_mv_old`; +# RENAME TABLE `stat_page_views_mv_new` TO `stat_page_views_mv`; +# DROP TABLE IF EXISTS `stat_page_views_mv_old`; +# +# COMMIT; +# diff --git a/sql_code/fetchCatTreeForStore.sql b/sql_code/fetchCatTreeForStore.sql new file mode 100644 index 000000000..033821e22 --- /dev/null +++ b/sql_code/fetchCatTreeForStore.sql @@ -0,0 +1,47 @@ +CREATE + DEFINER = `root`@`localhost` PROCEDURE `fetchCatTreeForStore`( + IN `STORE_ID` int(11) +) +BEGIN + + DROP TABLE IF EXISTS `tmp_store_cat`; + + CREATE TEMPORARY TABLE `tmp_store_cat` + ( + INDEX `idx_cat_id` (`project_category_id`) + ) + ENGINE MEMORY + AS + SELECT `csc`.`store_id`, `csc`.`project_category_id`, `csc`.`order`, `pc`.`title`, `pc`.`lft`, `pc`.`rgt` + FROM `config_store_category` AS `csc` + JOIN `project_category` AS `pc` ON `pc`.`project_category_id` = `csc`.`project_category_id` + WHERE `csc`.`store_id` = `STORE_ID` + GROUP BY `csc`.`store_category_id` + ORDER BY `csc`.`order`, `pc`.`title`; + + SET @`NEW_ORDER` := 0; + UPDATE `tmp_store_cat` SET `order` = (@`NEW_ORDER` := @`NEW_ORDER` + 10); + + + SELECT `sct`.`lft`, + `sct`.`rgt`, + `sct`.`project_category_id` AS `id`, + `sct`.`title`, + `scpc`.`count_product` AS `product_count`, + `sct`.`xdg_type`, + `sct`.`name_legacy`, + if(`sct`.`rgt` - `sct`.`lft` = 1, 0, 1) AS `has_children`, + (SELECT `project_category_id` + FROM `stat_cat_tree` AS `sct2` + WHERE `sct2`.`lft` < `sct`.`lft` + AND `sct2`.`rgt` > `sct`.`rgt` + ORDER BY `sct2`.`rgt` - `sct`.`rgt` + LIMIT 1) AS `parent_id` + FROM `tmp_store_cat` AS `cfc` + JOIN `stat_cat_tree` AS `sct` ON find_in_set(`cfc`.`project_category_id`, `sct`.`ancestor_id_path`) + JOIN `stat_store_prod_count` AS `scpc` + ON `sct`.`project_category_id` = `scpc`.`project_category_id` AND `scpc`.`tag_id` IS NULL + WHERE `cfc`.`store_id` = `STORE_ID` + ORDER BY `cfc`.`order`, `sct`.`lft`; + +END \ No newline at end of file